Code

Updated DEBUG output for cyrus 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>IMAP: 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>IMAP: Account exists in imap server.</b>"); 
78     }else{
79       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,"","<b>IMAP: 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>IMAP: Successfully received account quota</b>");
146     }else{
147       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__, imap_last_error() , 
148           "<b>IMAP: 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>IMAP: 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>IMAP: 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>IMAP: 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>IMAP: Received mailbox folders.</b>");
300       $this->error = imap_last_error();
301     }else{
302       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,imap_last_error(),
303           "<b>IMAP: 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>IMAP: 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     /* Merge given ACL with acl mapping
341        This ensures that no ACL will accidentally overwritten by gosa.
342      */
343     foreach($folder_acls as $user => $acl){
344       if(!isset($this->acl_mapping[$acl])){
345         $this->acl_mapping[$acl] = $acl;
346       }
347     }
349     return($folder_acls);
350   }
354   /*! \brief  Write ACLs back to imap or what ever
355    */
356   public function  setFolderACLs($permissions)
357   {
358     $this->reset_error();
360     /* imap_getacl available? */
361     if (!function_exists('imap_getacl')){
362       $this->error = _("The module imap_getacl is not implemented!");
363       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,"The imap_getacl module is missing!",
364           "<b>IMAP: Cannot set folder acls.</b>");
365       return(FALSE);
366     }
368     /* Get list of subfolders */
369     $folders= $this->getMailboxList();
370     foreach ($folders as $subfolder){
371       $folder_id = $this->create_folder_id($subfolder);
372       echo $folder_id."<br>";
374       /* Remove all acl's for this folder */
375       $users= @imap_getacl ($this->imap_handle, $folder_id);
376       
377       if(is_array($users)){
378         foreach ($users as $userid => $perms){
379           $userid = strtolower($userid);
380           imap_setacl ($this->imap_handle, $folder_id, $userid, "");
381           @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,$folder_id." -> ".$userid,
382               "<b>IMAP: Removing folder permissions.</b>");
383         }
384       }
385     }
387     /* Set permissions for this folder */
388     foreach($folders as $subfolder){
389       $folder_id = $this->create_folder_id($subfolder);
391       foreach ($permissions as $user => $acl){
392         imap_setacl ($this->imap_handle, $folder_id, $user, $acl);
393         @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,$folder_id." -> ".$user.": ".$acl,
394             "<b>IMAP: Setting new folder permissions.</b>");
395       }
396     }
397     return(TRUE);
398   }
401   public function saveSieveSettings()
402   {
403     mailMethod::saveSieveSettings();
405     /* Map attribute from parent class 
406      */
407     $mail = $this->parent->mail;
408     $gosaMailDeliveryMode = $this->parent->gosaMailDeliveryMode;
409     $gosaMailAlternateAddress = $this->parent->gosaMailAlternateAddress;
410     $gosaMailMaxSize = $this->parent->gosaMailMaxSize;
411     $gosaSpamMailbox = $this->parent->gosaSpamMailbox;
412     $gosaSpamSortLevel = $this->parent->gosaSpamSortLevel;
413     $gosaVacationMessage = $this->parent->gosaVacationMessage;
415     /* Try to login into sieve
416      */ 
417     $cfg = $this->ServerList[$this->MailServer];
418     $sieve= new sieve($cfg["sieve_server"], $cfg["sieve_port"], $this->getUAttribValue(),
419         $cfg["password"], $cfg["admin"],$cfg["sieve_option"]);
420     if (!$sieve->sieve_login()){
421       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,$sieve->error_raw ,"<b>SIEVE: login failed.</b>");
422       $this->error = $sieve->error_raw;
423       return(FALSE);
424     }
426     /* Build spamlevel. Spamassassin tags mails with "*" for each integer
427        point of spam. So a spam level of 5.3 gets "*****" which can be
428        checked easily by spam filters */
429     $spamlevel= str_pad("",(int) $gosaSpamSortLevel,"*");
431     /* Get current sieve script named 'gosa'.
432         Check if it valid ("###GOSA" must be the first string).
433         If it is valid just replace it, if it is NOT valid
434          create a backup of the old 
435      */
436     $script= "";
437     if($sieve->sieve_listscripts()){
438       if (in_array("gosa", $sieve->response)){
439         if(!$sieve->sieve_getscript("gosa")){
440           $this->error = sprintf(_("Cannot retrieve SIEVE script: %s"),to_string($sieve->error_raw));
441           @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,$sieve->error_raw ,
442               "<b>SIEVE: Connot read 'gosa' sieve script.</b>");
443           $this->error = $sieve->error_raw;
444           return(FALSE);
445         }
447         $is_valid_script = FALSE;
448         foreach ($sieve->response as $line){
449           if(empty($line)) continue;
450           if (preg_match ("/^###GOSA/", $line) && strlen($script) == 0){
451             $is_valid_script = TRUE;
452           }
453           $line= rtrim($line);
454           $script .= $line;
455         }
457         if($is_valid_script || strlen($script) == 0 || empty($script)){
458           @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,"" ,
459               "<b>SIEVE</b>: Sieve script 'gosa' was a valid GOsa script and will be replaced.");
460         }else{
461           $new_name = "non_gosa_".date("Ymd_H-i-s");
462           $sieve->sieve_sendscript($new_name, $script);
463           @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,$this->sieve->error_raw ,
464               "<b>SIEVE</b>: Non GOsa sieve script. <b>Creating backup of the current sieve script '".$new_name."'.</b>");
465         }
466       }
467     }
470     /*****
471       Build up new sieve script here.
472      *****/
474     /* Only create a new one, if it is not empty */
475     $script= "";
476     if (is_integer(strpos($gosaMailDeliveryMode, "R")) ||
477         is_integer(strpos($gosaMailDeliveryMode, "C")) ||
478         !is_integer(strpos($gosaMailDeliveryMode, "L")) ||
479         is_integer(strpos($gosaMailDeliveryMode, "V")) ||
480         is_integer(strpos($gosaMailDeliveryMode, "S"))){
482       $text= preg_replace('/"/', '\\"', implode ("", file(CONFIG_DIR."/sieve-header.txt")));
483       eval ("\$script.=\"$text\";");
484     }
486     /* Add anti-spam code */
487     if (is_integer(strpos($gosaMailDeliveryMode, "S"))){
488       $spambox= $gosaSpamMailbox;
489       $text= preg_replace('/"/', '\\"', implode ("", file(CONFIG_DIR."/sieve-spam.txt")));
490       eval ("\$script.=\"$text\";");
491     }
493     /* Add "reject due to mailsize" code, message is currently not
494        adjustable through GOsa. */
495     if (is_integer(strpos($gosaMailDeliveryMode, "R"))){
496       $maxsize= $gosaMailMaxSize;
497       $text= preg_replace('/"/', '\\"', implode ("", file(CONFIG_DIR."/sieve-mailsize.txt")));
498       eval ("\$script.=\"$text\";");
499     }
501     /* Add vacation information */
502     if (is_integer(strpos($gosaMailDeliveryMode, "V"))){
504       /* Sieve wants all destination addresses for the
505          vacation message, so we've to assemble them from
506          mail and mailAlternateAddress */
507       $addrlist= "\"".$mail."\"";
508       foreach ($gosaMailAlternateAddress as $val){
509         $addrlist .= ", \"$val\"";
510       }
511       $vacmsg= $gosaVacationMessage;
512       $text= preg_replace('/"/', '\\"', implode ("", file(CONFIG_DIR."/sieve-vacation.txt")));
513       eval ("\$script.=\"$text\";");
514     }
516     /* If no local delivery is wanted, tell the script to discard the mail */
517     if (!is_integer(strpos($gosaMailDeliveryMode, "L"))){
518       $text= preg_replace('/"/', '\\"', implode ("", file(CONFIG_DIR."/sieve-discard.txt")));
519       eval ("\$script.=\"$text\";");
520     }
522     /****
523       Sieve script build complete
524      ****/
526     /* Upload script and make it the default one */
527     if (!$sieve->sieve_sendscript("gosa", $script)){
528       $this->error = sprintf(_("Cannot store SIEVE script: %s"), to_string($sieve->error_raw));
529       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__, "Error was: ".to_string($sieve->error_raw) ,
530         "<b>SIEVE: Writing new Sieve script failed!</b>");
531       return(FALSE);
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     $sieve->sieve_logout();
540   }
543 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
544 ?>