Code

First step to get start/stop for vacation messages inside
[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"]);
547     $smarty->assign("mailServers", $mailserver);
548     foreach(array(
549           "gosaMailServer", 
550           "gosaMailQuota", 
551           "perms", 
552           "mail",
553           "gosaMailAlternateAddress", 
554           "gosaMailForwardingAddress",
556           // gosaMailDeliveryMode Flags 
557           "drop_own_mails",                       // No local delivery 
558           "gosaMailMaxSize",                      // Enable - Drop mails > max size
559           "gosaSpamSortLevel", "gosaSpamMailbox", // Enable - Spam sort options
560           "gosaVacationMessage",                  // Enable - Vacation message      
561           "gosaVacationStart",
562           "gosaVacationStop",
563           "custom_sieve",                         // Use custom sieve script
564           "only_local"                            // Send/receive local mails 
565                                         ) as $val){
566       if(isset($this->$val)){
567         $smarty->assign("$val", $this->$val);
568       }
569       $smarty->assign("$val"."ACL", chkacl($this->acl, "$val"));
570     }
572     if (isset($this->gosaVacationStart)){
573       $smarty->assign("use_vacation_interval", 1);
574     } else {
575       $smarty->assign("use_vacation_interval", 0);
576     }
578     if (is_numeric($this->gosaMailQuota) && $this->gosaMailQuota != 0){
579       $smarty->assign("quotausage", progressbar(round(($this->quotaUsage * 100)/ $this->gosaMailQuota),100,15,true));
580       $smarty->assign("quotadefined", "true");
581     } else {
582       $smarty->assign("quotadefined", "false");
583     }
585     /* Disable mail field if needed */
586     $method= new $this->method($this->config);
587     if ($method->uattrib == "mail" && $this->initially_was_account){
588       $smarty->assign("mailACL", "disabled");
589     }
592     if (!preg_match("/L/", $this->gosaMailDeliveryMode)) {
593       $smarty->assign("drop_own_mails", "checked");
594     } else {
595       $smarty->assign("drop_own_mails", "");
596     }
598     $types = array(
599           "V"=>"use_vacation",
600           "S"=>"use_spam_filter",
601           "R"=>"use_mailsize_limit",
602           "I"=>"only_local",
603           "C"=>"own_script");
605     /* Fill checkboxes */
606     foreach($types as $option => $varname){
607       if (preg_match("/".$option."/", $this->gosaMailDeliveryMode)) {
608         $smarty->assign($varname, "checked");
609       } else {
610         $smarty->assign($varname, "");
611       }
612     }
613     
614     if (preg_match("/V/", $this->gosaMailDeliveryMode)) {
615       $smarty->assign("use_vacation", "checked");
616     } else {
617       $smarty->assign("use_vacation", "");
618     }
619     if (preg_match("/S/", $this->gosaMailDeliveryMode)) {
620       $smarty->assign("use_spam_filter", "checked");
621     } else {
622       $smarty->assign("use_spam_filter", "");
623     }
624     if (preg_match("/R/", $this->gosaMailDeliveryMode)) {
625       $smarty->assign("use_mailsize_limit", "checked");
626     } else {
627       $smarty->assign("use_mailsize_limit", "");
628     }
629     if (preg_match("/I/", $this->gosaMailDeliveryMode)) {
630       $smarty->assign("only_local", "checked");
631     } else {
632       $smarty->assign("only_local", "");
633     }
634     if (preg_match("/C/", $this->gosaMailDeliveryMode)) {
635       $smarty->assign("own_script", "checked");
636     } else {
637       $smarty->assign("own_script", "");
638     }
640     /* Have vacation templates? */
641     $smarty->assign("template", "");
642     if (count($this->vacation)){
643       $smarty->assign("show_templates", "true");
644       $smarty->assign("vacationtemplates", $this->vacation);
645       if (isset($_POST['vacation_template'])){
646         $smarty->assign("template", $_POST['vacation_template']);
647       }
648     } else {
649       $smarty->assign("show_templates", "false");
650     }
652     /* Fill spam selector */
653     $spamlevel= array();
654     for ($i= 0; $i<21; $i++){
655       $spamlevel[]= $i;
656     }
657     $smarty->assign("spamlevel", $spamlevel);
658     $smarty->assign("spambox", $this->mailboxList);
659     $smarty->assign("custom_sieveACL", chkacl($this->acl, "custom_sieve"));     
660     $smarty->assign("only_localACL", chkacl($this->acl, "only_local")); 
662     $display.= $smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
663     return ($display);
664   }
666   /* check if we have some delegations configured, those delegations must be removed first */
667   function accountDelegationsConfigured()
668   { 
669     /* We are in administrational edit mode.
670         Check tab configurations directly */
671     if(isset($this->attrs)){
672       $checkArray  = array("kolabInvitationPolicy","unrestrictedMailSize", "calFBURL","kolabDelegate","kolabFreeBusyFuture");
673       foreach($checkArray as $index){
674         if(isset($this->attrs[$index])){
675            return(true);
676         }
677       }
678     }
679     if(isset($this->parent->by_object['connectivity']->plugin['kolabAccount'])){
680       if($this->parent->by_object['connectivity']->plugin['kolabAccount']->is_account){
681         return(true);
682       }
683     }
684     return(false); 
685   }
688   /* remove object from parent */
689   function remove_from_parent()
690   {
691     /* Cancel if there's nothing to do here */
692     if (!$this->initially_was_account){
693       return;
694     }
695     
696     /* include global link_info */
697     $ldap= $this->config->get_ldap_link();
699     /* Remove and write to LDAP */
700     plugin::remove_from_parent();
702     /* Zero arrays */
703     $this->attrs['gosaMailAlternateAddress']= array();
704     $this->attrs['gosaMailForwardingAddress']= array();
706     /* Adapt attributes if needed */
707     $method= new $this->method($this->config);
708     $method->fixAttributesOnRemove($this);
710     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,$this->attributes, "Save");
711     $ldap->cd($this->dn);
712     $this->cleanup();
713     $ldap->modify ($this->attrs); 
715     show_ldap_error($ldap->get_error(), _("Removing mail account failed"));
717     /* Connect to IMAP server for account deletion */
718     if ($this->gosaMailServer != ""){
719       $method= new $this->method($this->config);
720       $id= $method->uattrib;
721       if ($method->connect($this->gosaMailServer)){
723         /* Remove account from IMAP server */
724         $method->deleteMailbox($this->folder_prefix.$this->$id);
725         $method->disconnect();
726       }
727     }
729     /* Optionally execute a command after we're done */
730     $this->handle_post_events("remove", array('uid'=> $this->uid));
731   }
734   /* Save data to object */
735   function save_object()
736   {
737     if (isset($_POST['mailTab'])){
738       /* Save ldap attributes */
739       plugin::save_object();
741       /* Assemble mail delivery mode
742          The mode field in ldap consists of values between braces, this must
743          be called when 'mail' is set, because checkboxes may not be set when
744          we're in some other dialog.
746          Example for gosaMailDeliveryMode [LR        ]
747          L: Local delivery
748          R: Reject when exceeding mailsize limit
749          S: Use spam filter
750          V: Use vacation message
751          C: Use custm sieve script
752          I: Only insider delivery */
754       $tmp= "";
755       $Flags = array(
756                      "R"  => array("ACL" => "gosaMailMaxSize",    "POST" => "use_mailsize_limit"),
757                      "V"  => array("ACL" => "gosaVacationMessage","POST" => "use_vacation"),
758                      "C"  => array("ACL" => "custom_sieve",       "POST" => "own_script"),
759                      "I"  => array("ACL" => "only_local",         "POST" => "only_local"));
761       /* Check acls and set new value if allowed. 
762          If we do not have permission to change the value 
763           check for the old value and use this */
764       foreach($Flags as $flag => $val){
765         $acl  = $val['ACL'];
766         $post = $val['POST'];
767         if(chkacl($this->acl,$acl) ==""){
768           if (isset($_POST[$post])){
769             $tmp.= $flag;
770           }
771         }else{
772           if(preg_match("/".$flag."/",$this->gosaMailDeliveryMode)){
773             $tmp.= $flag ;
774           }
775         }
776       }
778       /* ! Inverse flag handling for drop_own_mails */
779       if(chkacl($this->acl,"drop_own_mails") == ""){
780         if (!isset($_POST['drop_own_mails'])){
781           $tmp.= "L";
782         }
783       }else{
784         if(preg_match("/L/",$this->gosaMailDeliveryMode)){
785           $tmp.= "L" ;
786         }
787       }
789       /* If one of these acls are given, we are allowed to enable disable the the spam settings */
790       if(chkacl($this->acl,"gosaSpamMailbox") == "" || chkacl($this->acl,"gosaSpamSortLevel") ==""){
791         if (isset($_POST["use_spam_filter"])){
792           $tmp.= "S";
793         }
794       }else{
795         if(preg_match("/S/",$this->gosaMailDeliveryMode)){
796           $tmp.= "S" ;
797         }
798       }
799       
800       /* Check if something has changed an assign new gosaMailDeliveryMode */
801       $tmp= "[$tmp]";
802       if ($this->gosaMailDeliveryMode != $tmp){
803         $this->is_modified= TRUE;
804       }
805       $this->gosaMailDeliveryMode= $tmp;
806     }
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     /* Save data to LDAP */
840     $ldap->cd($this->dn);
841     $this->cleanup();
842     $ldap->modify ($this->attrs); 
844     show_ldap_error($ldap->get_error(), _("Saving mail account failed"));
846     /* Only do IMAP actions if we are not a template */
847     if (!$this->is_template){
849       if ($method->connect($this->gosaMailServer)){
850         $method->updateMailbox($this->folder_prefix.$this->$id);
851         
852         $method->setQuota($this->folder_prefix.$this->$id, $this->gosaMailQuota);
853         $method->disconnect();
855         /* Only talk with sieve if the mail account already exists */
856         if($this->initially_was_account){
857           
858           /* Write sieve information only if not in C mode */
859           if (!is_integer(strpos($this->gosaMailDeliveryMode, "C"))){
860             $method->configureFilter($this->$id,
861                 $this->gosaMailDeliveryMode,
862                 $this->mail,
863                 $this->gosaMailAlternateAddress,
864                 $this->gosaMailMaxSize,
865                 $this->gosaSpamMailbox,
866                 $this->gosaSpamSortLevel,
867                 $this->gosaVacationMessage);
868           }
869         }
870       }
871     }
873     /* Optionally execute a command after we're done */
874     if ($this->initially_was_account == $this->is_account){
875       if ($this->is_modified){
876         $this->handle_post_events("modify", array('uid'=> $this->uid));
877       }
878     } else {
879       $this->handle_post_events("add", array('uid'=>$this->uid));
880     }
882   }
885   /* Check formular input */
886   function check()
887   {
888     if(!$this->is_account) return(array());
890     $ldap= $this->config->get_ldap_link();
892     /* Call common method to give check the hook */
893     $message= plugin::check();
895     if(empty($this->gosaMailServer)){
896       $message[]= _("There is no valid mailserver specified, please add one in the system setup.");
897     }
899     /* must: mail */
900     if ($this->mail == ""){
901       $message[]= _("The required field 'Primary address' is not set.");
902     }
903     if ($this->is_template){
904       if (!is_email($this->mail, TRUE)){
905         $message[]= _("Please enter a valid email address in 'Primary address' field.");
906       }
907     } else {
908       if (!is_email($this->mail)){
909         $message[]= _("Please enter a valid email address in 'Primary address' field.");
910       }
911     }
912     $ldap->cd($this->config->current['BASE']);
913     $ldap->search ("(&(!(objectClass=gosaUserTemplate))(objectClass=gosaMailAccount)(|(mail=".$this->mail.")(gosaMailAlternateAddress=".$this->mail."))(!(uid=".$this->uid."))(!(cn=".$this->uid.")))", array("uid"));
914     if ($ldap->count() != 0){
915       $message[]= _("The primary address you've entered is already in use.");
916     }
918     /* Check quota */
919     if ($this->gosaMailQuota != '' && chkacl ($this->acl, "gosaMailQuota") == ""){
920       if (!is_numeric($this->gosaMailQuota)) {
921         $message[]= _("Value in 'Quota size' is not valid.");
922       } else {
923         $this->gosaMailQuota= (int) $this->gosaMailQuota;
924       }
925     }
927     /* Check rejectsize for integer */
928     if ($this->gosaMailMaxSize != '' && chkacl ($this->acl, "gosaMailQuota") == ""){
929       if (!is_numeric($this->gosaMailMaxSize)){
930         $message[]= _("Please specify a vaild mail size for mails to be rejected.");
931       } else {
932         $this->gosaMailMaxSize= (int) $this->gosaMailMaxSize;
933       }
934     }
936     /* Need gosaMailMaxSize if use_mailsize_limit is checked */
937     if (is_integer(strpos($this->gosaMailDeliveryMode, "R")) && 
938         $this->gosaMailMaxSize == ""){
940       $message[]= _("You need to set the maximum mail size in order to reject anything.");
941     }
943     if((preg_match("/S/", $this->gosaMailDeliveryMode))&&(empty($this->gosaSpamMailbox))) {
944       $message[]= _("You specified Spam settings, but there is no Folder specified.");
945     }
947     return ($message);
948   }
951   /* Adapt from template, using 'dn' */
952   function adapt_from_template($dn)
953   {
954     plugin::adapt_from_template($dn);
956     foreach (array("gosaMailAlternateAddress", "gosaMailForwardingAddress") as $val){
957       $this->$val= array();
958       if (isset($this->attrs["$val"]["count"])){
959         for ($i= 0; $i<$this->attrs["$val"]["count"]; $i++){
960           $value= $this->attrs["$val"][$i];
961           foreach (array("sn", "givenName", "uid") as $repl){
962             if (preg_match("/%$repl/i", $value)){
963               $value= preg_replace ("/%$repl/i", $this->parent->$repl, $value);
964             }
965           }
966           array_push($this->$val, strtolower(rewrite($value)));
967         }
968       }
969     }
970     $this->mail= strtolower(rewrite($this->mail));
971   }
974   /* Add entry to forwarder list */
975   function addForwarder($address)
976   {
977     $this->gosaMailForwardingAddress[]= $address;
978     $this->gosaMailForwardingAddress= array_unique ($this->gosaMailForwardingAddress);
979     sort ($this->gosaMailForwardingAddress);
980     reset ($this->gosaMailForwardingAddress);
981     $this->is_modified= TRUE;
982   }
985   /* Remove list of addresses from forwarder list */
986   function delForwarder($addresses)
987   {
988     $this->gosaMailForwardingAddress= array_remove_entries ($addresses, $this->gosaMailForwardingAddress);
989     $this->is_modified= TRUE;
990   }
993   /* Add given mail address to the list of alternate adresses , 
994       check if this mal address is used, skip adding in this case */
995   function addAlternate($address)
996   {
997     $ldap= $this->config->get_ldap_link();
998     $address= strtolower($address);
999       
1000     /* Is this address already assigned in LDAP? */
1001     $ldap->cd ($this->config->current['BASE']);
1002     $ldap->search ("(&(!(objectClass=gosaUserTemplate))(objectClass=gosaMailAccount)(|(mail=$address)"."(gosaMailAlternateAddress=$address)))", array("uid"));
1004     if ($ldap->count() > 0){
1005       $attrs= $ldap->fetch ();
1006       return ($attrs["uid"][0]);
1007     }
1009     /* Add to list of alternates */
1010     if (!in_array($address, $this->gosaMailAlternateAddress)){
1011       $this->gosaMailAlternateAddress[]= $address;
1012       $this->is_modified= TRUE;
1013     }
1015     sort ($this->gosaMailAlternateAddress);
1016     reset ($this->gosaMailAlternateAddress);
1017     return ("");
1018   }
1021   function delAlternate($addresses)
1022   {
1023     $this->gosaMailAlternateAddress= array_remove_entries ($addresses,
1024                                                            $this->gosaMailAlternateAddress);
1025     $this->is_modified= TRUE;
1026   }
1028   function make_name($attrs)
1029   {
1030     $name= "";
1031     if (isset($attrs['sn'][0])){
1032       $name= $attrs['sn'][0];
1033     }
1034     if (isset($attrs['givenName'][0])){
1035       if ($name != ""){
1036         $name.= ", ".$attrs['givenName'][0];
1037       } else {
1038         $name.= $attrs['givenName'][0];
1039       }
1040     }
1041     if ($name != ""){
1042       $name.= " ";
1043     }
1045     return ($name);
1046   }
1048   
1049   /* Create the mail part for the copy & paste dialog */
1050   function getCopyDialog()
1051   {
1052     if(!$this->is_account) return("");
1053     $smarty = get_smarty();
1054     $smarty->assign("mail",$this->mail); 
1055     $smarty->assign("gosaMailAlternateAddress",$this->gosaMailAlternateAddress);
1056     $smarty->assign("gosaMailForwardingAddress",$this->gosaMailForwardingAddress);
1057     $str = $smarty->fetch(get_template_path("copypaste.tpl",TRUE, dirname(__FILE__)));
1059     $ret = array();
1060     $ret['status'] = "";
1061     $ret['string'] = $str;
1062     return($ret);
1063   }
1065   function saveCopyDialog()
1066   {
1067     if(!$this->is_account) return;  
1069     /* Execute to save mailAlternateAddress && gosaMailForwardingAddress */
1070     $this->execute();
1071     
1072     if(isset($_POST['mail'])){
1073       $this->mail = $_POST['mail'];
1074     }
1075   }
1077    
1078   function PrepareForCopyPaste($source)
1079   {
1080     plugin::PrepareForCopyPaste($source);
1082     /* Reset alternate mail addresses */
1083     $this->gosaMailAlternateAddress = array();    
1084   }
1087   function allow_remove()
1088   {
1089     if (isset($this->config->current['MAILMETHOD'])){
1090       $method= $this->config->current['MAILMETHOD'];
1091       if(preg_match("/olab/i",$method)){
1092         $ldap = $this->config->get_ldap_link();
1093         $ldap->cd($this->config->current['BASE']);
1094         $ldap->cat($this->dn);
1095         if($ldap->count()){
1096           $attrs = $ldap->fetch();
1097           if(isset($attrs['kolabDeleteFlag'])){ 
1098             return(_("Waiting for kolab to remove mail properties."));
1099           }elseif(in_array("gosaMailAccount",$attrs['objectClass'])){
1100             return(_("Please remove the mail account first, to allow kolab to call its remove methods."));
1101           }
1102         }
1103       }
1104     }
1105   }
1108 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1109 ?>