Code

Removed show_ldap_error() calls
[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     if (!$ldap->success()){
755       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_MOD, get_class()));
756     }
759     new log("remove","groups/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
761     /* Optionally execute a command after we're done */
762     $this->handle_post_events("remove");
763   }
766   /* Save data to object */
767   function save_object()
768   {
770     /* Add special kolab attributes */    
771     if(isset($this->config->current['MAILMETHOD'])&&preg_match("/olab/i",$this->config->current['MAILMETHOD'])){
772       if(isset($_POST['kolabFolderType_Type'])){
773         $this->kolabFolderType_Type = get_post("kolabFolderType_Type");
774         $this->kolabFolderType_SubType = get_post("kolabFolderType_SubType");
775       }
776     }
777   
778     /* Check if user wants to remove the shared folder from imap too */
779     if($this->initially_was_account && !$this->is_account){
780       if(isset($_POST['remove_folder_from_imap'])){
781         $this->remove_folder_from_imap = true;
782       }else{
783         $this->remove_folder_from_imap = false;
784       }
785     }
787     /* Assemble mail delivery mode
788        The mode field in ldap consists of values between braces, this must
789        be called when 'mail' is set, because checkboxes may not be set when
790        we're in some other dialog.
792        Example for gosaMailDeliveryMode [LR        ]
793 L: Local delivery
794 R: Reject when exceeding mailsize limit
795 S: Use spam filter
796 V: Use vacation message
797 C: Use custom sieve script
798 I: Only insider delivery */
799     if (isset($_POST['mailedit'])){
801       plugin::save_object();
803       $tmp= preg_replace("/[^a-z]/i","",$this->gosaMailDeliveryMode);
805       /* Handle delivery flags */
806       if($this->acl_is_writeable("gosaMailDeliveryModeL")){
807         if(!preg_match("/L/",$tmp) && !isset($_POST['drop_own_mails'])){
808           $tmp.="L";
809         }elseif(preg_match("/L/",$tmp) && isset($_POST['drop_own_mails'])){
810           $tmp = preg_replace("/L/","",$tmp);
811         }
812       }
814       $opts = array(
815           "R"   => "use_mailsize_limit",
816           "S"   => "use_spam_filter",
817           "V"   => "use_vacation",
818           "C"   => "own_script",
819           "I"   => "only_local");
821       foreach($opts as $flag => $post){
822         if($this->acl_is_writeable("gosaMailDeliveryMode".$flag)){
823           if(!preg_match("/".$flag."/",$tmp) && isset($_POST[$post])){
824             $tmp.= $flag;
825           }elseif(preg_match("/".$flag."/",$tmp) && !isset($_POST[$post])){
826             $tmp = preg_replace("/".$flag."/","",$tmp);
827           }
828         }
829       }
831       $tmp= "[$tmp]";
832       if ($this->gosaMailDeliveryMode != $tmp){
833         $this->is_modified= TRUE;
834       }
835       $this->gosaMailDeliveryMode= $tmp;
837       /* Collect data and re-assign it to the imapacl array */
838       if ($this->acl_is_writeable("acl")){
839         $this->imapacl= array();
840         $this->imapacl['%members%']= $_POST['member_permissions'];
841         $this->imapacl['anyone']= $_POST['default_permissions'];
842         foreach ($this->indexed_user as $nr => $user){
843           if (!isset($_POST["user_$nr"])){
844             continue;
845           }
846           if ($_POST["user_$nr"] != $user ||
847               $_POST["perm_$nr"] != $this->indexed_acl[$nr]){
848             $this->is_modified= TRUE;
849           }
850           $this->imapacl[$_POST["user_$nr"]]= $_POST["perm_$nr"];
851         }
852       }
853     }
855   }
858   /* Save data to LDAP, depending on is_account we save or delete */
859   function save()
860   {
861     $ldap= $this->config->get_ldap_link();
862     $ldap->cd($this->config->current['BASE']);
864     /* Call parents save to prepare $this->attrs */
865     plugin::save();
867     /* Save arrays */
868     $this->attrs['gosaMailAlternateAddress']  = $this->gosaMailAlternateAddress;
869     $this->attrs['gosaMailForwardingAddress'] = $this->gosaMailForwardingAddress;
870     $this->attrs['gosaSharedFolderTarget']    = "share+".$this->uid;
871     $this->attrs['acl']= array();
873     /* Prepare Mail server attribute */
874     if(preg_match("/olab/i",$this->mmethod)){
875       if (empty($this->gosaMailServer)||is_array($this->gosaMailServer)){
876         if(isset($this->attrs['gosaMailServer'][0])){
877           $this->gosaMailServer = $this->attrs['gosaMailServer'][0];
878         }
879       }
880     }  
881  /* Exchange '%member%' pseudo entry */
882     $memberacl= $this->imapacl['%members%'];
883     foreach ($this->members as $user){
884       if (!isset($this->imapacl[$user])){
885         $this->imapacl[$user]= $memberacl;
886       }
887     }
889     /* Prepare kolab attributes to be written  */
890     if(preg_match("/olab/i",$this->mmethod)){
891       if(!empty($this->kolabFolderType_Type)){
892         $this->attrs['kolabFolderType'] = $this->kolabFolderType_Type.".".$this->kolabFolderType_SubType;
893       }else{
894         $this->attrs['kolabFolderType'] = array();
895       }
896     }
898     /* Get naming attribute for mail accounts */
899     $tmp = new $this->method($this->config);
900     $uattrib = $tmp->uattrib;
902     /* Create ACL array
903        What is done here.
905        1.  Do not write acl entries for empty entries.
906        2.  Check if given user is a valid GOsa user.
907        - If he is one, check if he has a valid mail extension
908        -If this is true, add the user to the ACL entry.
909        -If this is NOT true, skip ACL entries for this user.
910        - He is not a GOsa Account, so write the ACL. (Manually entered ACL)
911        3. In case of "olab" mail method, remove the entry from the $this->imapacl array
912        because the kolab deamon will set the acls for us.
914      */
915     foreach ($this->imapacl as $user => $acl){
917       /* Skip empty entries */
918       if (empty($user) || $user == ""){
919         unset($this->imapacl[$user]);
920       }
922       /* Skip placeholder */
923       if (empty($user) || $user == "" || preg_match("/%members%/",$user)){
924         continue;
925       }
927       /* Check if your is a real GOsa user
928        * If user is a real GOsa user but do not have an email address - SKIP adding acls
929        * If user is a real GOsa user with an email address - add acls
930        */
931       $ldap->search("(&(objectClass=person)(|(uid=".$user.")(mail=".$user.")))",array("mail","uid"));
932       if($ldap->count()){
934         /* Has the user a valid mail account? */
935         $attrs = $ldap->fetch();
936         if(isset($attrs['mail'][0])){
938           $name = $attrs[$uattrib][0];
939           $this->attrs['acl'][]= $name." ".$acl;
941           /* Do not write imap acl directly i nkolab mode, let the kolab deamon do this. */
942           unset($this->imapacl[$user]);
943           if(!preg_match("/olab/i",$this->mmethod)){
944             $this->imapacl[$name] = $acl;
945           }
947         }else{
949           /* User is a valid GOsa account, but he has no mail extension. Skip ACLs */
950           unset($this->imapacl[$user]);
951         }
952       }else{
954         /* Seems to be a manually a added acl
955          * Write this acl.
956          */
957         $this->attrs['acl'][]= $user." ".$acl;
959         /* In case of kolab methods, let the deamon add the imap acls */
960         if(preg_match("/olab/i",$this->mmethod)){
961           unset($this->imapacl[$user]);
962         }
963       }
964     }
966     /* Handle mail method actions, set acls, quota ...*/
967     if ((!$this->is_template)&&(!empty($this->gosaMailServer))){
968       $method= new $this->method($this->config);
969       $method->fixAttributesOnStore($this);
970       if (($method->connect($this->gosaMailServer))){
971         $method->updateMailbox($this->uid);
972         $method->setQuota($this->uid, $this->gosaMailQuota);
974         /* Only write imap acls directly if we are not
975          *  using a kolab like mail method.
976          */
977         if(!preg_match("/olab/i",$this->mmethod)){
978           $method->setSharedFolderPermissions($this->uid, $this->imapacl);
979         }
980         $method->disconnect();
981       }
982     }
984     /* Save data to LDAP */
985     $ldap->cd($this->dn);
986     $this->cleanup();
987     $ldap->modify ($this->attrs); 
988     if (!$ldap->success()){
989       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_MOD, get_class()));
990     }
991     
992     if($this->initially_was_account){
993       new log("modify","groups/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
994     }else{
995       new log("create","groups/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());  
996     }
997     
999     /* Optionally execute a command after we're done */
1000     if ($this->initially_was_account == $this->is_account){
1001       if ($this->is_modified){
1002         $this->handle_post_events("modify");
1003       }
1004     } else {
1005       $this->handle_post_events("add");
1006     }
1007   }
1011   /* Check formular input */
1012   function check()
1013   {
1014     $ldap= $this->config->get_ldap_link();
1016     /* Call common method to give check the hook */
1017     $message= plugin::check();
1019     if(!$this->is_account) return array();
1020     
1021     //$message[] = $str;      
1023     /* must: mail */
1024     if ($this->mail == ""){
1025       $message[]= _("The required field 'Primary address' is not set.");
1026     }
1027     if (!tests::is_email($this->mail)){
1028       $message[]= _("Please enter a valid email addres in 'Primary address' field.");
1029     }
1030     $ldap->cd($this->config->current['BASE']);
1031     $ldap->search ("(&(!(objectClass=gosaUserTemplate))(objectClass=gosaMailAccount)(|(mail=".$this->mail.")(gosaMailAlternateAddress=".
1032         $this->mail."))(!(uid=".$this->orig_cn."))(!(cn=".$this->orig_cn.")))");
1033     if ($ldap->count() != 0){
1034       $message[]= _("The primary address you've entered is already in use.");
1035     }
1036   
1037     /* Check quota */
1038     if ($this->gosaMailQuota != '' && $this->acl_is_writeable("gosaMailQuota")){
1039       if (!is_numeric($this->gosaMailQuota)) {
1040         $message[]= _("Value in 'Quota size' is not valid.");
1041       } else {
1042         $this->gosaMailQuota= (int) $this->gosaMailQuota;
1043       }
1044     }
1046     /* Check rejectsize for integer */
1047     if ($this->gosaMailMaxSize != '' && $this->acl_is_writeable("gosaMailQuota")){
1048       if (!is_numeric($this->gosaMailMaxSize)){
1049         $message[]= _("Please specify a vaild mail size for mails to be rejected.");
1050       } else {
1051         $this->gosaMailMaxSize= (int) $this->gosaMailMaxSize;
1052       }
1053     }
1055     /* Need gosaMailMaxSize if use_mailsize_limit is checked */
1056     if (is_integer(strpos($this->gosaMailDeliveryMode, "reject")) && $this->gosaMailMaxSize == ""){
1057       $message[]= _("You need to set the maximum mail size in order to reject anything.");
1058     }
1060     if(ord($this->imapacl['anyone'][0])==194){
1061       $message[] = _("Please choose valid permission settings. Default permission can't be emtpy.");
1062     }
1064     if(empty($this->gosaMailServer)){
1065       $message[] = _("Please select a valid mail server.");
1066     }
1068     return ($message);
1069   }
1071   /* Adapt from template, using 'dn' */
1072   function adapt_from_template($dn)
1073   {
1074     plugin::adapt_from_template($dn);
1076     foreach (array("gosaMailAlternateAddress", "gosaMailForwardingAddress") as $val){
1077       $this->$val= array();
1078       if (isset($this->attrs["$val"]["count"])){
1079         for ($i= 0; $i<$this->attrs["$val"]["count"]; $i++){
1080           $value= $this->attrs["$val"][$i];
1081           foreach (array("sn", "givenName", "uid") as $repl){
1082             if (preg_match("/%$repl/i", $value)){
1083               $value= preg_replace ("/%$repl/i", $this->parent->$repl, $value);
1084             }
1085           }
1086           array_push($this->$val, $value);
1087         }
1088       }
1089     }
1090   }
1092   /* Add entry to forwarder list */
1093   function addForwarder($address)
1094   {
1095     $this->gosaMailForwardingAddress[]= $address;
1096     $this->gosaMailForwardingAddress= array_unique($this->gosaMailForwardingAddress);
1098     /* Update multiple edit values too */
1099     if($this->multiple_support_active){
1100       $this->gosaMailForwardingAddress_Some= 
1101         array_remove_entries (array($address),$this->gosaMailForwardingAddress_Some);
1102     }
1104     sort ($this->gosaMailForwardingAddress);
1105     reset ($this->gosaMailForwardingAddress);
1106     $this->is_modified= TRUE;
1107   }
1109   /* Remove list of addresses from forwarder list */
1110   function delForwarder($addresses)
1111   {
1112     $this->gosaMailForwardingAddress= array_remove_entries ($addresses,
1113         $this->gosaMailForwardingAddress);
1115     /* Update multiple edit values too */
1116     if($this->multiple_support_active){
1117       $this->gosaMailForwardingAddress_Some = array_remove_entries ($addresses,
1118           $this->gosaMailForwardingAddress_Some);
1119     }
1120     $this->is_modified= TRUE;
1121   }
1125   function addAlternate($address)
1126   {
1127     $ldap= $this->config->get_ldap_link();
1129     $address= strtolower($address);
1131     /* Is this address already assigned in LDAP? */
1132     $ldap->cd ($this->config->current['BASE']);
1133     $ldap->search ("(&(objectClass=gosaMailAccount)(|(mail=$address)".
1134         "(gosaMailAlternateAddress=$address)))");
1136     if ($ldap->count() > 0){
1137       $attrs= $ldap->fetch ();
1138       return ($attrs["uid"][0]);
1139     }
1141     /* Add to list of alternates */
1142     if (!in_array($address, $this->gosaMailAlternateAddress)){
1143       $this->gosaMailAlternateAddress[]= $address;
1144     }
1146     sort ($this->gosaMailAlternateAddress);
1147     reset ($this->gosaMailAlternateAddress);
1148     $this->is_modified= TRUE;
1150     return ("");
1151   }
1154   function delAlternate($addresses)
1155   {
1156     $this->gosaMailAlternateAddress= array_remove_entries ($addresses,
1157         $this->gosaMailAlternateAddress);
1158     $this->is_modified= TRUE;
1159   }
1162   function make_name($attrs)
1163   {
1164     $name= "";
1165     if (isset($attrs['sn'][0])){
1166       $name= $attrs['sn'][0];
1167     }
1168     if (isset($attrs['givenName'][0])){
1169       if ($name != ""){
1170         $name.= ", ".$attrs['givenName'][0];
1171       } else {
1172         $name.= $attrs['givenName'][0];
1173       }
1174     }
1175     if ($name != ""){
1176       $name.= " ";
1177     }
1179     return ($name);
1180   }
1182   function getCopyDialog()
1183   {
1184     if(!$this->is_account) return("");
1186     $smarty = get_smarty();
1187     $smarty->assign("gosaMailAlternateAddress",$this->gosaMailAlternateAddress);
1188     $smarty->assign("gosaMailForwardingAddress",$this->gosaMailForwardingAddress);
1189     $smarty->assign("mail",$this->mail);
1190     $display= $smarty->fetch (get_template_path('paste_mail.tpl', TRUE, dirname(__FILE__)));
1191     $ret = array();
1192     $ret['string'] = $display;
1193     $ret['status'] = "";
1194     return($ret);
1195   }
1197   function saveCopyDialog()
1198   {
1199     if(!$this->is_account) return;
1201     /* Perform ADD / REMOVE ... for mail alternate / mail forwarding addresses 
1202     */
1203     $this->execute();
1204     if(isset($_POST['mail'])){
1205       $this->mail = $_POST['mail'];
1206     }
1207   }
1210   function PrepareForCopyPaste($source)
1211   {
1212     plugin::PrepareForCopyPaste($source);
1213  
1214     /* Reset alternate mail addresses */
1215     $this->gosaMailAlternateAddress = array();
1216   }
1219   /* Return plugin informations for acl handling  */
1220   static function plInfo()
1221   {
1222     return (array(
1223           "plShortName"   => _("Mail"),
1224           "plDescription" => _("Group mail"),
1225           "plSelfModify"  => FALSE,
1226           "plDepends"     => array(),
1227           "plPriority"    => 0,
1228           "plSection"     => array("administration"),
1229           "plCategory"    => array("groups"), 
1230           "plProvidedAcls"=> array(
1231             "mail"                      => _("Mail address"),
1232             "gosaMailAlternateAddress"  => _("Alternate addresses"),
1233             "gosaMailForwardingAddress" => _("Forwarding addresses"),
1234             "gosaMailQuota"             => _("Quota size"),
1235             "gosaMailServer"            => _("Mail server"),
1236             "acl"                       => _("Permissions"))
1237           ));
1238   }
1240   
1241   /* Remove given ACL for given member (uid,mail) ..
1242    */
1243   function removeUserAcl($index )
1244   {
1245     if(isset($this->imapacl[$index])){
1246       unset($this->imapacl[$index]);
1247     }
1248   }
1250   function multiple_execute()
1251   {
1252     return($this->execute());
1253   }
1256   function init_multiple_support($attrs,$all)
1257   {
1258     plugin::init_multiple_support($attrs,$all);
1260     $this->gosaMailForwardingAddress = array();
1261     if(isset($attrs['gosaMailForwardingAddress'])){
1262       for($i = 0 ; $i < $attrs['gosaMailForwardingAddress']['count'] ; $i++){
1263         $this->gosaMailForwardingAddress[] = $attrs['gosaMailForwardingAddress'][$i];
1264       }
1265     }
1267     $this->gosaMailForwardingAddress_Some = array();
1268     if(isset($all['gosaMailForwardingAddress'])){
1269       for($i = 0 ; $i < $all['gosaMailForwardingAddress']['count'] ; $i++){
1270         if(!in_array($all['gosaMailForwardingAddress'][$i],$this->gosaMailForwardingAddress)){
1271           $this->gosaMailForwardingAddress_Some[] = $all['gosaMailForwardingAddress'][$i];
1272         }
1273       }
1274     }
1275   }
1277   function multiple_save_object()
1278   {
1279     if(isset($_POST['multiple_mail_group_posted'])){
1280       plugin::multiple_save_object();
1281       
1282       foreach(array("kolabFolderType") as $attr){
1283         if(isset($_POST['use_'.$attr])){
1284           $this->multi_boxes[] = $attr;
1285         }
1286       }
1288       /* Add special kolab attributes */
1289       if(isset($this->config->current['MAILMETHOD'])&&preg_match("/olab/i",$this->config->current['MAILMETHOD'])){
1290         if(isset($_POST['kolabFolderType_Type'])){
1291           $this->kolabFolderType_Type = get_post("kolabFolderType_Type");
1292           $this->kolabFolderType_SubType = get_post("kolabFolderType_SubType");
1293         }
1294       }
1296       /* Collect data and re-assign it to the imapacl array */
1297       if ($this->acl_is_writeable("acl")){
1298         $this->imapacl= array();
1299         $this->imapacl['%members%']= $_POST['member_permissions'];
1300         $this->imapacl['anyone']= $_POST['default_permissions'];
1301         foreach ($this->indexed_user as $nr => $user){
1302           if (!isset($_POST["user_$nr"])){
1303             continue;
1304           }
1305           if ($_POST["user_$nr"] != $user ||
1306               $_POST["perm_$nr"] != $this->indexed_acl[$nr]){
1307             $this->is_modified= TRUE;
1308           }
1309           $this->imapacl[$_POST["user_$nr"]]= $_POST["perm_$nr"];
1310         }
1311       }
1312     }
1313   }
1314   
1315   
1316   /* Return selected values for multiple edit */
1317   function get_multi_edit_values()
1318   {
1319     $ret = plugin::get_multi_edit_values();
1320     $ret['Forward_some'] = $this->gosaMailForwardingAddress_Some;    
1321     $ret['Forward_all'] = $this->gosaMailForwardingAddress;    
1322     if(in_array('kolabFolderType',$this->multi_boxes)){
1323       $ret['kolabFolderType_Type'] = $this->kolabFolderType_Type;
1324       $ret['kolabFolderType_SubType'] = $this->kolabFolderType_SubType;
1325     }
1326     if(in_array("acl",$this->multi_boxes)){
1327       $ret['imapacl'] = $this->imapacl;
1328     }
1329     return($ret);
1330   }
1332   function set_multi_edit_values($attrs)
1333   {
1334     $forward = array();
1335     foreach($attrs['Forward_some'] as $addr){
1336       if(in_array($addr,$this->gosaMailForwardingAddress)){
1337         $forward[] = $addr;
1338       }
1339     }
1340     foreach($attrs['Forward_all'] as $addr){
1341       $forward[] = $addr;
1342     }
1343     plugin::set_multi_edit_values($attrs);
1344     $this->gosaMailForwardingAddress = $forward;
1345   }
1348   // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1349 ?>