Code

Updated mail group
[gosa.git] / plugins / admin / groups / 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 $gosaMailServer             = "";       // Selected mailserver 
17   var $gosaMailQuota              = "";       // Defined Quota 
18   var $quotaUsage                 = 0;        // Currently used quota
20   var $gosaVacationMessage        = "";       // Vocation message 
22   var $imapacl                    = array(
23       '%members%' => 'lrspw',  // %members% are all group-members
24       'anyone'    => 'p',     // Set acls for everyone
25       ''          => 'p');    // Every user added gets this right
28   var $gosaSpamSortLevel          = "";     
29   var $gosaSpamMailbox            = "";
30   var $gosaSharedFolderTarget     ;
32   var $forward_dialog             = FALSE;    
34   var $members                    = array();  // Group members
36   var $mailusers                  = array();
37   var $perms                      = array();
38   var $gosaMailDeliveryMode       = "[L        ]";   // 
39   var $gosaMailMaxSize            = "";       // 
40   
41   var $remove_folder_from_imap    = true;
43   /* Helper */
44   var $indexed_acl= array();
45   var $indexed_user= array();
47   /* Copy & paste */
48   var $CopyPasteVars          = array("quotaUsage","imapacl");
50   /* attribute list for save action */
51   var $attributes= array( "mail",   "gosaMailServer", "gosaMailQuota", "gosaMailMaxSize",
52       "gosaMailAlternateAddress", "gosaMailForwardingAddress",
53       "gosaMailDeliveryMode", "gosaSpamSortLevel", "gosaSpamMailbox",
54       "acl","gosaSharedFolderTarget", "gosaVacationMessage");
56   var $objectclasses= array("gosaMailAccount");
58   var $kolabFolderType_SubType = "";
59   var $kolabFolderType_Type = "";
61   function mailgroup ($config, $dn= NULL, $parent= NULL)
62   {
63     /* Initialise all available attributes ... if possible
64      */
65     plugin::plugin($config, $dn, $parent);
67     /* Save initial cn */
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     if (class_exists("mailMethod$this->mmethod")){
79       $this->method= "mailMethod$this->mmethod";
80     } else {
81       print_red(sprintf(_("There is no mail method '%s' specified in your gosa.conf available."), $this->mmethod));
82     }
84     /* Load Mailserver  
85      */
86     if(isset($this->attrs['gosaMailServer'][0])){
87       $this->gosaMailServer =  $this->attrs['gosaMailServer'][0];
88     }
90     /* Convert cn to uid in case of existing entry
91      */
92     if (isset($this->attrs['cn'][0])){
93       $this->uid = $this->cn = $this->attrs['cn'][0];
94     }
96     /* Get folder type */
97     if(isset($this->config->current['MAILMETHOD'])&&preg_match("/olab/i",$this->config->current['MAILMETHOD'])){
98       if(isset($this->attrs['kolabFolderType'])){
99         $tmp = split("\.",$this->attrs['kolabFolderType'][0]);
100         $this->kolabFolderType_Type = $tmp[0];
101         $this->kolabFolderType_SubType = $tmp[1];
102       }
103     }
105     /* If this isn't a new mailgroup, read all required data from ldap
106      */
107     if (($dn != "new")&&($dn != NULL)){
109       /* Load attributes which represent multiple entries  
110        */
111       foreach (array("gosaMailAlternateAddress", "gosaMailForwardingAddress") as $val){
112         $this->$val = array();
113         if (isset($this->attrs["$val"]["count"])){
114           for ($i= 0; $i<$this->attrs["$val"]["count"]; $i++){
115             array_push($this->$val, $this->attrs["$val"][$i]);
116           }
117         }
118       }
120       /* Only do IMAP actions if gosaMailServer attribute is set 
121        */
122       if (isset ($this->attrs["gosaMailServer"][0])){
124         /* Create new instance of our defined mailclass
125          */
126         $method= new $this->method($this->config);
127         if ($method->connect($this->attrs["gosaMailServer"][0])){
129           /* If we do NOT use kolab or equal methods, 
130              read imap the acls from the mail method class.
131              They will be merged later with the ldap specified acls.
132            */
133           if(!preg_match("/olab/i",$this->mmethod) && !empty($this->mmethod)){
134             $this->imapacl=  $method->getSharedFolderPermissions($this->uid);
136             /* Need to filter what a member acl could be... */
137             $vote= array();
138             $peak= 0;
139             $leader= "";
140             foreach ($this->imapacl as $user => $acl){
142               if ($user != "anyone" ){
143                 if (!isset($vote[$acl])){
144                   $vote[$acl]= 1;
145                 } else {
146                   $vote[$acl]++;
147                 }
148                 if ($vote[$acl] > $peak){
149                   $leader= $acl;
150                   $peek= $vote[$acl];
151                 }
152               }
153             }
154             /* Highest count wins as %members%, remove all members
155                with the same acl */
156             if(!empty($leader)){
157               $this->imapacl['%members%']= $leader;
158             }
159             foreach ($this->imapacl as $user => $acl){
160               if ($this->acl == $leader && in_array($user, $this->attrs['memberUid'])){
161                 unset($this->imapacl[$user]);
162               }
163             }
164           }
166           /* Adapt attributes if needed */
167           $method->fixAttributesOnLoad($this);
169           /*  get Quota */
170           $quota= $method->getQuota($this->uid);
172           /* Update quota values */
173           if(is_array($quota)){
174             if ($quota['gosaMailQuota'] == 2147483647){
175               $this->quotaUsage= "";
176               $this->gosaMailQuota= "";
177             } else {
178               $this->quotaUsage= $quota['quotaUsage'];
179               $this->gosaMailQuota= $quota['gosaMailQuota'];
180             }
181           }else{
182             $this->quotaUsage     = "";
183             $this->gosaMailQuota  = "";
184           }
185           $method->disconnect();
186         }   // ENDE $method->connect($this->attrs["gosaMailServer"][0])){
187       }   // ENDE gosaMailServer
188     }   // ENDE dn != "new"
191     /* Get global filter config */
192     if (!is_global("gmailfilter")){
193       $ui= get_userinfo();
194       $base= get_base_from_people($ui->dn);
195       $gmailfilter= array( "depselect"       => $base,
196           "muser"            => "",
197           "regex"           => "*");
198       register_global("gmailfilter", $gmailfilter);
199     }
201     /* Load permissions */
202     $tmp = array();
203     $ldap = $this->config->get_ldap_link();
205     /* Read acls  from ldap and merge them with 
206      *  acls read from mail method. 
207      */
208     if (isset($this->attrs['acl'])){
210       for ($i= 0; $i<$this->attrs['acl']['count']; $i++){
211         list($user, $permission)= split(' ', $this->attrs['acl'][$i]);
213         /* Add to list */
214         $this->imapacl[$user]= $permission;
216         /* Get all user permissions sorted by acl, to detect the most used acl
217            This acl is then used for %members%
218          */
219         if ($user != "anyone" && $user != "%members%"){
220           $tmp[$permission][] = $user;
221         }
223         /* There is an entry in $this->imapacl like this this ... 
224            $this->attrs['imapacl']['anyone'] = "p";
225            $this->attrs['imapacl']['%members%'] = "lprs";
226            $this->attrs['imapacl'][''] = ""; <------ This is used to diplay an empty 
227            Field for special acls in our template.
228            If there is at least one special acl in out imapacl,
229            we don't need this entry anymore, because it is already displayed. 
230          */
231         if ($user != "anyone" && $user != "%members%"){
232           unset($this->imapacl['']);
233         }
234       }
235     }
237     /**
238      * Detect group members which use the same acl 
239      *  as used for %members% and remove them.
240      **/
242     /* In this section we detect which acl is the most used.
243        This will be used as %members% acl.
244      */
245     $tmp2 = array(); 
246     foreach($tmp as $acl => $user){
247       $tmp2[count($tmp[$acl])]=$acl;
248     }
249     /* Most used at last 
250      */
251     ksort($tmp2);      
253     /* Assign last (most used acl) to %members% acl 
254      */
255     $str = array_pop($tmp2);
256     if(!empty($str)) {
257       $this->imapacl['%members%']=$str;
258     }
259     if(!isset($this->imapacl['%members%'])){
260       $this->imapacl['%members%'] = "lrspw";
261     }
264     /* Open ldap connection 
265      */
266     $ldap = $this->config->get_ldap_link();
267     $ldap->cd($this->config->current['BASE']);
269     /* Remove those users, that use %members% acl && are member of this group. */
270     foreach($this->imapacl as $mail => $permission){
271       $ldap->search("(&(objectClass=person)(|(mail=".$mail.")(uid=".$mail.")))",array("uid"));
272       $atr = $ldap->fetch();
273       if((isset($this->attrs['memberUid'])) && (is_array($this->attrs['memberUid']))){
274         if((isset($atr['uid'][0]))&&(in_array($atr['uid'][0],$this->attrs['memberUid']))&&($permission == $this->imapacl['%members%'])){
275           unset($this->imapacl[$mail]);
276         }
277       }
278     }
280     /**
281      * ENDE: Detect group member with same acl and replace them with %members%
282      **/
283     $this->indexed_user = array("%members%","anyone");
285     /* Append an empty entry, for special acl handling */
286     if(count($this->imapacl)==2){
287       $this->imapacl[''] ="lrsw";
288       $this->indexed_user[] = ''; 
289     }
291     /* Load Mailserver  
292      */
293     if(isset($this->attrs['gosaMailServer'][0])){
294       $this->gosaMailServer =  $this->attrs['gosaMailServer'][0];
295     }
296     /* Fill translations */
297     $this->perms["lrsw"]= _("read");
298     $this->perms["lrswp"]= _("post");
299     $this->perms["p"]= _("external post");
300     $this->perms["lrswip"]= _("append");
301     $this->perms["lrswipcd"]= _("write");
302     $this->perms["lrswipcda"]= _("admin");
303     $this->perms[""]= _("none");
304   }
307   function execute()
308   {
309     /* Call parent execute */
310     //plugin::execute();
312     /* Load templating engine */
313     $smarty= get_smarty();
314     $display = "";
315     if ($_SESSION['js']==FALSE){
316       $smarty->assign("javascript", "false");
317     } else {
318       $smarty->assign("javascript", "true");
319     }
321     /* Do we need to flip is_account state? */
322     if (isset($_POST['modify_state'])){
324       /* Onyl change account state if allowed */
325       if($this->is_account && $this->acl == "#all#"){
326         $this->is_account= !$this->is_account;
327       }elseif(!$this->is_account && chkacl($this->acl,"create") == ""){
328         $this->is_account= !$this->is_account;
329       }
330     }
331     
332     /* Do we represent a valid account? */
333     if (!$this->is_account && $this->parent == NULL){
335       $display.= "<img alt=\"\" src=\"images/stop.png\" align=middle>&nbsp;<b>".
336         _("This 'dn' has no valid mail extensions.")."</b>";
337       return ($display);
338     }
340     /* Show tab dialog headers */
341     $display= "";
342     if ($this->parent != NULL){
343       if ($this->is_account){
344         $display= $this->show_header(_("Remove mail account"),
345             _("This account has mail features enabled. You can disable them by clicking below."));
346       } else {
347         $display.= $this->show_header(_("Create mail account"),
348             _("This account has mail features disabled. You can enable them by clicking below."));
350         /* Show checkbox that allows us to remove imap entry too*/
351         if($this->initially_was_account){
352         
353           $c = "";
354           if($this->remove_folder_from_imap){
355             $c= " checked ";
356           }
357   
358           $display .= "<h2>Shared folder delete options</h2>
359                        <input class='center' type='checkbox' name='remove_folder_from_imap' value='1' ".$c."  
360                           title='"._("Remove shared folder from mail server database when entry gets removed in LDAP")."'>";
361           $display .= _("Remove the shared folder and all its contents after saving this account"); 
362         }
364         return ($display);
365       }
366     }
368     /* Add ACL? */
369     if (isset($_POST["add_acl"])){
370       $this->imapacl[""]= "lrsw";
371       $this->indexed_user[] = "";
372     }
373     foreach ($this->indexed_user as $nr => $user){
374       if (isset($_POST["del_$nr"])){
375         unset ($this->imapacl[$user]);
376       }
377     }
379     /* Trigger forward add dialog? */
380     if (isset($_POST['add_local_forwarder'])){
381       $this->forward_dialog= TRUE;
382       $this->dialog= TRUE;
383     }
385     /* Cancel forward add dialog? */
386     if (isset($_POST['add_locals_cancel'])){
387       $this->forward_dialog= FALSE;
388       $this->dialog= FALSE;
389     }
391     /* Finished adding of locals? */
392     if (isset($_POST['add_locals_finish'])){
393       if (count ($_POST['local_list']) &&
394           chkacl ($this->acl, "gosaMailForwardingAddress") == ""){
396         /* Walk through list of forwarders, ignore own addresses */
397         foreach ($_POST['local_list'] as $val){
398           if (!in_array ($val, $this->gosaMailAlternateAddress) &&
399               $val != $this->mail){
401             $this->addForwarder($val);
402           }
403         }
404       }
405       $this->forward_dialog= FALSE;
406       $this->dialog= FALSE;
407     }
409     /* Add forward email addresses */
410     if (isset($_POST['add_forwarder'])){
411       if ($_POST['forward_address'] != ""){
413         /* Valid email address specified? */
414         $address= $_POST['forward_address'];
415         if (!is_email($address)){
417           print_red (_("You're trying to add an invalid email address ".
418                 "to the list of forwarders."));
420         } elseif ($address == $this->mail
421             || in_array($address, $this->gosaMailAlternateAddress)) {
423           print_red (_("Adding your one of your own addresses to the forwarders makes no sense."));
425         } else {
427           /* Add it */
428           if (chkacl ($this->acl, "gosaMailForwardingAddress") == ""){
429             $this->addForwarder ($address);
430           }
432         }
433       }
434     }
436     /* Delete forward email addresses */
437     if (isset($_POST['delete_forwarder'])){
438       if (count($_POST['forwarder_list'])
439           && chkacl ($this->acl, "gosaMailForwardingAddress") == ""){
441         $this->delForwarder ($_POST['forwarder_list']);
442       }
443     }
445     /* Add alternate email addresses */
446     if (isset($_POST['add_alternate'])){
447       if ($_POST['alternate_address'] != "" &&
448           chkacl ($this->acl, "gosaMailAlternateAddress") == ""){
450         if (!is_email($_POST['alternate_address'])){
451           print_red (_("You're trying to add an invalid email address to the list of alternate addresses."));
453         } elseif (($user= $this->addAlternate ($_POST['alternate_address'])) != ""){
454           $ui= get_userinfo();
455           if ($user != $ui->username){
456             print_red (_("The address you're trying to add is already used by user")." '$user'.");
457           }
458         }
459       }
460     }
462     /* Delete alternate email addresses */
463     if (isset($_POST['delete_alternate']) && isset ($_POST['alternates_list'])){
464       if (count($_POST['alternates_list']) &&
465           chkacl ($this->acl, "gosaMailAlternateAddress") == ""){
467         $this->delAlternate ($_POST['alternates_list']);
468       }
469     }
471     /* Show forward add dialog */
472     if ($this->forward_dialog){
473       $ldap= $this->config->get_ldap_link();
475       /* Save data */
476       $gmailfilter= get_global("gmailfilter");
477       foreach( array("depselect", "muser", "regex") as $type){
478         if (isset($_POST[$type])){
479           $gmailfilter[$type]= $_POST[$type];
480         }
481       }
482       if (isset($_GET['search'])){
483         $s= mb_substr($_GET['search'], 0, 1, "UTF8")."*";
484         if ($s == "**"){
485           $s= "*";
486         }
487         $gmailfilter['regex']= $s;
488       }
489       register_global("gmailfilter", $gmailfilter);
491       /* Get actual list */
492       $mailusers= array ();
493       if ($gmailfilter['regex'] != '*' && $gmailfilter['regex'] != ""){
494         $regex= $gmailfilter['regex'];
495         $filter= "(|(mail=$regex)(gosaMailAlternateAddress=$regex))";
496       } else {
497         $filter= "";
498       }
499       if ($gmailfilter['muser'] != ""){
500         $user= $gmailfilter['muser'];
501         $filter= "$filter(|(uid=$user)(cn=$user)(givenName=$user)(sn=$user))";
502       }
504       /* Add already present people to the filter */
505       $exclude= "";
506       foreach ($this->gosaMailForwardingAddress as $mail){
507         $exclude.= "(mail=$mail)";
508       }
509       if ($exclude != ""){
510         $filter.= "(!(|$exclude))";
511       }
513       $acl= array($this->config->current['BASE'] => ":all");
514       $res= get_list("(&(objectClass=gosaMailAccount)$filter)", $acl, $gmailfilter['depselect'],
515                      array("sn", "mail", "givenName"), GL_SUBSEARCH | GL_SIZELIMIT);
516       $ldap->cd($gmailfilter['depselect']);
517       $ldap->search ("(&(objectClass=gosaMailAccount)$filter)", array("sn", "mail", "givenName"));
518       error_reporting (0);
519       while ($attrs= $ldap->fetch()){
520         if(preg_match('/%/', $attrs['mail'][0])){
521           continue;
522         }
523         $name= $this->make_name($attrs);
524         $mailusers[$attrs['mail'][0]]= $name."&lt;".
525           $attrs['mail'][0]."&gt;";
526       }
527       error_reporting (E_ALL);
528       natcasesort ($mailusers);
529       reset ($mailusers);
531       /* Show dialog */
532       $smarty->assign("search_image", get_template_path('images/search.png'));
533       $smarty->assign("usearch_image", get_template_path('images/search_user.png'));
534       $smarty->assign("tree_image", get_template_path('images/tree.png'));
535       $smarty->assign("infoimage", get_template_path('images/info.png'));
536       $smarty->assign("launchimage", get_template_path('images/small_filter.png'));
537       $smarty->assign("mailusers", $mailusers);
538       $smarty->assign("deplist", $this->config->idepartments);
539       $smarty->assign("apply", apply_filter());
540       $smarty->assign("alphabet", generate_alphabet());
541       $smarty->assign("hint", print_sizelimit_warning());
542       foreach( array("depselect", "muser", "regex") as $type){
543         $smarty->assign("$type", $gmailfilter[$type]);
544       }
545       $smarty->assign("hint", print_sizelimit_warning());
546       $display.= $smarty->fetch (get_template_path('mail_locals.tpl', TRUE));
547       return ($display);
548     }
550     /* Assemble normal permissions */
551     $smarty->assign("permissionsACL", chkacl($this->acl, "permissions"));
552     if (isset($this->imapacl['anyone'])){
553       $smarty->assign("default_permissions", $this->imapacl['anyone']);
554     }
555     $smarty->assign("member_permissions", "lrsp");
556     if (isset($this->imapacl['%members%'])){
557       $smarty->assign("member_permissions", $this->imapacl['%members%']);
558     }
560     /* Assemble extra attributes */
561     $perm= chkacl($this->acl, "permissions");
562     $tmp= "";
563     $nr= 0;
564     $count= count($this->imapacl);
565     $this->indexed_user= array();
566     $this->indexed_acl= array();
567     foreach($this->imapacl as $user => $acl){
568       if ($user != "anyone" && $user != "%members%"){
569         $tmp.= "<tr><td><input name=\"user_$nr\" size=20 maxlength=60 ".
570           "value=\"$user\" $perm></td><td><select size=\"1\" name=\"perm_$nr\" $perm>";
571         foreach ($this->perms as $key => $value){
572           if ($acl == $key){
573             $tmp.= "<option value=\"$key\" selected>$value</option>";
574           } else {
575             $tmp.= "<option value=\"$key\">$value</option>";
576           }
577         }
578         $tmp.= "</select>&nbsp;";
579         if ($nr == $count - 1){
580         }
581         if ($count > 2){
582           $tmp.= "</td><td><input type=submit value=\""._("Remove")."\" ".
583             "name=\"del_$nr\" $perm></td></tr>";
584         }
585       }
586       $this->indexed_user[$nr]= $user;
587       $this->indexed_acl[$nr++]= $acl;
588     }
589     $tmp.= "<tr><td></td><td></td><td><input type=submit value='"._("Add")."' name='add_acl' $perm>";
590     $smarty->assign("plusattributes", $tmp);
592     /* Show main page */
593     $mailserver= array();
594     foreach ($this->config->data['SERVERS']['IMAP'] as $key => $val){
595       $mailserver[]= $key;
596     }
597     $smarty->assign("mailServers", $mailserver);
598     foreach(array("gosaMailServer", "gosaMailQuota", "perms", "mail",
599           "gosaMailAlternateAddress", "gosaMailForwardingAddress") as $val){
600       $smarty->assign("$val", $this->$val);
601       $smarty->assign("$val"."ACL", chkacl($this->acl, "$val"));
602     }
603     if (is_numeric($this->gosaMailQuota) && $this->gosaMailQuota != 0){
604       $smarty->assign("quotausage", progressbar(round(($this->quotaUsage * 100)/ $this->gosaMailQuota),100,15,true));
605       $smarty->assign("quotadefined", "true");
606     } else {
607       $smarty->assign("quotadefined", "false");
608     }
610     if(isset($this->config->current['MAILMETHOD'])&&preg_match("/olab/i",$this->config->current['MAILMETHOD'])){
612       $smarty->assign("kolab", TRUE);
613       $smarty->assign("JS",$_SESSION['js']);
614       $smarty->assign("kolabFolderType_Types",    array (   ''      => _('Unspecified'),  'mail' => _('Mails'),
615                                                             'task'  => _('Tasks') ,       'journal' => _('Journals'),
616                                                             'calendar' => _('Calendar'),       'contact' => _('Contacts'), 
617                                                             'note'  => _('Notes')));
618       if($this->kolabFolderType_Type == "mail"){
619         $smarty->assign("kolabFolderType_SubTypes", array(    
620               ''          => _('Unspecified'),  'inbox'     => _("Inbox")   , 
621               'drafts'    => _("Drafts"),       'sentitems' => _("Sent items"),
622               'junkemail' => _("Junk mail")));
623       }else{
624         $smarty->assign("kolabFolderType_SubTypes", array(  'default' => _("Default")));
625       }
626       $smarty->assign("kolabFolderType_Type",     $this->kolabFolderType_Type);
627       $smarty->assign("kolabFolderType_SubType",  $this->kolabFolderType_SubType);
628     }else{
629       $smarty->assign("kolab", FALSE);
630     }
633     $display.= $smarty->fetch (get_template_path('mail.tpl', TRUE));
634     return ($display);
635   }
638   /* remove object from parent */
639   function remove_from_parent()
640   {
641     /* Added these ObjectClass and Attributes, because they were not 
642        removed correctly, only in case of kolab ... 
643      */
644     if(isset($this->config->current['MAILMETHOD'])&&preg_match("/olab/i",$this->config->current['MAILMETHOD'])){
645       $this->attributes[]="acl";
646       $this->objectclasses[] = "kolabSharedFolder";
647     }
648     /* include global link_info */
649     $ldap= $this->config->get_ldap_link();
651     /* Remove and write to LDAP */
652     plugin::remove_from_parent();
654     /* Zero arrays */
655     $this->attrs['gosaMailAlternateAddress']= array();
656     $this->attrs['gosaMailForwardingAddress']= array();
657     $this->attrs['gosaSharedFolderTarget']= array();
659     /* Connect to IMAP server for account deletion */
660     if ($this->initially_was_account){
661  
662       $method= new $this->method($this->config);
663       $method->fixAttributesOnRemove($this);
664       if ($method->connect($this->gosaMailServer) && $this->remove_folder_from_imap){
666         /* Remove account from IMAP server */
667         $method->deleteMailbox($this->uid);
668         $method->disconnect();
669       }
670     }
671     /* Keep uid */
672     unset ($this->attrs['uid']);
674     $ldap->cd($this->dn);
675     $ldap->modify ($this->attrs); 
676     show_ldap_error($ldap->get_error(), _("Removing group mail settings failed"));
678     /* Optionally execute a command after we're done */
679     $this->handle_post_events("remove");
680   }
683   /* Save data to object */
684   function save_object()
685   {
687     /* Add special kolab attributes */    
688     if(isset($this->config->current['MAILMETHOD'])&&preg_match("/olab/i",$this->config->current['MAILMETHOD'])){
689       if(isset($_POST['kolabFolderType_Type'])){
690         $this->kolabFolderType_Type = get_post("kolabFolderType_Type");
691         $this->kolabFolderType_SubType = get_post("kolabFolderType_SubType");
692       }
693     }
694   
695     /* Check if user wants to remove the shared folder from imap too */
696     if($this->initially_was_account && !$this->is_account){
697       if(isset($_POST['remove_folder_from_imap'])){
698         $this->remove_folder_from_imap = true;
699       }else{
700         $this->remove_folder_from_imap = false;
701       }
702     }
704     /* Assemble mail delivery mode
705        The mode field in ldap consists of values between braces, this must
706        be called when 'mail' is set, because checkboxes may not be set when
707        we're in some other dialog.
709        Example for gosaMailDeliveryMode [LR        ]
710 L: Local delivery
711 R: Reject when exceeding mailsize limit
712 S: Use spam filter
713 V: Use vacation message
714 C: Use custom sieve script
715 I: Only insider delivery */
716     if (isset($_POST['mailedit'])){
718       /* Save ldap attributes */
719       plugin::save_object();
721       $tmp= "";
722       if (!isset($_POST["drop_own_mails"])){
723         $tmp.= "L";
724       }
725       if (isset($_POST["use_mailsize_limit"])){
726         $tmp.= "R";
727       }
728       if (isset($_POST["use_spam_filter"])){
729         $tmp.= "S";
730       }
731       if (isset($_POST["use_vacation"])){
732         $tmp.= "V";
733       }
734       if (isset($_POST["own_script"])){
735         $tmp.= "C";
736       }
737       if (isset($_POST["only_local"])){
738         $tmp.= "I";
739       }
740       $tmp= "[$tmp]";
742       if (chkacl ($this->acl, "gosaMailDeliveryMode") == ""){
743         $this->gosaMailDeliveryMode= $tmp;
744       }
746       /* Collect data and re-assign it to the imapacl array */
747       if (chkacl($this->acl, "permissions") == ""){
748         $this->imapacl= array();
749         $this->imapacl['%members%']= $_POST['member_permissions'];
750         $this->imapacl['anyone']= $_POST['default_permissions'];
751         foreach ($this->indexed_user as $nr => $user){
752           if (!isset($_POST["user_$nr"])){
753             continue;
754           }
755           if ($_POST["user_$nr"] != $user ||
756               $_POST["perm_$nr"] != $this->indexed_acl[$nr]){
757             $this->is_modified= TRUE;
758           }
759           $this->imapacl[$_POST["user_$nr"]]= $_POST["perm_$nr"];
760           $this->indexed_user[$nr] = $_POST["user_$nr"];
761         }
762       }
763     }
764   }
767   /* Save data to LDAP, depending on is_account we save or delete */
768   function save()
769   {
770     $ldap= $this->config->get_ldap_link();
771     $ldap->cd($this->config->current['BASE']);
773     /* Call parents save to prepare $this->attrs */
774     plugin::save();
776     /* Save arrays */
777     $this->attrs['gosaMailAlternateAddress']  = $this->gosaMailAlternateAddress;
778     $this->attrs['gosaMailForwardingAddress'] = $this->gosaMailForwardingAddress;
779     $this->attrs['gosaSharedFolderTarget']    = "share+".$this->uid;
780     $this->attrs['acl']= array();
782     /* Prepare Mail server attribute */
783     if(preg_match("/olab/i",$this->mmethod)){
784       if (empty($this->gosaMailServer)||is_array($this->gosaMailServer)){
785         if(isset($this->attrs['gosaMailServer'][0])){
786           $this->gosaMailServer = $this->attrs['gosaMailServer'][0];
787         }
788       }
789     }  
791     /* Exchange '%member%' pseudo entry */
792     $memberacl= $this->imapacl['%members%'];
793     foreach ($this->members as $user){
794       if (!isset($this->imapacl[$user])){
795         $this->imapacl[$user]= $memberacl;
796       }
797     }
799     /* Prepare kolab attributes to be written  */
800     if(preg_match("/olab/i",$this->mmethod)){
801       if(!empty($this->kolabFolderType_Type)){ 
802         $this->attrs['kolabFolderType'] = $this->kolabFolderType_Type.".".$this->kolabFolderType_SubType;
803       }else{
804         $this->attrs['kolabFolderType'] = array();
805       }
806     }
808     /* Get naming attribute for mail accounts */  
809     $tmp = new $this->method($this->config);
810     $uattrib = $tmp->uattrib;
812     /* Create ACL array 
813       What is done here.
814         
815         1.  Do not write acl entries for empty entries. 
816         2.  Check if given user is a valid GOsa user. 
817             - If he is one, check if he has a valid mail extension
818               -If this is true, add the user to the ACL entry.
819               -If this is NOT true, skip ACL entries for this user.
820             - He is not a GOsa Account, so write the ACL. (Manually entered ACL)
821         3. In case of "olab" mail method, remove the entry from the $this->imapacl array
822             because the kolab deamon will set the acls for us.
824      */
825     $acls_set_for = array();
826     foreach ($this->imapacl as $user => $acl){
828       /* Skip empty entries */
829       if (empty($user) || $user == ""){
830         unset($this->imapacl[$user]);
831       }
832   
833       /* Skip placeholder */
834       if (empty($user) || $user == "" || preg_match("/%members%/",$user)){
835         continue;
836       }
838       /* Check if your is a real GOsa user  
839        * If user is a real GOsa user but do not have an email address - SKIP adding acls
840        * If user is a real GOsa user with an email address - add acls  
841        */
842       $ldap->search("(&(objectClass=person)(|(uid=".$user.")(mail=".$user.")))",array("mail","uid"));
843       if($ldap->count()){
845         /* Has the user a valid mail account? */
846         $attrs = $ldap->fetch();
847         if(isset($attrs['mail'][0])){
849           $name = $attrs[$uattrib][0];
851           /* Do not overwrite manually set ACLs with group member acls 
852           */
853           if(!in_array($name,$acls_set_for)){
854             $this->attrs['acl'][]= $name." ".$acl;
855           }
856           $acls_set_for[] = $name;
857       
859           /* Do not write imap acl directly i nkolab mode, let the kolab deamon do this. */
860           unset($this->imapacl[$user]);
861           if(!preg_match("/olab/i",$this->mmethod)){
862             $this->imapacl[$name] = $acl;
863           }
865         }else{
867           /* User is a valid GOsa account, but he has no mail extension. Skip ACLs */
868           unset($this->imapacl[$user]);
869         }
870       }else{
872         /* Seems to be a manually a added acl 
873          * Write this acl.
874          */
876         /* Do not overwrite manually set ACLs with group member acls 
877          */
878         if(!in_array($user,$acls_set_for)){
879           $this->attrs['acl'][]= $user." ".$acl;
880           $acls_set_for[] = $user;
881         }
883         /* In case of kolab methods, let the deamon add the imap acls */
884         if(preg_match("/olab/i",$this->mmethod)){
885           unset($this->imapacl[$user]);
886         }
887       }
888     }
890     /* Handle mail method actions, set acls, quota ...*/ 
891     if ((!$this->is_template)&&(!empty($this->gosaMailServer))){
892       $method= new $this->method($this->config);
893       $method->fixAttributesOnStore($this);
894       if (($method->connect($this->gosaMailServer))){
895         $method->updateMailbox($this->uid);
896         $method->setQuota($this->uid, $this->gosaMailQuota);
898         /* Only write imap acls directly if we are not 
899          *  using a kolab like mail method.
900          */
901         if(!preg_match("/olab/i",$this->mmethod)){
902           $method->setSharedFolderPermissions($this->uid, $this->imapacl);
903         }
904         $method->disconnect();
905       }
906     }
908     /* Save data to LDAP */
909     $ldap->cd($this->dn);
910     $this->cleanup();
911     $ldap->modify ($this->attrs); 
912     show_ldap_error($ldap->get_error(), _("Saving group mail settings failed"));
914     /* Optionally execute a command after we're done */
915     if ($this->initially_was_account == $this->is_account){
916       if ($this->is_modified){
917         $this->handle_post_events("modify");
918       }
919     } else {
920       $this->handle_post_events("add");
921     }
922   }
925   /* Check formular input */
926   function check()
927   {
928     $ldap= $this->config->get_ldap_link();
930     /* Call common method to give check the hook */
931     $message= plugin::check();
933     if(!$this->is_account) return array();
934     
935     //$message[] = $str;      
937     /* must: mail */
938     if ($this->mail == ""){
939       $message[]= _("The required field 'Primary address' is not set.");
940     }
941     if (!is_email($this->mail)){
942       $message[]= _("Please enter a valid email addres in 'Primary address' field.");
943     }
944     $ldap->cd($this->config->current['BASE']);
945     $ldap->search ("(&(!(objectClass=gosaUserTemplate))(objectClass=gosaMailAccount)(|(mail=".$this->mail.")(gosaMailAlternateAddress=".
946         $this->mail."))(!(uid=".$this->orig_cn."))(!(cn=".$this->orig_cn.")))");
947     if ($ldap->count() != 0){
948       $message[]= _("The primary address you've entered is already in use.");
949     }
950   
951     /* Check quota */
952     if ($this->gosaMailQuota != '' && chkacl ($this->acl, "gosaMailQuota") == ""){
953       if (!is_numeric($this->gosaMailQuota)) {
954         $message[]= _("Value in 'Quota size' is not valid.");
955       } else {
956         $this->gosaMailQuota= (int) $this->gosaMailQuota;
957       }
958     }
960     /* Check rejectsize for integer */
961     if ($this->gosaMailMaxSize != '' && chkacl ($this->acl, "gosaMailQuota") == ""){
962       if (!is_numeric($this->gosaMailMaxSize)){
963         $message[]= _("Please specify a vaild mail size for mails to be rejected.");
964       } else {
965         $this->gosaMailMaxSize= (int) $this->gosaMailMaxSize;
966       }
967     }
969     /* Need gosaMailMaxSize if use_mailsize_limit is checked */
970     if (is_integer(strpos($this->gosaMailDeliveryMode, "reject")) && $this->gosaMailMaxSize == ""){
971       $message[]= _("You need to set the maximum mail size in order to reject anything.");
972     }
974     if(ord($this->imapacl['anyone'][0])==194){
975       $message[] = _("Please choose valid permission settings. Default permission can't be emtpy.");
976     }
978     if(empty($this->gosaMailServer)){
979       $message[] = _("Please select a valid mail server.");
980     }
982     return ($message);
983   }
985   /* Adapt from template, using 'dn' */
986   function adapt_from_template($dn)
987   {
988     plugin::adapt_from_template($dn);
990     foreach (array("gosaMailAlternateAddress", "gosaMailForwardingAddress") as $val){
991       $this->$val= array();
992       if (isset($this->attrs["$val"]["count"])){
993         for ($i= 0; $i<$this->attrs["$val"]["count"]; $i++){
994           $value= $this->attrs["$val"][$i];
995           foreach (array("sn", "givenName", "uid") as $repl){
996             if (preg_match("/%$repl/i", $value)){
997               $value= preg_replace ("/%$repl/i", $this->parent->$repl, $value);
998             }
999           }
1000           array_push($this->$val, $value);
1001         }
1002       }
1003     }
1004   }
1006   /* Add entry to forwarder list */
1007   function addForwarder($address)
1008   {
1009     $this->gosaMailForwardingAddress[]= $address;
1010     $this->gosaMailForwardingAddress= array_unique ($this->gosaMailForwardingAddress);
1012     sort ($this->gosaMailForwardingAddress);
1013     reset ($this->gosaMailForwardingAddress);
1014     $this->is_modified= TRUE;
1015   }
1017   /* Remove list of addresses from forwarder list */
1018   function delForwarder($addresses)
1019   {
1020     $this->gosaMailForwardingAddress= array_remove_entries ($addresses,
1021         $this->gosaMailForwardingAddress);
1022     $this->is_modified= TRUE;
1023   }
1027   function addAlternate($address)
1028   {
1029     $ldap= $this->config->get_ldap_link();
1031     $address= strtolower($address);
1033     /* Is this address already assigned in LDAP? */
1034     $ldap->cd ($this->config->current['BASE']);
1035     $ldap->search ("(&(objectClass=gosaMailAccount)(|(mail=$address)".
1036         "(gosaMailAlternateAddress=$address)))");
1038     if ($ldap->count() > 0){
1039       $attrs= $ldap->fetch ();
1040       return ($attrs["uid"][0]);
1041     }
1043     /* Add to list of alternates */
1044     if (!in_array($address, $this->gosaMailAlternateAddress)){
1045       $this->gosaMailAlternateAddress[]= $address;
1046     }
1048     sort ($this->gosaMailAlternateAddress);
1049     reset ($this->gosaMailAlternateAddress);
1050     $this->is_modified= TRUE;
1052     return ("");
1053   }
1056   function delAlternate($addresses)
1057   {
1058     $this->gosaMailAlternateAddress= array_remove_entries ($addresses,
1059         $this->gosaMailAlternateAddress);
1060     $this->is_modified= TRUE;
1061   }
1064   function make_name($attrs)
1065   {
1066     $name= "";
1067     if (isset($attrs['sn'][0])){
1068       $name= $attrs['sn'][0];
1069     }
1070     if (isset($attrs['givenName'][0])){
1071       if ($name != ""){
1072         $name.= ", ".$attrs['givenName'][0];
1073       } else {
1074         $name.= $attrs['givenName'][0];
1075       }
1076     }
1077     if ($name != ""){
1078       $name.= " ";
1079     }
1081     return ($name);
1082   }
1084   function getCopyDialog()
1085   {
1086     if(!$this->is_account) return("");
1088     $smarty = get_smarty();
1089     $smarty->assign("gosaMailAlternateAddress",$this->gosaMailAlternateAddress);
1090     $smarty->assign("gosaMailForwardingAddress",$this->gosaMailForwardingAddress);
1091     $smarty->assign("mail",$this->mail);
1092     $display= $smarty->fetch (get_template_path('paste_mail.tpl', TRUE));
1093     $ret = array();
1094     $ret['string'] = $display;
1095     $ret['status'] = "";
1096     return($ret);
1097   }
1099   function saveCopyDialog()
1100   {
1101     if(!$this->is_account) return;
1103     /* Perform ADD / REMOVE ... for mail alternate / mail forwarding addresses 
1104     */
1105     $this->execute();
1106     if(isset($_POST['mail'])){
1107       $this->mail = $_POST['mail'];
1108     }
1109   }
1111   function PrepareForCopyPaste($source)
1112   {
1113     plugin::PrepareForCopyPaste($source);
1115     /* Reset alternate mail addresses */
1116     $this->gosaMailAlternateAddress = array();
1117   }
1119   
1120   /* Remove given ACL for given member (uid,mail) ..
1121    */
1122   function removeUserAcl($index )
1123   {
1124     if(isset($this->imapacl[$index])){
1125       unset($this->imapacl[$index]);
1126     }
1127   }
1130 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1131 ?>