Code

Corrected (some) cyrus ACLs
[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%' => 'lrswp',  // %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("/olab/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["lrsw"]= _("read");
289     $this->perms["lrspw"]= _("post");
290     $this->perms["p"]= _("external post");
291     $this->perms["lrsipw"]= _("append");
292     $this->perms["lrswipcd"]= _("write");
293     $this->perms["lrswipcda"]= _("admin");
294     $this->perms[""]= _("none");
295   }
297   function execute()
298   {
299     /* Call parent execute */
300     //plugin::execute();
302     /* Load templating engine */
303     $smarty= get_smarty();
305     /* Assign acls */
306     $tmp = $this->plInfo();
307     foreach($tmp['plProvidedAcls'] as $name => $translation) {
308       $smarty->assign($name."ACL",$this->getacl($name));
309     }
311     if ($_SESSION['js']==FALSE){
312       $smarty->assign("javascript", "false");
313     } else {
314       $smarty->assign("javascript", "true");
315     }
317     /* Do we need to flip is_account state? */
318     if(isset($_POST['modify_state'])){
319       if($this->is_account && $this->acl_is_removeable()){
320         $this->is_account= FALSE;
321       }elseif(!$this->is_account && $this->acl_is_createable()){
322         $this->is_account= TRUE;
323       }
324     }
326     $display = "";
328     /* Do we represent a valid account? */
329     if (!$this->is_account && $this->parent == NULL){
331       $display.= "<img alt=\"\" src=\"images/stop.png\" align=middle>&nbsp;<b>".
332         _("This 'dn' has no valid mail extensions.")."</b>";
333       return ($display);
334     }
336     /* Show tab dialog headers */
337     $display= "";
338     if ($this->parent != NULL){
339       if ($this->is_account){
340         $display.= $this->show_disable_header(_("Remove mail account"),
341             _("This account has mail features enabled. You can disable them by clicking below."));
342       } else {
343         $display.= $this->show_enable_header(_("Create mail account"),
344             _("This account has mail features disabled. You can enable them by clicking below."));
345   
346         /* Show checkbox that allows us to remove imap entry too*/
347         if($this->initially_was_account){
348           $c = "";
349           if($this->remove_folder_from_imap){
350             $c= " checked ";
351           }
352           $display .= "<h2>Shared folder delete options</h2>
353                        <input class='center' type='checkbox' name='remove_folder_from_imap' value='1' ".$c."
354                         title='"._("Remove shared folder from mail server database when entry gets removed in LDAP")."'>";
355           $display .= _("Remove the shared folder and all its contents after saving this account");
356         }
357         return ($display);
358       }
359     }
361     /* Add ACL? */
362     if($this->acl_is_writeable("acl")){
363       foreach ($this->indexed_user as $nr => $user){
364         if (isset($_POST["add_$nr"])){
365           $this->imapacl[""]= "l";
366         }
367         if (isset($_POST["del_$nr"])){
368           unset ($this->imapacl[$user]);
369         }
370       }
371     }
373     /* Trigger forward add dialog? */
374     if($this->acl_is_writeable("gosaMailForwardingAddress")){
375       if (isset($_POST['add_local_forwarder'])){
376         $this->forward_dialog= TRUE;
377         $this->dialog= TRUE;
378       }
379     }
381     /* Cancel forward add dialog? */
382     if($this->acl_is_writeable("gosaMailForwardingAddress")){
383       if (isset($_POST['add_locals_cancel'])){
384         $this->forward_dialog= FALSE;
385         $this->dialog= FALSE;
386       }
387     }
389     /* Finished adding of locals? */
390     if ((isset($_POST['add_locals_finish'])) && ($this->acl_is_writeable("gosaMailForwardingAddress"))) {
391       if (count ($_POST['local_list']) && $this->acl_is_writeable("gosaMailForwardingAddress")){
393         /* Walk through list of forwarders, ignore own addresses */
394         foreach ($_POST['local_list'] as $val){
395           if (!in_array ($val, $this->gosaMailAlternateAddress) &&
396               $val != $this->mail){
398             $this->addForwarder($val);
399           }
400         }
401       }
402       $this->forward_dialog= FALSE;
403       $this->dialog= FALSE;
404     }
406     /* Add forward email addresses */
407     if ((isset($_POST['add_forwarder'])) && ($this->acl_is_writeable("gosaMailForwardingAddress"))){
408       if ($_POST['forward_address'] != ""){
410         /* Valid email address specified? */
411         $address= $_POST['forward_address'];
412         if (!is_email($address)){
414           print_red (_("You're trying to add an invalid email address ".
415                 "to the list of forwarders."));
417         } elseif ($address == $this->mail
418             || in_array($address, $this->gosaMailAlternateAddress)) {
420           print_red (_("Adding your one of your own addresses to the forwarders makes no sense."));
422         } else {
424           /* Add it */
425           if ($this->acl_is_writeable("gosaMailForwardingAddress")){
426             $this->addForwarder ($address);
427           }
429         }
430       }
431     }
433     /* Delete forward email addresses */
434     if (isset($_POST['delete_forwarder']) && ($this->acl_is_writeable("gosaMailForwardingAddress"))){
435       if (count($_POST['forwarder_list'])&& $this->acl_is_writeable("gosaMailForwardingAddress")){
437         $this->delForwarder ($_POST['forwarder_list']);
438       }
439     }
441     /* Add alternate email addresses */
442     if (isset($_POST['add_alternate'])){
443       if ($_POST['alternate_address'] != "" && $this->acl_is_writeable("gosaMailAlternateAddress")){
445         if (!is_email($_POST['alternate_address'])){
446           print_red (_("You're trying to add an invalid email address to the list of alternate addresses."));
448         } elseif (($user= $this->addAlternate ($_POST['alternate_address'])) != ""){
449           $ui= get_userinfo();
450           if ($user != $ui->username){
451             print_red (_("The address you're trying to add is already used by user")." '$user'.");
452           }
453         }
454       }
455     }
457     /* Delete alternate email addresses */
458     if($this->acl_is_writeable("gosaMailAlternateAddress")){
459       if (isset($_POST['delete_alternate']) && isset ($_POST['alternates_list'])){
460         if (count($_POST['alternates_list']) && $this->acl_is_writeable("gosaMailAlternateAddress")){
461           $this->delAlternate ($_POST['alternates_list']);
462         }
463       }
464     }
466     /* Show forward add dialog */
467     if ($this->forward_dialog){
468       $ldap= $this->config->get_ldap_link();
470       /* Save data */
471       $gmailfilter= get_global("gmailfilter");
472       foreach( array("depselect", "muser", "regex") as $type){
473         if (isset($_POST[$type])){
474           $gmailfilter[$type]= $_POST[$type];
475         }
476       }
477       if (isset($_GET['search'])){
478         $s= mb_substr($_GET['search'], 0, 1, "UTF8")."*";
479         if ($s == "**"){
480           $s= "*";
481         }
482         $gmailfilter['regex']= $s;
483       }
484       register_global("gmailfilter", $gmailfilter);
486       /* Get actual list */
487       $mailusers= array ();
488       if ($gmailfilter['regex'] != '*' && $gmailfilter['regex'] != ""){
489         $regex= $gmailfilter['regex'];
490         $filter= "(|(mail=$regex)(gosaMailAlternateAddress=$regex))";
491       } else {
492         $filter= "";
493       }
494       if ($gmailfilter['muser'] != ""){
495         $user= $gmailfilter['muser'];
496         $filter= "$filter(|(uid=$user)(cn=$user)(givenName=$user)(sn=$user))";
497       }
499       /* Add already present people to the filter */
500       $exclude= "";
501       foreach ($this->gosaMailForwardingAddress as $mail){
502         $exclude.= "(mail=$mail)";
503       }
504       if ($exclude != ""){
505         $filter.= "(!(|$exclude))";
506       }
508       $res= get_list("(&(objectClass=gosaMailAccount)$filter)", "users", $gmailfilter['depselect'],
509                      array("sn", "mail", "givenName"), GL_SUBSEARCH | GL_SIZELIMIT);
510       $ldap->cd($gmailfilter['depselect']);
511       $ldap->search ("(&(objectClass=gosaMailAccount)$filter)", array("sn", "mail", "givenName"));
512       error_reporting (0);
513       while ($attrs= $ldap->fetch()){
514         if(preg_match('/%/', $attrs['mail'][0])){
515           continue;
516         }
517         $name= $this->make_name($attrs);
518         $mailusers[$attrs['mail'][0]]= $name."&lt;".
519           $attrs['mail'][0]."&gt;";
520       }
521       error_reporting (E_ALL);
522       natcasesort ($mailusers);
523       reset ($mailusers);
525       /* Show dialog */
526       $smarty->assign("search_image", get_template_path('images/search.png'));
527       $smarty->assign("usearch_image", get_template_path('images/search_user.png'));
528       $smarty->assign("tree_image", get_template_path('images/tree.png'));
529       $smarty->assign("infoimage", get_template_path('images/info.png'));
530       $smarty->assign("launchimage", get_template_path('images/small_filter.png'));
531       $smarty->assign("mailusers", $mailusers);
532       $smarty->assign("deplist", $this->config->idepartments);
533       $smarty->assign("apply", apply_filter());
534       $smarty->assign("alphabet", generate_alphabet());
535       $smarty->assign("hint", print_sizelimit_warning());
536       foreach( array("depselect", "muser", "regex") as $type){
537         $smarty->assign("$type", $gmailfilter[$type]);
538       }
539       $smarty->assign("hint", print_sizelimit_warning());
540       $display.= $smarty->fetch (get_template_path('mail_locals.tpl', TRUE));
541       return ($display);
542     }
544     /* Assemble normal permissions */
545     if (isset($this->imapacl['anyone'])){
546       $smarty->assign("default_permissions", $this->imapacl['anyone']);
547     }
548     $smarty->assign("member_permissions", "lrsp");
549     if (isset($this->imapacl['%members%'])){
550       $smarty->assign("member_permissions", $this->imapacl['%members%']);
551     }
553     /* Assemble extra attributes */
554     $perm= $this->getacl( "permissions");
555     $tmp= "";
556     $nr= 0;
557     $count= count($this->imapacl);
558     $this->indexed_user= array();
559     $this->indexed_acl= array();
560     foreach($this->imapacl as $user => $acl){
562       /* Add additional acl settings */
563       if ($user != "anyone" && $user != "%members%"){
565         $Dis  = "";
566         if(!preg_match("/w/",$perm)){
567           $Dis = " disabled ";
568         }
569   
570         /* Reset given Acls to ensure that nobody can read username and acls if not allwoed */
571         if(!preg_match("/r/",$perm)){
572           $user = "";
573           $nr   = "none";
574           $key  = "none";  
575         }
577         $tmp.= "<tr>  
578                  <td>
579                   <input name=\"user_$nr\" size=20 maxlength=60 value=\"$user\" ".$Dis.">
580                  </td>
581                  <td>
582                  <select size=\"1\" name=\"perm_$nr\" ".$Dis.">";
584         /* Add acl options for this additional acl setting */
585         if(preg_match("/r/",$perm)){
586           foreach ($this->perms as $key => $value){
587             if ($acl == $key){
588               $tmp.= "<option value=\"$key\" selected>$value</option>";
589             } else {
590               $tmp.= "<option value=\"$key\">$value</option>";
591             }
592           }
593         }
594         $tmp.= "</select>&nbsp;";
597         
598         if ($nr == $count - 1){
599           if($this->acl_is_writeable("acl")){
600             $tmp.= "<input type=submit value=\""._("Add")."\" ".
601               "name=\"add_$nr\" >";
602           }
603         }
604         if ($count > 3){
605           if($this->acl_is_writeable("acl")){
606             $tmp.= "<input type=submit value=\""._("Remove")."\" ".
607               "name=\"del_$nr\" ></td></tr>";        
608           }
609         }
610       }
611       $this->indexed_user[$nr]= $user;
612       $this->indexed_acl[$nr++]= $acl;
613     }
614     $smarty->assign("plusattributes", $tmp);
616     /* Show main page */
617     $mailserver= array();
618     foreach ($this->config->data['SERVERS']['IMAP'] as $key => $val){
619       $mailserver[]= $key;
620     }
621     $smarty->assign("mailServers", $mailserver);
622     foreach(array("gosaMailServer", "gosaMailQuota", "perms", "mail",
623           "gosaMailAlternateAddress", "gosaMailForwardingAddress") as $val){
624       $smarty->assign("$val", $this->$val);
625     }
626     if (is_numeric($this->gosaMailQuota) && $this->gosaMailQuota != 0){
627       if($this->acl_is_readable("gosaMailQuota")){
628         $smarty->assign("quotausage", progressbar(round(($this->quotaUsage * 100)/ $this->gosaMailQuota),100,15,true));
629         $smarty->assign("quotadefined", "true");
630       }else{
631         $smarty->assign("quotadefined", "true");
632         $smarty->assign("quotausage", "-");
633       }
634     } else {
635       $smarty->assign("quotadefined", "false");
636     }
638     $display.= $smarty->fetch (get_template_path('mail.tpl', TRUE));
639     return ($display);
640   }
643   /* remove object from parent */
644   function remove_from_parent()
645   {
646     /* Added these ObjectClass and Attributes, because they were not 
647        removed correctly, only in case of kolab ... 
648      */
649     if(isset($this->config->current['MAILMETHOD'])&&preg_match("/olab/i",$this->config->current['MAILMETHOD'])){
650       $this->attributes[]="acl";
651       $this->objectclasses[] = "kolabSharedFolder";
652     }
653     /* include global link_info */
654     $ldap= $this->config->get_ldap_link();
656     /* Remove and write to LDAP */
657     plugin::remove_from_parent();
659     /* Zero arrays */
660     $this->attrs['gosaMailAlternateAddress']= array();
661     $this->attrs['gosaMailForwardingAddress']= array();
662     $this->attrs['gosaSharedFolderTarget']= array();
664     /* Connect to IMAP server for account deletion */
665     if ($this->initially_was_account){
666  
667       $method= new $this->method($this->config);
668       $method->fixAttributesOnRemove($this);
669       if ($method->connect($this->gosaMailServer) && $this->remove_folder_from_imap){
671         /* Remove account from IMAP server */
672         $method->deleteMailbox($this->uid);
673         $method->disconnect();
674       }
675     }
676     /* Keep uid */
677     unset ($this->attrs['uid']);
679     $ldap->cd($this->dn);
680     $ldap->modify ($this->attrs); 
681     show_ldap_error($ldap->get_error(), sprintf(_("Removing of groups/mail with dn '%s' failed."),$this->dn));
683     /* Optionally execute a command after we're done */
684     $this->handle_post_events("remove");
685   }
688   /* Save data to object */
689   function save_object()
690   {
692     /* Check if user wants to remove the shared folder from imap too */
693     if($this->initially_was_account && !$this->is_account){
694       if(isset($_POST['remove_folder_from_imap'])){
695         $this->remove_folder_from_imap = true;
696       }else{
697         $this->remove_folder_from_imap = false;
698       }
699     }
701     /* Assemble mail delivery mode
702        The mode field in ldap consists of values between braces, this must
703        be called when 'mail' is set, because checkboxes may not be set when
704        we're in some other dialog.
706        Example for gosaMailDeliveryMode [LR        ]
707 L: Local delivery
708 R: Reject when exceeding mailsize limit
709 S: Use spam filter
710 V: Use vacation message
711 C: Use custom sieve script
712 I: Only insider delivery */
713     if (isset($_POST['mailedit'])){
715       plugin::save_object();
717       $tmp= preg_replace("/[^a-z]/i","",$this->gosaMailDeliveryMode);
719       /* Handle delivery flags */
720       if($this->acl_is_writeable("gosaMailDeliveryModeL")){
721         if(!preg_match("/L/",$tmp) && !isset($_POST['drop_own_mails'])){
722           $tmp.="L";
723         }elseif(preg_match("/L/",$tmp) && isset($_POST['drop_own_mails'])){
724           $tmp = preg_replace("/L/","",$tmp);
725         }
726       }
728       $opts = array(
729           "R"   => "use_mailsize_limit",
730           "S"   => "use_spam_filter",
731           "V"   => "use_vacation",
732           "C"   => "own_script",
733           "I"   => "only_local");
735       foreach($opts as $flag => $post){
736         if($this->acl_is_writeable("gosaMailDeliveryMode".$flag)){
737           if(!preg_match("/".$flag."/",$tmp) && isset($_POST[$post])){
738             $tmp.= $flag;
739           }elseif(preg_match("/".$flag."/",$tmp) && !isset($_POST[$post])){
740             $tmp = preg_replace("/".$flag."/","",$tmp);
741           }
742         }
743       }
745       $tmp= "[$tmp]";
746       if ($this->gosaMailDeliveryMode != $tmp){
747         $this->is_modified= TRUE;
748       }
749       $this->gosaMailDeliveryMode= $tmp;
751       /* Collect data and re-assign it to the imapacl array */
752       if ($this->acl_is_writeable("acl")){
753         $this->imapacl= array();
754         $this->imapacl['%members%']= $_POST['member_permissions'];
755         $this->imapacl['anyone']= $_POST['default_permissions'];
756         foreach ($this->indexed_user as $nr => $user){
757           if (!isset($_POST["user_$nr"])){
758             continue;
759           }
760           if ($_POST["user_$nr"] != $user ||
761               $_POST["perm_$nr"] != $this->indexed_acl[$nr]){
762             $this->is_modified= TRUE;
763           }
764           $this->imapacl[$_POST["user_$nr"]]= $_POST["perm_$nr"];
765         }
766       }
767     }
769   }
773   /* Save data to LDAP, depending on is_account we save or delete */
774   function save()
775   {
776     $ldap= $this->config->get_ldap_link();
777     $ldap->cd($this->config->current['BASE']);
779     /* Call parents save to prepare $this->attrs */
780     plugin::save();
782     /* Save arrays */
783     $this->attrs['gosaMailAlternateAddress']  = $this->gosaMailAlternateAddress;
784     $this->attrs['gosaMailForwardingAddress'] = $this->gosaMailForwardingAddress;
785     $this->attrs['gosaSharedFolderTarget']    = "share+".$this->uid;
787     if(preg_match("/olab/i",$this->mmethod)){
788       /* Save acl's */
789       $this->attrs['acl']= array();
790       foreach ($this->imapacl as $user => $acl){
791         if ($user == ""){
792           continue;
793         }
794         $ldap->search("(&(objectClass=person)(|(uid=".$user.")(mail=".$user.")))",array("mail"));
795         $mail = $ldap->fetch();
796         if($mail){
797           if(isset($mail['mail'][0])){
798             $this->attrs['acl'][]= $mail['mail'][0]." $acl";
799           }
800         }else{
801           $this->attrs['acl'][]= "$user $acl";
802         }
803       }
804     }else{
805       /* Save acl's */
806       $this->attrs['acl']= array();
807       foreach ($this->imapacl as $user => $acl){
808         if ($user == ""){
809           continue;
810         }
811         $this->attrs['acl'][]= "$user $acl";
812       }
813     }
815     /* Only do IMAP actions if we are not a template */
816     if(preg_match("/olab/i",$this->mmethod)){
817       if (empty($this->gosaMailServer)||is_array($this->gosaMailServer)){
818         if(isset($this->attrs['gosaMailServer'][0])){
819           $this->gosaMailServer = $this->attrs['gosaMailServer'][0];
820         }
821       }
822     }  
825     /* Exchange '%member%' pseudo entry */
826     $memberacl= $this->imapacl['%members%'];
828     foreach ($this->members as $user){
829       if(preg_match("/olab/i",$this->mmethod)){
830         $ldap->cd($this->config->current['BASE']);
831         $ldap->search("(&(objectClass=person)(|(mail=".$user.")(uid=".$user.")))",array("mail"));
832         $at = $ldap->fetch();
833         if(isset($at['mail'][0])){
834           $user = $at['mail'][0];
835         }
836       }
837       if (!isset($this->imapacl[$user])){
838         $this->imapacl[$user]= $memberacl;
839       }
840     }
841     $this->attrs['acl'] = array();
842     
843     
844     foreach($this->imapacl as $user => $acl){
846       /* Remove empty user entry, to avoid entry like this im imap 
847        *   "" lrs
848        */
849       if(empty($user)){
850         unset($this->imapacl[$user]);
851       }
852    
853       /* Skip invalid values */
854       if(preg_match("/%members%/",$user) || empty($user)){
855         continue;
856       }
858       /* Append ldap acl entries */
859       $this->attrs['acl'][] = $user." ".$acl;
860     }
862     if ((!$this->is_template)&&(!empty($this->gosaMailServer))){
863       $method= new $this->method($this->config);
864       $method->fixAttributesOnStore($this);
865       if (($method->connect($this->gosaMailServer))){
866         $method->updateMailbox($this->uid);
867         $method->setQuota($this->uid, $this->gosaMailQuota);
868         $method->setSharedFolderPermissions($this->uid, $this->imapacl);
869         $method->disconnect();
870       }
871     }
873     /* Save data to LDAP */
874     $ldap->cd($this->dn);
875     $this->cleanup();
876     $ldap->modify ($this->attrs); 
877     show_ldap_error($ldap->get_error(), sprintf(_("Saving of groups/mail with dn '%s' failed."),$this->dn));
879     /* Optionally execute a command after we're done */
880     if ($this->initially_was_account == $this->is_account){
881       if ($this->is_modified){
882         $this->handle_post_events("modify");
883       }
884     } else {
885       $this->handle_post_events("add");
886     }
887   }
889   /* Check formular input */
890   function check()
891   {
892     $ldap= $this->config->get_ldap_link();
894     /* Call common method to give check the hook */
895     $message= plugin::check();
897     if(!$this->is_account) return array();
898     
899     //$message[] = $str;      
901     /* must: mail */
902     if ($this->mail == ""){
903       $message[]= _("The required field 'Primary address' is not set.");
904     }
905     if (!is_email($this->mail)){
906       $message[]= _("Please enter a valid email addres in 'Primary address' field.");
907     }
908     $ldap->cd($this->config->current['BASE']);
909     $ldap->search ("(&(!(objectClass=gosaUserTemplate))(objectClass=gosaMailAccount)(|(mail=".$this->mail.")(gosaMailAlternateAddress=".
910         $this->mail."))(!(uid=".$this->orig_cn."))(!(cn=".$this->orig_cn.")))");
911     if ($ldap->count() != 0){
912       $message[]= _("The primary address you've entered is already in use.");
913     }
914   
915     /* Check quota */
916     if ($this->gosaMailQuota != '' && $this->acl_is_writeable("gosaMailQuota")){
917       if (!is_numeric($this->gosaMailQuota)) {
918         $message[]= _("Value in 'Quota size' is not valid.");
919       } else {
920         $this->gosaMailQuota= (int) $this->gosaMailQuota;
921       }
922     }
924     /* Check rejectsize for integer */
925     if ($this->gosaMailMaxSize != '' && $this->acl_is_writeable("gosaMailQuota")){
926       if (!is_numeric($this->gosaMailMaxSize)){
927         $message[]= _("Please specify a vaild mail size for mails to be rejected.");
928       } else {
929         $this->gosaMailMaxSize= (int) $this->gosaMailMaxSize;
930       }
931     }
933     /* Need gosaMailMaxSize if use_mailsize_limit is checked */
934     if (is_integer(strpos($this->gosaMailDeliveryMode, "reject")) && $this->gosaMailMaxSize == ""){
935       $message[]= _("You need to set the maximum mail size in order to reject anything.");
936     }
938     if(ord($this->imapacl['anyone'][0])==194){
939       $message[] = _("Please choose valid permission settings. Default permission can't be emtpy.");
940     }
942     if(empty($this->gosaMailServer)){
943       $message[] = _("Please select a valid mail server.");
944     }
946     return ($message);
947   }
949   /* Adapt from template, using 'dn' */
950   function adapt_from_template($dn)
951   {
952     plugin::adapt_from_template($dn);
954     foreach (array("gosaMailAlternateAddress", "gosaMailForwardingAddress") as $val){
955       $this->$val= array();
956       if (isset($this->attrs["$val"]["count"])){
957         for ($i= 0; $i<$this->attrs["$val"]["count"]; $i++){
958           $value= $this->attrs["$val"][$i];
959           foreach (array("sn", "givenName", "uid") as $repl){
960             if (preg_match("/%$repl/i", $value)){
961               $value= preg_replace ("/%$repl/i", $this->parent->$repl, $value);
962             }
963           }
964           array_push($this->$val, $value);
965         }
966       }
967     }
968   }
970   /* Add entry to forwarder list */
971   function addForwarder($address)
972   {
973     $this->gosaMailForwardingAddress[]= $address;
974     $this->gosaMailForwardingAddress= array_unique ($this->gosaMailForwardingAddress);
976     sort ($this->gosaMailForwardingAddress);
977     reset ($this->gosaMailForwardingAddress);
978     $this->is_modified= TRUE;
979   }
981   /* Remove list of addresses from forwarder list */
982   function delForwarder($addresses)
983   {
984     $this->gosaMailForwardingAddress= array_remove_entries ($addresses,
985         $this->gosaMailForwardingAddress);
986     $this->is_modified= TRUE;
987   }
991   function addAlternate($address)
992   {
993     $ldap= $this->config->get_ldap_link();
995     $address= strtolower($address);
997     /* Is this address already assigned in LDAP? */
998     $ldap->cd ($this->config->current['BASE']);
999     $ldap->search ("(&(objectClass=gosaMailAccount)(|(mail=$address)".
1000         "(gosaMailAlternateAddress=$address)))");
1002     if ($ldap->count() > 0){
1003       $attrs= $ldap->fetch ();
1004       return ($attrs["uid"][0]);
1005     }
1007     /* Add to list of alternates */
1008     if (!in_array($address, $this->gosaMailAlternateAddress)){
1009       $this->gosaMailAlternateAddress[]= $address;
1010     }
1012     sort ($this->gosaMailAlternateAddress);
1013     reset ($this->gosaMailAlternateAddress);
1014     $this->is_modified= TRUE;
1016     return ("");
1017   }
1020   function delAlternate($addresses)
1021   {
1022     $this->gosaMailAlternateAddress= array_remove_entries ($addresses,
1023         $this->gosaMailAlternateAddress);
1024     $this->is_modified= TRUE;
1025   }
1028   function make_name($attrs)
1029   {
1030     $name= "";
1031     if (isset($attrs['sn'][0])){
1032       $name= $attrs['sn'][0];
1033     }
1034     if (isset($attrs['givenName'][0])){
1035       if ($name != ""){
1036         $name.= ", ".$attrs['givenName'][0];
1037       } else {
1038         $name.= $attrs['givenName'][0];
1039       }
1040     }
1041     if ($name != ""){
1042       $name.= " ";
1043     }
1045     return ($name);
1046   }
1048   function getCopyDialog()
1049   {
1050     if(!$this->is_account) return("");
1052     $smarty = get_smarty();
1053     $smarty->assign("gosaMailAlternateAddress",$this->gosaMailAlternateAddress);
1054     $smarty->assign("gosaMailForwardingAddress",$this->gosaMailForwardingAddress);
1055     $smarty->assign("mail",$this->mail);
1056     $display= $smarty->fetch (get_template_path('paste_mail.tpl', TRUE));
1057     $ret = array();
1058     $ret['string'] = $display;
1059     $ret['status'] = "";
1060     return($ret);
1061   }
1063   function saveCopyDialog()
1064   {
1065     if(!$this->is_account) return;
1067     /* Perform ADD / REMOVE ... for mail alternate / mail forwarding addresses 
1068     */
1069     $this->execute();
1070     if(isset($_POST['mail'])){
1071       $this->mail = $_POST['mail'];
1072     }
1073   }
1076   function PrepareForCopyPaste($source)
1077   {
1078     plugin::PrepareForCopyPaste($source);
1079  
1080     /* Reset alternate mail addresses */
1081     $this->gosaMailAlternateAddress = array();
1082   }
1085   /* Return plugin informations for acl handling  */
1086   function plInfo()
1087   {
1088     return (array(
1089           "plShortName"   => _("Mail"),
1090           "plDescription" => _("Group mail"),
1091           "plSelfModify"  => FALSE,
1092           "plDepends"     => array(),
1093           "plPriority"    => 0,
1094           "plSection"     => array("administration"),
1095           "plCategory"    => array("groups"), 
1096           "plProvidedAcls"=> array(
1097             "mail"                      => _("Mail address"),
1098             "gosaMailAlternateAddress"  => _("Alternate addresses"),
1099             "gosaMailForwardingAddress" => _("Forwarding addresses"),
1100             "gosaMailQuota"             => _("Quota size"),
1101             "gosaMailServer"            => _("Mail server"),
1102             "acl"                       => _("Permissions"))
1103           ));
1104   }
1107 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1108 ?>