Code

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