Code

Some Acl fixes / updates.
[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     if ((!$this->is_template)&&(!empty($this->gosaMailServer))){
825       $method= new $this->method($this->config);
826       $method->fixAttributesOnStore($this);
827       if (($method->connect($this->gosaMailServer))){
828         $method->updateMailbox($this->uid);
829         $method->setQuota($this->uid, $this->gosaMailQuota);
830         $method->setSharedFolderPermissions($this->uid, $this->imapacl);
831         $method->disconnect();
832       }
833     }
835     /* Exchange '%member%' pseudo entry */
836     $memberacl= $this->imapacl['%members%'];
838     foreach ($this->members as $user){
839       if(preg_match("/kolab/i",$this->mmethod)){
840         $ldap->cd($this->config->current['BASE']);
841         $ldap->search("(&(objectClass=person)(|(mail=".$user.")(uid=".$user.")))",array("mail"));
842         $at = $ldap->fetch();
843         if(isset($at['mail'][0])){
844           $user = $at['mail'][0];
845         }
846       }
847       if (!isset($this->imapacl[$user])){
848         $this->imapacl[$user]= $memberacl;
849       }
850     }
851     $this->attrs['acl'] = array();
852     foreach($this->imapacl as $user => $acl){
853       if(preg_match("/%members%/",$user) || empty($user)) continue;
854       
855       $this->attrs['acl'][] = $user." ".$acl;
856     }
858     /* Save data to LDAP */
859     $ldap->cd($this->dn);
860     $this->cleanup();
861     $ldap->modify ($this->attrs); 
862     show_ldap_error($ldap->get_error(), sprintf(_("Saving of groups/mail with dn '%s' failed."),$this->dn));
864     /* Optionally execute a command after we're done */
865     if ($this->initially_was_account == $this->is_account){
866       if ($this->is_modified){
867         $this->handle_post_events("modify");
868       }
869     } else {
870       $this->handle_post_events("add");
871     }
872   }
874   /* Check formular input */
875   function check()
876   {
877     $ldap= $this->config->get_ldap_link();
879     /* Call common method to give check the hook */
880     $message= plugin::check();
882     if(!$this->is_account) return array();
883     
884     //$message[] = $str;      
886     /* must: mail */
887     if ($this->mail == ""){
888       $message[]= _("The required field 'Primary address' is not set.");
889     }
890     if (!is_email($this->mail)){
891       $message[]= _("Please enter a valid email addres in 'Primary address' field.");
892     }
893     $ldap->cd($this->config->current['BASE']);
894     $ldap->search ("(&(!(objectClass=gosaUserTemplate))(objectClass=gosaMailAccount)(|(mail=".$this->mail.")(gosaMailAlternateAddress=".
895         $this->mail."))(!(uid=".$this->orig_cn."))(!(cn=".$this->orig_cn.")))");
896     if ($ldap->count() != 0){
897       $message[]= _("The primary address you've entered is already in use.");
898     }
899   
900     /* Check quota */
901     if ($this->gosaMailQuota != '' && $this->acl_is_writeable("gosaMailQuota")){
902       if (!is_numeric($this->gosaMailQuota)) {
903         $message[]= _("Value in 'Quota size' is not valid.");
904       } else {
905         $this->gosaMailQuota= (int) $this->gosaMailQuota;
906       }
907     }
909     /* Check rejectsize for integer */
910     if ($this->gosaMailMaxSize != '' && $this->acl_is_writeable("gosaMailQuota")){
911       if (!is_numeric($this->gosaMailMaxSize)){
912         $message[]= _("Please specify a vaild mail size for mails to be rejected.");
913       } else {
914         $this->gosaMailMaxSize= (int) $this->gosaMailMaxSize;
915       }
916     }
918     /* Need gosaMailMaxSize if use_mailsize_limit is checked */
919     if (is_integer(strpos($this->gosaMailDeliveryMode, "reject")) && $this->gosaMailMaxSize == ""){
920       $message[]= _("You need to set the maximum mail size in order to reject anything.");
921     }
923     if(ord($this->imapacl['anyone'][0])==194){
924       $message[] = _("Please choose valid permission settings. Default permission can't be emtpy.");
925     }
927     if(empty($this->gosaMailServer)){
928       $message[] = _("Please select a valid mail server.");
929     }
931     return ($message);
932   }
934   /* Adapt from template, using 'dn' */
935   function adapt_from_template($dn)
936   {
937     plugin::adapt_from_template($dn);
939     foreach (array("gosaMailAlternateAddress", "gosaMailForwardingAddress") as $val){
940       $this->$val= array();
941       if (isset($this->attrs["$val"]["count"])){
942         for ($i= 0; $i<$this->attrs["$val"]["count"]; $i++){
943           $value= $this->attrs["$val"][$i];
944           foreach (array("sn", "givenName", "uid") as $repl){
945             if (preg_match("/%$repl/i", $value)){
946               $value= preg_replace ("/%$repl/i", $this->parent->$repl, $value);
947             }
948           }
949           array_push($this->$val, $value);
950         }
951       }
952     }
953   }
955   /* Add entry to forwarder list */
956   function addForwarder($address)
957   {
958     $this->gosaMailForwardingAddress[]= $address;
959     $this->gosaMailForwardingAddress= array_unique ($this->gosaMailForwardingAddress);
961     sort ($this->gosaMailForwardingAddress);
962     reset ($this->gosaMailForwardingAddress);
963     $this->is_modified= TRUE;
964   }
966   /* Remove list of addresses from forwarder list */
967   function delForwarder($addresses)
968   {
969     $this->gosaMailForwardingAddress= array_remove_entries ($addresses,
970         $this->gosaMailForwardingAddress);
971     $this->is_modified= TRUE;
972   }
976   function addAlternate($address)
977   {
978     $ldap= $this->config->get_ldap_link();
980     $address= strtolower($address);
982     /* Is this address already assigned in LDAP? */
983     $ldap->cd ($this->config->current['BASE']);
984     $ldap->search ("(&(objectClass=gosaMailAccount)(|(mail=$address)".
985         "(gosaMailAlternateAddress=$address)))");
987     if ($ldap->count() > 0){
988       $attrs= $ldap->fetch ();
989       return ($attrs["uid"][0]);
990     }
992     /* Add to list of alternates */
993     if (!in_array($address, $this->gosaMailAlternateAddress)){
994       $this->gosaMailAlternateAddress[]= $address;
995     }
997     sort ($this->gosaMailAlternateAddress);
998     reset ($this->gosaMailAlternateAddress);
999     $this->is_modified= TRUE;
1001     return ("");
1002   }
1005   function delAlternate($addresses)
1006   {
1007     $this->gosaMailAlternateAddress= array_remove_entries ($addresses,
1008         $this->gosaMailAlternateAddress);
1009     $this->is_modified= TRUE;
1010   }
1013   function make_name($attrs)
1014   {
1015     $name= "";
1016     if (isset($attrs['sn'][0])){
1017       $name= $attrs['sn'][0];
1018     }
1019     if (isset($attrs['givenName'][0])){
1020       if ($name != ""){
1021         $name.= ", ".$attrs['givenName'][0];
1022       } else {
1023         $name.= $attrs['givenName'][0];
1024       }
1025     }
1026     if ($name != ""){
1027       $name.= " ";
1028     }
1030     return ($name);
1031   }
1033   function getCopyDialog()
1034   {
1035     if(!$this->is_account) return("");
1037     $smarty = get_smarty();
1038     $smarty->assign("gosaMailAlternateAddress",$this->gosaMailAlternateAddress);
1039     $smarty->assign("gosaMailForwardingAddress",$this->gosaMailForwardingAddress);
1040     $smarty->assign("mail",$this->mail);
1041     $display= $smarty->fetch (get_template_path('paste_mail.tpl', TRUE));
1042     $ret = array();
1043     $ret['string'] = $display;
1044     $ret['status'] = "";
1045     return($ret);
1046   }
1048   function saveCopyDialog()
1049   {
1050     if(!$this->is_account) return;
1052     /* Perform ADD / REMOVE ... for mail alternate / mail forwarding addresses 
1053     */
1054     $this->execute();
1055     if(isset($_POST['mail'])){
1056       $this->mail = $_POST['mail'];
1057     }
1058   }
1061   function PrepareForCopyPaste($source)
1062   {
1063     plugin::PrepareForCopyPaste($source);
1064  
1065     /* Reset alternate mail addresses */
1066     $this->gosaMailAlternateAddress = array();
1067   }
1070   /* Return plugin informations for acl handling  */
1071   function plInfo()
1072   {
1073     return (array(
1074           "plShortName"   => _("Mail"),
1075           "plDescription" => _("Group mail"),
1076           "plSelfModify"  => FALSE,
1077           "plDepends"     => array(),
1078           "plPriority"    => 0,
1079           "plSection"     => array("administration"),
1080           "plCategory"    => array("groups"), 
1081           "plProvidedAcls"=> array(
1082             "mail"                      => _("Mail address"),
1083             "gosaMailAlternateAddress"  => _("Alternate addresses"),
1084             "gosaMailForwardingAddress" => _("Forwarding addresses"),
1085             "gosaMailQuota"             => _("Quota size"),
1086             "gosaMailServer"            => _("Mail server"),
1087             "acl"                       => _("Permissions"))
1088           ));
1089   }
1092 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1093 ?>