Code

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