Code

Closes #317 Application 'apply' will no longer add a category.
[gosa.git] / gosa-core / 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 $gosaMailForwardingAddress_Some  = array();  // Used in multiple edit 
23   var $gosaMailServer             = "";       // Selected mailserver 
24   var $gosaMailQuota              = "";       // Defined Quota 
25   var $quotaUsage                 = 0;        // Currently used quota
27   var $gosaVacationMessage        = "";       // Vocation message 
29   var $imapacl                    = array('anyone'    => 'p',     // Set acls for everyone
30       '%members%' => 'lrswp',  // %members% are all group-members
31       ''          => 'p');    // Every user added gets this right
33   var $kolabFolderType_SubType = "";
34   var $kolabFolderType_Type = "";
36   var $gosaSpamSortLevel          = "";     
37   var $gosaSpamMailbox            = "";
38   var $gosaSharedFolderTarget     ;
40   var $forward_dialog             = FALSE;    
42   var $members                    = array();  // Group members
44   var $mailusers                  = array();
45   var $perms                      = array();
46   var $gosaMailDeliveryMode       = "[L        ]";   // 
47   var $gosaMailMaxSize            = "";       // 
48   
49   var $remove_folder_from_imap    = true;
51   /* Helper */
52   var $indexed_acl= array();
53   var $indexed_user= array();
55   var $view_logged = FALSE;
57   /* attribute list for save action */
58   var $attributes= array( "mail",   "gosaMailServer", "gosaMailQuota", "gosaMailMaxSize",
59       "gosaMailAlternateAddress", "gosaMailForwardingAddress",
60       "gosaMailDeliveryMode", "gosaSpamSortLevel", "gosaSpamMailbox",
61       "acl","gosaSharedFolderTarget", "gosaVacationMessage");
63   var $objectclasses= array("gosaMailAccount");
64   var $CopyPasteVars          = array("quotaUsage","imapacl");
66   var $multiple_support = TRUE;
68   function mailgroup (&$config, $dn= NULL, $ui= NULL)
69   {
70     /* Initialise all available attributes ... if possible
71      */
72     plugin::plugin($config, $dn);
73     $this->orig_cn = $this->cn;
75     /* Set mailMethod to the one defined in gosa.conf 
76      */
77     if (isset($this->config->current['MAILMETHOD'])){
78       $this->mmethod= $this->config->current['MAILMETHOD'];
79     }
81     /* Check if selected mail method exists 
82      */
83     $cls = get_correct_class_name("mailMethod$this->mmethod");
84     if ($cls && class_exists($cls)){
85       $this->method= $cls;
86     } else {
87       print_red(sprintf(_("There is no mail method '%s' specified in your gosa.conf available."), $this->mmethod));
88     }
90     /* Load Mailserver  
91      */
92     if(isset($this->attrs['gosaMailServer'][0])){
93       $this->gosaMailServer =  $this->attrs['gosaMailServer'][0];
94     }
96     /* Convert cn to uid in case of existing entry
97      */
98     if (isset($this->attrs['cn'][0])){
99       $this->uid= $this->attrs['cn'][0];
100     }
102     /* Get folder type */
103     if(isset($this->config->current['MAILMETHOD'])&&preg_match("/olab/i",$this->config->current['MAILMETHOD'])){
104       if(isset($this->attrs['kolabFolderType'])){
105         $tmp = split("\.",$this->attrs['kolabFolderType'][0]);
106         $this->kolabFolderType_Type = $tmp[0];
107         $this->kolabFolderType_SubType = $tmp[1];
108       }
109     }
111     /* If this isn't a new mailgroup, read all required data from ldap
112      */
113     if (($dn != "new")&&($dn !== NULL)){
115       /* Load attributes which represent multiple entries  
116        */
117       foreach (array("gosaMailAlternateAddress", "gosaMailForwardingAddress") as $val){
118         $this->$val = array();
119         if (isset($this->attrs["$val"]["count"])){
120           for ($i= 0; $i<$this->attrs["$val"]["count"]; $i++){
121             array_push($this->$val, $this->attrs["$val"][$i]);
122           }
123         }
124       }
126       /* Only do IMAP actions if gosaMailServer attribute is set 
127        */
128       if (isset ($this->attrs["gosaMailServer"][0])){
130         /* Create new instance of our defined mailclass
131          */
132         $method= new $this->method($this->config);
133         if ($method->connect($this->attrs["gosaMailServer"][0])){
135           /* If we do NOT use kolab or equal methods, 
136              read imap the acls from the mail method class.
137              They will be merged later with the ldap specified acls.
138            */
139           if(!preg_match("/olab/i",$this->mmethod) && !empty($this->mmethod)){
140             $this->imapacl=  $method->getSharedFolderPermissions($this->uid);
142             /* Need to filter what a member acl could be... */
143             $vote= array();
144             $peak= 0;
145             $leader= "";
146             foreach ($this->imapacl as $user => $acl){
148               if ($user != "anyone" ){
149                 if (!isset($vote[$acl])){
150                   $vote[$acl]= 1;
151                 } else {
152                   $vote[$acl]++;
153                 }
154                 if ($vote[$acl] > $peak){
155                   $leader= $acl;
156                   $peek= $vote[$acl];
157                 }
158               }
159             }
160             /* Highest count wins as %members%, remove all members
161                with the same acl */
162             if(!empty($leader)){
163               $this->imapacl['%members%']= $leader;
164             }
165             foreach ($this->imapacl as $user => $acl){
166               if ($this->acl == $leader && in_array($user, $this->attrs['memberUid'])){
167                 unset($this->imapacl[$user]);
168               }
169             }
170           }
172           /* Adapt attributes if needed */
173           $method->fixAttributesOnLoad($this);
175           /*  get Quota */
176           $quota= $method->getQuota($this->uid);
178           /* Update quota values */
179           if(is_array($quota)){
180             if ($quota['gosaMailQuota'] == 2147483647){
181               $this->quotaUsage= "";
182               $this->gosaMailQuota= "";
183             } else {
184               $this->quotaUsage= $quota['quotaUsage'];
185               $this->gosaMailQuota= $quota['gosaMailQuota'];
186             }
187           }else{
188             $this->quotaUsage     = "";
189             $this->gosaMailQuota  = "";
190           }
191           $method->disconnect();
192         }   // ENDE $method->connect($this->attrs["gosaMailServer"][0])){
193       }   // ENDE gosaMailServer
194     }   // ENDE dn != "new"
197     /* Get global filter config */
198     if (!session::is_set("gmailfilter")){
199       $ui= get_userinfo();
200       $base= get_base_from_people($ui->dn);
201       $gmailfilter= array( "depselect"       => $base,
202           "muser"            => "",
203           "regex"           => "*");
204       session::set("gmailfilter", $gmailfilter);
205     }
207     /* Load permissions */
208     $tmp = array();
209     $ldap = $this->config->get_ldap_link();
211     /* Read acls  from ldap and merge them with
212      *  acls read from mail method.
213      */
214     if (isset($this->attrs['acl'])){
216       for ($i= 0; $i<$this->attrs['acl']['count']; $i++){
217         list($user, $permission)= split(' ', $this->attrs['acl'][$i]);
219         /* Add to list */
220         $this->imapacl[$user]= $permission;
222         /* Get all user permissions sorted by acl, to detect the most used acl
223            This acl is then used for %members%
224          */
225         if ($user != "anyone" && $user != "%members%"){
226           $tmp[$permission][] = $user;
227         }
229         /* There is an entry in $this->imapacl like this this ... 
230            $this->attrs['imapacl']['anyone'] = "p";
231            $this->attrs['imapacl']['%members%'] = "lprs";
232            $this->attrs['imapacl'][''] = ""; <------ This is used to diplay an empty 
233            Field for special acls in our template.
234            If there is at least one special acl in out imapacl,
235            we don't need this entry anymore, because it is already displayed. 
236          */
237         if ($user != "anyone" && $user != "%members%"){
238           unset($this->imapacl['']);
239         }
240       }
241     }
243     /**
244      * Detect group members which use the same acl
245      *  as used for %members% and remove them.
246      **/
248     /* In this section we detect which acl is the most used.
249        This will be used as %members% acl.
250      */
251     $tmp2 = array(); 
252     foreach($tmp as $acl => $user){
253       $tmp2[count($tmp[$acl])]=$acl;
254     }
255     /* Most used at last 
256      */
257     ksort($tmp2);      
259     /* Assign last (most used acl) to %members% acl 
260      */
261     $str = array_pop($tmp2);
262     if(!empty($str)) {
263       $this->imapacl['%members%']=$str;
264     }
265     if(!isset($this->imapacl['%members%'])){
266       $this->imapacl['%members%'] = "lrspw";
267     }
270     /* Open ldap connection 
271      */
272     $ldap = $this->config->get_ldap_link();
273     $ldap->cd($this->config->current['BASE']);
275     /* Remove those users, that use %members% acl && are member of this group. */
276     foreach($this->imapacl as $mail => $permission){
277       $ldap->search("(&(objectClass=person)(|(mail=".$mail.")(uid=".$mail.")))",array("uid"));
278       $atr = $ldap->fetch();
279       if((isset($this->attrs['memberUid'])) && (is_array($this->attrs['memberUid']))){
280         if((isset($atr['uid'][0]))&&(in_array($atr['uid'][0],$this->attrs['memberUid']))&&($permission == $this->imapacl['%members%'])){
281           unset($this->imapacl[$mail]);
282         }
283       }
284     }
286     /**
287      * ENDE: Detect group member with same acl and replace them with %members%
288      **/
289     $this->indexed_user = array("%members%","anyone");
291     /* Append an empty entry, for special acl handling */
292     if(count($this->imapacl)==2){
293       $this->imapacl[''] ="lrsw";
294       $this->indexed_user[] = '';
295     }
297     /* Load Mailserver
298      */
299     if(isset($this->attrs['gosaMailServer'][0])){
300       $this->gosaMailServer =  $this->attrs['gosaMailServer'][0];
301     }
302     /* Fill translations */
303     $this->perms["lrsw"]= _("read");
304     $this->perms["lrswp"]= _("post");
305     $this->perms["p"]= _("external post");
306     $this->perms["lrswip"]= _("append");
307     $this->perms["lrswipcd"]= _("write");
308     $this->perms["lrswipcda"]= _("admin");
309     $this->perms[""]= _("none");
310   }
314   function execute()
315   {
316     /* Call parent execute */
317     //plugin::execute();
318     $display = "";
320     /* Log view */
321     if($this->is_account && !$this->view_logged){
322       $this->view_logged = TRUE;
323       new log("view","groups/".get_class($this),$this->dn);
324     }
326     /* Load templating engine */
327     $smarty= get_smarty();
329     /* Assign acls */
330     $tmp = $this->plInfo();
331     foreach($tmp['plProvidedAcls'] as $name => $translation) {
332       $smarty->assign($name."ACL",$this->getacl($name));
333     }
335     if (session::get('js')==FALSE){
336       $smarty->assign("javascript", "false");
337     } else {
338       $smarty->assign("javascript", "true");
339     }
341     /* Handle actions should not be done, when 
342      *  editing multiple entries at once. e.g. account state
343      */ 
344     if(!$this->multiple_support_active){
346       /* Do we need to flip is_account state? */
347       if(isset($_POST['modify_state'])){
348         if($this->is_account && $this->acl_is_removeable()){
349           $this->is_account= FALSE;
350         }elseif(!$this->is_account && $this->acl_is_createable()){
351           $this->is_account= TRUE;
352         }
353       }
355       $display = "";
357       /* Do we represent a valid account? */
358       if (!$this->is_account && $this->parent === NULL){
360         $display.= "<img alt=\"\" src=\"images/stop.png\" align=middle>&nbsp;<b>".
361           _("This 'dn' has no valid mail extensions.")."</b>";
362         return ($display);
363       }
365       /* Show tab dialog headers */
366       $display= "";
367       if ($this->parent !== NULL){
368         if ($this->is_account){
369           $display.= $this->show_disable_header(_("Remove mail account"),
370               _("This account has mail features enabled. You can disable them by clicking below."));
371         } else {
372           $display.= $this->show_enable_header(_("Create mail account"),
373               _("This account has mail features disabled. You can enable them by clicking below."));
375           /* Show checkbox that allows us to remove imap entry too*/
376           if($this->initially_was_account){
377             $c = "";
378             if($this->remove_folder_from_imap){
379               $c= " checked ";
380             }
381             $display .= "<h2>Shared folder delete options</h2>
382               <input class='center' type='checkbox' name='remove_folder_from_imap' value='1' ".$c."
383               title='"._("Remove shared folder from mail server database when entry gets removed in LDAP")."'>";
384             $display .= _("Remove the shared folder and all its contents after saving this account");
385           }
386           return ($display);
387         }
388       }
389     }
391     /* Add ACL? */
392     if($this->acl_is_writeable("acl")){
393       foreach ($this->indexed_user as $nr => $user){
394         if (isset($_POST["add_$nr"])){
395           $this->imapacl[""]= "l";
396         }
397         if (isset($_POST["del_$nr"])){
398           unset ($this->imapacl[$user]);
399         }
400       }
401     }
403     /* Trigger forward add dialog? */
404     if($this->acl_is_writeable("gosaMailForwardingAddress")){
405       if (isset($_POST['add_local_forwarder'])){
406         $this->forward_dialog= TRUE;
407         $this->dialog= TRUE;
408       }
409     }
411     /* Cancel forward add dialog? */
412     if($this->acl_is_writeable("gosaMailForwardingAddress")){
413       if (isset($_POST['add_locals_cancel'])){
414         $this->forward_dialog= FALSE;
415         $this->dialog= FALSE;
416       }
417     }
419     /* Finished adding of locals? */
420     if ((isset($_POST['add_locals_finish'])) && ($this->acl_is_writeable("gosaMailForwardingAddress"))) {
421       if (count ($_POST['local_list']) && $this->acl_is_writeable("gosaMailForwardingAddress")){
423         /* Walk through list of forwarders, ignore own addresses */
424         foreach ($_POST['local_list'] as $val){
425           if (!in_array ($val, $this->gosaMailAlternateAddress) &&
426               $val != $this->mail){
428             $this->addForwarder($val);
429           }
430         }
431       }
432       $this->forward_dialog= FALSE;
433       $this->dialog= FALSE;
434     }
436     /* Add forward email addresses */
437     if ((isset($_POST['add_forwarder'])) && ($this->acl_is_writeable("gosaMailForwardingAddress"))){
438       if ($_POST['forward_address'] != ""){
440         /* Valid email address specified? */
441         $address= $_POST['forward_address'];
442         if (!tests::is_email($address)){
444           print_red (_("You're trying to add an invalid email address ".
445                 "to the list of forwarders."));
447         } elseif ($address == $this->mail
448             || in_array($address, $this->gosaMailAlternateAddress)) {
450           print_red (_("Adding your one of your own addresses to the forwarders makes no sense."));
452         } else {
454           /* Add it */
455           if ($this->acl_is_writeable("gosaMailForwardingAddress")){
456             $this->addForwarder ($address);
457           }
459         }
460       }
461     }
463     /* Delete forward email addresses */
464     if (isset($_POST['delete_forwarder']) && ($this->acl_is_writeable("gosaMailForwardingAddress"))){
465       if (count($_POST['forwarder_list'])&& $this->acl_is_writeable("gosaMailForwardingAddress")){
467         $this->delForwarder ($_POST['forwarder_list']);
468       }
469     }
471     /* Add alternate email addresses */
472     if (isset($_POST['add_alternate'])){
473       if ($_POST['alternate_address'] != "" && $this->acl_is_writeable("gosaMailAlternateAddress")){
475         if (!tests::is_email($_POST['alternate_address'])){
476           print_red (_("You're trying to add an invalid email address to the list of alternate addresses."));
478         } elseif (($user= $this->addAlternate ($_POST['alternate_address'])) != ""){
479           $ui= get_userinfo();
480           if ($user != $ui->username){
481             print_red (_("The address you're trying to add is already used by user")." '$user'.");
482           }
483         }
484       }
485     }
487     /* Delete alternate email addresses */
488     if($this->acl_is_writeable("gosaMailAlternateAddress")){
489       if (isset($_POST['delete_alternate']) && isset ($_POST['alternates_list'])){
490         if (count($_POST['alternates_list']) && $this->acl_is_writeable("gosaMailAlternateAddress")){
491           $this->delAlternate ($_POST['alternates_list']);
492         }
493       }
494     }
496     /* Show forward add dialog */
497     if ($this->forward_dialog){
498       $ldap= $this->config->get_ldap_link();
500       /* Save data */
501       $gmailfilter= session::get("gmailfilter");
502       foreach( array("depselect", "muser", "regex") as $type){
503         if (isset($_POST[$type])){
504           $gmailfilter[$type]= $_POST[$type];
505         }
506       }
507       if (isset($_GET['search'])){
508         $s= mb_substr($_GET['search'], 0, 1, "UTF8")."*";
509         if ($s == "**"){
510           $s= "*";
511         }
512         $gmailfilter['regex']= $s;
513       }
514       session::set("gmailfilter", $gmailfilter);
516       /* Get actual list */
517       $mailusers= array ();
518       if ($gmailfilter['regex'] != '*' && $gmailfilter['regex'] != ""){
519         $regex= $gmailfilter['regex'];
520         $filter= "(|(mail=$regex)(gosaMailAlternateAddress=$regex))";
521       } else {
522         $filter= "";
523       }
524       if ($gmailfilter['muser'] != ""){
525         $user= $gmailfilter['muser'];
526         $filter= "$filter(|(uid=$user)(cn=$user)(givenName=$user)(sn=$user))";
527       }
529       /* Add already present people to the filter */
530       $exclude= "";
531       foreach ($this->gosaMailForwardingAddress as $mail){
532         $exclude.= "(mail=$mail)";
533       }
534       if ($exclude != ""){
535         $filter.= "(!(|$exclude))";
536       }
538       $res= get_list("(&(objectClass=gosaMailAccount)$filter)", "users", $gmailfilter['depselect'],
539                      array("sn", "mail", "givenName"), GL_SUBSEARCH | GL_SIZELIMIT);
540       $ldap->cd($gmailfilter['depselect']);
541       $ldap->search ("(&(objectClass=gosaMailAccount)$filter)", array("sn", "mail", "givenName"));
542       error_reporting (0);
543       while ($attrs= $ldap->fetch()){
544         if(preg_match('/%/', $attrs['mail'][0])){
545           continue;
546         }
547         $name= $this->make_name($attrs);
548         $mailusers[$attrs['mail'][0]]= $name."&lt;".
549           $attrs['mail'][0]."&gt;";
550       }
551       error_reporting (E_ALL | E_STRICT);
552       natcasesort ($mailusers);
553       reset ($mailusers);
555       /* Show dialog */
556       $smarty->assign("search_image", get_template_path('images/search.png'));
557       $smarty->assign("usearch_image", get_template_path('images/search_user.png'));
558       $smarty->assign("tree_image", get_template_path('images/tree.png'));
559       $smarty->assign("infoimage", get_template_path('images/info.png'));
560       $smarty->assign("launchimage", get_template_path('images/small_filter.png'));
561       $smarty->assign("mailusers", $mailusers);
562       $smarty->assign("deplist", $this->config->idepartments);
563       $smarty->assign("apply", apply_filter());
564       $smarty->assign("alphabet", generate_alphabet());
565       $smarty->assign("hint", print_sizelimit_warning());
566       foreach( array("depselect", "muser", "regex") as $type){
567         $smarty->assign("$type", $gmailfilter[$type]);
568       }
569       $smarty->assign("hint", print_sizelimit_warning());
570       $display.= $smarty->fetch (get_template_path('mail_locals.tpl', TRUE));
571       return ($display);
572     }
574     /* Assemble normal permissions */
575     if (isset($this->imapacl['anyone'])){
576       $smarty->assign("default_permissions", $this->imapacl['anyone']);
577     }
578     $smarty->assign("member_permissions", "lrsp");
579     if (isset($this->imapacl['%members%'])){
580       $smarty->assign("member_permissions", $this->imapacl['%members%']);
581     }
583     /* Assemble extra attributes */
584     $perm= $this->getacl( "permissions");
585     $tmp= "";
586     $nr= 0;
587     $count= count($this->imapacl);
588     $this->indexed_user= array();
589     $this->indexed_acl= array();
590     foreach($this->imapacl as $user => $acl){
592       /* Add additional acl settings */
593       if ($user != "anyone" && $user != "%members%"){
595         $Dis  = "";
596         if(!preg_match("/w/",$perm)){
597           $Dis = " disabled ";
598         }
599   
600         /* Reset given Acls to ensure that nobody can read username and acls if not allwoed */
601         if(!preg_match("/r/",$perm)){
602           $user = "";
603           $nr   = "none";
604           $key  = "none";  
605         }
607         $tmp.= "<tr>  
608                  <td>
609                   <input name=\"user_$nr\" size=20 maxlength=60 value=\"$user\" ".$Dis.">
610                  </td>
611                  <td>
612                  <select size=\"1\" name=\"perm_$nr\" ".$Dis.">";
614         /* Add acl options for this additional acl setting */
615         if(preg_match("/r/",$perm)){
616           foreach ($this->perms as $key => $value){
617             if ($acl == $key){
618               $tmp.= "<option value=\"$key\" selected>$value</option>";
619             } else {
620               $tmp.= "<option value=\"$key\">$value</option>";
621             }
622           }
623         }
624         $tmp.= "</select>&nbsp;";
627         
628         if ($nr == $count - 1){
629           if($this->acl_is_writeable("acl")){
630             $tmp.= "<input type=submit value=\""._("Add")."\" ".
631               "name=\"add_$nr\" >";
632           }
633         }
634         if ($count > 3){
635           if($this->acl_is_writeable("acl")){
636             $tmp.= "<input type=submit value=\""._("Remove")."\" ".
637               "name=\"del_$nr\" ></td></tr>";        
638           }
639         }
640       }
641       $this->indexed_user[$nr]= $user;
642       $this->indexed_acl[$nr++]= $acl;
643     }
644     $smarty->assign("plusattributes", $tmp);
646     /* Show main page */
647     $mailserver= array();
648     foreach ($this->config->data['SERVERS']['IMAP'] as $key => $val){
649       $mailserver[]= $key;
650     }
651     $smarty->assign("mailServers", $mailserver);
652     foreach(array("gosaMailServer", "gosaMailQuota", "perms", "mail",
653           "gosaMailAlternateAddress", "gosaMailForwardingAddress") as $val){
654       $smarty->assign("$val", $this->$val);
655     }
656     if (is_numeric($this->gosaMailQuota) && $this->gosaMailQuota != 0){
657       if($this->acl_is_readable("gosaMailQuota")){
658         $smarty->assign("quotausage", progressbar(round(($this->quotaUsage * 100)/ $this->gosaMailQuota),100,15,true));
659         $smarty->assign("quotadefined", "true");
660       }else{
661         $smarty->assign("quotadefined", "true");
662         $smarty->assign("quotausage", "-");
663       }
664     } else {
665       $smarty->assign("quotadefined", "false");
666     }
668     if(isset($this->config->current['MAILMETHOD'])&&preg_match("/olab/i",$this->config->current['MAILMETHOD'])){
670       $smarty->assign("kolab", TRUE);
671       $smarty->assign("JS",session::get('js'));
672       $smarty->assign("kolabFolderType_Types",    array (   ''      => _('Unspecified'),  'mail' => _('Mails'),
673                                                             'task'  => _('Tasks') ,       'journal' => _('Journals'),
674                                                             'calendar' => _('Calendar'),       'contact' => _('Contacts'), 
675                                                             'note'  => _('Notes')));
676       if($this->kolabFolderType_Type == "mail"){
677         $smarty->assign("kolabFolderType_SubTypes", array(    
678               ''          => _('Unspecified'),  'inbox'     => _("Inbox")   , 
679               'drafts'    => _("Drafts"),       'sentitems' => _("Sent items"),
680               'junkemail' => _("Junk mail")));
681       }else{
682         $smarty->assign("kolabFolderType_SubTypes", array(  'default' => _("Default")));
683       }
684       $smarty->assign("kolabFolderType_Type",     $this->kolabFolderType_Type);
685       $smarty->assign("kolabFolderType_SubType",  $this->kolabFolderType_SubType);
686     }else{
687       $smarty->assign("kolab", FALSE);
688     }
690     /* Multiple support handling */
691     foreach($this->attributes as $attr){
692       if(in_array($attr,$this->multi_boxes)){
693         $smarty->assign("use_".$attr,TRUE);
694       }else{
695         $smarty->assign("use_".$attr,FALSE);
696       }
697     }
699     /* Multiple support handling */
700     foreach(array("kolabFolderType") as $attr){
701       if(in_array($attr,$this->multi_boxes)){
702         $smarty->assign("use_".$attr,TRUE);
703       }else{
704         $smarty->assign("use_".$attr,FALSE);
705       }
706     }
708     $smarty->assign("Forward_all",$this->gosaMailForwardingAddress);
709     $smarty->assign("Forward_some",$this->gosaMailForwardingAddress_Some);
711     $smarty->assign("multiple_support",$this->multiple_support_active);
712     $display.= $smarty->fetch (get_template_path('mail.tpl', TRUE));
713     return ($display);
714   }
717   /* remove object from parent */
718   function remove_from_parent()
719   {
720     if(!$this->initially_was_account){
721       return;
722     }
723   
724     /* Added these ObjectClass and Attributes, because they were not 
725        removed correctly, only in case of kolab ... 
726      */
727     if(isset($this->config->current['MAILMETHOD'])&&preg_match("/olab/i",$this->config->current['MAILMETHOD'])){
728       $this->attributes[]="acl";
729       $this->objectclasses[] = "kolabSharedFolder";
730     }
731     /* include global link_info */
732     $ldap= $this->config->get_ldap_link();
734     /* Remove and write to LDAP */
735     plugin::remove_from_parent();
737     /* Zero arrays */
738     $this->attrs['gosaMailAlternateAddress']= array();
739     $this->attrs['gosaMailForwardingAddress']= array();
740     $this->attrs['gosaSharedFolderTarget']= array();
742     /* Connect to IMAP server for account deletion */
743     if ($this->initially_was_account){
744  
745       $method= new $this->method($this->config);
746       $method->fixAttributesOnRemove($this);
747       if ($method->connect($this->gosaMailServer) && $this->remove_folder_from_imap){
749         /* Remove account from IMAP server */
750         $method->deleteMailbox($this->uid);
751         $method->disconnect();
752       }
753     }
754     /* Keep uid */
755     unset ($this->attrs['uid']);
757     $ldap->cd($this->dn);
758     $ldap->modify ($this->attrs); 
759     show_ldap_error($ldap->get_error(), sprintf(_("Removing of groups/mail with dn '%s' failed."),$this->dn));
762     new log("remove","groups/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
764     /* Optionally execute a command after we're done */
765     $this->handle_post_events("remove");
766   }
769   /* Save data to object */
770   function save_object()
771   {
773     /* Add special kolab attributes */    
774     if(isset($this->config->current['MAILMETHOD'])&&preg_match("/olab/i",$this->config->current['MAILMETHOD'])){
775       if(isset($_POST['kolabFolderType_Type'])){
776         $this->kolabFolderType_Type = get_post("kolabFolderType_Type");
777         $this->kolabFolderType_SubType = get_post("kolabFolderType_SubType");
778       }
779     }
780   
781     /* Check if user wants to remove the shared folder from imap too */
782     if($this->initially_was_account && !$this->is_account){
783       if(isset($_POST['remove_folder_from_imap'])){
784         $this->remove_folder_from_imap = true;
785       }else{
786         $this->remove_folder_from_imap = false;
787       }
788     }
790     /* Assemble mail delivery mode
791        The mode field in ldap consists of values between braces, this must
792        be called when 'mail' is set, because checkboxes may not be set when
793        we're in some other dialog.
795        Example for gosaMailDeliveryMode [LR        ]
796 L: Local delivery
797 R: Reject when exceeding mailsize limit
798 S: Use spam filter
799 V: Use vacation message
800 C: Use custom sieve script
801 I: Only insider delivery */
802     if (isset($_POST['mailedit'])){
804       plugin::save_object();
806       $tmp= preg_replace("/[^a-z]/i","",$this->gosaMailDeliveryMode);
808       /* Handle delivery flags */
809       if($this->acl_is_writeable("gosaMailDeliveryModeL")){
810         if(!preg_match("/L/",$tmp) && !isset($_POST['drop_own_mails'])){
811           $tmp.="L";
812         }elseif(preg_match("/L/",$tmp) && isset($_POST['drop_own_mails'])){
813           $tmp = preg_replace("/L/","",$tmp);
814         }
815       }
817       $opts = array(
818           "R"   => "use_mailsize_limit",
819           "S"   => "use_spam_filter",
820           "V"   => "use_vacation",
821           "C"   => "own_script",
822           "I"   => "only_local");
824       foreach($opts as $flag => $post){
825         if($this->acl_is_writeable("gosaMailDeliveryMode".$flag)){
826           if(!preg_match("/".$flag."/",$tmp) && isset($_POST[$post])){
827             $tmp.= $flag;
828           }elseif(preg_match("/".$flag."/",$tmp) && !isset($_POST[$post])){
829             $tmp = preg_replace("/".$flag."/","",$tmp);
830           }
831         }
832       }
834       $tmp= "[$tmp]";
835       if ($this->gosaMailDeliveryMode != $tmp){
836         $this->is_modified= TRUE;
837       }
838       $this->gosaMailDeliveryMode= $tmp;
840       /* Collect data and re-assign it to the imapacl array */
841       if ($this->acl_is_writeable("acl")){
842         $this->imapacl= array();
843         $this->imapacl['%members%']= $_POST['member_permissions'];
844         $this->imapacl['anyone']= $_POST['default_permissions'];
845         foreach ($this->indexed_user as $nr => $user){
846           if (!isset($_POST["user_$nr"])){
847             continue;
848           }
849           if ($_POST["user_$nr"] != $user ||
850               $_POST["perm_$nr"] != $this->indexed_acl[$nr]){
851             $this->is_modified= TRUE;
852           }
853           $this->imapacl[$_POST["user_$nr"]]= $_POST["perm_$nr"];
854         }
855       }
856     }
858   }
861   /* Save data to LDAP, depending on is_account we save or delete */
862   function save()
863   {
864     $ldap= $this->config->get_ldap_link();
865     $ldap->cd($this->config->current['BASE']);
867     /* Call parents save to prepare $this->attrs */
868     plugin::save();
870     /* Save arrays */
871     $this->attrs['gosaMailAlternateAddress']  = $this->gosaMailAlternateAddress;
872     $this->attrs['gosaMailForwardingAddress'] = $this->gosaMailForwardingAddress;
873     $this->attrs['gosaSharedFolderTarget']    = "share+".$this->uid;
874     $this->attrs['acl']= array();
876     /* Prepare Mail server attribute */
877     if(preg_match("/olab/i",$this->mmethod)){
878       if (empty($this->gosaMailServer)||is_array($this->gosaMailServer)){
879         if(isset($this->attrs['gosaMailServer'][0])){
880           $this->gosaMailServer = $this->attrs['gosaMailServer'][0];
881         }
882       }
883     }  
884  /* Exchange '%member%' pseudo entry */
885     $memberacl= $this->imapacl['%members%'];
886     foreach ($this->members as $user){
887       if (!isset($this->imapacl[$user])){
888         $this->imapacl[$user]= $memberacl;
889       }
890     }
892     /* Prepare kolab attributes to be written  */
893     if(preg_match("/olab/i",$this->mmethod)){
894       if(!empty($this->kolabFolderType_Type)){
895         $this->attrs['kolabFolderType'] = $this->kolabFolderType_Type.".".$this->kolabFolderType_SubType;
896       }else{
897         $this->attrs['kolabFolderType'] = array();
898       }
899     }
901     /* Get naming attribute for mail accounts */
902     $tmp = new $this->method($this->config);
903     $uattrib = $tmp->uattrib;
905     /* Create ACL array
906        What is done here.
908        1.  Do not write acl entries for empty entries.
909        2.  Check if given user is a valid GOsa user.
910        - If he is one, check if he has a valid mail extension
911        -If this is true, add the user to the ACL entry.
912        -If this is NOT true, skip ACL entries for this user.
913        - He is not a GOsa Account, so write the ACL. (Manually entered ACL)
914        3. In case of "olab" mail method, remove the entry from the $this->imapacl array
915        because the kolab deamon will set the acls for us.
917      */
918     foreach ($this->imapacl as $user => $acl){
920       /* Skip empty entries */
921       if (empty($user) || $user == ""){
922         unset($this->imapacl[$user]);
923       }
925       /* Skip placeholder */
926       if (empty($user) || $user == "" || preg_match("/%members%/",$user)){
927         continue;
928       }
930       /* Check if your is a real GOsa user
931        * If user is a real GOsa user but do not have an email address - SKIP adding acls
932        * If user is a real GOsa user with an email address - add acls
933        */
934       $ldap->search("(&(objectClass=person)(|(uid=".$user.")(mail=".$user.")))",array("mail","uid"));
935       if($ldap->count()){
937         /* Has the user a valid mail account? */
938         $attrs = $ldap->fetch();
939         if(isset($attrs['mail'][0])){
941           $name = $attrs[$uattrib][0];
942           $this->attrs['acl'][]= $name." ".$acl;
944           /* Do not write imap acl directly i nkolab mode, let the kolab deamon do this. */
945           unset($this->imapacl[$user]);
946           if(!preg_match("/olab/i",$this->mmethod)){
947             $this->imapacl[$name] = $acl;
948           }
950         }else{
952           /* User is a valid GOsa account, but he has no mail extension. Skip ACLs */
953           unset($this->imapacl[$user]);
954         }
955       }else{
957         /* Seems to be a manually a added acl
958          * Write this acl.
959          */
960         $this->attrs['acl'][]= $user." ".$acl;
962         /* In case of kolab methods, let the deamon add the imap acls */
963         if(preg_match("/olab/i",$this->mmethod)){
964           unset($this->imapacl[$user]);
965         }
966       }
967     }
969     /* Handle mail method actions, set acls, quota ...*/
970     if ((!$this->is_template)&&(!empty($this->gosaMailServer))){
971       $method= new $this->method($this->config);
972       $method->fixAttributesOnStore($this);
973       if (($method->connect($this->gosaMailServer))){
974         $method->updateMailbox($this->uid);
975         $method->setQuota($this->uid, $this->gosaMailQuota);
977         /* Only write imap acls directly if we are not
978          *  using a kolab like mail method.
979          */
980         if(!preg_match("/olab/i",$this->mmethod)){
981           $method->setSharedFolderPermissions($this->uid, $this->imapacl);
982         }
983         $method->disconnect();
984       }
985     }
987     /* Save data to LDAP */
988     $ldap->cd($this->dn);
989     $this->cleanup();
990     $ldap->modify ($this->attrs); 
991     show_ldap_error($ldap->get_error(), sprintf(_("Saving of groups/mail with dn '%s' failed."),$this->dn));
992     
993     if($this->initially_was_account){
994       new log("modify","groups/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
995     }else{
996       new log("create","groups/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());  
997     }
998     
1000     /* Optionally execute a command after we're done */
1001     if ($this->initially_was_account == $this->is_account){
1002       if ($this->is_modified){
1003         $this->handle_post_events("modify");
1004       }
1005     } else {
1006       $this->handle_post_events("add");
1007     }
1008   }
1012   /* Check formular input */
1013   function check()
1014   {
1015     $ldap= $this->config->get_ldap_link();
1017     /* Call common method to give check the hook */
1018     $message= plugin::check();
1020     if(!$this->is_account) return array();
1021     
1022     //$message[] = $str;      
1024     /* must: mail */
1025     if ($this->mail == ""){
1026       $message[]= _("The required field 'Primary address' is not set.");
1027     }
1028     if (!tests::is_email($this->mail)){
1029       $message[]= _("Please enter a valid email addres in 'Primary address' field.");
1030     }
1031     $ldap->cd($this->config->current['BASE']);
1032     $ldap->search ("(&(!(objectClass=gosaUserTemplate))(objectClass=gosaMailAccount)(|(mail=".$this->mail.")(gosaMailAlternateAddress=".
1033         $this->mail."))(!(uid=".$this->orig_cn."))(!(cn=".$this->orig_cn.")))");
1034     if ($ldap->count() != 0){
1035       $message[]= _("The primary address you've entered is already in use.");
1036     }
1037   
1038     /* Check quota */
1039     if ($this->gosaMailQuota != '' && $this->acl_is_writeable("gosaMailQuota")){
1040       if (!is_numeric($this->gosaMailQuota)) {
1041         $message[]= _("Value in 'Quota size' is not valid.");
1042       } else {
1043         $this->gosaMailQuota= (int) $this->gosaMailQuota;
1044       }
1045     }
1047     /* Check rejectsize for integer */
1048     if ($this->gosaMailMaxSize != '' && $this->acl_is_writeable("gosaMailQuota")){
1049       if (!is_numeric($this->gosaMailMaxSize)){
1050         $message[]= _("Please specify a vaild mail size for mails to be rejected.");
1051       } else {
1052         $this->gosaMailMaxSize= (int) $this->gosaMailMaxSize;
1053       }
1054     }
1056     /* Need gosaMailMaxSize if use_mailsize_limit is checked */
1057     if (is_integer(strpos($this->gosaMailDeliveryMode, "reject")) && $this->gosaMailMaxSize == ""){
1058       $message[]= _("You need to set the maximum mail size in order to reject anything.");
1059     }
1061     if(ord($this->imapacl['anyone'][0])==194){
1062       $message[] = _("Please choose valid permission settings. Default permission can't be emtpy.");
1063     }
1065     if(empty($this->gosaMailServer)){
1066       $message[] = _("Please select a valid mail server.");
1067     }
1069     return ($message);
1070   }
1072   /* Adapt from template, using 'dn' */
1073   function adapt_from_template($dn)
1074   {
1075     plugin::adapt_from_template($dn);
1077     foreach (array("gosaMailAlternateAddress", "gosaMailForwardingAddress") as $val){
1078       $this->$val= array();
1079       if (isset($this->attrs["$val"]["count"])){
1080         for ($i= 0; $i<$this->attrs["$val"]["count"]; $i++){
1081           $value= $this->attrs["$val"][$i];
1082           foreach (array("sn", "givenName", "uid") as $repl){
1083             if (preg_match("/%$repl/i", $value)){
1084               $value= preg_replace ("/%$repl/i", $this->parent->$repl, $value);
1085             }
1086           }
1087           array_push($this->$val, $value);
1088         }
1089       }
1090     }
1091   }
1093   /* Add entry to forwarder list */
1094   function addForwarder($address)
1095   {
1096     $this->gosaMailForwardingAddress[]= $address;
1097     $this->gosaMailForwardingAddress= array_unique($this->gosaMailForwardingAddress);
1099     /* Update multiple edit values too */
1100     if($this->multiple_support_active){
1101       $this->gosaMailForwardingAddress_Some= 
1102         array_remove_entries (array($address),$this->gosaMailForwardingAddress_Some);
1103     }
1105     sort ($this->gosaMailForwardingAddress);
1106     reset ($this->gosaMailForwardingAddress);
1107     $this->is_modified= TRUE;
1108   }
1110   /* Remove list of addresses from forwarder list */
1111   function delForwarder($addresses)
1112   {
1113     $this->gosaMailForwardingAddress= array_remove_entries ($addresses,
1114         $this->gosaMailForwardingAddress);
1116     /* Update multiple edit values too */
1117     if($this->multiple_support_active){
1118       $this->gosaMailForwardingAddress_Some = array_remove_entries ($addresses,
1119           $this->gosaMailForwardingAddress_Some);
1120     }
1121     $this->is_modified= TRUE;
1122   }
1126   function addAlternate($address)
1127   {
1128     $ldap= $this->config->get_ldap_link();
1130     $address= strtolower($address);
1132     /* Is this address already assigned in LDAP? */
1133     $ldap->cd ($this->config->current['BASE']);
1134     $ldap->search ("(&(objectClass=gosaMailAccount)(|(mail=$address)".
1135         "(gosaMailAlternateAddress=$address)))");
1137     if ($ldap->count() > 0){
1138       $attrs= $ldap->fetch ();
1139       return ($attrs["uid"][0]);
1140     }
1142     /* Add to list of alternates */
1143     if (!in_array($address, $this->gosaMailAlternateAddress)){
1144       $this->gosaMailAlternateAddress[]= $address;
1145     }
1147     sort ($this->gosaMailAlternateAddress);
1148     reset ($this->gosaMailAlternateAddress);
1149     $this->is_modified= TRUE;
1151     return ("");
1152   }
1155   function delAlternate($addresses)
1156   {
1157     $this->gosaMailAlternateAddress= array_remove_entries ($addresses,
1158         $this->gosaMailAlternateAddress);
1159     $this->is_modified= TRUE;
1160   }
1163   function make_name($attrs)
1164   {
1165     $name= "";
1166     if (isset($attrs['sn'][0])){
1167       $name= $attrs['sn'][0];
1168     }
1169     if (isset($attrs['givenName'][0])){
1170       if ($name != ""){
1171         $name.= ", ".$attrs['givenName'][0];
1172       } else {
1173         $name.= $attrs['givenName'][0];
1174       }
1175     }
1176     if ($name != ""){
1177       $name.= " ";
1178     }
1180     return ($name);
1181   }
1183   function getCopyDialog()
1184   {
1185     if(!$this->is_account) return("");
1187     $smarty = get_smarty();
1188     $smarty->assign("gosaMailAlternateAddress",$this->gosaMailAlternateAddress);
1189     $smarty->assign("gosaMailForwardingAddress",$this->gosaMailForwardingAddress);
1190     $smarty->assign("mail",$this->mail);
1191     $display= $smarty->fetch (get_template_path('paste_mail.tpl', TRUE));
1192     $ret = array();
1193     $ret['string'] = $display;
1194     $ret['status'] = "";
1195     return($ret);
1196   }
1198   function saveCopyDialog()
1199   {
1200     if(!$this->is_account) return;
1202     /* Perform ADD / REMOVE ... for mail alternate / mail forwarding addresses 
1203     */
1204     $this->execute();
1205     if(isset($_POST['mail'])){
1206       $this->mail = $_POST['mail'];
1207     }
1208   }
1211   function PrepareForCopyPaste($source)
1212   {
1213     plugin::PrepareForCopyPaste($source);
1214  
1215     /* Reset alternate mail addresses */
1216     $this->gosaMailAlternateAddress = array();
1217   }
1220   /* Return plugin informations for acl handling  */
1221   static function plInfo()
1222   {
1223     return (array(
1224           "plShortName"   => _("Mail"),
1225           "plDescription" => _("Group mail"),
1226           "plSelfModify"  => FALSE,
1227           "plDepends"     => array(),
1228           "plPriority"    => 0,
1229           "plSection"     => array("administration"),
1230           "plCategory"    => array("groups"), 
1231           "plProvidedAcls"=> array(
1232             "mail"                      => _("Mail address"),
1233             "gosaMailAlternateAddress"  => _("Alternate addresses"),
1234             "gosaMailForwardingAddress" => _("Forwarding addresses"),
1235             "gosaMailQuota"             => _("Quota size"),
1236             "gosaMailServer"            => _("Mail server"),
1237             "acl"                       => _("Permissions"))
1238           ));
1239   }
1241   
1242   /* Remove given ACL for given member (uid,mail) ..
1243    */
1244   function removeUserAcl($index )
1245   {
1246     if(isset($this->imapacl[$index])){
1247       unset($this->imapacl[$index]);
1248     }
1249   }
1251   function multiple_execute()
1252   {
1253     return($this->execute());
1254   }
1257   function init_multiple_support($attrs,$all)
1258   {
1259     plugin::init_multiple_support($attrs,$all);
1261     $this->gosaMailForwardingAddress = array();
1262     if(isset($attrs['gosaMailForwardingAddress'])){
1263       for($i = 0 ; $i < $attrs['gosaMailForwardingAddress']['count'] ; $i++){
1264         $this->gosaMailForwardingAddress[] = $attrs['gosaMailForwardingAddress'][$i];
1265       }
1266     }
1268     $this->gosaMailForwardingAddress_Some = array();
1269     if(isset($all['gosaMailForwardingAddress'])){
1270       for($i = 0 ; $i < $all['gosaMailForwardingAddress']['count'] ; $i++){
1271         if(!in_array($all['gosaMailForwardingAddress'][$i],$this->gosaMailForwardingAddress)){
1272           $this->gosaMailForwardingAddress_Some[] = $all['gosaMailForwardingAddress'][$i];
1273         }
1274       }
1275     }
1276   }
1278   function multiple_save_object()
1279   {
1280     if(isset($_POST['multiple_mail_group_posted'])){
1281       plugin::multiple_save_object();
1282       
1283       foreach(array("kolabFolderType") as $attr){
1284         if(isset($_POST['use_'.$attr])){
1285           $this->multi_boxes[] = $attr;
1286         }
1287       }
1289       /* Add special kolab attributes */
1290       if(isset($this->config->current['MAILMETHOD'])&&preg_match("/olab/i",$this->config->current['MAILMETHOD'])){
1291         if(isset($_POST['kolabFolderType_Type'])){
1292           $this->kolabFolderType_Type = get_post("kolabFolderType_Type");
1293           $this->kolabFolderType_SubType = get_post("kolabFolderType_SubType");
1294         }
1295       }
1297       /* Collect data and re-assign it to the imapacl array */
1298       if ($this->acl_is_writeable("acl")){
1299         $this->imapacl= array();
1300         $this->imapacl['%members%']= $_POST['member_permissions'];
1301         $this->imapacl['anyone']= $_POST['default_permissions'];
1302         foreach ($this->indexed_user as $nr => $user){
1303           if (!isset($_POST["user_$nr"])){
1304             continue;
1305           }
1306           if ($_POST["user_$nr"] != $user ||
1307               $_POST["perm_$nr"] != $this->indexed_acl[$nr]){
1308             $this->is_modified= TRUE;
1309           }
1310           $this->imapacl[$_POST["user_$nr"]]= $_POST["perm_$nr"];
1311         }
1312       }
1313     }
1314   }
1315   
1316   
1317   /* Return selected values for multiple edit */
1318   function get_multi_edit_values()
1319   {
1320     $ret = plugin::get_multi_edit_values();
1321     $ret['Forward_some'] = $this->gosaMailForwardingAddress_Some;    
1322     $ret['Forward_all'] = $this->gosaMailForwardingAddress;    
1323     if(in_array('kolabFolderType',$this->multi_boxes)){
1324       $ret['kolabFolderType_Type'] = $this->kolabFolderType_Type;
1325       $ret['kolabFolderType_SubType'] = $this->kolabFolderType_SubType;
1326     }
1327     if(in_array("acl",$this->multi_boxes)){
1328       $ret['imapacl'] = $this->imapacl;
1329     }
1330     return($ret);
1331   }
1333   function set_multi_edit_values($attrs)
1334   {
1335     $forward = array();
1336     foreach($attrs['Forward_some'] as $addr){
1337       if(in_array($addr,$this->gosaMailForwardingAddress)){
1338         $forward[] = $addr;
1339       }
1340     }
1341     foreach($attrs['Forward_all'] as $addr){
1342       $forward[] = $addr;
1343     }
1344     plugin::set_multi_edit_values($attrs);
1345     $this->gosaMailForwardingAddress = $forward;
1346   }
1349   // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1350 ?>