Code

Added logging to ogroup
[gosa.git] / plugins / personal / mail / class_mailAccount.inc
1 <?php
2 /*! \brief   mail plugin
3   \author  Cajus Pollmeier <pollmeier@gonicus.de>
4   \version 2.00
5   \date    24.07.2003
7   This class provides the functionality to read and write all attributes
8   relevant for gosaMailAccounts from/to the LDAP. It does syntax checking
9   and displays the formulars required.
10  */
12 /* Load sieve support */
13 require_once ("sieve/libsieve.inc");
15 /* Load mail methods */
16 global $BASE_DIR;
17 get_dir_list("$BASE_DIR/include");
19 class mailAccount extends plugin
20 {
21   /* Definitions */
22   var $plHeadline         = "Mail";
23   var $plDescription      = "This does something";
24   var $method             = "mailMethod";
26   /* CLI vars */
27   var $gosaVacationStart                  = 0;
28   var $gosaVacationStop                   = 0;
30   /* plugin specific values */
31   var $mail                               = "";
32   var $gosaMailAlternateAddress           = array();
33   var $gosaMailForwardingAddress          = array();
34   var $gosaMailDeliveryMode               = "[L        ]";
35   var $gosaMailServer                     = "";
36   var $gosaMailQuota                      = "";
37   var $gosaMailMaxSize                    = "";
38   var $gosaVacationMessage                = "";
39   var $gosaSpamSortLevel                  = "";
40   var $gosaSpamMailbox                    = "";
42   var $quotaUsage                         = 0;
43   var $forward_dialog                     = FALSE;
44   var $folder_prefix                      = "";
45   var $mailboxList                        = array("INBOX");
46   var $default_permissions                = "none";
47   var $member_permissions                 = "post";
48   var $members                            = array();
49   var $admins                             = array();
50   var $vacations                          = array();
51   var $perms                              = array(  "lrs"       => "read", 
52                                                     "lrsp"      => "post", 
53                                                     "lrsip"     => "append",
54                                                     "lrswipcd"  => "write", 
55                                                     "lrswipcda" => "all" );
57   /* attribute list for save action */
58   var $attributes= array("mail", "gosaMailServer", "gosaMailQuota", "gosaMailMaxSize","gosaMailForwardingAddress",
59       "gosaMailDeliveryMode", "gosaSpamSortLevel", "gosaSpamMailbox","gosaMailAlternateAddress","gosaVacationStart","gosaVacationStop",
60       "gosaVacationMessage", "gosaMailAlternateAddress", "gosaMailForwardingAddress");
61   var $objectclasses= array("gosaMailAccount");
62   var $uid;
64   var $sieve_management = NULL;
66   /* constructor, if 'dn' is set, the node loads the given
67      'dn' from LDAP */
68   function mailAccount ($config, $dn= NULL)
69   {
70     /* Load bases attributes */
71     plugin::plugin($config, $dn);
73     /* Set uid */
74     if(isset($this->attrs['uid'])){
75       $this->uid = $this->attrs['uid'][0];
76     }
77  
78     if(is_array($this->gosaMailServer) && isset($this->gosaMailServer[0])){
79       $this->gosaMailServer = $this->gosaMailServer[0];
80     }
82     /* Save initial account state */
83     $this->initially_was_account= $this->is_account;
85     /*  Set mailMethod to the one defined in gosa.conf */
86     if (isset($this->config->current['MAILMETHOD'])){
87       $method= $this->config->current['MAILMETHOD'];
88       if (class_exists("mailMethod$method")){
89         $this->method= "mailMethod$method";
90       } else {
91         print_red(sprintf(_("There is no mail method '%s' specified in your gosa.conf available."), $method));
92       }
93     }
95     
96     /* Create the account prefix  user. user/ 
97        Preset folder prefix. Will change it later to respect
98        altnamespace. */
99     if (isset($this->config->current['CYRUSUNIXSTYLE']) && $this->config->current['CYRUSUNIXSTYLE'] == "true"){
100       $this->folder_prefix= "user/";
101     }elseif (isset($this->config->data['MAIN']['CYRUSUNIXSTYLE']) && $this->config->data['MAIN']['CYRUSUNIXSTYLE'] == "true"){
102       $this->folder_prefix= "user/";
103     } else {
104       $this->folder_prefix= "user.";
105     }
106     
107     /* This is not a new account, parse additional attributes */
108     if (($dn != NULL) && ($dn != "new") && $this->is_account){
110       /* Load attributes containing arrays */
111       foreach (array("gosaMailAlternateAddress", "gosaMailForwardingAddress") as $val){
112         $this->$val= array();
113         if (isset($this->attrs["$val"]["count"])){
114           for ($i= 0; $i<$this->attrs["$val"]["count"]; $i++){
115             array_push($this->$val, $this->attrs["$val"][$i]);
116           }
117         }
118       }
121       /* Only do IMAP actions if gosaMailServer attribute is set */
122       if (isset ($this->attrs["gosaMailServer"][0])){
124         $method = new $this->method($this->config);
125         $id     = $method->uattrib;
127         /* Adapt attributes if needed */
128         $method->fixAttributesOnLoad($this);
130         /* FixAttributesOnLoad possibly creates an array out of gosaMailServer.
131             If the mail tab wasn't opened once before saving, the account can't be saved */
132         if(is_array($this->gosaMailServer)){
133           $this->gosaMailServer = $this->gosaMailServer[0];
134         }
136         if ($method->connect($this->attrs["gosaMailServer"][0])){
138           /* Update quota values */
139           $quota= $method->getQuota($this->folder_prefix.$this->$id);
140          
141           if($quota){
142             if ($quota['gosaMailQuota'] == 2147483647){
143               $this->quotaUsage     = "";
144               $this->gosaMailQuota  = "";
145             } else {
146               $this->quotaUsage     = $quota['quotaUsage'];
147               $this->gosaMailQuota  = $quota['gosaMailQuota'];
148             }
149           }else{
150             $this->quotaUsage     = "";
151             $this->gosaMailQuota  = "";
152 //            print_red(sprintf(_("Can't get quota information for '%s'."),$this->folder_prefix.$this->$id));
153           }
155           /* Get mailboxes / folder like INBOX ..*/
156           $this->mailboxList= $method->getMailboxList($this->folder_prefix.$this->$id,$this->$id);
157           
158           $method->disconnect();
159         }else{
160           /* Could not connect to ldap.
161            */
162           if (isset($this->attrs['gosaMailQuota'][0])){
163             $this->gosaMailQuota = $this->attrs['gosaMailQuota'][0];
164           }
165         }
166       }
167     }
169     /* Fill vacation array */
170     $this->vacation= array();
171     if (isset($this->config->current['VACATIONDIR'])){
172       $dir= $this->config->current['VACATIONDIR'];
173       if (is_dir($dir) && is_readable($dir)){
175         /* Look for files and build the vacation array */
176         $dh= opendir($dir);
177         while ($file = readdir($dh)){
178           $description= $this->parse_vacation("$dir/$file");
179           if ($description != ""){
180             $this->vacation["$dir/$file"]= $description;
181           }
182         }
183         closedir($dh);
184       }
185     }
187     /* Create sieve management class */
188     $method = new $this->method($this->config);
189     $id     = $method->uattrib;
190     $this->sieve_management = new sieveManagement($this->config,$this->dn,$this,$id);
192     /* Get global filter config */
193     if (!is_global("mailfilter")){
194       $ui= get_userinfo();
195       $base= get_base_from_people($ui->dn);
196       $mailfilter= array( "depselect"       => $base,
197           "muser"            => "",
198           "regex"           => "*");
199       register_global("mailfilter", $mailfilter);
200     }
201    
202     /* Add "view" to logging class */ 
203     if($this->is_account){
204       @log::log("view","users/".get_class($this),$this->dn);
205     }
206   }
209   function parse_vacation($file)
210   {
211     $desc= "";
213     if (is_file($file)){
214       $fh = fopen($file, "r");
215       $line= fgets($fh, 256);
217       if (!preg_match('/^DESC:/', $line)){
218         print_red (_("No DESC tag in vacation file:")." $file");
219         return $desc;
220       }
221       fclose ($fh);
223       $desc= trim(preg_replace('/^DESC:\s*/', '', $line));
224     }
226     return $desc;
227   }
230   function execute()
231   {
232     /* Call parent execute */
233     plugin::execute();
235     /* Initialise vars */
237     /* Load templating engine */
238     $smarty= get_smarty();
239     $display= "";
241     /* Get available mailserver */
242     $mailserver= array();
243     foreach ($this->config->data['SERVERS']['IMAP'] as $key => $val){
244       $mailserver[]= $key;
245     }
247     /* 
248      * Sieve Management 
249      */
250     if(isset($_POST['sieveManagement']) 
251         && preg_match("/C/",$this->gosaMailDeliveryMode)
252         && $this->acl_is_writeable("sieveManagement")) {
254       $this->dialog = $this->sieve_management;
255     }
256    
257     /* Cancel sieve edit */
258     if(isset($_POST['sieve_cancel'])){
259       $this->dialog = NULL;
260     }
261  
262     /* Save sieve changes */
263     if(isset($_POST['sieve_finish'])){
264       $this->sieve_management = $this->dialog;
265       $this->dialog = NULL;
266     }
267  
268     if(is_object($this->dialog)){
269       $this->dialog->save_object();
270       return($this->dialog->execute());
271     } 
274     /* Handle account state */
275     /* Do we need to flip is_account state? */
276     if(isset($_POST['modify_state'])){
277       if($this->is_account && $this->acl_is_removeable()){
278         $this->is_account= FALSE;
279       }elseif(!$this->is_account && $this->acl_is_createable()){
280         $this->is_account= TRUE;
281       }
282     }
284     /* Do we represent a valid account? */
285     if (!$this->is_account && $this->parent == NULL){
286       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
287         _("This account has no mail extensions.")."</b>";
289       $display.= back_to_main();
290       return ($display);
291     }
293     /* Show tab dialog headers */
294     if ($this->parent != NULL){
295       if ($this->is_account){
296         if($this->accountDelegationsConfigured()){
297           $display= $this->show_disable_header(_("Remove mail account"),
298               _("This account can't be removed while there are delegations configured. Remove those delegations first."),TRUE,TRUE);
299         }else{
300           $display= $this->show_disable_header(_("Remove mail account"),
301               _("This account has mail features enabled. You can disable them by clicking below."));
302         }
303       } else {
304         $display= $this->show_enable_header(_("Create mail account"), _("This account has mail features disabled. You can enable them by clicking below."));
305         return ($display);
306       }
307     }
310     /* Forwarder  subdialog */
312     /* Trigger forward add dialog? */
313     if (isset($_POST['add_local_forwarder'])){
314       $this->forward_dialog= TRUE;
315       $this->dialog= TRUE;
316     }
318     /* Cancel forward add dialog? */
319     if (isset($_POST['add_locals_cancel'])){
320       $this->forward_dialog= FALSE;
321       $this->dialog= FALSE;
322     }
324     /* Finished adding of locals? */
325     if (isset($_POST['add_locals_finish'])){
327       /* Check if we are able to write gosaMailForwardingAddress */
328       if($this->acl_is_writeable("gosaMailForwardingAddress")){
330         /* Walk through list of forwarders, ignore own addresses */
331         foreach ($_POST['local_list'] as $val){
332           if (!in_array ($val, $this->gosaMailAlternateAddress) &&
333               $val != $this->mail){
335             $this->addForwarder($val);
336             $this->is_modified= TRUE;
337           }
338         }
339       }
340       $this->forward_dialog= FALSE;
341       $this->dialog= FALSE;
342     }
344     /* Add forward email addresses */
345     if (isset($_POST['add_forwarder'])){
346       if ($_POST['forward_address'] != ""){
348         /* Valid email address specified? */
349         $address= $_POST['forward_address'];
350         $valid= FALSE;
351         if (!is_email($address)){
352           if (!is_email($address, TRUE)){
353             if ($this->is_template){
354               $valid= TRUE;
355             } else {
356               print_red (_("You're trying to add an invalid email address to the list of forwarders."));
357             }
358           }
359         } elseif ($address == $this->mail
360             || in_array($address, $this->gosaMailAlternateAddress)) {
362           print_red (_("Adding your one of your own addresses to the forwarders makes no sense."));
364         } else {
365           $valid= TRUE;
366         }
368         if ($valid){
370           /* Add it, if we are able to write gosaMailForwardingAddress */
371           if($this->acl_is_writeable("gosaMailForwardingAddress")){
372             $this->addForwarder ($address);
373             $this->is_modified= TRUE;
374           }
375         }
376       }
377     }
379     /* Delete forward email addresses */
380     if (isset($_POST['delete_forwarder'])){
381       $this->delForwarder ($_POST['forwarder_list']);
382     }
385     /* Add alternate email addresses */
386     if (isset($_POST['add_alternate'])){
388       $valid= FALSE;
389       if (!is_email($_POST['alternate_address'])){
390         if ($this->is_template){
391           if (!(is_email($_POST['alternate_address'], TRUE))){
392             print_red (_("You're trying to add an invalid email address to the list of alternate addresses."));
393           } else {
394             $valid= TRUE;
395           }
396         } else {
397           print_red (_("You're trying to add an invalid email address to the list of alternate addresses."));
398         }
400       } else {
401         $valid= TRUE;
402       }
404       if ($valid && ($user= $this->addAlternate ($_POST['alternate_address'])) != ""){
405         $ui= get_userinfo();
406         if ($user != $ui->username){
407           print_red (_("The address you're trying to add is already used by user")." '$user'.");
408         }
409       }
410     }
412     /* Delete alternate email addresses */
413     if (isset($_POST['delete_alternate']) && isset($_POST['alternates_list'])){
414       $this->delAlternate ($_POST['alternates_list']);
415     }
417   
418     /* Vacation message */
419   
420     /* Import vacation message? */
421     if (isset($_POST["import_vacation"]) && isset($this->vacation[$_POST["vacation_template"]])){
422       $contents= "";
423       $lines= file($_POST["vacation_template"]);
424       foreach ($lines as $line){
425         if (!preg_match('/^DESC:/', $line)){
426           $contents.= $line;
427         }
428       }
430       /* Replace attributes */
431       $attrs= $this->parent->by_object['user']->attributes;
432       foreach ($attrs as $val){
433         
434         if(preg_match("/dateOfBirth/",$val)){
435           if($this->parent->by_object['user']->use_dob){
436             $contents= preg_replace("/%$val/",date("Y-d-m",$this->parent->by_object['user']->dateOfBirth),$contents);
437           }
438         }else {
439           $contents= preg_replace("/%$val/",
440               $this->parent->by_object['user']->$val, $contents);
441         }
442       }
444       /* Save message */
445       $this->gosaVacationMessage= htmlspecialchars($contents);
446     }
448   
449     /* Display forward dialog if requested above */
451     /* Show forward add dialog */
452     if ($this->forward_dialog){
453       $ldap= $this->config->get_ldap_link();
455       /* Save data */
456       $mailfilter= get_global("mailfilter");
457       foreach( array("depselect", "muser", "regex") as $type){
458         if (isset($_POST[$type])){
459           $mailfilter[$type]= $_POST[$type];
460         }
461       }
462       if (isset($_GET['search'])){
463         $s= mb_substr($_GET['search'], 0, 1, "UTF8")."*";
464         if ($s == "**"){
465           $s= "*";
466         }
467         $mailfilter['regex']= $s;
468       }
469       register_global("mailfilter", $mailfilter);
471       /* Get actual list */
472       $mailusers= array ();
473       if ($mailfilter['regex'] != '*' && $mailfilter['regex'] != ""){
474         $regex= $mailfilter['regex'];
475         $filter= "(|(mail=$regex)(gosaMailAlternateAddress=$regex))";
476       } else {
477         $filter= "";
478       }
479       if ($mailfilter['muser'] != ""){
480         $user= $mailfilter['muser'];
481         $filter= "$filter(|(uid=$user)(cn=$user)(givenName=$user)(sn=$user))";
482       }
484       /* Add already present people to the filter */
485       $exclude= "";
486       foreach ($this->gosaMailForwardingAddress as $mail){
487         $exclude.= "(mail=$mail)";
488       }
489       if ($exclude != ""){
490         $filter.= "(!(|$exclude))";
491       }
493       $res= get_list("(&(objectClass=gosaMailAccount)$filter)", "users", $mailfilter['depselect'], 
494                      array("sn", "mail", "givenName"), GL_SIZELIMIT | GL_SUBSEARCH);
495       $ldap->cd($mailfilter['depselect']);
496       $ldap->search ("(&(objectClass=gosaMailAccount)$filter)", array("sn", "mail", "givenName"));
497       error_reporting (0);
498       while ($attrs= $ldap->fetch()){
499         if(preg_match('/%/', $attrs['mail'][0])){
500           continue;
501         }
502         $name= $this->make_name($attrs);
503         $mailusers[$attrs['mail'][0]]= $name."&lt;".
504           $attrs['mail'][0]."&gt;";
505       }
506       error_reporting (E_ALL);
507       natcasesort ($mailusers);
508       reset ($mailusers);
510       /* Show dialog */
511       $smarty->assign("search_image", get_template_path('images/search.png'));
512       $smarty->assign("usearch_image", get_template_path('images/search_user.png'));
513       $smarty->assign("tree_image", get_template_path('images/tree.png'));
514       $smarty->assign("infoimage", get_template_path('images/info.png'));
515       $smarty->assign("launchimage", get_template_path('images/small_filter.png'));
516       $smarty->assign("mailusers", $mailusers);
517       if (isset($_POST['depselect'])){
518         $smarty->assign("depselect", $_POST['depselect']);
519       }
520       $smarty->assign("deplist", $this->config->idepartments);
521       $smarty->assign("apply", apply_filter());
522       $smarty->assign("alphabet", generate_alphabet());
523       $smarty->assign("hint", print_sizelimit_warning());
524       foreach( array("depselect", "muser", "regex") as $type){
525         $smarty->assign("$type", $mailfilter[$type]);
526       }
527       $smarty->assign("hint", print_sizelimit_warning());
529       $display.= $smarty->fetch (get_template_path('mail_locals.tpl', TRUE, dirname(__FILE__)));
530       return ($display);
531     }
533     /* Display mail account tab */
535     $smarty->assign("mailServers", $mailserver);
536     $SkipWrite = (!isset($this->parent) || !$this->parent) && !isset($_SESSION['edit']);
538     $tmp  = $this->plInfo();
539     foreach($tmp['plProvidedAcls'] as $name => $transl){
540       $smarty->assign("$name"."ACL", $this->getacl($name,$SkipWrite));
541     }
543     foreach(array("gosaMailServer", "gosaMailQuota", "perms", "mail",
544           "gosaMailAlternateAddress", "gosaMailForwardingAddress",
545           "gosaVacationMessage", "gosaMailDeliveryMode", "gosaVacationStart",
546           "gosaVacationStop", "gosaMailMaxSize", "gosaSpamSortLevel", "gosaSpamMailbox") as $val){
547       $smarty->assign("$val", $this->$val);
548     }
550     if (is_numeric($this->gosaMailQuota) && $this->gosaMailQuota != 0){
551       $smarty->assign("quotausage", progressbar(round(($this->quotaUsage * 100)/ $this->gosaMailQuota),100,15,true));
552       $smarty->assign("quotadefined", "true");
553     } else {
554       $smarty->assign("quotadefined", "false");
555     }
557     /* Disable mail field if needed */
558     $method= new $this->method($this->config);
559     if ($method->uattrib == "mail" && $this->initially_was_account){
560       $smarty->assign("mailACL", preg_replace("/w/","",$this->getacl("mail",$SkipWrite)));
561     }
563     /* Disable/Enable range select, but do not disable them twice 
564      *  if they are already diabled by "use own sieve script"
565      */
566     if (preg_match('/V/', $this->gosaMailDeliveryMode) || preg_match("/C/",$this->gosaMailDeliveryMode)){
567       $smarty->assign('rangeEnabled', "");
568     } else {
569       $smarty->assign('rangeEnabled', "disabled");
570     }
572     if (!preg_match("/L/", $this->gosaMailDeliveryMode)) {
573       $smarty->assign("only_local", "checked");
574     } else {
575       $smarty->assign("only_local", "");
576     }
578     $types = array(
579           "V"=>"use_vacation",
580           "S"=>"use_spam_filter",
581           "R"=>"use_mailsize_limit",
582           "I"=>"drop_own_mails",
583           "C"=>"own_script");
585     /* Fill checkboxes */
586     foreach($types as $option => $varname){
587       if (preg_match("/".$option."/", $this->gosaMailDeliveryMode)) {
588         $smarty->assign($varname, "checked");
589       } else {
590         $smarty->assign($varname, "");
591       }
592     }
593    
594     /* Display mail account tab */
595     if($this->gosaVacationStart ==0){
596       $date= getdate(time());
597     }else{
598       $date= getdate($this->gosaVacationStart);
599     }
600     $days= array();
601     for($d= 1; $d<32; $d++){
602       $days[$d]= $d;
603     }
604     $years= array();
605     for($y= $date['year']-10; $y<$date['year']+10; $y++){
606       $years[]= $y;
607     }
608     $months= array(_("January"), _("February"), _("March"), _("April"),
609         _("May"), _("June"), _("July"), _("August"), _("September"),
610         _("October"), _("November"), _("December"));
611     $smarty->assign("start_day", $date["mday"]);
612     $smarty->assign("days", $days);
613     $smarty->assign("months", $months);
614     $smarty->assign("start_month", $date["mon"]-1);
615     $smarty->assign("years", $years);
616     $smarty->assign("start_year", $date["year"]);
618     if($this->gosaVacationStop ==0){
619       $date= getdate(time());
620       $date["mday"]++;
621     }else{
622       $date= getdate($this->gosaVacationStop);
623     }
624     $smarty->assign("end_day", $date["mday"]);
625     $smarty->assign("end_month", $date["mon"]-1);
626     $smarty->assign("end_year", $date["year"]);
629  
630     /* Have vacation templates? */
631     $smarty->assign("template", "");
632     if (count($this->vacation)){
633       $smarty->assign("show_templates", "true");
634       $smarty->assign("vacationtemplates", $this->vacation);
635       if (isset($_POST['vacation_template'])){
636         $smarty->assign("template", $_POST['vacation_template']);
637       }
638     } else {
639       $smarty->assign("show_templates", "false");
640     }
642     /* Fill spam selector */
643     $spamlevel= array();
644     for ($i= 0; $i<21; $i++){
645       $spamlevel[]= $i;
646     }
647     $smarty->assign("spamlevel", $spamlevel);
648     $smarty->assign("spambox", $this->mailboxList);
650     $display.= $smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
651     return ($display);
652   }
655   /* remove object from parent */
656   function remove_from_parent()
657   {
658     /* Cancel if there's nothing to do here */
659     if (!$this->initially_was_account){
660       return;
661     }
662     
663     /* include global link_info */
664     $ldap= $this->config->get_ldap_link();
666     /* Remove and write to LDAP */
667     plugin::remove_from_parent();
669     /* Zero arrays */
670     $this->attrs['gosaMailAlternateAddress']= array();
671     $this->attrs['gosaMailForwardingAddress']= array();
673     /* Adapt attributes if needed */
674     $method= new $this->method($this->config);
675     $method->fixAttributesOnRemove($this);
677     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,$this->attributes, "Save");
678     $ldap->cd($this->dn);
679     $this->cleanup();
681     $ldap->modify ($this->attrs); 
683     /* Add "view" to logging class */ 
684     @log::log("remove","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
686     show_ldap_error($ldap->get_error(), sprintf(_("Removing of user/mail account with dn '%s' failed."),$this->dn));
688     /* Connect to IMAP server for account deletion */
689     if ($this->gosaMailServer != ""){
690       $method= new $this->method($this->config);
691       $id= $method->uattrib;
692       if ($method->connect($this->gosaMailServer)){
694         /* Remove account from IMAP server */
695         $method->deleteMailbox($this->folder_prefix.$this->$id);
696         $method->disconnect();
697       }
698     }
700     /* Optionally execute a command after we're done */
701     $this->handle_post_events("remove",array("uid" => $this->uid));
702   }
704   
705   /* check if we have some delegations configured, those delegations must be removed first */
706   function accountDelegationsConfigured()
707   { 
708     /* We are in administrational edit mode.
709         Check tab configurations directly */
710     if(isset($this->attrs)){
711       $checkArray  = array("kolabInvitationPolicy","unrestrictedMailSize", "calFBURL","kolabDelegate","kolabFreeBusyFuture");
712       foreach($checkArray as $index){
713         if(isset($this->attrs[$index])){
714            return(true);
715         }
716       }
717     }
718     return(false); 
719   }
720  
722   /* Save data to object */
723   function save_object()
724   {
725     if (isset($_POST['mailTab'])){
727       /* Save ldap attributes */
728       plugin::save_object();
731       if(isset($_POST['own_script'])){
733         if(!preg_match("/C/",$this->gosaMailDeliveryMode)){
734           $str= preg_replace("/[\[\]]/","",$this->gosaMailDeliveryMode);
735           $this->gosaMailDeliveryMode = "[".$str."C]";
736         }
738       }else{
740         /* Assemble mail delivery mode
741            The mode field in ldap consists of values between braces, this must
742            be called when 'mail' is set, because checkboxes may not be set when
743            we're in some other dialog.
745           Example for gosaMailDeliveryMode [LR        ]
746           L: Local delivery
747           R: Reject when exceeding mailsize limit
748           S: Use spam filter
749           V: Use vacation message
750           C: Use custm sieve script
751           I: Only insider delivery */
753         $tmp= preg_replace("/[^a-z]/i","",$this->gosaMailDeliveryMode);
756         /* Handle delivery flags */
757         if($this->acl_is_writeable("gosaMailDeliveryModeL")){
758           if(!preg_match("/L/",$tmp) && !isset($_POST['only_local'])){
759             $tmp.="L";
760           }elseif(preg_match("/L/",$tmp) && isset($_POST['only_local'])){
761             $tmp = preg_replace("/L/","",$tmp);
762           }
763         }
765         $opts = array(     
766             "R"   => "use_mailsize_limit",
767             "S"   => "use_spam_filter",
768             "V"   => "use_vacation",
769             "C"   => "own_script",
770             "I"   => "drop_own_mails");
772         foreach($opts as $flag => $post){
773           if($this->acl_is_writeable("gosaMailDeliveryMode".$flag)){
774             if(!preg_match("/".$flag."/",$tmp) && isset($_POST[$post])){
775               $tmp.= $flag;
776             }elseif(preg_match("/".$flag."/",$tmp) && !isset($_POST[$post])){
777               $tmp = preg_replace("/".$flag."/","",$tmp);
778             }
779           }
780         }
782         $tmp= "[$tmp]";
783         if ($this->gosaMailDeliveryMode != $tmp){
784           $this->is_modified= TRUE;
785         }
786         $this->gosaMailDeliveryMode= $tmp;
787       }
788     }
790   }
793   /* Save data to LDAP, depending on is_account we save or delete */
794   function save()
795   {
796     $ldap= $this->config->get_ldap_link();
798     /* Call parents save to prepare $this->attrs */
799     plugin::save();
801     /* Save arrays */
802     $this->attrs['gosaMailAlternateAddress']= $this->gosaMailAlternateAddress;
803     $this->attrs['gosaMailForwardingAddress']= $this->gosaMailForwardingAddress;
805     /* Adapt attributes if needed */
806     $method= new $this->method($this->config);
807     $id= $method->uattrib;
809     $method->fixAttributesOnStore($this);
811     /* Remove Mailquota if = "" or "0"  */
812     if((isset($this->attrs['gosaMailQuota']))&&(!$this->attrs['gosaMailQuota'])) {
813       $this->attrs['gosaMailQuota']=0;
814     }
816     if(empty($this->attrs['gosaSpamMailbox'])){
817       unset($this->attrs['gosaSpamMailbox']);
818     }
820     $this->attrs['mail'] = strtolower($this->attrs['mail']); 
822         /* Remove attributes - if not needed */
823     if (!preg_match('/V/', $this->gosaMailDeliveryMode)){
824       unset($this->attrs['gosaVacationStart']);
825       unset($this->attrs['gosaVacationStop']);
826     }
829     /* Remove attributes - if not needed */
830     if (!preg_match('/V/', $this->gosaMailDeliveryMode)){
831       unset($this->attrs['gosaVacationStart']);
832       unset($this->attrs['gosaVacationStop']);
833     }
835     /* Save data to LDAP */
836     $ldap->cd($this->dn);
837     $this->cleanup();
838     $ldap->modify ($this->attrs); 
840     show_ldap_error($ldap->get_error(), sprintf(_("Saving of user/mail account with dn '%s' failed."),$this->dn));
842     /* Log last action */ 
843     if($this->initially_was_account){
844       @log::log("modify","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
845     }else{
846       @log::log("create","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
847     }
849     /* Only do IMAP actions if we are not a template */
850     if (!$this->is_template){
852       if ($method->connect($this->gosaMailServer)){
853         $method->updateMailbox($this->folder_prefix.$this->$id);
854         
855         $method->setQuota($this->folder_prefix.$this->$id, $this->gosaMailQuota);
856         $method->disconnect();
858         /* Ensure that this is an existing account */
859         if(1==1 || $this->initially_was_account){
861           /* Write sieve information only if not in C mode */
862           if (!is_integer(strpos($this->gosaMailDeliveryMode, "C"))){
863             $method->configureFilter($this->$id,
864                 $this->gosaMailDeliveryMode,
865                 $this->mail,
866                 $this->gosaMailAlternateAddress,
867                 $this->gosaMailMaxSize,
868                 $this->gosaSpamMailbox,
869                 $this->gosaSpamSortLevel,
870                 $this->gosaVacationMessage);
871           }else{
872             $this->sieve_management->save();
873           }
874         }
875       }
876     }
878     /* Optionally execute a command after we're done */
879     if ($this->initially_was_account == $this->is_account){
880       if ($this->is_modified){
881         $this->handle_post_events("modify", array("uid" => $this->uid));
882       }
883     } else {
884       $this->handle_post_events("add", array("uid" => $this->uid));
885     }
887   }
890   /* Check formular input */
891   function check()
892   {
893     if(!$this->is_account) return(array());
895     $ldap= $this->config->get_ldap_link();
897     /* Call common method to give check the hook */
898     $message= plugin::check();
900     if(empty($this->gosaMailServer)){
901       $message[]= _("There is no valid mailserver specified, please add one in the system setup.");
902     }
904     /* must: mail */
905     if ($this->mail == ""){
906       $message[]= _("The required field 'Primary address' is not set.");
907     }
908     if ($this->is_template){
909       if (!is_email($this->mail, TRUE)){
910         $message[]= _("Please enter a valid email address in 'Primary address' field.");
911       }
912     } else {
913       if (!is_email($this->mail)){
914         $message[]= _("Please enter a valid email address in 'Primary address' field.");
915       }
916     }
917     $ldap->cd($this->config->current['BASE']);
918     $ldap->search ("(&(!(objectClass=gosaUserTemplate))(objectClass=gosaMailAccount)(|(mail=".$this->mail.")(gosaMailAlternateAddress=".$this->mail."))(!(uid=".$this->uid."))(!(cn=".$this->uid.")))", array("uid"));
919     if ($ldap->count() != 0){
920       $message[]= _("The primary address you've entered is already in use.");
921     }
923     /* Check quota */
924     if ($this->gosaMailQuota != '' && $this->acl_is_writeable("gosaMailQuota")){
925       if (!is_numeric($this->gosaMailQuota)) {
926         $message[]= _("Value in 'Quota size' is not valid.");
927       } else {
928         $this->gosaMailQuota= (int) $this->gosaMailQuota;
929       }
930     }
932     /* Check rejectsize for integer */
933     if ($this->gosaMailMaxSize != '' && $this->acl_is_writeable("gosaMailMaxSize")){
934       if (!is_numeric($this->gosaMailMaxSize)){
935         $message[]= _("Please specify a vaild mail size for mails to be rejected.");
936       } else {
937         $this->gosaMailMaxSize= (int) $this->gosaMailMaxSize;
938       }
939     }
941     /* Need gosaMailMaxSize if use_mailsize_limit is checked */
942     if (is_integer(strpos($this->gosaMailDeliveryMode, "R")) && 
943         $this->gosaMailMaxSize == ""){
945       $message[]= _("You need to set the maximum mail size in order to reject anything.");
946     }
948     if((preg_match("/S/", $this->gosaMailDeliveryMode))&&(empty($this->gosaSpamMailbox))) {
949       $message[]= _("You specified Spam settings, but there is no Folder specified.");
950     }
952     if (preg_match('/V/', $this->gosaMailDeliveryMode) && $this->gosaVacationStart >= $this->gosaVacationStop){
953       $message[]= _("Time interval to show vacation message is not valid.");
954     }
956     return ($message);
957   }
960   /* Adapt from template, using 'dn' */
961   function adapt_from_template($dn)
962   {
963     plugin::adapt_from_template($dn);
965     foreach (array("gosaMailAlternateAddress", "gosaMailForwardingAddress") as $val){
966       $this->$val= array();
967       if (isset($this->attrs["$val"]["count"])){
968         for ($i= 0; $i<$this->attrs["$val"]["count"]; $i++){
969           $value= $this->attrs["$val"][$i];
970           foreach (array("sn", "givenName", "uid") as $repl){
971             if (preg_match("/%$repl/i", $value)){
972               $value= preg_replace ("/%$repl/i", $this->parent->$repl, $value);
973             }
974           }
975           array_push($this->$val, strtolower(rewrite($value)));
976         }
977       }
978     }
979     $this->mail= strtolower(rewrite($this->mail));
980   }
983   /* Add entry to forwarder list */
984   function addForwarder($address)
985   {
986     if($this->acl_is_writeable("gosaMailForwardingAddress")){
987       $this->gosaMailForwardingAddress[]= $address;
988       $this->gosaMailForwardingAddress= array_unique ($this->gosaMailForwardingAddress);
989       sort ($this->gosaMailForwardingAddress);
990       reset ($this->gosaMailForwardingAddress);
991       $this->is_modified= TRUE;
992     }else{
993       print_red(_("You are not allowed to write mail forwarding."));
994     }
995   }
998   /* Remove list of addresses from forwarder list */
999   function delForwarder($addresses)
1000   {
1001     if($this->acl_is_writeable("gosaMailForwardingAddress")){
1002       $this->gosaMailForwardingAddress= array_remove_entries ($addresses, $this->gosaMailForwardingAddress);
1003       $this->is_modified= TRUE;
1004     }else{
1005       print_red(_("You are not allowed to write mail forwarding."));
1006     }
1007   }
1010   /* Add given mail address to the list of alternate adresses , 
1011      check if this mal address is used, skip adding in this case */
1012   function addAlternate($address)
1013   {
1014     if($this->acl_is_writeable("gosaMailAlternateAddress")){
1015       $ldap= $this->config->get_ldap_link();
1016       $address= strtolower($address);
1018       /* Is this address already assigned in LDAP? */
1019       $ldap->cd ($this->config->current['BASE']);
1020       $ldap->search ("(&(objectClass=gosaMailAccount)(|(mail=$address)"."(gosaMailAlternateAddress=$address)))", array("uid"));
1021       $ldap->search ("(&(!(objectClass=gosaUserTemplate))(objectClass=gosaMailAccount)(|(mail=$address)"."(gosaMailAlternateAddress=$address)))", array("uid"));
1023       if ($ldap->count() > 0){
1024         $attrs= $ldap->fetch ();
1025         return ($attrs["uid"][0]);
1026       }
1028       /* Add to list of alternates */
1029       if (!in_array($address, $this->gosaMailAlternateAddress)){
1030         $this->gosaMailAlternateAddress[]= $address;
1031         $this->is_modified= TRUE;
1032       }
1034       sort ($this->gosaMailAlternateAddress);
1035       reset ($this->gosaMailAlternateAddress);
1036       return ("");
1037     }else{
1038       print_red(_("You are not allowed to write mail alternate address."));
1039     }
1040   }
1043   function delAlternate($addresses)
1044   {
1045     if($this->acl_is_writeable("gosaMailAlternateAddress")){
1046       $this->gosaMailAlternateAddress= array_remove_entries ($addresses,$this->gosaMailAlternateAddress);
1047       $this->is_modified= TRUE;
1048     }else{
1049       print_red(_("You are not allowed to write mail alternate address."));
1050     }
1051   }
1053   function make_name($attrs)
1054   {
1055     $name= "";
1056     if (isset($attrs['sn'][0])){
1057       $name= $attrs['sn'][0];
1058     }
1059     if (isset($attrs['givenName'][0])){
1060       if ($name != ""){
1061         $name.= ", ".$attrs['givenName'][0];
1062       } else {
1063         $name.= $attrs['givenName'][0];
1064       }
1065     }
1066     if ($name != ""){
1067       $name.= " ";
1068     }
1070     return ($name);
1071   }
1073   
1074   /* Create the mail part for the copy & paste dialog */
1075   function getCopyDialog()
1076   {
1077     if(!$this->is_account) return("");
1078     $smarty = get_smarty();
1079     $smarty->assign("mail",$this->mail); 
1080     $smarty->assign("gosaMailAlternateAddress",$this->gosaMailAlternateAddress);
1081     $smarty->assign("gosaMailForwardingAddress",$this->gosaMailForwardingAddress);
1082     $str = $smarty->fetch(get_template_path("copypaste.tpl",TRUE, dirname(__FILE__)));
1084     $ret = array();
1085     $ret['status'] = "";
1086     $ret['string'] = $str;
1087     return($ret);
1088   }
1090   function saveCopyDialog()
1091   {
1092     if(!$this->is_account) return;  
1094     /* Execute to save mailAlternateAddress && gosaMailForwardingAddress */
1095     $this->execute();
1096     
1097     if(isset($_POST['mail'])){
1098       $this->mail = $_POST['mail'];
1099     }
1101   }
1103   function allow_remove()
1104   {
1105     if (isset($this->config->current['MAILMETHOD'])){
1106       $method= $this->config->current['MAILMETHOD'];
1107       if(preg_match("/olab/i",$method)){
1108         $ldap = $this->config->get_ldap_link();
1109         $ldap->cd($this->config->current['BASE']);
1110         $ldap->cat($this->dn);
1111         if($ldap->count()){
1112           $attrs = $ldap->fetch();
1113           if(isset($attrs['kolabDeleteFlag'])){ 
1114             return(_("Waiting for kolab to remove mail properties."));
1115           }elseif(in_array("gosaMailAccount",$attrs['objectClass'])){
1116             return(_("Please remove the mail account first, to allow kolab to call its remove methods."));
1117           }
1118         }
1119       }
1120     }
1121   }
1123    
1124   function PrepareForCopyPaste($source)
1125   {
1126     plugin::PrepareForCopyPaste($source);
1128     /* Reset alternate mail addresses */
1129     $this->gosaMailAlternateAddress = array();    
1130    }
1133   function plInfo()
1134   {
1135     return (array(
1136           "plShortName"     => _("Mail"),
1137           "plDescription"   => _("Mail settings"),
1138           "plSelfModify"    => TRUE,
1139           "plDepends"       => array("user"),                     // This plugin depends on
1140           "plPriority"      => 4,                                 // Position in tabs
1141           "plSection"     => array("personal" => _("My account")),
1142           "plCategory"    => array("users"),
1143           "plOptions"       => array(),
1144   
1145           "plProvidedAcls"  => array(
1146             "mail"                      =>  _("Mail address"),
1147             "gosaMailServer"            =>  _("Mail server"),
1148             "gosaMailQuota"             =>  _("Quota size"),
1150             "gosaMailDeliveryModeV"     =>  _("Add vacation information"),  // This is flag of gosaMailDeliveryMode
1151             "gosaVacationMessage"       =>  _("Vacation message"),
1153             "gosaMailDeliveryModeS"     =>  _("Use spam filter"),           // This is flag of gosaMailDeliveryMode
1154             "gosaSpamSortLevel"         =>  _("Spam level"),
1155             "gosaSpamMailbox"           =>  _("Spam mail box"),
1157             "sieveManagement"           =>  _("Sieve management"),
1159             "gosaMailDeliveryModeR"     =>  _("Reject due to mailsize"),    // This is flag of gosaMailDeliveryMode
1160             "gosaMailMaxSize"           =>  _("Mail max size"),
1162             "gosaMailForwardingAddress" =>  _("Forwarding address"),
1163             "gosaMailDeliveryModeL"     =>  _("Local delivery"),            // This is flag of gosaMailDeliveryMode
1164             "gosaMailDeliveryModeI"     =>  _("No delivery to own mailbox "),     // This is flag of gosaMailDeliveryMode
1165             "gosaMailAlternateAddress"  =>  _("Mail alternative addresses"),
1167             "gosaMailForwardingAddress" =>  _("Forwarding address"),
1168             "gosaMailDeliveryModeC"     =>  _("Use custom sieve script"))   // This is flag of gosaMailDeliveryMode
1169         ));
1170   }
1173 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1174 ?>