Code

Added remove and activate script button
[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   /* CLI vars */
27   var $cli_summary        = "Manage users mail account";
28   var $cli_description    = "Some longer text\nfor help";
29   var $cli_parameters     = array("eins" => "Eins ist toll", "zwei" => "Zwei ist noch besser");
31   /* plugin specific values */
32   var $mail                               = "";
33   var $gosaMailAlternateAddress           = array();
34   var $gosaMailForwardingAddress          = array();
35   var $gosaMailDeliveryMode               = "[L        ]";
36   var $gosaMailServer                     = "";
37   var $gosaMailQuota                      = "";
38   var $gosaMailMaxSize                    = "";
39   var $gosaVacationMessage                = "";
40   var $gosaSpamSortLevel                  = "";
41   var $gosaSpamMailbox                    = "";
43   var $quotaUsage                         = 0;
44   var $forward_dialog                     = FALSE;
45   var $folder_prefix                      = "";
46   var $mailboxList                        = array("INBOX");
47   var $default_permissions                = "none";
48   var $member_permissions                 = "post";
49   var $members                            = array();
50   var $admins                             = array();
51   var $vacations                          = array();
52   var $perms                              = array(  "lrs"       => "read", 
53                                                     "lrsp"      => "post", 
54                                                     "lrsip"     => "append",
55                                                     "lrswipcd"  => "write", 
56                                                     "lrswipcda" => "all" );
58   /* attribute list for save action */
59   var $attributes= array("mail", "gosaMailServer", "gosaMailQuota", "gosaMailMaxSize","gosaMailForwardingAddress",
60       "gosaMailDeliveryMode", "gosaSpamSortLevel", "gosaSpamMailbox","gosaMailAlternateAddress",
61       "gosaVacationMessage", "gosaMailAlternateAddress", "gosaMailForwardingAddress");
62   var $objectclasses= array("gosaMailAccount");
63   var $uid;
65   /* constructor, if 'dn' is set, the node loads the given
66      'dn' from LDAP */
67   function mailAccount ($config, $dn= NULL)
68   {
69     /* Load bases attributes */
70     plugin::plugin($config, $dn);
72     /* Set uid */
73     if(isset($this->attrs['uid'])){
74       $this->uid = $this->attrs['uid'][0];
75     }
76  
77     if(is_array($this->gosaMailServer) && isset($this->gosaMailServer[0])){
78       $this->gosaMailServer = $this->gosaMailServer[0];
79     }
81     /* Save initial account state */
82     $this->initially_was_account= $this->is_account;
84     /*  Set mailMethod to the one defined in gosa.conf */
85     if (isset($this->config->current['MAILMETHOD'])){
86       $method= $this->config->current['MAILMETHOD'];
87       if (class_exists("mailMethod$method")){
88         $this->method= "mailMethod$method";
89       } else {
90         print_red(sprintf(_("There is no mail method '%s' specified in your gosa.conf available."), $method));
91       }
92     }
94     
95     /* Create the account prefix  user. user/ 
96        Preset folder prefix. Will change it later to respect
97        altnamespace. */
98     if (isset($this->config->current['CYRUSUNIXSTYLE']) && $this->config->current['CYRUSUNIXSTYLE'] == "true"){
99       $this->folder_prefix= "user/";
100     }elseif (isset($this->config->data['MAIN']['CYRUSUNIXSTYLE']) && $this->config->data['MAIN']['CYRUSUNIXSTYLE'] == "true"){
101       $this->folder_prefix= "user/";
102     } else {
103       $this->folder_prefix= "user.";
104     }
105     
106     /* This is not a new account, parse additional attributes */
107     if (($dn != NULL) && ($dn != "new") && $this->is_account){
109       /* Load attributes containing arrays */
110       foreach (array("gosaMailAlternateAddress", "gosaMailForwardingAddress") as $val){
111         $this->$val= array();
112         if (isset($this->attrs["$val"]["count"])){
113           for ($i= 0; $i<$this->attrs["$val"]["count"]; $i++){
114             array_push($this->$val, $this->attrs["$val"][$i]);
115           }
116         }
117       }
120       /* Only do IMAP actions if gosaMailServer attribute is set */
121       if (isset ($this->attrs["gosaMailServer"][0])){
123         $method = new $this->method($this->config);
124         $id     = $method->uattrib;
126         /* Adapt attributes if needed */
127         $method->fixAttributesOnLoad($this);
129         /* FixAttributesOnLoad possibly creates an array out of gosaMailServer.
130             If the mail tab wasn't opened once before saving, the account can't be saved */
131         if(is_array($this->gosaMailServer)){
132           $this->gosaMailServer = $this->gosaMailServer[0];
133         }
135         if ($method->connect($this->attrs["gosaMailServer"][0])){
137           /* Update quota values */
138           $quota= $method->getQuota($this->folder_prefix.$this->$id);
139          
140           if($quota){
141             if ($quota['gosaMailQuota'] == 2147483647){
142               $this->quotaUsage     = "";
143               $this->gosaMailQuota  = "";
144             } else {
145               $this->quotaUsage     = $quota['quotaUsage'];
146               $this->gosaMailQuota  = $quota['gosaMailQuota'];
147             }
148           }else{
149             $this->quotaUsage     = "";
150             $this->gosaMailQuota  = "";
151 //            print_red(sprintf(_("Can't get quota information for '%s'."),$this->folder_prefix.$this->$id));
152           }
154           /* Get mailboxes / folder like INBOX ..*/
155           $this->mailboxList= $method->getMailboxList($this->folder_prefix.$this->$id,$this->$id);
156           
157           $method->disconnect();
158         }else{
159           /* Could not connect to ldap.
160            */
161           if (isset($this->attrs['gosaMailQuota'][0])){
162             $this->gosaMailQuota = $this->attrs['gosaMailQuota'][0];
163           }
164         }
165       }
166     }
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     }
187   /* Create filter */
189     /* Get global filter config */
190     if (!is_global("mailfilter")){
191       $ui= get_userinfo();
192       $base= get_base_from_people($ui->dn);
193       $mailfilter= array( "depselect"       => $base,
194           "muser"            => "",
195           "regex"           => "*");
196       register_global("mailfilter", $mailfilter);
197     }
198   }
201   function parse_vacation($file)
202   {
203     $desc= "";
205     if (is_file($file)){
206       $fh = fopen($file, "r");
207       $line= fgets($fh, 256);
209       if (!preg_match('/^DESC:/', $line)){
210         print_red (_("No DESC tag in vacation file:")." $file");
211         return $desc;
212       }
213       fclose ($fh);
215       $desc= trim(preg_replace('/^DESC:\s*/', '', $line));
216     }
218     return $desc;
219   }
222   function execute()
223   {
224     /* Call parent execute */
225     plugin::execute();
227     /* Initialise vars */
229     /* Load templating engine */
230     $smarty= get_smarty();
231     $display= "";
233     /* Get available mailserver */
234     $mailserver= array();
235     foreach ($this->config->data['SERVERS']['IMAP'] as $key => $val){
236       $mailserver[]= $key;
237     }
240     /* 
241      * Sieve Management 
242      */
243     if(isset($_POST['sieveManagement'])) {
244       $this->dialog = new sieveManagement($this->config,$this->dn,$this);
245     }
246    
247     /* Cancel sieve edit */
248     if(isset($_POST['sieve_cancel'])){
249       $this->dialog = NULL;
250     }
251  
252     /* Save sieve changes */
253     if(isset($_POST['sieve_finish'])){
254       if($this->dialog->save()){
255         $this->dialog = NULL;
256       }
257     }
258  
259     if(is_object($this->dialog)){
260       $this->dialog->save_object();
261       return($this->dialog->execute());
262     } 
272     /* Handle account state */
273     /* Do we need to flip is_account state? */
274     if(isset($_POST['modify_state'])){
275       if($this->is_account && $this->acl_is_removeable()){
276         $this->is_account= FALSE;
277       }elseif(!$this->is_account && $this->acl_is_createable()){
278         $this->is_account= TRUE;
279       }
280     }
282     /* Do we represent a valid account? */
283     if (!$this->is_account && $this->parent == NULL){
284       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
285         _("This account has no mail extensions.")."</b>";
287       $display.= back_to_main();
288       return ($display);
289     }
291     /* Show tab dialog headers */
292     if ($this->parent != NULL){
293       if ($this->is_account){
294         if($this->accountDelegationsConfigured()){
295           $display= $this->show_disable_header(_("Remove mail account"),
296               _("This account can't be removed while there are delegations configured. Remove those delegations first."),TRUE,TRUE);
297         }else{
298           $display= $this->show_disable_header(_("Remove mail account"),
299               _("This account has mail features enabled. You can disable them by clicking below."));
300         }
301       } else {
302         $display= $this->show_enable_header(_("Create mail account"), _("This account has mail features disabled. You can enable them by clicking below."));
303         return ($display);
304       }
305     }
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'])){
325       /* Check if we are able to write gosaMailForwardingAddress */
326       if($this->acl_is_writeable("gosaMailForwardingAddress")){
328         /* Walk through list of forwarders, ignore own addresses */
329         foreach ($_POST['local_list'] as $val){
330           if (!in_array ($val, $this->gosaMailAlternateAddress) &&
331               $val != $this->mail){
333             $this->addForwarder($val);
334             $this->is_modified= TRUE;
335           }
336         }
337       }
338       $this->forward_dialog= FALSE;
339       $this->dialog= FALSE;
340     }
342     /* Add forward email addresses */
343     if (isset($_POST['add_forwarder'])){
344       if ($_POST['forward_address'] != ""){
346         /* Valid email address specified? */
347         $address= $_POST['forward_address'];
348         $valid= FALSE;
349         if (!is_email($address)){
350           if (!is_email($address, TRUE)){
351             if ($this->is_template){
352               $valid= TRUE;
353             } else {
354               print_red (_("You're trying to add an invalid email address to the list of forwarders."));
355             }
356           }
357         } elseif ($address == $this->mail
358             || in_array($address, $this->gosaMailAlternateAddress)) {
360           print_red (_("Adding your one of your own addresses to the forwarders makes no sense."));
362         } else {
363           $valid= TRUE;
364         }
366         if ($valid){
368           /* Add it, if we are able to write gosaMailForwardingAddress */
369           if($this->acl_is_writeable("gosaMailForwardingAddress")){
370             $this->addForwarder ($address);
371             $this->is_modified= TRUE;
372           }
373         }
374       }
375     }
377     /* Delete forward email addresses */
378     if (isset($_POST['delete_forwarder'])){
379       $this->delForwarder ($_POST['forwarder_list']);
380     }
383     /* Add alternate email addresses */
384     if (isset($_POST['add_alternate'])){
386       $valid= FALSE;
387       if (!is_email($_POST['alternate_address'])){
388         if ($this->is_template){
389           if (!(is_email($_POST['alternate_address'], TRUE))){
390             print_red (_("You're trying to add an invalid email address to the list of alternate addresses."));
391           } else {
392             $valid= TRUE;
393           }
394         } else {
395           print_red (_("You're trying to add an invalid email address to the list of alternate addresses."));
396         }
398       } else {
399         $valid= TRUE;
400       }
402       if ($valid && ($user= $this->addAlternate ($_POST['alternate_address'])) != ""){
403         $ui= get_userinfo();
404         if ($user != $ui->username){
405           print_red (_("The address you're trying to add is already used by user")." '$user'.");
406         }
407       }
408     }
410     /* Delete alternate email addresses */
411     if (isset($_POST['delete_alternate']) && isset($_POST['alternates_list'])){
412       $this->delAlternate ($_POST['alternates_list']);
413     }
415   
416     /* Vacation message */
417   
418     /* Import vacation message? */
419     if (isset($_POST["import_vacation"]) && isset($this->vacation[$_POST["vacation_template"]])){
420       $contents= "";
421       $lines= file($_POST["vacation_template"]);
422       foreach ($lines as $line){
423         if (!preg_match('/^DESC:/', $line)){
424           $contents.= $line;
425         }
426       }
428       /* Replace attributes */
429       $attrs= $this->parent->by_object['user']->attributes;
430       foreach ($attrs as $val){
431         
432         if(preg_match("/dateOfBirth/",$val)){
433           if($this->parent->by_object['user']->use_dob){
434             $contents= preg_replace("/%$val/",date("Y-d-m",$this->parent->by_object['user']->dateOfBirth),$contents);
435           }
436         }else {
437           $contents= preg_replace("/%$val/",
438               $this->parent->by_object['user']->$val, $contents);
439         }
440       }
442       /* Save message */
443       $this->gosaVacationMessage= htmlspecialchars($contents);
444     }
446   
447     /* Display forward dialog if requested above */
449     /* Show forward add dialog */
450     if ($this->forward_dialog){
451       $ldap= $this->config->get_ldap_link();
453       /* Save data */
454       $mailfilter= get_global("mailfilter");
455       foreach( array("depselect", "muser", "regex") as $type){
456         if (isset($_POST[$type])){
457           $mailfilter[$type]= $_POST[$type];
458         }
459       }
460       if (isset($_GET['search'])){
461         $s= mb_substr($_GET['search'], 0, 1, "UTF8")."*";
462         if ($s == "**"){
463           $s= "*";
464         }
465         $mailfilter['regex']= $s;
466       }
467       register_global("mailfilter", $mailfilter);
469       /* Get actual list */
470       $mailusers= array ();
471       if ($mailfilter['regex'] != '*' && $mailfilter['regex'] != ""){
472         $regex= $mailfilter['regex'];
473         $filter= "(|(mail=$regex)(gosaMailAlternateAddress=$regex))";
474       } else {
475         $filter= "";
476       }
477       if ($mailfilter['muser'] != ""){
478         $user= $mailfilter['muser'];
479         $filter= "$filter(|(uid=$user)(cn=$user)(givenName=$user)(sn=$user))";
480       }
482       /* Add already present people to the filter */
483       $exclude= "";
484       foreach ($this->gosaMailForwardingAddress as $mail){
485         $exclude.= "(mail=$mail)";
486       }
487       if ($exclude != ""){
488         $filter.= "(!(|$exclude))";
489       }
491       $res= get_list("(&(objectClass=gosaMailAccount)$filter)", "users", $mailfilter['depselect'], 
492                      array("sn", "mail", "givenName"), GL_SIZELIMIT | GL_SUBSEARCH);
493       $ldap->cd($mailfilter['depselect']);
494       $ldap->search ("(&(objectClass=gosaMailAccount)$filter)", array("sn", "mail", "givenName"));
495       error_reporting (0);
496       while ($attrs= $ldap->fetch()){
497         if(preg_match('/%/', $attrs['mail'][0])){
498           continue;
499         }
500         $name= $this->make_name($attrs);
501         $mailusers[$attrs['mail'][0]]= $name."&lt;".
502           $attrs['mail'][0]."&gt;";
503       }
504       error_reporting (E_ALL);
505       natcasesort ($mailusers);
506       reset ($mailusers);
508       /* Show dialog */
509       $smarty->assign("search_image", get_template_path('images/search.png'));
510       $smarty->assign("usearch_image", get_template_path('images/search_user.png'));
511       $smarty->assign("tree_image", get_template_path('images/tree.png'));
512       $smarty->assign("infoimage", get_template_path('images/info.png'));
513       $smarty->assign("launchimage", get_template_path('images/small_filter.png'));
514       $smarty->assign("mailusers", $mailusers);
515       if (isset($_POST['depselect'])){
516         $smarty->assign("depselect", $_POST['depselect']);
517       }
518       $smarty->assign("deplist", $this->config->idepartments);
519       $smarty->assign("apply", apply_filter());
520       $smarty->assign("alphabet", generate_alphabet());
521       $smarty->assign("hint", print_sizelimit_warning());
522       foreach( array("depselect", "muser", "regex") as $type){
523         $smarty->assign("$type", $mailfilter[$type]);
524       }
525       $smarty->assign("hint", print_sizelimit_warning());
527       $display.= $smarty->fetch (get_template_path('mail_locals.tpl', TRUE, dirname(__FILE__)));
528       return ($display);
529     }
531     /* Display mail account tab */
533     $smarty->assign("mailServers", $mailserver);
534     $SkipWrite = (!isset($this->parent) || !$this->parent) && !isset($_SESSION['edit']);
536     $tmp  = $this->plInfo();
537     foreach($tmp['plProvidedAcls'] as $name => $transl){
538       $smarty->assign("$name"."ACL", $this->getacl($name,$SkipWrite));
539     }
541     foreach(array("gosaMailServer", "gosaMailQuota", "perms", "mail",
542           "gosaMailAlternateAddress", "gosaMailForwardingAddress",
543           "gosaVacationMessage", "gosaMailDeliveryMode",
544           "gosaMailMaxSize", "gosaSpamSortLevel", "gosaSpamMailbox") as $val){
545       $smarty->assign("$val", $this->$val);
546     }
548     if (is_numeric($this->gosaMailQuota) && $this->gosaMailQuota != 0){
549       $smarty->assign("quotausage", progressbar(round(($this->quotaUsage * 100)/ $this->gosaMailQuota),100,15,true));
550       $smarty->assign("quotadefined", "true");
551     } else {
552       $smarty->assign("quotadefined", "false");
553     }
555     /* Disable mail field if needed */
556     $method= new $this->method($this->config);
557     if ($method->uattrib == "mail" && $this->initially_was_account){
558       $smarty->assign("mailACL", preg_replace("/w/","",$this->getacl("mail",$SkipWrite)));
559     }
562     if (!preg_match("/L/", $this->gosaMailDeliveryMode)) {
563       $smarty->assign("only_local", "checked");
564     } else {
565       $smarty->assign("only_local", "");
566     }
568     $types = array(
569           "V"=>"use_vacation",
570           "S"=>"use_spam_filter",
571           "R"=>"use_mailsize_limit",
572           "I"=>"drop_own_mails",
573           "C"=>"own_script");
575     /* Fill checkboxes */
576     foreach($types as $option => $varname){
577       if (preg_match("/".$option."/", $this->gosaMailDeliveryMode)) {
578         $smarty->assign($varname, "checked");
579       } else {
580         $smarty->assign($varname, "");
581       }
582     }
583     
584     /* Have vacation templates? */
585     $smarty->assign("template", "");
586     if (count($this->vacation)){
587       $smarty->assign("show_templates", "true");
588       $smarty->assign("vacationtemplates", $this->vacation);
589       if (isset($_POST['vacation_template'])){
590         $smarty->assign("template", $_POST['vacation_template']);
591       }
592     } else {
593       $smarty->assign("show_templates", "false");
594     }
596     /* Fill spam selector */
597     $spamlevel= array();
598     for ($i= 0; $i<21; $i++){
599       $spamlevel[]= $i;
600     }
601     $smarty->assign("spamlevel", $spamlevel);
602     $smarty->assign("spambox", $this->mailboxList);
604     $display.= $smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
605     return ($display);
606   }
609   /* remove object from parent */
610   function remove_from_parent()
611   {
612     /* Cancel if there's nothing to do here */
613     if (!$this->initially_was_account){
614       return;
615     }
616     
617     /* include global link_info */
618     $ldap= $this->config->get_ldap_link();
620     /* Remove and write to LDAP */
621     plugin::remove_from_parent();
623     /* Zero arrays */
624     $this->attrs['gosaMailAlternateAddress']= array();
625     $this->attrs['gosaMailForwardingAddress']= array();
627     /* Adapt attributes if needed */
628     $method= new $this->method($this->config);
629     $method->fixAttributesOnRemove($this);
631     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,$this->attributes, "Save");
632     $ldap->cd($this->dn);
633     $this->cleanup();
634     $ldap->modify ($this->attrs); 
636     show_ldap_error($ldap->get_error(), sprintf(_("Removing of user/mail account with dn '%s' failed."),$this->dn));
638     /* Connect to IMAP server for account deletion */
639     if ($this->gosaMailServer != ""){
640       $method= new $this->method($this->config);
641       $id= $method->uattrib;
642       if ($method->connect($this->gosaMailServer)){
644         /* Remove account from IMAP server */
645         $method->deleteMailbox($this->folder_prefix.$this->$id);
646         $method->disconnect();
647       }
648     }
650     /* Optionally execute a command after we're done */
651     $this->handle_post_events("remove",array("uid" => $this->uid));
652   }
654   
655   /* check if we have some delegations configured, those delegations must be removed first */
656   function accountDelegationsConfigured()
657   { 
658     /* We are in administrational edit mode.
659         Check tab configurations directly */
660     if(isset($this->attrs)){
661       $checkArray  = array("kolabInvitationPolicy","unrestrictedMailSize", "calFBURL","kolabDelegate","kolabFreeBusyFuture");
662       foreach($checkArray as $index){
663         if(isset($this->attrs[$index])){
664            return(true);
665         }
666       }
667     }
668     return(false); 
669   }
670  
672   /* Save data to object */
673   function save_object()
674   {
675     if (isset($_POST['mailTab'])){
676       /* Save ldap attributes */
677       plugin::save_object();
679       /* Assemble mail delivery mode
680          The mode field in ldap consists of values between braces, this must
681          be called when 'mail' is set, because checkboxes may not be set when
682          we're in some other dialog.
684          Example for gosaMailDeliveryMode [LR        ]
685          L: Local delivery
686          R: Reject when exceeding mailsize limit
687          S: Use spam filter
688          V: Use vacation message
689          C: Use custm sieve script
690          I: Only insider delivery */
692       $tmp= preg_replace("/[^a-z]/i","",$this->gosaMailDeliveryMode);
695       /* Handle delivery flags */
696       if($this->acl_is_writeable("gosaMailDeliveryModeL")){
697         if(!preg_match("/L/",$tmp) && !isset($_POST['only_local'])){
698           $tmp.="L";
699         }elseif(preg_match("/L/",$tmp) && isset($_POST['only_local'])){
700           $tmp = preg_replace("/L/","",$tmp);
701         }
702       }
704       $opts = array(     
705           "R"   => "use_mailsize_limit",
706           "S"   => "use_spam_filter",
707           "V"   => "use_vacation",
708           "C"   => "own_script",
709           "I"   => "drop_own_mails");
711       foreach($opts as $flag => $post){
712         if($this->acl_is_writeable("gosaMailDeliveryMode".$flag)){
713           if(!preg_match("/".$flag."/",$tmp) && isset($_POST[$post])){
714             $tmp.= $flag;
715           }elseif(preg_match("/".$flag."/",$tmp) && !isset($_POST[$post])){
716             $tmp = preg_replace("/".$flag."/","",$tmp);
717           }
718         }
719       }
721       $tmp= "[$tmp]";
722       if ($this->gosaMailDeliveryMode != $tmp){
723         $this->is_modified= TRUE;
724       }
725       $this->gosaMailDeliveryMode= $tmp;
726     }
727   }
730   /* Save data to LDAP, depending on is_account we save or delete */
731   function save()
732   {
733     $ldap= $this->config->get_ldap_link();
735     /* Call parents save to prepare $this->attrs */
736     plugin::save();
738     /* Save arrays */
739     $this->attrs['gosaMailAlternateAddress']= $this->gosaMailAlternateAddress;
740     $this->attrs['gosaMailForwardingAddress']= $this->gosaMailForwardingAddress;
742     /* Adapt attributes if needed */
743     $method= new $this->method($this->config);
744     $id= $method->uattrib;
746     $method->fixAttributesOnStore($this);
748     /* Remove Mailquota if = "" or "0"  */
749     if((isset($this->attrs['gosaMailQuota']))&&(!$this->attrs['gosaMailQuota'])) {
750       $this->attrs['gosaMailQuota']=0;
751     }
753     if(empty($this->attrs['gosaSpamMailbox'])){
754       unset($this->attrs['gosaSpamMailbox']);
755     }
757     $this->attrs['mail'] = strtolower($this->attrs['mail']); 
759     /* Save data to LDAP */
760     $ldap->cd($this->dn);
761     $this->cleanup();
762     $ldap->modify ($this->attrs); 
764     show_ldap_error($ldap->get_error(), sprintf(_("Saving of user/mail account with dn '%s' failed."),$this->dn));
766     /* Only do IMAP actions if we are not a template */
767     if (!$this->is_template){
769       if ($method->connect($this->gosaMailServer)){
770         $method->updateMailbox($this->folder_prefix.$this->$id);
771         
772         $method->setQuota($this->folder_prefix.$this->$id, $this->gosaMailQuota);
773         $method->disconnect();
775         /* Ensure that this is an existing account */
776         if($this->initially_was_account){
778           /* Write sieve information only if not in C mode */
779           if (!is_integer(strpos($this->gosaMailDeliveryMode, "C"))){
780             $method->configureFilter($this->$id,
781                 $this->gosaMailDeliveryMode,
782                 $this->mail,
783                 $this->gosaMailAlternateAddress,
784                 $this->gosaMailMaxSize,
785                 $this->gosaSpamMailbox,
786                 $this->gosaSpamSortLevel,
787                 $this->gosaVacationMessage);
788           }
789         }
790       }
791     }
793     /* Optionally execute a command after we're done */
794     if ($this->initially_was_account == $this->is_account){
795       if ($this->is_modified){
796         $this->handle_post_events("modify", array("uid" => $this->uid));
797       }
798     } else {
799       $this->handle_post_events("add", array("uid" => $this->uid));
800     }
802   }
805   /* Check formular input */
806   function check()
807   {
808     if(!$this->is_account) return(array());
810     $ldap= $this->config->get_ldap_link();
812     /* Call common method to give check the hook */
813     $message= plugin::check();
815     if(empty($this->gosaMailServer)){
816       $message[]= _("There is no valid mailserver specified, please add one in the system setup.");
817     }
819     /* must: mail */
820     if ($this->mail == ""){
821       $message[]= _("The required field 'Primary address' is not set.");
822     }
823     if ($this->is_template){
824       if (!is_email($this->mail, TRUE)){
825         $message[]= _("Please enter a valid email address in 'Primary address' field.");
826       }
827     } else {
828       if (!is_email($this->mail)){
829         $message[]= _("Please enter a valid email address in 'Primary address' field.");
830       }
831     }
832     $ldap->cd($this->config->current['BASE']);
833     $ldap->search ("(&(!(objectClass=gosaUserTemplate))(objectClass=gosaMailAccount)(|(mail=".$this->mail.")(gosaMailAlternateAddress=".$this->mail."))(!(uid=".$this->uid."))(!(cn=".$this->uid.")))", array("uid"));
834     if ($ldap->count() != 0){
835       $message[]= _("The primary address you've entered is already in use.");
836     }
838     /* Check quota */
839     if ($this->gosaMailQuota != '' && $this->acl_is_writeable("gosaMailQuota")){
840       if (!is_numeric($this->gosaMailQuota)) {
841         $message[]= _("Value in 'Quota size' is not valid.");
842       } else {
843         $this->gosaMailQuota= (int) $this->gosaMailQuota;
844       }
845     }
847     /* Check rejectsize for integer */
848     if ($this->gosaMailMaxSize != '' && $this->acl_is_writeable("gosaMailMaxSize")){
849       if (!is_numeric($this->gosaMailMaxSize)){
850         $message[]= _("Please specify a vaild mail size for mails to be rejected.");
851       } else {
852         $this->gosaMailMaxSize= (int) $this->gosaMailMaxSize;
853       }
854     }
856     /* Need gosaMailMaxSize if use_mailsize_limit is checked */
857     if (is_integer(strpos($this->gosaMailDeliveryMode, "R")) && 
858         $this->gosaMailMaxSize == ""){
860       $message[]= _("You need to set the maximum mail size in order to reject anything.");
861     }
863     if((preg_match("/S/", $this->gosaMailDeliveryMode))&&(empty($this->gosaSpamMailbox))) {
864       $message[]= _("You specified Spam settings, but there is no Folder specified.");
865     }
867     return ($message);
868   }
871   /* Adapt from template, using 'dn' */
872   function adapt_from_template($dn)
873   {
874     plugin::adapt_from_template($dn);
876     foreach (array("gosaMailAlternateAddress", "gosaMailForwardingAddress") as $val){
877       $this->$val= array();
878       if (isset($this->attrs["$val"]["count"])){
879         for ($i= 0; $i<$this->attrs["$val"]["count"]; $i++){
880           $value= $this->attrs["$val"][$i];
881           foreach (array("sn", "givenName", "uid") as $repl){
882             if (preg_match("/%$repl/i", $value)){
883               $value= preg_replace ("/%$repl/i", $this->parent->$repl, $value);
884             }
885           }
886           array_push($this->$val, strtolower(rewrite($value)));
887         }
888       }
889     }
890     $this->mail= strtolower(rewrite($this->mail));
891   }
894   /* Add entry to forwarder list */
895   function addForwarder($address)
896   {
897     if($this->acl_is_writeable("gosaMailForwardingAddress")){
898       $this->gosaMailForwardingAddress[]= $address;
899       $this->gosaMailForwardingAddress= array_unique ($this->gosaMailForwardingAddress);
900       sort ($this->gosaMailForwardingAddress);
901       reset ($this->gosaMailForwardingAddress);
902       $this->is_modified= TRUE;
903     }else{
904       print_red(_("You are not allowed to write mail forwarding."));
905     }
906   }
909   /* Remove list of addresses from forwarder list */
910   function delForwarder($addresses)
911   {
912     if($this->acl_is_writeable("gosaMailForwardingAddress")){
913       $this->gosaMailForwardingAddress= array_remove_entries ($addresses, $this->gosaMailForwardingAddress);
914       $this->is_modified= TRUE;
915     }else{
916       print_red(_("You are not allowed to write mail forwarding."));
917     }
918   }
921   /* Add given mail address to the list of alternate adresses , 
922      check if this mal address is used, skip adding in this case */
923   function addAlternate($address)
924   {
925     if($this->acl_is_writeable("gosaMailAlternateAddress")){
926       $ldap= $this->config->get_ldap_link();
927       $address= strtolower($address);
929       /* Is this address already assigned in LDAP? */
930       $ldap->cd ($this->config->current['BASE']);
931       $ldap->search ("(&(objectClass=gosaMailAccount)(|(mail=$address)"."(gosaMailAlternateAddress=$address)))", array("uid"));
932       $ldap->search ("(&(!(objectClass=gosaUserTemplate))(objectClass=gosaMailAccount)(|(mail=$address)"."(gosaMailAlternateAddress=$address)))", array("uid"));
934       if ($ldap->count() > 0){
935         $attrs= $ldap->fetch ();
936         return ($attrs["uid"][0]);
937       }
939       /* Add to list of alternates */
940       if (!in_array($address, $this->gosaMailAlternateAddress)){
941         $this->gosaMailAlternateAddress[]= $address;
942         $this->is_modified= TRUE;
943       }
945       sort ($this->gosaMailAlternateAddress);
946       reset ($this->gosaMailAlternateAddress);
947       return ("");
948     }else{
949       print_red(_("You are not allowed to write mail alternate address."));
950     }
951   }
954   function delAlternate($addresses)
955   {
956     if($this->acl_is_writeable("gosaMailAlternateAddress")){
957       $this->gosaMailAlternateAddress= array_remove_entries ($addresses,$this->gosaMailAlternateAddress);
958       $this->is_modified= TRUE;
959     }else{
960       print_red(_("You are not allowed to write mail alternate address."));
961     }
962   }
964   function make_name($attrs)
965   {
966     $name= "";
967     if (isset($attrs['sn'][0])){
968       $name= $attrs['sn'][0];
969     }
970     if (isset($attrs['givenName'][0])){
971       if ($name != ""){
972         $name.= ", ".$attrs['givenName'][0];
973       } else {
974         $name.= $attrs['givenName'][0];
975       }
976     }
977     if ($name != ""){
978       $name.= " ";
979     }
981     return ($name);
982   }
984   
985   /* Create the mail part for the copy & paste dialog */
986   function getCopyDialog()
987   {
988     if(!$this->is_account) return("");
989     $smarty = get_smarty();
990     $smarty->assign("mail",$this->mail); 
991     $smarty->assign("gosaMailAlternateAddress",$this->gosaMailAlternateAddress);
992     $smarty->assign("gosaMailForwardingAddress",$this->gosaMailForwardingAddress);
993     $str = $smarty->fetch(get_template_path("copypaste.tpl",TRUE, dirname(__FILE__)));
995     $ret = array();
996     $ret['status'] = "";
997     $ret['string'] = $str;
998     return($ret);
999   }
1001   function saveCopyDialog()
1002   {
1003     if(!$this->is_account) return;  
1005     /* Execute to save mailAlternateAddress && gosaMailForwardingAddress */
1006     $this->execute();
1007     
1008     if(isset($_POST['mail'])){
1009       $this->mail = $_POST['mail'];
1010     }
1012   }
1014   function allow_remove()
1015   {
1016     if (isset($this->config->current['MAILMETHOD'])){
1017       $method= $this->config->current['MAILMETHOD'];
1018       if(preg_match("/olab/i",$method)){
1019         $ldap = $this->config->get_ldap_link();
1020         $ldap->cd($this->config->current['BASE']);
1021         $ldap->cat($this->dn);
1022         if($ldap->count()){
1023           $attrs = $ldap->fetch();
1024           if(isset($attrs['kolabDeleteFlag'])){ 
1025             return(_("Waiting for kolab to remove mail properties."));
1026           }elseif(in_array("gosaMailAccount",$attrs['objectClass'])){
1027             return(_("Please remove the mail account first, to allow kolab to call its remove methods."));
1028           }
1029         }
1030       }
1031     }
1032   }
1034    
1035   function PrepareForCopyPaste($source)
1036   {
1037     plugin::PrepareForCopyPaste($source);
1039     /* Reset alternate mail addresses */
1040     $this->gosaMailAlternateAddress = array();    
1041    }
1044   function plInfo()
1045   {
1046     return (array(
1047           "plShortName"     => _("Mail"),
1048           "plDescription"   => _("Mail settings"),
1049           "plSelfModify"    => TRUE,
1050           "plDepends"       => array("user"),                     // This plugin depends on
1051           "plPriority"      => 4,                                 // Position in tabs
1052           "plSection"     => array("personal" => _("My account")),
1053           "plCategory"    => array("users"),
1054           "plOptions"       => array(),
1055   
1056           "plProvidedAcls"  => array(
1057             "mail"                      =>  _("Mail address"),
1058             "gosaMailServer"            =>  _("Mail server"),
1059             "gosaMailQuota"             =>  _("Quota size"),
1061             "gosaMailDeliveryModeV"     =>  _("Add vacation information"),  // This is flag of gosaMailDeliveryMode
1062             "gosaVacationMessage"       =>  _("Vacation message"),
1064             "gosaMailDeliveryModeS"     =>  _("Use spam filter"),           // This is flag of gosaMailDeliveryMode
1065             "gosaSpamSortLevel"         =>  _("Spam level"),
1066             "gosaSpamMailbox"           =>  _("Spam mail box"),
1068             "gosaMailDeliveryModeR"     =>  _("Reject due to mailsize"),    // This is flag of gosaMailDeliveryMode
1069             "gosaMailMaxSize"           =>  _("Mail max size"),
1071             "gosaMailForwardingAddress" =>  _("Forwarding address"),
1072             "gosaMailDeliveryModeL"     =>  _("Local delivery"),            // This is flag of gosaMailDeliveryMode
1073             "gosaMailDeliveryModeI"     =>  _("No delivery to own mailbox "),     // This is flag of gosaMailDeliveryMode
1074             "gosaMailAlternateAddress"  =>  _("Mail alternative addresses"),
1076             "gosaMailForwardingAddress" =>  _("Forwarding address"),
1077             "gosaMailDeliveryModeC"     =>  _("Use custom sieve script"))   // This is flag of gosaMailDeliveryMode
1078         ));
1079   }
1082 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1083 ?>