Code

Updated css und div framework.
[gosa.git] / plugins / admin / groups / class_groupMail.inc
1 <?php
3 class mailgroup extends plugin
4 {
5   /* CLI vars */
6   var $cli_summary        = "Manage mail groups/shared folders";
7   var $cli_description    = "Some longer text\nfor help";
8   var $cli_parameters     = array("eins" => "Eins ist toll", "zwei" => "Zwei ist noch besser");
10   var $uid                        = "";       // User id 
11   var $cn                         = "";       // cn
12   var $orig_cn                    = "";       // cn
14   var $method                     = "mailMethod"; // Used Mail method 
15   var $mmethod                    = "";           // Contains the gosa.conf MAILMETHOD
16   var $mail                       = "";           // Default mail address 
18   var $gosaMailAlternateAddress   = array();  // Set default Alternate Mail Adresses to empty array
19   var $gosaMailForwardingAddress  = array();  // Forwarding also empty
21   var $gosaMailServer             = "";       // Selected mailserver 
22   var $gosaMailQuota              = "";       // Defined Quota 
23   var $quotaUsage                 = 0;        // Currently used quota
25   var $gosaVacationMessage        = "";       // Vocation message 
27   var $imapacl                    = array('anyone'    => 'p',     // Set acls for everyone
28       '%members%' => 'lrsp',  // %members% are all group-members
29       ''          => 'p');    // Every user added gets this right
32   var $gosaSpamSortLevel          = "";     
33   var $gosaSpamMailbox            = "";
34   var $gosaSharedFolderTarget     ;
36   var $forward_dialog             = FALSE;    
38   var $members                    = array();  // Group members
40   var $mailusers                  = array();
41   var $perms                      = array();
42   var $gosaMailDeliveryMode       = "[L        ]";   // 
43   var $gosaMailMaxSize            = "";       // 
44   
45   var $remove_folder_from_imap    = true;
47   /* Helper */
48   var $indexed_acl= array();
49   var $indexed_user= array();
51   /* attribute list for save action */
52   var $attributes= array( "mail",   "gosaMailServer", "gosaMailQuota", "gosaMailMaxSize",
53       "gosaMailAlternateAddress", "gosaMailForwardingAddress",
54       "gosaMailDeliveryMode", "gosaSpamSortLevel", "gosaSpamMailbox",
55       "acl","gosaSharedFolderTarget", "gosaVacationMessage");
57   var $objectclasses= array("gosaMailAccount");
58   var $CopyPasteVars          = array("quotaUsage","imapacl");
60   function mailgroup ($config, $dn= NULL, $ui= NULL)
61   {
62     /* Initialise all available attributes ... if possible
63      */
64     plugin::plugin($config, $dn);
66     $this->orig_cn = $this->cn;
68     /* Set mailMethod to the one defined in gosa.conf 
69      */
70     if (isset($this->config->current['MAILMETHOD'])){
71       $this->mmethod= $this->config->current['MAILMETHOD'];
72     }
74     /* Check if selected mail method exists 
75      */
76     if (class_exists("mailMethod$this->mmethod")){
77       $this->method= "mailMethod$this->mmethod";
78     } else {
79       print_red(sprintf(_("There is no mail method '%s' specified in your gosa.conf available."), $this->mmethod));
80     }
82     /* Load Mailserver  
83      */
84     if(isset($this->attrs['gosaMailServer'][0])){
85       $this->gosaMailServer =  $this->attrs['gosaMailServer'][0];
86     }
88     /* Convert cn to uid in case of existing entry
89      */
90     if (isset($this->attrs['cn'][0])){
91       $this->uid= $this->attrs['cn'][0];
92     }
95     /* If this ins't new mailgroup, read all required data from ldap
96      */
97     if (($dn != "new")&&($dn != NULL)){
99       /* Load attributes which represent multiple entries  
100        */
101       foreach (array("gosaMailAlternateAddress", "gosaMailForwardingAddress") as $val){
102         $this->$val = array();
103         if (isset($this->attrs["$val"]["count"])){
104           for ($i= 0; $i<$this->attrs["$val"]["count"]; $i++){
105             array_push($this->$val, $this->attrs["$val"][$i]);
106           }
107         }
108       }
110       /* Only do IMAP actions if gosaMailServer attribute is set 
111        */
112       if (isset ($this->attrs["gosaMailServer"][0])){
114         /* Create new instance of our defined mailclass
115          */
116         $method= new $this->method($this->config);
118         if ($method->connect($this->attrs["gosaMailServer"][0])){
119         
121           /* Maybe the entry is not saved in new style, get
122              permissions from IMAP and convert them to acl attributes */
123           if (!isset($this->attrs['acl'])){
124             $this->imapacl=  $method->getSharedFolderPermissions($this->uid);
126             /* Need to filter what a member acl could be... */
127             $vote= array();
128             $peak= 0;
129             $leader= "";
130             foreach ($this->imapacl as $user => $acl){
132               if ($user != "anyone" ){
133                 if (!isset($vote[$acl])){
134                   $vote[$acl]= 1;
135                 } else {
136                   $vote[$acl]++;
137                 }
138                 if ($vote[$acl] > $peak){
139                   $leader= $acl;
140                   $peek= $vote[$acl];
141                 }
142               }
144             }
146             /* Highest count wins as %members%, remove all members
147                with the same acl */
148             if(!empty($leader)){
149               $this->imapacl['%members%']= $leader;
150             }
151             foreach ($this->imapacl as $user => $acl){
152               if ($this->acl == $leader && in_array($user, $this->attrs['memberUid'])){
153                 unset($this->imapacl[$user]);
154               }
155             }
157           } // ENDE ! isset ($this->attrs['acl'])
158           
159           /* Adapt attributes if needed */
160           $method->fixAttributesOnLoad($this);
161           
162           /*  get Quota */
163           $quota= $method->getQuota($this->uid);
165           /* Update quota values */
166           if(is_array($quota)){
167             if ($quota['gosaMailQuota'] == 2147483647){
168               $this->quotaUsage= "";
169               $this->gosaMailQuota= "";
170             } else {
171               $this->quotaUsage= $quota['quotaUsage'];
172               $this->gosaMailQuota= $quota['gosaMailQuota'];
173             }
174           }else{
175             $this->quotaUsage     = "";
176             $this->gosaMailQuota  = "";
177 //            print_red(sprintf(_("Can't get quota information for '%s'."),$this->uid));
178           }
179           $method->disconnect();
180         }   // ENDE $method->connect($this->attrs["gosaMailServer"][0])){
182       }   // ENDE gosaMailServer
184     }   // ENDE dn != "new"
187     /* Get global filter config */
188     if (!is_global("gmailfilter")){
189       $ui= get_userinfo();
190       $base= get_base_from_people($ui->dn);
191       $gmailfilter= array( "depselect"       => $base,
192           "muser"            => "",
193           "regex"           => "*");
194       register_global("gmailfilter", $gmailfilter);
195     }
197     /* Load permissions */
198     $tmp = array();
199     if(preg_match("/kolab/i",$this->mmethod)){
200       $ldap = $this->config->get_ldap_link();
202       if (isset($this->attrs['acl'])){
204         for ($i= 0; $i<$this->attrs['acl']['count']; $i++){
205           list($user, $permission)= split(' ', $this->attrs['acl'][$i]);
207           /* Add to list */
208           $this->imapacl[$user]= $permission;
210           /* Get all user permissions sorted by acl, to detect the most used acl
211              This acl is then used for %members%
212            */
213           if ($user != "anyone" && $user != "%members%"){
214             $tmp[$permission][] = $user;
215           }
217           /* There is an entry in $this->imapacl like this this ... 
218              $this->attrs['imapacl']['anyone'] = "p";
219              $this->attrs['imapacl']['%members%'] = "lprs";
220              $this->attrs['imapacl'][''] = ""; <------ This is used to diplay an empty 
221              Field for special acls in our template.
222              If there is at least one special acl in out imapacl,
223              we don't need this entry anymore, because it is already displayed. 
224            */
225           if ($user != "anyone" && $user != "%members%"){
226             unset($this->imapacl['']);
227           }
228         }
229       }
231       /* In this section we dectect which acl is tho most used 
232          This will be used as %members% acl  
233        */
234       $tmp2 = array(); 
235       foreach($tmp as $acl => $user){
236         $tmp2[count($tmp[$acl])]=$acl;
237       }
238       /* Most used at last 
239        */
240       ksort($tmp2);      
241   
242       /* Assign last (most used acl) to %members% acl 
243        */
244       $str = array_pop($tmp2);
245       if(!empty($str)) {
246         $this->imapacl['%members%']=$str;
247       }
249       /* Open ldap connection 
250        */
251       $ldap = $this->config->get_ldap_link();
252       $ldap->cd($this->config->current['BASE']);
254       /* Remove those users, that use %members% acl && are member of this group. */
255       foreach($this->imapacl as $mail => $permission){
256         $ldap->search("(&(objectClass=person)(mail=".$mail."))",array("uid"));
257         $atr = $ldap->fetch();
258         if((isset($this->attrs['memberUid'])) && (is_array($this->attrs['memberUid']))){
259           if((isset($atr['uid'][0]))&&(in_array($atr['uid'][0],$this->attrs['memberUid']))&&($permission == $this->imapacl['%members%'])){
260             unset($this->imapacl[$mail]);
261           }
262         }
263       }
264       /* Append an empty entry, for special acl handling */
265       if(count($this->imapacl)==2){
266         $this->imapacl[''] ="";
267       }
268   
269     }else{ // Not kolab 
270       /* Load permissions */ 
271       if (isset($this->attrs['acl'])){
272         for ($i= 0; $i<$this->attrs['acl']['count']; $i++){
273           list($user, $permission)= split(' ', $this->attrs['acl'][$i]);
274           $this->imapacl[$user]= $permission;
275           if ($user != "anyone" && $user != "%members%"){
276             unset($this->imapacl['']);
277           }
278         }
279       }
280     }
282     /* Load Mailserver  
283      */
284     if(isset($this->attrs['gosaMailServer'][0])){
285       $this->gosaMailServer =  $this->attrs['gosaMailServer'][0];
286     }
287     /* Fill translations */
288     $this->perms["lrs"]= _("read");
289     $this->perms["lrsp"]= _("post");
290     $this->perms["p"]= _("external post");
291     $this->perms["lrsip"]= _("append");
292     $this->perms["lrswipcd"]= _("write");
293     $this->perms[""]= _("none");
294   }
296   function execute()
297   {
298     /* Call parent execute */
299     //plugin::execute();
301     /* Load templating engine */
302     $smarty= get_smarty();
304     /* Assign acls */
305     $tmp = $this->plInfo();
306     foreach($tmp['plProvidedAcls'] as $name => $translation) {
307       $smarty->assign($name."ACL",$this->getacl($name));
308     }
310     if ($_SESSION['js']==FALSE){
311       $smarty->assign("javascript", "false");
312     } else {
313       $smarty->assign("javascript", "true");
314     }
316     /* Do we need to flip is_account state? */
317     if(isset($_POST['modify_state'])){
318       if($this->is_account && $this->acl_is_removeable()){
319         $this->is_account= FALSE;
320       }elseif(!$this->is_account && $this->acl_is_createable()){
321         $this->is_account= TRUE;
322       }
323     }
325     $display = "";
327     /* Do we represent a valid account? */
328     if (!$this->is_account && $this->parent == NULL){
330       $display.= "<img alt=\"\" src=\"images/stop.png\" align=middle>&nbsp;<b>".
331         _("This 'dn' has no valid mail extensions.")."</b>";
332       return ($display);
333     }
335     /* Show tab dialog headers */
336     $display= "";
337     if ($this->parent != NULL){
338       if ($this->is_account){
339         $display.= $this->show_disable_header(_("Remove mail account"),
340             _("This account has mail features enabled. You can disable them by clicking below."));
341       } else {
342         $display.= $this->show_enable_header(_("Create mail account"),
343             _("This account has mail features disabled. You can enable them by clicking below."));
344   
345         /* Show checkbox that allows us to remove imap entry too*/
346         if($this->initially_was_account){
347           $c = "";
348           if($this->remove_folder_from_imap){
349             $c= " checked ";
350           }
351           $display .= "<h2>Shared folder delete options</h2>
352                        <input class='center' type='checkbox' name='remove_folder_from_imap' value='1' ".$c."
353                         title='"._("Remove shared folder from mail server database when entry gets removed in LDAP")."'>";
354           $display .= _("Remove the shared folder and all its contents after saving this account");
355         }
356         return ($display);
357       }
358     }
360     /* Add ACL? */
361     if($this->acl_is_writeable("acl")){
362       foreach ($this->indexed_user as $nr => $user){
363         if (isset($_POST["add_$nr"])){
364           $this->imapacl[""]= "l";
365         }
366         if (isset($_POST["del_$nr"])){
367           unset ($this->imapacl[$user]);
368         }
369       }
370     }
372     /* Trigger forward add dialog? */
373     if($this->acl_is_writeable("gosaMailForwardingAddress")){
374       if (isset($_POST['add_local_forwarder'])){
375         $this->forward_dialog= TRUE;
376         $this->dialog= TRUE;
377       }
378     }
380     /* Cancel forward add dialog? */
381     if($this->acl_is_writeable("gosaMailForwardingAddress")){
382       if (isset($_POST['add_locals_cancel'])){
383         $this->forward_dialog= FALSE;
384         $this->dialog= FALSE;
385       }
386     }
388     /* Finished adding of locals? */
389     if ((isset($_POST['add_locals_finish'])) && ($this->acl_is_writeable("gosaMailForwardingAddress"))) {
390       if (count ($_POST['local_list']) && $this->acl_is_writeable("gosaMailForwardingAddress")){
392         /* Walk through list of forwarders, ignore own addresses */
393         foreach ($_POST['local_list'] as $val){
394           if (!in_array ($val, $this->gosaMailAlternateAddress) &&
395               $val != $this->mail){
397             $this->addForwarder($val);
398           }
399         }
400       }
401       $this->forward_dialog= FALSE;
402       $this->dialog= FALSE;
403     }
405     /* Add forward email addresses */
406     if ((isset($_POST['add_forwarder'])) && ($this->acl_is_writeable("gosaMailForwardingAddress"))){
407       if ($_POST['forward_address'] != ""){
409         /* Valid email address specified? */
410         $address= $_POST['forward_address'];
411         if (!is_email($address)){
413           print_red (_("You're trying to add an invalid email address ".
414                 "to the list of forwarders."));
416         } elseif ($address == $this->mail
417             || in_array($address, $this->gosaMailAlternateAddress)) {
419           print_red (_("Adding your one of your own addresses to the forwarders makes no sense."));
421         } else {
423           /* Add it */
424           if ($this->acl_is_writeable("gosaMailForwardingAddress")){
425             $this->addForwarder ($address);
426           }
428         }
429       }
430     }
432     /* Delete forward email addresses */
433     if (isset($_POST['delete_forwarder']) && ($this->acl_is_writeable("gosaMailForwardingAddress"))){
434       if (count($_POST['forwarder_list'])&& $this->acl_is_writeable("gosaMailForwardingAddress")){
436         $this->delForwarder ($_POST['forwarder_list']);
437       }
438     }
440     /* Add alternate email addresses */
441     if (isset($_POST['add_alternate'])){
442       if ($_POST['alternate_address'] != "" && $this->acl_is_writeable("gosaMailAlternateAddress")){
444         if (!is_email($_POST['alternate_address'])){
445           print_red (_("You're trying to add an invalid email address to the list of alternate addresses."));
447         } elseif (($user= $this->addAlternate ($_POST['alternate_address'])) != ""){
448           $ui= get_userinfo();
449           if ($user != $ui->username){
450             print_red (_("The address you're trying to add is already used by user")." '$user'.");
451           }
452         }
453       }
454     }
456     /* Delete alternate email addresses */
457     if($this->acl_is_writeable("gosaMailAlternateAddress")){
458       if (isset($_POST['delete_alternate']) && isset ($_POST['alternates_list'])){
459         if (count($_POST['alternates_list']) && $this->acl_is_writeable("gosaMailAlternateAddress")){
460           $this->delAlternate ($_POST['alternates_list']);
461         }
462       }
463     }
465     /* Show forward add dialog */
466     if ($this->forward_dialog){
467       $ldap= $this->config->get_ldap_link();
469       /* Save data */
470       $gmailfilter= get_global("gmailfilter");
471       foreach( array("depselect", "muser", "regex") as $type){
472         if (isset($_POST[$type])){
473           $gmailfilter[$type]= $_POST[$type];
474         }
475       }
476       if (isset($_GET['search'])){
477         $s= mb_substr($_GET['search'], 0, 1, "UTF8")."*";
478         if ($s == "**"){
479           $s= "*";
480         }
481         $gmailfilter['regex']= $s;
482       }
483       register_global("gmailfilter", $gmailfilter);
485       /* Get actual list */
486       $mailusers= array ();
487       if ($gmailfilter['regex'] != '*' && $gmailfilter['regex'] != ""){
488         $regex= $gmailfilter['regex'];
489         $filter= "(|(mail=$regex)(gosaMailAlternateAddress=$regex))";
490       } else {
491         $filter= "";
492       }
493       if ($gmailfilter['muser'] != ""){
494         $user= $gmailfilter['muser'];
495         $filter= "$filter(|(uid=$user)(cn=$user)(givenName=$user)(sn=$user))";
496       }
498       /* Add already present people to the filter */
499       $exclude= "";
500       foreach ($this->gosaMailForwardingAddress as $mail){
501         $exclude.= "(mail=$mail)";
502       }
503       if ($exclude != ""){
504         $filter.= "(!(|$exclude))";
505       }
507       $res= get_list("(&(objectClass=gosaMailAccount)$filter)", "users", $gmailfilter['depselect'],
508                      array("sn", "mail", "givenName"), GL_SUBSEARCH | GL_SIZELIMIT);
509       $ldap->cd($gmailfilter['depselect']);
510       $ldap->search ("(&(objectClass=gosaMailAccount)$filter)", array("sn", "mail", "givenName"));
511       error_reporting (0);
512       while ($attrs= $ldap->fetch()){
513         if(preg_match('/%/', $attrs['mail'][0])){
514           continue;
515         }
516         $name= $this->make_name($attrs);
517         $mailusers[$attrs['mail'][0]]= $name."&lt;".
518           $attrs['mail'][0]."&gt;";
519       }
520       error_reporting (E_ALL);
521       natcasesort ($mailusers);
522       reset ($mailusers);
524       /* Show dialog */
525       $smarty->assign("search_image", get_template_path('images/search.png'));
526       $smarty->assign("usearch_image", get_template_path('images/search_user.png'));
527       $smarty->assign("tree_image", get_template_path('images/tree.png'));
528       $smarty->assign("infoimage", get_template_path('images/info.png'));
529       $smarty->assign("launchimage", get_template_path('images/small_filter.png'));
530       $smarty->assign("mailusers", $mailusers);
531       $smarty->assign("deplist", $this->config->idepartments);
532       $smarty->assign("apply", apply_filter());
533       $smarty->assign("alphabet", generate_alphabet());
534       $smarty->assign("hint", print_sizelimit_warning());
535       foreach( array("depselect", "muser", "regex") as $type){
536         $smarty->assign("$type", $gmailfilter[$type]);
537       }
538       $smarty->assign("hint", print_sizelimit_warning());
539       $display.= $smarty->fetch (get_template_path('mail_locals.tpl', TRUE));
540       return ($display);
541     }
543     /* Assemble normal permissions */
544     if (isset($this->imapacl['anyone'])){
545       $smarty->assign("default_permissions", $this->imapacl['anyone']);
546     }
547     $smarty->assign("member_permissions", "lrsp");
548     if (isset($this->imapacl['%members%'])){
549       $smarty->assign("member_permissions", $this->imapacl['%members%']);
550     }
552     /* Assemble extra attributes */
553     $perm= $this->getacl( "permissions");
554     $tmp= "";
555     $nr= 0;
556     $count= count($this->imapacl);
557     $this->indexed_user= array();
558     $this->indexed_acl= array();
559     foreach($this->imapacl as $user => $acl){
561       /* Add additional acl settings */
562       if ($user != "anyone" && $user != "%members%"){
564         $Dis  = "";
565         if(!preg_match("/w/",$perm)){
566           $Dis = " disabled ";
567         }
568   
569         /* Reset given Acls to ensure that nobody can read username and acls if not allwoed */
570         if(!preg_match("/r/",$perm)){
571           $user = "";
572           $nr   = "none";
573           $key  = "none";  
574         }
576         $tmp.= "<tr>  
577                  <td>
578                   <input name=\"user_$nr\" size=20 maxlength=60 value=\"$user\" ".$Dis.">
579                  </td>
580                  <td>
581                  <select size=\"1\" name=\"perm_$nr\" ".$Dis.">";
583         /* Add acl options for this additional acl setting */
584         if(preg_match("/r/",$perm)){
585           foreach ($this->perms as $key => $value){
586             if ($acl == $key){
587               $tmp.= "<option value=$key selected>$value</option>";
588             } else {
589               $tmp.= "<option value=$key>$value</option>";
590             }
591           }
592         }
593         $tmp.= "</select>&nbsp;";
596         
597         if ($nr == $count - 1){
598           if($this->acl_is_writeable("acl")){
599             $tmp.= "<input type=submit value=\""._("Add")."\" ".
600               "name=\"add_$nr\" >";
601           }
602         }
603         if ($count > 3){
604           if($this->acl_is_writeable("acl")){
605             $tmp.= "<input type=submit value=\""._("Remove")."\" ".
606               "name=\"del_$nr\" ></td></tr>";        
607           }
608         }
609       }
610       $this->indexed_user[$nr]= $user;
611       $this->indexed_acl[$nr++]= $acl;
612     }
613     $smarty->assign("plusattributes", $tmp);
615     /* Show main page */
616     $mailserver= array();
617     foreach ($this->config->data['SERVERS']['IMAP'] as $key => $val){
618       $mailserver[]= $key;
619     }
620     $smarty->assign("mailServers", $mailserver);
621     foreach(array("gosaMailServer", "gosaMailQuota", "perms", "mail",
622           "gosaMailAlternateAddress", "gosaMailForwardingAddress") as $val){
623       $smarty->assign("$val", $this->$val);
624     }
625     if (is_numeric($this->gosaMailQuota) && $this->gosaMailQuota != 0){
626       if($this->acl_is_readable("gosaMailQuota")){
627         $smarty->assign("quotausage", progressbar(round(($this->quotaUsage * 100)/ $this->gosaMailQuota),100,15,true));
628         $smarty->assign("quotadefined", "true");
629       }else{
630         $smarty->assign("quotadefined", "true");
631         $smarty->assign("quotausage", "-");
632       }
633     } else {
634       $smarty->assign("quotadefined", "false");
635     }
637     $display.= $smarty->fetch (get_template_path('mail.tpl', TRUE));
638     return ($display);
639   }
642   /* remove object from parent */
643   function remove_from_parent()
644   {
645     /* Added these ObjectClass and Attributes, because they were not 
646        removed correctly, only in case of kolab ... 
647      */
648     if(isset($this->config->current['MAILMETHOD'])&&preg_match("/kolab/i",$this->config->current['MAILMETHOD'])){
649       $this->attributes[]="acl";
650       $this->objectclasses[] = "kolabSharedFolder";
651     }
652     /* include global link_info */
653     $ldap= $this->config->get_ldap_link();
655     /* Remove and write to LDAP */
656     plugin::remove_from_parent();
658     /* Zero arrays */
659     $this->attrs['gosaMailAlternateAddress']= array();
660     $this->attrs['gosaMailForwardingAddress']= array();
661     $this->attrs['gosaSharedFolderTarget']= array();
663     /* Connect to IMAP server for account deletion */
664     if ($this->initially_was_account){
665  
666       $method= new $this->method($this->config);
667       $method->fixAttributesOnRemove($this);
668       if ($method->connect($this->gosaMailServer) && $this->remove_folder_from_imap){
670         /* Remove account from IMAP server */
671         $method->deleteMailbox($this->uid);
672         $method->disconnect();
673       }
674     }
675     /* Keep uid */
676     unset ($this->attrs['uid']);
678     $ldap->cd($this->dn);
679     $ldap->modify ($this->attrs); 
680     show_ldap_error($ldap->get_error(), sprintf(_("Removing of groups/mail with dn '%s' failed."),$this->dn));
682     /* Optionally execute a command after we're done */
683     $this->handle_post_events("remove");
684   }
687   /* Save data to object */
688   function save_object()
689   {
691     /* Check if user wants to remove the shared folder from imap too */
692     if($this->initially_was_account && !$this->is_account){
693       if(isset($_POST['remove_folder_from_imap'])){
694         $this->remove_folder_from_imap = true;
695       }else{
696         $this->remove_folder_from_imap = false;
697       }
698     }
700     /* Assemble mail delivery mode
701        The mode field in ldap consists of values between braces, this must
702        be called when 'mail' is set, because checkboxes may not be set when
703        we're in some other dialog.
705        Example for gosaMailDeliveryMode [LR        ]
706 L: Local delivery
707 R: Reject when exceeding mailsize limit
708 S: Use spam filter
709 V: Use vacation message
710 C: Use custom sieve script
711 I: Only insider delivery */
712     if (isset($_POST['mailedit'])){
714       plugin::save_object();
716       $tmp= preg_replace("/[^a-z]/i","",$this->gosaMailDeliveryMode);
718       /* Handle delivery flags */
719       if($this->acl_is_writeable("gosaMailDeliveryModeL")){
720         if(!preg_match("/L/",$tmp) && !isset($_POST['drop_own_mails'])){
721           $tmp.="L";
722         }elseif(preg_match("/L/",$tmp) && isset($_POST['drop_own_mails'])){
723           $tmp = preg_replace("/L/","",$tmp);
724         }
725       }
727       $opts = array(
728           "R"   => "use_mailsize_limit",
729           "S"   => "use_spam_filter",
730           "V"   => "use_vacation",
731           "C"   => "own_script",
732           "I"   => "only_local");
734       foreach($opts as $flag => $post){
735         if($this->acl_is_writeable("gosaMailDeliveryMode".$flag)){
736           if(!preg_match("/".$flag."/",$tmp) && isset($_POST[$post])){
737             $tmp.= $flag;
738           }elseif(preg_match("/".$flag."/",$tmp) && !isset($_POST[$post])){
739             $tmp = preg_replace("/".$flag."/","",$tmp);
740           }
741         }
742       }
744       $tmp= "[$tmp]";
745       if ($this->gosaMailDeliveryMode != $tmp){
746         $this->is_modified= TRUE;
747       }
748       $this->gosaMailDeliveryMode= $tmp;
750       /* Collect data and re-assign it to the imapacl array */
751       if ($this->acl_is_writeable("acl")){
752         $this->imapacl= array();
753         $this->imapacl['%members%']= $_POST['member_permissions'];
754         $this->imapacl['anyone']= $_POST['default_permissions'];
755         foreach ($this->indexed_user as $nr => $user){
756           if (!isset($_POST["user_$nr"])){
757             continue;
758           }
759           if ($_POST["user_$nr"] != $user ||
760               $_POST["perm_$nr"] != $this->indexed_acl[$nr]){
761             $this->is_modified= TRUE;
762           }
763           $this->imapacl[$_POST["user_$nr"]]= $_POST["perm_$nr"];
764         }
765       }
766     }
768   }
772   /* Save data to LDAP, depending on is_account we save or delete */
773   function save()
774   {
775     $ldap= $this->config->get_ldap_link();
776     $ldap->cd($this->config->current['BASE']);
778     /* Call parents save to prepare $this->attrs */
779     plugin::save();
781     /* Save arrays */
782     $this->attrs['gosaMailAlternateAddress']  = $this->gosaMailAlternateAddress;
783     $this->attrs['gosaMailForwardingAddress'] = $this->gosaMailForwardingAddress;
784     $this->attrs['gosaSharedFolderTarget']    = "share+".$this->uid;
786     if(preg_match("/kolab/i",$this->mmethod)){
787       /* Save acl's */
788       $this->attrs['acl']= array();
789       foreach ($this->imapacl as $user => $acl){
790         if ($user == ""){
791           continue;
792         }
793         $ldap->search("(&(objectClass=person)(|(uid=".$user.")(mail=".$user.")))",array("mail"));
794         $mail = $ldap->fetch();
795         if($mail){
796           if(isset($mail['mail'][0])){
797             $this->attrs['acl'][]= $mail['mail'][0]." $acl";
798           }
799         }else{
800           $this->attrs['acl'][]= "$user $acl";
801         }
802       }
803     }else{
804       /* Save acl's */
805       $this->attrs['acl']= array();
806       foreach ($this->imapacl as $user => $acl){
807         if ($user == ""){
808           continue;
809         }
810         $this->attrs['acl'][]= "$user $acl";
811       }
812     }
814     /* Only do IMAP actions if we are not a template */
815     if(preg_match("/kolab/i",$this->mmethod)){
816       if (empty($this->gosaMailServer)||is_array($this->gosaMailServer)){
817         if(isset($this->attrs['gosaMailServer'][0])){
818           $this->gosaMailServer = $this->attrs['gosaMailServer'][0];
819         }
820       }
821     }  
824     /* Exchange '%member%' pseudo entry */
825     $memberacl= $this->imapacl['%members%'];
827     foreach ($this->members as $user){
828       if(preg_match("/kolab/i",$this->mmethod)){
829         $ldap->cd($this->config->current['BASE']);
830         $ldap->search("(&(objectClass=person)(|(mail=".$user.")(uid=".$user.")))",array("mail"));
831         $at = $ldap->fetch();
832         if(isset($at['mail'][0])){
833           $user = $at['mail'][0];
834         }
835       }
836       if (!isset($this->imapacl[$user])){
837         $this->imapacl[$user]= $memberacl;
838       }
839     }
840     $this->attrs['acl'] = array();
841     
842     
843     foreach($this->imapacl as $user => $acl){
845       /* Remove empty user entry, to avoid entry like this im imap 
846        *   "" lrs
847        */
848       if(empty($user)){
849         unset($this->imapacl[$user]);
850       }
851    
852       /* Skip invalid values */
853       if(preg_match("/%members%/",$user) || empty($user)){
854         continue;
855       }
857       /* Append ldap acl entries */
858       $this->attrs['acl'][] = $user." ".$acl;
859     }
861     if ((!$this->is_template)&&(!empty($this->gosaMailServer))){
862       $method= new $this->method($this->config);
863       $method->fixAttributesOnStore($this);
864       if (($method->connect($this->gosaMailServer))){
865         $method->updateMailbox($this->uid);
866         $method->setQuota($this->uid, $this->gosaMailQuota);
867         $method->setSharedFolderPermissions($this->uid, $this->imapacl);
868         $method->disconnect();
869       }
870     }
872     /* Save data to LDAP */
873     $ldap->cd($this->dn);
874     $this->cleanup();
875     $ldap->modify ($this->attrs); 
876     show_ldap_error($ldap->get_error(), sprintf(_("Saving of groups/mail with dn '%s' failed."),$this->dn));
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");
882       }
883     } else {
884       $this->handle_post_events("add");
885     }
886   }
888   /* Check formular input */
889   function check()
890   {
891     $ldap= $this->config->get_ldap_link();
893     /* Call common method to give check the hook */
894     $message= plugin::check();
896     if(!$this->is_account) return array();
897     
898     //$message[] = $str;      
900     /* must: mail */
901     if ($this->mail == ""){
902       $message[]= _("The required field 'Primary address' is not set.");
903     }
904     if (!is_email($this->mail)){
905       $message[]= _("Please enter a valid email addres in 'Primary address' field.");
906     }
907     $ldap->cd($this->config->current['BASE']);
908     $ldap->search ("(&(!(objectClass=gosaUserTemplate))(objectClass=gosaMailAccount)(|(mail=".$this->mail.")(gosaMailAlternateAddress=".
909         $this->mail."))(!(uid=".$this->orig_cn."))(!(cn=".$this->orig_cn.")))");
910     if ($ldap->count() != 0){
911       $message[]= _("The primary address you've entered is already in use.");
912     }
913   
914     /* Check quota */
915     if ($this->gosaMailQuota != '' && $this->acl_is_writeable("gosaMailQuota")){
916       if (!is_numeric($this->gosaMailQuota)) {
917         $message[]= _("Value in 'Quota size' is not valid.");
918       } else {
919         $this->gosaMailQuota= (int) $this->gosaMailQuota;
920       }
921     }
923     /* Check rejectsize for integer */
924     if ($this->gosaMailMaxSize != '' && $this->acl_is_writeable("gosaMailQuota")){
925       if (!is_numeric($this->gosaMailMaxSize)){
926         $message[]= _("Please specify a vaild mail size for mails to be rejected.");
927       } else {
928         $this->gosaMailMaxSize= (int) $this->gosaMailMaxSize;
929       }
930     }
932     /* Need gosaMailMaxSize if use_mailsize_limit is checked */
933     if (is_integer(strpos($this->gosaMailDeliveryMode, "reject")) && $this->gosaMailMaxSize == ""){
934       $message[]= _("You need to set the maximum mail size in order to reject anything.");
935     }
937     if(ord($this->imapacl['anyone'][0])==194){
938       $message[] = _("Please choose valid permission settings. Default permission can't be emtpy.");
939     }
941     if(empty($this->gosaMailServer)){
942       $message[] = _("Please select a valid mail server.");
943     }
945     return ($message);
946   }
948   /* Adapt from template, using 'dn' */
949   function adapt_from_template($dn)
950   {
951     plugin::adapt_from_template($dn);
953     foreach (array("gosaMailAlternateAddress", "gosaMailForwardingAddress") as $val){
954       $this->$val= array();
955       if (isset($this->attrs["$val"]["count"])){
956         for ($i= 0; $i<$this->attrs["$val"]["count"]; $i++){
957           $value= $this->attrs["$val"][$i];
958           foreach (array("sn", "givenName", "uid") as $repl){
959             if (preg_match("/%$repl/i", $value)){
960               $value= preg_replace ("/%$repl/i", $this->parent->$repl, $value);
961             }
962           }
963           array_push($this->$val, $value);
964         }
965       }
966     }
967   }
969   /* Add entry to forwarder list */
970   function addForwarder($address)
971   {
972     $this->gosaMailForwardingAddress[]= $address;
973     $this->gosaMailForwardingAddress= array_unique ($this->gosaMailForwardingAddress);
975     sort ($this->gosaMailForwardingAddress);
976     reset ($this->gosaMailForwardingAddress);
977     $this->is_modified= TRUE;
978   }
980   /* Remove list of addresses from forwarder list */
981   function delForwarder($addresses)
982   {
983     $this->gosaMailForwardingAddress= array_remove_entries ($addresses,
984         $this->gosaMailForwardingAddress);
985     $this->is_modified= TRUE;
986   }
990   function addAlternate($address)
991   {
992     $ldap= $this->config->get_ldap_link();
994     $address= strtolower($address);
996     /* Is this address already assigned in LDAP? */
997     $ldap->cd ($this->config->current['BASE']);
998     $ldap->search ("(&(objectClass=gosaMailAccount)(|(mail=$address)".
999         "(gosaMailAlternateAddress=$address)))");
1001     if ($ldap->count() > 0){
1002       $attrs= $ldap->fetch ();
1003       return ($attrs["uid"][0]);
1004     }
1006     /* Add to list of alternates */
1007     if (!in_array($address, $this->gosaMailAlternateAddress)){
1008       $this->gosaMailAlternateAddress[]= $address;
1009     }
1011     sort ($this->gosaMailAlternateAddress);
1012     reset ($this->gosaMailAlternateAddress);
1013     $this->is_modified= TRUE;
1015     return ("");
1016   }
1019   function delAlternate($addresses)
1020   {
1021     $this->gosaMailAlternateAddress= array_remove_entries ($addresses,
1022         $this->gosaMailAlternateAddress);
1023     $this->is_modified= TRUE;
1024   }
1027   function make_name($attrs)
1028   {
1029     $name= "";
1030     if (isset($attrs['sn'][0])){
1031       $name= $attrs['sn'][0];
1032     }
1033     if (isset($attrs['givenName'][0])){
1034       if ($name != ""){
1035         $name.= ", ".$attrs['givenName'][0];
1036       } else {
1037         $name.= $attrs['givenName'][0];
1038       }
1039     }
1040     if ($name != ""){
1041       $name.= " ";
1042     }
1044     return ($name);
1045   }
1047   function getCopyDialog()
1048   {
1049     if(!$this->is_account) return("");
1051     $smarty = get_smarty();
1052     $smarty->assign("gosaMailAlternateAddress",$this->gosaMailAlternateAddress);
1053     $smarty->assign("gosaMailForwardingAddress",$this->gosaMailForwardingAddress);
1054     $smarty->assign("mail",$this->mail);
1055     $display= $smarty->fetch (get_template_path('paste_mail.tpl', TRUE));
1056     $ret = array();
1057     $ret['string'] = $display;
1058     $ret['status'] = "";
1059     return($ret);
1060   }
1062   function saveCopyDialog()
1063   {
1064     if(!$this->is_account) return;
1066     /* Perform ADD / REMOVE ... for mail alternate / mail forwarding addresses 
1067     */
1068     $this->execute();
1069     if(isset($_POST['mail'])){
1070       $this->mail = $_POST['mail'];
1071     }
1072   }
1075   function PrepareForCopyPaste($source)
1076   {
1077     plugin::PrepareForCopyPaste($source);
1078  
1079     /* Reset alternate mail addresses */
1080     $this->gosaMailAlternateAddress = array();
1081   }
1084   /* Return plugin informations for acl handling  */
1085   function plInfo()
1086   {
1087     return (array(
1088           "plShortName"   => _("Mail"),
1089           "plDescription" => _("Group mail"),
1090           "plSelfModify"  => FALSE,
1091           "plDepends"     => array(),
1092           "plPriority"    => 0,
1093           "plSection"     => array("administration"),
1094           "plCategory"    => array("groups"), 
1095           "plProvidedAcls"=> array(
1096             "mail"                      => _("Mail address"),
1097             "gosaMailAlternateAddress"  => _("Alternate addresses"),
1098             "gosaMailForwardingAddress" => _("Forwarding addresses"),
1099             "gosaMailQuota"             => _("Quota size"),
1100             "gosaMailServer"            => _("Mail server"),
1101             "acl"                       => _("Permissions"))
1102           ));
1103   }
1106 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1107 ?>