Code

Avoid PHP warnings in mailAccount
[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 = array();
442       $obj = NULL;
443       if(isset($this->parent->by_object['user'])){
444         $attrs  = $this->parent->by_object['user']->attributes;
445         $obj    = $this->parent->by_object['user'];
446       }else{
447         $obj    = new user($this->config,$this->dn);
448         $attrs  = $obj->attributes;
449       }
451       if($obj){
452         foreach ($attrs as $val){
453           if(preg_match("/dateOfBirth/",$val)){
454             if($obj->use_dob){
455               $contents= preg_replace("/%$val/",date("Y-d-m",$obj->dateOfBirth),$contents);
456             }
457           }else {
458             $contents= preg_replace("/%$val/",
459                 $obj->$val, $contents);
460           }
462           /* Replace vacation start and end time */
463           if(preg_match("/%start/",$contents)){
464             $contents = preg_replace("/%start/",date("d.m.Y",$this->gosaVacationStart),$contents);
465           }
466           if(preg_match("/%end/",$contents)){
467             $contents = preg_replace("/%end/",date("d.m.Y",$this->gosaVacationStop),$contents);
468           }
469         }
470       }
472       /* Save message */
473       $this->gosaVacationMessage= htmlspecialchars($contents);
474     }
476   
477     /* Display forward dialog if requested above */
479     /* Show forward add dialog */
480     if ($this->forward_dialog){
481       $ldap= $this->config->get_ldap_link();
483       /* Save data */
484       $mailfilter= get_global("mailfilter");
485       foreach( array("depselect", "muser", "regex") as $type){
486         if (isset($_POST[$type])){
487           $mailfilter[$type]= $_POST[$type];
488         }
489       }
490       if (isset($_GET['search'])){
491         $s= mb_substr($_GET['search'], 0, 1, "UTF8")."*";
492         if ($s == "**"){
493           $s= "*";
494         }
495         $mailfilter['regex']= $s;
496       }
497       register_global("mailfilter", $mailfilter);
499       /* Get actual list */
500       $mailusers= array ();
501       if ($mailfilter['regex'] != '*' && $mailfilter['regex'] != ""){
502         $regex= $mailfilter['regex'];
503         $filter= "(|(mail=$regex)(gosaMailAlternateAddress=$regex))";
504       } else {
505         $filter= "";
506       }
507       if ($mailfilter['muser'] != ""){
508         $user= $mailfilter['muser'];
509         $filter= "$filter(|(uid=$user)(cn=$user)(givenName=$user)(sn=$user))";
510       }
512       /* Add already present people to the filter */
513       $exclude= "";
514       foreach ($this->gosaMailForwardingAddress as $mail){
515         $exclude.= "(mail=$mail)";
516       }
517       if ($exclude != ""){
518         $filter.= "(!(|$exclude))";
519       }
521       $acl= array($this->config->current['BASE'] => ":all");
522       $res= get_list("(&(objectClass=gosaMailAccount)$filter)", $acl, $mailfilter['depselect'], 
523                      array("sn", "mail", "givenName"), GL_SIZELIMIT | GL_SUBSEARCH);
524       $ldap->cd($mailfilter['depselect']);
525       $ldap->search ("(&(objectClass=gosaMailAccount)$filter)", array("sn", "mail", "givenName"));
526       error_reporting (0);
527       while ($attrs= $ldap->fetch()){
528         if(preg_match('/%/', $attrs['mail'][0])){
529           continue;
530         }
531         $name= $this->make_name($attrs);
532         $mailusers[$attrs['mail'][0]]= $name."&lt;".
533           $attrs['mail'][0]."&gt;";
534       }
535       error_reporting (E_ALL);
536       natcasesort ($mailusers);
537       reset ($mailusers);
539       /* Show dialog */
540       $smarty->assign("search_image", get_template_path('images/search.png'));
541       $smarty->assign("usearch_image", get_template_path('images/search_user.png'));
542       $smarty->assign("tree_image", get_template_path('images/tree.png'));
543       $smarty->assign("infoimage", get_template_path('images/info.png'));
544       $smarty->assign("launchimage", get_template_path('images/small_filter.png'));
545       $smarty->assign("mailusers", $mailusers);
546       if (isset($_POST['depselect'])){
547         $smarty->assign("depselect", $_POST['depselect']);
548       }
549       $smarty->assign("deplist", $this->config->idepartments);
550       $smarty->assign("apply", apply_filter());
551       $smarty->assign("alphabet", generate_alphabet());
552       $smarty->assign("hint", print_sizelimit_warning());
553       foreach( array("depselect", "muser", "regex") as $type){
554         $smarty->assign("$type", $mailfilter[$type]);
555       }
556       $smarty->assign("hint", print_sizelimit_warning());
558       $display.= $smarty->fetch (get_template_path('mail_locals.tpl', TRUE, dirname(__FILE__)));
559       return ($display);
560     }
562     /* Display mail account tab */
563     if($this->gosaVacationStart ==0){
564       $date= getdate(time());
565       $this->gosaVacationStart = time();
566     }else{
567       $date= getdate($this->gosaVacationStart);
568     }
569     $days= array();
570     for($d= 1; $d<32; $d++){
571       $days[$d]= $d;
572     }
573     $years= array();
574     for($y= $date['year']-10; $y<$date['year']+10; $y++){
575       $years[]= $y;
576     }
577     $months= array(_("January"), _("February"), _("March"), _("April"),
578         _("May"), _("June"), _("July"), _("August"), _("September"),
579         _("October"), _("November"), _("December"));
580     $smarty->assign("start_day", $date["mday"]);
581     $smarty->assign("days", $days);
582     $smarty->assign("months", $months);
583     $smarty->assign("start_month", $date["mon"]-1);
584     $smarty->assign("years", $years);
585     $smarty->assign("start_year", $date["year"]);
587     if($this->gosaVacationStop ==0){
588       $date= getdate(time());
589       $date["mday"]++;
590       $this->gosaVacationStop = time() + (60*60*24);
591     }else{
592       $date= getdate($this->gosaVacationStop);
593     }
594     $smarty->assign("end_day", $date["mday"]);
595     $smarty->assign("end_month", $date["mon"]-1);
596     $smarty->assign("end_year", $date["year"]);
598     $smarty->assign("mailServers", $mailserver);
599     foreach(array(
600           "gosaMailServer", 
601           "gosaMailQuota", 
602           "perms", 
603           "mail",
604           "gosaMailAlternateAddress", 
605           "gosaMailForwardingAddress",
607           // gosaMailDeliveryMode Flags 
608           "drop_own_mails",                       // No local delivery 
609           "gosaMailMaxSize",                      // Enable - Drop mails > max size
610           "gosaSpamSortLevel", "gosaSpamMailbox", // Enable - Spam sort options
611           "gosaVacationMessage",                  // Enable - Vacation message      
612           "gosaVacationStart",
613           "gosaVacationStop",
614           "custom_sieve",                         // Use custom sieve script
615           "only_local"                            // Send/receive local mails 
616                                         ) as $val){
617       if(isset($this->$val)){
618         $smarty->assign("$val", $this->$val);
619       }
620       $smarty->assign("$val"."ACL", chkacl($this->acl, "$val"));
621     }
623     $smarty->assign("sieveManagementACL", chkacl($this->acl,"sieveManagement"));
625     if (preg_match('/V/', $this->gosaMailDeliveryMode)){
626       $smarty->assign('rangeEnabled', "");
627     } else {
628       $smarty->assign('rangeEnabled', "disabled");
629     }
631     if (is_numeric($this->gosaMailQuota) && $this->gosaMailQuota != 0){
632       $smarty->assign("quotausage", progressbar(round(($this->quotaUsage * 100)/ $this->gosaMailQuota),100,15,true));
633       $smarty->assign("quotadefined", "true");
634     } else {
635       $smarty->assign("quotadefined", "false");
636     }
638     /* Disable mail field if needed */
639     $method= new $this->method($this->config);
640     if ($method->uattrib == "mail" && $this->initially_was_account){
641       $smarty->assign("mailACL", "disabled");
642     }
645     if (!preg_match("/L/", $this->gosaMailDeliveryMode)) {
646       $smarty->assign("drop_own_mails", "checked");
647     } else {
648       $smarty->assign("drop_own_mails", "");
649     }
651     $types = array(
652           "V"=>"use_vacation",
653           "S"=>"use_spam_filter",
654           "R"=>"use_mailsize_limit",
655           "I"=>"only_local",
656           "C"=>"own_script");
658     /* Fill checkboxes */
659     foreach($types as $option => $varname){
660       if (preg_match("/".$option."/", $this->gosaMailDeliveryMode)) {
661         $smarty->assign($varname, "checked");
662       } else {
663         $smarty->assign($varname, "");
664       }
665     }
666     
667     if (preg_match("/V/", $this->gosaMailDeliveryMode)) {
668       $smarty->assign("use_vacation", "checked");
669     } else {
670       $smarty->assign("use_vacation", "");
671     }
672     if (preg_match("/S/", $this->gosaMailDeliveryMode)) {
673       $smarty->assign("use_spam_filter", "checked");
674     } else {
675       $smarty->assign("use_spam_filter", "");
676     }
677     if (preg_match("/R/", $this->gosaMailDeliveryMode)) {
678       $smarty->assign("use_mailsize_limit", "checked");
679     } else {
680       $smarty->assign("use_mailsize_limit", "");
681     }
682     if (preg_match("/I/", $this->gosaMailDeliveryMode)) {
683       $smarty->assign("only_local", "checked");
684     } else {
685       $smarty->assign("only_local", "");
686     }
687     if (preg_match("/C/", $this->gosaMailDeliveryMode)) {
688       $smarty->assign("own_script", "checked");
689     } else {
690       $smarty->assign("own_script", "");
691     }
693     /* Have vacation templates? */
694     $smarty->assign("template", "");
695     if (count($this->vacation)){
696       $smarty->assign("show_templates", "true");
697       $smarty->assign("vacationtemplates", $this->vacation);
698       if (isset($_POST['vacation_template'])){
699         $smarty->assign("template", $_POST['vacation_template']);
700       }
701     } else {
702       $smarty->assign("show_templates", "false");
703     }
705     /* Fill spam selector */
706     $spamlevel= array();
707     for ($i= 0; $i<21; $i++){
708       $spamlevel[]= $i;
709     }
710     $smarty->assign("spamlevel", $spamlevel);
711     $smarty->assign("spambox", $this->mailboxList);
712     $smarty->assign("custom_sieveACL", chkacl($this->acl, "custom_sieve"));     
713     $smarty->assign("only_localACL", chkacl($this->acl, "only_local")); 
715     $display.= $smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
716     return ($display);
717   }
719   /* check if we have some delegations configured, those delegations must be removed first */
720   function accountDelegationsConfigured()
721   { 
722     /* We are in administrational edit mode.
723         Check tab configurations directly */
724     if(isset($this->attrs)){
725       $checkArray  = array("kolabInvitationPolicy","unrestrictedMailSize", "calFBURL","kolabDelegate","kolabFreeBusyFuture");
726       foreach($checkArray as $index){
727         if(isset($this->attrs[$index])){
728            return(true);
729         }
730       }
731     }
732     if(isset($this->parent->by_object['connectivity']->plugin['kolabAccount'])){
733       if($this->parent->by_object['connectivity']->plugin['kolabAccount']->is_account){
734         return(true);
735       }
736     }
737     return(false); 
738   }
741   /* remove object from parent */
742   function remove_from_parent()
743   {
744     /* Cancel if there's nothing to do here */
745     if (!$this->initially_was_account){
746       return;
747     }
748     
749     /* include global link_info */
750     $ldap= $this->config->get_ldap_link();
752     /* Remove and write to LDAP */
753     plugin::remove_from_parent();
755     /* Zero arrays */
756     $this->attrs['gosaMailAlternateAddress']= array();
757     $this->attrs['gosaMailForwardingAddress']= array();
759     /* Adapt attributes if needed */
760     $method= new $this->method($this->config);
761     $method->fixAttributesOnRemove($this);
763     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,$this->attributes, "Save");
764     $ldap->cd($this->dn);
765     $this->cleanup();
766     $ldap->modify ($this->attrs); 
768     show_ldap_error($ldap->get_error(), _("Removing mail account failed"));
770     /* Connect to IMAP server for account deletion */
771     if ($this->gosaMailServer != ""){
772       $method= new $this->method($this->config);
773       $id= $method->uattrib;
774       if ($method->connect($this->gosaMailServer)){
776         /* Remove account from IMAP server */
777         $method->deleteMailbox($this->folder_prefix.$this->$id);
778         $method->disconnect();
779       }
780     }
782     /* Update shared folder membership, ACL may need to be updated */
783     $this->updateSharedFolder(); 
785     /* Optionally execute a command after we're done */
786     $this->handle_post_events("remove", array('uid'=> $this->uid));
787   }
790   /* Save data to object */
791   function save_object()
792   {
793     if (isset($_POST['mailTab'])){
794       /* Save ldap attributes */
795       plugin::save_object();
797       /* Assemble mail delivery mode
798          The mode field in ldap consists of values between braces, this must
799          be called when 'mail' is set, because checkboxes may not be set when
800          we're in some other dialog.
802          Example for gosaMailDeliveryMode [LR        ]
803          L: Local delivery
804          R: Reject when exceeding mailsize limit
805          S: Use spam filter
806          V: Use vacation message
807          C: Use custm sieve script
808          I: Only insider delivery */
810       $tmp= "";
811       $Flags = array(
812                      "R"  => array("ACL" => "gosaMailMaxSize",    "POST" => "use_mailsize_limit"),
813                      "V"  => array("ACL" => "gosaVacationMessage","POST" => "use_vacation"),
814                      "C"  => array("ACL" => "custom_sieve",       "POST" => "own_script"),
815                      "I"  => array("ACL" => "only_local",         "POST" => "only_local"));
817       /* Check acls and set new value if allowed. 
818          If we do not have permission to change the value 
819           check for the old value and use this */
820       foreach($Flags as $flag => $val){
821         $acl  = $val['ACL'];
822         $post = $val['POST'];
823         if(chkacl($this->acl,$acl) ==""){
824           if (isset($_POST[$post])){
825             $tmp.= $flag;
826           }
827         }else{
828           if(preg_match("/".$flag."/",$this->gosaMailDeliveryMode)){
829             $tmp.= $flag ;
830           }
831         }
832       }
834       /* ! Inverse flag handling for drop_own_mails */
835       if(chkacl($this->acl,"drop_own_mails") == ""){
836         if (!isset($_POST['drop_own_mails'])){
837           $tmp.= "L";
838         }
839       }else{
840         if(preg_match("/L/",$this->gosaMailDeliveryMode)){
841           $tmp.= "L" ;
842         }
843       }
845       /* If one of these acls are given, we are allowed to enable disable the the spam settings */
846       if(chkacl($this->acl,"gosaSpamMailbox") == "" || chkacl($this->acl,"gosaSpamSortLevel") ==""){
847         if (isset($_POST["use_spam_filter"])){
848           $tmp.= "S";
849         }
850       }else{
851         if(preg_match("/S/",$this->gosaMailDeliveryMode)){
852           $tmp.= "S" ;
853         }
854       }
855       
856       /* Check if something has changed an assign new gosaMailDeliveryMode */
857       $tmp= "[$tmp]";
858       if ($this->gosaMailDeliveryMode != $tmp){
859         $this->is_modified= TRUE;
860       }
861       $this->gosaMailDeliveryMode= $tmp;
863       if(chkacl($this->acl,"gosaVacationMessage") == "" && preg_match("/V/",$this->gosaMailDeliveryMode)){
864         if(isset($_POST['gosaVacationStart'])){
865           $this->gosaVacationStart = $_POST['gosaVacationStart'];
866         }
867         if(isset($_POST['gosaVacationStop'])){
868           $this->gosaVacationStop = $_POST['gosaVacationStop'];
869         }
870       }
871     }
872   }
875   /* Save data to LDAP, depending on is_account we save or delete */
876   function save()
877   {
878     $ldap= $this->config->get_ldap_link();
880     /* Call parents save to prepare $this->attrs */
881     plugin::save();
883     /* Save arrays */
884     $this->attrs['gosaMailAlternateAddress']= $this->gosaMailAlternateAddress;
885     $this->attrs['gosaMailForwardingAddress']= $this->gosaMailForwardingAddress;
887     /* Adapt attributes if needed */
888     $method= new $this->method($this->config);
889     $id= $method->uattrib;
891     $method->fixAttributesOnStore($this);
893     /* Remove Mailquota if = "" or "0"  */
894     if((isset($this->attrs['gosaMailQuota']))&&(!$this->attrs['gosaMailQuota'])) {
895       $this->attrs['gosaMailQuota']=0;
896     }
898     if(empty($this->attrs['gosaSpamMailbox'])){
899       unset($this->attrs['gosaSpamMailbox']);
900     }
902     $this->attrs['mail'] = strtolower($this->attrs['mail']); 
904     /* Remove attributes - if not needed */
905     if (!preg_match('/V/', $this->gosaMailDeliveryMode)){
906       unset($this->attrs['gosaVacationStart']);
907       unset($this->attrs['gosaVacationStop']);
908     }
910     /* Save data to LDAP */
911     $ldap->cd($this->dn);
912     $this->cleanup();
913     $ldap->modify ($this->attrs); 
915     show_ldap_error($ldap->get_error(), _("Saving mail account failed"));
917     /* Only do IMAP actions if we are not a template */
918     if (!$this->is_template){
920       if ($method->connect($this->gosaMailServer)){
921         $method->updateMailbox($this->folder_prefix.$this->$id);
922         
923         $method->setQuota($this->folder_prefix.$this->$id, $this->gosaMailQuota);
924         $method->disconnect();
926         /* Only talk with sieve if the mail account already exists */
927         if($this->initially_was_account){
928          
929           /* Write sieve information only if not in C mode */
930           if (!is_integer(strpos($this->gosaMailDeliveryMode, "C"))){
931             $method->configureFilter($this->$id,
932                 $this->gosaMailDeliveryMode,
933                 $this->mail,
934                 $this->gosaMailAlternateAddress,
935                 $this->gosaMailMaxSize,
936                 $this->gosaSpamMailbox,
937                 $this->gosaSpamSortLevel,
938                 $this->gosaVacationMessage);
939             $this->is_modified = TRUE;
940           }else{
941             $this->sieve_management->save();
942           }
943         }
944       }
945     }
947     /* Optionally execute a command after we're done */
948     if ($this->initially_was_account == $this->is_account){
949       if ($this->is_modified){
950         $this->handle_post_events("modify", array('uid'=> $this->uid));
951       }
952     } else {
953       $this->handle_post_events("add", array('uid'=>$this->uid));
954     }
956     $this->updateSharedFolder();
957   }
960   /* Check formular input */
961   function check()
962   {
963     if(!$this->is_account) return(array());
965     $ldap= $this->config->get_ldap_link();
967     /* Call common method to give check the hook */
968     $message= plugin::check();
970     if(empty($this->gosaMailServer)){
971       $message[]= _("There is no valid mailserver specified, please add one in the system setup.");
972     }
974     /* must: mail */
975     if ($this->mail == ""){
976       $message[]= _("The required field 'Primary address' is not set.");
977     }
978     if ($this->is_template){
979       if (!is_email($this->mail, TRUE)){
980         $message[]= _("Please enter a valid email address in 'Primary address' field.");
981       }
982     } else {
983       if (!is_email($this->mail)){
984         $message[]= _("Please enter a valid email address in 'Primary address' field.");
985       }
986     }
987     $ldap->cd($this->config->current['BASE']);
988     $ldap->search ("(&(!(objectClass=gosaUserTemplate))(objectClass=gosaMailAccount)(|(mail=".$this->mail.")(gosaMailAlternateAddress=".$this->mail."))(!(uid=".$this->uid."))(!(cn=".$this->uid.")))", array("uid"));
989     if ($ldap->count() != 0){
990       $message[]= _("The primary address you've entered is already in use.");
991     }
993     /* Check quota */
994     if ($this->gosaMailQuota != '' && chkacl ($this->acl, "gosaMailQuota") == ""){
995       if (!is_numeric($this->gosaMailQuota)) {
996         $message[]= _("Value in 'Quota size' is not valid.");
997       } else {
998         $this->gosaMailQuota= (int) $this->gosaMailQuota;
999       }
1000     }
1002     /* Check rejectsize for integer */
1003     if ($this->gosaMailMaxSize != '' && chkacl ($this->acl, "gosaMailQuota") == ""){
1004       if (!is_numeric($this->gosaMailMaxSize)){
1005         $message[]= _("Please specify a vaild mail size for mails to be rejected.");
1006       } else {
1007         $this->gosaMailMaxSize= (int) $this->gosaMailMaxSize;
1008       }
1009     }
1011     /* Need gosaMailMaxSize if use_mailsize_limit is checked */
1012     if (is_integer(strpos($this->gosaMailDeliveryMode, "R")) && 
1013         $this->gosaMailMaxSize == ""){
1015       $message[]= _("You need to set the maximum mail size in order to reject anything.");
1016     }
1018     if((preg_match("/S/", $this->gosaMailDeliveryMode))&&(empty($this->gosaSpamMailbox))) {
1019       $message[]= _("You specified Spam settings, but there is no Folder specified.");
1020     }
1022     if (preg_match('/V/', $this->gosaMailDeliveryMode) && $this->gosaVacationStart > $this->gosaVacationStop){
1023       $message[]= _("Time interval to show vacation message is not valid.");
1024     }
1026     return ($message);
1027   }
1030   /* Adapt from template, using 'dn' */
1031   function adapt_from_template($dn)
1032   {
1033     plugin::adapt_from_template($dn);
1035     foreach (array("gosaMailAlternateAddress", "gosaMailForwardingAddress") as $val){
1036       $this->$val= array();
1037       if (isset($this->attrs["$val"]["count"])){
1038         for ($i= 0; $i<$this->attrs["$val"]["count"]; $i++){
1039           $value= $this->attrs["$val"][$i];
1040           foreach (array("sn", "givenName", "uid") as $repl){
1041             if (preg_match("/%$repl/i", $value)){
1042               $value= preg_replace ("/%$repl/i", $this->parent->$repl, $value);
1043             }
1044           }
1045           array_push($this->$val, strtolower(rewrite($value)));
1046         }
1047       }
1048     }
1049     $this->mail= strtolower(rewrite($this->mail));
1050   }
1053   /* Add entry to forwarder list */
1054   function addForwarder($address)
1055   {
1056     $this->gosaMailForwardingAddress[]= $address;
1057     $this->gosaMailForwardingAddress= array_unique ($this->gosaMailForwardingAddress);
1058     sort ($this->gosaMailForwardingAddress);
1059     reset ($this->gosaMailForwardingAddress);
1060     $this->is_modified= TRUE;
1061   }
1064   /* Remove list of addresses from forwarder list */
1065   function delForwarder($addresses)
1066   {
1067     $this->gosaMailForwardingAddress= array_remove_entries ($addresses, $this->gosaMailForwardingAddress);
1068     $this->is_modified= TRUE;
1069   }
1072   /* Add given mail address to the list of alternate adresses , 
1073       check if this mal address is used, skip adding in this case */
1074   function addAlternate($address)
1075   {
1076     $ldap= $this->config->get_ldap_link();
1077     $address= strtolower($address);
1078       
1079     /* Is this address already assigned in LDAP? */
1080     $ldap->cd ($this->config->current['BASE']);
1081     $ldap->search ("(&(!(objectClass=gosaUserTemplate))(objectClass=gosaMailAccount)(|(mail=$address)"."(gosaMailAlternateAddress=$address)))", array("uid"));
1083     if ($ldap->count() > 0){
1084       $attrs= $ldap->fetch ();
1085       return ($attrs["uid"][0]);
1086     }
1088     /* Add to list of alternates */
1089     if (!in_array($address, $this->gosaMailAlternateAddress)){
1090       $this->gosaMailAlternateAddress[]= $address;
1091       $this->is_modified= TRUE;
1092     }
1094     sort ($this->gosaMailAlternateAddress);
1095     reset ($this->gosaMailAlternateAddress);
1096     return ("");
1097   }
1100   function delAlternate($addresses)
1101   {
1102     $this->gosaMailAlternateAddress= array_remove_entries ($addresses,
1103                                                            $this->gosaMailAlternateAddress);
1104     $this->is_modified= TRUE;
1105   }
1107   function make_name($attrs)
1108   {
1109     $name= "";
1110     if (isset($attrs['sn'][0])){
1111       $name= $attrs['sn'][0];
1112     }
1113     if (isset($attrs['givenName'][0])){
1114       if ($name != ""){
1115         $name.= ", ".$attrs['givenName'][0];
1116       } else {
1117         $name.= $attrs['givenName'][0];
1118       }
1119     }
1120     if ($name != ""){
1121       $name.= " ";
1122     }
1124     return ($name);
1125   }
1127   
1128   /* Create the mail part for the copy & paste dialog */
1129   function getCopyDialog()
1130   {
1131     if(!$this->is_account) return("");
1132     $smarty = get_smarty();
1133     $smarty->assign("mail",$this->mail); 
1134     $smarty->assign("gosaMailAlternateAddress",$this->gosaMailAlternateAddress);
1135     $smarty->assign("gosaMailForwardingAddress",$this->gosaMailForwardingAddress);
1136     $str = $smarty->fetch(get_template_path("copypaste.tpl",TRUE, dirname(__FILE__)));
1138     $ret = array();
1139     $ret['status'] = "";
1140     $ret['string'] = $str;
1141     return($ret);
1142   }
1144   function saveCopyDialog()
1145   {
1146     if(!$this->is_account) return;  
1148     /* Execute to save mailAlternateAddress && gosaMailForwardingAddress */
1149     $this->execute();
1150     
1151     if(isset($_POST['mail'])){
1152       $this->mail = $_POST['mail'];
1153     }
1154   }
1156    
1157   function PrepareForCopyPaste($source)
1158   {
1159     plugin::PrepareForCopyPaste($source);
1161     /* Reset alternate mail addresses */
1162     $this->gosaMailAlternateAddress = array();    
1163   }
1166   function allow_remove()
1167   {
1168     if (isset($this->config->current['MAILMETHOD'])){
1169       $method= $this->config->current['MAILMETHOD'];
1170       if(preg_match("/olab/i",$method)){
1171         $ldap = $this->config->get_ldap_link();
1172         $ldap->cd($this->config->current['BASE']);
1173         $ldap->cat($this->dn);
1174         if($ldap->count()){
1175           $attrs = $ldap->fetch();
1176           if(isset($attrs['kolabDeleteFlag'])){ 
1177             return(_("Waiting for kolab to remove mail properties."));
1178           }elseif(in_array("gosaMailAccount",$attrs['objectClass'])){
1179             return(_("Please remove the mail account first, to allow kolab to call its remove methods."));
1180           }
1181         }
1182       }
1183     }
1184   }
1186   /* Upated shared folder ACLs 
1187    */
1188   function updateSharedFolder()
1189   {
1190     $ldap = $this->config->get_ldap_link();
1191     $ldap->cd($this->config->current['BASE']);
1192     $ldap->search("(&(objectClass=posixGroup)(objectClass=gosaMailAccount)(memberUid=".$this->uid."))",array('dn','cn'));
1193     if(class_exists("grouptabs")){
1194       while($attrs = $ldap->fetch()){
1195         $tmp = new grouptabs($this->config, $this->config->data['TABS']['GROUPTABS'], $attrs['dn']);
1196         if(isset($tmp->by_object['mailgroup'])){
1197           $tmp->by_object['mailgroup']->members= $tmp->by_object['group']->memberUid;
1198           if(!$this->is_account){
1199             $tmp->by_object['mailgroup']->removeUserAcl($this->uid);
1200             $tmp->by_object['mailgroup']->removeUserAcl($this->mail);
1201           }
1202           $tmp->by_object['mailgroup']->save();
1203         }
1204       }
1205     } 
1206   }
1209 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1210 ?>