Code

Call post events if sieve script was written
[gosa.git] / plugins / personal / mail / class_mailAccount.inc
1 <?php
2 /*! \brief   mail plugin
3   \author  Cajus Pollmeier <pollmeier@gonicus.de>
4   \version 2.00
5   \date    24.07.2003
7   This class provides the functionality to read and write all attributes
8   relevant for gosaMailAccounts from/to the LDAP. It does syntax checking
9   and displays the formulars required.
10  */
12 /* Load sieve support */
13 require_once ("sieve/libsieve.inc");
15 /* Load mail methods */
16 global $BASE_DIR;
17 get_dir_list("$BASE_DIR/include");
19 class mailAccount extends plugin
20 {
21   /* Definitions */
22   var $plHeadline         = "Mail";
23   var $plDescription      = "This does something";
24   var $method             = "mailMethod";
26   /* plugin specific values */
27   var $mail                               = "";
28   var $uid                                = "";
29   var $gosaMailAlternateAddress           = array();
30   var $gosaMailForwardingAddress          = array();
31   var $gosaMailDeliveryMode               = "[L        ]";
32   var $gosaMailServer                     = "";
33   var $gosaMailQuota                      = "";
34   var $gosaMailMaxSize                    = "";
35   var $gosaVacationMessage                = "";
36   var $gosaVacationStart                  = 0;
37   var $gosaVacationStop                   = 0;
38   var $gosaSpamSortLevel                  = "";
39   var $gosaSpamMailbox                    = "";
41   var $quotaUsage                         = 0;
42   var $forward_dialog                     = FALSE;
43   var $folder_prefix                      = "";
44   var $mailboxList                        = array("INBOX");
45   var $default_permissions                = "none";
46   var $member_permissions                 = "post";
47   var $members                            = array();
48   var $admins                             = array();
49   var $vacations                          = array();
50   var $perms                              = array(  "lrs"       => "read", 
51                                                     "lrsp"      => "post", 
52                                                     "lrsip"     => "append",
53                                                     "lrswipcd"  => "write", 
54                                                     "lrswipcda" => "all" );
56   /* attribute list for save action */
57   var $attributes= array("mail", "gosaMailServer", "gosaMailQuota", "gosaMailMaxSize","gosaMailForwardingAddress",
58       "gosaMailDeliveryMode", "gosaSpamSortLevel", "gosaSpamMailbox","gosaMailAlternateAddress",
59       "gosaVacationMessage", "gosaMailAlternateAddress", "gosaMailForwardingAddress", "gosaVacationStart", "gosaVacationStop");
60   var $objectclasses= array("gosaMailAccount");
62   var $sieve_management = NULL;
64   /* constructor, if 'dn' is set, the node loads the given
65      'dn' from LDAP */
66   function mailAccount ($config, $dn= NULL, $parent= NULL)
67   {
68     /* Load bases attributes */
69     plugin::plugin($config, $dn, $parent);
71     if(isset($this->attrs['uid'])){
72       $this->uid = $this->attrs['uid'][0];
73     }
74  
75     if(is_array($this->gosaMailServer) && isset($this->gosaMailServer[0])){
76       $this->gosaMailServer = $this->gosaMailServer[0];
77     }
79     /* Save initial account state */
80     $this->initially_was_account= $this->is_account;
82     /*  Set mailMethod to the one defined in gosa.conf */
83     if (isset($this->config->current['MAILMETHOD'])){
84       $method= $this->config->current['MAILMETHOD'];
85       if (class_exists("mailMethod$method")){
86         $this->method= "mailMethod$method";
87       } else {
88         print_red(sprintf(_("There is no mail method '%s' specified in your gosa.conf available."), $method));
89       }
90     }
92     /* Create the account prefix  user. user/ 
93        Preset folder prefix. Will change it later to respect
94        altnamespace. */
95     if (isset($this->config->current['CYRUSUNIXSTYLE']) && $this->config->current['CYRUSUNIXSTYLE'] == "true"){
96       $this->folder_prefix= "user/";
97     }elseif (isset($this->config->data['MAIN']['CYRUSUNIXSTYLE']) && $this->config->data['MAIN']['CYRUSUNIXSTYLE'] == "true"){
98       $this->folder_prefix= "user/";
99     } else {
100       $this->folder_prefix= "user.";
101     }
102    
103     /* This is not a new account, parse additional attributes */
104     if (($dn != NULL) && ($dn != "new") && $this->is_account){
106       /* Load attributes containing arrays */
107       foreach (array("gosaMailAlternateAddress", "gosaMailForwardingAddress") as $val){
108         $this->$val= array();
109         if (isset($this->attrs["$val"]["count"])){
110           for ($i= 0; $i<$this->attrs["$val"]["count"]; $i++){
111             array_push($this->$val, $this->attrs["$val"][$i]);
112           }
113         }
114       }
117       /* Only do IMAP actions if gosaMailServer attribute is set */
118       if (isset ($this->attrs["gosaMailServer"][0])){
120         $method = new $this->method($this->config);
121         $id     = $method->uattrib;
123         /* Adapt attributes if needed */
124         $method->fixAttributesOnLoad($this);
126         /* FixAttributesOnLoad possibly creates an array out of gosaMailServer.
127             If the mail tab wasn't opened once before saving, the account can't be saved */
128         if(is_array($this->gosaMailServer)){
129           $this->gosaMailServer = $this->gosaMailServer[0];
130         }
132         if ($method->connect($this->attrs["gosaMailServer"][0])){
134           /* Update quota values */
135           $quota= $method->getQuota($this->folder_prefix.$this->$id);
136          
137           if($quota){
138             if ($quota['gosaMailQuota'] == 2147483647){
139               $this->quotaUsage     = "";
140               $this->gosaMailQuota  = "";
141             } else {
142               $this->quotaUsage     = $quota['quotaUsage'];
143               $this->gosaMailQuota  = $quota['gosaMailQuota'];
144             }
145           }else{
146             $this->quotaUsage     = "";
147             $this->gosaMailQuota  = "";
148 //            print_red(sprintf(_("Can't get quota information for '%s'."),$this->folder_prefix.$this->$id));
149           }
151           /* Get mailboxes / folder like INBOX ..*/
152           $this->mailboxList= $method->getMailboxList($this->folder_prefix.$this->$id,$this->$id);
153           
154           $method->disconnect();
155         }else{
156           /* Could not connect to ldap.
157            */
158           if (isset($this->attrs['gosaMailQuota'][0])){
159             $this->gosaMailQuota = $this->attrs['gosaMailQuota'][0];
160           }
161         }
162       }
163     }
166     /* Get vacation message */
168     /* Fill vacation array */
169     $this->vacation= array();
170     if (isset($this->config->current['VACATIONDIR'])){
171       $dir= $this->config->current['VACATIONDIR'];
172       if (is_dir($dir) && is_readable($dir)){
174         /* Look for files and build the vacation array */
175         $dh= opendir($dir);
176         while ($file = readdir($dh)){
177           $description= $this->parse_vacation("$dir/$file");
178           if ($description != ""){
179             $this->vacation["$dir/$file"]= $description;
180           }
181         }
182         closedir($dh);
183       }
184     }
186     /* Create sieve management class */
187     $method = new $this->method($this->config);
188     $id     = $method->uattrib;
189     $this->sieve_management = new sieveManagement($this->config,$this->dn,$this,$id);
191   /* Create filter */
193     /* Get global filter config */
194     if (!is_global("mailfilter")){
195       $ui= get_userinfo();
196       $base= get_base_from_people($ui->dn);
197       $mailfilter= array( "depselect"       => $base,
198           "muser"            => "",
199           "regex"           => "*");
200       register_global("mailfilter", $mailfilter);
201     }
202   }
205   function parse_vacation($file)
206   {
207     $desc= "";
209     if (is_file($file)){
210       $fh = fopen($file, "r");
211       $line= fgets($fh, 256);
213       if (!preg_match('/^DESC:/', $line)){
214         print_red (_("No DESC tag in vacation file:")." $file");
215         return $desc;
216       }
217       fclose ($fh);
219       $desc= trim(preg_replace('/^DESC:\s*/', '', $line));
220     }
222     return $desc;
223   }
226   function execute()
227   {
228     /* Call parent execute */
229     plugin::execute();
231     /* Initialise vars */
233     /* Load templating engine */
234     $smarty= get_smarty();
235     $display= "";
237     /* Get available mailserver */
238     $mailserver= array();
239     foreach ($this->config->data['SERVERS']['IMAP'] as $key => $val){
240       $mailserver[]= $key;
241     }
244     /*
245      * Sieve Management
246      */
247     if(isset($_POST['sieveManagement'])
248         && preg_match("/C/",$this->gosaMailDeliveryMode)
249         && chkacl($this->acl,"sieveManagement") == "") {
250       $this->dialog = $this->sieve_management;
251     }
253     /* Cancel sieve edit */
254     if(isset($_POST['sieve_cancel'])){
255       $this->dialog = NULL;
256     }
258     /* Save sieve changes */
259     if(isset($_POST['sieve_finish'])){
260       $this->sieve_management = $this->dialog;
261       $this->dialog = NULL;
262     }
264     if(is_object($this->dialog)){
265       $this->dialog->save_object();
266       return($this->dialog->execute());
267     }
270     /* Handle account state */
272     /* Do we need to flip is_account state? */
273     if (isset($_POST['modify_state'])){
275       /* Onyl change account state if allowed */
276       if($this->is_account && $this->acl == "#all#" && !$this->accountDelegationsConfigured()){
277         $this->is_account= !$this->is_account;
278       }elseif(!$this->is_account && chkacl($this->acl,"create") == ""){
279         $this->is_account= !$this->is_account;
280       }
281     }
283     /* Do we represent a valid account? */
284     if (!$this->is_account && $this->parent == NULL){
285       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
286         _("This account has no mail extensions.")."</b>";
288       $display.= back_to_main();
289       return ($display);
290     }
292     /* Show tab dialog headers */
293     if ($this->parent != NULL){
294       if ($this->is_account){
295         if($this->accountDelegationsConfigured()){
296           $display= $this->show_header(_("Remove mail account"),
297               _("This account can't be removed while there are delegations configured. Remove those delegations first."),TRUE,TRUE);
298         }else{
299           $display= $this->show_header(_("Remove mail account"),
300               _("This account has mail features enabled. You can disable them by clicking below."));
301         }
302       } else {
303         $display= $this->show_header(_("Create mail account"), _("This account has mail features disabled. You can enable them by clicking below."));
304         return ($display);
305       }
306     }
308     /* Forwarder  subdialog */
310     /* Trigger forward add dialog? */
311     if (isset($_POST['add_local_forwarder'])){
312       $this->forward_dialog= TRUE;
313       $this->dialog= TRUE;
314     }
316     /* Cancel forward add dialog? */
317     if (isset($_POST['add_locals_cancel'])){
318       $this->forward_dialog= FALSE;
319       $this->dialog= FALSE;
320     }
322     /* Finished adding of locals? */
323     if (isset($_POST['add_locals_finish'])){
324       if (count ($_POST['local_list']) &&
325           chkacl ($this->acl, "gosaMailForwardingAddress") == ""){
327         /* Walk through list of forwarders, ignore own addresses */
328         foreach ($_POST['local_list'] as $val){
329           if (!in_array ($val, $this->gosaMailAlternateAddress) &&
330               $val != $this->mail){
332             $this->addForwarder($val);
333             $this->is_modified= TRUE;
334           }
335         }
336       }
337       $this->forward_dialog= FALSE;
338       $this->dialog= FALSE;
339     }
341     /* Add forward email addresses */
342     if (isset($_POST['add_forwarder'])){
343       if ($_POST['forward_address'] != ""){
345         /* Valid email address specified? */
346         $address= $_POST['forward_address'];
347         $valid= FALSE;
348         if (!is_email($address)){
349           if (!is_email($address, TRUE)){
350             if ($this->is_template){
351               $valid= TRUE;
352             } else {
353               print_red (_("You're trying to add an invalid email address to the list of forwarders."));
354             }
355           }
356         } elseif ($address == $this->mail
357             || in_array($address, $this->gosaMailAlternateAddress)) {
359           print_red (_("Adding your one of your own addresses to the forwarders makes no sense."));
361         } else {
362           $valid= TRUE;
363         }
365         if ($valid){
366           /* Add it */
367           if (chkacl ($this->acl, "gosaMailForwardingAddress") == ""){
368             $this->addForwarder ($address);
369             $this->is_modified= TRUE;
370           }
372         }
373       }
374     }
376     /* Delete forward email addresses */
377     if (isset($_POST['delete_forwarder'])){
378       if (count($_POST['forwarder_list']) 
379           && chkacl ($this->acl, "gosaMailForwardingAddress") == ""){
381         $this->delForwarder ($_POST['forwarder_list']);
382       }
383     }
385     
386     /* Alternate address handling */
388     /* Add alternate email addresses */
389     if (isset($_POST['add_alternate'])){
390       if ($_POST['alternate_address'] != "" &&
391           chkacl ($this->acl, "gosaMailAlternateAddress") == ""){
393         $valid= FALSE;
394         if (!is_email($_POST['alternate_address'])){
395           if ($this->is_template){
396             if (!(is_email($_POST['alternate_address'], TRUE))){
397               print_red (_("You're trying to add an invalid email address to the list of alternate addresses."));
398             } else {
399               $valid= TRUE;
400             }
401           } else {
402             print_red (_("You're trying to add an invalid email address to the list of alternate addresses."));
403           }
405         } else {
406           $valid= TRUE;
407         }
409         if ($valid && ($user= $this->addAlternate ($_POST['alternate_address'])) != ""){
410           $ui= get_userinfo();
411           if ($user != $ui->username && !$this->is_template){
412             print_red (_("The address you're trying to add is already used by user")." '$user'.");
413           }
414         }
415       }
416     }
418     /* Delete alternate email addresses */
419     if (isset($_POST['delete_alternate']) && isset ($_POST['alternates_list'])){
420       if (count($_POST['alternates_list']) &&
421           chkacl ($this->acl, "gosaMailAlternateAddress") == ""){
423         $this->delAlternate ($_POST['alternates_list']);
424       }
425     }
427   
428     /* Vocation message */
429   
430     /* Import vacation message? */
431     if (isset($_POST["import_vacation"]) && isset($this->vacation[$_POST["vacation_template"]])){
432       $contents= "";
433       $lines= file($_POST["vacation_template"]);
434       foreach ($lines as $line){
435         if (!preg_match('/^DESC:/', $line)){
436           $contents.= $line;
437         }
438       }
440       /* Replace attributes */
441       $attrs= $this->parent->by_object['user']->attributes;
442       foreach ($attrs as $val){
443         
444         if(preg_match("/dateOfBirth/",$val)){
445           if($this->parent->by_object['user']->use_dob){
446             $contents= preg_replace("/%$val/",date("Y-d-m",$this->parent->by_object['user']->dateOfBirth),$contents);
447           }
448         }else {
449           $contents= preg_replace("/%$val/",
450               $this->parent->by_object['user']->$val, $contents);
451         }
452       }
454       /* Save message */
455       $this->gosaVacationMessage= htmlspecialchars($contents);
456     }
458   
459     /* Display forward dialog if requested above */
461     /* Show forward add dialog */
462     if ($this->forward_dialog){
463       $ldap= $this->config->get_ldap_link();
465       /* Save data */
466       $mailfilter= get_global("mailfilter");
467       foreach( array("depselect", "muser", "regex") as $type){
468         if (isset($_POST[$type])){
469           $mailfilter[$type]= $_POST[$type];
470         }
471       }
472       if (isset($_GET['search'])){
473         $s= mb_substr($_GET['search'], 0, 1, "UTF8")."*";
474         if ($s == "**"){
475           $s= "*";
476         }
477         $mailfilter['regex']= $s;
478       }
479       register_global("mailfilter", $mailfilter);
481       /* Get actual list */
482       $mailusers= array ();
483       if ($mailfilter['regex'] != '*' && $mailfilter['regex'] != ""){
484         $regex= $mailfilter['regex'];
485         $filter= "(|(mail=$regex)(gosaMailAlternateAddress=$regex))";
486       } else {
487         $filter= "";
488       }
489       if ($mailfilter['muser'] != ""){
490         $user= $mailfilter['muser'];
491         $filter= "$filter(|(uid=$user)(cn=$user)(givenName=$user)(sn=$user))";
492       }
494       /* Add already present people to the filter */
495       $exclude= "";
496       foreach ($this->gosaMailForwardingAddress as $mail){
497         $exclude.= "(mail=$mail)";
498       }
499       if ($exclude != ""){
500         $filter.= "(!(|$exclude))";
501       }
503       $acl= array($this->config->current['BASE'] => ":all");
504       $res= get_list("(&(objectClass=gosaMailAccount)$filter)", $acl, $mailfilter['depselect'], 
505                      array("sn", "mail", "givenName"), GL_SIZELIMIT | GL_SUBSEARCH);
506       $ldap->cd($mailfilter['depselect']);
507       $ldap->search ("(&(objectClass=gosaMailAccount)$filter)", array("sn", "mail", "givenName"));
508       error_reporting (0);
509       while ($attrs= $ldap->fetch()){
510         if(preg_match('/%/', $attrs['mail'][0])){
511           continue;
512         }
513         $name= $this->make_name($attrs);
514         $mailusers[$attrs['mail'][0]]= $name."&lt;".
515           $attrs['mail'][0]."&gt;";
516       }
517       error_reporting (E_ALL);
518       natcasesort ($mailusers);
519       reset ($mailusers);
521       /* Show dialog */
522       $smarty->assign("search_image", get_template_path('images/search.png'));
523       $smarty->assign("usearch_image", get_template_path('images/search_user.png'));
524       $smarty->assign("tree_image", get_template_path('images/tree.png'));
525       $smarty->assign("infoimage", get_template_path('images/info.png'));
526       $smarty->assign("launchimage", get_template_path('images/small_filter.png'));
527       $smarty->assign("mailusers", $mailusers);
528       if (isset($_POST['depselect'])){
529         $smarty->assign("depselect", $_POST['depselect']);
530       }
531       $smarty->assign("deplist", $this->config->idepartments);
532       $smarty->assign("apply", apply_filter());
533       $smarty->assign("alphabet", generate_alphabet());
534       $smarty->assign("hint", print_sizelimit_warning());
535       foreach( array("depselect", "muser", "regex") as $type){
536         $smarty->assign("$type", $mailfilter[$type]);
537       }
538       $smarty->assign("hint", print_sizelimit_warning());
540       $display.= $smarty->fetch (get_template_path('mail_locals.tpl', TRUE, dirname(__FILE__)));
541       return ($display);
542     }
544     /* Display mail account tab */
545     if($this->gosaVacationStart ==0){
546       $date= getdate(time());
547       $this->gosaVacationStart = time();
548     }else{
549       $date= getdate($this->gosaVacationStart);
550     }
551     $days= array();
552     for($d= 1; $d<32; $d++){
553       $days[$d]= $d;
554     }
555     $years= array();
556     for($y= $date['year']-10; $y<$date['year']+10; $y++){
557       $years[]= $y;
558     }
559     $months= array(_("January"), _("February"), _("March"), _("April"),
560         _("May"), _("June"), _("July"), _("August"), _("September"),
561         _("October"), _("November"), _("December"));
562     $smarty->assign("start_day", $date["mday"]);
563     $smarty->assign("days", $days);
564     $smarty->assign("months", $months);
565     $smarty->assign("start_month", $date["mon"]-1);
566     $smarty->assign("years", $years);
567     $smarty->assign("start_year", $date["year"]);
569     if($this->gosaVacationStop ==0){
570       $date= getdate(time());
571       $date["mday"]++;
572       $this->gosaVacationStop = time() + (60*60*24);
573     }else{
574       $date= getdate($this->gosaVacationStop);
575     }
576     $smarty->assign("end_day", $date["mday"]);
577     $smarty->assign("end_month", $date["mon"]-1);
578     $smarty->assign("end_year", $date["year"]);
580     $smarty->assign("mailServers", $mailserver);
581     foreach(array(
582           "gosaMailServer", 
583           "gosaMailQuota", 
584           "perms", 
585           "mail",
586           "gosaMailAlternateAddress", 
587           "gosaMailForwardingAddress",
589           // gosaMailDeliveryMode Flags 
590           "drop_own_mails",                       // No local delivery 
591           "gosaMailMaxSize",                      // Enable - Drop mails > max size
592           "gosaSpamSortLevel", "gosaSpamMailbox", // Enable - Spam sort options
593           "gosaVacationMessage",                  // Enable - Vacation message      
594           "gosaVacationStart",
595           "gosaVacationStop",
596           "custom_sieve",                         // Use custom sieve script
597           "only_local"                            // Send/receive local mails 
598                                         ) as $val){
599       if(isset($this->$val)){
600         $smarty->assign("$val", $this->$val);
601       }
602       $smarty->assign("$val"."ACL", chkacl($this->acl, "$val"));
603     }
605     $smarty->assign("sieveManagementACL", chkacl($this->acl,"sieveManagement"));
607     if (preg_match('/V/', $this->gosaMailDeliveryMode)){
608       $smarty->assign('rangeEnabled', "");
609     } else {
610       $smarty->assign('rangeEnabled', "disabled");
611     }
613     if (is_numeric($this->gosaMailQuota) && $this->gosaMailQuota != 0){
614       $smarty->assign("quotausage", progressbar(round(($this->quotaUsage * 100)/ $this->gosaMailQuota),100,15,true));
615       $smarty->assign("quotadefined", "true");
616     } else {
617       $smarty->assign("quotadefined", "false");
618     }
620     /* Disable mail field if needed */
621     $method= new $this->method($this->config);
622     if ($method->uattrib == "mail" && $this->initially_was_account){
623       $smarty->assign("mailACL", "disabled");
624     }
627     if (!preg_match("/L/", $this->gosaMailDeliveryMode)) {
628       $smarty->assign("drop_own_mails", "checked");
629     } else {
630       $smarty->assign("drop_own_mails", "");
631     }
633     $types = array(
634           "V"=>"use_vacation",
635           "S"=>"use_spam_filter",
636           "R"=>"use_mailsize_limit",
637           "I"=>"only_local",
638           "C"=>"own_script");
640     /* Fill checkboxes */
641     foreach($types as $option => $varname){
642       if (preg_match("/".$option."/", $this->gosaMailDeliveryMode)) {
643         $smarty->assign($varname, "checked");
644       } else {
645         $smarty->assign($varname, "");
646       }
647     }
648     
649     if (preg_match("/V/", $this->gosaMailDeliveryMode)) {
650       $smarty->assign("use_vacation", "checked");
651     } else {
652       $smarty->assign("use_vacation", "");
653     }
654     if (preg_match("/S/", $this->gosaMailDeliveryMode)) {
655       $smarty->assign("use_spam_filter", "checked");
656     } else {
657       $smarty->assign("use_spam_filter", "");
658     }
659     if (preg_match("/R/", $this->gosaMailDeliveryMode)) {
660       $smarty->assign("use_mailsize_limit", "checked");
661     } else {
662       $smarty->assign("use_mailsize_limit", "");
663     }
664     if (preg_match("/I/", $this->gosaMailDeliveryMode)) {
665       $smarty->assign("only_local", "checked");
666     } else {
667       $smarty->assign("only_local", "");
668     }
669     if (preg_match("/C/", $this->gosaMailDeliveryMode)) {
670       $smarty->assign("own_script", "checked");
671     } else {
672       $smarty->assign("own_script", "");
673     }
675     /* Have vacation templates? */
676     $smarty->assign("template", "");
677     if (count($this->vacation)){
678       $smarty->assign("show_templates", "true");
679       $smarty->assign("vacationtemplates", $this->vacation);
680       if (isset($_POST['vacation_template'])){
681         $smarty->assign("template", $_POST['vacation_template']);
682       }
683     } else {
684       $smarty->assign("show_templates", "false");
685     }
687     /* Fill spam selector */
688     $spamlevel= array();
689     for ($i= 0; $i<21; $i++){
690       $spamlevel[]= $i;
691     }
692     $smarty->assign("spamlevel", $spamlevel);
693     $smarty->assign("spambox", $this->mailboxList);
694     $smarty->assign("custom_sieveACL", chkacl($this->acl, "custom_sieve"));     
695     $smarty->assign("only_localACL", chkacl($this->acl, "only_local")); 
697     $display.= $smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
698     return ($display);
699   }
701   /* check if we have some delegations configured, those delegations must be removed first */
702   function accountDelegationsConfigured()
703   { 
704     /* We are in administrational edit mode.
705         Check tab configurations directly */
706     if(isset($this->attrs)){
707       $checkArray  = array("kolabInvitationPolicy","unrestrictedMailSize", "calFBURL","kolabDelegate","kolabFreeBusyFuture");
708       foreach($checkArray as $index){
709         if(isset($this->attrs[$index])){
710            return(true);
711         }
712       }
713     }
714     if(isset($this->parent->by_object['connectivity']->plugin['kolabAccount'])){
715       if($this->parent->by_object['connectivity']->plugin['kolabAccount']->is_account){
716         return(true);
717       }
718     }
719     return(false); 
720   }
723   /* remove object from parent */
724   function remove_from_parent()
725   {
726     /* Cancel if there's nothing to do here */
727     if (!$this->initially_was_account){
728       return;
729     }
730     
731     /* include global link_info */
732     $ldap= $this->config->get_ldap_link();
734     /* Remove and write to LDAP */
735     plugin::remove_from_parent();
737     /* Zero arrays */
738     $this->attrs['gosaMailAlternateAddress']= array();
739     $this->attrs['gosaMailForwardingAddress']= array();
741     /* Adapt attributes if needed */
742     $method= new $this->method($this->config);
743     $method->fixAttributesOnRemove($this);
745     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,$this->attributes, "Save");
746     $ldap->cd($this->dn);
747     $this->cleanup();
748     $ldap->modify ($this->attrs); 
750     show_ldap_error($ldap->get_error(), _("Removing mail account failed"));
752     /* Connect to IMAP server for account deletion */
753     if ($this->gosaMailServer != ""){
754       $method= new $this->method($this->config);
755       $id= $method->uattrib;
756       if ($method->connect($this->gosaMailServer)){
758         /* Remove account from IMAP server */
759         $method->deleteMailbox($this->folder_prefix.$this->$id);
760         $method->disconnect();
761       }
762     }
764     /* Optionally execute a command after we're done */
765     $this->handle_post_events("remove", array('uid'=> $this->uid));
766   }
769   /* Save data to object */
770   function save_object()
771   {
772     if (isset($_POST['mailTab'])){
773       /* Save ldap attributes */
774       plugin::save_object();
776       /* Assemble mail delivery mode
777          The mode field in ldap consists of values between braces, this must
778          be called when 'mail' is set, because checkboxes may not be set when
779          we're in some other dialog.
781          Example for gosaMailDeliveryMode [LR        ]
782          L: Local delivery
783          R: Reject when exceeding mailsize limit
784          S: Use spam filter
785          V: Use vacation message
786          C: Use custm sieve script
787          I: Only insider delivery */
789       $tmp= "";
790       $Flags = array(
791                      "R"  => array("ACL" => "gosaMailMaxSize",    "POST" => "use_mailsize_limit"),
792                      "V"  => array("ACL" => "gosaVacationMessage","POST" => "use_vacation"),
793                      "C"  => array("ACL" => "custom_sieve",       "POST" => "own_script"),
794                      "I"  => array("ACL" => "only_local",         "POST" => "only_local"));
796       /* Check acls and set new value if allowed. 
797          If we do not have permission to change the value 
798           check for the old value and use this */
799       foreach($Flags as $flag => $val){
800         $acl  = $val['ACL'];
801         $post = $val['POST'];
802         if(chkacl($this->acl,$acl) ==""){
803           if (isset($_POST[$post])){
804             $tmp.= $flag;
805           }
806         }else{
807           if(preg_match("/".$flag."/",$this->gosaMailDeliveryMode)){
808             $tmp.= $flag ;
809           }
810         }
811       }
813       /* ! Inverse flag handling for drop_own_mails */
814       if(chkacl($this->acl,"drop_own_mails") == ""){
815         if (!isset($_POST['drop_own_mails'])){
816           $tmp.= "L";
817         }
818       }else{
819         if(preg_match("/L/",$this->gosaMailDeliveryMode)){
820           $tmp.= "L" ;
821         }
822       }
824       /* If one of these acls are given, we are allowed to enable disable the the spam settings */
825       if(chkacl($this->acl,"gosaSpamMailbox") == "" || chkacl($this->acl,"gosaSpamSortLevel") ==""){
826         if (isset($_POST["use_spam_filter"])){
827           $tmp.= "S";
828         }
829       }else{
830         if(preg_match("/S/",$this->gosaMailDeliveryMode)){
831           $tmp.= "S" ;
832         }
833       }
834       
835       /* Check if something has changed an assign new gosaMailDeliveryMode */
836       $tmp= "[$tmp]";
837       if ($this->gosaMailDeliveryMode != $tmp){
838         $this->is_modified= TRUE;
839       }
840       $this->gosaMailDeliveryMode= $tmp;
841     }
843   }
846   /* Save data to LDAP, depending on is_account we save or delete */
847   function save()
848   {
849     $ldap= $this->config->get_ldap_link();
851     /* Call parents save to prepare $this->attrs */
852     plugin::save();
854     /* Save arrays */
855     $this->attrs['gosaMailAlternateAddress']= $this->gosaMailAlternateAddress;
856     $this->attrs['gosaMailForwardingAddress']= $this->gosaMailForwardingAddress;
858     /* Adapt attributes if needed */
859     $method= new $this->method($this->config);
860     $id= $method->uattrib;
862     $method->fixAttributesOnStore($this);
864     /* Remove Mailquota if = "" or "0"  */
865     if((isset($this->attrs['gosaMailQuota']))&&(!$this->attrs['gosaMailQuota'])) {
866       $this->attrs['gosaMailQuota']=0;
867     }
869     if(empty($this->attrs['gosaSpamMailbox'])){
870       unset($this->attrs['gosaSpamMailbox']);
871     }
873     $this->attrs['mail'] = strtolower($this->attrs['mail']); 
875     /* Remove attributes - if not needed */
876     if (!preg_match('/V/', $this->gosaMailDeliveryMode)){
877       unset($this->attrs['gosaVacationStart']);
878       unset($this->attrs['gosaVacationStop']);
879     }
881     /* Save data to LDAP */
882     $ldap->cd($this->dn);
883     $this->cleanup();
884     $ldap->modify ($this->attrs); 
886     show_ldap_error($ldap->get_error(), _("Saving mail account failed"));
888     /* Only do IMAP actions if we are not a template */
889     if (!$this->is_template){
891       if ($method->connect($this->gosaMailServer)){
892         $method->updateMailbox($this->folder_prefix.$this->$id);
893         
894         $method->setQuota($this->folder_prefix.$this->$id, $this->gosaMailQuota);
895         $method->disconnect();
897         /* Only talk with sieve if the mail account already exists */
898         if($this->initially_was_account){
899          
900           /* Write sieve information only if not in C mode */
901           if (!is_integer(strpos($this->gosaMailDeliveryMode, "C"))){
902             $method->configureFilter($this->$id,
903                 $this->gosaMailDeliveryMode,
904                 $this->mail,
905                 $this->gosaMailAlternateAddress,
906                 $this->gosaMailMaxSize,
907                 $this->gosaSpamMailbox,
908                 $this->gosaSpamSortLevel,
909                 $this->gosaVacationMessage);
910             $this->is_modified = TRUE;
911           }else{
912             $this->sieve_management->save();
913           }
914         }
915       }
916     }
918     /* Optionally execute a command after we're done */
919     if ($this->initially_was_account == $this->is_account){
920       if ($this->is_modified){
921         $this->handle_post_events("modify", array('uid'=> $this->uid));
922       }
923     } else {
924       $this->handle_post_events("add", array('uid'=>$this->uid));
925     }
927   }
930   /* Check formular input */
931   function check()
932   {
933     if(!$this->is_account) return(array());
935     $ldap= $this->config->get_ldap_link();
937     /* Call common method to give check the hook */
938     $message= plugin::check();
940     if(empty($this->gosaMailServer)){
941       $message[]= _("There is no valid mailserver specified, please add one in the system setup.");
942     }
944     /* must: mail */
945     if ($this->mail == ""){
946       $message[]= _("The required field 'Primary address' is not set.");
947     }
948     if ($this->is_template){
949       if (!is_email($this->mail, TRUE)){
950         $message[]= _("Please enter a valid email address in 'Primary address' field.");
951       }
952     } else {
953       if (!is_email($this->mail)){
954         $message[]= _("Please enter a valid email address in 'Primary address' field.");
955       }
956     }
957     $ldap->cd($this->config->current['BASE']);
958     $ldap->search ("(&(!(objectClass=gosaUserTemplate))(objectClass=gosaMailAccount)(|(mail=".$this->mail.")(gosaMailAlternateAddress=".$this->mail."))(!(uid=".$this->uid."))(!(cn=".$this->uid.")))", array("uid"));
959     if ($ldap->count() != 0){
960       $message[]= _("The primary address you've entered is already in use.");
961     }
963     /* Check quota */
964     if ($this->gosaMailQuota != '' && chkacl ($this->acl, "gosaMailQuota") == ""){
965       if (!is_numeric($this->gosaMailQuota)) {
966         $message[]= _("Value in 'Quota size' is not valid.");
967       } else {
968         $this->gosaMailQuota= (int) $this->gosaMailQuota;
969       }
970     }
972     /* Check rejectsize for integer */
973     if ($this->gosaMailMaxSize != '' && chkacl ($this->acl, "gosaMailQuota") == ""){
974       if (!is_numeric($this->gosaMailMaxSize)){
975         $message[]= _("Please specify a vaild mail size for mails to be rejected.");
976       } else {
977         $this->gosaMailMaxSize= (int) $this->gosaMailMaxSize;
978       }
979     }
981     /* Need gosaMailMaxSize if use_mailsize_limit is checked */
982     if (is_integer(strpos($this->gosaMailDeliveryMode, "R")) && 
983         $this->gosaMailMaxSize == ""){
985       $message[]= _("You need to set the maximum mail size in order to reject anything.");
986     }
988     if((preg_match("/S/", $this->gosaMailDeliveryMode))&&(empty($this->gosaSpamMailbox))) {
989       $message[]= _("You specified Spam settings, but there is no Folder specified.");
990     }
992     if (preg_match('/V/', $this->gosaMailDeliveryMode) && $this->gosaVacationStart >= $this->gosaVacationStop){
993       $message[]= _("Time interval to show vacation message is not valid.");
994     }
996     return ($message);
997   }
1000   /* Adapt from template, using 'dn' */
1001   function adapt_from_template($dn)
1002   {
1003     plugin::adapt_from_template($dn);
1005     foreach (array("gosaMailAlternateAddress", "gosaMailForwardingAddress") as $val){
1006       $this->$val= array();
1007       if (isset($this->attrs["$val"]["count"])){
1008         for ($i= 0; $i<$this->attrs["$val"]["count"]; $i++){
1009           $value= $this->attrs["$val"][$i];
1010           foreach (array("sn", "givenName", "uid") as $repl){
1011             if (preg_match("/%$repl/i", $value)){
1012               $value= preg_replace ("/%$repl/i", $this->parent->$repl, $value);
1013             }
1014           }
1015           array_push($this->$val, strtolower(rewrite($value)));
1016         }
1017       }
1018     }
1019     $this->mail= strtolower(rewrite($this->mail));
1020   }
1023   /* Add entry to forwarder list */
1024   function addForwarder($address)
1025   {
1026     $this->gosaMailForwardingAddress[]= $address;
1027     $this->gosaMailForwardingAddress= array_unique ($this->gosaMailForwardingAddress);
1028     sort ($this->gosaMailForwardingAddress);
1029     reset ($this->gosaMailForwardingAddress);
1030     $this->is_modified= TRUE;
1031   }
1034   /* Remove list of addresses from forwarder list */
1035   function delForwarder($addresses)
1036   {
1037     $this->gosaMailForwardingAddress= array_remove_entries ($addresses, $this->gosaMailForwardingAddress);
1038     $this->is_modified= TRUE;
1039   }
1042   /* Add given mail address to the list of alternate adresses , 
1043       check if this mal address is used, skip adding in this case */
1044   function addAlternate($address)
1045   {
1046     $ldap= $this->config->get_ldap_link();
1047     $address= strtolower($address);
1048       
1049     /* Is this address already assigned in LDAP? */
1050     $ldap->cd ($this->config->current['BASE']);
1051     $ldap->search ("(&(!(objectClass=gosaUserTemplate))(objectClass=gosaMailAccount)(|(mail=$address)"."(gosaMailAlternateAddress=$address)))", array("uid"));
1053     if ($ldap->count() > 0){
1054       $attrs= $ldap->fetch ();
1055       return ($attrs["uid"][0]);
1056     }
1058     /* Add to list of alternates */
1059     if (!in_array($address, $this->gosaMailAlternateAddress)){
1060       $this->gosaMailAlternateAddress[]= $address;
1061       $this->is_modified= TRUE;
1062     }
1064     sort ($this->gosaMailAlternateAddress);
1065     reset ($this->gosaMailAlternateAddress);
1066     return ("");
1067   }
1070   function delAlternate($addresses)
1071   {
1072     $this->gosaMailAlternateAddress= array_remove_entries ($addresses,
1073                                                            $this->gosaMailAlternateAddress);
1074     $this->is_modified= TRUE;
1075   }
1077   function make_name($attrs)
1078   {
1079     $name= "";
1080     if (isset($attrs['sn'][0])){
1081       $name= $attrs['sn'][0];
1082     }
1083     if (isset($attrs['givenName'][0])){
1084       if ($name != ""){
1085         $name.= ", ".$attrs['givenName'][0];
1086       } else {
1087         $name.= $attrs['givenName'][0];
1088       }
1089     }
1090     if ($name != ""){
1091       $name.= " ";
1092     }
1094     return ($name);
1095   }
1097   
1098   /* Create the mail part for the copy & paste dialog */
1099   function getCopyDialog()
1100   {
1101     if(!$this->is_account) return("");
1102     $smarty = get_smarty();
1103     $smarty->assign("mail",$this->mail); 
1104     $smarty->assign("gosaMailAlternateAddress",$this->gosaMailAlternateAddress);
1105     $smarty->assign("gosaMailForwardingAddress",$this->gosaMailForwardingAddress);
1106     $str = $smarty->fetch(get_template_path("copypaste.tpl",TRUE, dirname(__FILE__)));
1108     $ret = array();
1109     $ret['status'] = "";
1110     $ret['string'] = $str;
1111     return($ret);
1112   }
1114   function saveCopyDialog()
1115   {
1116     if(!$this->is_account) return;  
1118     /* Execute to save mailAlternateAddress && gosaMailForwardingAddress */
1119     $this->execute();
1120     
1121     if(isset($_POST['mail'])){
1122       $this->mail = $_POST['mail'];
1123     }
1124   }
1126    
1127   function PrepareForCopyPaste($source)
1128   {
1129     plugin::PrepareForCopyPaste($source);
1131     /* Reset alternate mail addresses */
1132     $this->gosaMailAlternateAddress = array();    
1133   }
1136   function allow_remove()
1137   {
1138     if (isset($this->config->current['MAILMETHOD'])){
1139       $method= $this->config->current['MAILMETHOD'];
1140       if(preg_match("/olab/i",$method)){
1141         $ldap = $this->config->get_ldap_link();
1142         $ldap->cd($this->config->current['BASE']);
1143         $ldap->cat($this->dn);
1144         if($ldap->count()){
1145           $attrs = $ldap->fetch();
1146           if(isset($attrs['kolabDeleteFlag'])){ 
1147             return(_("Waiting for kolab to remove mail properties."));
1148           }elseif(in_array("gosaMailAccount",$attrs['objectClass'])){
1149             return(_("Please remove the mail account first, to allow kolab to call its remove methods."));
1150           }
1151         }
1152       }
1153     }
1154   }
1157 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1158 ?>