Code

Renoved debug tag
[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       }
443       /* Save message */
444       $this->gosaVacationMessage= htmlspecialchars($contents);
445     }
447   
448     /* Display forward dialog if requested above */
450     /* Show forward add dialog */
451     if ($this->forward_dialog){
452       $ldap= $this->config->get_ldap_link();
454       /* Save data */
455       $mailfilter= get_global("mailfilter");
456       foreach( array("depselect", "muser", "regex") as $type){
457         if (isset($_POST[$type])){
458           $mailfilter[$type]= $_POST[$type];
459         }
460       }
461       if (isset($_GET['search'])){
462         $s= mb_substr($_GET['search'], 0, 1, "UTF8")."*";
463         if ($s == "**"){
464           $s= "*";
465         }
466         $mailfilter['regex']= $s;
467       }
468       register_global("mailfilter", $mailfilter);
470       /* Get actual list */
471       $mailusers= array ();
472       if ($mailfilter['regex'] != '*' && $mailfilter['regex'] != ""){
473         $regex= $mailfilter['regex'];
474         $filter= "(|(mail=$regex)(gosaMailAlternateAddress=$regex))";
475       } else {
476         $filter= "";
477       }
478       if ($mailfilter['muser'] != ""){
479         $user= $mailfilter['muser'];
480         $filter= "$filter(|(uid=$user)(cn=$user)(givenName=$user)(sn=$user))";
481       }
483       /* Add already present people to the filter */
484       $exclude= "";
485       foreach ($this->gosaMailForwardingAddress as $mail){
486         $exclude.= "(mail=$mail)";
487       }
488       if ($exclude != ""){
489         $filter.= "(!(|$exclude))";
490       }
492       $res= get_list("(&(objectClass=gosaMailAccount)$filter)", "users", $mailfilter['depselect'], 
493                      array("sn", "mail", "givenName"), GL_SIZELIMIT | GL_SUBSEARCH);
494       $ldap->cd($mailfilter['depselect']);
495       $ldap->search ("(&(objectClass=gosaMailAccount)$filter)", array("sn", "mail", "givenName"));
496       error_reporting (0);
497       while ($attrs= $ldap->fetch()){
498         if(preg_match('/%/', $attrs['mail'][0])){
499           continue;
500         }
501         $name= $this->make_name($attrs);
502         $mailusers[$attrs['mail'][0]]= $name."&lt;".
503           $attrs['mail'][0]."&gt;";
504       }
505       error_reporting (E_ALL | E_STRICT);
506       natcasesort ($mailusers);
507       reset ($mailusers);
509       /* Show dialog */
510       $smarty->assign("search_image", get_template_path('images/search.png'));
511       $smarty->assign("usearch_image", get_template_path('images/search_user.png'));
512       $smarty->assign("tree_image", get_template_path('images/tree.png'));
513       $smarty->assign("infoimage", get_template_path('images/info.png'));
514       $smarty->assign("launchimage", get_template_path('images/small_filter.png'));
515       $smarty->assign("mailusers", $mailusers);
516       if (isset($_POST['depselect'])){
517         $smarty->assign("depselect", $_POST['depselect']);
518       }
519       $smarty->assign("deplist", $this->config->idepartments);
520       $smarty->assign("apply", apply_filter());
521       $smarty->assign("alphabet", generate_alphabet());
522       $smarty->assign("hint", print_sizelimit_warning());
523       foreach( array("depselect", "muser", "regex") as $type){
524         $smarty->assign("$type", $mailfilter[$type]);
525       }
526       $smarty->assign("hint", print_sizelimit_warning());
528       $display.= $smarty->fetch (get_template_path('mail_locals.tpl', TRUE, dirname(__FILE__)));
529       return ($display);
530     }
532     /* Display mail account tab */
534     $smarty->assign("mailServers", $mailserver);
535     $SkipWrite = (!isset($this->parent) || !$this->parent) && !isset($_SESSION['edit']);
537     $tmp  = $this->plInfo();
538     foreach($tmp['plProvidedAcls'] as $name => $transl){
539       $smarty->assign("$name"."ACL", $this->getacl($name,$SkipWrite));
540     }
542     foreach(array("gosaMailServer", "gosaMailQuota", "perms", "mail",
543           "gosaMailAlternateAddress", "gosaMailForwardingAddress",
544           "gosaVacationMessage", "gosaMailDeliveryMode", "gosaVacationStart",
545           "gosaVacationStop", "gosaMailMaxSize", "gosaSpamSortLevel", "gosaSpamMailbox") as $val){
546       $smarty->assign("$val", $this->$val);
547     }
549     if (is_numeric($this->gosaMailQuota) && $this->gosaMailQuota != 0){
550       $smarty->assign("quotausage", progressbar(round(($this->quotaUsage * 100)/ $this->gosaMailQuota),100,15,true));
551       $smarty->assign("quotadefined", "true");
552     } else {
553       $smarty->assign("quotadefined", "false");
554     }
556     /* Disable mail field if needed */
557     $method= new $this->method($this->config);
558     if ($method->uattrib == "mail" && $this->initially_was_account){
559       $smarty->assign("mailACL", preg_replace("/w/","",$this->getacl("mail",$SkipWrite)));
560     }
562     /* Disable/Enable range select, but do not disable them twice 
563      *  if they are already diabled by "use own sieve script"
564      */
565     if (preg_match('/V/', $this->gosaMailDeliveryMode) || preg_match("/C/",$this->gosaMailDeliveryMode)){
566       $smarty->assign('rangeEnabled', "");
567     } else {
568       $smarty->assign('rangeEnabled', "disabled");
569     }
571     if (!preg_match("/L/", $this->gosaMailDeliveryMode)) {
572       $smarty->assign("only_local", "checked");
573     } else {
574       $smarty->assign("only_local", "");
575     }
577     $types = array(
578           "V"=>"use_vacation",
579           "S"=>"use_spam_filter",
580           "R"=>"use_mailsize_limit",
581           "I"=>"drop_own_mails",
582           "C"=>"own_script");
584     /* Fill checkboxes */
585     foreach($types as $option => $varname){
586       if (preg_match("/".$option."/", $this->gosaMailDeliveryMode)) {
587         $smarty->assign($varname, "checked");
588       } else {
589         $smarty->assign($varname, "");
590       }
591     }
592    
593     /* Display mail account tab */
594     if($this->gosaVacationStart ==0){
595       $date= getdate(time());
596     }else{
597       $date= getdate($this->gosaVacationStart);
598     }
599     $days= array();
600     for($d= 1; $d<32; $d++){
601       $days[$d]= $d;
602     }
603     $years= array();
604     for($y= $date['year']-10; $y<$date['year']+10; $y++){
605       $years[]= $y;
606     }
607     $months= array(_("January"), _("February"), _("March"), _("April"),
608         _("May"), _("June"), _("July"), _("August"), _("September"),
609         _("October"), _("November"), _("December"));
610     $smarty->assign("start_day", $date["mday"]);
611     $smarty->assign("days", $days);
612     $smarty->assign("months", $months);
613     $smarty->assign("start_month", $date["mon"]-1);
614     $smarty->assign("years", $years);
615     $smarty->assign("start_year", $date["year"]);
617     if($this->gosaVacationStop ==0){
618       $date= getdate(time());
619       $date["mday"]++;
620     }else{
621       $date= getdate($this->gosaVacationStop);
622     }
623     $smarty->assign("end_day", $date["mday"]);
624     $smarty->assign("end_month", $date["mon"]-1);
625     $smarty->assign("end_year", $date["year"]);
628  
629     /* Have vacation templates? */
630     $smarty->assign("template", "");
631     if (count($this->vacation)){
632       $smarty->assign("show_templates", "true");
633       $smarty->assign("vacationtemplates", $this->vacation);
634       if (isset($_POST['vacation_template'])){
635         $smarty->assign("template", $_POST['vacation_template']);
636       }
637     } else {
638       $smarty->assign("show_templates", "false");
639     }
641     /* Fill spam selector */
642     $spamlevel= array();
643     for ($i= 0; $i<21; $i++){
644       $spamlevel[]= $i;
645     }
646     $smarty->assign("spamlevel", $spamlevel);
647     $smarty->assign("spambox", $this->mailboxList);
649     $display.= $smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
650     return ($display);
651   }
654   /* remove object from parent */
655   function remove_from_parent()
656   {
657     /* Cancel if there's nothing to do here */
658     if (!$this->initially_was_account){
659       return;
660     }
661     
662     /* include global link_info */
663     $ldap= $this->config->get_ldap_link();
665     /* Remove and write to LDAP */
666     plugin::remove_from_parent();
668     /* Zero arrays */
669     $this->attrs['gosaMailAlternateAddress']= array();
670     $this->attrs['gosaMailForwardingAddress']= array();
672     /* Adapt attributes if needed */
673     $method= new $this->method($this->config);
674     $method->fixAttributesOnRemove($this);
676     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,$this->attributes, "Save");
677     $ldap->cd($this->dn);
678     $this->cleanup();
680     $ldap->modify ($this->attrs); 
682     /* Add "view" to logging class */ 
683     new log("remove","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
685     show_ldap_error($ldap->get_error(), sprintf(_("Removing of user/mail account with dn '%s' failed."),$this->dn));
687     /* Connect to IMAP server for account deletion */
688     if ($this->gosaMailServer != ""){
689       $method= new $this->method($this->config);
690       $id= $method->uattrib;
691       if ($method->connect($this->gosaMailServer)){
693         /* Remove account from IMAP server */
694         $method->deleteMailbox($this->folder_prefix.$this->$id);
695         $method->disconnect();
696       }
697     }
699     /* Optionally execute a command after we're done */
700     $this->handle_post_events("remove",array("uid" => $this->uid));
701   }
703   
704   /* check if we have some delegations configured, those delegations must be removed first */
705   function accountDelegationsConfigured()
706   { 
707     /* We are in administrational edit mode.
708         Check tab configurations directly */
709     if(isset($this->attrs)){
710       $checkArray  = array("kolabInvitationPolicy","unrestrictedMailSize", "calFBURL","kolabDelegate","kolabFreeBusyFuture");
711       foreach($checkArray as $index){
712         if(isset($this->attrs[$index])){
713            return(true);
714         }
715       }
716     }
717     return(false); 
718   }
719  
721   /* Save data to object */
722   function save_object()
723   {
724     if (isset($_POST['mailTab'])){
726       /* Save ldap attributes */
727       plugin::save_object();
730       if(isset($_POST['own_script'])){
732         if(!preg_match("/C/",$this->gosaMailDeliveryMode)){
733           $str= preg_replace("/[\[\]]/","",$this->gosaMailDeliveryMode);
734           $this->gosaMailDeliveryMode = "[".$str."C]";
735         }
737       }else{
739         /* Assemble mail delivery mode
740            The mode field in ldap consists of values between braces, this must
741            be called when 'mail' is set, because checkboxes may not be set when
742            we're in some other dialog.
744           Example for gosaMailDeliveryMode [LR        ]
745           L: Local delivery
746           R: Reject when exceeding mailsize limit
747           S: Use spam filter
748           V: Use vacation message
749           C: Use custm sieve script
750           I: Only insider delivery */
752         $tmp= preg_replace("/[^a-z]/i","",$this->gosaMailDeliveryMode);
755         /* Handle delivery flags */
756         if($this->acl_is_writeable("gosaMailDeliveryModeL")){
757           if(!preg_match("/L/",$tmp) && !isset($_POST['only_local'])){
758             $tmp.="L";
759           }elseif(preg_match("/L/",$tmp) && isset($_POST['only_local'])){
760             $tmp = preg_replace("/L/","",$tmp);
761           }
762         }
764         $opts = array(     
765             "R"   => "use_mailsize_limit",
766             "S"   => "use_spam_filter",
767             "V"   => "use_vacation",
768             "C"   => "own_script",
769             "I"   => "drop_own_mails");
771         foreach($opts as $flag => $post){
772           if($this->acl_is_writeable("gosaMailDeliveryMode".$flag)){
773             if(!preg_match("/".$flag."/",$tmp) && isset($_POST[$post])){
774               $tmp.= $flag;
775             }elseif(preg_match("/".$flag."/",$tmp) && !isset($_POST[$post])){
776               $tmp = preg_replace("/".$flag."/","",$tmp);
777             }
778           }
779         }
781         $tmp= "[$tmp]";
782         if ($this->gosaMailDeliveryMode != $tmp){
783           $this->is_modified= TRUE;
784         }
785         $this->gosaMailDeliveryMode= $tmp;
786       }
787     }
789   }
792   /* Save data to LDAP, depending on is_account we save or delete */
793   function save()
794   {
795     $ldap= $this->config->get_ldap_link();
797     /* Call parents save to prepare $this->attrs */
798     plugin::save();
800     /* Save arrays */
801     $this->attrs['gosaMailAlternateAddress']= $this->gosaMailAlternateAddress;
802     $this->attrs['gosaMailForwardingAddress']= $this->gosaMailForwardingAddress;
804     /* Adapt attributes if needed */
805     $method= new $this->method($this->config);
806     $id= $method->uattrib;
808     $method->fixAttributesOnStore($this);
810     /* Remove Mailquota if = "" or "0"  */
811     if((isset($this->attrs['gosaMailQuota']))&&(!$this->attrs['gosaMailQuota'])) {
812       $this->attrs['gosaMailQuota']=0;
813     }
815     if(empty($this->attrs['gosaSpamMailbox'])){
816       unset($this->attrs['gosaSpamMailbox']);
817     }
819     $this->attrs['mail'] = strtolower($this->attrs['mail']); 
821         /* Remove attributes - if not needed */
822     if (!preg_match('/V/', $this->gosaMailDeliveryMode)){
823       unset($this->attrs['gosaVacationStart']);
824       unset($this->attrs['gosaVacationStop']);
825     }
828     /* Remove attributes - if not needed */
829     if (!preg_match('/V/', $this->gosaMailDeliveryMode)){
830       unset($this->attrs['gosaVacationStart']);
831       unset($this->attrs['gosaVacationStop']);
832     }
834     /* Save data to LDAP */
835     $ldap->cd($this->dn);
836     $this->cleanup();
837     $ldap->modify ($this->attrs); 
839     show_ldap_error($ldap->get_error(), sprintf(_("Saving of user/mail account with dn '%s' failed."),$this->dn));
841     /* Log last action */ 
842     if($this->initially_was_account){
843       new log("modify","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
844     }else{
845       new log("create","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
846     }
848     /* Only do IMAP actions if we are not a template */
849     if (!$this->is_template){
851       if ($method->connect($this->gosaMailServer)){
852         $method->updateMailbox($this->folder_prefix.$this->$id);
853         
854         $method->setQuota($this->folder_prefix.$this->$id, $this->gosaMailQuota);
855         $method->disconnect();
857         /* Ensure that this is an existing account */
858         if(1==1 || $this->initially_was_account){
860           /* Write sieve information only if not in C mode */
861           if (!is_integer(strpos($this->gosaMailDeliveryMode, "C"))){
862             $method->configureFilter($this->$id,
863                 $this->gosaMailDeliveryMode,
864                 $this->mail,
865                 $this->gosaMailAlternateAddress,
866                 $this->gosaMailMaxSize,
867                 $this->gosaSpamMailbox,
868                 $this->gosaSpamSortLevel,
869                 $this->gosaVacationMessage);
870           }else{
871             $this->sieve_management->save();
872           }
873         }
874       }
875     }
877     /* Optionally execute a command after we're done */
878     if ($this->initially_was_account == $this->is_account){
879       if ($this->is_modified){
880         $this->handle_post_events("modify", array("uid" => $this->uid));
881       }
882     } else {
883       $this->handle_post_events("add", array("uid" => $this->uid));
884     }
886   }
889   /* Check formular input */
890   function check()
891   {
892     if(!$this->is_account) return(array());
894     $ldap= $this->config->get_ldap_link();
896     /* Call common method to give check the hook */
897     $message= plugin::check();
899     if(empty($this->gosaMailServer)){
900       $message[]= _("There is no valid mailserver specified, please add one in the system setup.");
901     }
903     /* must: mail */
904     if ($this->mail == ""){
905       $message[]= _("The required field 'Primary address' is not set.");
906     }
907     if ($this->is_template){
908       if (!is_email($this->mail, TRUE)){
909         $message[]= _("Please enter a valid email address in 'Primary address' field.");
910       }
911     } else {
912       if (!is_email($this->mail)){
913         $message[]= _("Please enter a valid email address in 'Primary address' field.");
914       }
915     }
916     $ldap->cd($this->config->current['BASE']);
917     $ldap->search ("(&(!(objectClass=gosaUserTemplate))(objectClass=gosaMailAccount)(|(mail=".$this->mail.")(gosaMailAlternateAddress=".$this->mail."))(!(uid=".$this->uid."))(!(cn=".$this->uid.")))", array("uid"));
918     if ($ldap->count() != 0){
919       $message[]= _("The primary address you've entered is already in use.");
920     }
922     /* Check quota */
923     if ($this->gosaMailQuota != '' && $this->acl_is_writeable("gosaMailQuota")){
924       if (!is_numeric($this->gosaMailQuota)) {
925         $message[]= _("Value in 'Quota size' is not valid.");
926       } else {
927         $this->gosaMailQuota= (int) $this->gosaMailQuota;
928       }
929     }
931     /* Check rejectsize for integer */
932     if ($this->gosaMailMaxSize != '' && $this->acl_is_writeable("gosaMailMaxSize")){
933       if (!is_numeric($this->gosaMailMaxSize)){
934         $message[]= _("Please specify a vaild mail size for mails to be rejected.");
935       } else {
936         $this->gosaMailMaxSize= (int) $this->gosaMailMaxSize;
937       }
938     }
940     /* Need gosaMailMaxSize if use_mailsize_limit is checked */
941     if (is_integer(strpos($this->gosaMailDeliveryMode, "R")) && 
942         $this->gosaMailMaxSize == ""){
944       $message[]= _("You need to set the maximum mail size in order to reject anything.");
945     }
947     if((preg_match("/S/", $this->gosaMailDeliveryMode))&&(empty($this->gosaSpamMailbox))) {
948       $message[]= _("You specified Spam settings, but there is no Folder specified.");
949     }
951     if (preg_match('/V/', $this->gosaMailDeliveryMode) && $this->gosaVacationStart >= $this->gosaVacationStop){
952       $message[]= _("Time interval to show vacation message is not valid.");
953     }
955     return ($message);
956   }
959   /* Adapt from template, using 'dn' */
960   function adapt_from_template($dn)
961   {
962     plugin::adapt_from_template($dn);
964     foreach (array("gosaMailAlternateAddress", "gosaMailForwardingAddress") as $val){
965       $this->$val= array();
966       if (isset($this->attrs["$val"]["count"])){
967         for ($i= 0; $i<$this->attrs["$val"]["count"]; $i++){
968           $value= $this->attrs["$val"][$i];
969           foreach (array("sn", "givenName", "uid") as $repl){
970             if (preg_match("/%$repl/i", $value)){
971               $value= preg_replace ("/%$repl/i", $this->parent->$repl, $value);
972             }
973           }
974           array_push($this->$val, strtolower(rewrite($value)));
975         }
976       }
977     }
978     $this->mail= strtolower(rewrite($this->mail));
979   }
982   /* Add entry to forwarder list */
983   function addForwarder($address)
984   {
985     if($this->acl_is_writeable("gosaMailForwardingAddress")){
986       $this->gosaMailForwardingAddress[]= $address;
987       $this->gosaMailForwardingAddress= array_unique ($this->gosaMailForwardingAddress);
988       sort ($this->gosaMailForwardingAddress);
989       reset ($this->gosaMailForwardingAddress);
990       $this->is_modified= TRUE;
991     }else{
992       print_red(_("You are not allowed to write mail forwarding."));
993     }
994   }
997   /* Remove list of addresses from forwarder list */
998   function delForwarder($addresses)
999   {
1000     if($this->acl_is_writeable("gosaMailForwardingAddress")){
1001       $this->gosaMailForwardingAddress= array_remove_entries ($addresses, $this->gosaMailForwardingAddress);
1002       $this->is_modified= TRUE;
1003     }else{
1004       print_red(_("You are not allowed to write mail forwarding."));
1005     }
1006   }
1009   /* Add given mail address to the list of alternate adresses , 
1010      check if this mal address is used, skip adding in this case */
1011   function addAlternate($address)
1012   {
1013     if($this->acl_is_writeable("gosaMailAlternateAddress")){
1014       $ldap= $this->config->get_ldap_link();
1015       $address= strtolower($address);
1017       /* Is this address already assigned in LDAP? */
1018       $ldap->cd ($this->config->current['BASE']);
1019       $ldap->search ("(&(objectClass=gosaMailAccount)(|(mail=$address)"."(gosaMailAlternateAddress=$address)))", array("uid"));
1020       $ldap->search ("(&(!(objectClass=gosaUserTemplate))(objectClass=gosaMailAccount)(|(mail=$address)"."(gosaMailAlternateAddress=$address)))", array("uid"));
1022       if ($ldap->count() > 0){
1023         $attrs= $ldap->fetch ();
1024         return ($attrs["uid"][0]);
1025       }
1027       /* Add to list of alternates */
1028       if (!in_array($address, $this->gosaMailAlternateAddress)){
1029         $this->gosaMailAlternateAddress[]= $address;
1030         $this->is_modified= TRUE;
1031       }
1033       sort ($this->gosaMailAlternateAddress);
1034       reset ($this->gosaMailAlternateAddress);
1035       return ("");
1036     }else{
1037       print_red(_("You are not allowed to write mail alternate address."));
1038     }
1039   }
1042   function delAlternate($addresses)
1043   {
1044     if($this->acl_is_writeable("gosaMailAlternateAddress")){
1045       $this->gosaMailAlternateAddress= array_remove_entries ($addresses,$this->gosaMailAlternateAddress);
1046       $this->is_modified= TRUE;
1047     }else{
1048       print_red(_("You are not allowed to write mail alternate address."));
1049     }
1050   }
1052   function make_name($attrs)
1053   {
1054     $name= "";
1055     if (isset($attrs['sn'][0])){
1056       $name= $attrs['sn'][0];
1057     }
1058     if (isset($attrs['givenName'][0])){
1059       if ($name != ""){
1060         $name.= ", ".$attrs['givenName'][0];
1061       } else {
1062         $name.= $attrs['givenName'][0];
1063       }
1064     }
1065     if ($name != ""){
1066       $name.= " ";
1067     }
1069     return ($name);
1070   }
1072   
1073   /* Create the mail part for the copy & paste dialog */
1074   function getCopyDialog()
1075   {
1076     if(!$this->is_account) return("");
1077     $smarty = get_smarty();
1078     $smarty->assign("mail",$this->mail); 
1079     $smarty->assign("gosaMailAlternateAddress",$this->gosaMailAlternateAddress);
1080     $smarty->assign("gosaMailForwardingAddress",$this->gosaMailForwardingAddress);
1081     $str = $smarty->fetch(get_template_path("copypaste.tpl",TRUE, dirname(__FILE__)));
1083     $ret = array();
1084     $ret['status'] = "";
1085     $ret['string'] = $str;
1086     return($ret);
1087   }
1089   function saveCopyDialog()
1090   {
1091     if(!$this->is_account) return;  
1093     /* Execute to save mailAlternateAddress && gosaMailForwardingAddress */
1094     $this->execute();
1095     
1096     if(isset($_POST['mail'])){
1097       $this->mail = $_POST['mail'];
1098     }
1100   }
1102   function allow_remove()
1103   {
1104     if (isset($this->config->current['MAILMETHOD'])){
1105       $method= $this->config->current['MAILMETHOD'];
1106       if(preg_match("/olab/i",$method)){
1107         $ldap = $this->config->get_ldap_link();
1108         $ldap->cd($this->config->current['BASE']);
1109         $ldap->cat($this->dn);
1110         if($ldap->count()){
1111           $attrs = $ldap->fetch();
1112           if(isset($attrs['kolabDeleteFlag'])){ 
1113             return(_("Waiting for kolab to remove mail properties."));
1114           }elseif(in_array("gosaMailAccount",$attrs['objectClass'])){
1115             return(_("Please remove the mail account first, to allow kolab to call its remove methods."));
1116           }
1117         }
1118       }
1119     }
1120   }
1122    
1123   function PrepareForCopyPaste($source)
1124   {
1125     plugin::PrepareForCopyPaste($source);
1127     /* Reset alternate mail addresses */
1128     $this->gosaMailAlternateAddress = array();    
1129    }
1132   function plInfo()
1133   {
1134     return (array(
1135           "plShortName"     => _("Mail"),
1136           "plDescription"   => _("Mail settings"),
1137           "plSelfModify"    => TRUE,
1138           "plDepends"       => array("user"),                     // This plugin depends on
1139           "plPriority"      => 4,                                 // Position in tabs
1140           "plSection"     => array("personal" => _("My account")),
1141           "plCategory"    => array("users"),
1142           "plOptions"       => array(),
1143   
1144           "plProvidedAcls"  => array(
1145             "mail"                      =>  _("Mail address"),
1146             "gosaMailServer"            =>  _("Mail server"),
1147             "gosaMailQuota"             =>  _("Quota size"),
1149             "gosaMailDeliveryModeV"     =>  _("Add vacation information"),  // This is flag of gosaMailDeliveryMode
1150             "gosaVacationMessage"       =>  _("Vacation message"),
1152             "gosaMailDeliveryModeS"     =>  _("Use spam filter"),           // This is flag of gosaMailDeliveryMode
1153             "gosaSpamSortLevel"         =>  _("Spam level"),
1154             "gosaSpamMailbox"           =>  _("Spam mail box"),
1156             "sieveManagement"           =>  _("Sieve management"),
1158             "gosaMailDeliveryModeR"     =>  _("Reject due to mailsize"),    // This is flag of gosaMailDeliveryMode
1159             "gosaMailMaxSize"           =>  _("Mail max size"),
1161             "gosaMailForwardingAddress" =>  _("Forwarding address"),
1162             "gosaMailDeliveryModeL"     =>  _("Local delivery"),            // This is flag of gosaMailDeliveryMode
1163             "gosaMailDeliveryModeI"     =>  _("No delivery to own mailbox "),     // This is flag of gosaMailDeliveryMode
1164             "gosaMailAlternateAddress"  =>  _("Mail alternative addresses"),
1166             "gosaMailForwardingAddress" =>  _("Forwarding address"),
1167             "gosaMailDeliveryModeC"     =>  _("Use custom sieve script"))   // This is flag of gosaMailDeliveryMode
1168         ));
1169   }
1172 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1173 ?>