Code

Fixed )
[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>".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)){
438           print_red (msgPool::invalid(_("forward address")));
440         } elseif ($address == $this->mail
441             || in_array($address, $this->gosaMailAlternateAddress)) {
443           print_red (_("Adding your one of your own addresses to the forwarders makes no sense."));
445         } else {
447           /* Add it */
448           if ($this->acl_is_writeable("gosaMailForwardingAddress")){
449             $this->addForwarder ($address);
450           }
452         }
453       }
454     }
456     /* Delete forward email addresses */
457     if (isset($_POST['delete_forwarder']) && ($this->acl_is_writeable("gosaMailForwardingAddress"))){
458       if (count($_POST['forwarder_list'])&& $this->acl_is_writeable("gosaMailForwardingAddress")){
460         $this->delForwarder ($_POST['forwarder_list']);
461       }
462     }
464     /* Add alternate email addresses */
465     if (isset($_POST['add_alternate'])){
466       if ($_POST['alternate_address'] != "" && $this->acl_is_writeable("gosaMailAlternateAddress")){
468         if (!tests::is_email($_POST['alternate_address'])){
469           print_red (msgPool::invalid(_("alternate address")));
471         } elseif (($user= $this->addAlternate ($_POST['alternate_address'])) != ""){
472           $ui= get_userinfo();
473           if ($user != $ui->username){
474             print_red (msgPool::duplicated(_("mail address")));
475           }
476         }
477       }
478     }
480     /* Delete alternate email addresses */
481     if($this->acl_is_writeable("gosaMailAlternateAddress")){
482       if (isset($_POST['delete_alternate']) && isset ($_POST['alternates_list'])){
483         if (count($_POST['alternates_list']) && $this->acl_is_writeable("gosaMailAlternateAddress")){
484           $this->delAlternate ($_POST['alternates_list']);
485         }
486       }
487     }
489     /* Show forward add dialog */
490     if ($this->forward_dialog){
491       $ldap= $this->config->get_ldap_link();
493       /* Save data */
494       $gmailfilter= session::get("gmailfilter");
495       foreach( array("depselect", "muser", "regex") as $type){
496         if (isset($_POST[$type])){
497           $gmailfilter[$type]= $_POST[$type];
498         }
499       }
500       if (isset($_GET['search'])){
501         $s= mb_substr($_GET['search'], 0, 1, "UTF8")."*";
502         if ($s == "**"){
503           $s= "*";
504         }
505         $gmailfilter['regex']= $s;
506       }
507       session::set("gmailfilter", $gmailfilter);
509       /* Get actual list */
510       $mailusers= array ();
511       if ($gmailfilter['regex'] != '*' && $gmailfilter['regex'] != ""){
512         $regex= $gmailfilter['regex'];
513         $filter= "(|(mail=$regex)(gosaMailAlternateAddress=$regex))";
514       } else {
515         $filter= "";
516       }
517       if ($gmailfilter['muser'] != ""){
518         $user= $gmailfilter['muser'];
519         $filter= "$filter(|(uid=$user)(cn=$user)(givenName=$user)(sn=$user))";
520       }
522       /* Add already present people to the filter */
523       $exclude= "";
524       foreach ($this->gosaMailForwardingAddress as $mail){
525         $exclude.= "(mail=$mail)";
526       }
527       if ($exclude != ""){
528         $filter.= "(!(|$exclude))";
529       }
531       $res= get_list("(&(objectClass=gosaMailAccount)$filter)", "users", $gmailfilter['depselect'],
532                      array("sn", "mail", "givenName"), GL_SUBSEARCH | GL_SIZELIMIT);
533       $ldap->cd($gmailfilter['depselect']);
534       $ldap->search ("(&(objectClass=gosaMailAccount)$filter)", array("sn", "mail", "givenName"));
535       error_reporting (0);
536       while ($attrs= $ldap->fetch()){
537         if(preg_match('/%/', $attrs['mail'][0])){
538           continue;
539         }
540         $name= $this->make_name($attrs);
541         $mailusers[$attrs['mail'][0]]= $name."&lt;".
542           $attrs['mail'][0]."&gt;";
543       }
544       error_reporting (E_ALL | E_STRICT);
545       natcasesort ($mailusers);
546       reset ($mailusers);
548       /* Show dialog */
549       $smarty->assign("search_image", get_template_path('images/search.png'));
550       $smarty->assign("usearch_image", get_template_path('images/search_user.png'));
551       $smarty->assign("tree_image", get_template_path('images/tree.png'));
552       $smarty->assign("infoimage", get_template_path('images/info.png'));
553       $smarty->assign("launchimage", get_template_path('images/small_filter.png'));
554       $smarty->assign("mailusers", $mailusers);
555       $smarty->assign("deplist", $this->config->idepartments);
556       $smarty->assign("apply", apply_filter());
557       $smarty->assign("alphabet", generate_alphabet());
558       $smarty->assign("hint", print_sizelimit_warning());
559       foreach( array("depselect", "muser", "regex") as $type){
560         $smarty->assign("$type", $gmailfilter[$type]);
561       }
562       $smarty->assign("hint", print_sizelimit_warning());
563       $display.= $smarty->fetch (get_template_path('mail_locals.tpl', TRUE, dirname(__FILE__)));
564       return ($display);
565     }
567     /* Assemble normal permissions */
568     if (isset($this->imapacl['anyone'])){
569       $smarty->assign("default_permissions", $this->imapacl['anyone']);
570     }
571     $smarty->assign("member_permissions", "lrsp");
572     if (isset($this->imapacl['%members%'])){
573       $smarty->assign("member_permissions", $this->imapacl['%members%']);
574     }
576     /* Assemble extra attributes */
577     $perm= $this->getacl( "permissions");
578     $tmp= "";
579     $nr= 0;
580     $count= count($this->imapacl);
581     $this->indexed_user= array();
582     $this->indexed_acl= array();
583     foreach($this->imapacl as $user => $acl){
585       /* Add additional acl settings */
586       if ($user != "anyone" && $user != "%members%"){
588         $Dis  = "";
589         if(!preg_match("/w/",$perm)){
590           $Dis = " disabled ";
591         }
592   
593         /* Reset given Acls to ensure that nobody can read username and acls if not allwoed */
594         if(!preg_match("/r/",$perm)){
595           $user = "";
596           $nr   = "none";
597           $key  = "none";  
598         }
600         $tmp.= "<tr>  
601                  <td>
602                   <input name=\"user_$nr\" size=20 maxlength=60 value=\"$user\" ".$Dis.">
603                  </td>
604                  <td>
605                  <select size=\"1\" name=\"perm_$nr\" ".$Dis.">";
607         /* Add acl options for this additional acl setting */
608         if(preg_match("/r/",$perm)){
609           foreach ($this->perms as $key => $value){
610             if ($acl == $key){
611               $tmp.= "<option value=\"$key\" selected>$value</option>";
612             } else {
613               $tmp.= "<option value=\"$key\">$value</option>";
614             }
615           }
616         }
617         $tmp.= "</select>&nbsp;";
620         
621         if ($nr == $count - 1){
622           if($this->acl_is_writeable("acl")){
623             $tmp.= "<input type=submit value=\""._("Add")."\" ".
624               "name=\"add_$nr\" >";
625           }
626         }
627         if ($count > 3){
628           if($this->acl_is_writeable("acl")){
629             $tmp.= "<input type=submit value=\""._("Remove")."\" ".
630               "name=\"del_$nr\" ></td></tr>";        
631           }
632         }
633       }
634       $this->indexed_user[$nr]= $user;
635       $this->indexed_acl[$nr++]= $acl;
636     }
637     $smarty->assign("plusattributes", $tmp);
639     /* Show main page */
640     $mailserver= array();
641     foreach ($this->config->data['SERVERS']['IMAP'] as $key => $val){
642       $mailserver[]= $key;
643     }
644     $smarty->assign("mailServers", $mailserver);
645     foreach(array("gosaMailServer", "gosaMailQuota", "perms", "mail",
646           "gosaMailAlternateAddress", "gosaMailForwardingAddress") as $val){
647       $smarty->assign("$val", $this->$val);
648     }
649     if (is_numeric($this->gosaMailQuota) && $this->gosaMailQuota != 0){
650       if($this->acl_is_readable("gosaMailQuota")){
651         $smarty->assign("quotausage", progressbar(round(($this->quotaUsage * 100)/ $this->gosaMailQuota),100,15,true));
652         $smarty->assign("quotadefined", "true");
653       }else{
654         $smarty->assign("quotadefined", "true");
655         $smarty->assign("quotausage", "-");
656       }
657     } else {
658       $smarty->assign("quotadefined", "false");
659     }
661     if(isset($this->config->current['MAILMETHOD'])&&preg_match("/olab/i",$this->config->current['MAILMETHOD'])){
663       $smarty->assign("kolab", TRUE);
664       $smarty->assign("JS",session::get('js'));
665       $smarty->assign("kolabFolderType_Types",    array (   ''      => _('Unspecified'),  'mail' => _('Mails'),
666                                                             'task'  => _('Tasks') ,       'journal' => _('Journals'),
667                                                             'calendar' => _('Calendar'),       'contact' => _('Contacts'), 
668                                                             'note'  => _('Notes')));
669       if($this->kolabFolderType_Type == "mail"){
670         $smarty->assign("kolabFolderType_SubTypes", array(    
671               ''          => _('Unspecified'),  'inbox'     => _("Inbox")   , 
672               'drafts'    => _("Drafts"),       'sentitems' => _("Sent items"),
673               'junkemail' => _("Junk mail")));
674       }else{
675         $smarty->assign("kolabFolderType_SubTypes", array(  'default' => _("Default")));
676       }
677       $smarty->assign("kolabFolderType_Type",     $this->kolabFolderType_Type);
678       $smarty->assign("kolabFolderType_SubType",  $this->kolabFolderType_SubType);
679     }else{
680       $smarty->assign("kolab", FALSE);
681     }
683     /* Multiple support handling */
684     foreach($this->attributes as $attr){
685       if(in_array($attr,$this->multi_boxes)){
686         $smarty->assign("use_".$attr,TRUE);
687       }else{
688         $smarty->assign("use_".$attr,FALSE);
689       }
690     }
692     /* Multiple support handling */
693     foreach(array("kolabFolderType") as $attr){
694       if(in_array($attr,$this->multi_boxes)){
695         $smarty->assign("use_".$attr,TRUE);
696       }else{
697         $smarty->assign("use_".$attr,FALSE);
698       }
699     }
701     $smarty->assign("Forward_all",$this->gosaMailForwardingAddress);
702     $smarty->assign("Forward_some",$this->gosaMailForwardingAddress_Some);
704     $smarty->assign("multiple_support",$this->multiple_support_active);
705     $display.= $smarty->fetch (get_template_path('mail.tpl', TRUE, dirname(__FILE__)));
706     return ($display);
707   }
710   /* remove object from parent */
711   function remove_from_parent()
712   {
713     if(!$this->initially_was_account){
714       return;
715     }
716   
717     /* Added these ObjectClass and Attributes, because they were not 
718        removed correctly, only in case of kolab ... 
719      */
720     if(isset($this->config->current['MAILMETHOD'])&&preg_match("/olab/i",$this->config->current['MAILMETHOD'])){
721       $this->attributes[]="acl";
722       $this->objectclasses[] = "kolabSharedFolder";
723     }
724     /* include global link_info */
725     $ldap= $this->config->get_ldap_link();
727     /* Remove and write to LDAP */
728     plugin::remove_from_parent();
730     /* Zero arrays */
731     $this->attrs['gosaMailAlternateAddress']= array();
732     $this->attrs['gosaMailForwardingAddress']= array();
733     $this->attrs['gosaSharedFolderTarget']= array();
735     /* Connect to IMAP server for account deletion */
736     if ($this->initially_was_account){
737  
738       $method= new $this->method($this->config);
739       $method->fixAttributesOnRemove($this);
740       if ($method->connect($this->gosaMailServer) && $this->remove_folder_from_imap){
742         /* Remove account from IMAP server */
743         $method->deleteMailbox($this->uid);
744         $method->disconnect();
745       }
746     }
747     /* Keep uid */
748     unset ($this->attrs['uid']);
750     $ldap->cd($this->dn);
751     $ldap->modify ($this->attrs); 
752     if (!$ldap->success()){
753       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_MOD, get_class()));
754     }
757     new log("remove","groups/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
759     /* Optionally execute a command after we're done */
760     $this->handle_post_events("remove");
761   }
764   /* Save data to object */
765   function save_object()
766   {
768     /* Add special kolab attributes */    
769     if(isset($this->config->current['MAILMETHOD'])&&preg_match("/olab/i",$this->config->current['MAILMETHOD'])){
770       if(isset($_POST['kolabFolderType_Type'])){
771         $this->kolabFolderType_Type = get_post("kolabFolderType_Type");
772         $this->kolabFolderType_SubType = get_post("kolabFolderType_SubType");
773       }
774     }
775   
776     /* Check if user wants to remove the shared folder from imap too */
777     if($this->initially_was_account && !$this->is_account){
778       if(isset($_POST['remove_folder_from_imap'])){
779         $this->remove_folder_from_imap = true;
780       }else{
781         $this->remove_folder_from_imap = false;
782       }
783     }
785     /* Assemble mail delivery mode
786        The mode field in ldap consists of values between braces, this must
787        be called when 'mail' is set, because checkboxes may not be set when
788        we're in some other dialog.
790        Example for gosaMailDeliveryMode [LR        ]
791 L: Local delivery
792 R: Reject when exceeding mailsize limit
793 S: Use spam filter
794 V: Use vacation message
795 C: Use custom sieve script
796 I: Only insider delivery */
797     if (isset($_POST['mailedit'])){
799       plugin::save_object();
801       $tmp= preg_replace("/[^a-z]/i","",$this->gosaMailDeliveryMode);
803       /* Handle delivery flags */
804       if($this->acl_is_writeable("gosaMailDeliveryModeL")){
805         if(!preg_match("/L/",$tmp) && !isset($_POST['drop_own_mails'])){
806           $tmp.="L";
807         }elseif(preg_match("/L/",$tmp) && isset($_POST['drop_own_mails'])){
808           $tmp = preg_replace("/L/","",$tmp);
809         }
810       }
812       $opts = array(
813           "R"   => "use_mailsize_limit",
814           "S"   => "use_spam_filter",
815           "V"   => "use_vacation",
816           "C"   => "own_script",
817           "I"   => "only_local");
819       foreach($opts as $flag => $post){
820         if($this->acl_is_writeable("gosaMailDeliveryMode".$flag)){
821           if(!preg_match("/".$flag."/",$tmp) && isset($_POST[$post])){
822             $tmp.= $flag;
823           }elseif(preg_match("/".$flag."/",$tmp) && !isset($_POST[$post])){
824             $tmp = preg_replace("/".$flag."/","",$tmp);
825           }
826         }
827       }
829       $tmp= "[$tmp]";
830       if ($this->gosaMailDeliveryMode != $tmp){
831         $this->is_modified= TRUE;
832       }
833       $this->gosaMailDeliveryMode= $tmp;
835       /* Collect data and re-assign it to the imapacl array */
836       if ($this->acl_is_writeable("acl")){
837         $this->imapacl= array();
838         $this->imapacl['%members%']= $_POST['member_permissions'];
839         $this->imapacl['anyone']= $_POST['default_permissions'];
840         foreach ($this->indexed_user as $nr => $user){
841           if (!isset($_POST["user_$nr"])){
842             continue;
843           }
844           if ($_POST["user_$nr"] != $user ||
845               $_POST["perm_$nr"] != $this->indexed_acl[$nr]){
846             $this->is_modified= TRUE;
847           }
848           $this->imapacl[$_POST["user_$nr"]]= $_POST["perm_$nr"];
849         }
850       }
851     }
853   }
856   /* Save data to LDAP, depending on is_account we save or delete */
857   function save()
858   {
859     $ldap= $this->config->get_ldap_link();
860     $ldap->cd($this->config->current['BASE']);
862     /* Call parents save to prepare $this->attrs */
863     plugin::save();
865     /* Save arrays */
866     $this->attrs['gosaMailAlternateAddress']  = $this->gosaMailAlternateAddress;
867     $this->attrs['gosaMailForwardingAddress'] = $this->gosaMailForwardingAddress;
868     $this->attrs['gosaSharedFolderTarget']    = "share+".$this->uid;
869     $this->attrs['acl']= array();
871     /* Prepare Mail server attribute */
872     if(preg_match("/olab/i",$this->mmethod)){
873       if (empty($this->gosaMailServer)||is_array($this->gosaMailServer)){
874         if(isset($this->attrs['gosaMailServer'][0])){
875           $this->gosaMailServer = $this->attrs['gosaMailServer'][0];
876         }
877       }
878     }  
879  /* Exchange '%member%' pseudo entry */
880     $memberacl= $this->imapacl['%members%'];
881     foreach ($this->members as $user){
882       if (!isset($this->imapacl[$user])){
883         $this->imapacl[$user]= $memberacl;
884       }
885     }
887     /* Prepare kolab attributes to be written  */
888     if(preg_match("/olab/i",$this->mmethod)){
889       if(!empty($this->kolabFolderType_Type)){
890         $this->attrs['kolabFolderType'] = $this->kolabFolderType_Type.".".$this->kolabFolderType_SubType;
891       }else{
892         $this->attrs['kolabFolderType'] = array();
893       }
894     }
896     /* Get naming attribute for mail accounts */
897     $tmp = new $this->method($this->config);
898     $uattrib = $tmp->uattrib;
900     /* Create ACL array
901        What is done here.
903        1.  Do not write acl entries for empty entries.
904        2.  Check if given user is a valid GOsa user.
905        - If he is one, check if he has a valid mail extension
906        -If this is true, add the user to the ACL entry.
907        -If this is NOT true, skip ACL entries for this user.
908        - He is not a GOsa Account, so write the ACL. (Manually entered ACL)
909        3. In case of "olab" mail method, remove the entry from the $this->imapacl array
910        because the kolab deamon will set the acls for us.
912      */
913     foreach ($this->imapacl as $user => $acl){
915       /* Skip empty entries */
916       if (empty($user) || $user == ""){
917         unset($this->imapacl[$user]);
918       }
920       /* Skip placeholder */
921       if (empty($user) || $user == "" || preg_match("/%members%/",$user)){
922         continue;
923       }
925       /* Check if your is a real GOsa user
926        * If user is a real GOsa user but do not have an email address - SKIP adding acls
927        * If user is a real GOsa user with an email address - add acls
928        */
929       $ldap->search("(&(objectClass=person)(|(uid=".$user.")(mail=".$user.")))",array("mail","uid"));
930       if($ldap->count()){
932         /* Has the user a valid mail account? */
933         $attrs = $ldap->fetch();
934         if(isset($attrs['mail'][0])){
936           $name = $attrs[$uattrib][0];
937           $this->attrs['acl'][]= $name." ".$acl;
939           /* Do not write imap acl directly i nkolab mode, let the kolab deamon do this. */
940           unset($this->imapacl[$user]);
941           if(!preg_match("/olab/i",$this->mmethod)){
942             $this->imapacl[$name] = $acl;
943           }
945         }else{
947           /* User is a valid GOsa account, but he has no mail extension. Skip ACLs */
948           unset($this->imapacl[$user]);
949         }
950       }else{
952         /* Seems to be a manually a added acl
953          * Write this acl.
954          */
955         $this->attrs['acl'][]= $user." ".$acl;
957         /* In case of kolab methods, let the deamon add the imap acls */
958         if(preg_match("/olab/i",$this->mmethod)){
959           unset($this->imapacl[$user]);
960         }
961       }
962     }
964     /* Handle mail method actions, set acls, quota ...*/
965     if ((!$this->is_template)&&(!empty($this->gosaMailServer))){
966       $method= new $this->method($this->config);
967       $method->fixAttributesOnStore($this);
968       if (($method->connect($this->gosaMailServer))){
969         $method->updateMailbox($this->uid);
970         $method->setQuota($this->uid, $this->gosaMailQuota);
972         /* Only write imap acls directly if we are not
973          *  using a kolab like mail method.
974          */
975         if(!preg_match("/olab/i",$this->mmethod)){
976           $method->setSharedFolderPermissions($this->uid, $this->imapacl);
977         }
978         $method->disconnect();
979       }
980     }
982     /* Save data to LDAP */
983     $ldap->cd($this->dn);
984     $this->cleanup();
985     $ldap->modify ($this->attrs); 
986     if (!$ldap->success()){
987       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_MOD, get_class()));
988     }
989     
990     if($this->initially_was_account){
991       new log("modify","groups/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
992     }else{
993       new log("create","groups/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());  
994     }
995     
997     /* Optionally execute a command after we're done */
998     if ($this->initially_was_account == $this->is_account){
999       if ($this->is_modified){
1000         $this->handle_post_events("modify");
1001       }
1002     } else {
1003       $this->handle_post_events("add");
1004     }
1005   }
1009   /* Check formular input */
1010   function check()
1011   {
1012     $ldap= $this->config->get_ldap_link();
1014     /* Call common method to give check the hook */
1015     $message= plugin::check();
1017     if(!$this->is_account) return array();
1018     
1019     //$message[] = $str;      
1021     /* must: mail */
1022     if ($this->mail == ""){
1023       $message[]= _("The required field 'Primary address' is not set.");
1024     }
1025     if (!tests::is_email($this->mail)){
1026       $message[]= _("Please enter a valid email addres in 'Primary address' field.");
1027     }
1028     $ldap->cd($this->config->current['BASE']);
1029     $ldap->search ("(&(!(objectClass=gosaUserTemplate))(objectClass=gosaMailAccount)(|(mail=".$this->mail.")(gosaMailAlternateAddress=".
1030         $this->mail."))(!(uid=".$this->orig_cn."))(!(cn=".$this->orig_cn.")))");
1031     if ($ldap->count() != 0){
1032       $message[]= _("The primary address you've entered is already in use.");
1033     }
1034   
1035     /* Check quota */
1036     if ($this->gosaMailQuota != '' && $this->acl_is_writeable("gosaMailQuota")){
1037       if (!is_numeric($this->gosaMailQuota)) {
1038         $message[]= _("Value in 'Quota size' is not valid.");
1039       } else {
1040         $this->gosaMailQuota= (int) $this->gosaMailQuota;
1041       }
1042     }
1044     /* Check rejectsize for integer */
1045     if ($this->gosaMailMaxSize != '' && $this->acl_is_writeable("gosaMailQuota")){
1046       if (!is_numeric($this->gosaMailMaxSize)){
1047         $message[]= _("Please specify a vaild mail size for mails to be rejected.");
1048       } else {
1049         $this->gosaMailMaxSize= (int) $this->gosaMailMaxSize;
1050       }
1051     }
1053     /* Need gosaMailMaxSize if use_mailsize_limit is checked */
1054     if (is_integer(strpos($this->gosaMailDeliveryMode, "reject")) && $this->gosaMailMaxSize == ""){
1055       $message[]= _("You need to set the maximum mail size in order to reject anything.");
1056     }
1058     if(ord($this->imapacl['anyone'][0])==194){
1059       $message[] = _("Please choose valid permission settings. Default permission can't be emtpy.");
1060     }
1062     if(empty($this->gosaMailServer)){
1063       $message[] = _("Please select a valid mail server.");
1064     }
1066     return ($message);
1067   }
1069   /* Adapt from template, using 'dn' */
1070   function adapt_from_template($dn)
1071   {
1072     plugin::adapt_from_template($dn);
1074     foreach (array("gosaMailAlternateAddress", "gosaMailForwardingAddress") as $val){
1075       $this->$val= array();
1076       if (isset($this->attrs["$val"]["count"])){
1077         for ($i= 0; $i<$this->attrs["$val"]["count"]; $i++){
1078           $value= $this->attrs["$val"][$i];
1079           foreach (array("sn", "givenName", "uid") as $repl){
1080             if (preg_match("/%$repl/i", $value)){
1081               $value= preg_replace ("/%$repl/i", $this->parent->$repl, $value);
1082             }
1083           }
1084           array_push($this->$val, $value);
1085         }
1086       }
1087     }
1088   }
1090   /* Add entry to forwarder list */
1091   function addForwarder($address)
1092   {
1093     $this->gosaMailForwardingAddress[]= $address;
1094     $this->gosaMailForwardingAddress= array_unique($this->gosaMailForwardingAddress);
1096     /* Update multiple edit values too */
1097     if($this->multiple_support_active){
1098       $this->gosaMailForwardingAddress_Some= 
1099         array_remove_entries (array($address),$this->gosaMailForwardingAddress_Some);
1100     }
1102     sort ($this->gosaMailForwardingAddress);
1103     reset ($this->gosaMailForwardingAddress);
1104     $this->is_modified= TRUE;
1105   }
1107   /* Remove list of addresses from forwarder list */
1108   function delForwarder($addresses)
1109   {
1110     $this->gosaMailForwardingAddress= array_remove_entries ($addresses,
1111         $this->gosaMailForwardingAddress);
1113     /* Update multiple edit values too */
1114     if($this->multiple_support_active){
1115       $this->gosaMailForwardingAddress_Some = array_remove_entries ($addresses,
1116           $this->gosaMailForwardingAddress_Some);
1117     }
1118     $this->is_modified= TRUE;
1119   }
1123   function addAlternate($address)
1124   {
1125     $ldap= $this->config->get_ldap_link();
1127     $address= strtolower($address);
1129     /* Is this address already assigned in LDAP? */
1130     $ldap->cd ($this->config->current['BASE']);
1131     $ldap->search ("(&(objectClass=gosaMailAccount)(|(mail=$address)".
1132         "(gosaMailAlternateAddress=$address)))");
1134     if ($ldap->count() > 0){
1135       $attrs= $ldap->fetch ();
1136       return ($attrs["uid"][0]);
1137     }
1139     /* Add to list of alternates */
1140     if (!in_array($address, $this->gosaMailAlternateAddress)){
1141       $this->gosaMailAlternateAddress[]= $address;
1142     }
1144     sort ($this->gosaMailAlternateAddress);
1145     reset ($this->gosaMailAlternateAddress);
1146     $this->is_modified= TRUE;
1148     return ("");
1149   }
1152   function delAlternate($addresses)
1153   {
1154     $this->gosaMailAlternateAddress= array_remove_entries ($addresses,
1155         $this->gosaMailAlternateAddress);
1156     $this->is_modified= TRUE;
1157   }
1160   function make_name($attrs)
1161   {
1162     $name= "";
1163     if (isset($attrs['sn'][0])){
1164       $name= $attrs['sn'][0];
1165     }
1166     if (isset($attrs['givenName'][0])){
1167       if ($name != ""){
1168         $name.= ", ".$attrs['givenName'][0];
1169       } else {
1170         $name.= $attrs['givenName'][0];
1171       }
1172     }
1173     if ($name != ""){
1174       $name.= " ";
1175     }
1177     return ($name);
1178   }
1180   function getCopyDialog()
1181   {
1182     if(!$this->is_account) return("");
1184     $smarty = get_smarty();
1185     $smarty->assign("gosaMailAlternateAddress",$this->gosaMailAlternateAddress);
1186     $smarty->assign("gosaMailForwardingAddress",$this->gosaMailForwardingAddress);
1187     $smarty->assign("mail",$this->mail);
1188     $display= $smarty->fetch (get_template_path('paste_mail.tpl', TRUE, dirname(__FILE__)));
1189     $ret = array();
1190     $ret['string'] = $display;
1191     $ret['status'] = "";
1192     return($ret);
1193   }
1195   function saveCopyDialog()
1196   {
1197     if(!$this->is_account) return;
1199     /* Perform ADD / REMOVE ... for mail alternate / mail forwarding addresses 
1200     */
1201     $this->execute();
1202     if(isset($_POST['mail'])){
1203       $this->mail = $_POST['mail'];
1204     }
1205   }
1208   function PrepareForCopyPaste($source)
1209   {
1210     plugin::PrepareForCopyPaste($source);
1211  
1212     /* Reset alternate mail addresses */
1213     $this->gosaMailAlternateAddress = array();
1214   }
1217   /* Return plugin informations for acl handling  */
1218   static function plInfo()
1219   {
1220     return (array(
1221           "plShortName"   => _("Mail"),
1222           "plDescription" => _("Group mail"),
1223           "plSelfModify"  => FALSE,
1224           "plDepends"     => array(),
1225           "plPriority"    => 0,
1226           "plSection"     => array("administration"),
1227           "plCategory"    => array("groups"), 
1228           "plProvidedAcls"=> array(
1229             "mail"                      => _("Mail address"),
1230             "gosaMailAlternateAddress"  => _("Alternate addresses"),
1231             "gosaMailForwardingAddress" => _("Forwarding addresses"),
1232             "gosaMailQuota"             => _("Quota size"),
1233             "gosaMailServer"            => _("Mail server"),
1234             "acl"                       => _("Permissions"))
1235           ));
1236   }
1238   
1239   /* Remove given ACL for given member (uid,mail) ..
1240    */
1241   function removeUserAcl($index )
1242   {
1243     if(isset($this->imapacl[$index])){
1244       unset($this->imapacl[$index]);
1245     }
1246   }
1248   function multiple_execute()
1249   {
1250     return($this->execute());
1251   }
1254   function init_multiple_support($attrs,$all)
1255   {
1256     plugin::init_multiple_support($attrs,$all);
1258     $this->gosaMailForwardingAddress = array();
1259     if(isset($attrs['gosaMailForwardingAddress'])){
1260       for($i = 0 ; $i < $attrs['gosaMailForwardingAddress']['count'] ; $i++){
1261         $this->gosaMailForwardingAddress[] = $attrs['gosaMailForwardingAddress'][$i];
1262       }
1263     }
1265     $this->gosaMailForwardingAddress_Some = array();
1266     if(isset($all['gosaMailForwardingAddress'])){
1267       for($i = 0 ; $i < $all['gosaMailForwardingAddress']['count'] ; $i++){
1268         if(!in_array($all['gosaMailForwardingAddress'][$i],$this->gosaMailForwardingAddress)){
1269           $this->gosaMailForwardingAddress_Some[] = $all['gosaMailForwardingAddress'][$i];
1270         }
1271       }
1272     }
1273   }
1275   function multiple_save_object()
1276   {
1277     if(isset($_POST['multiple_mail_group_posted'])){
1278       plugin::multiple_save_object();
1279       
1280       foreach(array("kolabFolderType") as $attr){
1281         if(isset($_POST['use_'.$attr])){
1282           $this->multi_boxes[] = $attr;
1283         }
1284       }
1286       /* Add special kolab attributes */
1287       if(isset($this->config->current['MAILMETHOD'])&&preg_match("/olab/i",$this->config->current['MAILMETHOD'])){
1288         if(isset($_POST['kolabFolderType_Type'])){
1289           $this->kolabFolderType_Type = get_post("kolabFolderType_Type");
1290           $this->kolabFolderType_SubType = get_post("kolabFolderType_SubType");
1291         }
1292       }
1294       /* Collect data and re-assign it to the imapacl array */
1295       if ($this->acl_is_writeable("acl")){
1296         $this->imapacl= array();
1297         $this->imapacl['%members%']= $_POST['member_permissions'];
1298         $this->imapacl['anyone']= $_POST['default_permissions'];
1299         foreach ($this->indexed_user as $nr => $user){
1300           if (!isset($_POST["user_$nr"])){
1301             continue;
1302           }
1303           if ($_POST["user_$nr"] != $user ||
1304               $_POST["perm_$nr"] != $this->indexed_acl[$nr]){
1305             $this->is_modified= TRUE;
1306           }
1307           $this->imapacl[$_POST["user_$nr"]]= $_POST["perm_$nr"];
1308         }
1309       }
1310     }
1311   }
1312   
1313   
1314   /* Return selected values for multiple edit */
1315   function get_multi_edit_values()
1316   {
1317     $ret = plugin::get_multi_edit_values();
1318     $ret['Forward_some'] = $this->gosaMailForwardingAddress_Some;    
1319     $ret['Forward_all'] = $this->gosaMailForwardingAddress;    
1320     if(in_array('kolabFolderType',$this->multi_boxes)){
1321       $ret['kolabFolderType_Type'] = $this->kolabFolderType_Type;
1322       $ret['kolabFolderType_SubType'] = $this->kolabFolderType_SubType;
1323     }
1324     if(in_array("acl",$this->multi_boxes)){
1325       $ret['imapacl'] = $this->imapacl;
1326     }
1327     return($ret);
1328   }
1330   function set_multi_edit_values($attrs)
1331   {
1332     $forward = array();
1333     foreach($attrs['Forward_some'] as $addr){
1334       if(in_array($addr,$this->gosaMailForwardingAddress)){
1335         $forward[] = $addr;
1336       }
1337     }
1338     foreach($attrs['Forward_all'] as $addr){
1339       $forward[] = $addr;
1340     }
1341     plugin::set_multi_edit_values($attrs);
1342     $this->gosaMailForwardingAddress = $forward;
1343   }
1346   // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1347 ?>