Code

Updated folder creation
[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     imap_timeout(1, 10 );
61     $this->imap_handle = @imap_open($cfg['connect'], $cfg['admin'], $cfg['password'], OP_HALFOPEN);
63     /* Mailbox reachable? */
64     if ($this->imap_handle === FALSE){
65       $this->error = imap_last_error();
67       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,"<b>Failed</b> :".imap_last_error(),
68         "<b>IMAP:</b> ".$cfg['admin']."@".$cfg['connect']);
70       return (FALSE);
71       $this->connected = FALSE;
72     }
73     @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,"<b>successful</b>",
74         "<b>IMAP:</b> ".$cfg['admin']."@".$cfg['connect']);
75     $this->connected = TRUE;
77     return (TRUE);
78   }
81   public function account_exists()
82   {
83     if(!$this->is_connected() || !$this->imap_handle){
84       trigger_error("Method not connected, catch error.");
85       return(array());
86     }
88     /* Get server config */
89     $cfg= $this->ServerList[$this->MailServer];
90     $list = @imap_listmailbox($this->imap_handle, $cfg["connect"], $this->account_id);
91     $res = is_array($list) && count($list);
92     if($res){
93       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,"","<b>IMAP: Account exists in imap server.</b>"); 
94     }else{
95       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,"","<b>IMAP: Account seems NOT to exists in imap server.</b>"); 
96     }
97     return($res);
98   }
100   public function disconnect()
101   {
102     mailMethod::disconnect();
103     if($this->is_connected()){
104       @imap_close ($this->imap_handle);
105     }
106   }
109   public function is_connected()
110   {
111     $ret =    mailMethod::is_connected();
112     return($ret && $this->imap_handle);
113   }
115   protected function loadQuota()
116   {
117     if(!$this->quotaEnabled()) return(TRUE);
118     if(!$this->is_connected() || !$this->imap_handle){
119       trigger_error("Method not connected, catch error.");
120       return(FALSE);
121     }
123     $this->reset_error();
125     /* Load quota settings */
126     $result = array("quotaUsage"=>"","gosaMailQuota"=>"");
127     $quota_value = @imap_get_quota($this->imap_handle, $this->account_id);
129     /* Reset error queue, imap_qet_quota() will fail if the quota wasn't set yet.
130      */
131     imap_errors();
133     if(is_array($quota_value) && count($quota_value)) {
134       if (isset($quota_value["STORAGE"]) && is_array($quota_value["STORAGE"])){
136         /* use for PHP >= 4.3 */
137         if($quota_value["STORAGE"]['limit'] == 2147483647){
138           $result['quotaUsage']=    (int) ($quota_value["STORAGE"]['usage'] / 1024);
139           $result['gosaMailQuota']=  "";
140         }else{
141           $result['quotaUsage']=    (int) ($quota_value["STORAGE"]['usage'] / 1024);
142           $result['gosaMailQuota']= (int) ($quota_value["STORAGE"]['limit'] / 1024);
143         }
144       } else {
146         /* backward icompatible */
147         if($quota_value['usage'] == 2147483647){
148           $result['quotaUsage']=    (int) ($quota_value['usage'] / 1024);
149           $result['gosaMailQuota']= "";
150         }else{
151           $result['quotaUsage']=    (int) ($quota_value['usage'] / 1024);
152           $result['gosaMailQuota']= (int) ($quota_value['limit'] / 1024);
153         }
154       }
155     }
156     $this->quotaValue = $result['gosaMailQuota'];
157     $this->quotaUsage = $result['quotaUsage'];
159     /* Write debug output */
160     if(is_array($quota_value)){
161       if($this->quotaValue == ""){
162         $quota = "(".$this->quotaUsage." / unlimited)";
163       }else{
164         $quota = "(".$this->quotaUsage." / ".$this->quotaValue.")";
165       }
166       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__, $quota , 
167           "<b>IMAP: Successfully received account quota</b>");
168     }else{
169       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__, imap_last_error() , 
170           "<b>IMAP: Failed to receive account quota</b>");
171     }
172   }
174   public function getQuota($quota)
175   {
176     mailMethod::getQuota($quota);
177     if(!$this->quota_loaded){
178       $this->quota_loaded = TRUE;
179       $this->loadQuota();
180     }
181     return($this->quotaValue);
182   }
184   public function getQuotaUsage()
185   {
186     mailMethod::getQuotaUsage();
187     if(!$this->quota_loaded){
188       $this->quota_loaded = TRUE;
189       $this->loadQuota();
190     }
191     return($this->quotaUsage);
192   }
194   public function setQuota($number)
195   {
196     mailMethod::setQuota($number);    
198     if(!$this->quotaEnabled()) return(TRUE);
199     if(!$this->is_connected() || !$this->imap_handle){
200       trigger_error("Method not connected, catch error.");
201       return(FALSE);
202     }
204     $this->build_account_id();
206     /* Workaround for the php imap extension */
207     if (($this->quotaValue == "") || ($this->quotaValue== "2147483647")){
208       $this->quotaValue= "2147483647";
209     }elseif($this->quotaValue > 0){
210       $this->quotaValue = $this->quotaValue *1024;
211     }
212     $debug_number = $this->quotaValue." KB";
213     if($this->quotaValue == "2147483647"){
214       $debug_number .= "<i>Unlimited</i>";
215     }
217     if (!imap_set_quota($this->imap_handle, $this->account_id, $this->quotaValue)){
218       msg_dialog::display(_("IMAP error"), sprintf(_("Cannot modify IMAP mailbox quota: %s"),
219             '<br><br><i>'.imap_last_error().'</i>'), ERROR_DIALOG);
220       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__, "<b>".$this->account_id.": (".$debug_number.")</b>" , 
221           "<b>IMAP: Set account quota</b> on server '".$this->MailServer."' <b>".imap_last_error()."</b>");
222       return (FALSE);
223     }
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);
226     return (TRUE);
227   }
230   public function updateMailbox()
231   {
232     mailMethod::updateMailbox();
234     if(!$this->is_connected() || !$this->imap_handle){
235       trigger_error("Method not connected, catch error.");
236       return(FALSE);
237     }
238   
239     $this->build_account_id ();
240     if($this->is_connected()){
241       $cfg= $this->ServerList[$this->MailServer];
242       $list = imap_listmailbox($this->imap_handle, $cfg["connect"], $this->account_id);
243       if ($list === FALSE){
244         @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__, "<b>".$this->account_id."</b>" , 
245           "<b>IMAP: Add/Update account</b> on server :".$this->MailServer);
246         if (!imap_createmailbox($this->imap_handle, $cfg["connect"]. $this->account_id)){
247           $this->error = imap_last_error();
248           return(FALSE);
249         }
250       }
251     }
252     return(TRUE);
253   }
256   public function deleteMailbox()
257   {
258     mailMethod::deleteMailbox();
260     if(!$this->is_connected() || !$this->imap_handle){
261       trigger_error("Method not connected, catch error.");
262       return(FALSE);
263     }
265     $this->build_account_id ();
267     $cfg= $this->ServerList[$this->MailServer];
268     @imap_setacl ($this->imap_handle, $this->account_id, $cfg["admin"], "lrswipcda");
269     if (!imap_deletemailbox($this->imap_handle, $cfg["connect"].$this->account_id)){
270       $this->error = imap_last_error();
271       return (FALSE);
272     }
273     return (TRUE);
274   }
276   
277   public function getMailboxList()
278   {
279     mailMethod::getMailboxList();
281     if(!$this->is_connected() || !$this->imap_handle){
282       trigger_error("Method not connected, catch error.");
283       return(array());
284     }
286     $result = array();
288     /* Get server config */
289     $cfg= $this->ServerList[$this->MailServer];
291     /* Create search string
292        And prepare replacements 
293      */ 
294     if(preg_match("/\@/",$this->account_id)){
295       $search = preg_replace("/\@/","*@",$this->account_id);
296       $with_domain = TRUE;
297     }else{
298       $search = $this->account_id."*";
299       $with_domain = FALSE;
300     }
301     $folder = $this->account_id;
302     if(preg_match("/\@/",$folder)){
303       $folder = preg_replace("/\@.*$/","",$folder);
304     }
306     /* Contact imap server */
307     $list = @imap_listmailbox($this->imap_handle, $cfg["connect"], $search);
309     /* Create list of returned folder names */
310     if (is_array($list)){
311       foreach ($list as $val){
312         $str = trim(preg_replace("/^\{[^\}]*+\}/","",$val));
313         if($with_domain){
314           $str = trim(preg_replace("/\@.*$/","",$str));
315         }
316         $str = preg_replace ("/^.*".preg_quote($folder, '/')."/","INBOX", 
317           mb_convert_encoding($str, "UTF-8", "UTF7-IMAP"));
318         $result[] = $str;      
319       }
320       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,trim(implode($result,", "),", "),
321           "<b>IMAP: Received mailbox folders.</b>");
322       $this->error = imap_last_error();
323     }else{
324       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,imap_last_error(),
325           "<b>IMAP: Cannot receive mailbox folders.</b>");
326       $this->error = imap_last_error();
327       return(array());
328     }
330     /* Append "INBOX" to the folder array if result is empty and request comes from user dialog */
331     if(!count($result)){
332       $result[] = "INBOX";
333     }
335     return($result);
336   }
339   /*! \brief  Returns configured acls
340    */
341   public function  getFolderACLs($folder_acls)
342   {
343     $this->reset_error();
345     /* imap_getacl available? */
346     if (!function_exists('imap_getacl')){
347       $this->error = _("The module imap_getacl is not implemented!");
348       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,"The imap_getacl module is missing!",
349           "<b>IMAP: Cannot set folder acls.</b>");
350       return($folder_acls);
351     }
353     /* Get ACLs and merge them with the already given acls (ldap)
354      */
355     $this->build_account_id();
356     $acls = imap_getacl ($this->imap_handle, $this->account_id);
357     foreach($acls as $user => $acl){
358       if($user == "anyone") $user = "__anyone__"; // Map to internal placeholder
359       $folder_acls[$user] = $acl;
360     }
362     /* Merge given ACL with acl mapping
363        This ensures that no ACL will accidentally overwritten by gosa.
364      */
365     foreach($folder_acls as $user => $acl){
366       if(!isset($this->acl_mapping[$acl])){
367         $this->acl_mapping[$acl] = $acl;
368       }
369     }
371     return($folder_acls);
372   }
376   /*! \brief  Write ACLs back to imap or what ever
377    */
378   public function  setFolderACLs($permissions)
379   {
380     $this->reset_error();
382     /* imap_getacl available? */
383     if (!function_exists('imap_getacl')){
384       $this->error = _("The module imap_getacl is not implemented!");
385       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,"The imap_getacl module is missing!",
386           "<b>IMAP: Cannot set folder acls.</b>");
387       return(FALSE);
388     }
390     /* Get list of subfolders */
391     $folders= $this->getMailboxList();
392     foreach ($folders as $subfolder){
393       $folder_id = $this->create_folder_id($subfolder);
395       /* Remove all acl's for this folder */
396       $users= @imap_getacl ($this->imap_handle, $folder_id);
397       
398       if(is_array($users)){
399         foreach ($users as $userid => $perms){
400           $userid = strtolower($userid);
401           imap_setacl ($this->imap_handle, $folder_id, $userid, "");
402           @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,$folder_id." -> ".$userid,
403               "<b>IMAP: Removing folder permissions.</b>");
404         }
405       }
406     }
408     /* Set permissions for this folder */
409     foreach($folders as $subfolder){
410       $folder_id = $this->create_folder_id($subfolder);
412       foreach ($permissions as $user => $acl){
413         imap_setacl ($this->imap_handle, $folder_id, $user, $acl);
414         @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,$folder_id." -> ".$user.": ".$acl,
415             "<b>IMAP: Setting new folder permissions.</b>");
416       }
417     }
418     return(TRUE);
419   }
422   public function saveSieveSettings()
423   {
424     mailMethod::saveSieveSettings();
426     /* Map attribute from parent class 
427      */
428     $mail = $this->parent->mail;
429     $gosaMailDeliveryMode = $this->parent->gosaMailDeliveryMode;
430     $gosaMailAlternateAddress = $this->parent->gosaMailAlternateAddress;
431     $gosaMailMaxSize = $this->parent->gosaMailMaxSize;
432     $gosaSpamMailbox = $this->parent->gosaSpamMailbox;
433     $gosaSpamSortLevel = $this->parent->gosaSpamSortLevel;
434     $gosaVacationMessage = $this->parent->gosaVacationMessage;
436     /* Try to login into sieve
437      */ 
438     $cfg = $this->ServerList[$this->MailServer];
439     $sieve= new sieve($cfg["sieve_server"], $cfg["sieve_port"], $this->getUAttribValue(),
440         $cfg["password"], $cfg["admin"],$cfg["sieve_option"]);
441     if (!$sieve->sieve_login()){
442       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,$sieve->error_raw ,"<b>SIEVE: login failed.</b>");
443       $this->error = $sieve->error_raw;
444       return(FALSE);
445     }
447     /* Build spamlevel. Spamassassin tags mails with "*" for each integer
448        point of spam. So a spam level of 5.3 gets "*****" which can be
449        checked easily by spam filters */
450     $spamlevel= str_pad("",(int) $gosaSpamSortLevel,"*");
452     /* Get current sieve script named 'gosa'.
453         Check if it valid ("###GOSA" must be the first string).
454         If it is valid just replace it, if it is NOT valid
455          create a backup of the old 
456      */
457     $script= "";
458     if($sieve->sieve_listscripts()){
459       if (in_array("gosa", $sieve->response)){
460         if(!$sieve->sieve_getscript("gosa")){
461           $this->error = sprintf(_("Cannot retrieve SIEVE script: %s"),to_string($sieve->error_raw));
462           @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,$sieve->error_raw ,
463               "<b>SIEVE: Connot read 'gosa' sieve script.</b>");
464           $this->error = $sieve->error_raw;
465           return(FALSE);
466         }
468         $is_valid_script = FALSE;
469         foreach ($sieve->response as $line){
470           if(empty($line)) continue;
471           if (preg_match ("/^###GOSA/", $line) && strlen($script) == 0){
472             $is_valid_script = TRUE;
473           }
474           $line= rtrim($line);
475           $script .= $line;
476         }
478         if($is_valid_script || strlen($script) == 0 || empty($script)){
479           @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,"" ,
480               "<b>SIEVE</b>: Sieve script 'gosa' was a valid GOsa script and will be replaced.");
481         }else{
482           $new_name = "non_gosa_".date("Ymd_H-i-s");
483           $sieve->sieve_sendscript($new_name, $script);
484           @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,$this->sieve->error_raw ,
485               "<b>SIEVE</b>: Non GOsa sieve script. <b>Creating backup of the current sieve script '".$new_name."'.</b>");
486         }
487       }
488     }
491     /*****
492       Build up new sieve script here.
493      *****/
495     /* Only create a new one, if it is not empty */
496     $script= "";
497     if (is_integer(strpos($gosaMailDeliveryMode, "R")) ||
498         is_integer(strpos($gosaMailDeliveryMode, "C")) ||
499         !is_integer(strpos($gosaMailDeliveryMode, "L")) ||
500         is_integer(strpos($gosaMailDeliveryMode, "V")) ||
501         is_integer(strpos($gosaMailDeliveryMode, "S"))){
503       $text= preg_replace('/"/', '\\"', implode ("", file(CONFIG_DIR."/sieve-header.txt")));
504       eval ("\$script.=\"$text\";");
505     }
507     /* Add anti-spam code */
508     if (is_integer(strpos($gosaMailDeliveryMode, "S"))){
509       $spambox= $gosaSpamMailbox;
510       $text= preg_replace('/"/', '\\"', implode ("", file(CONFIG_DIR."/sieve-spam.txt")));
511       eval ("\$script.=\"$text\";");
512     }
514     /* Add "reject due to mailsize" code, message is currently not
515        adjustable through GOsa. */
516     if (is_integer(strpos($gosaMailDeliveryMode, "R"))){
517       $maxsize= $gosaMailMaxSize;
518       $text= preg_replace('/"/', '\\"', implode ("", file(CONFIG_DIR."/sieve-mailsize.txt")));
519       eval ("\$script.=\"$text\";");
520     }
522     /* Add vacation information */
523     if (is_integer(strpos($gosaMailDeliveryMode, "V"))){
525       /* Sieve wants all destination addresses for the
526          vacation message, so we've to assemble them from
527          mail and mailAlternateAddress */
528       $addrlist= "\"".$mail."\"";
529       foreach ($gosaMailAlternateAddress as $val){
530         $addrlist .= ", \"$val\"";
531       }
532       $vacmsg= $gosaVacationMessage;
533       $text= preg_replace('/"/', '\\"', implode ("", file(CONFIG_DIR."/sieve-vacation.txt")));
534       eval ("\$script.=\"$text\";");
535     }
537     /* If no local delivery is wanted, tell the script to discard the mail */
538     if (!is_integer(strpos($gosaMailDeliveryMode, "L"))){
539       $text= preg_replace('/"/', '\\"', implode ("", file(CONFIG_DIR."/sieve-discard.txt")));
540       eval ("\$script.=\"$text\";");
541     }
543     /****
544       Sieve script build complete
545      ****/
547     /* Upload script and make it the default one */
548     if (!$sieve->sieve_sendscript("gosa", $script)){
549       $this->error = sprintf(_("Cannot store SIEVE script: %s"), to_string($sieve->error_raw));
550       @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__, "Error was: ".to_string($sieve->error_raw) ,
551         "<b>SIEVE: Writing new Sieve script failed!</b>");
552       return(FALSE);
553     }
555     if(!$sieve->sieve_setactivescript("gosa")){
556       $this->error = sprintf(_("Cannot activate SIEVE script: %s"), to_string($sieve->error_raw));
557       return(FALSE);
558     }
560     $sieve->sieve_logout();
561   }
564 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
565 ?>