Code

Update mail method
[gosa.git] / gosa-plugins / mail / personal / mail / class_mail-methods-cyrus.inc
1 <?php
4 class mailMethodCyrus extends mailMethod{
6   protected $ServerList = array();
7   protected $imap_handle = NULL;
8   protected $quota_loaded = FALSE;
9    
10   /* Allow modification of account_ids for existing mail accounts */
11   protected $modifyableMail = FALSE;
13   /* Enforces same value for 'mail' as used for 'cn' */
14   protected $mailEqualsCN   = FALSE; 
16   protected $enableDomainSelection= FALSE;
17   protected $enableQuota          = TRUE;
18   protected $enableSieveManager   = TRUE;
19   protected $enableVacationRange  = TRUE;
20   protected $enableFolderTypes    = FALSE;
22   protected function init()
23   {
24     mailMethod::init();
25     $this->ServerList = $this->config->data['SERVERS']['IMAP']; 
26   }
28   
29   public function connect()
30   {
31     mailMethod::connect();
32  
33     if (!isset($this->ServerList[$this->MailServer])){
34       $this->error = _("Mail server for this account is invalid!");
35       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,
36           "<b>The selected mail server '".$this->MailServer."' is invalid.</b>",""); 
37       return(FALSE);
38     } else {
39       $cfg= $this->ServerList[$this->MailServer];
40     }
42     /* For some reason, hiding errors with @ does not wor here... */
43     if(!isset($cfg['connect']))   $cfg['connect']="";
44     if(!isset($cfg['admin']))     $cfg['admin']="";
45     if(!isset($cfg['password']))  $cfg['password']="";
47     /* Setting connect timeout to 10 seconds,
48         else the GOsa UI may freeze for 60 seconds.
49        (PHP default is 'default_socket_timeout = 60') */
50     imap_timeout(1, 10 );
51     $this->imap_handle = @imap_open($cfg['connect'], $cfg['admin'], $cfg['password'], OP_HALFOPEN);
53     /* Mailbox reachable? */
54     if ($this->imap_handle === FALSE){
55       $this->error = imap_last_error();
56       return (FALSE);
57       $this->connected = FALSE;
58     }
59     $this->connected = TRUE;
61     return (TRUE);
62   }
65   public function account_exists()
66   {
67     if(!$this->is_connected() || !$this->imap_handle){
68       trigger_error("Method not connected, catch error.");
69       return(array());
70     }
72     /* Get server config */
73     $cfg= $this->ServerList[$this->MailServer];
74     $list = @imap_listmailbox($this->imap_handle, $cfg["connect"], $this->account_id);
75     $res = is_array($list) && count($list);
76     if($res){
77       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,"","<b>Account exists in imap server.</b>"); 
78     }else{
79       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,"","<b>Account seems NOT to exists in imap server.</b>"); 
80     }
81     return($res);
82   }
84   public function disconnect()
85   {
86     mailMethod::disconnect();
87     if($this->is_connected()){
88       @imap_close ($this->imap_handle);
89     }
90   }
93   public function is_connected()
94   {
95     $ret =    mailMethod::is_connected();
96     return($ret && $this->imap_handle);
97   }
99   protected function loadQuota()
100   {
101     if(!$this->quotaEnabled()) return(TRUE);
102     if(!$this->is_connected() || !$this->imap_handle){
103       trigger_error("Method not connected, catch error.");
104       return(FALSE);
105     }
107     /* Load quota settings */
108     $result = array("quotaUsage"=>"","gosaMailQuota"=>"");
109     $quota_value = @imap_get_quota($this->imap_handle, $this->account_id);
111     if(is_array($quota_value) && count($quota_value)) {
112       if (isset($quota_value["STORAGE"]) && is_array($quota_value["STORAGE"])){
114         /* use for PHP >= 4.3 */
115         if($quota_value["STORAGE"]['limit'] == 2147483647){
116           $result['quotaUsage']=    (int) ($quota_value["STORAGE"]['usage'] / 1024);
117           $result['gosaMailQuota']=  "";
118         }else{
119           $result['quotaUsage']=    (int) ($quota_value["STORAGE"]['usage'] / 1024);
120           $result['gosaMailQuota']= (int) ($quota_value["STORAGE"]['limit'] / 1024);
121         }
122       } else {
124         /* backward icompatible */
125         if($quota_value['usage'] == 2147483647){
126           $result['quotaUsage']=    (int) ($quota_value['usage'] / 1024);
127           $result['gosaMailQuota']= "";
128         }else{
129           $result['quotaUsage']=    (int) ($quota_value['usage'] / 1024);
130           $result['gosaMailQuota']= (int) ($quota_value['limit'] / 1024);
131         }
132       }
133     }
134     $this->quotaValue = $result['gosaMailQuota'];
135     $this->quotaUsage = $result['quotaUsage'];
137     /* Write debug output */
138     if(is_array($quota_value)){
139       if($this->quotaValue == ""){
140         $quota = "(".$this->quotaUsage." / unlimited)";
141       }else{
142         $quota = "(".$this->quotaUsage." / ".$this->quotaValue.")";
143       }
144       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__, $quota , 
145           "<b>Successfully received account quota</b>");
146     }else{
147       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__, imap_last_error() , 
148           "<b>Failed to receive account quota</b>");
149     }
150   }
152   public function getQuota($quota)
153   {
154     mailMethod::getQuota($quota);
155     if(!$this->quota_loaded){
156       $this->quota_loaded = TRUE;
157       $this->loadQuota();
158     }
159     return($this->quotaValue);
160   }
162   public function getQuotaUsage()
163   {
164     mailMethod::getQuotaUsage();
165     if(!$this->quota_loaded){
166       $this->quota_loaded = TRUE;
167       $this->loadQuota();
168     }
169     return($this->quotaUsage);
170   }
172   public function setQuota($number)
173   {
174     mailMethod::setQuota($number);    
176     if(!$this->quotaEnabled()) return(TRUE);
177     if(!$this->is_connected() || !$this->imap_handle){
178       trigger_error("Method not connected, catch error.");
179       return(FALSE);
180     }
182     $this->build_account_id();
184     /* Workaround for the php imap extension */
185     if (($this->quotaValue == "") || ($this->quotaValue== "2147483647")){
186       $this->quotaValue= "2147483647";
187     }elseif($this->quotaValue > 0){
188       $this->quotaValue = $this->quotaValue *1024;
189     }
190     $debug_number = $this->quotaValue." KB";
191     if($this->quotaValue == "2147483647"){
192       $debug_number .= "<i>Unlimited</i>";
193     }
195     if (!imap_set_quota($this->imap_handle, $this->account_id, $this->quotaValue)){
196       msg_dialog::display(_("IMAP error"), sprintf(_("Cannot modify IMAP mailbox quota: %s"),
197             '<br><br><i>'.imap_last_error().'</i>'), ERROR_DIALOG);
198       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__, "<b>".$this->account_id.": (".$debug_number.")</b>" , 
199           "<b>Set account quota</b> on server '".$this->MailServer."' <b>".imap_last_error()."</b>");
200       return (FALSE);
201     }
202     @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__, "<b>".$this->account_id.": (".$debug_number.")</b>" , 
203         "<b>Set account quota</b> on server :".$this->MailServer);
204     return (TRUE);
205   }
208   public function updateMailbox()
209   {
210     mailMethod::updateMailbox();
212     if(!$this->is_connected() || !$this->imap_handle){
213       trigger_error("Method not connected, catch error.");
214       return(FALSE);
215     }
216   
217     $this->build_account_id ();
218     if($this->is_connected()){
219       $cfg= $this->ServerList[$this->MailServer];
220       $list = imap_listmailbox($this->imap_handle, $cfg["connect"], $this->account_id);
221       if ($list === FALSE){
222         @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__, "<b>".$this->account_id."</b>" , 
223           "<b>Add/Update account</b> on server :".$this->MailServer);
224         if (!imap_createmailbox($this->imap_handle, $cfg["connect"]. $this->account_id)){
225           $this->error = imap_last_error();
226           return(FALSE);
227         }
228       }
229     }
230     return(TRUE);
231   }
234   public function deleteMailbox()
235   {
236     mailMethod::deleteMailbox();
238     if(!$this->is_connected() || !$this->imap_handle){
239       trigger_error("Method not connected, catch error.");
240       return(FALSE);
241     }
243     $this->build_account_id ();
245     $cfg= $this->ServerList[$this->MailServer];
246     @imap_setacl ($this->imap_handle, $this->account_id, $cfg["admin"], "lrswipcda");
247     if (!imap_deletemailbox($this->imap_handle, $cfg["connect"].$this->account_id)){
248       $this->error = imap_last_error();
249       return (FALSE);
250     }
251     return (TRUE);
252   }
254   
255   public function getMailboxList()
256   {
257     mailMethod::getMailboxList();
259     if(!$this->is_connected() || !$this->imap_handle){
260       trigger_error("Method not connected, catch error.");
261       return(array());
262     }
264     $result = array();
266     /* Get server config */
267     $cfg= $this->ServerList[$this->MailServer];
269     /* Create search string
270        And prepare replacements 
271      */ 
272     if(preg_match("/\@/",$this->account_id)){
273       $search = preg_replace("/\@/","*@",$this->account_id);
274       $with_domain = TRUE;
275     }else{
276       $search = $this->account_id."*";
277       $with_domain = FALSE;
278     }
279     $folder = $this->account_id;
280     if(preg_match("/\@/",$folder)){
281       $folder = preg_replace("/\@.*$/","",$folder);
282     }
284     /* Contact imap server */
285     $list = @imap_listmailbox($this->imap_handle, $cfg["connect"], $search);
287     /* Create list of returned folder names */
288     if (is_array($list)){
289       foreach ($list as $val){
290         $str = trim(preg_replace("/^\{[^\}]*+\}/","",$val));
291         if($with_domain){
292           $str = trim(preg_replace("/\@.*$/","",$str));
293         }
294         $str = preg_replace ("/^.*".preg_quote($folder, '/')."/","INBOX", 
295           mb_convert_encoding($str, "UTF-8", "UTF7-IMAP"));
296         $result[] = $str;      
297       }
298       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,trim(implode($result,", "),", "),
299           "<b>Received mailbox folders.</b>");
300       $this->error = imap_last_error();
301     }else{
302       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,imap_last_error(),
303           "<b>Cannot receive mailbox folders.</b>");
304       $this->error = imap_last_error();
305       return(array());
306     }
308     /* Append "INBOX" to the folder array if result is empty and request comes from user dialog */
309     if(!count($result)){
310       $result[] = "INBOX";
311     }
313     return($result);
314   }
317   /*! \brief  Returns configured acls
318    */
319   public function  getFolderACLs($folder_acls)
320   {
321     $this->reset_error();
323     /* imap_getacl available? */
324     if (!function_exists('imap_getacl')){
325       $this->error = _("The module imap_getacl is not implemented!");
326       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,"The imap_getacl module is missing!",
327           "<b>Cannot set folder acls.</b>");
328       return($folder_acls);
329     }
331     /* Get ACLs and merge them with the already given acls (ldap)
332      */
333     $this->build_account_id();
334     $acls = imap_getacl ($this->imap_handle, $this->account_id);
335     foreach($acls as $user => $acl){
336       if($user == "anyone") $user = "__anyone__"; // Map to internal placeholder
337       $folder_acls[$user] = $acl;
338     }
340     return($folder_acls);
341   }
345   /*! \brief  Write ACLs back to imap or what ever
346    */
347   public function  setFolderACLs($permissions)
348   {
349     $this->reset_error();
351     /* imap_getacl available? */
352     if (!function_exists('imap_getacl')){
353       $this->error = _("The module imap_getacl is not implemented!");
354       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,"The imap_getacl module is missing!",
355           "<b>Cannot set folder acls.</b>");
356       return(FALSE);
357     }
359     /* Get list of subfolders */
360     $folders= $this->getMailboxList();
361     foreach ($folders as $subfolder){
362       $folder_id = $this->create_folder_id($subfolder);
363       echo $folder_id."<br>";
365       /* Remove all acl's for this folder */
366       $users= @imap_getacl ($this->imap_handle, $folder_id);
367       
368       if(is_array($users)){
369         foreach ($users as $userid => $perms){
370           $userid = strtolower($userid);
371           imap_setacl ($this->imap_handle, $folder_id, $userid, "");
372           @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,$folder_id." -> ".$userid,
373               "<b>Removing folder permissions.</b>");
374         }
375       }
376     }
378     /* Set permissions for this folder */
379     foreach($folders as $subfolder){
380       $folder_id = $this->create_folder_id($subfolder);
382       foreach ($permissions as $user => $acl){
383         imap_setacl ($this->imap_handle, $folder_id, $user, $acl);
384         @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,$folder_id." -> ".$user.": ".$acl,
385             "<b>Setting new folder permissions.</b>");
386       }
387     }
388     return(TRUE);
389   }
392   public function saveSieveSettings()
393   {
394     mailMethod::saveSieveSettings();
396     /* Map attribute from parent class 
397      */
398     $mail = $this->parent->mail;
399     $gosaMailDeliveryMode = $this->parent->gosaMailDeliveryMode;
400     $gosaMailAlternateAddress = $this->parent->gosaMailAlternateAddress;
401     $gosaMailMaxSize = $this->parent->gosaMailMaxSize;
402     $gosaSpamMailbox = $this->parent->gosaSpamMailbox;
403     $gosaSpamSortLevel = $this->parent->gosaSpamSortLevel;
404     $gosaVacationMessage = $this->parent->gosaVacationMessage;
406     /* Try to login into sieve
407      */ 
408     $cfg = $this->ServerList[$this->MailServer];
409     $sieve= new sieve($cfg["sieve_server"], $cfg["sieve_port"], $this->getUAttribValue(),
410         $cfg["password"], $cfg["admin"],$cfg["sieve_option"]);
411     if (!$sieve->sieve_login()){
412       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,$sieve->error_raw ,"<b>SIEVE: login failed.</b>");
413       $this->error = $sieve->error_raw;
414       return(FALSE);
415     }else{
416       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__, "Options: ".$cfg["sieve_option"] ,
417           "SIEVE: <b>login successfull.</b>");
418     }
420     /* Build spamlevel. Spamassassin tags mails with "*" for each integer
421        point of spam. So a spam level of 5.3 gets "*****" which can be
422        checked easily by spam filters */
423     $spamlevel= str_pad("",(int) $gosaSpamSortLevel,"*");
425     /* Get current sieve script named 'gosa'.
426         Check if it valid ("###GOSA" must be the first string).
427         If it is valid just replace it, if it is NOT valid
428          create a backup of the old 
429      */
430     $script= "";
431     if($sieve->sieve_listscripts()){
432       if (in_array("gosa", $sieve->response)){
433         if(!$sieve->sieve_getscript("gosa")){
434           $this->error = sprintf(_("Cannot retrieve SIEVE script: %s"),to_string($sieve->error_raw));
435           @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,$sieve->error_raw ,
436               "SIEVE: <b>Connot read 'gosa' sieve script.</b>");
437           $this->error = $sieve->error_raw;
438           return(FALSE);
439         }else{
440           @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,$sieve->error_raw ,
441               "SIEVE: <b>Sieve script named 'gosa' found.</b>");
442         }
444         $is_valid_script = FALSE;
445         foreach ($sieve->response as $line){
446           if(empty($line)) continue;
447           if (preg_match ("/^###GOSA/", $line) && strlen($script) == 0){
448             $is_valid_script = TRUE;
449           }
450           $line= rtrim($line);
451           $script .= $line;
452         }
454         if($is_valid_script || strlen($script) == 0 || empty($script)){
455           @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,"" ,
456               "SIEVE: Sieve script 'gosa' was a valid GOsa script and will be replaced.");
457         }else{
458           $new_name = "non_gosa_".date("Ymd_H-i-s");
459           $sieve->sieve_sendscript($new_name, $script);
460           @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,$this->sieve->error_raw ,
461               "SIEVE: Non GOsa sieve script. <b>Creating backup of the current sieve script '".$new_name."'.</b>");
462         }
463       }
464     }
467     /*****
468       Build up new sieve script here.
469      *****/
471     /* Only create a new one, if it is not empty */
472     $script= "";
473     if (is_integer(strpos($gosaMailDeliveryMode, "R")) ||
474         is_integer(strpos($gosaMailDeliveryMode, "C")) ||
475         !is_integer(strpos($gosaMailDeliveryMode, "L")) ||
476         is_integer(strpos($gosaMailDeliveryMode, "V")) ||
477         is_integer(strpos($gosaMailDeliveryMode, "S"))){
479       $text= preg_replace('/"/', '\\"', implode ("", file(CONFIG_DIR."/sieve-header.txt")));
480       eval ("\$script.=\"$text\";");
481     }
483     /* Add anti-spam code */
484     if (is_integer(strpos($gosaMailDeliveryMode, "S"))){
485       $spambox= $gosaSpamMailbox;
486       $text= preg_replace('/"/', '\\"', implode ("", file(CONFIG_DIR."/sieve-spam.txt")));
487       eval ("\$script.=\"$text\";");
488     }
490     /* Add "reject due to mailsize" code, message is currently not
491        adjustable through GOsa. */
492     if (is_integer(strpos($gosaMailDeliveryMode, "R"))){
493       $maxsize= $gosaMailMaxSize;
494       $text= preg_replace('/"/', '\\"', implode ("", file(CONFIG_DIR."/sieve-mailsize.txt")));
495       eval ("\$script.=\"$text\";");
496     }
498     /* Add vacation information */
499     if (is_integer(strpos($gosaMailDeliveryMode, "V"))){
501       /* Sieve wants all destination addresses for the
502          vacation message, so we've to assemble them from
503          mail and mailAlternateAddress */
504       $addrlist= "\"".$mail."\"";
505       foreach ($gosaMailAlternateAddress as $val){
506         $addrlist .= ", \"$val\"";
507       }
508       $vacmsg= $gosaVacationMessage;
509       $text= preg_replace('/"/', '\\"', implode ("", file(CONFIG_DIR."/sieve-vacation.txt")));
510       eval ("\$script.=\"$text\";");
511     }
513     /* If no local delivery is wanted, tell the script to discard the mail */
514     if (!is_integer(strpos($gosaMailDeliveryMode, "L"))){
515       $text= preg_replace('/"/', '\\"', implode ("", file(CONFIG_DIR."/sieve-discard.txt")));
516       eval ("\$script.=\"$text\";");
517     }
519     /****
520       Sieve script build complete
521      ****/
523     /* Upload script and make it the default one */
524     if (!$sieve->sieve_sendscript("gosa", $script)){
525       $this->error = sprintf(_("Cannot store SIEVE script: %s"), to_string($sieve->error_raw));
526       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__, "Error was: ".to_string($sieve->error_raw) ,
527         "SIEVE: <b>Writing new Sieve script failed!</b>");
528       return(FALSE);
529     }else{
530       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,"<b>Successfully written!</b>" ,
531         "SIEVE: <b>NEW sieve script 'gosa' contains '".strlen($script)."' characters.</b>");
532     }
534     if(!$sieve->sieve_setactivescript("gosa")){
535       $this->error = sprintf(_("Cannot activate SIEVE script: %s"), to_string($sieve->error_raw));
536       return(FALSE);
537     }
539     @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,"","SIEVE: <b>Logout</b>");
540     $sieve->sieve_logout();
541   }
544 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
545 ?>