Code

Moved images
[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       msg_dialog::display(_("Configuration error"), sprintf(_("Cannot locate mail method '%s'!"), $this->mmethod), ERROR_DIALOG);
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/small-error.png\" align=middle>&nbsp;<b>".msgPool::noValidExtension(_("mail"))."</b>";
356         return ($display);
357       }
359       /* Show tab dialog headers */
360       $display= "";
361       if ($this->parent !== NULL){
362         if ($this->is_account){
363           $display.= $this->show_disable_header(_("Remove mail account"),
364               msgPool::featuresEnabled(_("mail")));
365         } else {
366           $display.= $this->show_enable_header(_("Create mail account"),
367               msgPool::featuresDisabled(_("mail")));
369           /* Show checkbox that allows us to remove imap entry too*/
370           if($this->initially_was_account){
371             $c = "";
372             if($this->remove_folder_from_imap){
373               $c= " checked ";
374             }
375             $display .= "<h2>Shared folder delete options</h2>
376               <input class='center' type='checkbox' name='remove_folder_from_imap' value='1' ".$c."
377               title='"._("Remove shared folder from mail server database when entry gets removed in LDAP")."'>";
378             $display .= _("Remove the shared folder and all its contents after saving this account");
379           }
380           return ($display);
381         }
382       }
383     }
385     /* Add ACL? */
386     if($this->acl_is_writeable("acl")){
387       foreach ($this->indexed_user as $nr => $user){
388         if (isset($_POST["add_$nr"])){
389           $this->imapacl[""]= "l";
390         }
391         if (isset($_POST["del_$nr"])){
392           unset ($this->imapacl[$user]);
393         }
394       }
395     }
397     /* Trigger forward add dialog? */
398     if($this->acl_is_writeable("gosaMailForwardingAddress")){
399       if (isset($_POST['add_local_forwarder'])){
400         $this->forward_dialog= TRUE;
401         $this->dialog= TRUE;
402       }
403     }
405     /* Cancel forward add dialog? */
406     if($this->acl_is_writeable("gosaMailForwardingAddress")){
407       if (isset($_POST['add_locals_cancel'])){
408         $this->forward_dialog= FALSE;
409         $this->dialog= FALSE;
410       }
411     }
413     /* Finished adding of locals? */
414     if ((isset($_POST['add_locals_finish'])) && ($this->acl_is_writeable("gosaMailForwardingAddress"))) {
415       if (count ($_POST['local_list']) && $this->acl_is_writeable("gosaMailForwardingAddress")){
417         /* Walk through list of forwarders, ignore own addresses */
418         foreach ($_POST['local_list'] as $val){
419           if (!in_array ($val, $this->gosaMailAlternateAddress) &&
420               $val != $this->mail){
422             $this->addForwarder($val);
423           }
424         }
425       }
426       $this->forward_dialog= FALSE;
427       $this->dialog= FALSE;
428     }
430     /* Add forward email addresses */
431     if ((isset($_POST['add_forwarder'])) && ($this->acl_is_writeable("gosaMailForwardingAddress"))){
432       if ($_POST['forward_address'] != ""){
434         /* Valid email address specified? */
435         $address= $_POST['forward_address'];
436         if (!tests::is_email($address)){
437           msg_dialog::display(_("Error"), msgPool::invalid(_("forward address")), ERROR_DIALOG);
438         } elseif ($address == $this->mail
439             || in_array($address, $this->gosaMailAlternateAddress)) {
441           msg_dialog::display(_("Error"), _("Cannot forward to users own mail address!"), ERROR_DIALOG);
443         } else {
445           /* Add it */
446           if ($this->acl_is_writeable("gosaMailForwardingAddress")){
447             $this->addForwarder ($address);
448           }
450         }
451       }
452     }
454     /* Delete forward email addresses */
455     if (isset($_POST['delete_forwarder']) && ($this->acl_is_writeable("gosaMailForwardingAddress"))){
456       if (count($_POST['forwarder_list'])&& $this->acl_is_writeable("gosaMailForwardingAddress")){
458         $this->delForwarder ($_POST['forwarder_list']);
459       }
460     }
462     /* Add alternate email addresses */
463     if (isset($_POST['add_alternate'])){
464       if ($_POST['alternate_address'] != "" && $this->acl_is_writeable("gosaMailAlternateAddress")){
466         if (!tests::is_email($_POST['alternate_address'])){
467           msg_dialog::display(_("Error"),msgPool::invalid(_("Alternate address")), ERROR_DIALOG);
469         } elseif (($user= $this->addAlternate ($_POST['alternate_address'])) != ""){
470           $ui= get_userinfo();
471           if ($user != $ui->username){
472           msg_dialog::display(_("Error"),msgPool::duplicated(_("Mail address")), ERROR_DIALOG);
473           }
474         }
475       }
476     }
478     /* Delete alternate email addresses */
479     if($this->acl_is_writeable("gosaMailAlternateAddress")){
480       if (isset($_POST['delete_alternate']) && isset ($_POST['alternates_list'])){
481         if (count($_POST['alternates_list']) && $this->acl_is_writeable("gosaMailAlternateAddress")){
482           $this->delAlternate ($_POST['alternates_list']);
483         }
484       }
485     }
487     /* Show forward add dialog */
488     if ($this->forward_dialog){
489       $ldap= $this->config->get_ldap_link();
491       /* Save data */
492       $gmailfilter= session::get("gmailfilter");
493       foreach( array("depselect", "muser", "regex") as $type){
494         if (isset($_POST[$type])){
495           $gmailfilter[$type]= $_POST[$type];
496         }
497       }
498       if (isset($_GET['search'])){
499         $s= mb_substr($_GET['search'], 0, 1, "UTF8")."*";
500         if ($s == "**"){
501           $s= "*";
502         }
503         $gmailfilter['regex']= $s;
504       }
505       session::set("gmailfilter", $gmailfilter);
507       /* Get actual list */
508       $mailusers= array ();
509       if ($gmailfilter['regex'] != '*' && $gmailfilter['regex'] != ""){
510         $regex= $gmailfilter['regex'];
511         $filter= "(|(mail=$regex)(gosaMailAlternateAddress=$regex))";
512       } else {
513         $filter= "";
514       }
515       if ($gmailfilter['muser'] != ""){
516         $user= $gmailfilter['muser'];
517         $filter= "$filter(|(uid=$user)(cn=$user)(givenName=$user)(sn=$user))";
518       }
520       /* Add already present people to the filter */
521       $exclude= "";
522       foreach ($this->gosaMailForwardingAddress as $mail){
523         $exclude.= "(mail=$mail)";
524       }
525       if ($exclude != ""){
526         $filter.= "(!(|$exclude))";
527       }
529       $res= get_list("(&(objectClass=gosaMailAccount)$filter)", "users", $gmailfilter['depselect'],
530                      array("sn", "mail", "givenName"), GL_SUBSEARCH | GL_SIZELIMIT);
531       $ldap->cd($gmailfilter['depselect']);
532       $ldap->search ("(&(objectClass=gosaMailAccount)$filter)", array("sn", "mail", "givenName"));
533       error_reporting (0);
534       while ($attrs= $ldap->fetch()){
535         if(preg_match('/%/', $attrs['mail'][0])){
536           continue;
537         }
538         $name= $this->make_name($attrs);
539         $mailusers[$attrs['mail'][0]]= $name."&lt;".
540           $attrs['mail'][0]."&gt;";
541       }
542       error_reporting (E_ALL | E_STRICT);
543       natcasesort ($mailusers);
544       reset ($mailusers);
546       /* Show dialog */
547       $smarty->assign("search_image", get_template_path('images/search.png'));
548       $smarty->assign("usearch_image", get_template_path('images/search_user.png'));
549       $smarty->assign("tree_image", get_template_path('images/tree.png'));
550       $smarty->assign("infoimage", get_template_path('images/info.png'));
551       $smarty->assign("launchimage", get_template_path('images/lists/action.png'));
552       $smarty->assign("mailusers", $mailusers);
553       $smarty->assign("deplist", $this->config->idepartments);
554       $smarty->assign("apply", apply_filter());
555       $smarty->assign("alphabet", generate_alphabet());
556       $smarty->assign("hint", print_sizelimit_warning());
557       foreach( array("depselect", "muser", "regex") as $type){
558         $smarty->assign("$type", $gmailfilter[$type]);
559       }
560       $smarty->assign("hint", print_sizelimit_warning());
561       $display.= $smarty->fetch (get_template_path('mail_locals.tpl', TRUE, dirname(__FILE__)));
562       return ($display);
563     }
565     /* Assemble normal permissions */
566     if (isset($this->imapacl['anyone'])){
567       $smarty->assign("default_permissions", $this->imapacl['anyone']);
568     }
569     $smarty->assign("member_permissions", "lrsp");
570     if (isset($this->imapacl['%members%'])){
571       $smarty->assign("member_permissions", $this->imapacl['%members%']);
572     }
574     /* Assemble extra attributes */
575     $perm= $this->getacl( "permissions");
576     $tmp= "";
577     $nr= 0;
578     $count= count($this->imapacl);
579     $this->indexed_user= array();
580     $this->indexed_acl= array();
581     foreach($this->imapacl as $user => $acl){
583       /* Add additional acl settings */
584       if ($user != "anyone" && $user != "%members%"){
586         $Dis  = "";
587         if(!preg_match("/w/",$perm)){
588           $Dis = " disabled ";
589         }
590   
591         /* Reset given Acls to ensure that nobody can read username and acls if not allwoed */
592         if(!preg_match("/r/",$perm)){
593           $user = "";
594           $nr   = "none";
595           $key  = "none";  
596         }
598         $tmp.= "<tr>  
599                  <td>
600                   <input name=\"user_$nr\" size=20 maxlength=60 value=\"$user\" ".$Dis.">
601                  </td>
602                  <td>
603                  <select size=\"1\" name=\"perm_$nr\" ".$Dis.">";
605         /* Add acl options for this additional acl setting */
606         if(preg_match("/r/",$perm)){
607           foreach ($this->perms as $key => $value){
608             if ($acl == $key){
609               $tmp.= "<option value=\"$key\" selected>$value</option>";
610             } else {
611               $tmp.= "<option value=\"$key\">$value</option>";
612             }
613           }
614         }
615         $tmp.= "</select>&nbsp;";
618         
619         if ($nr == $count - 1){
620           if($this->acl_is_writeable("acl")){
621             $tmp.= "<input type=submit value=\""._("Add")."\" ".
622               "name=\"add_$nr\" >";
623           }
624         }
625         if ($count > 3){
626           if($this->acl_is_writeable("acl")){
627             $tmp.= "<input type=submit value=\""._("Remove")."\" ".
628               "name=\"del_$nr\" ></td></tr>";        
629           }
630         }
631       }
632       $this->indexed_user[$nr]= $user;
633       $this->indexed_acl[$nr++]= $acl;
634     }
635     $smarty->assign("plusattributes", $tmp);
637     /* Show main page */
638     $mailserver= array();
639     foreach ($this->config->data['SERVERS']['IMAP'] as $key => $val){
640       $mailserver[]= $key;
641     }
642     $smarty->assign("mailServers", $mailserver);
643     foreach(array("gosaMailServer", "gosaMailQuota", "perms", "mail",
644           "gosaMailAlternateAddress", "gosaMailForwardingAddress") as $val){
645       $smarty->assign("$val", $this->$val);
646     }
647     if (is_numeric($this->gosaMailQuota) && $this->gosaMailQuota != 0){
648       if($this->acl_is_readable("gosaMailQuota")){
649         $smarty->assign("quotausage", progressbar(round(($this->quotaUsage * 100)/ $this->gosaMailQuota),100,15,true));
650         $smarty->assign("quotadefined", "true");
651       }else{
652         $smarty->assign("quotadefined", "true");
653         $smarty->assign("quotausage", "-");
654       }
655     } else {
656       $smarty->assign("quotadefined", "false");
657     }
659     if(isset($this->config->current['MAILMETHOD'])&&preg_match("/olab/i",$this->config->current['MAILMETHOD'])){
661       $smarty->assign("kolab", TRUE);
662       $smarty->assign("JS",session::get('js'));
663       $smarty->assign("kolabFolderType_Types",    array (   ''      => _('Unspecified'),  'mail' => _('Mails'),
664                                                             'task'  => _('Tasks') ,       'journal' => _('Journals'),
665                                                             'calendar' => _('Calendar'),       'contact' => _('Contacts'), 
666                                                             'note'  => _('Notes')));
667       if($this->kolabFolderType_Type == "mail"){
668         $smarty->assign("kolabFolderType_SubTypes", array(    
669               ''          => _('Unspecified'),  'inbox'     => _("Inbox")   , 
670               'drafts'    => _("Drafts"),       'sentitems' => _("Sent items"),
671               'junkemail' => _("Junk mail")));
672       }else{
673         $smarty->assign("kolabFolderType_SubTypes", array(  'default' => _("Default")));
674       }
675       $smarty->assign("kolabFolderType_Type",     $this->kolabFolderType_Type);
676       $smarty->assign("kolabFolderType_SubType",  $this->kolabFolderType_SubType);
677     }else{
678       $smarty->assign("kolab", FALSE);
679     }
681     /* Multiple support handling */
682     foreach($this->attributes as $attr){
683       if(in_array($attr,$this->multi_boxes)){
684         $smarty->assign("use_".$attr,TRUE);
685       }else{
686         $smarty->assign("use_".$attr,FALSE);
687       }
688     }
690     /* Multiple support handling */
691     foreach(array("kolabFolderType") as $attr){
692       if(in_array($attr,$this->multi_boxes)){
693         $smarty->assign("use_".$attr,TRUE);
694       }else{
695         $smarty->assign("use_".$attr,FALSE);
696       }
697     }
699     $smarty->assign("Forward_all",$this->gosaMailForwardingAddress);
700     $smarty->assign("Forward_some",$this->gosaMailForwardingAddress_Some);
702     $smarty->assign("multiple_support",$this->multiple_support_active);
703     $display.= $smarty->fetch (get_template_path('mail.tpl', TRUE, dirname(__FILE__)));
704     return ($display);
705   }
708   /* remove object from parent */
709   function remove_from_parent()
710   {
711     if(!$this->initially_was_account){
712       return;
713     }
714   
715     /* Added these ObjectClass and Attributes, because they were not 
716        removed correctly, only in case of kolab ... 
717      */
718     if(isset($this->config->current['MAILMETHOD'])&&preg_match("/olab/i",$this->config->current['MAILMETHOD'])){
719       $this->attributes[]="acl";
720       $this->objectclasses[] = "kolabSharedFolder";
721     }
722     /* include global link_info */
723     $ldap= $this->config->get_ldap_link();
725     /* Remove and write to LDAP */
726     plugin::remove_from_parent();
728     /* Zero arrays */
729     $this->attrs['gosaMailAlternateAddress']= array();
730     $this->attrs['gosaMailForwardingAddress']= array();
731     $this->attrs['gosaSharedFolderTarget']= array();
733     /* Connect to IMAP server for account deletion */
734     if ($this->initially_was_account){
735  
736       $method= new $this->method($this->config);
737       $method->fixAttributesOnRemove($this);
738       if ($method->connect($this->gosaMailServer) && $this->remove_folder_from_imap){
740         /* Remove account from IMAP server */
741         $method->deleteMailbox($this->uid);
742         $method->disconnect();
743       }
744     }
745     /* Keep uid */
746     unset ($this->attrs['uid']);
748     $ldap->cd($this->dn);
749     $ldap->modify ($this->attrs); 
750     if (!$ldap->success()){
751       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_MOD, get_class()));
752     }
755     new log("remove","groups/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
757     /* Optionally execute a command after we're done */
758     $this->handle_post_events("remove");
759   }
762   /* Save data to object */
763   function save_object()
764   {
766     /* Add special kolab attributes */    
767     if(isset($this->config->current['MAILMETHOD'])&&preg_match("/olab/i",$this->config->current['MAILMETHOD'])){
768       if(isset($_POST['kolabFolderType_Type'])){
769         $this->kolabFolderType_Type = get_post("kolabFolderType_Type");
770         $this->kolabFolderType_SubType = get_post("kolabFolderType_SubType");
771       }
772     }
773   
774     /* Check if user wants to remove the shared folder from imap too */
775     if($this->initially_was_account && !$this->is_account){
776       if(isset($_POST['remove_folder_from_imap'])){
777         $this->remove_folder_from_imap = true;
778       }else{
779         $this->remove_folder_from_imap = false;
780       }
781     }
783     /* Assemble mail delivery mode
784        The mode field in ldap consists of values between braces, this must
785        be called when 'mail' is set, because checkboxes may not be set when
786        we're in some other dialog.
788        Example for gosaMailDeliveryMode [LR        ]
789 L: Local delivery
790 R: Reject when exceeding mailsize limit
791 S: Use spam filter
792 V: Use vacation message
793 C: Use custom sieve script
794 I: Only insider delivery */
795     if (isset($_POST['mailedit'])){
797       plugin::save_object();
799       $tmp= preg_replace("/[^a-z]/i","",$this->gosaMailDeliveryMode);
801       /* Handle delivery flags */
802       if($this->acl_is_writeable("gosaMailDeliveryModeL")){
803         if(!preg_match("/L/",$tmp) && !isset($_POST['drop_own_mails'])){
804           $tmp.="L";
805         }elseif(preg_match("/L/",$tmp) && isset($_POST['drop_own_mails'])){
806           $tmp = preg_replace("/L/","",$tmp);
807         }
808       }
810       $opts = array(
811           "R"   => "use_mailsize_limit",
812           "S"   => "use_spam_filter",
813           "V"   => "use_vacation",
814           "C"   => "own_script",
815           "I"   => "only_local");
817       foreach($opts as $flag => $post){
818         if($this->acl_is_writeable("gosaMailDeliveryMode".$flag)){
819           if(!preg_match("/".$flag."/",$tmp) && isset($_POST[$post])){
820             $tmp.= $flag;
821           }elseif(preg_match("/".$flag."/",$tmp) && !isset($_POST[$post])){
822             $tmp = preg_replace("/".$flag."/","",$tmp);
823           }
824         }
825       }
827       $tmp= "[$tmp]";
828       if ($this->gosaMailDeliveryMode != $tmp){
829         $this->is_modified= TRUE;
830       }
831       $this->gosaMailDeliveryMode= $tmp;
833       /* Collect data and re-assign it to the imapacl array */
834       if ($this->acl_is_writeable("acl")){
835         $this->imapacl= array();
836         $this->imapacl['%members%']= $_POST['member_permissions'];
837         $this->imapacl['anyone']= $_POST['default_permissions'];
838         foreach ($this->indexed_user as $nr => $user){
839           if (!isset($_POST["user_$nr"])){
840             continue;
841           }
842           if ($_POST["user_$nr"] != $user ||
843               $_POST["perm_$nr"] != $this->indexed_acl[$nr]){
844             $this->is_modified= TRUE;
845           }
846           $this->imapacl[$_POST["user_$nr"]]= $_POST["perm_$nr"];
847         }
848       }
849     }
851   }
854   /* Save data to LDAP, depending on is_account we save or delete */
855   function save()
856   {
857     $ldap= $this->config->get_ldap_link();
858     $ldap->cd($this->config->current['BASE']);
860     /* Call parents save to prepare $this->attrs */
861     plugin::save();
863     /* Save arrays */
864     $this->attrs['gosaMailAlternateAddress']  = $this->gosaMailAlternateAddress;
865     $this->attrs['gosaMailForwardingAddress'] = $this->gosaMailForwardingAddress;
866     $this->attrs['gosaSharedFolderTarget']    = "share+".$this->uid;
867     $this->attrs['acl']= array();
869     /* Prepare Mail server attribute */
870     if(preg_match("/olab/i",$this->mmethod)){
871       if (empty($this->gosaMailServer)||is_array($this->gosaMailServer)){
872         if(isset($this->attrs['gosaMailServer'][0])){
873           $this->gosaMailServer = $this->attrs['gosaMailServer'][0];
874         }
875       }
876     }  
877  /* Exchange '%member%' pseudo entry */
878     $memberacl= $this->imapacl['%members%'];
879     foreach ($this->members as $user){
880       if (!isset($this->imapacl[$user])){
881         $this->imapacl[$user]= $memberacl;
882       }
883     }
885     /* Prepare kolab attributes to be written  */
886     if(preg_match("/olab/i",$this->mmethod)){
887       if(!empty($this->kolabFolderType_Type)){
888         $this->attrs['kolabFolderType'] = $this->kolabFolderType_Type.".".$this->kolabFolderType_SubType;
889       }else{
890         $this->attrs['kolabFolderType'] = array();
891       }
892     }
894     /* Get naming attribute for mail accounts */
895     $tmp = new $this->method($this->config);
896     $uattrib = $tmp->uattrib;
898     /* Create ACL array
899        What is done here.
901        1.  Do not write acl entries for empty entries.
902        2.  Check if given user is a valid GOsa user.
903        - If he is one, check if he has a valid mail extension
904        -If this is true, add the user to the ACL entry.
905        -If this is NOT true, skip ACL entries for this user.
906        - He is not a GOsa Account, so write the ACL. (Manually entered ACL)
907        3. In case of "olab" mail method, remove the entry from the $this->imapacl array
908        because the kolab deamon will set the acls for us.
910      */
911     $acls_set_for = array();
912     foreach ($this->imapacl as $user => $acl){
914       /* Skip empty entries */
915       if (empty($user) || $user == ""){
916         unset($this->imapacl[$user]);
917       }
919       /* Skip placeholder */
920       if (empty($user) || $user == "" || preg_match("/%members%/",$user)){
921         continue;
922       }
924       /* Check if your is a real GOsa user
925        * If user is a real GOsa user but do not have an email address - SKIP adding acls
926        * If user is a real GOsa user with an email address - add acls
927        */
928       $ldap->search("(&(objectClass=person)(|(uid=".$user.")(mail=".$user.")))",array("mail","uid"));
929       if($ldap->count()){
931         /* Has the user a valid mail account? */
932         $attrs = $ldap->fetch();
933         if(isset($attrs['mail'][0])){
935           $name = $attrs[$uattrib][0];
937           /* Do not overwrite manually set ACLs with group member acls 
938           */
939           if(!in_array($name,$acls_set_for)){
940             $this->attrs['acl'][]= $name." ".$acl;
941           }
942           $acls_set_for[] = $name;
943       
945           /* Do not write imap acl directly i nkolab mode, let the kolab deamon do this. */
946           unset($this->imapacl[$user]);
947           if(!preg_match("/olab/i",$this->mmethod)){
948             $this->imapacl[$name] = $acl;
949           }
951         }else{
953           /* User is a valid GOsa account, but he has no mail extension. Skip ACLs */
954           unset($this->imapacl[$user]);
955         }
956       }else{
958         /* Seems to be a manually a added acl
959          * Write this acl.
960          */
962         /* Do not overwrite manually set ACLs with group member acls 
963          */
964         if(!in_array($user,$acls_set_for)){
965           $this->attrs['acl'][]= $user." ".$acl;
966           $acls_set_for[] = $user;
967         }
969         /* In case of kolab methods, let the deamon add the imap acls */
970         if(preg_match("/olab/i",$this->mmethod)){
971           unset($this->imapacl[$user]);
972         }
973       }
974     }
976     /* Handle mail method actions, set acls, quota ...*/
977     if ((!$this->is_template)&&(!empty($this->gosaMailServer))){
978       $method= new $this->method($this->config);
979       $method->fixAttributesOnStore($this);
980       if (($method->connect($this->gosaMailServer))){
981         $method->updateMailbox($this->uid);
982         $method->setQuota($this->uid, $this->gosaMailQuota);
984         /* Only write imap acls directly if we are not
985          *  using a kolab like mail method.
986          */
987         if(!preg_match("/olab/i",$this->mmethod)){
988           $method->setSharedFolderPermissions($this->uid, $this->imapacl);
989         }
990         $method->disconnect();
991       }
992     }
994     /* Save data to LDAP */
995     $ldap->cd($this->dn);
996     $this->cleanup();
997     $ldap->modify ($this->attrs); 
998     if (!$ldap->success()){
999       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_MOD, get_class()));
1000     }
1001     
1002     if($this->initially_was_account){
1003       new log("modify","groups/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1004     }else{
1005       new log("create","groups/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());  
1006     }
1007     
1009     /* Optionally execute a command after we're done */
1010     if ($this->initially_was_account == $this->is_account){
1011       if ($this->is_modified){
1012         $this->handle_post_events("modify");
1013       }
1014     } else {
1015       $this->handle_post_events("add");
1016     }
1017   }
1021   /* Check formular input */
1022   function check()
1023   {
1024     $ldap= $this->config->get_ldap_link();
1026     /* Call common method to give check the hook */
1027     $message= plugin::check();
1029     if(!$this->is_account) return array();
1030     
1031     //$message[] = $str;      
1033     /* must: mail */
1034     if ($this->mail == ""){
1035       $message[]= msgPool::required(_("Mail address"));
1036     }
1037     if (!tests::is_email($this->mail)){
1038       $message[]= msgPool::invalid(_("Mail address"),"","",_("your-name@your-domain.com"));
1039     }
1040     $ldap->cd($this->config->current['BASE']);
1041     $ldap->search ("(&(!(objectClass=gosaUserTemplate))(objectClass=gosaMailAccount)(|(mail=".$this->mail.")(gosaMailAlternateAddress=".
1042         $this->mail."))(!(uid=".$this->orig_cn."))(!(cn=".$this->orig_cn.")))");
1043     if ($ldap->count() != 0){
1044       $message[]= msgPool::duplicated(_("Mail address"));
1045     }
1046   
1047     /* Check quota */
1048     if ($this->gosaMailQuota != '' && $this->acl_is_writeable("gosaMailQuota")){
1049       if (!is_numeric($this->gosaMailQuota)) {
1050         $message[]= msgPool::invalid(_("Quota size"),$this->gosaMailQuota,"/[0-9]/");
1051       } else {
1052         $this->gosaMailQuota= (int) $this->gosaMailQuota;
1053       }
1054     }
1056     /* Check rejectsize for integer */
1057     if ($this->gosaMailMaxSize != '' && $this->acl_is_writeable("gosaMailQuota")){
1058       if (!is_numeric($this->gosaMailMaxSize)){
1059         $message[]= msgPool::invalid(_("Mail max size"));
1060       } else {
1061         $this->gosaMailMaxSize= (int) $this->gosaMailMaxSize;
1062       }
1063     }
1065     /* Need gosaMailMaxSize if use_mailsize_limit is checked */
1066     if (is_integer(strpos($this->gosaMailDeliveryMode, "reject")) && $this->gosaMailMaxSize == ""){
1067       $message[]= _("You need to set the maximum mail size in order to reject anything.");
1068     }
1070     if(ord($this->imapacl['anyone'][0])==194){
1071       $message[] = _("Please choose valid permission settings. Default permission can't be emtpy.");
1072     }
1074     if(empty($this->gosaMailServer)){
1075       $message[] = msgPool::requried(_("Mail server"));
1076     }
1078     return ($message);
1079   }
1081   /* Adapt from template, using 'dn' */
1082   function adapt_from_template($dn, $skip= array())
1083   {
1084     plugin::adapt_from_template($dn, $skip);
1086     foreach (array("gosaMailAlternateAddress", "gosaMailForwardingAddress") as $val){
1087  
1088       if (in_array($val, $skip)){
1089         continue;
1090       }
1092       $this->$val= array();
1093       if (isset($this->attrs["$val"]["count"])){
1094         for ($i= 0; $i<$this->attrs["$val"]["count"]; $i++){
1095           $value= $this->attrs["$val"][$i];
1096           foreach (array("sn", "givenName", "uid") as $repl){
1097             if (preg_match("/%$repl/i", $value)){
1098               $value= preg_replace ("/%$repl/i", $this->parent->$repl, $value);
1099             }
1100           }
1101           array_push($this->$val, $value);
1102         }
1103       }
1104     }
1105   }
1107   /* Add entry to forwarder list */
1108   function addForwarder($address)
1109   {
1110     $this->gosaMailForwardingAddress[]= $address;
1111     $this->gosaMailForwardingAddress= array_unique($this->gosaMailForwardingAddress);
1113     /* Update multiple edit values too */
1114     if($this->multiple_support_active){
1115       $this->gosaMailForwardingAddress_Some= 
1116         array_remove_entries (array($address),$this->gosaMailForwardingAddress_Some);
1117     }
1119     sort ($this->gosaMailForwardingAddress);
1120     reset ($this->gosaMailForwardingAddress);
1121     $this->is_modified= TRUE;
1122   }
1124   /* Remove list of addresses from forwarder list */
1125   function delForwarder($addresses)
1126   {
1127     $this->gosaMailForwardingAddress= array_remove_entries ($addresses,
1128         $this->gosaMailForwardingAddress);
1130     /* Update multiple edit values too */
1131     if($this->multiple_support_active){
1132       $this->gosaMailForwardingAddress_Some = array_remove_entries ($addresses,
1133           $this->gosaMailForwardingAddress_Some);
1134     }
1135     $this->is_modified= TRUE;
1136   }
1140   function addAlternate($address)
1141   {
1142     $ldap= $this->config->get_ldap_link();
1144     $address= strtolower($address);
1146     /* Is this address already assigned in LDAP? */
1147     $ldap->cd ($this->config->current['BASE']);
1148     $ldap->search ("(&(objectClass=gosaMailAccount)(|(mail=$address)".
1149         "(gosaMailAlternateAddress=$address)))");
1151     if ($ldap->count() > 0){
1152       $attrs= $ldap->fetch ();
1153       return ($attrs["uid"][0]);
1154     }
1156     /* Add to list of alternates */
1157     if (!in_array($address, $this->gosaMailAlternateAddress)){
1158       $this->gosaMailAlternateAddress[]= $address;
1159     }
1161     sort ($this->gosaMailAlternateAddress);
1162     reset ($this->gosaMailAlternateAddress);
1163     $this->is_modified= TRUE;
1165     return ("");
1166   }
1169   function delAlternate($addresses)
1170   {
1171     $this->gosaMailAlternateAddress= array_remove_entries ($addresses,
1172         $this->gosaMailAlternateAddress);
1173     $this->is_modified= TRUE;
1174   }
1177   function make_name($attrs)
1178   {
1179     $name= "";
1180     if (isset($attrs['sn'][0])){
1181       $name= $attrs['sn'][0];
1182     }
1183     if (isset($attrs['givenName'][0])){
1184       if ($name != ""){
1185         $name.= ", ".$attrs['givenName'][0];
1186       } else {
1187         $name.= $attrs['givenName'][0];
1188       }
1189     }
1190     if ($name != ""){
1191       $name.= " ";
1192     }
1194     return ($name);
1195   }
1197   function getCopyDialog()
1198   {
1199     if(!$this->is_account) return("");
1201     $smarty = get_smarty();
1202     $smarty->assign("gosaMailAlternateAddress",$this->gosaMailAlternateAddress);
1203     $smarty->assign("gosaMailForwardingAddress",$this->gosaMailForwardingAddress);
1204     $smarty->assign("mail",$this->mail);
1205     $display= $smarty->fetch (get_template_path('paste_mail.tpl', TRUE, dirname(__FILE__)));
1206     $ret = array();
1207     $ret['string'] = $display;
1208     $ret['status'] = "";
1209     return($ret);
1210   }
1212   function saveCopyDialog()
1213   {
1214     if(!$this->is_account) return;
1216     /* Perform ADD / REMOVE ... for mail alternate / mail forwarding addresses 
1217     */
1218     $this->execute();
1219     if(isset($_POST['mail'])){
1220       $this->mail = $_POST['mail'];
1221     }
1222   }
1225   function PrepareForCopyPaste($source)
1226   {
1227     plugin::PrepareForCopyPaste($source);
1228  
1229     /* Reset alternate mail addresses */
1230     $this->gosaMailAlternateAddress = array();
1231   }
1234   /* Return plugin informations for acl handling  */
1235   static function plInfo()
1236   {
1237     return (array(
1238           "plShortName"   => _("Mail"),
1239           "plDescription" => _("Group mail"),
1240           "plSelfModify"  => FALSE,
1241           "plDepends"     => array(),
1242           "plPriority"    => 0,
1243           "plSection"     => array("administration"),
1244           "plCategory"    => array("groups"), 
1245           "plProvidedAcls"=> array(
1246             "mail"                      => _("Mail address"),
1247             "gosaMailAlternateAddress"  => _("Alternate addresses"),
1248             "gosaMailForwardingAddress" => _("Forwarding addresses"),
1249             "gosaMailQuota"             => _("Quota size"),
1250             "gosaMailServer"            => _("Mail server"),
1251             "acl"                       => _("Permissions"))
1252           ));
1253   }
1255   
1256   /* Remove given ACL for given member (uid,mail) ..
1257    */
1258   function removeUserAcl($index )
1259   {
1260     if(isset($this->imapacl[$index])){
1261       unset($this->imapacl[$index]);
1262     }
1263   }
1265   function multiple_execute()
1266   {
1267     return($this->execute());
1268   }
1271   function init_multiple_support($attrs,$all)
1272   {
1273     plugin::init_multiple_support($attrs,$all);
1275     $this->gosaMailForwardingAddress = array();
1276     if(isset($attrs['gosaMailForwardingAddress'])){
1277       for($i = 0 ; $i < $attrs['gosaMailForwardingAddress']['count'] ; $i++){
1278         $this->gosaMailForwardingAddress[] = $attrs['gosaMailForwardingAddress'][$i];
1279       }
1280     }
1282     $this->gosaMailForwardingAddress_Some = array();
1283     if(isset($all['gosaMailForwardingAddress'])){
1284       for($i = 0 ; $i < $all['gosaMailForwardingAddress']['count'] ; $i++){
1285         if(!in_array($all['gosaMailForwardingAddress'][$i],$this->gosaMailForwardingAddress)){
1286           $this->gosaMailForwardingAddress_Some[] = $all['gosaMailForwardingAddress'][$i];
1287         }
1288       }
1289     }
1290   }
1292   function multiple_save_object()
1293   {
1294     if(isset($_POST['multiple_mail_group_posted'])){
1295       plugin::multiple_save_object();
1296       
1297       foreach(array("kolabFolderType") as $attr){
1298         if(isset($_POST['use_'.$attr])){
1299           $this->multi_boxes[] = $attr;
1300         }
1301       }
1303       /* Add special kolab attributes */
1304       if(isset($this->config->current['MAILMETHOD'])&&preg_match("/olab/i",$this->config->current['MAILMETHOD'])){
1305         if(isset($_POST['kolabFolderType_Type'])){
1306           $this->kolabFolderType_Type = get_post("kolabFolderType_Type");
1307           $this->kolabFolderType_SubType = get_post("kolabFolderType_SubType");
1308         }
1309       }
1311       /* Collect data and re-assign it to the imapacl array */
1312       if ($this->acl_is_writeable("acl")){
1313         $this->imapacl= array();
1314         $this->imapacl['%members%']= $_POST['member_permissions'];
1315         $this->imapacl['anyone']= $_POST['default_permissions'];
1316         foreach ($this->indexed_user as $nr => $user){
1317           if (!isset($_POST["user_$nr"])){
1318             continue;
1319           }
1320           if ($_POST["user_$nr"] != $user ||
1321               $_POST["perm_$nr"] != $this->indexed_acl[$nr]){
1322             $this->is_modified= TRUE;
1323           }
1324           $this->imapacl[$_POST["user_$nr"]]= $_POST["perm_$nr"];
1325         }
1326       }
1327     }
1328   }
1329   
1330   
1331   /* Return selected values for multiple edit */
1332   function get_multi_edit_values()
1333   {
1334     $ret = plugin::get_multi_edit_values();
1335     $ret['Forward_some'] = $this->gosaMailForwardingAddress_Some;    
1336     $ret['Forward_all'] = $this->gosaMailForwardingAddress;    
1337     if(in_array('kolabFolderType',$this->multi_boxes)){
1338       $ret['kolabFolderType_Type'] = $this->kolabFolderType_Type;
1339       $ret['kolabFolderType_SubType'] = $this->kolabFolderType_SubType;
1340     }
1341     if(in_array("acl",$this->multi_boxes)){
1342       $ret['imapacl'] = $this->imapacl;
1343     }
1344     return($ret);
1345   }
1347   function set_multi_edit_values($attrs)
1348   {
1349     $forward = array();
1350     foreach($attrs['Forward_some'] as $addr){
1351       if(in_array($addr,$this->gosaMailForwardingAddress)){
1352         $forward[] = $addr;
1353       }
1354     }
1355     foreach($attrs['Forward_all'] as $addr){
1356       $forward[] = $addr;
1357     }
1358     plugin::set_multi_edit_values($attrs);
1359     $this->gosaMailForwardingAddress = $forward;
1360   }
1363   // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1364 ?>