Code

Update shared folder when a user updates his mailAccount plugin.
[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     /* Update shared folder membership, ACL may need to be updated */
765     $this->updateSharedFolder(); 
767     /* Optionally execute a command after we're done */
768     $this->handle_post_events("remove", array('uid'=> $this->uid));
769   }
772   /* Save data to object */
773   function save_object()
774   {
775     if (isset($_POST['mailTab'])){
776       /* Save ldap attributes */
777       plugin::save_object();
779       /* Assemble mail delivery mode
780          The mode field in ldap consists of values between braces, this must
781          be called when 'mail' is set, because checkboxes may not be set when
782          we're in some other dialog.
784          Example for gosaMailDeliveryMode [LR        ]
785          L: Local delivery
786          R: Reject when exceeding mailsize limit
787          S: Use spam filter
788          V: Use vacation message
789          C: Use custm sieve script
790          I: Only insider delivery */
792       $tmp= "";
793       $Flags = array(
794                      "R"  => array("ACL" => "gosaMailMaxSize",    "POST" => "use_mailsize_limit"),
795                      "V"  => array("ACL" => "gosaVacationMessage","POST" => "use_vacation"),
796                      "C"  => array("ACL" => "custom_sieve",       "POST" => "own_script"),
797                      "I"  => array("ACL" => "only_local",         "POST" => "only_local"));
799       /* Check acls and set new value if allowed. 
800          If we do not have permission to change the value 
801           check for the old value and use this */
802       foreach($Flags as $flag => $val){
803         $acl  = $val['ACL'];
804         $post = $val['POST'];
805         if(chkacl($this->acl,$acl) ==""){
806           if (isset($_POST[$post])){
807             $tmp.= $flag;
808           }
809         }else{
810           if(preg_match("/".$flag."/",$this->gosaMailDeliveryMode)){
811             $tmp.= $flag ;
812           }
813         }
814       }
816       /* ! Inverse flag handling for drop_own_mails */
817       if(chkacl($this->acl,"drop_own_mails") == ""){
818         if (!isset($_POST['drop_own_mails'])){
819           $tmp.= "L";
820         }
821       }else{
822         if(preg_match("/L/",$this->gosaMailDeliveryMode)){
823           $tmp.= "L" ;
824         }
825       }
827       /* If one of these acls are given, we are allowed to enable disable the the spam settings */
828       if(chkacl($this->acl,"gosaSpamMailbox") == "" || chkacl($this->acl,"gosaSpamSortLevel") ==""){
829         if (isset($_POST["use_spam_filter"])){
830           $tmp.= "S";
831         }
832       }else{
833         if(preg_match("/S/",$this->gosaMailDeliveryMode)){
834           $tmp.= "S" ;
835         }
836       }
837       
838       /* Check if something has changed an assign new gosaMailDeliveryMode */
839       $tmp= "[$tmp]";
840       if ($this->gosaMailDeliveryMode != $tmp){
841         $this->is_modified= TRUE;
842       }
843       $this->gosaMailDeliveryMode= $tmp;
844     }
846   }
849   /* Save data to LDAP, depending on is_account we save or delete */
850   function save()
851   {
852     $ldap= $this->config->get_ldap_link();
854     /* Call parents save to prepare $this->attrs */
855     plugin::save();
857     /* Save arrays */
858     $this->attrs['gosaMailAlternateAddress']= $this->gosaMailAlternateAddress;
859     $this->attrs['gosaMailForwardingAddress']= $this->gosaMailForwardingAddress;
861     /* Adapt attributes if needed */
862     $method= new $this->method($this->config);
863     $id= $method->uattrib;
865     $method->fixAttributesOnStore($this);
867     /* Remove Mailquota if = "" or "0"  */
868     if((isset($this->attrs['gosaMailQuota']))&&(!$this->attrs['gosaMailQuota'])) {
869       $this->attrs['gosaMailQuota']=0;
870     }
872     if(empty($this->attrs['gosaSpamMailbox'])){
873       unset($this->attrs['gosaSpamMailbox']);
874     }
876     $this->attrs['mail'] = strtolower($this->attrs['mail']); 
878     /* Remove attributes - if not needed */
879     if (!preg_match('/V/', $this->gosaMailDeliveryMode)){
880       unset($this->attrs['gosaVacationStart']);
881       unset($this->attrs['gosaVacationStop']);
882     }
884     /* Save data to LDAP */
885     $ldap->cd($this->dn);
886     $this->cleanup();
887     $ldap->modify ($this->attrs); 
889     show_ldap_error($ldap->get_error(), _("Saving mail account failed"));
891     /* Only do IMAP actions if we are not a template */
892     if (!$this->is_template){
894       if ($method->connect($this->gosaMailServer)){
895         $method->updateMailbox($this->folder_prefix.$this->$id);
896         
897         $method->setQuota($this->folder_prefix.$this->$id, $this->gosaMailQuota);
898         $method->disconnect();
900         /* Only talk with sieve if the mail account already exists */
901         if($this->initially_was_account){
902          
903           /* Write sieve information only if not in C mode */
904           if (!is_integer(strpos($this->gosaMailDeliveryMode, "C"))){
905             $method->configureFilter($this->$id,
906                 $this->gosaMailDeliveryMode,
907                 $this->mail,
908                 $this->gosaMailAlternateAddress,
909                 $this->gosaMailMaxSize,
910                 $this->gosaSpamMailbox,
911                 $this->gosaSpamSortLevel,
912                 $this->gosaVacationMessage);
913             $this->is_modified = TRUE;
914           }else{
915             $this->sieve_management->save();
916           }
917         }
918       }
919     }
921     /* Optionally execute a command after we're done */
922     if ($this->initially_was_account == $this->is_account){
923       if ($this->is_modified){
924         $this->handle_post_events("modify", array('uid'=> $this->uid));
925       }
926     } else {
927       $this->handle_post_events("add", array('uid'=>$this->uid));
928     }
930     $this->updateSharedFolder();
931   }
934   /* Check formular input */
935   function check()
936   {
937     if(!$this->is_account) return(array());
939     $ldap= $this->config->get_ldap_link();
941     /* Call common method to give check the hook */
942     $message= plugin::check();
944     if(empty($this->gosaMailServer)){
945       $message[]= _("There is no valid mailserver specified, please add one in the system setup.");
946     }
948     /* must: mail */
949     if ($this->mail == ""){
950       $message[]= _("The required field 'Primary address' is not set.");
951     }
952     if ($this->is_template){
953       if (!is_email($this->mail, TRUE)){
954         $message[]= _("Please enter a valid email address in 'Primary address' field.");
955       }
956     } else {
957       if (!is_email($this->mail)){
958         $message[]= _("Please enter a valid email address in 'Primary address' field.");
959       }
960     }
961     $ldap->cd($this->config->current['BASE']);
962     $ldap->search ("(&(!(objectClass=gosaUserTemplate))(objectClass=gosaMailAccount)(|(mail=".$this->mail.")(gosaMailAlternateAddress=".$this->mail."))(!(uid=".$this->uid."))(!(cn=".$this->uid.")))", array("uid"));
963     if ($ldap->count() != 0){
964       $message[]= _("The primary address you've entered is already in use.");
965     }
967     /* Check quota */
968     if ($this->gosaMailQuota != '' && chkacl ($this->acl, "gosaMailQuota") == ""){
969       if (!is_numeric($this->gosaMailQuota)) {
970         $message[]= _("Value in 'Quota size' is not valid.");
971       } else {
972         $this->gosaMailQuota= (int) $this->gosaMailQuota;
973       }
974     }
976     /* Check rejectsize for integer */
977     if ($this->gosaMailMaxSize != '' && chkacl ($this->acl, "gosaMailQuota") == ""){
978       if (!is_numeric($this->gosaMailMaxSize)){
979         $message[]= _("Please specify a vaild mail size for mails to be rejected.");
980       } else {
981         $this->gosaMailMaxSize= (int) $this->gosaMailMaxSize;
982       }
983     }
985     /* Need gosaMailMaxSize if use_mailsize_limit is checked */
986     if (is_integer(strpos($this->gosaMailDeliveryMode, "R")) && 
987         $this->gosaMailMaxSize == ""){
989       $message[]= _("You need to set the maximum mail size in order to reject anything.");
990     }
992     if((preg_match("/S/", $this->gosaMailDeliveryMode))&&(empty($this->gosaSpamMailbox))) {
993       $message[]= _("You specified Spam settings, but there is no Folder specified.");
994     }
996     if (preg_match('/V/', $this->gosaMailDeliveryMode) && $this->gosaVacationStart >= $this->gosaVacationStop){
997       $message[]= _("Time interval to show vacation message is not valid.");
998     }
1000     return ($message);
1001   }
1004   /* Adapt from template, using 'dn' */
1005   function adapt_from_template($dn)
1006   {
1007     plugin::adapt_from_template($dn);
1009     foreach (array("gosaMailAlternateAddress", "gosaMailForwardingAddress") as $val){
1010       $this->$val= array();
1011       if (isset($this->attrs["$val"]["count"])){
1012         for ($i= 0; $i<$this->attrs["$val"]["count"]; $i++){
1013           $value= $this->attrs["$val"][$i];
1014           foreach (array("sn", "givenName", "uid") as $repl){
1015             if (preg_match("/%$repl/i", $value)){
1016               $value= preg_replace ("/%$repl/i", $this->parent->$repl, $value);
1017             }
1018           }
1019           array_push($this->$val, strtolower(rewrite($value)));
1020         }
1021       }
1022     }
1023     $this->mail= strtolower(rewrite($this->mail));
1024   }
1027   /* Add entry to forwarder list */
1028   function addForwarder($address)
1029   {
1030     $this->gosaMailForwardingAddress[]= $address;
1031     $this->gosaMailForwardingAddress= array_unique ($this->gosaMailForwardingAddress);
1032     sort ($this->gosaMailForwardingAddress);
1033     reset ($this->gosaMailForwardingAddress);
1034     $this->is_modified= TRUE;
1035   }
1038   /* Remove list of addresses from forwarder list */
1039   function delForwarder($addresses)
1040   {
1041     $this->gosaMailForwardingAddress= array_remove_entries ($addresses, $this->gosaMailForwardingAddress);
1042     $this->is_modified= TRUE;
1043   }
1046   /* Add given mail address to the list of alternate adresses , 
1047       check if this mal address is used, skip adding in this case */
1048   function addAlternate($address)
1049   {
1050     $ldap= $this->config->get_ldap_link();
1051     $address= strtolower($address);
1052       
1053     /* Is this address already assigned in LDAP? */
1054     $ldap->cd ($this->config->current['BASE']);
1055     $ldap->search ("(&(!(objectClass=gosaUserTemplate))(objectClass=gosaMailAccount)(|(mail=$address)"."(gosaMailAlternateAddress=$address)))", array("uid"));
1057     if ($ldap->count() > 0){
1058       $attrs= $ldap->fetch ();
1059       return ($attrs["uid"][0]);
1060     }
1062     /* Add to list of alternates */
1063     if (!in_array($address, $this->gosaMailAlternateAddress)){
1064       $this->gosaMailAlternateAddress[]= $address;
1065       $this->is_modified= TRUE;
1066     }
1068     sort ($this->gosaMailAlternateAddress);
1069     reset ($this->gosaMailAlternateAddress);
1070     return ("");
1071   }
1074   function delAlternate($addresses)
1075   {
1076     $this->gosaMailAlternateAddress= array_remove_entries ($addresses,
1077                                                            $this->gosaMailAlternateAddress);
1078     $this->is_modified= TRUE;
1079   }
1081   function make_name($attrs)
1082   {
1083     $name= "";
1084     if (isset($attrs['sn'][0])){
1085       $name= $attrs['sn'][0];
1086     }
1087     if (isset($attrs['givenName'][0])){
1088       if ($name != ""){
1089         $name.= ", ".$attrs['givenName'][0];
1090       } else {
1091         $name.= $attrs['givenName'][0];
1092       }
1093     }
1094     if ($name != ""){
1095       $name.= " ";
1096     }
1098     return ($name);
1099   }
1101   
1102   /* Create the mail part for the copy & paste dialog */
1103   function getCopyDialog()
1104   {
1105     if(!$this->is_account) return("");
1106     $smarty = get_smarty();
1107     $smarty->assign("mail",$this->mail); 
1108     $smarty->assign("gosaMailAlternateAddress",$this->gosaMailAlternateAddress);
1109     $smarty->assign("gosaMailForwardingAddress",$this->gosaMailForwardingAddress);
1110     $str = $smarty->fetch(get_template_path("copypaste.tpl",TRUE, dirname(__FILE__)));
1112     $ret = array();
1113     $ret['status'] = "";
1114     $ret['string'] = $str;
1115     return($ret);
1116   }
1118   function saveCopyDialog()
1119   {
1120     if(!$this->is_account) return;  
1122     /* Execute to save mailAlternateAddress && gosaMailForwardingAddress */
1123     $this->execute();
1124     
1125     if(isset($_POST['mail'])){
1126       $this->mail = $_POST['mail'];
1127     }
1128   }
1130    
1131   function PrepareForCopyPaste($source)
1132   {
1133     plugin::PrepareForCopyPaste($source);
1135     /* Reset alternate mail addresses */
1136     $this->gosaMailAlternateAddress = array();    
1137   }
1140   function allow_remove()
1141   {
1142     if (isset($this->config->current['MAILMETHOD'])){
1143       $method= $this->config->current['MAILMETHOD'];
1144       if(preg_match("/olab/i",$method)){
1145         $ldap = $this->config->get_ldap_link();
1146         $ldap->cd($this->config->current['BASE']);
1147         $ldap->cat($this->dn);
1148         if($ldap->count()){
1149           $attrs = $ldap->fetch();
1150           if(isset($attrs['kolabDeleteFlag'])){ 
1151             return(_("Waiting for kolab to remove mail properties."));
1152           }elseif(in_array("gosaMailAccount",$attrs['objectClass'])){
1153             return(_("Please remove the mail account first, to allow kolab to call its remove methods."));
1154           }
1155         }
1156       }
1157     }
1158   }
1160   /* Upated shared folder ACLs 
1161    */
1162   function updateSharedFolder()
1163   {
1164     $ldap = $this->config->get_ldap_link();
1165     $ldap->cd($this->config->current['BASE']);
1166     $ldap->search("(&(objectClass=posixGroup)(objectClass=gosaMailAccount)(memberUid=".$this->uid."))",array('dn','cn'));
1167     if(class_exists("grouptabs")){
1168       while($attrs = $ldap->fetch()){
1169         $tmp = new grouptabs($this->config, $this->config->data['TABS']['GROUPTABS'], $attrs['dn']);
1170         if(isset($tmp->by_object['mailgroup'])){
1171           $tmp->by_object['mailgroup']->members= $tmp->by_object['group']->memberUid;
1172           if(!$this->is_account){
1173             $tmp->by_object['mailgroup']->removeUserAcl($this->uid);
1174             $tmp->by_object['mailgroup']->removeUserAcl($this->mail);
1175           }
1176           $tmp->by_object['mailgroup']->save();
1177         }
1178       }
1179     } 
1180   }
1183 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1184 ?>