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