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"], $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);
394 echo $folder_id."<br>";
396 /* Remove all acl's for this folder */
397 $users= @imap_getacl ($this->imap_handle, $folder_id);
399 if(is_array($users)){
400 foreach ($users as $userid => $perms){
401 $userid = strtolower($userid);
402 imap_setacl ($this->imap_handle, $folder_id, $userid, "");
403 @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,$folder_id." -> ".$userid,
404 "<b>IMAP: Removing folder permissions.</b>");
405 }
406 }
407 }
409 /* Set permissions for this folder */
410 foreach($folders as $subfolder){
411 $folder_id = $this->create_folder_id($subfolder);
413 foreach ($permissions as $user => $acl){
414 imap_setacl ($this->imap_handle, $folder_id, $user, $acl);
415 @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,$folder_id." -> ".$user.": ".$acl,
416 "<b>IMAP: Setting new folder permissions.</b>");
417 }
418 }
419 return(TRUE);
420 }
423 public function saveSieveSettings()
424 {
425 mailMethod::saveSieveSettings();
427 /* Map attribute from parent class
428 */
429 $mail = $this->parent->mail;
430 $gosaMailDeliveryMode = $this->parent->gosaMailDeliveryMode;
431 $gosaMailAlternateAddress = $this->parent->gosaMailAlternateAddress;
432 $gosaMailMaxSize = $this->parent->gosaMailMaxSize;
433 $gosaSpamMailbox = $this->parent->gosaSpamMailbox;
434 $gosaSpamSortLevel = $this->parent->gosaSpamSortLevel;
435 $gosaVacationMessage = $this->parent->gosaVacationMessage;
437 /* Try to login into sieve
438 */
439 $cfg = $this->ServerList[$this->MailServer];
440 $sieve= new sieve($cfg["sieve_server"], $cfg["sieve_port"], $this->getUAttribValue(),
441 $cfg["password"], $cfg["admin"],$cfg["sieve_option"]);
442 if (!$sieve->sieve_login()){
443 @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,$sieve->error_raw ,"<b>SIEVE: login failed.</b>");
444 $this->error = $sieve->error_raw;
445 return(FALSE);
446 }
448 /* Build spamlevel. Spamassassin tags mails with "*" for each integer
449 point of spam. So a spam level of 5.3 gets "*****" which can be
450 checked easily by spam filters */
451 $spamlevel= str_pad("",(int) $gosaSpamSortLevel,"*");
453 /* Get current sieve script named 'gosa'.
454 Check if it valid ("###GOSA" must be the first string).
455 If it is valid just replace it, if it is NOT valid
456 create a backup of the old
457 */
458 $script= "";
459 if($sieve->sieve_listscripts()){
460 if (in_array("gosa", $sieve->response)){
461 if(!$sieve->sieve_getscript("gosa")){
462 $this->error = sprintf(_("Cannot retrieve SIEVE script: %s"),to_string($sieve->error_raw));
463 @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,$sieve->error_raw ,
464 "<b>SIEVE: Connot read 'gosa' sieve script.</b>");
465 $this->error = $sieve->error_raw;
466 return(FALSE);
467 }
469 $is_valid_script = FALSE;
470 foreach ($sieve->response as $line){
471 if(empty($line)) continue;
472 if (preg_match ("/^###GOSA/", $line) && strlen($script) == 0){
473 $is_valid_script = TRUE;
474 }
475 $line= rtrim($line);
476 $script .= $line;
477 }
479 if($is_valid_script || strlen($script) == 0 || empty($script)){
480 @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,"" ,
481 "<b>SIEVE</b>: Sieve script 'gosa' was a valid GOsa script and will be replaced.");
482 }else{
483 $new_name = "non_gosa_".date("Ymd_H-i-s");
484 $sieve->sieve_sendscript($new_name, $script);
485 @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__,$this->sieve->error_raw ,
486 "<b>SIEVE</b>: Non GOsa sieve script. <b>Creating backup of the current sieve script '".$new_name."'.</b>");
487 }
488 }
489 }
492 /*****
493 Build up new sieve script here.
494 *****/
496 /* Only create a new one, if it is not empty */
497 $script= "";
498 if (is_integer(strpos($gosaMailDeliveryMode, "R")) ||
499 is_integer(strpos($gosaMailDeliveryMode, "C")) ||
500 !is_integer(strpos($gosaMailDeliveryMode, "L")) ||
501 is_integer(strpos($gosaMailDeliveryMode, "V")) ||
502 is_integer(strpos($gosaMailDeliveryMode, "S"))){
504 $text= preg_replace('/"/', '\\"', implode ("", file(CONFIG_DIR."/sieve-header.txt")));
505 eval ("\$script.=\"$text\";");
506 }
508 /* Add anti-spam code */
509 if (is_integer(strpos($gosaMailDeliveryMode, "S"))){
510 $spambox= $gosaSpamMailbox;
511 $text= preg_replace('/"/', '\\"', implode ("", file(CONFIG_DIR."/sieve-spam.txt")));
512 eval ("\$script.=\"$text\";");
513 }
515 /* Add "reject due to mailsize" code, message is currently not
516 adjustable through GOsa. */
517 if (is_integer(strpos($gosaMailDeliveryMode, "R"))){
518 $maxsize= $gosaMailMaxSize;
519 $text= preg_replace('/"/', '\\"', implode ("", file(CONFIG_DIR."/sieve-mailsize.txt")));
520 eval ("\$script.=\"$text\";");
521 }
523 /* Add vacation information */
524 if (is_integer(strpos($gosaMailDeliveryMode, "V"))){
526 /* Sieve wants all destination addresses for the
527 vacation message, so we've to assemble them from
528 mail and mailAlternateAddress */
529 $addrlist= "\"".$mail."\"";
530 foreach ($gosaMailAlternateAddress as $val){
531 $addrlist .= ", \"$val\"";
532 }
533 $vacmsg= $gosaVacationMessage;
534 $text= preg_replace('/"/', '\\"', implode ("", file(CONFIG_DIR."/sieve-vacation.txt")));
535 eval ("\$script.=\"$text\";");
536 }
538 /* If no local delivery is wanted, tell the script to discard the mail */
539 if (!is_integer(strpos($gosaMailDeliveryMode, "L"))){
540 $text= preg_replace('/"/', '\\"', implode ("", file(CONFIG_DIR."/sieve-discard.txt")));
541 eval ("\$script.=\"$text\";");
542 }
544 /****
545 Sieve script build complete
546 ****/
548 /* Upload script and make it the default one */
549 if (!$sieve->sieve_sendscript("gosa", $script)){
550 $this->error = sprintf(_("Cannot store SIEVE script: %s"), to_string($sieve->error_raw));
551 @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__, "Error was: ".to_string($sieve->error_raw) ,
552 "<b>SIEVE: Writing new Sieve script failed!</b>");
553 return(FALSE);
554 }
556 if(!$sieve->sieve_setactivescript("gosa")){
557 $this->error = sprintf(_("Cannot activate SIEVE script: %s"), to_string($sieve->error_raw));
558 return(FALSE);
559 }
561 $sieve->sieve_logout();
562 }
563 }
565 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
566 ?>