Code

Udpated mailMethod
[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   /* plugin specific values */
27   var $mail                               = "";
28   var $uid                                = "";
29   var $gosaMailAlternateAddress           = array();
30   var $gosaMailForwardingAddress          = array();
31   var $gosaMailDeliveryMode               = "[L        ]";
32   var $gosaMailServer                     = "";
33   var $gosaMailQuota                      = "";
34   var $gosaMailMaxSize                    = "";
35   var $gosaVacationMessage                = "";
36   var $gosaVacationStart                  = 0;
37   var $gosaVacationStop                   = 0;
38   var $gosaSpamSortLevel                  = "";
39   var $gosaSpamMailbox                    = "";
41   var $quotaUsage                         = 0;
42   var $forward_dialog                     = FALSE;
43   var $folder_prefix                      = "";
44   var $mailboxList                        = array("INBOX");
45   var $default_permissions                = "none";
46   var $member_permissions                 = "post";
47   var $members                            = array();
48   var $admins                             = array();
49   var $vacations                          = array();
50   var $perms                              = array(  "lrs"       => "read", 
51                                                     "lrsp"      => "post", 
52                                                     "lrsip"     => "append",
53                                                     "lrswipcd"  => "write", 
54                                                     "lrswipcda" => "all" );
56   /* attribute list for save action */
57   var $attributes= array("mail", "gosaMailServer", "gosaMailQuota", "gosaMailMaxSize","gosaMailForwardingAddress",
58       "gosaMailDeliveryMode", "gosaSpamSortLevel", "gosaSpamMailbox","gosaMailAlternateAddress",
59       "gosaVacationMessage", "gosaMailAlternateAddress", "gosaMailForwardingAddress", "gosaVacationStart", "gosaVacationStop");
60   var $objectclasses= array("gosaMailAccount");
62   var $sieve_management = NULL;
64   /* constructor, if 'dn' is set, the node loads the given
65      'dn' from LDAP */
66   function mailAccount ($config, $dn= NULL, $parent= NULL)
67   {
68     /* Load bases attributes */
69     plugin::plugin($config, $dn, $parent);
71     if(isset($this->attrs['uid'])){
72       $this->uid = $this->attrs['uid'][0];
73     }
74  
75     if(is_array($this->gosaMailServer) && isset($this->gosaMailServer[0])){
76       $this->gosaMailServer = $this->gosaMailServer[0];
77     }
79     /* Save initial account state */
80     $this->initially_was_account= $this->is_account;
82     /*  Set mailMethod to the one defined in gosa.conf */
83     if (isset($this->config->current['MAILMETHOD'])){
84       $method= $this->config->current['MAILMETHOD'];
85       if (class_exists("mailMethod$method")){
86         $this->method= "mailMethod$method";
87       } else {
88         print_red(sprintf(_("There is no mail method '%s' specified in your gosa.conf available."), $method));
89       }
90     }
92     /* Create the account prefix  user. user/ 
93        Preset folder prefix. Will change it later to respect
94        altnamespace. */
95     if (isset($this->config->current['CYRUSUNIXSTYLE']) && $this->config->current['CYRUSUNIXSTYLE'] == "true"){
96       $this->folder_prefix= "user/";
97     }elseif (isset($this->config->data['MAIN']['CYRUSUNIXSTYLE']) && $this->config->data['MAIN']['CYRUSUNIXSTYLE'] == "true"){
98       $this->folder_prefix= "user/";
99     } else {
100       $this->folder_prefix= "user.";
101     }
102    
103     /* This is not a new account, parse additional attributes */
104     if (($dn != NULL) && ($dn != "new") && $this->is_account){
106       /* Load attributes containing arrays */
107       foreach (array("gosaMailAlternateAddress", "gosaMailForwardingAddress") as $val){
108         $this->$val= array();
109         if (isset($this->attrs["$val"]["count"])){
110           for ($i= 0; $i<$this->attrs["$val"]["count"]; $i++){
111             array_push($this->$val, $this->attrs["$val"][$i]);
112           }
113         }
114       }
117       /* Only do IMAP actions if gosaMailServer attribute is set */
118       if (isset ($this->attrs["gosaMailServer"][0])){
120         $method = new $this->method($this->config);
121         $id     = $method->uattrib;
123         /* Adapt attributes if needed */
124         $method->fixAttributesOnLoad($this);
126         /* FixAttributesOnLoad possibly creates an array out of gosaMailServer.
127             If the mail tab wasn't opened once before saving, the account can't be saved */
128         if(is_array($this->gosaMailServer)){
129           $this->gosaMailServer = $this->gosaMailServer[0];
130         }
132         if ($method->connect($this->attrs["gosaMailServer"][0])){
134           /* Update quota values */
135           $quota= $method->getQuota($this->folder_prefix.$this->$id);
136          
137           if($quota){
138             if ($quota['gosaMailQuota'] == 2147483647){
139               $this->quotaUsage     = "";
140               $this->gosaMailQuota  = "";
141             } else {
142               $this->quotaUsage     = $quota['quotaUsage'];
143               $this->gosaMailQuota  = $quota['gosaMailQuota'];
144             }
145           }else{
146             $this->quotaUsage     = "";
147             $this->gosaMailQuota  = "";
148 //            print_red(sprintf(_("Can't get quota information for '%s'."),$this->folder_prefix.$this->$id));
149           }
151           /* Get mailboxes / folder like INBOX ..*/
152           $this->mailboxList= $method->getMailboxList($this->folder_prefix.$this->$id,$this->$id);
153           
154           $method->disconnect();
155         }else{
156           /* Could not connect to ldap.
157            */
158           if (isset($this->attrs['gosaMailQuota'][0])){
159             $this->gosaMailQuota = $this->attrs['gosaMailQuota'][0];
160           }
161         }
162       }
163     }
166     /* Get vacation message */
168     /* Fill vacation array */
169     $this->vacation= array();
170     if (isset($this->config->current['VACATIONDIR'])){
171       $dir= $this->config->current['VACATIONDIR'];
172       if (is_dir($dir) && is_readable($dir)){
174         /* Look for files and build the vacation array */
175         $dh= opendir($dir);
176         while ($file = readdir($dh)){
177           $description= $this->parse_vacation("$dir/$file");
178           if ($description != ""){
179             $this->vacation["$dir/$file"]= $description;
180           }
181         }
182         closedir($dh);
183       }
184     }
186     /* Create sieve management class */
187     $method = new $this->method($this->config);
188     $id     = $method->uattrib;
189     $this->sieve_management = new sieveManagement($this->config,$this->dn,$this,$id);
191   /* Create filter */
193     /* Get global filter config */
194     if (!is_global("mailfilter")){
195       $ui= get_userinfo();
196       $base= get_base_from_people($ui->dn);
197       $mailfilter= array( "depselect"       => $base,
198           "muser"            => "",
199           "regex"           => "*");
200       register_global("mailfilter", $mailfilter);
201     }
202   }
205   function parse_vacation($file)
206   {
207     $desc= "";
209     if (is_file($file)){
210       $fh = fopen($file, "r");
211       $line= fgets($fh, 256);
213       if (!preg_match('/^DESC:/', $line)){
214         print_red (_("No DESC tag in vacation file:")." $file");
215         return $desc;
216       }
217       fclose ($fh);
219       $desc= trim(preg_replace('/^DESC:\s*/', '', $line));
220     }
222     return $desc;
223   }
226   function execute()
227   {
228     /* Call parent execute */
229     plugin::execute();
231     /* Initialise vars */
233     /* Load templating engine */
234     $smarty= get_smarty();
235     $display= "";
237     /* Get available mailserver */
238     $mailserver= array();
239     foreach ($this->config->data['SERVERS']['IMAP'] as $key => $val){
240       $mailserver[]= $key;
241     }
244     /*
245      * Sieve Management
246      */
247     if(isset($_POST['sieveManagement'])
248         && preg_match("/C/",$this->gosaMailDeliveryMode)
249         && chkacl($this->acl,"sieveManagement") == "") {
250       $this->dialog = $this->sieve_management;
251     }
253     /* Cancel sieve edit */
254     if(isset($_POST['sieve_cancel'])){
255       $this->dialog = NULL;
256     }
258     /* Save sieve changes */
259     if(isset($_POST['sieve_finish'])){
260       $this->sieve_management = $this->dialog;
261       $this->dialog = NULL;
262     }
264     if(is_object($this->dialog)){
265       $this->dialog->save_object();
266       return($this->dialog->execute());
267     }
270     /* Handle account state */
272     /* Do we need to flip is_account state? */
273     if (isset($_POST['modify_state'])){
275       /* Onyl change account state if allowed */
276       if($this->is_account && $this->acl == "#all#" && !$this->accountDelegationsConfigured()){
277         $this->is_account= !$this->is_account;
278       }elseif(!$this->is_account && chkacl($this->acl,"create") == ""){
279         $this->is_account= !$this->is_account;
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_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_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_header(_("Create mail account"), _("This account has mail features disabled. You can enable them by clicking below."));
304         return ($display);
305       }
306     }
308     /* Forwarder  subdialog */
310     /* Trigger forward add dialog? */
311     if (isset($_POST['add_local_forwarder'])){
312       $this->forward_dialog= TRUE;
313       $this->dialog= TRUE;
314     }
316     /* Cancel forward add dialog? */
317     if (isset($_POST['add_locals_cancel'])){
318       $this->forward_dialog= FALSE;
319       $this->dialog= FALSE;
320     }
322     /* Finished adding of locals? */
323     if (isset($_POST['add_locals_finish'])){
324       if (count ($_POST['local_list']) &&
325           chkacl ($this->acl, "gosaMailForwardingAddress") == ""){
327         /* Walk through list of forwarders, ignore own addresses */
328         foreach ($_POST['local_list'] as $val){
329           if (!in_array ($val, $this->gosaMailAlternateAddress) &&
330               $val != $this->mail){
332             $this->addForwarder($val);
333             $this->is_modified= TRUE;
334           }
335         }
336       }
337       $this->forward_dialog= FALSE;
338       $this->dialog= FALSE;
339     }
341     /* Add forward email addresses */
342     if (isset($_POST['add_forwarder'])){
343       if ($_POST['forward_address'] != ""){
345         /* Valid email address specified? */
346         $address= $_POST['forward_address'];
347         $valid= FALSE;
348         if (!is_email($address)){
349           if (!is_email($address, TRUE)){
350             if ($this->is_template){
351               $valid= TRUE;
352             } else {
353               print_red (_("You're trying to add an invalid email address to the list of forwarders."));
354             }
355           }
356         } elseif ($address == $this->mail
357             || in_array($address, $this->gosaMailAlternateAddress)) {
359           print_red (_("Adding your one of your own addresses to the forwarders makes no sense."));
361         } else {
362           $valid= TRUE;
363         }
365         if ($valid){
366           /* Add it */
367           if (chkacl ($this->acl, "gosaMailForwardingAddress") == ""){
368             $this->addForwarder ($address);
369             $this->is_modified= TRUE;
370           }
372         }
373       }
374     }
376     /* Delete forward email addresses */
377     if (isset($_POST['delete_forwarder'])){
378       if (count($_POST['forwarder_list']) 
379           && chkacl ($this->acl, "gosaMailForwardingAddress") == ""){
381         $this->delForwarder ($_POST['forwarder_list']);
382       }
383     }
385     
386     /* Alternate address handling */
388     /* Add alternate email addresses */
389     if (isset($_POST['add_alternate'])){
390       if ($_POST['alternate_address'] != "" &&
391           chkacl ($this->acl, "gosaMailAlternateAddress") == ""){
393         $valid= FALSE;
394         if (!is_email($_POST['alternate_address'])){
395           if ($this->is_template){
396             if (!(is_email($_POST['alternate_address'], TRUE))){
397               print_red (_("You're trying to add an invalid email address to the list of alternate addresses."));
398             } else {
399               $valid= TRUE;
400             }
401           } else {
402             print_red (_("You're trying to add an invalid email address to the list of alternate addresses."));
403           }
405         } else {
406           $valid= TRUE;
407         }
409         if ($valid && ($user= $this->addAlternate ($_POST['alternate_address'])) != ""){
410           $ui= get_userinfo();
411           if ($user != $ui->username && !$this->is_template){
412             print_red (_("The address you're trying to add is already used by user")." '$user'.");
413           }
414         }
415       }
416     }
418     /* Delete alternate email addresses */
419     if (isset($_POST['delete_alternate']) && isset ($_POST['alternates_list'])){
420       if (count($_POST['alternates_list']) &&
421           chkacl ($this->acl, "gosaMailAlternateAddress") == ""){
423         $this->delAlternate ($_POST['alternates_list']);
424       }
425     }
427   
428     /* Vocation message */
429   
430     /* Import vacation message? */
431     if (isset($_POST["import_vacation"]) && isset($this->vacation[$_POST["vacation_template"]])){
432       $contents= "";
433       $lines= file($_POST["vacation_template"]);
434       foreach ($lines as $line){
435         if (!preg_match('/^DESC:/', $line)){
436           $contents.= $line;
437         }
438       }
440       /* Replace attributes */
441       $attrs= $this->parent->by_object['user']->attributes;
442       foreach ($attrs as $val){
443         
444         if(preg_match("/dateOfBirth/",$val)){
445           if($this->parent->by_object['user']->use_dob){
446             $contents= preg_replace("/%$val/",date("Y-d-m",$this->parent->by_object['user']->dateOfBirth),$contents);
447           }
448         }else {
449           $contents= preg_replace("/%$val/",
450               $this->parent->by_object['user']->$val, $contents);
451         }
452         
453         /* Replace vacation start and end time */
454         if(preg_match("/%start/",$contents)){
455           $contents = preg_replace("/%start/",date("d.m.Y",$this->gosaVacationStart),$contents);
456         }
457         if(preg_match("/%end/",$contents)){
458           $contents = preg_replace("/%end/",date("d.m.Y",$this->gosaVacationStop),$contents);
459         }
460       }
462       /* Save message */
463       $this->gosaVacationMessage= htmlspecialchars($contents);
464     }
466   
467     /* Display forward dialog if requested above */
469     /* Show forward add dialog */
470     if ($this->forward_dialog){
471       $ldap= $this->config->get_ldap_link();
473       /* Save data */
474       $mailfilter= get_global("mailfilter");
475       foreach( array("depselect", "muser", "regex") as $type){
476         if (isset($_POST[$type])){
477           $mailfilter[$type]= $_POST[$type];
478         }
479       }
480       if (isset($_GET['search'])){
481         $s= mb_substr($_GET['search'], 0, 1, "UTF8")."*";
482         if ($s == "**"){
483           $s= "*";
484         }
485         $mailfilter['regex']= $s;
486       }
487       register_global("mailfilter", $mailfilter);
489       /* Get actual list */
490       $mailusers= array ();
491       if ($mailfilter['regex'] != '*' && $mailfilter['regex'] != ""){
492         $regex= $mailfilter['regex'];
493         $filter= "(|(mail=$regex)(gosaMailAlternateAddress=$regex))";
494       } else {
495         $filter= "";
496       }
497       if ($mailfilter['muser'] != ""){
498         $user= $mailfilter['muser'];
499         $filter= "$filter(|(uid=$user)(cn=$user)(givenName=$user)(sn=$user))";
500       }
502       /* Add already present people to the filter */
503       $exclude= "";
504       foreach ($this->gosaMailForwardingAddress as $mail){
505         $exclude.= "(mail=$mail)";
506       }
507       if ($exclude != ""){
508         $filter.= "(!(|$exclude))";
509       }
511       $acl= array($this->config->current['BASE'] => ":all");
512       $res= get_list("(&(objectClass=gosaMailAccount)$filter)", $acl, $mailfilter['depselect'], 
513                      array("sn", "mail", "givenName"), GL_SIZELIMIT | GL_SUBSEARCH);
514       $ldap->cd($mailfilter['depselect']);
515       $ldap->search ("(&(objectClass=gosaMailAccount)$filter)", array("sn", "mail", "givenName"));
516       error_reporting (0);
517       while ($attrs= $ldap->fetch()){
518         if(preg_match('/%/', $attrs['mail'][0])){
519           continue;
520         }
521         $name= $this->make_name($attrs);
522         $mailusers[$attrs['mail'][0]]= $name."&lt;".
523           $attrs['mail'][0]."&gt;";
524       }
525       error_reporting (E_ALL);
526       natcasesort ($mailusers);
527       reset ($mailusers);
529       /* Show dialog */
530       $smarty->assign("search_image", get_template_path('images/search.png'));
531       $smarty->assign("usearch_image", get_template_path('images/search_user.png'));
532       $smarty->assign("tree_image", get_template_path('images/tree.png'));
533       $smarty->assign("infoimage", get_template_path('images/info.png'));
534       $smarty->assign("launchimage", get_template_path('images/small_filter.png'));
535       $smarty->assign("mailusers", $mailusers);
536       if (isset($_POST['depselect'])){
537         $smarty->assign("depselect", $_POST['depselect']);
538       }
539       $smarty->assign("deplist", $this->config->idepartments);
540       $smarty->assign("apply", apply_filter());
541       $smarty->assign("alphabet", generate_alphabet());
542       $smarty->assign("hint", print_sizelimit_warning());
543       foreach( array("depselect", "muser", "regex") as $type){
544         $smarty->assign("$type", $mailfilter[$type]);
545       }
546       $smarty->assign("hint", print_sizelimit_warning());
548       $display.= $smarty->fetch (get_template_path('mail_locals.tpl', TRUE, dirname(__FILE__)));
549       return ($display);
550     }
552     /* Display mail account tab */
553     if($this->gosaVacationStart ==0){
554       $date= getdate(time());
555       $this->gosaVacationStart = time();
556     }else{
557       $date= getdate($this->gosaVacationStart);
558     }
559     $days= array();
560     for($d= 1; $d<32; $d++){
561       $days[$d]= $d;
562     }
563     $years= array();
564     for($y= $date['year']-10; $y<$date['year']+10; $y++){
565       $years[]= $y;
566     }
567     $months= array(_("January"), _("February"), _("March"), _("April"),
568         _("May"), _("June"), _("July"), _("August"), _("September"),
569         _("October"), _("November"), _("December"));
570     $smarty->assign("start_day", $date["mday"]);
571     $smarty->assign("days", $days);
572     $smarty->assign("months", $months);
573     $smarty->assign("start_month", $date["mon"]-1);
574     $smarty->assign("years", $years);
575     $smarty->assign("start_year", $date["year"]);
577     if($this->gosaVacationStop ==0){
578       $date= getdate(time());
579       $date["mday"]++;
580       $this->gosaVacationStop = time() + (60*60*24);
581     }else{
582       $date= getdate($this->gosaVacationStop);
583     }
584     $smarty->assign("end_day", $date["mday"]);
585     $smarty->assign("end_month", $date["mon"]-1);
586     $smarty->assign("end_year", $date["year"]);
588     $smarty->assign("mailServers", $mailserver);
589     foreach(array(
590           "gosaMailServer", 
591           "gosaMailQuota", 
592           "perms", 
593           "mail",
594           "gosaMailAlternateAddress", 
595           "gosaMailForwardingAddress",
597           // gosaMailDeliveryMode Flags 
598           "drop_own_mails",                       // No local delivery 
599           "gosaMailMaxSize",                      // Enable - Drop mails > max size
600           "gosaSpamSortLevel", "gosaSpamMailbox", // Enable - Spam sort options
601           "gosaVacationMessage",                  // Enable - Vacation message      
602           "gosaVacationStart",
603           "gosaVacationStop",
604           "custom_sieve",                         // Use custom sieve script
605           "only_local"                            // Send/receive local mails 
606                                         ) as $val){
607       if(isset($this->$val)){
608         $smarty->assign("$val", $this->$val);
609       }
610       $smarty->assign("$val"."ACL", chkacl($this->acl, "$val"));
611     }
613     $smarty->assign("sieveManagementACL", chkacl($this->acl,"sieveManagement"));
615     if (preg_match('/V/', $this->gosaMailDeliveryMode)){
616       $smarty->assign('rangeEnabled', "");
617     } else {
618       $smarty->assign('rangeEnabled', "disabled");
619     }
621     if (is_numeric($this->gosaMailQuota) && $this->gosaMailQuota != 0){
622       $smarty->assign("quotausage", progressbar(round(($this->quotaUsage * 100)/ $this->gosaMailQuota),100,15,true));
623       $smarty->assign("quotadefined", "true");
624     } else {
625       $smarty->assign("quotadefined", "false");
626     }
628     /* Disable mail field if needed */
629     $method= new $this->method($this->config);
630     if ($method->uattrib == "mail" && $this->initially_was_account){
631       $smarty->assign("mailACL", "disabled");
632     }
635     if (!preg_match("/L/", $this->gosaMailDeliveryMode)) {
636       $smarty->assign("drop_own_mails", "checked");
637     } else {
638       $smarty->assign("drop_own_mails", "");
639     }
641     $types = array(
642           "V"=>"use_vacation",
643           "S"=>"use_spam_filter",
644           "R"=>"use_mailsize_limit",
645           "I"=>"only_local",
646           "C"=>"own_script");
648     /* Fill checkboxes */
649     foreach($types as $option => $varname){
650       if (preg_match("/".$option."/", $this->gosaMailDeliveryMode)) {
651         $smarty->assign($varname, "checked");
652       } else {
653         $smarty->assign($varname, "");
654       }
655     }
656     
657     if (preg_match("/V/", $this->gosaMailDeliveryMode)) {
658       $smarty->assign("use_vacation", "checked");
659     } else {
660       $smarty->assign("use_vacation", "");
661     }
662     if (preg_match("/S/", $this->gosaMailDeliveryMode)) {
663       $smarty->assign("use_spam_filter", "checked");
664     } else {
665       $smarty->assign("use_spam_filter", "");
666     }
667     if (preg_match("/R/", $this->gosaMailDeliveryMode)) {
668       $smarty->assign("use_mailsize_limit", "checked");
669     } else {
670       $smarty->assign("use_mailsize_limit", "");
671     }
672     if (preg_match("/I/", $this->gosaMailDeliveryMode)) {
673       $smarty->assign("only_local", "checked");
674     } else {
675       $smarty->assign("only_local", "");
676     }
677     if (preg_match("/C/", $this->gosaMailDeliveryMode)) {
678       $smarty->assign("own_script", "checked");
679     } else {
680       $smarty->assign("own_script", "");
681     }
683     /* Have vacation templates? */
684     $smarty->assign("template", "");
685     if (count($this->vacation)){
686       $smarty->assign("show_templates", "true");
687       $smarty->assign("vacationtemplates", $this->vacation);
688       if (isset($_POST['vacation_template'])){
689         $smarty->assign("template", $_POST['vacation_template']);
690       }
691     } else {
692       $smarty->assign("show_templates", "false");
693     }
695     /* Fill spam selector */
696     $spamlevel= array();
697     for ($i= 0; $i<21; $i++){
698       $spamlevel[]= $i;
699     }
700     $smarty->assign("spamlevel", $spamlevel);
701     $smarty->assign("spambox", $this->mailboxList);
702     $smarty->assign("custom_sieveACL", chkacl($this->acl, "custom_sieve"));     
703     $smarty->assign("only_localACL", chkacl($this->acl, "only_local")); 
705     $display.= $smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
706     return ($display);
707   }
709   /* check if we have some delegations configured, those delegations must be removed first */
710   function accountDelegationsConfigured()
711   { 
712     /* We are in administrational edit mode.
713         Check tab configurations directly */
714     if(isset($this->attrs)){
715       $checkArray  = array("kolabInvitationPolicy","unrestrictedMailSize", "calFBURL","kolabDelegate","kolabFreeBusyFuture");
716       foreach($checkArray as $index){
717         if(isset($this->attrs[$index])){
718            return(true);
719         }
720       }
721     }
722     if(isset($this->parent->by_object['connectivity']->plugin['kolabAccount'])){
723       if($this->parent->by_object['connectivity']->plugin['kolabAccount']->is_account){
724         return(true);
725       }
726     }
727     return(false); 
728   }
731   /* remove object from parent */
732   function remove_from_parent()
733   {
734     /* Cancel if there's nothing to do here */
735     if (!$this->initially_was_account){
736       return;
737     }
738     
739     /* include global link_info */
740     $ldap= $this->config->get_ldap_link();
742     /* Remove and write to LDAP */
743     plugin::remove_from_parent();
745     /* Zero arrays */
746     $this->attrs['gosaMailAlternateAddress']= array();
747     $this->attrs['gosaMailForwardingAddress']= array();
749     /* Adapt attributes if needed */
750     $method= new $this->method($this->config);
751     $method->fixAttributesOnRemove($this);
753     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,$this->attributes, "Save");
754     $ldap->cd($this->dn);
755     $this->cleanup();
756     $ldap->modify ($this->attrs); 
758     show_ldap_error($ldap->get_error(), _("Removing mail account failed"));
760     /* Connect to IMAP server for account deletion */
761     if ($this->gosaMailServer != ""){
762       $method= new $this->method($this->config);
763       $id= $method->uattrib;
764       if ($method->connect($this->gosaMailServer)){
766         /* Remove account from IMAP server */
767         $method->deleteMailbox($this->folder_prefix.$this->$id);
768         $method->disconnect();
769       }
770     }
772     /* Update shared folder membership, ACL may need to be updated */
773     $this->updateSharedFolder(); 
775     /* Optionally execute a command after we're done */
776     $this->handle_post_events("remove", array('uid'=> $this->uid));
777   }
780   /* Save data to object */
781   function save_object()
782   {
783     if (isset($_POST['mailTab'])){
784       /* Save ldap attributes */
785       plugin::save_object();
787       /* Assemble mail delivery mode
788          The mode field in ldap consists of values between braces, this must
789          be called when 'mail' is set, because checkboxes may not be set when
790          we're in some other dialog.
792          Example for gosaMailDeliveryMode [LR        ]
793          L: Local delivery
794          R: Reject when exceeding mailsize limit
795          S: Use spam filter
796          V: Use vacation message
797          C: Use custm sieve script
798          I: Only insider delivery */
800       $tmp= "";
801       $Flags = array(
802                      "R"  => array("ACL" => "gosaMailMaxSize",    "POST" => "use_mailsize_limit"),
803                      "V"  => array("ACL" => "gosaVacationMessage","POST" => "use_vacation"),
804                      "C"  => array("ACL" => "custom_sieve",       "POST" => "own_script"),
805                      "I"  => array("ACL" => "only_local",         "POST" => "only_local"));
807       /* Check acls and set new value if allowed. 
808          If we do not have permission to change the value 
809           check for the old value and use this */
810       foreach($Flags as $flag => $val){
811         $acl  = $val['ACL'];
812         $post = $val['POST'];
813         if(chkacl($this->acl,$acl) ==""){
814           if (isset($_POST[$post])){
815             $tmp.= $flag;
816           }
817         }else{
818           if(preg_match("/".$flag."/",$this->gosaMailDeliveryMode)){
819             $tmp.= $flag ;
820           }
821         }
822       }
824       /* ! Inverse flag handling for drop_own_mails */
825       if(chkacl($this->acl,"drop_own_mails") == ""){
826         if (!isset($_POST['drop_own_mails'])){
827           $tmp.= "L";
828         }
829       }else{
830         if(preg_match("/L/",$this->gosaMailDeliveryMode)){
831           $tmp.= "L" ;
832         }
833       }
835       /* If one of these acls are given, we are allowed to enable disable the the spam settings */
836       if(chkacl($this->acl,"gosaSpamMailbox") == "" || chkacl($this->acl,"gosaSpamSortLevel") ==""){
837         if (isset($_POST["use_spam_filter"])){
838           $tmp.= "S";
839         }
840       }else{
841         if(preg_match("/S/",$this->gosaMailDeliveryMode)){
842           $tmp.= "S" ;
843         }
844       }
845       
846       /* Check if something has changed an assign new gosaMailDeliveryMode */
847       $tmp= "[$tmp]";
848       if ($this->gosaMailDeliveryMode != $tmp){
849         $this->is_modified= TRUE;
850       }
851       $this->gosaMailDeliveryMode= $tmp;
852     }
854   }
857   /* Save data to LDAP, depending on is_account we save or delete */
858   function save()
859   {
860     $ldap= $this->config->get_ldap_link();
862     /* Call parents save to prepare $this->attrs */
863     plugin::save();
865     /* Save arrays */
866     $this->attrs['gosaMailAlternateAddress']= $this->gosaMailAlternateAddress;
867     $this->attrs['gosaMailForwardingAddress']= $this->gosaMailForwardingAddress;
869     /* Adapt attributes if needed */
870     $method= new $this->method($this->config);
871     $id= $method->uattrib;
873     $method->fixAttributesOnStore($this);
875     /* Remove Mailquota if = "" or "0"  */
876     if((isset($this->attrs['gosaMailQuota']))&&(!$this->attrs['gosaMailQuota'])) {
877       $this->attrs['gosaMailQuota']=0;
878     }
880     if(empty($this->attrs['gosaSpamMailbox'])){
881       unset($this->attrs['gosaSpamMailbox']);
882     }
884     $this->attrs['mail'] = strtolower($this->attrs['mail']); 
886     /* Remove attributes - if not needed */
887     if (!preg_match('/V/', $this->gosaMailDeliveryMode)){
888       unset($this->attrs['gosaVacationStart']);
889       unset($this->attrs['gosaVacationStop']);
890     }
892     /* Save data to LDAP */
893     $ldap->cd($this->dn);
894     $this->cleanup();
895     $ldap->modify ($this->attrs); 
897     show_ldap_error($ldap->get_error(), _("Saving mail account failed"));
899     /* Only do IMAP actions if we are not a template */
900     if (!$this->is_template){
902       if ($method->connect($this->gosaMailServer)){
903         $method->updateMailbox($this->folder_prefix.$this->$id);
904         
905         $method->setQuota($this->folder_prefix.$this->$id, $this->gosaMailQuota);
906         $method->disconnect();
908         /* Only talk with sieve if the mail account already exists */
909         if($this->initially_was_account){
910          
911           /* Write sieve information only if not in C mode */
912           if (!is_integer(strpos($this->gosaMailDeliveryMode, "C"))){
913             $method->configureFilter($this->$id,
914                 $this->gosaMailDeliveryMode,
915                 $this->mail,
916                 $this->gosaMailAlternateAddress,
917                 $this->gosaMailMaxSize,
918                 $this->gosaSpamMailbox,
919                 $this->gosaSpamSortLevel,
920                 $this->gosaVacationMessage);
921             $this->is_modified = TRUE;
922           }else{
923             $this->sieve_management->save();
924           }
925         }
926       }
927     }
929     /* Optionally execute a command after we're done */
930     if ($this->initially_was_account == $this->is_account){
931       if ($this->is_modified){
932         $this->handle_post_events("modify", array('uid'=> $this->uid));
933       }
934     } else {
935       $this->handle_post_events("add", array('uid'=>$this->uid));
936     }
938     $this->updateSharedFolder();
939   }
942   /* Check formular input */
943   function check()
944   {
945     if(!$this->is_account) return(array());
947     $ldap= $this->config->get_ldap_link();
949     /* Call common method to give check the hook */
950     $message= plugin::check();
952     if(empty($this->gosaMailServer)){
953       $message[]= _("There is no valid mailserver specified, please add one in the system setup.");
954     }
956     /* must: mail */
957     if ($this->mail == ""){
958       $message[]= _("The required field 'Primary address' is not set.");
959     }
960     if ($this->is_template){
961       if (!is_email($this->mail, TRUE)){
962         $message[]= _("Please enter a valid email address in 'Primary address' field.");
963       }
964     } else {
965       if (!is_email($this->mail)){
966         $message[]= _("Please enter a valid email address in 'Primary address' field.");
967       }
968     }
969     $ldap->cd($this->config->current['BASE']);
970     $ldap->search ("(&(!(objectClass=gosaUserTemplate))(objectClass=gosaMailAccount)(|(mail=".$this->mail.")(gosaMailAlternateAddress=".$this->mail."))(!(uid=".$this->uid."))(!(cn=".$this->uid.")))", array("uid"));
971     if ($ldap->count() != 0){
972       $message[]= _("The primary address you've entered is already in use.");
973     }
975     /* Check quota */
976     if ($this->gosaMailQuota != '' && chkacl ($this->acl, "gosaMailQuota") == ""){
977       if (!is_numeric($this->gosaMailQuota)) {
978         $message[]= _("Value in 'Quota size' is not valid.");
979       } else {
980         $this->gosaMailQuota= (int) $this->gosaMailQuota;
981       }
982     }
984     /* Check rejectsize for integer */
985     if ($this->gosaMailMaxSize != '' && chkacl ($this->acl, "gosaMailQuota") == ""){
986       if (!is_numeric($this->gosaMailMaxSize)){
987         $message[]= _("Please specify a vaild mail size for mails to be rejected.");
988       } else {
989         $this->gosaMailMaxSize= (int) $this->gosaMailMaxSize;
990       }
991     }
993     /* Need gosaMailMaxSize if use_mailsize_limit is checked */
994     if (is_integer(strpos($this->gosaMailDeliveryMode, "R")) && 
995         $this->gosaMailMaxSize == ""){
997       $message[]= _("You need to set the maximum mail size in order to reject anything.");
998     }
1000     if((preg_match("/S/", $this->gosaMailDeliveryMode))&&(empty($this->gosaSpamMailbox))) {
1001       $message[]= _("You specified Spam settings, but there is no Folder specified.");
1002     }
1004     if (preg_match('/V/', $this->gosaMailDeliveryMode) && $this->gosaVacationStart > $this->gosaVacationStop){
1005       $message[]= _("Time interval to show vacation message is not valid.");
1006     }
1008     return ($message);
1009   }
1012   /* Adapt from template, using 'dn' */
1013   function adapt_from_template($dn)
1014   {
1015     plugin::adapt_from_template($dn);
1017     foreach (array("gosaMailAlternateAddress", "gosaMailForwardingAddress") as $val){
1018       $this->$val= array();
1019       if (isset($this->attrs["$val"]["count"])){
1020         for ($i= 0; $i<$this->attrs["$val"]["count"]; $i++){
1021           $value= $this->attrs["$val"][$i];
1022           foreach (array("sn", "givenName", "uid") as $repl){
1023             if (preg_match("/%$repl/i", $value)){
1024               $value= preg_replace ("/%$repl/i", $this->parent->$repl, $value);
1025             }
1026           }
1027           array_push($this->$val, strtolower(rewrite($value)));
1028         }
1029       }
1030     }
1031     $this->mail= strtolower(rewrite($this->mail));
1032   }
1035   /* Add entry to forwarder list */
1036   function addForwarder($address)
1037   {
1038     $this->gosaMailForwardingAddress[]= $address;
1039     $this->gosaMailForwardingAddress= array_unique ($this->gosaMailForwardingAddress);
1040     sort ($this->gosaMailForwardingAddress);
1041     reset ($this->gosaMailForwardingAddress);
1042     $this->is_modified= TRUE;
1043   }
1046   /* Remove list of addresses from forwarder list */
1047   function delForwarder($addresses)
1048   {
1049     $this->gosaMailForwardingAddress= array_remove_entries ($addresses, $this->gosaMailForwardingAddress);
1050     $this->is_modified= TRUE;
1051   }
1054   /* Add given mail address to the list of alternate adresses , 
1055       check if this mal address is used, skip adding in this case */
1056   function addAlternate($address)
1057   {
1058     $ldap= $this->config->get_ldap_link();
1059     $address= strtolower($address);
1060       
1061     /* Is this address already assigned in LDAP? */
1062     $ldap->cd ($this->config->current['BASE']);
1063     $ldap->search ("(&(!(objectClass=gosaUserTemplate))(objectClass=gosaMailAccount)(|(mail=$address)"."(gosaMailAlternateAddress=$address)))", array("uid"));
1065     if ($ldap->count() > 0){
1066       $attrs= $ldap->fetch ();
1067       return ($attrs["uid"][0]);
1068     }
1070     /* Add to list of alternates */
1071     if (!in_array($address, $this->gosaMailAlternateAddress)){
1072       $this->gosaMailAlternateAddress[]= $address;
1073       $this->is_modified= TRUE;
1074     }
1076     sort ($this->gosaMailAlternateAddress);
1077     reset ($this->gosaMailAlternateAddress);
1078     return ("");
1079   }
1082   function delAlternate($addresses)
1083   {
1084     $this->gosaMailAlternateAddress= array_remove_entries ($addresses,
1085                                                            $this->gosaMailAlternateAddress);
1086     $this->is_modified= TRUE;
1087   }
1089   function make_name($attrs)
1090   {
1091     $name= "";
1092     if (isset($attrs['sn'][0])){
1093       $name= $attrs['sn'][0];
1094     }
1095     if (isset($attrs['givenName'][0])){
1096       if ($name != ""){
1097         $name.= ", ".$attrs['givenName'][0];
1098       } else {
1099         $name.= $attrs['givenName'][0];
1100       }
1101     }
1102     if ($name != ""){
1103       $name.= " ";
1104     }
1106     return ($name);
1107   }
1109   
1110   /* Create the mail part for the copy & paste dialog */
1111   function getCopyDialog()
1112   {
1113     if(!$this->is_account) return("");
1114     $smarty = get_smarty();
1115     $smarty->assign("mail",$this->mail); 
1116     $smarty->assign("gosaMailAlternateAddress",$this->gosaMailAlternateAddress);
1117     $smarty->assign("gosaMailForwardingAddress",$this->gosaMailForwardingAddress);
1118     $str = $smarty->fetch(get_template_path("copypaste.tpl",TRUE, dirname(__FILE__)));
1120     $ret = array();
1121     $ret['status'] = "";
1122     $ret['string'] = $str;
1123     return($ret);
1124   }
1126   function saveCopyDialog()
1127   {
1128     if(!$this->is_account) return;  
1130     /* Execute to save mailAlternateAddress && gosaMailForwardingAddress */
1131     $this->execute();
1132     
1133     if(isset($_POST['mail'])){
1134       $this->mail = $_POST['mail'];
1135     }
1136   }
1138    
1139   function PrepareForCopyPaste($source)
1140   {
1141     plugin::PrepareForCopyPaste($source);
1143     /* Reset alternate mail addresses */
1144     $this->gosaMailAlternateAddress = array();    
1145   }
1148   function allow_remove()
1149   {
1150     if (isset($this->config->current['MAILMETHOD'])){
1151       $method= $this->config->current['MAILMETHOD'];
1152       if(preg_match("/olab/i",$method)){
1153         $ldap = $this->config->get_ldap_link();
1154         $ldap->cd($this->config->current['BASE']);
1155         $ldap->cat($this->dn);
1156         if($ldap->count()){
1157           $attrs = $ldap->fetch();
1158           if(isset($attrs['kolabDeleteFlag'])){ 
1159             return(_("Waiting for kolab to remove mail properties."));
1160           }elseif(in_array("gosaMailAccount",$attrs['objectClass'])){
1161             return(_("Please remove the mail account first, to allow kolab to call its remove methods."));
1162           }
1163         }
1164       }
1165     }
1166   }
1168   /* Upated shared folder ACLs 
1169    */
1170   function updateSharedFolder()
1171   {
1172     $ldap = $this->config->get_ldap_link();
1173     $ldap->cd($this->config->current['BASE']);
1174     $ldap->search("(&(objectClass=posixGroup)(objectClass=gosaMailAccount)(memberUid=".$this->uid."))",array('dn','cn'));
1175     if(class_exists("grouptabs")){
1176       while($attrs = $ldap->fetch()){
1177         $tmp = new grouptabs($this->config, $this->config->data['TABS']['GROUPTABS'], $attrs['dn']);
1178         if(isset($tmp->by_object['mailgroup'])){
1179           $tmp->by_object['mailgroup']->members= $tmp->by_object['group']->memberUid;
1180           if(!$this->is_account){
1181             $tmp->by_object['mailgroup']->removeUserAcl($this->uid);
1182             $tmp->by_object['mailgroup']->removeUserAcl($this->mail);
1183           }
1184           $tmp->by_object['mailgroup']->save();
1185         }
1186       }
1187     } 
1188   }
1191 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1192 ?>