Code

Prepared for multiple asterisk servers
[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   /* 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     }
239     /* Handle account state */
240     /* Do we need to flip is_account state? */
241     if(isset($_POST['modify_state'])){
242       if($this->is_account && $this->acl_is_removeable()){
243         $this->is_account= FALSE;
244       }elseif(!$this->is_account && $this->acl_is_createable()){
245         $this->is_account= TRUE;
246       }
247     }
249     /* Do we represent a valid account? */
250     if (!$this->is_account && $this->parent == NULL){
251       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
252         _("This account has no mail extensions.")."</b>";
254       $display.= back_to_main();
255       return ($display);
256     }
258     /* Show tab dialog headers */
259     if ($this->parent != NULL){
260       if ($this->is_account){
261         if($this->accountDelegationsConfigured()){
262           $display= $this->show_disable_header(_("Remove mail account"),
263               _("This account can't be removed while there are delegations configured. Remove those delegations first."),TRUE,TRUE);
264         }else{
265           $display= $this->show_disable_header(_("Remove mail account"),
266               _("This account has mail features enabled. You can disable them by clicking below."));
267         }
268       } else {
269         $display= $this->show_enable_header(_("Create mail account"), _("This account has mail features disabled. You can enable them by clicking below."));
270         return ($display);
271       }
272     }
275     /* Forwarder  subdialog */
277     /* Trigger forward add dialog? */
278     if (isset($_POST['add_local_forwarder'])){
279       $this->forward_dialog= TRUE;
280       $this->dialog= TRUE;
281     }
283     /* Cancel forward add dialog? */
284     if (isset($_POST['add_locals_cancel'])){
285       $this->forward_dialog= FALSE;
286       $this->dialog= FALSE;
287     }
289     /* Finished adding of locals? */
290     if (isset($_POST['add_locals_finish'])){
292       /* Check if we are able to write gosaMailForwardingAddress */
293       if($this->acl_is_writeable("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){
335           /* Add it, if we are able to write gosaMailForwardingAddress */
336           if($this->acl_is_writeable("gosaMailForwardingAddress")){
337             $this->addForwarder ($address);
338             $this->is_modified= TRUE;
339           }
340         }
341       }
342     }
344     /* Delete forward email addresses */
345     if (isset($_POST['delete_forwarder'])){
346       $this->delForwarder ($_POST['forwarder_list']);
347     }
350     /* Add alternate email addresses */
351     if (isset($_POST['add_alternate'])){
353       $valid= FALSE;
354       if (!is_email($_POST['alternate_address'])){
355         if ($this->is_template){
356           if (!(is_email($_POST['alternate_address'], TRUE))){
357             print_red (_("You're trying to add an invalid email address to the list of alternate addresses."));
358           } else {
359             $valid= TRUE;
360           }
361         } else {
362           print_red (_("You're trying to add an invalid email address to the list of alternate addresses."));
363         }
365       } else {
366         $valid= TRUE;
367       }
369       if ($valid && ($user= $this->addAlternate ($_POST['alternate_address'])) != ""){
370         $ui= get_userinfo();
371         if ($user != $ui->username){
372           print_red (_("The address you're trying to add is already used by user")." '$user'.");
373         }
374       }
375     }
377     /* Delete alternate email addresses */
378     if (isset($_POST['delete_alternate']) && isset($_POST['alternates_list'])){
379       $this->delAlternate ($_POST['alternates_list']);
380     }
382   
383     /* Vacation message */
384   
385     /* Import vacation message? */
386     if (isset($_POST["import_vacation"]) && isset($this->vacation[$_POST["vacation_template"]])){
387       $contents= "";
388       $lines= file($_POST["vacation_template"]);
389       foreach ($lines as $line){
390         if (!preg_match('/^DESC:/', $line)){
391           $contents.= $line;
392         }
393       }
395       /* Replace attributes */
396       $attrs= $this->parent->by_object['user']->attributes;
397       foreach ($attrs as $val){
398         $contents= preg_replace("/%$val/",
399             $this->parent->by_object['user']->$val, $contents);
400       }
402       /* Save message */
403       $this->gosaVacationMessage= htmlspecialchars($contents);
404     }
406   
407     /* Display forward dialog if requested above */
409     /* Show forward add dialog */
410     if ($this->forward_dialog){
411       $ldap= $this->config->get_ldap_link();
413       /* Save data */
414       $mailfilter= get_global("mailfilter");
415       foreach( array("depselect", "muser", "regex") as $type){
416         if (isset($_POST[$type])){
417           $mailfilter[$type]= $_POST[$type];
418         }
419       }
420       if (isset($_GET['search'])){
421         $s= mb_substr($_GET['search'], 0, 1, "UTF8")."*";
422         if ($s == "**"){
423           $s= "*";
424         }
425         $mailfilter['regex']= $s;
426       }
427       register_global("mailfilter", $mailfilter);
429       /* Get actual list */
430       $mailusers= array ();
431       if ($mailfilter['regex'] != '*' && $mailfilter['regex'] != ""){
432         $regex= $mailfilter['regex'];
433         $filter= "(|(mail=$regex)(gosaMailAlternateAddress=$regex))";
434       } else {
435         $filter= "";
436       }
437       if ($mailfilter['muser'] != ""){
438         $user= $mailfilter['muser'];
439         $filter= "$filter(|(uid=$user)(cn=$user)(givenName=$user)(sn=$user))";
440       }
442       /* Add already present people to the filter */
443       $exclude= "";
444       foreach ($this->gosaMailForwardingAddress as $mail){
445         $exclude.= "(mail=$mail)";
446       }
447       if ($exclude != ""){
448         $filter.= "(!(|$exclude))";
449       }
451       $res= get_list("(&(objectClass=gosaMailAccount)$filter)", "users", $mailfilter['depselect'], 
452                      array("sn", "mail", "givenName"), GL_SIZELIMIT | GL_SUBSEARCH);
453       $ldap->cd($mailfilter['depselect']);
454       $ldap->search ("(&(objectClass=gosaMailAccount)$filter)", array("sn", "mail", "givenName"));
455       error_reporting (0);
456       while ($attrs= $ldap->fetch()){
457         if(preg_match('/%/', $attrs['mail'][0])){
458           continue;
459         }
460         $name= $this->make_name($attrs);
461         $mailusers[$attrs['mail'][0]]= $name."&lt;".
462           $attrs['mail'][0]."&gt;";
463       }
464       error_reporting (E_ALL);
465       natcasesort ($mailusers);
466       reset ($mailusers);
468       /* Show dialog */
469       $smarty->assign("search_image", get_template_path('images/search.png'));
470       $smarty->assign("usearch_image", get_template_path('images/search_user.png'));
471       $smarty->assign("tree_image", get_template_path('images/tree.png'));
472       $smarty->assign("infoimage", get_template_path('images/info.png'));
473       $smarty->assign("launchimage", get_template_path('images/small_filter.png'));
474       $smarty->assign("mailusers", $mailusers);
475       if (isset($_POST['depselect'])){
476         $smarty->assign("depselect", $_POST['depselect']);
477       }
478       $smarty->assign("deplist", $this->config->idepartments);
479       $smarty->assign("apply", apply_filter());
480       $smarty->assign("alphabet", generate_alphabet());
481       $smarty->assign("hint", print_sizelimit_warning());
482       foreach( array("depselect", "muser", "regex") as $type){
483         $smarty->assign("$type", $mailfilter[$type]);
484       }
485       $smarty->assign("hint", print_sizelimit_warning());
487       $display.= $smarty->fetch (get_template_path('mail_locals.tpl', TRUE, dirname(__FILE__)));
488       return ($display);
489     }
491     /* Display mail account tab */
493     $smarty->assign("mailServers", $mailserver);
494     $SkipWrite = (!isset($this->parent) || !$this->parent) && !isset($_SESSION['edit']);
496     $tmp  = $this->plInfo();
497     foreach($tmp['plProvidedAcls'] as $name => $transl){
498       $smarty->assign("$name"."ACL", $this->getacl($name,$SkipWrite));
499     }
501     foreach(array("gosaMailServer", "gosaMailQuota", "perms", "mail",
502           "gosaMailAlternateAddress", "gosaMailForwardingAddress",
503           "gosaVacationMessage", "gosaMailDeliveryMode",
504           "gosaMailMaxSize", "gosaSpamSortLevel", "gosaSpamMailbox") as $val){
505       $smarty->assign("$val", $this->$val);
506     }
508     if (is_numeric($this->gosaMailQuota) && $this->gosaMailQuota != 0){
509       $smarty->assign("quotausage", progressbar(round(($this->quotaUsage * 100)/ $this->gosaMailQuota),100,15,true));
510       $smarty->assign("quotadefined", "true");
511     } else {
512       $smarty->assign("quotadefined", "false");
513     }
515     /* Disable mail field if needed */
516     $method= new $this->method($this->config);
517     if ($method->uattrib == "mail" && $this->initially_was_account){
518       $smarty->assign("mailACL", preg_replace("/w/","",$this->getacl("mail",$SkipWrite)));
519     }
522     if (!preg_match("/L/", $this->gosaMailDeliveryMode)) {
523       $smarty->assign("only_local", "checked");
524     } else {
525       $smarty->assign("only_local", "");
526     }
528     $types = array(
529           "V"=>"use_vacation",
530           "S"=>"use_spam_filter",
531           "R"=>"use_mailsize_limit",
532           "I"=>"drop_own_mails",
533           "C"=>"own_script");
535     /* Fill checkboxes */
536     foreach($types as $option => $varname){
537       if (preg_match("/".$option."/", $this->gosaMailDeliveryMode)) {
538         $smarty->assign($varname, "checked");
539       } else {
540         $smarty->assign($varname, "");
541       }
542     }
543     
544     /* Have vacation templates? */
545     $smarty->assign("template", "");
546     if (count($this->vacation)){
547       $smarty->assign("show_templates", "true");
548       $smarty->assign("vacationtemplates", $this->vacation);
549       if (isset($_POST['vacation_template'])){
550         $smarty->assign("template", $_POST['vacation_template']);
551       }
552     } else {
553       $smarty->assign("show_templates", "false");
554     }
556     /* Fill spam selector */
557     $spamlevel= array();
558     for ($i= 0; $i<21; $i++){
559       $spamlevel[]= $i;
560     }
561     $smarty->assign("spamlevel", $spamlevel);
562     $smarty->assign("spambox", $this->mailboxList);
564     $display.= $smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
565     return ($display);
566   }
569   /* remove object from parent */
570   function remove_from_parent()
571   {
572     /* Cancel if there's nothing to do here */
573     if (!$this->initially_was_account){
574       return;
575     }
576     
577     /* include global link_info */
578     $ldap= $this->config->get_ldap_link();
580     /* Remove and write to LDAP */
581     plugin::remove_from_parent();
583     /* Zero arrays */
584     $this->attrs['gosaMailAlternateAddress']= array();
585     $this->attrs['gosaMailForwardingAddress']= array();
587     /* Adapt attributes if needed */
588     $method= new $this->method($this->config);
589     $method->fixAttributesOnRemove($this);
591     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,$this->attributes, "Save");
592     $ldap->cd($this->dn);
593     $this->cleanup();
594     $ldap->modify ($this->attrs); 
596     show_ldap_error($ldap->get_error(), sprintf(_("Removing of user/mail account with dn '%s' failed."),$this->dn));
598     /* Connect to IMAP server for account deletion */
599     if ($this->gosaMailServer != ""){
600       $method= new $this->method($this->config);
601       $id= $method->uattrib;
602       if ($method->connect($this->gosaMailServer)){
604         /* Remove account from IMAP server */
605         $method->deleteMailbox($this->folder_prefix.$this->$id);
606         $method->disconnect();
607       }
608     }
610     /* Optionally execute a command after we're done */
611     $this->handle_post_events("remove",array("uid" => $this->uid));
612   }
614   
615   /* check if we have some delegations configured, those delegations must be removed first */
616   function accountDelegationsConfigured()
617   { 
618     /* We are in administrational edit mode.
619         Check tab configurations directly */
620     if(isset($this->attrs)){
621       $checkArray  = array("kolabInvitationPolicy","unrestrictedMailSize", "calFBURL","kolabDelegate","kolabFreeBusyFuture");
622       foreach($checkArray as $index){
623         if(isset($this->attrs[$index])){
624            return(true);
625         }
626       }
627     }
628     return(false); 
629   }
630  
632   /* Save data to object */
633   function save_object()
634   {
635     if (isset($_POST['mailTab'])){
636       /* Save ldap attributes */
637       plugin::save_object();
639       /* Assemble mail delivery mode
640          The mode field in ldap consists of values between braces, this must
641          be called when 'mail' is set, because checkboxes may not be set when
642          we're in some other dialog.
644          Example for gosaMailDeliveryMode [LR        ]
645          L: Local delivery
646          R: Reject when exceeding mailsize limit
647          S: Use spam filter
648          V: Use vacation message
649          C: Use custm sieve script
650          I: Only insider delivery */
652       $tmp= preg_replace("/[^a-z]/i","",$this->gosaMailDeliveryMode);
655       /* Handle delivery flags */
656       if($this->acl_is_writeable("gosaMailDeliveryModeL")){
657         if(!preg_match("/L/",$tmp) && !isset($_POST['only_local'])){
658           $tmp.="L";
659         }elseif(preg_match("/L/",$tmp) && isset($_POST['only_local'])){
660           $tmp = preg_replace("/L/","",$tmp);
661         }
662       }
664       $opts = array(     
665           "R"   => "use_mailsize_limit",
666           "S"   => "use_spam_filter",
667           "V"   => "use_vacation",
668           "C"   => "own_script",
669           "I"   => "drop_own_mails");
671       foreach($opts as $flag => $post){
672         if($this->acl_is_writeable("gosaMailDeliveryMode".$flag)){
673           if(!preg_match("/".$flag."/",$tmp) && isset($_POST[$post])){
674             $tmp.= $flag;
675           }elseif(preg_match("/".$flag."/",$tmp) && !isset($_POST[$post])){
676             $tmp = preg_replace("/".$flag."/","",$tmp);
677           }
678         }
679       }
681       $tmp= "[$tmp]";
682       if ($this->gosaMailDeliveryMode != $tmp){
683         $this->is_modified= TRUE;
684       }
685       $this->gosaMailDeliveryMode= $tmp;
686     }
687   }
690   /* Save data to LDAP, depending on is_account we save or delete */
691   function save()
692   {
693     $ldap= $this->config->get_ldap_link();
695     /* Call parents save to prepare $this->attrs */
696     plugin::save();
698     /* Save arrays */
699     $this->attrs['gosaMailAlternateAddress']= $this->gosaMailAlternateAddress;
700     $this->attrs['gosaMailForwardingAddress']= $this->gosaMailForwardingAddress;
702     /* Adapt attributes if needed */
703     $method= new $this->method($this->config);
704     $id= $method->uattrib;
706     $method->fixAttributesOnStore($this);
708     /* Remove Mailquota if = "" or "0"  */
709     if((isset($this->attrs['gosaMailQuota']))&&(!$this->attrs['gosaMailQuota'])) {
710       $this->attrs['gosaMailQuota']=0;
711     }
713     if(empty($this->attrs['gosaSpamMailbox'])){
714       unset($this->attrs['gosaSpamMailbox']);
715     }
717     $this->attrs['mail'] = strtolower($this->attrs['mail']); 
719     /* Save data to LDAP */
720     $ldap->cd($this->dn);
721     $this->cleanup();
722     $ldap->modify ($this->attrs); 
724     show_ldap_error($ldap->get_error(), sprintf(_("Saving of user/mail account with dn '%s' failed."),$this->dn));
726     /* Only do IMAP actions if we are not a template */
727     if (!$this->is_template){
729       if ($method->connect($this->gosaMailServer)){
730         $method->updateMailbox($this->folder_prefix.$this->$id);
731         
732         $method->setQuota($this->folder_prefix.$this->$id, $this->gosaMailQuota);
733         $method->disconnect();
735         /* Ensure that this is an existing account */
736         if($this->initially_was_account){
738           /* Write sieve information only if not in C mode */
739           if (!is_integer(strpos($this->gosaMailDeliveryMode, "C"))){
740             $method->configureFilter($this->$id,
741                 $this->gosaMailDeliveryMode,
742                 $this->mail,
743                 $this->gosaMailAlternateAddress,
744                 $this->gosaMailMaxSize,
745                 $this->gosaSpamMailbox,
746                 $this->gosaSpamSortLevel,
747                 $this->gosaVacationMessage);
748           }
749         }
750       }
751     }
753     /* Optionally execute a command after we're done */
754     if ($this->initially_was_account == $this->is_account){
755       if ($this->is_modified){
756         $this->handle_post_events("modify", array("uid" => $this->uid));
757       }
758     } else {
759       $this->handle_post_events("add", array("uid" => $this->uid));
760     }
762   }
765   /* Check formular input */
766   function check()
767   {
768     if(!$this->is_account) return(array());
770     $ldap= $this->config->get_ldap_link();
772     /* Call common method to give check the hook */
773     $message= plugin::check();
775     if(empty($this->gosaMailServer)){
776       $message[]= _("There is no valid mailserver specified, please add one in the system setup.");
777     }
779     /* must: mail */
780     if ($this->mail == ""){
781       $message[]= _("The required field 'Primary address' is not set.");
782     }
783     if ($this->is_template){
784       if (!is_email($this->mail, TRUE)){
785         $message[]= _("Please enter a valid email address in 'Primary address' field.");
786       }
787     } else {
788       if (!is_email($this->mail)){
789         $message[]= _("Please enter a valid email address in 'Primary address' field.");
790       }
791     }
792     $ldap->cd($this->config->current['BASE']);
793     $ldap->search ("(&(!(objectClass=gosaUserTemplate))(objectClass=gosaMailAccount)(|(mail=".$this->mail.")(gosaMailAlternateAddress=".$this->mail."))(!(uid=".$this->uid."))(!(cn=".$this->uid.")))", array("uid"));
794     if ($ldap->count() != 0){
795       $message[]= _("The primary address you've entered is already in use.");
796     }
798     /* Check quota */
799     if ($this->gosaMailQuota != '' && $this->acl_is_writeable("gosaMailQuota")){
800       if (!is_numeric($this->gosaMailQuota)) {
801         $message[]= _("Value in 'Quota size' is not valid.");
802       } else {
803         $this->gosaMailQuota= (int) $this->gosaMailQuota;
804       }
805     }
807     /* Check rejectsize for integer */
808     if ($this->gosaMailMaxSize != '' && $this->acl_is_writeable("gosaMailMaxSize")){
809       if (!is_numeric($this->gosaMailMaxSize)){
810         $message[]= _("Please specify a vaild mail size for mails to be rejected.");
811       } else {
812         $this->gosaMailMaxSize= (int) $this->gosaMailMaxSize;
813       }
814     }
816     /* Need gosaMailMaxSize if use_mailsize_limit is checked */
817     if (is_integer(strpos($this->gosaMailDeliveryMode, "R")) && 
818         $this->gosaMailMaxSize == ""){
820       $message[]= _("You need to set the maximum mail size in order to reject anything.");
821     }
823     if((preg_match("/S/", $this->gosaMailDeliveryMode))&&(empty($this->gosaSpamMailbox))) {
824       $message[]= _("You specified Spam settings, but there is no Folder specified.");
825     }
827     return ($message);
828   }
831   /* Adapt from template, using 'dn' */
832   function adapt_from_template($dn)
833   {
834     plugin::adapt_from_template($dn);
836     foreach (array("gosaMailAlternateAddress", "gosaMailForwardingAddress") as $val){
837       $this->$val= array();
838       if (isset($this->attrs["$val"]["count"])){
839         for ($i= 0; $i<$this->attrs["$val"]["count"]; $i++){
840           $value= $this->attrs["$val"][$i];
841           foreach (array("sn", "givenName", "uid") as $repl){
842             if (preg_match("/%$repl/i", $value)){
843               $value= preg_replace ("/%$repl/i", $this->parent->$repl, $value);
844             }
845           }
846           array_push($this->$val, strtolower(rewrite($value)));
847         }
848       }
849     }
850     $this->mail= strtolower(rewrite($this->mail));
851   }
854   /* Add entry to forwarder list */
855   function addForwarder($address)
856   {
857     if($this->acl_is_writeable("gosaMailForwardingAddress")){
858       $this->gosaMailForwardingAddress[]= $address;
859       $this->gosaMailForwardingAddress= array_unique ($this->gosaMailForwardingAddress);
860       sort ($this->gosaMailForwardingAddress);
861       reset ($this->gosaMailForwardingAddress);
862       $this->is_modified= TRUE;
863     }else{
864       print_red(_("You are not allowed to write mail forwarding."));
865     }
866   }
869   /* Remove list of addresses from forwarder list */
870   function delForwarder($addresses)
871   {
872     if($this->acl_is_writeable("gosaMailForwardingAddress")){
873       $this->gosaMailForwardingAddress= array_remove_entries ($addresses, $this->gosaMailForwardingAddress);
874       $this->is_modified= TRUE;
875     }else{
876       print_red(_("You are not allowed to write mail forwarding."));
877     }
878   }
881   /* Add given mail address to the list of alternate adresses , 
882      check if this mal address is used, skip adding in this case */
883   function addAlternate($address)
884   {
885     if($this->acl_is_writeable("gosaMailAlternateAddress")){
886       $ldap= $this->config->get_ldap_link();
887       $address= strtolower($address);
889       /* Is this address already assigned in LDAP? */
890       $ldap->cd ($this->config->current['BASE']);
891       $ldap->search ("(&(objectClass=gosaMailAccount)(|(mail=$address)"."(gosaMailAlternateAddress=$address)))", array("uid"));
893       if ($ldap->count() > 0){
894         $attrs= $ldap->fetch ();
895         return ($attrs["uid"][0]);
896       }
898       /* Add to list of alternates */
899       if (!in_array($address, $this->gosaMailAlternateAddress)){
900         $this->gosaMailAlternateAddress[]= $address;
901         $this->is_modified= TRUE;
902       }
904       sort ($this->gosaMailAlternateAddress);
905       reset ($this->gosaMailAlternateAddress);
906       return ("");
907     }else{
908       print_red(_("You are not allowed to write mail alternate address."));
909     }
910   }
913   function delAlternate($addresses)
914   {
915     if($this->acl_is_writeable("gosaMailAlternateAddress")){
916       $this->gosaMailAlternateAddress= array_remove_entries ($addresses,$this->gosaMailAlternateAddress);
917       $this->is_modified= TRUE;
918     }else{
919       print_red(_("You are not allowed to write mail alternate address."));
920     }
921   }
923   function make_name($attrs)
924   {
925     $name= "";
926     if (isset($attrs['sn'][0])){
927       $name= $attrs['sn'][0];
928     }
929     if (isset($attrs['givenName'][0])){
930       if ($name != ""){
931         $name.= ", ".$attrs['givenName'][0];
932       } else {
933         $name.= $attrs['givenName'][0];
934       }
935     }
936     if ($name != ""){
937       $name.= " ";
938     }
940     return ($name);
941   }
943   
944   /* Create the mail part for the copy & paste dialog */
945   function getCopyDialog()
946   {
947     if(!$this->is_account) return("");
948     $smarty = get_smarty();
949     $smarty->assign("mail",$this->mail); 
950     $smarty->assign("gosaMailAlternateAddress",$this->gosaMailAlternateAddress);
951     $smarty->assign("gosaMailForwardingAddress",$this->gosaMailForwardingAddress);
952     $str = $smarty->fetch(get_template_path("copypaste.tpl",TRUE, dirname(__FILE__)));
954     $ret = array();
955     $ret['status'] = "";
956     $ret['string'] = $str;
957     return($ret);
958   }
960   function saveCopyDialog()
961   {
962     if(!$this->is_account) return;  
964     /* Execute to save mailAlternateAddress && gosaMailForwardingAddress */
965     $this->execute();
966     
967     if(isset($_POST['mail'])){
968       $this->mail = $_POST['mail'];
969     }
971   }
973   function allow_remove()
974   {
975     if (isset($this->config->current['MAILMETHOD'])){
976       $method= $this->config->current['MAILMETHOD'];
977       if(preg_match("/kolab/i",$method)){
978         $ldap = $this->config->get_ldap_link();
979         $ldap->cd($this->config->current['BASE']);
980         $ldap->cat($this->dn);
981         if($ldap->count()){
982           $attrs = $ldap->fetch();
983           if(isset($attrs['kolabDeleteFlag'])){ 
984             return(_("Waiting for kolab to remove mail properties."));
985           }elseif(in_array("gosaMailAccount",$attrs['objectClass'])){
986             return(_("Please remove the mail account first, to allow kolab to call its remove methods."));
987           }
988         }
989       }
990     }
991   }
993    
994   function PrepareForCopyPaste($source)
995   {
996     plugin::PrepareForCopyPaste($source);
998     /* Reset alternate mail addresses */
999     $this->gosaMailAlternateAddress = array();    
1000    }
1003   function plInfo()
1004   {
1005     return (array(
1006           "plShortName"     => _("Mail"),
1007           "plDescription"   => _("Mail settings"),
1008           "plSelfModify"    => TRUE,
1009           "plDepends"       => array("user"),                     // This plugin depends on
1010           "plPriority"      => 4,                                 // Position in tabs
1011           "plSection"     => array("personal" => _("My account")),
1012           "plCategory"    => array("users" => array("description" => _("Mail account"),
1013                                                     "objectClass" => "gosaMailAccount")),
1014           "plOptions"       => array(),
1015   
1016           "plProvidedAcls"  => array(
1017             "mail"                      =>  _("Mail address"),
1018             "gosaMailServer"            =>  _("Mail server"),
1019             "gosaMailQuota"             =>  _("Quota size"),
1021             "gosaMailDeliveryModeV"     =>  _("Add vacation information"),  // This is flag of gosaMailDeliveryMode
1022             "gosaVacationMessage"       =>  _("Vacation message"),
1024             "gosaMailDeliveryModeS"     =>  _("Use spam filter"),           // This is flag of gosaMailDeliveryMode
1025             "gosaSpamSortLevel"         =>  _("Spam level"),
1026             "gosaSpamMailbox"           =>  _("Spam mail box"),
1028             "gosaMailDeliveryModeR"     =>  _("Reject due to mailsize"),    // This is flag of gosaMailDeliveryMode
1029             "gosaMailMaxSize"           =>  _("Mail max size"),
1031             "gosaMailForwardingAddress" =>  _("Forwarding address"),
1032             "gosaMailDeliveryModeL"     =>  _("Local delivery"),            // This is flag of gosaMailDeliveryMode
1033             "gosaMailDeliveryModeI"     =>  _("No delivery to own mailbox "),     // This is flag of gosaMailDeliveryMode
1034             "gosaMailAlternateAddress"  =>  _("Mail alternative addresses"),
1036             "gosaMailForwardingAddress" =>  _("Forwarding address"),
1037             "gosaMailDeliveryModeC"     =>  _("Use custom sieve script"))   // This is flag of gosaMailDeliveryMode
1038         ));
1039   }
1042 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1043 ?>