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 if(isset($this->config->data['SERVERS']['IMAP'])){
29 $this->ServerList = $this->config->data['SERVERS']['IMAP'];
30 }
31 }
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 }
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 }
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"], $this->account_id);
308 $list2 = @imap_listmailbox($this->imap_handle, $cfg["connect"], $search);
310 /* Create list of returned folder names */
311 if (is_array($list)){
313 /* Merge in subfolders */
314 if(is_array($list2)){
315 $list = array_merge($list,$list2);
316 }
318 foreach ($list as $val){
319 $str = trim(preg_replace("/^\{[^\}]*+\}/","",$val));
320 if($with_domain){
321 $str = trim(preg_replace("/\@.*$/","",$str));
322 }
323 $str = preg_replace ("/^.*".preg_quote($folder, '/')."/","INBOX",
324 mb_convert_encoding($str, "UTF-8", "UTF7-IMAP"));
325 $result[] = $str;
326 }
327 @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,trim(implode($result,", "),", "),
328 "<b>IMAP: Received mailbox folders.</b>");
329 $this->error = imap_last_error();
330 }else{
331 @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,imap_last_error(),
332 "<b>IMAP: Cannot receive mailbox folders.</b>");
333 $this->error = imap_last_error();
334 return(array());
335 }
337 /* Append "INBOX" to the folder array if result is empty and request comes from user dialog */
338 if(!count($result)){
339 $result[] = "INBOX";
340 }
342 return($result);
343 }
346 /*! \brief Returns configured acls
347 */
348 public function getFolderACLs($folder_acls)
349 {
350 $this->reset_error();
352 /* imap_getacl available? */
353 if (!function_exists('imap_getacl')){
354 $this->error = _("The module imap_getacl is not implemented!");
355 @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,"The imap_getacl module is missing!",
356 "<b>IMAP: Cannot set folder acls.</b>");
357 return($folder_acls);
358 }
360 /* Get ACLs and merge them with the already given acls (ldap)
361 */
362 $this->build_account_id();
363 $acls = imap_getacl ($this->imap_handle, $this->account_id);
364 foreach($acls as $user => $acl){
365 if($user == "anyone") $user = "__anyone__"; // Map to internal placeholder
366 $folder_acls[$user] = $acl;
367 }
369 /* Merge given ACL with acl mapping
370 This ensures that no ACL will accidentally overwritten by gosa.
371 */
372 foreach($folder_acls as $user => $acl){
373 if(!isset($this->acl_mapping[$acl])){
374 $this->acl_mapping[$acl] = $acl;
375 }
376 }
378 return($folder_acls);
379 }
383 /*! \brief Write ACLs back to imap or what ever
384 */
385 public function setFolderACLs($permissions)
386 {
387 $this->reset_error();
389 /* imap_getacl available? */
390 if (!function_exists('imap_getacl')){
391 $this->error = _("The module imap_getacl is not implemented!");
392 @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,"The imap_getacl module is missing!",
393 "<b>IMAP: Cannot set folder acls.</b>");
394 return(FALSE);
395 }
397 /* Get list of subfolders */
398 $folders= $this->getMailboxList();
399 foreach ($folders as $subfolder){
400 $folder_id = $this->create_folder_id($subfolder);
402 /* Remove all acl's for this folder */
403 $users= @imap_getacl ($this->imap_handle, $folder_id);
405 if(is_array($users)){
406 foreach ($users as $userid => $perms){
407 $userid = strtolower($userid);
408 imap_setacl ($this->imap_handle, $folder_id, $userid, "");
409 @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,$folder_id." -> ".$userid,
410 "<b>IMAP: Removing folder permissions.</b>");
411 }
412 }
413 }
415 /* Set permissions for this folder */
416 foreach($folders as $subfolder){
417 $folder_id = $this->create_folder_id($subfolder);
419 foreach ($permissions as $user => $acl){
420 imap_setacl ($this->imap_handle, $folder_id, $user, $acl);
421 @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,$folder_id." -> ".$user.": ".$acl,
422 "<b>IMAP: Setting new folder permissions.</b>");
423 }
424 }
425 return(TRUE);
426 }
429 public function saveSieveSettings()
430 {
431 mailMethod::saveSieveSettings();
433 /* Map attribute from parent class
434 */
435 $mail = $this->parent->mail;
436 $gosaMailDeliveryMode = $this->parent->gosaMailDeliveryMode;
437 $gosaMailAlternateAddress = $this->parent->gosaMailAlternateAddress;
438 $gosaMailMaxSize = $this->parent->gosaMailMaxSize;
439 $gosaSpamMailbox = $this->parent->gosaSpamMailbox;
440 $gosaSpamSortLevel = $this->parent->gosaSpamSortLevel;
441 $gosaVacationMessage = $this->parent->gosaVacationMessage;
443 /* Try to login into sieve
444 */
445 $cfg = $this->ServerList[$this->MailServer];
446 $sieve= new sieve($cfg["sieve_server"], $cfg["sieve_port"], $this->getUAttribValue(),
447 $cfg["password"], $cfg["admin"],$cfg["sieve_option"]);
448 if (!$sieve->sieve_login()){
449 @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,$sieve->error_raw ,"<b>SIEVE: login failed.</b>");
450 $this->error = $sieve->error_raw;
451 return(FALSE);
452 }
454 /* Build spamlevel. Spamassassin tags mails with "*" for each integer
455 point of spam. So a spam level of 5.3 gets "*****" which can be
456 checked easily by spam filters */
457 $spamlevel= str_pad("",(int) $gosaSpamSortLevel,"*");
459 /* Get current sieve script named 'gosa'.
460 Check if it valid ("###GOSA" must be the first string).
461 If it is valid just replace it, if it is NOT valid
462 create a backup of the old
463 */
464 $script= "";
465 if($sieve->sieve_listscripts()){
466 if (in_array("gosa", $sieve->response)){
467 if(!$sieve->sieve_getscript("gosa")){
468 $this->error = sprintf(_("Cannot retrieve SIEVE script: %s"),to_string($sieve->error_raw));
469 @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,$sieve->error_raw ,
470 "<b>SIEVE: Connot read 'gosa' sieve script.</b>");
471 $this->error = $sieve->error_raw;
472 return(FALSE);
473 }
475 $is_valid_script = FALSE;
476 foreach ($sieve->response as $line){
477 if(empty($line)) continue;
478 if (preg_match ("/^###GOSA/", $line) && strlen($script) == 0){
479 $is_valid_script = TRUE;
480 }
481 $line= rtrim($line);
482 $script .= $line;
483 }
485 if($is_valid_script || strlen($script) == 0 || empty($script)){
486 @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,"" ,
487 "<b>SIEVE</b>: Sieve script 'gosa' was a valid GOsa script and will be replaced.");
488 }else{
489 $new_name = "non_gosa_".date("Ymd_H-i-s");
490 $sieve->sieve_sendscript($new_name, $script);
491 @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,$this->sieve->error_raw ,
492 "<b>SIEVE</b>: Non GOsa sieve script. <b>Creating backup of the current sieve script '".$new_name."'.</b>");
493 }
494 }
495 }
498 /*****
499 Build up new sieve script here.
500 *****/
502 /* Only create a new one, if it is not empty */
503 $script= "";
504 if (is_integer(strpos($gosaMailDeliveryMode, "R")) ||
505 is_integer(strpos($gosaMailDeliveryMode, "C")) ||
506 !is_integer(strpos($gosaMailDeliveryMode, "L")) ||
507 is_integer(strpos($gosaMailDeliveryMode, "V")) ||
508 is_integer(strpos($gosaMailDeliveryMode, "S"))){
510 $text= preg_replace('/"/', '\\"', implode ("", file(CONFIG_DIR."/sieve-header.txt")));
511 eval ("\$script.=\"$text\";");
512 }
514 /* Add anti-spam code */
515 if (is_integer(strpos($gosaMailDeliveryMode, "S"))){
516 $spambox= $gosaSpamMailbox;
517 $text= preg_replace('/"/', '\\"', implode ("", file(CONFIG_DIR."/sieve-spam.txt")));
518 eval ("\$script.=\"$text\";");
519 }
521 /* Add "reject due to mailsize" code, message is currently not
522 adjustable through GOsa. */
523 if (is_integer(strpos($gosaMailDeliveryMode, "R"))){
524 $maxsize= $gosaMailMaxSize;
525 $text= preg_replace('/"/', '\\"', implode ("", file(CONFIG_DIR."/sieve-mailsize.txt")));
526 eval ("\$script.=\"$text\";");
527 }
529 /* Add vacation information */
530 if (is_integer(strpos($gosaMailDeliveryMode, "V"))){
532 /* Sieve wants all destination addresses for the
533 vacation message, so we've to assemble them from
534 mail and mailAlternateAddress */
535 $addrlist= "\"".$mail."\"";
536 foreach ($gosaMailAlternateAddress as $val){
537 $addrlist .= ", \"$val\"";
538 }
539 $vacmsg= $gosaVacationMessage;
540 $text= preg_replace('/"/', '\\"', implode ("", file(CONFIG_DIR."/sieve-vacation.txt")));
541 eval ("\$script.=\"$text\";");
542 }
544 /* If no local delivery is wanted, tell the script to discard the mail */
545 if (!is_integer(strpos($gosaMailDeliveryMode, "L"))){
546 $text= preg_replace('/"/', '\\"', implode ("", file(CONFIG_DIR."/sieve-discard.txt")));
547 eval ("\$script.=\"$text\";");
548 }
550 /****
551 Sieve script build complete
552 ****/
554 /* Upload script and make it the default one */
555 if (!$sieve->sieve_sendscript("gosa", $script)){
556 $this->error = sprintf(_("Cannot store SIEVE script: %s"), to_string($sieve->error_raw));
557 @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__, "Error was: ".to_string($sieve->error_raw) ,
558 "<b>SIEVE: Writing new Sieve script failed!</b>");
559 return(FALSE);
560 }
562 if(!$sieve->sieve_setactivescript("gosa")){
563 $this->error = sprintf(_("Cannot activate SIEVE script: %s"), to_string($sieve->error_raw));
564 return(FALSE);
565 }
567 $sieve->sieve_logout();
568 }
569 }
571 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
572 ?>