Code

4b6a7b9ef8e130f11c42f8b1fc75eaa551c82f95
[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 class mailAccount extends plugin
13 {
14   /* Definitions */
15   var $plHeadline         = "Mail";
16   var $plDescription      = "This does something";
17   var $method             = "mailMethod";
19   /* CLI vars */
20   var $gosaVacationStart                  = 0;
21   var $gosaVacationStop                   = 0;
22   var $view_logged = FALSE;
24   /* plugin specific values */
25   var $mail                               = "";
26   var $gosaMailAlternateAddress           = array();
27   var $gosaMailForwardingAddress          = array();
28   var $gosaMailDeliveryMode               = "[L        ]";
29   var $gosaMailServer                     = "";
30   var $gosaMailQuota                      = "";
31   var $gosaMailMaxSize                    = "";
32   var $gosaVacationMessage                = "";
33   var $gosaSpamSortLevel                  = "";
34   var $gosaSpamMailbox                    = "";
36   var $quotaUsage                         = 0;
37   var $forward_dialog                     = FALSE;
38   var $folder_prefix                      = "";
39   var $mailboxList                        = array("INBOX");
40   var $default_permissions                = "none";
41   var $member_permissions                 = "post";
42   var $members                            = array();
43   var $admins                             = array();
44   var $vacations                          = array();
45   var $perms                              = array(  "lrs"       => "read", 
46                                                     "lrsp"      => "post", 
47                                                     "lrsip"     => "append",
48                                                     "lrswipcd"  => "write", 
49                                                     "lrswipcda" => "all" );
51   /* attribute list for save action */
52   var $attributes= array("mail", "gosaMailServer", "gosaMailQuota", "gosaMailMaxSize","gosaMailForwardingAddress",
53       "gosaMailDeliveryMode", "gosaSpamSortLevel", "gosaSpamMailbox","gosaMailAlternateAddress","gosaVacationStart","gosaVacationStop",
54       "gosaVacationMessage", "gosaMailAlternateAddress", "gosaMailForwardingAddress");
55   var $objectclasses= array("gosaMailAccount");
56   var $uid              = "";
58   var $sieve_management = NULL;
60   /* constructor, if 'dn' is set, the node loads the given
61      'dn' from LDAP */
62   function mailAccount (&$config, $dn= NULL)
63   {
64     global $class_mapping;
66     /* Load bases attributes */
67     plugin::plugin($config, $dn);
69     /* Set uid */
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'];
85       $cls = get_correct_class_name("mailMethod$method");
86       if ($cls && class_exists($cls)){
87         $this->method= $cls;
88       } else {
89         print_red(sprintf(_("There is no mail method '%s' specified in your gosa.conf available."), $method));
90       }
91     }
93     
94     /* Create the account prefix  user. user/ 
95        Preset folder prefix. Will change it later to respect
96        altnamespace. */
97     if (isset($this->config->current['CYRUSUNIXSTYLE']) && $this->config->current['CYRUSUNIXSTYLE'] == "true"){
98       $this->folder_prefix= "user/";
99     }elseif (isset($this->config->data['MAIN']['CYRUSUNIXSTYLE']) && $this->config->data['MAIN']['CYRUSUNIXSTYLE'] == "true"){
100       $this->folder_prefix= "user/";
101     } else {
102       $this->folder_prefix= "user.";
103     }
104     
105     /* This is not a new account, parse additional attributes */
106     if (($dn !== NULL) && ($dn != "new") && $this->is_account){
108       /* Load attributes containing arrays */
109       foreach (array("gosaMailAlternateAddress", "gosaMailForwardingAddress") as $val){
110         $this->$val= array();
111         if (isset($this->attrs["$val"]["count"])){
112           for ($i= 0; $i<$this->attrs["$val"]["count"]; $i++){
113             array_push($this->$val, $this->attrs["$val"][$i]);
114           }
115         }
116       }
119       /* Only do IMAP actions if gosaMailServer attribute is set */
120       if (isset ($this->attrs["gosaMailServer"][0])){
122         $method = new $this->method($this->config);
123         $id     = $method->uattrib;
125         /* Adapt attributes if needed */
126         $method->fixAttributesOnLoad($this);
128         /* FixAttributesOnLoad possibly creates an array out of gosaMailServer.
129             If the mail tab wasn't opened once before saving, the account can't be saved */
130         if(is_array($this->gosaMailServer)){
131           $this->gosaMailServer = $this->gosaMailServer[0];
132         }
134         if ($method->connect($this->attrs["gosaMailServer"][0])){
136           /* Update quota values */
137           $quota= $method->getQuota($this->folder_prefix.$this->$id);
138          
139           if($quota){
140             if ($quota['gosaMailQuota'] == 2147483647){
141               $this->quotaUsage     = "";
142               $this->gosaMailQuota  = "";
143             } else {
144               $this->quotaUsage     = $quota['quotaUsage'];
145               $this->gosaMailQuota  = $quota['gosaMailQuota'];
146             }
147           }else{
148             $this->quotaUsage     = "";
149             $this->gosaMailQuota  = "";
150 //            print_red(sprintf(_("Can't get quota information for '%s'."),$this->folder_prefix.$this->$id));
151           }
153           /* Get mailboxes / folder like INBOX ..*/
154           $this->mailboxList= $method->getMailboxList($this->folder_prefix.$this->$id,$this->$id);
155           
156           $method->disconnect();
157         }else{
158           /* Could not connect to ldap.
159            */
160           if (isset($this->attrs['gosaMailQuota'][0])){
161             $this->gosaMailQuota = $this->attrs['gosaMailQuota'][0];
162           }
163         }
164       }
165     }
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     }
185     /* Create sieve management class */
186     $method = new $this->method($this->config);
187     $id     = $method->uattrib;
188     $this->sieve_management = new sieveManagement($this->config,$this->dn,$this,$id);
190     /* Get global filter config */
191     if (!is_global("mailfilter")){
192       $ui= get_userinfo();
193       $base= get_base_from_people($ui->dn);
194       $mailfilter= array( "depselect"       => $base,
195           "muser"            => "",
196           "regex"           => "*");
197       register_global("mailfilter", $mailfilter);
198     }
199   }
202   function parse_vacation($file)
203   {
204     $desc= "";
206     if (is_file($file)){
207       $fh = fopen($file, "r");
208       $line= fgets($fh, 256);
210       if (!preg_match('/^DESC:/', $line)){
211         print_red (_("No DESC tag in vacation file:")." $file");
212         return $desc;
213       }
214       fclose ($fh);
216       $desc= trim(preg_replace('/^DESC:\s*/', '', $line));
217     }
219     return $desc;
220   }
223   function execute()
224   {
225     /* Call parent execute */
226     plugin::execute();
228     /* Log view */
229     if($this->is_account && !$this->view_logged){
230       $this->view_logged = TRUE;
231       new log("view","users/".get_class($this),$this->dn);
232     }
234     /* Initialise vars */
236     /* Load templating engine */
237     $smarty= get_smarty();
238     $display= "";
240     /* Get available mailserver */
241     $mailserver= array();
242     foreach ($this->config->data['SERVERS']['IMAP'] as $key => $val){
243       $mailserver[]= $key;
244     }
246     /* 
247      * Sieve Management 
248      */
249     if(isset($_POST['sieveManagement']) 
250         && preg_match("/C/",$this->gosaMailDeliveryMode)
251         && $this->acl_is_writeable("sieveManagement")) {
253       $this->dialog = $this->sieve_management;
254     }
255    
256     /* Cancel sieve edit */
257     if(isset($_POST['sieve_cancel'])){
258       $this->dialog = FALSE;
259     }
260  
261     /* Save sieve changes */
262     if(isset($_POST['sieve_finish'])){
263       $this->sieve_management = $this->dialog;
264       $this->dialog = FALSE;
265     }
266  
267     if(is_object($this->dialog)){
268       $this->dialog->save_object();
269       return($this->dialog->execute());
270     } 
273     /* Handle account state */
274     /* Do we need to flip is_account state? */
275     if(isset($_POST['modify_state'])){
276       if($this->is_account && $this->acl_is_removeable()){
277         $this->is_account= FALSE;
278       }elseif(!$this->is_account && $this->acl_is_createable()){
279         $this->is_account= TRUE;
280       }
281     }
283     /* Do we represent a valid account? */
284     if (!$this->is_account && $this->parent === NULL){
285       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
286         _("This account has no mail extensions.")."</b>";
288       $display.= back_to_main();
289       return ($display);
290     }
292     /* Show tab dialog headers */
293     if ($this->parent !== NULL){
294       if ($this->is_account){
295         if($this->accountDelegationsConfigured()){
296           $display= $this->show_disable_header(_("Remove mail account"),
297               _("This account can't be removed while there are delegations configured. Remove those delegations first."),TRUE,TRUE);
298         }else{
299           $display= $this->show_disable_header(_("Remove mail account"),
300               _("This account has mail features enabled. You can disable them by clicking below."));
301         }
302       } else {
303         $display= $this->show_enable_header(_("Create mail account"), _("This account has mail features disabled. You can enable them by clicking below."));
304         return ($display);
305       }
306     }
309     /* Forwarder  subdialog */
311     /* Trigger forward add dialog? */
312     if (isset($_POST['add_local_forwarder'])){
313       $this->forward_dialog= TRUE;
314       $this->dialog= TRUE;
315     }
317     /* Cancel forward add dialog? */
318     if (isset($_POST['add_locals_cancel'])){
319       $this->forward_dialog= FALSE;
320       $this->dialog= FALSE;
321     }
323     /* Finished adding of locals? */
324     if (isset($_POST['add_locals_finish'])){
326       /* Check if we are able to write gosaMailForwardingAddress */
327       if($this->acl_is_writeable("gosaMailForwardingAddress")){
329         /* Walk through list of forwarders, ignore own addresses */
330         foreach ($_POST['local_list'] as $val){
331           if (!in_array ($val, $this->gosaMailAlternateAddress) &&
332               $val != $this->mail){
334             $this->addForwarder($val);
335             $this->is_modified= TRUE;
336           }
337         }
338       }
339       $this->forward_dialog= FALSE;
340       $this->dialog= FALSE;
341     }
343     /* Add forward email addresses */
344     if (isset($_POST['add_forwarder'])){
345       if ($_POST['forward_address'] != ""){
347         /* Valid email address specified? */
348         $address= $_POST['forward_address'];
349         $valid= FALSE;
350         if (!is_email($address)){
351           if (!is_email($address, TRUE)){
352             if ($this->is_template){
353               $valid= TRUE;
354             } else {
355               print_red (_("You're trying to add an invalid email address to the list of forwarders."));
356             }
357           }
358         } elseif ($address == $this->mail
359             || in_array($address, $this->gosaMailAlternateAddress)) {
361           print_red (_("Adding your one of your own addresses to the forwarders makes no sense."));
363         } else {
364           $valid= TRUE;
365         }
367         if ($valid){
369           /* Add it, if we are able to write gosaMailForwardingAddress */
370           if($this->acl_is_writeable("gosaMailForwardingAddress")){
371             $this->addForwarder ($address);
372             $this->is_modified= TRUE;
373           }
374         }
375       }
376     }
378     /* Delete forward email addresses */
379     if (isset($_POST['delete_forwarder'])){
380       $this->delForwarder ($_POST['forwarder_list']);
381     }
384     /* Add alternate email addresses */
385     if (isset($_POST['add_alternate'])){
387       $valid= FALSE;
388       if (!is_email($_POST['alternate_address'])){
389         if ($this->is_template){
390           if (!(is_email($_POST['alternate_address'], TRUE))){
391             print_red (_("You're trying to add an invalid email address to the list of alternate addresses."));
392           } else {
393             $valid= TRUE;
394           }
395         } else {
396           print_red (_("You're trying to add an invalid email address to the list of alternate addresses."));
397         }
399       } else {
400         $valid= TRUE;
401       }
403       if ($valid && ($user= $this->addAlternate ($_POST['alternate_address'])) != ""){
404         $ui= get_userinfo();
405         if ($user != $ui->username){
406           print_red (_("The address you're trying to add is already used by user")." '$user'.");
407         }
408       }
409     }
411     /* Delete alternate email addresses */
412     if (isset($_POST['delete_alternate']) && isset($_POST['alternates_list'])){
413       $this->delAlternate ($_POST['alternates_list']);
414     }
416   
417     /* Vacation message */
418   
419     /* Import vacation message? */
420     if (isset($_POST["import_vacation"]) && isset($this->vacation[$_POST["vacation_template"]])){
421       $contents= "";
422       $lines= file($_POST["vacation_template"]);
423       foreach ($lines as $line){
424         if (!preg_match('/^DESC:/', $line)){
425           $contents.= $line;
426         }
427       }
429       /* Replace attributes */
430       $attrs= $this->parent->by_object['user']->attributes;
431       foreach ($attrs as $val){
432         
433         if(preg_match("/dateOfBirth/",$val)){
434           if($this->parent->by_object['user']->use_dob){
435             $contents= preg_replace("/%$val/",date("Y-d-m",$this->parent->by_object['user']->dateOfBirth),$contents);
436           }
437         }else {
438           $contents= preg_replace("/%$val/",
439               $this->parent->by_object['user']->$val, $contents);
440         }
441         
442         /* Replace vacation start and end time */
443         if(preg_match("/%start/",$contents)){
444           $contents = preg_replace("/%start/",date("d.m.Y",$this->gosaVacationStart),$contents);
445         }
446         if(preg_match("/%end/",$contents)){
447           $contents = preg_replace("/%end/",date("d.m.Y",$this->gosaVacationStop),$contents);
448         }
449       }
451       /* Save message */
452       $this->gosaVacationMessage= htmlspecialchars($contents);
453     }
455   
456     /* Display forward dialog if requested above */
458     /* Show forward add dialog */
459     if ($this->forward_dialog){
460       $ldap= $this->config->get_ldap_link();
462       /* Save data */
463       $mailfilter= get_global("mailfilter");
464       foreach( array("depselect", "muser", "regex") as $type){
465         if (isset($_POST[$type])){
466           $mailfilter[$type]= $_POST[$type];
467         }
468       }
469       if (isset($_GET['search'])){
470         $s= mb_substr($_GET['search'], 0, 1, "UTF8")."*";
471         if ($s == "**"){
472           $s= "*";
473         }
474         $mailfilter['regex']= $s;
475       }
476       register_global("mailfilter", $mailfilter);
478       /* Get actual list */
479       $mailusers= array ();
480       if ($mailfilter['regex'] != '*' && $mailfilter['regex'] != ""){
481         $regex= $mailfilter['regex'];
482         $filter= "(|(mail=$regex)(gosaMailAlternateAddress=$regex))";
483       } else {
484         $filter= "";
485       }
486       if ($mailfilter['muser'] != ""){
487         $user= $mailfilter['muser'];
488         $filter= "$filter(|(uid=$user)(cn=$user)(givenName=$user)(sn=$user))";
489       }
491       /* Add already present people to the filter */
492       $exclude= "";
493       foreach ($this->gosaMailForwardingAddress as $mail){
494         $exclude.= "(mail=$mail)";
495       }
496       if ($exclude != ""){
497         $filter.= "(!(|$exclude))";
498       }
500       $res= get_list("(&(objectClass=gosaMailAccount)$filter)", "users", $mailfilter['depselect'], 
501                      array("sn", "mail", "givenName"), GL_SIZELIMIT | GL_SUBSEARCH);
502       $ldap->cd($mailfilter['depselect']);
503       $ldap->search ("(&(objectClass=gosaMailAccount)$filter)", array("sn", "mail", "givenName"));
504       error_reporting (0);
505       while ($attrs= $ldap->fetch()){
506         if(preg_match('/%/', $attrs['mail'][0])){
507           continue;
508         }
509         $name= $this->make_name($attrs);
510         $mailusers[$attrs['mail'][0]]= $name."&lt;".
511           $attrs['mail'][0]."&gt;";
512       }
513       error_reporting (E_ALL | E_STRICT);
514       natcasesort ($mailusers);
515       reset ($mailusers);
517       /* Show dialog */
518       $smarty->assign("search_image", get_template_path('images/search.png'));
519       $smarty->assign("usearch_image", get_template_path('images/search_user.png'));
520       $smarty->assign("tree_image", get_template_path('images/tree.png'));
521       $smarty->assign("infoimage", get_template_path('images/info.png'));
522       $smarty->assign("launchimage", get_template_path('images/small_filter.png'));
523       $smarty->assign("mailusers", $mailusers);
524       if (isset($_POST['depselect'])){
525         $smarty->assign("depselect", $_POST['depselect']);
526       }
527       $smarty->assign("deplist", $this->config->idepartments);
528       $smarty->assign("apply", apply_filter());
529       $smarty->assign("alphabet", generate_alphabet());
530       $smarty->assign("hint", print_sizelimit_warning());
531       foreach( array("depselect", "muser", "regex") as $type){
532         $smarty->assign("$type", $mailfilter[$type]);
533       }
534       $smarty->assign("hint", print_sizelimit_warning());
536       $display.= $smarty->fetch (get_template_path('mail_locals.tpl', TRUE, dirname(__FILE__)));
537       return ($display);
538     }
540     /* Display mail account tab */
542     $smarty->assign("mailServers", $mailserver);
543     $SkipWrite = (!isset($this->parent) || !$this->parent) && !isset($_SESSION['edit']);
545     $tmp  = $this->plInfo();
546     foreach($tmp['plProvidedAcls'] as $name => $transl){
547       $smarty->assign("$name"."ACL", $this->getacl($name,$SkipWrite));
548     }
550     foreach(array("gosaMailServer", "gosaMailQuota", "perms", "mail",
551           "gosaMailAlternateAddress", "gosaMailForwardingAddress",
552           "gosaVacationMessage", "gosaMailDeliveryMode", "gosaVacationStart",
553           "gosaVacationStop", "gosaMailMaxSize", "gosaSpamSortLevel", "gosaSpamMailbox") as $val){
554       $smarty->assign("$val", $this->$val);
555     }
557     if (is_numeric($this->gosaMailQuota) && $this->gosaMailQuota != 0){
558       $smarty->assign("quotausage", progressbar(round(($this->quotaUsage * 100)/ $this->gosaMailQuota),100,15,true));
559       $smarty->assign("quotadefined", "true");
560     } else {
561       $smarty->assign("quotadefined", "false");
562     }
564     /* Disable mail field if needed */
565     $method= new $this->method($this->config);
566     if ($method->uattrib == "mail" && $this->initially_was_account){
567       $smarty->assign("mailACL", preg_replace("/w/","",$this->getacl("mail",$SkipWrite)));
568     }
570     /* Disable/Enable range select, but do not disable them twice 
571      *  if they are already diabled by "use own sieve script"
572      */
573     if (preg_match('/V/', $this->gosaMailDeliveryMode) || preg_match("/C/",$this->gosaMailDeliveryMode)){
574       $smarty->assign('rangeEnabled', "");
575     } else {
576       $smarty->assign('rangeEnabled', "disabled");
577     }
579     if (!preg_match("/L/", $this->gosaMailDeliveryMode)) {
580       $smarty->assign("only_local", "checked");
581     } else {
582       $smarty->assign("only_local", "");
583     }
585     $types = array(
586           "V"=>"use_vacation",
587           "S"=>"use_spam_filter",
588           "R"=>"use_mailsize_limit",
589           "I"=>"drop_own_mails",
590           "C"=>"own_script");
592     /* Fill checkboxes */
593     foreach($types as $option => $varname){
594       if (preg_match("/".$option."/", $this->gosaMailDeliveryMode)) {
595         $smarty->assign($varname, "checked");
596       } else {
597         $smarty->assign($varname, "");
598       }
599     }
600    
601     /* Display mail account tab */
602     if($this->gosaVacationStart ==0){
603       $date= getdate(time());
604     }else{
605       $date= getdate($this->gosaVacationStart);
606     }
607     $days= array();
608     for($d= 1; $d<32; $d++){
609       $days[$d]= $d;
610     }
611     $years= array();
612     for($y= $date['year']-10; $y<$date['year']+10; $y++){
613       $years[]= $y;
614     }
615     $months= array(_("January"), _("February"), _("March"), _("April"),
616         _("May"), _("June"), _("July"), _("August"), _("September"),
617         _("October"), _("November"), _("December"));
618     $smarty->assign("start_day", $date["mday"]);
619     $smarty->assign("days", $days);
620     $smarty->assign("months", $months);
621     $smarty->assign("start_month", $date["mon"]-1);
622     $smarty->assign("years", $years);
623     $smarty->assign("start_year", $date["year"]);
625     if($this->gosaVacationStop ==0){
626       $date= getdate(time());
627       $date["mday"]++;
628     }else{
629       $date= getdate($this->gosaVacationStop);
630     }
631     $smarty->assign("end_day", $date["mday"]);
632     $smarty->assign("end_month", $date["mon"]-1);
633     $smarty->assign("end_year", $date["year"]);
636  
637     /* Have vacation templates? */
638     $smarty->assign("template", "");
639     if (count($this->vacation)){
640       $smarty->assign("show_templates", "true");
641       $smarty->assign("vacationtemplates", $this->vacation);
642       if (isset($_POST['vacation_template'])){
643         $smarty->assign("template", $_POST['vacation_template']);
644       }
645     } else {
646       $smarty->assign("show_templates", "false");
647     }
649     /* Fill spam selector */
650     $spamlevel= array();
651     for ($i= 0; $i<21; $i++){
652       $spamlevel[]= $i;
653     }
654     $smarty->assign("spamlevel", $spamlevel);
655     $smarty->assign("spambox", $this->mailboxList);
657     $display.= $smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
658     return ($display);
659   }
662   /* remove object from parent */
663   function remove_from_parent()
664   {
665     /* Cancel if there's nothing to do here */
666     if (!$this->initially_was_account){
667       return;
668     }
669     
670     /* include global link_info */
671     $ldap= $this->config->get_ldap_link();
673     /* Remove and write to LDAP */
674     plugin::remove_from_parent();
676     /* Zero arrays */
677     $this->attrs['gosaMailAlternateAddress']= array();
678     $this->attrs['gosaMailForwardingAddress']= array();
680     /* Adapt attributes if needed */
681     $method= new $this->method($this->config);
682     $method->fixAttributesOnRemove($this);
684     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,$this->attributes, "Save");
685     $ldap->cd($this->dn);
686     $this->cleanup();
688     $ldap->modify ($this->attrs); 
690     /* Add "view" to logging class */ 
691     new log("remove","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
693     show_ldap_error($ldap->get_error(), sprintf(_("Removing of user/mail account with dn '%s' failed."),$this->dn));
695     /* Connect to IMAP server for account deletion */
696     if ($this->gosaMailServer != ""){
697       $method= new $this->method($this->config);
698       $id= $method->uattrib;
699       if ($method->connect($this->gosaMailServer)){
701         /* Remove account from IMAP server */
702         $method->deleteMailbox($this->folder_prefix.$this->$id);
703         $method->disconnect();
704       }
705     }
707     /* Update shared folder membership, ACL may need to be updated */
708     $this->updateSharedFolder(); 
710     /* Optionally execute a command after we're done */
711     $this->handle_post_events("remove",array("uid" => $this->uid));
712   }
714   
715   /* check if we have some delegations configured, those delegations must be removed first */
716   function accountDelegationsConfigured()
717   { 
718     /* We are in administrational edit mode.
719         Check tab configurations directly */
720     if(isset($this->attrs)){
721       $checkArray  = array("kolabInvitationPolicy","unrestrictedMailSize", "calFBURL","kolabDelegate","kolabFreeBusyFuture");
722       foreach($checkArray as $index){
723         if(isset($this->attrs[$index])){
724            return(true);
725         }
726       }
727     }
728     return(false); 
729   }
730  
732   /* Save data to object */
733   function save_object()
734   {
735     if (isset($_POST['mailTab'])){
737       /* Save ldap attributes */
738       plugin::save_object();
741       if(isset($_POST['own_script'])){
743         if(!preg_match("/C/",$this->gosaMailDeliveryMode)){
744           $str= preg_replace("/[\[\]]/","",$this->gosaMailDeliveryMode);
745           $this->gosaMailDeliveryMode = "[".$str."C]";
746         }
748       }else{
750         /* Assemble mail delivery mode
751            The mode field in ldap consists of values between braces, this must
752            be called when 'mail' is set, because checkboxes may not be set when
753            we're in some other dialog.
755           Example for gosaMailDeliveryMode [LR        ]
756           L: Local delivery
757           R: Reject when exceeding mailsize limit
758           S: Use spam filter
759           V: Use vacation message
760           C: Use custm sieve script
761           I: Only insider delivery */
763         $tmp= preg_replace("/[^a-z]/i","",$this->gosaMailDeliveryMode);
766         /* Handle delivery flags */
767         if($this->acl_is_writeable("gosaMailDeliveryModeL")){
768           if(!preg_match("/L/",$tmp) && !isset($_POST['only_local'])){
769             $tmp.="L";
770           }elseif(preg_match("/L/",$tmp) && isset($_POST['only_local'])){
771             $tmp = preg_replace("/L/","",$tmp);
772           }
773         }
775         $opts = array(     
776             "R"   => "use_mailsize_limit",
777             "S"   => "use_spam_filter",
778             "V"   => "use_vacation",
779             "C"   => "own_script",
780             "I"   => "drop_own_mails");
782         foreach($opts as $flag => $post){
783           if($this->acl_is_writeable("gosaMailDeliveryMode".$flag)){
784             if(!preg_match("/".$flag."/",$tmp) && isset($_POST[$post])){
785               $tmp.= $flag;
786             }elseif(preg_match("/".$flag."/",$tmp) && !isset($_POST[$post])){
787               $tmp = preg_replace("/".$flag."/","",$tmp);
788             }
789           }
790         }
792         $tmp= "[$tmp]";
793         if ($this->gosaMailDeliveryMode != $tmp){
794           $this->is_modified= TRUE;
795         }
796         $this->gosaMailDeliveryMode= $tmp;
797       }
798     }
800   }
803   /* Save data to LDAP, depending on is_account we save or delete */
804   function save()
805   {
806     $ldap= $this->config->get_ldap_link();
808     /* Call parents save to prepare $this->attrs */
809     plugin::save();
811     /* Save arrays */
812     $this->attrs['gosaMailAlternateAddress']= $this->gosaMailAlternateAddress;
813     $this->attrs['gosaMailForwardingAddress']= $this->gosaMailForwardingAddress;
815     /* Adapt attributes if needed */
816     $method= new $this->method($this->config);
817     $id= $method->uattrib;
819     $method->fixAttributesOnStore($this);
821     /* Remove Mailquota if = "" or "0"  */
822     if((isset($this->attrs['gosaMailQuota']))&&(!$this->attrs['gosaMailQuota'])) {
823       $this->attrs['gosaMailQuota']=0;
824     }
826     if(empty($this->attrs['gosaSpamMailbox'])){
827       unset($this->attrs['gosaSpamMailbox']);
828     }
830     $this->attrs['mail'] = strtolower($this->attrs['mail']); 
832         /* Remove attributes - if not needed */
833     if (!preg_match('/V/', $this->gosaMailDeliveryMode)){
834       unset($this->attrs['gosaVacationStart']);
835       unset($this->attrs['gosaVacationStop']);
836     }
839     /* Remove attributes - if not needed */
840     if (!preg_match('/V/', $this->gosaMailDeliveryMode)){
841       unset($this->attrs['gosaVacationStart']);
842       unset($this->attrs['gosaVacationStop']);
843     }
845     /* Save data to LDAP */
846     $ldap->cd($this->dn);
847     $this->cleanup();
848     $ldap->modify ($this->attrs); 
850     show_ldap_error($ldap->get_error(), sprintf(_("Saving of user/mail account with dn '%s' failed."),$this->dn));
852     /* Log last action */ 
853     if($this->initially_was_account){
854       new log("modify","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
855     }else{
856       new log("create","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
857     }
859     /* Only do IMAP actions if we are not a template */
860     if (!$this->is_template){
862       if ($method->connect($this->gosaMailServer)){
863         $method->updateMailbox($this->folder_prefix.$this->$id);
864         
865         $method->setQuota($this->folder_prefix.$this->$id, $this->gosaMailQuota);
866         $method->disconnect();
868         /* Ensure that this is an existing account */
869         if(1==1 || $this->initially_was_account){
871           /* Write sieve information only if not in C mode */
872           if (!is_integer(strpos($this->gosaMailDeliveryMode, "C"))){
873             $method->configureFilter($this->$id,
874                 $this->gosaMailDeliveryMode,
875                 $this->mail,
876                 $this->gosaMailAlternateAddress,
877                 $this->gosaMailMaxSize,
878                 $this->gosaSpamMailbox,
879                 $this->gosaSpamSortLevel,
880                 $this->gosaVacationMessage);
881             $this->is_modified = TRUE;
882           }else{
883             $this->sieve_management->save();
884           }
885         }
886       }
887     }
889     /* Optionally execute a command after we're done */
890     if ($this->initially_was_account == $this->is_account){
891       if ($this->is_modified){
892         $this->handle_post_events("modify", array("uid" => $this->uid));
893       }
894     } else {
895       $this->handle_post_events("add", array("uid" => $this->uid));
896     }
898     $this->updateSharedFolder();
899   }
902   /* Check formular input */
903   function check()
904   {
905     if(!$this->is_account) return(array());
907     $ldap= $this->config->get_ldap_link();
909     /* Call common method to give check the hook */
910     $message= plugin::check();
912     if(empty($this->gosaMailServer)){
913       $message[]= _("There is no valid mailserver specified, please add one in the system setup.");
914     }
916     /* must: mail */
917     if ($this->mail == ""){
918       $message[]= _("The required field 'Primary address' is not set.");
919     }
920     if ($this->is_template){
921       if (!is_email($this->mail, TRUE)){
922         $message[]= _("Please enter a valid email address in 'Primary address' field.");
923       }
924     } else {
925       if (!is_email($this->mail)){
926         $message[]= _("Please enter a valid email address in 'Primary address' field.");
927       }
928     }
929     $ldap->cd($this->config->current['BASE']);
930     $ldap->search ("(&(!(objectClass=gosaUserTemplate))(objectClass=gosaMailAccount)(|(mail=".$this->mail.")(gosaMailAlternateAddress=".$this->mail."))(!(uid=".$this->uid."))(!(cn=".$this->uid.")))", array("uid"));
931     if ($ldap->count() != 0){
932       $message[]= _("The primary address you've entered is already in use.");
933     }
935     /* Check quota */
936     if ($this->gosaMailQuota != '' && $this->acl_is_writeable("gosaMailQuota")){
937       if (!is_numeric($this->gosaMailQuota)) {
938         $message[]= _("Value in 'Quota size' is not valid.");
939       } else {
940         $this->gosaMailQuota= (int) $this->gosaMailQuota;
941       }
942     }
944     /* Check rejectsize for integer */
945     if ($this->gosaMailMaxSize != '' && $this->acl_is_writeable("gosaMailMaxSize")){
946       if (!is_numeric($this->gosaMailMaxSize)){
947         $message[]= _("Please specify a vaild mail size for mails to be rejected.");
948       } else {
949         $this->gosaMailMaxSize= (int) $this->gosaMailMaxSize;
950       }
951     }
953     /* Need gosaMailMaxSize if use_mailsize_limit is checked */
954     if (is_integer(strpos($this->gosaMailDeliveryMode, "R")) && 
955         $this->gosaMailMaxSize == ""){
957       $message[]= _("You need to set the maximum mail size in order to reject anything.");
958     }
960     if((preg_match("/S/", $this->gosaMailDeliveryMode))&&(empty($this->gosaSpamMailbox))) {
961       $message[]= _("You specified Spam settings, but there is no Folder specified.");
962     }
964     if (preg_match('/V/', $this->gosaMailDeliveryMode) && $this->gosaVacationStart > $this->gosaVacationStop){
965       $message[]= _("Time interval to show vacation message is not valid.");
966     }
968     return ($message);
969   }
972   /* Adapt from template, using 'dn' */
973   function adapt_from_template($dn)
974   {
975     plugin::adapt_from_template($dn);
977     foreach (array("gosaMailAlternateAddress", "gosaMailForwardingAddress") as $val){
978       $this->$val= array();
979       if (isset($this->attrs["$val"]["count"])){
980         for ($i= 0; $i<$this->attrs["$val"]["count"]; $i++){
981           $value= $this->attrs["$val"][$i];
982           foreach (array("sn", "givenName", "uid") as $repl){
983             if (preg_match("/%$repl/i", $value)){
984               $value= preg_replace ("/%$repl/i", $this->parent->$repl, $value);
985             }
986           }
987           array_push($this->$val, strtolower(rewrite($value)));
988         }
989       }
990     }
991     $this->mail= strtolower(rewrite($this->mail));
992   }
995   /* Add entry to forwarder list */
996   function addForwarder($address)
997   {
998     if($this->acl_is_writeable("gosaMailForwardingAddress")){
999       $this->gosaMailForwardingAddress[]= $address;
1000       $this->gosaMailForwardingAddress= array_unique ($this->gosaMailForwardingAddress);
1001       sort ($this->gosaMailForwardingAddress);
1002       reset ($this->gosaMailForwardingAddress);
1003       $this->is_modified= TRUE;
1004     }else{
1005       print_red(_("You are not allowed to write mail forwarding."));
1006     }
1007   }
1010   /* Remove list of addresses from forwarder list */
1011   function delForwarder($addresses)
1012   {
1013     if($this->acl_is_writeable("gosaMailForwardingAddress")){
1014       $this->gosaMailForwardingAddress= array_remove_entries ($addresses, $this->gosaMailForwardingAddress);
1015       $this->is_modified= TRUE;
1016     }else{
1017       print_red(_("You are not allowed to write mail forwarding."));
1018     }
1019   }
1022   /* Add given mail address to the list of alternate adresses , 
1023      check if this mal address is used, skip adding in this case */
1024   function addAlternate($address)
1025   {
1026     if($this->acl_is_writeable("gosaMailAlternateAddress")){
1027       $ldap= $this->config->get_ldap_link();
1028       $address= strtolower($address);
1030       /* Is this address already assigned in LDAP? */
1031       $ldap->cd ($this->config->current['BASE']);
1032       $ldap->search ("(&(objectClass=gosaMailAccount)(|(mail=$address)"."(gosaMailAlternateAddress=$address)))", array("uid"));
1033       $ldap->search ("(&(!(objectClass=gosaUserTemplate))(objectClass=gosaMailAccount)(|(mail=$address)"."(gosaMailAlternateAddress=$address)))", array("uid"));
1035       if ($ldap->count() > 0){
1036         $attrs= $ldap->fetch ();
1037         return ($attrs["uid"][0]);
1038       }
1040       /* Add to list of alternates */
1041       if (!in_array($address, $this->gosaMailAlternateAddress)){
1042         $this->gosaMailAlternateAddress[]= $address;
1043         $this->is_modified= TRUE;
1044       }
1046       sort ($this->gosaMailAlternateAddress);
1047       reset ($this->gosaMailAlternateAddress);
1048       return ("");
1049     }else{
1050       print_red(_("You are not allowed to write mail alternate address."));
1051     }
1052   }
1055   function delAlternate($addresses)
1056   {
1057     if($this->acl_is_writeable("gosaMailAlternateAddress")){
1058       $this->gosaMailAlternateAddress= array_remove_entries ($addresses,$this->gosaMailAlternateAddress);
1059       $this->is_modified= TRUE;
1060     }else{
1061       print_red(_("You are not allowed to write mail alternate address."));
1062     }
1063   }
1065   function make_name($attrs)
1066   {
1067     $name= "";
1068     if (isset($attrs['sn'][0])){
1069       $name= $attrs['sn'][0];
1070     }
1071     if (isset($attrs['givenName'][0])){
1072       if ($name != ""){
1073         $name.= ", ".$attrs['givenName'][0];
1074       } else {
1075         $name.= $attrs['givenName'][0];
1076       }
1077     }
1078     if ($name != ""){
1079       $name.= " ";
1080     }
1082     return ($name);
1083   }
1085   
1086   /* Create the mail part for the copy & paste dialog */
1087   function getCopyDialog()
1088   {
1089     if(!$this->is_account) return("");
1090     $smarty = get_smarty();
1091     $smarty->assign("mail",$this->mail); 
1092     $smarty->assign("gosaMailAlternateAddress",$this->gosaMailAlternateAddress);
1093     $smarty->assign("gosaMailForwardingAddress",$this->gosaMailForwardingAddress);
1094     $str = $smarty->fetch(get_template_path("copypaste.tpl",TRUE, dirname(__FILE__)));
1096     $ret = array();
1097     $ret['status'] = "";
1098     $ret['string'] = $str;
1099     return($ret);
1100   }
1102   function saveCopyDialog()
1103   {
1104     if(!$this->is_account) return;  
1106     /* Execute to save mailAlternateAddress && gosaMailForwardingAddress */
1107     $this->execute();
1108     
1109     if(isset($_POST['mail'])){
1110       $this->mail = $_POST['mail'];
1111     }
1113   }
1115   function allow_remove()
1116   {
1117     if (isset($this->config->current['MAILMETHOD'])){
1118       $method= $this->config->current['MAILMETHOD'];
1119       if(preg_match("/olab/i",$method)){
1120         $ldap = $this->config->get_ldap_link();
1121         $ldap->cd($this->config->current['BASE']);
1122         $ldap->cat($this->dn);
1123         if($ldap->count()){
1124           $attrs = $ldap->fetch();
1125           if(isset($attrs['kolabDeleteFlag'])){ 
1126             return(_("Waiting for kolab to remove mail properties."));
1127           }elseif(in_array("gosaMailAccount",$attrs['objectClass'])){
1128             return(_("Please remove the mail account first, to allow kolab to call its remove methods."));
1129           }
1130         }
1131       }
1132     }
1133   }
1135    
1136   function PrepareForCopyPaste($source)
1137   {
1138     plugin::PrepareForCopyPaste($source);
1140     /* Reset alternate mail addresses */
1141     $this->gosaMailAlternateAddress = array();    
1142    }
1145   static function plInfo()
1146   {
1147     return (array(
1148           "plShortName"     => _("Mail"),
1149           "plDescription"   => _("Mail settings"),
1150           "plSelfModify"    => TRUE,
1151           "plDepends"       => array("user"),                     // This plugin depends on
1152           "plPriority"      => 4,                                 // Position in tabs
1153           "plSection"     => array("personal" => _("My account")),
1154           "plCategory"    => array("users"),
1155           "plOptions"       => array(),
1156   
1157           "plProvidedAcls"  => array(
1158             "mail"                      =>  _("Mail address"),
1159             "gosaMailServer"            =>  _("Mail server"),
1160             "gosaMailQuota"             =>  _("Quota size"),
1162             "gosaMailDeliveryModeV"     =>  _("Add vacation information"),  // This is flag of gosaMailDeliveryMode
1163             "gosaVacationMessage"       =>  _("Vacation message"),
1165             "gosaMailDeliveryModeS"     =>  _("Use spam filter"),           // This is flag of gosaMailDeliveryMode
1166             "gosaSpamSortLevel"         =>  _("Spam level"),
1167             "gosaSpamMailbox"           =>  _("Spam mail box"),
1169             "sieveManagement"           =>  _("Sieve management"),
1171             "gosaMailDeliveryModeR"     =>  _("Reject due to mailsize"),    // This is flag of gosaMailDeliveryMode
1172             "gosaMailMaxSize"           =>  _("Mail max size"),
1174             "gosaMailForwardingAddress" =>  _("Forwarding address"),
1175             "gosaMailDeliveryModeL"     =>  _("Local delivery"),            // This is flag of gosaMailDeliveryMode
1176             "gosaMailDeliveryModeI"     =>  _("No delivery to own mailbox "),     // This is flag of gosaMailDeliveryMode
1177             "gosaMailAlternateAddress"  =>  _("Mail alternative addresses"),
1179             "gosaMailForwardingAddress" =>  _("Forwarding address"),
1180             "gosaMailDeliveryModeC"     =>  _("Use custom sieve script"))   // This is flag of gosaMailDeliveryMode
1181         ));
1182   }
1184   /* Upated shared folder ACLs 
1185    */
1186   function updateSharedFolder()
1187   {
1188     $ldap = $this->config->get_ldap_link();
1189     $ldap->cd($this->config->current['BASE']);
1190     $ldap->search("(&(objectClass=posixGroup)(objectClass=gosaMailAccount)(memberUid=".$this->uid."))",array('dn','cn'));
1191     if(class_exists("grouptabs")){
1192       while($attrs = $ldap->fetch()){
1193         $tmp = new grouptabs($this->config, $this->config->data['TABS']['GROUPTABS'], $attrs['dn']);
1194         if(isset($tmp->by_object['mailgroup'])){
1195           $tmp->by_object['mailgroup']->members= $tmp->by_object['group']->memberUid;
1196           if(!$this->is_account){
1197             $tmp->by_object['mailgroup']->removeUserAcl($this->uid);
1198             $tmp->by_object['mailgroup']->removeUserAcl($this->mail);
1199           }
1200           $tmp->by_object['mailgroup']->save();
1201         }
1202       }
1203     } 
1204   }
1207 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1208 ?>