<?php

class Group {

  private static $maildir = '/home/leif/slask/maildir';


  private static $queryList = <<<EOS
    select ID, Gruppnamn, GruppInfo from Grupper order by Gruppnamn
EOS;

  private static $queryOne = <<<EOS
    select * from Grupper where ID = ?
EOS;

  private static $queryMembership = <<<EOS
    select Grupper.ID, Gruppnamn from Grupper,GruppAdress where 
    GruppID = Grupper.ID and Adressid = ? order by Gruppnamn
EOS;

  private static $querySetGroup = <<<EOS
    replace into GruppAdress set AdressID = ?, GruppID = ?
EOS;

  private static $queryUnsetGroup = <<<EOS
    delete from GruppAdress where AdressID = ? and GruppID = ?
EOS;

  private static $queryMail = <<<EOS
    select Epost from Adresser, GruppAdress where
    Adresser.ID = AdressID and GruppID = ?
EOS;

  private static $queryUpdate = <<<EOS
    update Grupper set where ID = ?
EOS;


  public static $groupFields = array('ID', 'Gruppnamn', 'GruppInfo');
  private static $buttonFields = array('change','print');

  private static $instance;

  private static $list = array();

  public function __construct($param = NULL) {
    foreach (self::$groupFields as $field) {$this->$field = '';}
    foreach (self::$buttonFields as $field) {$this->$field = '';}
    if (is_null($param)) return;
    if (is_array($param)) {
      foreach (self::$groupFields as $field) {
	$this->$field = $param[$field];
      }
      return;
    }
    $db = AddressDB::getDB();
    $result = $db->Execute(self::$queryOne,array($param));
    if ($result === false) { die("Database error!<br>" . $db->ErrorMsg());}
    $count = $result->RecordCount();
    switch ($count) {
    case 0:
      die(sprintf('Bad group ID %s'.PHP_EOL,$adressID));
      break;
    case 1:
      $row = $result->FetchRow();
      foreach (self::$groupFields as $field) {
	if (isset($row[$field])) $this->$field = $row[$field];
      }
      break;
    default:
      die(sprintf(
         'Strange error. Exactly one group record expected for key %s',
         $ID));
    }
  }

  private function createRecord() {
    $db = AddressDB::getDB();
    $query = 'insert into Grupper set Gruppnamn = ""';
    $result = $db->Execute($query,array());
    if ($result === false) {die("Database error!<br>" . $publDB->ErrorMsg()); }
    $this->ID = $db->Insert_ID();
  }
 
  public function updateRecord() {
    global $gCms; if (!isset($gCms)) exit;
    $db = AddressDB::getDB();
    if ($this->ID == '') { $this->createRecord(); }

    $query = 'update Grupper set ';
    $qfields = array(); $values = array();
    foreach (self::$groupFields as $field) {
      if ($field == 'ID') continue;
      $val = trim($this->$field);
      if (strlen($val) == 0) $val = null;
      $qfields[] = sprintf('%s = ?',$field);
      $values[] = $val;
    }
    $values[] = $this->ID;
    $query .= join(', ',$qfields) . ' where ID=?';
    $result = $db->Execute($query,$values);
    if ($result === false) {die("Database error!<br>" . $db->ErrorMsg());}
  }
 
  public static function getGroupList() {
    if (count(self::$list) > 0) return $list;
    global $gCms; if (!isset($gCms)) exit;
    $c = __CLASS__;
    $db = AddressDB::getDB();
    $result = $db->Execute(self::$queryList,array());
    if ($result === false) { die("Database error!<br>" . $db->ErrorMsg());}
    while ($row = $result->FetchRow()) {
      self::$list[] = new $c($row);
    }
    return self::$list;
  }
	
  /*   global $gCms; */
  /*   if (!isset($gCms)) exit; */
  /*   $ADB = AddressDB::getDB(); */
  /*   $result = $ADB->Execute(self::$queryList,array()); */
  /*   while ($row = $result->FetchRow()) { */
  /*     $this->list[$row['Gruppnamn']] = $row['ID']; */
  /*   } */
  /* } */
  
  public static function getMembers($GruppID) {
    global $gCms; if (!isset($gCms)) exit;
    $db = AddressDB::getDB();
    $result = $db->Execute(self::$queryMembership,array($GruppID));
    if ($result === false) { die("Database error!<br>" . $db->ErrorMsg()); }
    $list = array();
    while ($row = $result->FetchRow()) {
      $list[$row['Gruppnamn']] = $row['ID'];
    }
    return $list;
  }

  public static function getNonMembers($GruppID) {
    $members = self::getMembers($GruppID);
    $allgroups = array();
    self::getGroupList();
    foreach (self::$list as $group) {
      $allgroups[$group->Gruppnamn] = $group->ID;
    }
    $nonmembers = array_diff_assoc($allgroups,$members);
    return $nonmembers;
  }
    
  public static function setMember($ID,$GroupID) {
    global $gCms; if (!isset($gCms)) exit;
    $db = AddressDB::getDB();
    $values = array($ID, $GroupID);
    $result = $db->Execute(self::$querySetGroup,$values);
    if ($result === false) {die("Database error!<br>" . $db->ErrorMsg()); }
  }  

  public static function unsetMember($ID,$GroupID) {
    global $gCms; if (!isset($gCms)) exit;
    $db = AddressDB::getDB();
    $values = array($ID, $GroupID);
    //   echo '<pre>'; print_r($queryUnsetGroup); print_r($values); echo '</pre>';exit;
    
    $result = $db->Execute(self::$queryUnsetGroup,$values);
    if ($result === false) {die("Database error!<br>" . $db->ErrorMsg()); }
  }  

  /* public static function getGroup() { */
  /*   if (!isset(self::$instance)) { */
  /*     $c = __CLASS__; */
  /*     self::$instance = new $c; */
  /*   } */
  /*   return self::$instance->list; */
  /* } */

  public static function setMailLists() {
    global $gCms; if (!isset($gCms)) exit;
    $config =& $gCms->GetConfig();
    $maildir = $config['root_path'] . '/uploads/mailinglists';
    $db = AddressDB::getDB();
    $groups = self::getGroupList();
    //if(!is_dir(self::$maildir)) mkdir(self::$maildir,'0755',true);
    foreach ($groups as $group) {
      $pos = strrpos($group->Gruppnamn, '.dis');
      if ($pos === false) continue;
      $epost = array();
      $values = array($group->ID);
      $result = $db->Execute(self::$queryMail,$values);
      if ($result === false) { die("Database error!<br>" . $db->ErrorMsg()); }
      while ($row = $result->FetchRow()) {
	if (!$row['Epost']) continue;
	$epost[] = $row['Epost'];
      }
      if (count($epost) > 0) {
	//	echo '<pre>'; print_r($epost); echo '</pre>';
	$filename  = $maildir . '/' . $group->Gruppnamn;
	$file = fopen($filename,'w');
	if ($file === false) die('Cannot write '.$filename);
	foreach ($epost as $line) fwrite($file,$line.PHP_EOL);
	fclose($file);
      }
    }
    //  exit;
  }
}
?>