Code

Add vacation message stuff
[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 ("class_sieve.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                  = NULL;
37   var $gosaVacationStop                   = NULL;
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");
63   /* constructor, if 'dn' is set, the node loads the given
64      'dn' from LDAP */
65   function mailAccount ($config, $dn= NULL, $parent= NULL)
66   {
67     /* Load bases attributes */
68     plugin::plugin($config, $dn, $parent);
70     if(isset($this->attrs['uid'])){
71       $this->uid = $this->attrs['uid'][0];
72     }
73  
74     if(is_array($this->gosaMailServer) && isset($this->gosaMailServer[0])){
75       $this->gosaMailServer = $this->gosaMailServer[0];
76     }
78     /* Save initial account state */
79     $this->initially_was_account= $this->is_account;
81     /*  Set mailMethod to the one defined in gosa.conf */
82     if (isset($this->config->current['MAILMETHOD'])){
83       $method= $this->config->current['MAILMETHOD'];
84       if (class_exists("mailMethod$method")){
85         $this->method= "mailMethod$method";
86       } else {
87         print_red(sprintf(_("There is no mail method '%s' specified in your gosa.conf available."), $method));
88       }
89     }
91     /* Create the account prefix  user. user/ 
92        Preset folder prefix. Will change it later to respect
93        altnamespace. */
94     if (isset($this->config->current['CYRUSUNIXSTYLE']) && $this->config->current['CYRUSUNIXSTYLE'] == "true"){
95       $this->folder_prefix= "user/";
96     }elseif (isset($this->config->data['MAIN']['CYRUSUNIXSTYLE']) && $this->config->data['MAIN']['CYRUSUNIXSTYLE'] == "true"){
97       $this->folder_prefix= "user/";
98     } else {
99       $this->folder_prefix= "user.";
100     }
101     
102     /* This is not a new account, parse additional attributes */
103     if (($dn != NULL) && ($dn != "new") && $this->is_account){
105       /* Load attributes containing arrays */
106       foreach (array("gosaMailAlternateAddress", "gosaMailForwardingAddress") as $val){
107         $this->$val= array();
108         if (isset($this->attrs["$val"]["count"])){
109           for ($i= 0; $i<$this->attrs["$val"]["count"]; $i++){
110             array_push($this->$val, $this->attrs["$val"][$i]);
111           }
112         }
113       }
116       /* Only do IMAP actions if gosaMailServer attribute is set */
117       if (isset ($this->attrs["gosaMailServer"][0])){
119         $method = new $this->method($this->config);
120         $id     = $method->uattrib;
122         /* Adapt attributes if needed */
123         $method->fixAttributesOnLoad($this);
125         /* FixAttributesOnLoad possibly creates an array out of gosaMailServer.
126             If the mail tab wasn't opened once before saving, the account can't be saved */
127         if(is_array($this->gosaMailServer)){
128           $this->gosaMailServer = $this->gosaMailServer[0];
129         }
131         if ($method->connect($this->attrs["gosaMailServer"][0])){
133           /* Update quota values */
134           $quota= $method->getQuota($this->folder_prefix.$this->$id);
135          
136           if($quota){
137             if ($quota['gosaMailQuota'] == 2147483647){
138               $this->quotaUsage     = "";
139               $this->gosaMailQuota  = "";
140             } else {
141               $this->quotaUsage     = $quota['quotaUsage'];
142               $this->gosaMailQuota  = $quota['gosaMailQuota'];
143             }
144           }else{
145             $this->quotaUsage     = "";
146             $this->gosaMailQuota  = "";
147 //            print_red(sprintf(_("Can't get quota information for '%s'."),$this->folder_prefix.$this->$id));
148           }
150           /* Get mailboxes / folder like INBOX ..*/
151           $this->mailboxList= $method->getMailboxList($this->folder_prefix.$this->$id,$this->$id);
152           
153           $method->disconnect();
154         }else{
155           /* Could not connect to ldap.
156            */
157           if (isset($this->attrs['gosaMailQuota'][0])){
158             $this->gosaMailQuota = $this->attrs['gosaMailQuota'][0];
159           }
160         }
161       }
162     }
165     /* Get vacation message */
167     /* Fill vacation array */
168     $this->vacation= array();
169     if (isset($this->config->current['VACATIONDIR'])){
170       $dir= $this->config->current['VACATIONDIR'];
171       if (is_dir($dir) && is_readable($dir)){
173         /* Look for files and build the vacation array */
174         $dh= opendir($dir);
175         while ($file = readdir($dh)){
176           $description= $this->parse_vacation("$dir/$file");
177           if ($description != ""){
178             $this->vacation["$dir/$file"]= $description;
179           }
180         }
181         closedir($dh);
182       }
183     }
186   /* Create filter */
188     /* Get global filter config */
189     if (!is_global("mailfilter")){
190       $ui= get_userinfo();
191       $base= get_base_from_people($ui->dn);
192       $mailfilter= array( "depselect"       => $base,
193           "muser"            => "",
194           "regex"           => "*");
195       register_global("mailfilter", $mailfilter);
196     }
197   }
200   function parse_vacation($file)
201   {
202     $desc= "";
204     if (is_file($file)){
205       $fh = fopen($file, "r");
206       $line= fgets($fh, 256);
208       if (!preg_match('/^DESC:/', $line)){
209         print_red (_("No DESC tag in vacation file:")." $file");
210         return $desc;
211       }
212       fclose ($fh);
214       $desc= trim(preg_replace('/^DESC:\s*/', '', $line));
215     }
217     return $desc;
218   }
221   function execute()
222   {
223     /* Call parent execute */
224     plugin::execute();
226     /* Initialise vars */
228     /* Load templating engine */
229     $smarty= get_smarty();
230     $display= "";
232     /* Get available mailserver */
233     $mailserver= array();
234     foreach ($this->config->data['SERVERS']['IMAP'] as $key => $val){
235       $mailserver[]= $key;
236     }
238     /* Handle account state */
240     /* Do we need to flip is_account state? */
241     if (isset($_POST['modify_state'])){
243       /* Onyl change account state if allowed */
244       if($this->is_account && $this->acl == "#all#" && !$this->accountDelegationsConfigured()){
245         $this->is_account= !$this->is_account;
246       }elseif(!$this->is_account && chkacl($this->acl,"create") == ""){
247         $this->is_account= !$this->is_account;
248       }
249     }
251     /* Do we represent a valid account? */
252     if (!$this->is_account && $this->parent == NULL){
253       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
254         _("This account has no mail extensions.")."</b>";
256       $display.= back_to_main();
257       return ($display);
258     }
260     /* Show tab dialog headers */
261     if ($this->parent != NULL){
262       if ($this->is_account){
263         if($this->accountDelegationsConfigured()){
264           $display= $this->show_header(_("Remove mail account"),
265               _("This account can't be removed while there are delegations configured. Remove those delegations first."),TRUE,TRUE);
266         }else{
267           $display= $this->show_header(_("Remove mail account"),
268               _("This account has mail features enabled. You can disable them by clicking below."));
269         }
270       } else {
271         $display= $this->show_header(_("Create mail account"), _("This account has mail features disabled. You can enable them by clicking below."));
272         return ($display);
273       }
274     }
276     /* Forwarder  subdialog */
278     /* Trigger forward add dialog? */
279     if (isset($_POST['add_local_forwarder'])){
280       $this->forward_dialog= TRUE;
281       $this->dialog= TRUE;
282     }
284     /* Cancel forward add dialog? */
285     if (isset($_POST['add_locals_cancel'])){
286       $this->forward_dialog= FALSE;
287       $this->dialog= FALSE;
288     }
290     /* Finished adding of locals? */
291     if (isset($_POST['add_locals_finish'])){
292       if (count ($_POST['local_list']) &&
293           chkacl ($this->acl, "gosaMailForwardingAddress") == ""){
295         /* Walk through list of forwarders, ignore own addresses */
296         foreach ($_POST['local_list'] as $val){
297           if (!in_array ($val, $this->gosaMailAlternateAddress) &&
298               $val != $this->mail){
300             $this->addForwarder($val);
301             $this->is_modified= TRUE;
302           }
303         }
304       }
305       $this->forward_dialog= FALSE;
306       $this->dialog= FALSE;
307     }
309     /* Add forward email addresses */
310     if (isset($_POST['add_forwarder'])){
311       if ($_POST['forward_address'] != ""){
313         /* Valid email address specified? */
314         $address= $_POST['forward_address'];
315         $valid= FALSE;
316         if (!is_email($address)){
317           if (!is_email($address, TRUE)){
318             if ($this->is_template){
319               $valid= TRUE;
320             } else {
321               print_red (_("You're trying to add an invalid email address to the list of forwarders."));
322             }
323           }
324         } elseif ($address == $this->mail
325             || in_array($address, $this->gosaMailAlternateAddress)) {
327           print_red (_("Adding your one of your own addresses to the forwarders makes no sense."));
329         } else {
330           $valid= TRUE;
331         }
333         if ($valid){
334           /* Add it */
335           if (chkacl ($this->acl, "gosaMailForwardingAddress") == ""){
336             $this->addForwarder ($address);
337             $this->is_modified= TRUE;
338           }
340         }
341       }
342     }
344     /* Delete forward email addresses */
345     if (isset($_POST['delete_forwarder'])){
346       if (count($_POST['forwarder_list']) 
347           && chkacl ($this->acl, "gosaMailForwardingAddress") == ""){
349         $this->delForwarder ($_POST['forwarder_list']);
350       }
351     }
353     
354     /* Alternate address handling */
356     /* Add alternate email addresses */
357     if (isset($_POST['add_alternate'])){
358       if ($_POST['alternate_address'] != "" &&
359           chkacl ($this->acl, "gosaMailAlternateAddress") == ""){
361         $valid= FALSE;
362         if (!is_email($_POST['alternate_address'])){
363           if ($this->is_template){
364             if (!(is_email($_POST['alternate_address'], TRUE))){
365               print_red (_("You're trying to add an invalid email address to the list of alternate addresses."));
366             } else {
367               $valid= TRUE;
368             }
369           } else {
370             print_red (_("You're trying to add an invalid email address to the list of alternate addresses."));
371           }
373         } else {
374           $valid= TRUE;
375         }
377         if ($valid && ($user= $this->addAlternate ($_POST['alternate_address'])) != ""){
378           $ui= get_userinfo();
379           if ($user != $ui->username && !$this->is_template){
380             print_red (_("The address you're trying to add is already used by user")." '$user'.");
381           }
382         }
383       }
384     }
386     /* Delete alternate email addresses */
387     if (isset($_POST['delete_alternate']) && isset ($_POST['alternates_list'])){
388       if (count($_POST['alternates_list']) &&
389           chkacl ($this->acl, "gosaMailAlternateAddress") == ""){
391         $this->delAlternate ($_POST['alternates_list']);
392       }
393     }
395   
396     /* Vocation message */
397   
398     /* Import vacation message? */
399     if (isset($_POST["import_vacation"]) && isset($this->vacation[$_POST["vacation_template"]])){
400       $contents= "";
401       $lines= file($_POST["vacation_template"]);
402       foreach ($lines as $line){
403         if (!preg_match('/^DESC:/', $line)){
404           $contents.= $line;
405         }
406       }
408       /* Replace attributes */
409       $attrs= $this->parent->by_object['user']->attributes;
410       foreach ($attrs as $val){
411         
412         if(preg_match("/dateOfBirth/",$val)){
413           if($this->parent->by_object['user']->use_dob){
414             $contents= preg_replace("/%$val/",date("Y-d-m",$this->parent->by_object['user']->dateOfBirth),$contents);
415           }
416         }else {
417           $contents= preg_replace("/%$val/",
418               $this->parent->by_object['user']->$val, $contents);
419         }
420       }
422       /* Save message */
423       $this->gosaVacationMessage= htmlspecialchars($contents);
424     }
426   
427     /* Display forward dialog if requested above */
429     /* Show forward add dialog */
430     if ($this->forward_dialog){
431       $ldap= $this->config->get_ldap_link();
433       /* Save data */
434       $mailfilter= get_global("mailfilter");
435       foreach( array("depselect", "muser", "regex") as $type){
436         if (isset($_POST[$type])){
437           $mailfilter[$type]= $_POST[$type];
438         }
439       }
440       if (isset($_GET['search'])){
441         $s= mb_substr($_GET['search'], 0, 1, "UTF8")."*";
442         if ($s == "**"){
443           $s= "*";
444         }
445         $mailfilter['regex']= $s;
446       }
447       register_global("mailfilter", $mailfilter);
449       /* Get actual list */
450       $mailusers= array ();
451       if ($mailfilter['regex'] != '*' && $mailfilter['regex'] != ""){
452         $regex= $mailfilter['regex'];
453         $filter= "(|(mail=$regex)(gosaMailAlternateAddress=$regex))";
454       } else {
455         $filter= "";
456       }
457       if ($mailfilter['muser'] != ""){
458         $user= $mailfilter['muser'];
459         $filter= "$filter(|(uid=$user)(cn=$user)(givenName=$user)(sn=$user))";
460       }
462       /* Add already present people to the filter */
463       $exclude= "";
464       foreach ($this->gosaMailForwardingAddress as $mail){
465         $exclude.= "(mail=$mail)";
466       }
467       if ($exclude != ""){
468         $filter.= "(!(|$exclude))";
469       }
471       $acl= array($this->config->current['BASE'] => ":all");
472       $res= get_list("(&(objectClass=gosaMailAccount)$filter)", $acl, $mailfilter['depselect'], 
473                      array("sn", "mail", "givenName"), GL_SIZELIMIT | GL_SUBSEARCH);
474       $ldap->cd($mailfilter['depselect']);
475       $ldap->search ("(&(objectClass=gosaMailAccount)$filter)", array("sn", "mail", "givenName"));
476       error_reporting (0);
477       while ($attrs= $ldap->fetch()){
478         if(preg_match('/%/', $attrs['mail'][0])){
479           continue;
480         }
481         $name= $this->make_name($attrs);
482         $mailusers[$attrs['mail'][0]]= $name."&lt;".
483           $attrs['mail'][0]."&gt;";
484       }
485       error_reporting (E_ALL);
486       natcasesort ($mailusers);
487       reset ($mailusers);
489       /* Show dialog */
490       $smarty->assign("search_image", get_template_path('images/search.png'));
491       $smarty->assign("usearch_image", get_template_path('images/search_user.png'));
492       $smarty->assign("tree_image", get_template_path('images/tree.png'));
493       $smarty->assign("infoimage", get_template_path('images/info.png'));
494       $smarty->assign("launchimage", get_template_path('images/small_filter.png'));
495       $smarty->assign("mailusers", $mailusers);
496       if (isset($_POST['depselect'])){
497         $smarty->assign("depselect", $_POST['depselect']);
498       }
499       $smarty->assign("deplist", $this->config->idepartments);
500       $smarty->assign("apply", apply_filter());
501       $smarty->assign("alphabet", generate_alphabet());
502       $smarty->assign("hint", print_sizelimit_warning());
503       foreach( array("depselect", "muser", "regex") as $type){
504         $smarty->assign("$type", $mailfilter[$type]);
505       }
506       $smarty->assign("hint", print_sizelimit_warning());
508       $display.= $smarty->fetch (get_template_path('mail_locals.tpl', TRUE, dirname(__FILE__)));
509       return ($display);
510     }
512     /* Display mail account tab */
513     if(empty($this->gosaVacationStart)){
514       $date= getdate(time());
515     }else{
516       $date= getdate($this->gosaVacationStart);
517     }
518     $days= array();
519     for($d= 1; $d<32; $d++){
520       $days[$d]= $d;
521     }
522     $years= array();
523     for($y= $date['year']-10; $y<$date['year']+10; $y++){
524       $years[]= $y;
525     }
526     $months= array(_("January"), _("February"), _("March"), _("April"),
527         _("May"), _("June"), _("July"), _("August"), _("September"),
528         _("October"), _("November"), _("December"));
529     $smarty->assign("start_day", $date["mday"]);
530     $smarty->assign("days", $days);
531     $smarty->assign("months", $months);
532     $smarty->assign("start_month", $date["mon"]-1);
533     $smarty->assign("years", $years);
534     $smarty->assign("start_year", $date["year"]);
536     if(empty($this->gosaVacationStop)){
537       $date= getdate(time());
538       $date["mday"]++;
539     }else{
540       $date= getdate($this->gosaVacationStop);
541     }
542     $smarty->assign("end_day", $date["mday"]);
543     $smarty->assign("end_month", $date["mon"]-1);
544     $smarty->assign("end_year", $date["year"]);
546     $smarty->assign("mailServers", $mailserver);
547     foreach(array(
548           "gosaMailServer", 
549           "gosaMailQuota", 
550           "perms", 
551           "mail",
552           "gosaMailAlternateAddress", 
553           "gosaMailForwardingAddress",
555           // gosaMailDeliveryMode Flags 
556           "drop_own_mails",                       // No local delivery 
557           "gosaMailMaxSize",                      // Enable - Drop mails > max size
558           "gosaSpamSortLevel", "gosaSpamMailbox", // Enable - Spam sort options
559           "gosaVacationMessage",                  // Enable - Vacation message      
560           "gosaVacationStart",
561           "gosaVacationStop",
562           "custom_sieve",                         // Use custom sieve script
563           "only_local"                            // Send/receive local mails 
564                                         ) as $val){
565       if(isset($this->$val)){
566         $smarty->assign("$val", $this->$val);
567       }
568       $smarty->assign("$val"."ACL", chkacl($this->acl, "$val"));
569     }
571     if (preg_match('/V/', $this->gosaMailDeliveryMode)){
572       $smarty->assign('rangeEnabled', "");
573     } else {
574       $smarty->assign('rangeEnabled', "disabled");
575     }
577     if (is_numeric($this->gosaMailQuota) && $this->gosaMailQuota != 0){
578       $smarty->assign("quotausage", progressbar(round(($this->quotaUsage * 100)/ $this->gosaMailQuota),100,15,true));
579       $smarty->assign("quotadefined", "true");
580     } else {
581       $smarty->assign("quotadefined", "false");
582     }
584     /* Disable mail field if needed */
585     $method= new $this->method($this->config);
586     if ($method->uattrib == "mail" && $this->initially_was_account){
587       $smarty->assign("mailACL", "disabled");
588     }
591     if (!preg_match("/L/", $this->gosaMailDeliveryMode)) {
592       $smarty->assign("drop_own_mails", "checked");
593     } else {
594       $smarty->assign("drop_own_mails", "");
595     }
597     $types = array(
598           "V"=>"use_vacation",
599           "S"=>"use_spam_filter",
600           "R"=>"use_mailsize_limit",
601           "I"=>"only_local",
602           "C"=>"own_script");
604     /* Fill checkboxes */
605     foreach($types as $option => $varname){
606       if (preg_match("/".$option."/", $this->gosaMailDeliveryMode)) {
607         $smarty->assign($varname, "checked");
608       } else {
609         $smarty->assign($varname, "");
610       }
611     }
612     
613     if (preg_match("/V/", $this->gosaMailDeliveryMode)) {
614       $smarty->assign("use_vacation", "checked");
615     } else {
616       $smarty->assign("use_vacation", "");
617     }
618     if (preg_match("/S/", $this->gosaMailDeliveryMode)) {
619       $smarty->assign("use_spam_filter", "checked");
620     } else {
621       $smarty->assign("use_spam_filter", "");
622     }
623     if (preg_match("/R/", $this->gosaMailDeliveryMode)) {
624       $smarty->assign("use_mailsize_limit", "checked");
625     } else {
626       $smarty->assign("use_mailsize_limit", "");
627     }
628     if (preg_match("/I/", $this->gosaMailDeliveryMode)) {
629       $smarty->assign("only_local", "checked");
630     } else {
631       $smarty->assign("only_local", "");
632     }
633     if (preg_match("/C/", $this->gosaMailDeliveryMode)) {
634       $smarty->assign("own_script", "checked");
635     } else {
636       $smarty->assign("own_script", "");
637     }
639     /* Have vacation templates? */
640     $smarty->assign("template", "");
641     if (count($this->vacation)){
642       $smarty->assign("show_templates", "true");
643       $smarty->assign("vacationtemplates", $this->vacation);
644       if (isset($_POST['vacation_template'])){
645         $smarty->assign("template", $_POST['vacation_template']);
646       }
647     } else {
648       $smarty->assign("show_templates", "false");
649     }
651     /* Fill spam selector */
652     $spamlevel= array();
653     for ($i= 0; $i<21; $i++){
654       $spamlevel[]= $i;
655     }
656     $smarty->assign("spamlevel", $spamlevel);
657     $smarty->assign("spambox", $this->mailboxList);
658     $smarty->assign("custom_sieveACL", chkacl($this->acl, "custom_sieve"));     
659     $smarty->assign("only_localACL", chkacl($this->acl, "only_local")); 
661     $display.= $smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
662     return ($display);
663   }
665   /* check if we have some delegations configured, those delegations must be removed first */
666   function accountDelegationsConfigured()
667   { 
668     /* We are in administrational edit mode.
669         Check tab configurations directly */
670     if(isset($this->attrs)){
671       $checkArray  = array("kolabInvitationPolicy","unrestrictedMailSize", "calFBURL","kolabDelegate","kolabFreeBusyFuture");
672       foreach($checkArray as $index){
673         if(isset($this->attrs[$index])){
674            return(true);
675         }
676       }
677     }
678     if(isset($this->parent->by_object['connectivity']->plugin['kolabAccount'])){
679       if($this->parent->by_object['connectivity']->plugin['kolabAccount']->is_account){
680         return(true);
681       }
682     }
683     return(false); 
684   }
687   /* remove object from parent */
688   function remove_from_parent()
689   {
690     /* Cancel if there's nothing to do here */
691     if (!$this->initially_was_account){
692       return;
693     }
694     
695     /* include global link_info */
696     $ldap= $this->config->get_ldap_link();
698     /* Remove and write to LDAP */
699     plugin::remove_from_parent();
701     /* Zero arrays */
702     $this->attrs['gosaMailAlternateAddress']= array();
703     $this->attrs['gosaMailForwardingAddress']= array();
705     /* Adapt attributes if needed */
706     $method= new $this->method($this->config);
707     $method->fixAttributesOnRemove($this);
709     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,$this->attributes, "Save");
710     $ldap->cd($this->dn);
711     $this->cleanup();
712     $ldap->modify ($this->attrs); 
714     show_ldap_error($ldap->get_error(), _("Removing mail account failed"));
716     /* Connect to IMAP server for account deletion */
717     if ($this->gosaMailServer != ""){
718       $method= new $this->method($this->config);
719       $id= $method->uattrib;
720       if ($method->connect($this->gosaMailServer)){
722         /* Remove account from IMAP server */
723         $method->deleteMailbox($this->folder_prefix.$this->$id);
724         $method->disconnect();
725       }
726     }
728     /* Optionally execute a command after we're done */
729     $this->handle_post_events("remove", array('uid'=> $this->uid));
730   }
733   /* Save data to object */
734   function save_object()
735   {
736     if (isset($_POST['mailTab'])){
737       /* Save ldap attributes */
738       plugin::save_object();
740       /* Assemble mail delivery mode
741          The mode field in ldap consists of values between braces, this must
742          be called when 'mail' is set, because checkboxes may not be set when
743          we're in some other dialog.
745          Example for gosaMailDeliveryMode [LR        ]
746          L: Local delivery
747          R: Reject when exceeding mailsize limit
748          S: Use spam filter
749          V: Use vacation message
750          C: Use custm sieve script
751          I: Only insider delivery */
753       $tmp= "";
754       $Flags = array(
755                      "R"  => array("ACL" => "gosaMailMaxSize",    "POST" => "use_mailsize_limit"),
756                      "V"  => array("ACL" => "gosaVacationMessage","POST" => "use_vacation"),
757                      "C"  => array("ACL" => "custom_sieve",       "POST" => "own_script"),
758                      "I"  => array("ACL" => "only_local",         "POST" => "only_local"));
760       /* Check acls and set new value if allowed. 
761          If we do not have permission to change the value 
762           check for the old value and use this */
763       foreach($Flags as $flag => $val){
764         $acl  = $val['ACL'];
765         $post = $val['POST'];
766         if(chkacl($this->acl,$acl) ==""){
767           if (isset($_POST[$post])){
768             $tmp.= $flag;
769           }
770         }else{
771           if(preg_match("/".$flag."/",$this->gosaMailDeliveryMode)){
772             $tmp.= $flag ;
773           }
774         }
775       }
777       /* ! Inverse flag handling for drop_own_mails */
778       if(chkacl($this->acl,"drop_own_mails") == ""){
779         if (!isset($_POST['drop_own_mails'])){
780           $tmp.= "L";
781         }
782       }else{
783         if(preg_match("/L/",$this->gosaMailDeliveryMode)){
784           $tmp.= "L" ;
785         }
786       }
788       /* If one of these acls are given, we are allowed to enable disable the the spam settings */
789       if(chkacl($this->acl,"gosaSpamMailbox") == "" || chkacl($this->acl,"gosaSpamSortLevel") ==""){
790         if (isset($_POST["use_spam_filter"])){
791           $tmp.= "S";
792         }
793       }else{
794         if(preg_match("/S/",$this->gosaMailDeliveryMode)){
795           $tmp.= "S" ;
796         }
797       }
798       
799       /* Check if something has changed an assign new gosaMailDeliveryMode */
800       $tmp= "[$tmp]";
801       if ($this->gosaMailDeliveryMode != $tmp){
802         $this->is_modified= TRUE;
803       }
804       $this->gosaMailDeliveryMode= $tmp;
805     }
807   }
810   /* Save data to LDAP, depending on is_account we save or delete */
811   function save()
812   {
813     $ldap= $this->config->get_ldap_link();
815     /* Call parents save to prepare $this->attrs */
816     plugin::save();
818     /* Save arrays */
819     $this->attrs['gosaMailAlternateAddress']= $this->gosaMailAlternateAddress;
820     $this->attrs['gosaMailForwardingAddress']= $this->gosaMailForwardingAddress;
822     /* Adapt attributes if needed */
823     $method= new $this->method($this->config);
824     $id= $method->uattrib;
826     $method->fixAttributesOnStore($this);
828     /* Remove Mailquota if = "" or "0"  */
829     if((isset($this->attrs['gosaMailQuota']))&&(!$this->attrs['gosaMailQuota'])) {
830       $this->attrs['gosaMailQuota']=0;
831     }
833     if(empty($this->attrs['gosaSpamMailbox'])){
834       unset($this->attrs['gosaSpamMailbox']);
835     }
837     $this->attrs['mail'] = strtolower($this->attrs['mail']); 
839     /* Remove attributes - if not needed */
840     if (!preg_match('/V/', $this->gosaMailDeliveryMode)){
841       unset($this->attrs['gosaVacationStart']);
842       unset($this->attrs['gosaVacationStop']);
843     }
845     /* Save data to LDAP */
846     $ldap->cd($this->dn);
847     $this->cleanup();
848     $ldap->modify ($this->attrs); 
850     show_ldap_error($ldap->get_error(), _("Saving mail account failed"));
852     /* Only do IMAP actions if we are not a template */
853     if (!$this->is_template){
855       if ($method->connect($this->gosaMailServer)){
856         $method->updateMailbox($this->folder_prefix.$this->$id);
857         
858         $method->setQuota($this->folder_prefix.$this->$id, $this->gosaMailQuota);
859         $method->disconnect();
861         /* Only talk with sieve if the mail account already exists */
862         if($this->initially_was_account){
863           
864           /* Write sieve information only if not in C mode */
865           if (!is_integer(strpos($this->gosaMailDeliveryMode, "C"))){
866             $method->configureFilter($this->$id,
867                 $this->gosaMailDeliveryMode,
868                 $this->mail,
869                 $this->gosaMailAlternateAddress,
870                 $this->gosaMailMaxSize,
871                 $this->gosaSpamMailbox,
872                 $this->gosaSpamSortLevel,
873                 $this->gosaVacationMessage);
874           }
875         }
876       }
877     }
879     /* Optionally execute a command after we're done */
880     if ($this->initially_was_account == $this->is_account){
881       if ($this->is_modified){
882         $this->handle_post_events("modify", array('uid'=> $this->uid));
883       }
884     } else {
885       $this->handle_post_events("add", array('uid'=>$this->uid));
886     }
888   }
891   /* Check formular input */
892   function check()
893   {
894     if(!$this->is_account) return(array());
896     $ldap= $this->config->get_ldap_link();
898     /* Call common method to give check the hook */
899     $message= plugin::check();
901     if(empty($this->gosaMailServer)){
902       $message[]= _("There is no valid mailserver specified, please add one in the system setup.");
903     }
905     /* must: mail */
906     if ($this->mail == ""){
907       $message[]= _("The required field 'Primary address' is not set.");
908     }
909     if ($this->is_template){
910       if (!is_email($this->mail, TRUE)){
911         $message[]= _("Please enter a valid email address in 'Primary address' field.");
912       }
913     } else {
914       if (!is_email($this->mail)){
915         $message[]= _("Please enter a valid email address in 'Primary address' field.");
916       }
917     }
918     $ldap->cd($this->config->current['BASE']);
919     $ldap->search ("(&(!(objectClass=gosaUserTemplate))(objectClass=gosaMailAccount)(|(mail=".$this->mail.")(gosaMailAlternateAddress=".$this->mail."))(!(uid=".$this->uid."))(!(cn=".$this->uid.")))", array("uid"));
920     if ($ldap->count() != 0){
921       $message[]= _("The primary address you've entered is already in use.");
922     }
924     /* Check quota */
925     if ($this->gosaMailQuota != '' && chkacl ($this->acl, "gosaMailQuota") == ""){
926       if (!is_numeric($this->gosaMailQuota)) {
927         $message[]= _("Value in 'Quota size' is not valid.");
928       } else {
929         $this->gosaMailQuota= (int) $this->gosaMailQuota;
930       }
931     }
933     /* Check rejectsize for integer */
934     if ($this->gosaMailMaxSize != '' && chkacl ($this->acl, "gosaMailQuota") == ""){
935       if (!is_numeric($this->gosaMailMaxSize)){
936         $message[]= _("Please specify a vaild mail size for mails to be rejected.");
937       } else {
938         $this->gosaMailMaxSize= (int) $this->gosaMailMaxSize;
939       }
940     }
942     /* Need gosaMailMaxSize if use_mailsize_limit is checked */
943     if (is_integer(strpos($this->gosaMailDeliveryMode, "R")) && 
944         $this->gosaMailMaxSize == ""){
946       $message[]= _("You need to set the maximum mail size in order to reject anything.");
947     }
949     if((preg_match("/S/", $this->gosaMailDeliveryMode))&&(empty($this->gosaSpamMailbox))) {
950       $message[]= _("You specified Spam settings, but there is no Folder specified.");
951     }
953     if (preg_match('/V/', $this->gosaMailDeliveryMode) && $this->gosaVacationStart >= $this->gosaVacationStop){
954       $message[]= _("Time interval to show vacation message is not valid.");
955     }
957     return ($message);
958   }
961   /* Adapt from template, using 'dn' */
962   function adapt_from_template($dn)
963   {
964     plugin::adapt_from_template($dn);
966     foreach (array("gosaMailAlternateAddress", "gosaMailForwardingAddress") as $val){
967       $this->$val= array();
968       if (isset($this->attrs["$val"]["count"])){
969         for ($i= 0; $i<$this->attrs["$val"]["count"]; $i++){
970           $value= $this->attrs["$val"][$i];
971           foreach (array("sn", "givenName", "uid") as $repl){
972             if (preg_match("/%$repl/i", $value)){
973               $value= preg_replace ("/%$repl/i", $this->parent->$repl, $value);
974             }
975           }
976           array_push($this->$val, strtolower(rewrite($value)));
977         }
978       }
979     }
980     $this->mail= strtolower(rewrite($this->mail));
981   }
984   /* Add entry to forwarder list */
985   function addForwarder($address)
986   {
987     $this->gosaMailForwardingAddress[]= $address;
988     $this->gosaMailForwardingAddress= array_unique ($this->gosaMailForwardingAddress);
989     sort ($this->gosaMailForwardingAddress);
990     reset ($this->gosaMailForwardingAddress);
991     $this->is_modified= TRUE;
992   }
995   /* Remove list of addresses from forwarder list */
996   function delForwarder($addresses)
997   {
998     $this->gosaMailForwardingAddress= array_remove_entries ($addresses, $this->gosaMailForwardingAddress);
999     $this->is_modified= TRUE;
1000   }
1003   /* Add given mail address to the list of alternate adresses , 
1004       check if this mal address is used, skip adding in this case */
1005   function addAlternate($address)
1006   {
1007     $ldap= $this->config->get_ldap_link();
1008     $address= strtolower($address);
1009       
1010     /* Is this address already assigned in LDAP? */
1011     $ldap->cd ($this->config->current['BASE']);
1012     $ldap->search ("(&(!(objectClass=gosaUserTemplate))(objectClass=gosaMailAccount)(|(mail=$address)"."(gosaMailAlternateAddress=$address)))", array("uid"));
1014     if ($ldap->count() > 0){
1015       $attrs= $ldap->fetch ();
1016       return ($attrs["uid"][0]);
1017     }
1019     /* Add to list of alternates */
1020     if (!in_array($address, $this->gosaMailAlternateAddress)){
1021       $this->gosaMailAlternateAddress[]= $address;
1022       $this->is_modified= TRUE;
1023     }
1025     sort ($this->gosaMailAlternateAddress);
1026     reset ($this->gosaMailAlternateAddress);
1027     return ("");
1028   }
1031   function delAlternate($addresses)
1032   {
1033     $this->gosaMailAlternateAddress= array_remove_entries ($addresses,
1034                                                            $this->gosaMailAlternateAddress);
1035     $this->is_modified= TRUE;
1036   }
1038   function make_name($attrs)
1039   {
1040     $name= "";
1041     if (isset($attrs['sn'][0])){
1042       $name= $attrs['sn'][0];
1043     }
1044     if (isset($attrs['givenName'][0])){
1045       if ($name != ""){
1046         $name.= ", ".$attrs['givenName'][0];
1047       } else {
1048         $name.= $attrs['givenName'][0];
1049       }
1050     }
1051     if ($name != ""){
1052       $name.= " ";
1053     }
1055     return ($name);
1056   }
1058   
1059   /* Create the mail part for the copy & paste dialog */
1060   function getCopyDialog()
1061   {
1062     if(!$this->is_account) return("");
1063     $smarty = get_smarty();
1064     $smarty->assign("mail",$this->mail); 
1065     $smarty->assign("gosaMailAlternateAddress",$this->gosaMailAlternateAddress);
1066     $smarty->assign("gosaMailForwardingAddress",$this->gosaMailForwardingAddress);
1067     $str = $smarty->fetch(get_template_path("copypaste.tpl",TRUE, dirname(__FILE__)));
1069     $ret = array();
1070     $ret['status'] = "";
1071     $ret['string'] = $str;
1072     return($ret);
1073   }
1075   function saveCopyDialog()
1076   {
1077     if(!$this->is_account) return;  
1079     /* Execute to save mailAlternateAddress && gosaMailForwardingAddress */
1080     $this->execute();
1081     
1082     if(isset($_POST['mail'])){
1083       $this->mail = $_POST['mail'];
1084     }
1085   }
1087    
1088   function PrepareForCopyPaste($source)
1089   {
1090     plugin::PrepareForCopyPaste($source);
1092     /* Reset alternate mail addresses */
1093     $this->gosaMailAlternateAddress = array();    
1094   }
1097   function allow_remove()
1098   {
1099     if (isset($this->config->current['MAILMETHOD'])){
1100       $method= $this->config->current['MAILMETHOD'];
1101       if(preg_match("/olab/i",$method)){
1102         $ldap = $this->config->get_ldap_link();
1103         $ldap->cd($this->config->current['BASE']);
1104         $ldap->cat($this->dn);
1105         if($ldap->count()){
1106           $attrs = $ldap->fetch();
1107           if(isset($attrs['kolabDeleteFlag'])){ 
1108             return(_("Waiting for kolab to remove mail properties."));
1109           }elseif(in_array("gosaMailAccount",$attrs['objectClass'])){
1110             return(_("Please remove the mail account first, to allow kolab to call its remove methods."));
1111           }
1112         }
1113       }
1114     }
1115   }
1118 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1119 ?>