Code

0df2c97c481ccbef1b8589082e8661e63ae3e6ea
[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     if(isset($this->config->data['SERVERS']['IMAP'])){
29       $this->ServerList = $this->config->data['SERVERS']['IMAP']; 
30     }
31   }
33   
34   public function connect()
35   {
36     mailMethod::connect();
38     if(!count($this->ServerList)){
39       $this->error = _("There are no IMAP compatible mail servers defined!");
40       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,
41           "<b>IMAP: No mail servers configured, check systems->server->service->imap.</b>","");
42       return(FALSE);
43     }elseif (!isset($this->ServerList[$this->MailServer])){
44       $this->error = _("Mail server for this account is invalid!");
45       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,
46           "<b>IMAP: The selected mail server '".$this->MailServer."' is invalid.</b>",""); 
47       return(FALSE);
48     } else {
49       $cfg= $this->ServerList[$this->MailServer];
50     }
52     /* For some reason, hiding errors with @ does not wor here... */
53     if(!isset($cfg['connect']))   $cfg['connect']="";
54     if(!isset($cfg['admin']))     $cfg['admin']="";
55     if(!isset($cfg['password']))  $cfg['password']="";
57     /* Setting connect timeout to 10 seconds,
58         else the GOsa UI may freeze for 60 seconds.
59        (PHP default is 'default_socket_timeout = 60') */
60     $timeout = $this->config->get_cfg_value("imapTimeout",10);
61     @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,$timeout,
62           "<b>IMAP: Setting imap connect timeout to</b> (seconds)");
63     imap_timeout(1, $timeout);
65     $this->imap_handle = @imap_open($cfg['connect'], $cfg['admin'], $cfg['password'], OP_HALFOPEN);
67     /* Mailbox reachable? */
68     if ($this->imap_handle === FALSE){
69       $this->error = imap_last_error();
71       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,"<b>Failed</b> :".imap_last_error(),
72         "<b>IMAP:</b> ".$cfg['admin']."@".$cfg['connect']);
74       return (FALSE);
75       $this->connected = FALSE;
76     }
77     @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,"<b>successful</b>",
78         "<b>IMAP:</b> ".$cfg['admin']."@".$cfg['connect']);
79     $this->connected = TRUE;
81     return (TRUE);
82   }
85   public function account_exists()
86   {
87     if(!$this->is_connected() || !$this->imap_handle){
88       trigger_error("Method not connected, catch error.");
89       return(array());
90     }
92     /* Get server config */
93     $cfg= $this->ServerList[$this->MailServer];
94     $list = @imap_listmailbox($this->imap_handle, $cfg["connect"], $this->account_id);
95     $res = is_array($list) && count($list);
96     if($res){
97       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,"","<b>IMAP: Account exists in imap server.</b>"); 
98     }else{
99       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,"","<b>IMAP: Account seems NOT to exists in imap server.</b>"); 
100     }
101     return($res);
102   }
104   public function disconnect()
105   {
106     mailMethod::disconnect();
107     if($this->is_connected()){
108       @imap_close ($this->imap_handle);
109     }
110   }
113   public function is_connected()
114   {
115     $ret =    mailMethod::is_connected();
116     return($ret && $this->imap_handle);
117   }
119   protected function loadQuota()
120   {
121     if(!$this->quotaEnabled()) return(TRUE);
122     if(!$this->is_connected() || !$this->imap_handle){
123       trigger_error("Method not connected, catch error.");
124       return(FALSE);
125     }
127     $this->reset_error();
129     /* Load quota settings */
130     $result = array("quotaUsage"=>"","gosaMailQuota"=>"");
131     $quota_value = @imap_get_quota($this->imap_handle, $this->account_id);
133     /* Reset error queue, imap_qet_quota() will fail if the quota wasn't set yet.
134      */
135     imap_errors();
137     if(is_array($quota_value) && count($quota_value)) {
138       if (isset($quota_value["STORAGE"]) && is_array($quota_value["STORAGE"])){
140         /* use for PHP >= 4.3 */
141         if($quota_value["STORAGE"]['limit'] == 2147483647){
142           $result['quotaUsage']=    (int) ($quota_value["STORAGE"]['usage'] / 1024);
143           $result['gosaMailQuota']=  "";
144         }else{
145           $result['quotaUsage']=    (int) ($quota_value["STORAGE"]['usage'] / 1024);
146           $result['gosaMailQuota']= (int) ($quota_value["STORAGE"]['limit'] / 1024);
147         }
148       } else {
150         /* backward icompatible */
151         if($quota_value['usage'] == 2147483647){
152           $result['quotaUsage']=    (int) ($quota_value['usage'] / 1024);
153           $result['gosaMailQuota']= "";
154         }else{
155           $result['quotaUsage']=    (int) ($quota_value['usage'] / 1024);
156           $result['gosaMailQuota']= (int) ($quota_value['limit'] / 1024);
157         }
158       }
159     }
160     $this->quotaValue = $result['gosaMailQuota'];
161     $this->quotaUsage = $result['quotaUsage'];
163     /* Write debug output */
164     if(is_array($quota_value)){
165       if($this->quotaValue == ""){
166         $quota = "(".$this->quotaUsage." / unlimited)";
167       }else{
168         $quota = "(".$this->quotaUsage." / ".$this->quotaValue.")";
169       }
170       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__, $quota , 
171           "<b>IMAP: Successfully received account quota</b>");
172     }else{
173       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__, imap_last_error() , 
174           "<b>IMAP: Failed to receive account quota</b>");
175     }
176   }
178   public function getQuota($quota)
179   {
180     mailMethod::getQuota($quota);
181     if(!$this->quota_loaded){
182       $this->quota_loaded = TRUE;
183       $this->loadQuota();
184     }
185     return($this->quotaValue);
186   }
188   public function getQuotaUsage()
189   {
190     mailMethod::getQuotaUsage();
191     if(!$this->quota_loaded){
192       $this->quota_loaded = TRUE;
193       $this->loadQuota();
194     }
195     return($this->quotaUsage);
196   }
198   public function setQuota($number)
199   {
200     mailMethod::setQuota($number);    
202     if(!$this->quotaEnabled()) return(TRUE);
203     if(!$this->is_connected() || !$this->imap_handle){
204       trigger_error("Method not connected, catch error.");
205       return(FALSE);
206     }
208     $this->build_account_id();
210     /* Workaround for the php imap extension */
211     if (($this->quotaValue == "") || ($this->quotaValue== "2147483647")){
212       $this->quotaValue= "2147483647";
213     }elseif($this->quotaValue > 0){
214       $this->quotaValue = $this->quotaValue *1024;
215     }
216     $debug_number = $this->quotaValue." KB";
217     if($this->quotaValue == "2147483647"){
218       $debug_number .= "<i>Unlimited</i>";
219     }
221     if (!imap_set_quota($this->imap_handle, $this->account_id, $this->quotaValue)){
222       msg_dialog::display(_("IMAP error"), sprintf(_("Cannot modify IMAP mailbox quota: %s"),
223             '<br><br><i>'.imap_last_error().'</i>'), ERROR_DIALOG);
224       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__, "<b>".$this->account_id.": (".$debug_number.")</b>" , 
225           "<b>IMAP: Set account quota</b> on server '".$this->MailServer."' <b>".imap_last_error()."</b>");
226       return (FALSE);
227     }
228     @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__, "<b>".$this->account_id.": (".$debug_number.")</b>" , 
229         "<b>IMAP: Set account quota</b> on server :".$this->MailServer);
230     return (TRUE);
231   }
234   public function updateMailbox()
235   {
236     mailMethod::updateMailbox();
238     if(!$this->is_connected() || !$this->imap_handle){
239       trigger_error("Method not connected, catch error.");
240       return(FALSE);
241     }
242   
243     $this->build_account_id ();
244     if($this->is_connected()){
245       $cfg= $this->ServerList[$this->MailServer];
246       $list = imap_listmailbox($this->imap_handle, $cfg["connect"], $this->account_id);
247       if ($list === FALSE){
248         @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__, "<b>".$this->account_id."</b>" , 
249           "<b>IMAP: Add/Update account</b> on server :".$this->MailServer);
250         if (!imap_createmailbox($this->imap_handle, $cfg["connect"].$this->account_id)){
251           $this->error = imap_last_error();
252           return(FALSE);
253         }
255         /* Autocreate configured default folders */ 
256         $folders= $this->config->get_cfg_value("cyrusAutocreateFolders", null);
257         if ($folders) {
258           $foldersToCreate= explode(",", $folders);
259           $cyrus_delim= $this->cyrusUseSlashes?"/":".";
261           // Walk thru list of specified folders
262           foreach ($foldersToCreate as $folder) {
263             @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__, "<b>".$this->account_id."</b>" , 
264               "<b>IMAP: Add/Update account folder ".$folder."</b> on server :".$this->MailServer);
265             if(!imap_createmailbox($this->imap_handle, $cfg["connect"].$this->account_id.$cyrus_delim.$folder)) {
266               $this->error= imap_last_error();
267               return(FALSE);
268             }
269           }
271         }
272       }
273     }
274     return(TRUE);
275   }
278   public function deleteMailbox()
279   {
280     mailMethod::deleteMailbox();
282     if(!$this->is_connected() || !$this->imap_handle){
283       trigger_error("Method not connected, catch error.");
284       return(FALSE);
285     }
287     $this->build_account_id ();
289     $cfg= $this->ServerList[$this->MailServer];
290     @imap_setacl ($this->imap_handle, $this->account_id, $cfg["admin"], "lrswipcda");
292     if ($this->config->get_cfg_value("cyrusDeleteMailbox", "true") == "true"){
293       if (!imap_deletemailbox($this->imap_handle, $cfg["connect"].$this->account_id)){
294         $this->error = imap_last_error();
295         return (FALSE);
296       }
297     } else{ 
298       msg_dialog::display(_("Mail info"),
299         sprintf(_("LDAP entry has been removed but cyrus mailbox (%s) is kept.\nPlease delete it manually!"),
300         $this->account_id), INFO_DIALOG);
301     }
302     return (TRUE);
303   }
305   
306   public function getMailboxList()
307   {
308     mailMethod::getMailboxList();
310     if(!$this->is_connected() || !$this->imap_handle){
311       trigger_error("Method not connected, catch error.");
312       return(array());
313     }
315     $result = array();
317     /* Get server config */
318     $cfg= $this->ServerList[$this->MailServer];
320     /* Create search string
321        And prepare replacements 
322      */ 
323     if(preg_match("/\@/",$this->account_id)){
324       $search = preg_replace("/\@/","/*@",$this->account_id);
325       $with_domain = TRUE;
326     }else{
327       $search = $this->account_id."/*";
328       $with_domain = FALSE;
329     }
330     $folder = $this->account_id;
331     if(preg_match("/\@/",$folder)){
332       $folder = preg_replace("/\@.*$/","",$folder);
333     }
335     /* Contact imap server */
336     $list = @imap_listmailbox($this->imap_handle, $cfg["connect"], $this->account_id);
337     $list2 = @imap_listmailbox($this->imap_handle, $cfg["connect"], $search);
339     /* Create list of returned folder names */
340     if (is_array($list)){
342       /* Merge in subfolders */
343       if(is_array($list2)){
344         $list = array_merge($list,$list2);
345       }
347       foreach ($list as $val){
348         $str = trim(preg_replace("/^\{[^\}]*+\}/","",$val));
349         if($with_domain){
350           $str = trim(preg_replace("/\@.*$/","",$str));
351         }
352         $str = preg_replace ("/^.*".preg_quote($folder, '/')."/","INBOX", 
353           mb_convert_encoding($str, "UTF-8", "UTF7-IMAP"));
354         $result[] = $str;      
355       }
356       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,trim(implode($result,", "),", "),
357           "<b>IMAP: Received mailbox folders.</b>");
358       $this->error = imap_last_error();
359     }else{
360       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,imap_last_error(),
361           "<b>IMAP: Cannot receive mailbox folders.</b>");
362       $this->error = imap_last_error();
363       return(array());
364     }
366     /* Append "INBOX" to the folder array if result is empty and request comes from user dialog */
367     if(!count($result)){
368       $result[] = "INBOX";
369     }
371     return($result);
372   }
375   /*! \brief  Returns configured acls
376    */
377   public function  getFolderACLs($folder_acls)
378   {
379     $this->reset_error();
381     /* imap_getacl available? */
382     if (!function_exists('imap_getacl')){
383       $this->error = _("The module imap_getacl is not implemented!");
384       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,"The imap_getacl module is missing!",
385           "<b>IMAP: Cannot set folder acls.</b>");
386       return($folder_acls);
387     }
389     /* Get ACLs and merge them with the already given acls (ldap)
390      */
391     $this->build_account_id();
392     $acls = imap_getacl ($this->imap_handle, $this->account_id);
393     foreach($acls as $user => $acl){
394       if($user == "anyone") $user = "__anyone__"; // Map to internal placeholder
395       $folder_acls[$user] = $acl;
396     }
398     /* Merge given ACL with acl mapping
399        This ensures that no ACL will accidentally overwritten by gosa.
400      */
401     foreach($folder_acls as $user => $acl){
402       if(!isset($this->acl_mapping[$acl])){
403         $this->acl_mapping[$acl] = $acl;
404       }
405     }
407     return($folder_acls);
408   }
412   /*! \brief  Write ACLs back to imap or what ever
413    */
414   public function  setFolderACLs($permissions)
415   {
416     $this->reset_error();
418     /* imap_getacl available? */
419     if (!function_exists('imap_getacl')){
420       $this->error = _("The module imap_getacl is not implemented!");
421       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,"The imap_getacl module is missing!",
422           "<b>IMAP: Cannot set folder acls.</b>");
423       return(FALSE);
424     }
426     /* Get list of subfolders */
427     $folders= $this->getMailboxList();
428     foreach ($folders as $subfolder){
429       $folder_id = $this->create_folder_id($subfolder);
431       /* Remove all acl's for this folder */
432       $users= @imap_getacl ($this->imap_handle, $folder_id);
433       
434       if(is_array($users)){
435         foreach ($users as $userid => $perms){
436           $userid = strtolower($userid);
437           imap_setacl ($this->imap_handle, $folder_id, $userid, "");
438           @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,$folder_id." -> ".$userid,
439               "<b>IMAP: Removing folder permissions.</b>");
440         }
441       }
442     }
444     /* Set permissions for this folder */
445     foreach($folders as $subfolder){
446       $folder_id = $this->create_folder_id($subfolder);
448       foreach ($permissions as $user => $acl){
449         imap_setacl ($this->imap_handle, $folder_id, $user, $acl);
450         @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,$folder_id." -> ".$user.": ".$acl,
451             "<b>IMAP: Setting new folder permissions.</b>");
452       }
453     }
454     return(TRUE);
455   }
458   public function saveSieveSettings()
459   {
460     mailMethod::saveSieveSettings();
462     // Check file integrity 
463     $files = array();
464     foreach(array("sieve-header.txt","sieve-spam.txt","sieve-mailsize.txt","sieve-vacation.txt","sieve-discard.txt") as $file){
465       if(!file_exists(CONFIG_DIR."/".$file) || ! is_readable(CONFIG_DIR."/".$file)){
466         $files[] = CONFIG_DIR."/".$file;
467         @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__ , CONFIG_DIR."/".$file,
468             "<b>Sieve template missing, please locate and move the template file: </b>");
469       }
470     }
471     if(count($files)){
472       $msg = sprintf(_("File '%s' does not exist!"),implode($files,", "));
473       $msg .= "&nbsp;"._("The sieve script may not be written correctly.");
474       msg_dialog::display(_("Warning"),$msg,WARNING_DIALOG);
475     }
477     /* Map attribute from parent class 
478      */
479     $mail = $this->parent->mail;
480     $gosaMailDeliveryMode = $this->parent->gosaMailDeliveryMode;
481     $gosaMailAlternateAddress = $this->parent->gosaMailAlternateAddress;
482     $gosaMailMaxSize = $this->parent->gosaMailMaxSize;
483     $gosaSpamMailbox = $this->parent->gosaSpamMailbox;
484     $gosaSpamSortLevel = $this->parent->gosaSpamSortLevel;
485     $gosaVacationMessage = $this->parent->gosaVacationMessage;
487     /* Try to login into sieve
488      */ 
489     $cfg = $this->ServerList[$this->MailServer];
490     $sieve= new sieve($cfg["sieve_server"], $cfg["sieve_port"], $this->getUAttribValue(),
491         $cfg["password"], $cfg["admin"],$cfg["sieve_option"]);
492     if (!$sieve->sieve_login()){
493       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,$sieve->error_raw ,"<b>SIEVE: login failed.</b>");
494       $this->error = $sieve->error_raw;
495       return(FALSE);
496     }
498     /* Build spamlevel. Spamassassin tags mails with "*" for each integer
499        point of spam. So a spam level of 5.3 gets "*****" which can be
500        checked easily by spam filters */
501     $spamlevel= str_pad("",(int) $gosaSpamSortLevel,"*");
503     /* Get current sieve script named 'gosa'.
504         Check if it valid ("###GOSA" must be the first string).
505         If it is valid just replace it, if it is NOT valid
506          create a backup of the old 
507      */
508     $script= "";
509     if($sieve->sieve_listscripts()){
510       if (in_array_strict("gosa", $sieve->response)){
511         if(!$sieve->sieve_getscript("gosa")){
512           $this->error = sprintf(_("Cannot retrieve SIEVE script: %s"),to_string($sieve->error_raw));
513           @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,$sieve->error_raw ,
514               "<b>SIEVE: Connot read 'gosa' sieve script.</b>");
515           $this->error = $sieve->error_raw;
516           return(FALSE);
517         }
519         $is_valid_script = FALSE;
520         foreach ($sieve->response as $line){
521           if(empty($line)) continue;
522           if (preg_match ("/^###GOSA/", $line) && strlen($script) == 0){
523             $is_valid_script = TRUE;
524           }
525           $line= rtrim($line);
526           $script .= $line;
527         }
529         if($is_valid_script || strlen($script) == 0 || empty($script)){
530           @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,"" ,
531               "<b>SIEVE</b>: Sieve script 'gosa' was a valid GOsa script and will be replaced.");
532         }else{
533           $new_name = "non_gosa_".date("Ymd_H-i-s");
534           $sieve->sieve_sendscript($new_name, $script);
535           @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,$this->sieve->error_raw ,
536               "<b>SIEVE</b>: Non GOsa sieve script. <b>Creating backup of the current sieve script '".$new_name."'.</b>");
537         }
538       }
539     }
542     /*****
543       Build up new sieve script here.
544      *****/
547     /* Only create a new one, if it is not empty */
548     $script= "";
549     if (is_integer(strpos($gosaMailDeliveryMode, "R")) ||
550         is_integer(strpos($gosaMailDeliveryMode, "C")) ||
551         is_integer(strpos($gosaMailDeliveryMode, "I")) ||
552         is_integer(strpos($gosaMailDeliveryMode, "V")) ||
553         is_integer(strpos($gosaMailDeliveryMode, "S"))){
555       $text= preg_replace('/"/', '\\"', implode ("", file(CONFIG_DIR."/sieve-header.txt")));
556       eval ("\$script.=\"$text\";");
557     }
559     /* Add anti-spam code */
560     if (is_integer(strpos($gosaMailDeliveryMode, "S"))){
561       $spambox= $gosaSpamMailbox;
562       $text= preg_replace('/"/', '\\"', implode ("", file(CONFIG_DIR."/sieve-spam.txt")));
563       eval ("\$script.=\"$text\";");
564     }
566     /* Add "reject due to mailsize" code, message is currently not
567        adjustable through GOsa. */
568     if (is_integer(strpos($gosaMailDeliveryMode, "R"))){
569       $maxsize= $gosaMailMaxSize;
570       $text= preg_replace('/"/', '\\"', implode ("", file(CONFIG_DIR."/sieve-mailsize.txt")));
571       eval ("\$script.=\"$text\";");
572     }
574     /* Add vacation information */
575     if (is_integer(strpos($gosaMailDeliveryMode, "V"))){
577       /* Sieve wants all destination addresses for the
578          vacation message, so we've to assemble them from
579          mail and mailAlternateAddress */
580       $addrlist= "\"".$mail."\"";
581       foreach ($gosaMailAlternateAddress as $val){
582         $addrlist .= ", \"$val\"";
583       }
584       $vacmsg= addslashes(addslashes($gosaVacationMessage));
585       $text= preg_replace('/"/', '\\"', implode ("", file(CONFIG_DIR."/sieve-vacation.txt")));
586       eval ("\$script.=\"$text\";");
587     }
589     /* If no local delivery is wanted, tell the script to discard the mail */
590     if (is_integer(strpos($gosaMailDeliveryMode, "I"))){
591       $text= preg_replace('/"/', '\\"', implode ("", file(CONFIG_DIR."/sieve-discard.txt")));
592       eval ("\$script.=\"$text\";");
593     }
595     /****
596       Sieve script build complete
597      ****/
599     /* Upload script and make it the default one */
600     if (!$sieve->sieve_sendscript("gosa", $script)){
601       $this->error = sprintf(_("Cannot store SIEVE script: %s"), to_string($sieve->error_raw));
602       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__, "Error was: ".to_string($sieve->error_raw) ,
603         "<b>SIEVE: Writing new Sieve script failed!</b>");
604       return(FALSE);
605     }
607     if(!$sieve->sieve_setactivescript("gosa")){
608       $this->error = sprintf(_("Cannot activate SIEVE script: %s"), to_string($sieve->error_raw));
609       return(FALSE);
610     }
612     $sieve->sieve_logout();
613   }
616 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
617 ?>