Code

Updated mail group
[gosa.git] / gosa-plugins / mail / admin / groups / mail / class_groupMail.inc
1 <?php
3 class mailgroup extends plugin
4 {
5   /* Multiple edit */
6   var $gosaMailForwardingAddress_Some  = array();  // Used in multiple edit 
8   /* Default values */
9   var $mail                       = "";           // Default mail address 
10   var $gosaMailAlternateAddress   = array();  // Set default Alternate Mail Adresses to empty array
11   var $gosaMailForwardingAddress  = array();  // Forwarding also empty
12   var $gosaMailServer             = "";       // Selected mailserver 
13   var $gosaMailQuota              = "";       // Defined Quota 
14   var $gosaVacationMessage        = "";       // Vocation message 
15   var $gosaSpamSortLevel          = "";     
16   var $gosaSpamMailbox            = "";
17   var $gosaSharedFolderTarget     ;
18   var $gosaMailDeliveryMode       = "[L        ]";   // 
19   var $gosaMailMaxSize            = "";       // 
20   var $FolderType                 = array("CAT" => '', "SUB_CAT" => '');
22   var $quotaUsage                 = -1;        // -1 Means undefined
24   /* Internal */
25   var $AclTypes                   = array();
26   var $members                    = array();  // Group members
27   var $mailusers                  = array();  // Group member with mail account
28   var $folder_acls                = array();
29   var $MailMethod = NULL; 
30   var $forward_dialog             = FALSE;    
31   var $remove_folder_from_imap    = true;
32   var $view_logged                = FALSE;
33   var $mailDomainPart             = "";
35   /* attribute list for save action */
36   var $attributes= array( "mail",   "gosaMailServer", "gosaMailQuota", "gosaMailMaxSize",
37       "gosaMailAlternateAddress", "gosaMailForwardingAddress",
38       "gosaMailDeliveryMode", "gosaSpamSortLevel", "gosaSpamMailbox",
39       "acl","gosaSharedFolderTarget", "gosaVacationMessage");
41   var $objectclasses= array("gosaMailAccount");
42   var $multiple_support = FALSE; // Not tested yet
44   var $uid = "";
45   var $cn ="";
46   var $orig_cn = "";
48   function __construct (&$config, $dn= NULL, $ui= NULL)
49   {
50     plugin::plugin($config, $dn);
52     /* Get attributes from parent object
53      */
54     foreach(array("uid","cn") as $attr){
55       if(isset($this->parent->by_object['group']) && isset($this->parent->by_object['group']->$attr)){
56         $this->$attr = &$this->parent->by_object['group']->$attr;
57       }elseif(isset($this->attrs[$attr])){
58         $this->$attr = $this->attrs[$attr][0];
59       }
60     }
61     $this->orig_cn = $this->cn;
63     /* Intialize the used mailMethod
64      */
65     $tmp = new mailMethod($config,$this,"group");
66     $this->mailMethod           = $tmp->get_method();
67     $this->mailMethod->fixAttributesOnLoad();
68     $this->mailDomainParts      = $this->mailMethod->getMailDomains();
69     $this->AvailableFolderTypes = $this->mailMethod->getAvailableFolderTypes();
70     $this->MailBoxes = array();
72     /* Remember account status
73      */
74     $this->initially_was_account = $this->is_account;
76     /* Load folder_acls with defaults.
77       anyone -- The default acl, will be written to ldap.
78       member -- The ACL used for the members.
79      */ 
80     $this->folder_acls = $this->mailMethod->getDefaultACLs();
82     /* Load acls
83        The most used acl will be used as member acl, this
84         shortens the listed acls.        
85        This may be merged/overwritten by the mail methods.
86      */
87     $ldap = $this->config->get_ldap_link();
88     if(isset($this->attrs['acl'])){
89       for($i = 0; $i < $this->attrs['acl']['count'] ; $i++){
90         $str = trim($this->attrs['acl'][$i]);
92         /* Be carefull here, since kolab22 uses spaces in the acls (herbert read anon/post)
93          */
94         $name = trim(preg_replace("/^([^\s]*).*$/","\\1",$str));
95         $acl  = trim(preg_replace("/^[^\s]*+\s/","",$str));
96         if($name == "anyone") $name = "__anyone__";
97         $this->folder_acls[$name] = $acl;
98       }
99     }
101     /* Initialize configured values
102      */
103     if($this->is_account){
104       if($this->mailMethod->connect() && $this->mailMethod->account_exists()){
106         /* Read quota */
107         $this->gosaMailQuota = $this->mailMethod->getQuota($this->gosaMailQuota);
108         $this->quotaUsage = $this->mailMethod->getQuotaUsage($this->quotaUsage);
109         if($this->mailMethod->is_error()){
110           msg_dialog::display(_("Mail error"), sprintf(_("Cannot read quota settings: %s"),
111                 $this->mailMethod->get_error()), ERROR_DIALOG);
112         }
114         /* Read mailboxes */
115         $this->MailBoxes = $this->mailMethod->getMailboxList($this->MailBoxes);
116         if($this->mailMethod->is_error()){
117           msg_dialog::display(_("Mail error"), sprintf(_("Cannot get list of mailboxes: %s"),
118                 $this->mailMethod->get_error()), ERROR_DIALOG);
119         }
121         /* Receive folder types */
122         $this->FolderType = $this->mailMethod->getFolderType($this->FolderType);
123         if($this->mailMethod->is_error()){
124           msg_dialog::display(_("Mail error"), sprintf(_("Cannot receive folder types: %s"),
125                 $this->mailMethod->get_error()), ERROR_DIALOG);
126         }
128         /* Receive permissions */  
129         $this->folder_acls = $this->mailMethod->getFolderACLs($this->folder_acls);
130         if($this->mailMethod->is_error()){
131           msg_dialog::display(_("Mail error"), sprintf(_("Cannot receive folder permissions: %s"),
132                 $this->mailMethod->get_error()), ERROR_DIALOG);
133         }
135       }elseif(!$this->mailMethod->is_connected()){
136         msg_dialog::display(_("Mail error"), sprintf(_("Mail method cannot connect: %s"),
137               $this->mailMethod->get_error()), ERROR_DIALOG);
138       }elseif(!$this->mailMethod->account_exists()){
139         msg_dialog::display(_("Mail error"), sprintf(_("Mailbox '%s' doesn't exists on mail server: %s"),
140               $this->mailMethod->get_account_id(),$this->gosaMailServer), ERROR_DIALOG);
141       }
143       /* If the doamin part is selectable, we have to split the mail address
144        */
145       if(!(!$this->mailMethod->isModifyableMail() && $this->is_account)){
146         if($this->mailMethod->domainSelectionEnabled() || $this->mailMethod->mailEqualsCN()){
147           $this->mailDomainPart = preg_replace("/^[^@]*+@/","",$this->mail);
148           $this->mail = preg_replace("/@.*$/","\\1",$this->mail);
149           if(!in_array($this->mailDomainPart,$this->mailDomainParts)){
150             $this->mailDomainParts[] = $this->mailDomainPart;
151           }
152         }
153       }
155       /* Load attributes containing arrays */
156       foreach (array("gosaMailAlternateAddress", "gosaMailForwardingAddress") as $val){
157         $this->$val= array();
158         if (isset($this->attrs["$val"]["count"])){
159           for ($i= 0; $i<$this->attrs["$val"]["count"]; $i++){
160             array_push($this->$val, $this->attrs["$val"][$i]);
161           }
162         }
163       }
164     }
166     /* Disconnect mailMethod. Connect on demand later.
167      */
168     $this->mailMethod->disconnect();
169     $this->AclTypes = $this->mailMethod->getAclTypes();
171     /* Summarize most used ACLs as member acl 
172      */
173     if(count($this->folder_acls) > 2){
174       $acl_usage = array();
175       $most_acl = $this->folder_acls['__member__'];
176       $most_cnt = 0;
177       $member = $this->get_member();
178       foreach($this->folder_acls as $user => $acl){
179         if(preg_match("/^__/",$user)) continue;
180         if(!in_array($user,$member['mail'])) continue; 
181         if(!isset($acl_usage[$acl])) $acl_usage[$acl]=0;
182         $acl_usage[$acl] ++;
183         if($acl_usage[$acl] > $most_cnt){
184           $most_cnt = $acl_usage[$acl];
185           $most_acl = $acl;
186         }
187       }
188       $this->folder_acls['__member__'] = $most_acl;  
189       foreach($this->folder_acls as $name => $acl){
190         if(preg_match("/^__/",$name)) continue;
191         if($acl == $most_acl && in_array($name,$member['mail'])){
192           unset($this->folder_acls[$name]);
193         }
194       }
195     }
197     /* Get global filter config */
198     if (!session::is_set("gmailfilter")){
199       $ui= get_userinfo();
200       $base= get_base_from_people($ui->dn);
201       $gmailfilter= array( "depselect"       => $base,
202           "muser"            => "",
203           "regex"           => "*");
204       session::set("gmailfilter", $gmailfilter);
205     }
206   }
208  
209   /*! \brief  Returns all group members once with 'dn' and once with 'mail'.
210               This function is used to summarize ACLs by member acls.
211       @return Array   Containing all members, with mail and dn
212    */ 
213   function get_member()
214   {
215     $member = array('all' => array(), 'mail' => array());
216     $ldap = $this->config->get_ldap_link();
217     $ldap->cd($this->config->current['BASE']);
218     if(isset($this->parent->by_object['group'])){
219       foreach($this->parent->by_object['group']->memberUid as $uid){
220         $dn = $this->parent->by_object['group']->dnMapping[$uid];
221         $member['all'][$uid] = $uid;
222         if($ldap->object_match_filter($dn,"(&(objectClass=gosaMailAccount)(".$this->mailMethod->getUAttrib()."=*))")){
223           $ldap->cat($dn);
224           $attrs = $ldap->fetch();
225           $member['mail'][$uid] = $attrs[$this->mailMethod->getUAttrib()][0]; 
226         }
227       }
228     }else{
229       if(!isset($this->attrs['memberUid'])) return($member);
230       $uattrib = $this->mailMethod->getUAttrib();
231       $users = get_list("(&(objectClass=person)(objectClass=gosaAccount)(uid=*))",
232               "users",$this->config->current['BASE'],
233               array("uid","objectClass",$uattrib),GL_SUBSEARCH | GL_NO_ACL_CHECK);
234       foreach($users as $user){
235         $member['all'][$user['uid'][0]] = $user['dn'];
236         if(isset($user[$uattrib]) 
237             && in_array("gosaMailAccount",$user['objectClass']) 
238             && (in_array($user['uid'][0], $this->attrs['memberUid']))){
239           $member['mail'][$user['uid'][0]] = $user[$uattrib][0];
240         }
241       }
242     }
243     return($member);
244   }
247   function execute()
248   {
249     /* Call parent execute */
250     plugin::execute();
252     /* Log view */
253     if($this->is_account && !$this->view_logged){
254       $this->view_logged = TRUE;
255       new log("view","groups/".get_class($this),$this->dn);
256     }
258     /****************
259       Account status
260      ****************/
262     if(!$this->multiple_support_active){
264       if(isset($_POST['modify_state'])){
265         if($this->is_account && $this->acl_is_removeable() && $this->mailMethod->accountRemoveAble()){
266           $this->is_account= FALSE;
267         }elseif(!$this->is_account && $this->acl_is_createable() && $this->mailMethod->accountCreateable()){
268           $this->is_account= TRUE;
269         }
270       }
272       if ($this->is_account){
273         $reason = "";
274         if(!$this->mailMethod->accountRemoveable($reason)){
275           $display= $this->show_disable_header(msgPool::removeFeaturesButton(_("Mail")),$reason ,TRUE,TRUE);
276         }else{
277           $display= $this->show_disable_header(msgPool::removeFeaturesButton(_("Mail")),msgPool::
278               featuresEnabled(_("Mail")));
279         }
280       } else {
281         $reason = "";
282         if(!$this->mailMethod->accountCreateable($reason)){
283           $display= $this->show_disable_header(msgPool::addFeaturesButton(_("Mail")),$reason ,TRUE,TRUE);
284         }else{
285           $display= $this->show_disable_header(msgPool::addFeaturesButton(_("Mail")),msgPool::
286               featuresDisabled(_("Mail")));
288           /* Show checkbox that allows us to remove imap entry too*/
289           if($this->initially_was_account){
290             $c = "";
291             if($this->remove_folder_from_imap){
292               $c= " checked ";
293             }
294             $display .= "<h2>Shared folder delete options</h2>
295               <input class='center' type='checkbox' name='remove_folder_from_imap' value='1' ".$c."
296               title='"._("Remove shared folder from mail server database when entry gets removed in LDAP")."'>";
297             $display .= _("Remove the shared folder and all its contents after saving this account");
298           }
299         }
300         return ($display);
301       }
302     }
304     
305     /****************
306       Preset mail attribute
307      ****************/
308     if(empty($this->mail) && $this->mailMethod->mailEqualsCN() && !$this->initially_was_account){
309       if($this->mailMethod->domainSelectionEnabled()){
310         $this->mail = &$this->parent->by_object['group']->cn;
311       }
312     }
315     /****************
316       Forward addresses
317      ****************/
318     if (isset($_POST['add_local_forwarder'])){
319       $this->forward_dialog= TRUE;
320       $this->dialog= TRUE;
321     }
322     if (isset($_POST['add_locals_cancel'])){
323       $this->forward_dialog= FALSE;
324       $this->dialog= FALSE;
325     }
326     if (isset($_POST['add_locals_finish'])){
327       if (isset($_POST['local_list'])){
328         if($this->acl_is_writeable("gosaMailForwardingAddress")){
329           foreach ($_POST['local_list'] as $val){
330             if (!in_array ($val, $this->gosaMailAlternateAddress) &&
331                 $val != $this->mail){
332               $this->addForwarder($val);
333               $this->is_modified= TRUE;
334             }
335           }
336         }
337         $this->forward_dialog= FALSE;
338         $this->dialog= FALSE;
339       } else {
340         msg_dialog::display(_("Error"), _("Please select an entry!"), ERROR_DIALOG);
341       }
342     }
344     if (isset($_POST['add_forwarder'])){
345       if ($_POST['forward_address'] != ""){
346         $address= $_POST['forward_address'];
347         $valid= FALSE;
348         if (!tests::is_email($address)){
349           if (!tests::is_email($address, TRUE)){
350             if ($this->is_template){
351               $valid= TRUE;
352             } else {
353               msg_dialog::display(_("Error"), msgPool::invalid(_("Mail address"),
354                     "","","your-address@your-domain.com"),ERROR_DIALOG);
355             }
356           }
357         } elseif ($address == $this->mail
358             || in_array($address, $this->gosaMailAlternateAddress)) {
359           msg_dialog::display(_("Error"),_("Cannot add primary address to the list of forwarders!") , ERROR_DIALOG);
360         } else {
361           $valid= TRUE;
362         }
363         if ($valid){
364           if($this->acl_is_writeable("gosaMailForwardingAddress")){
365             $this->addForwarder ($address);
366             $this->is_modified= TRUE;
367           }
368         }
369       }
370     }
371     if (isset($_POST['delete_forwarder'])){
372       $this->delForwarder ($_POST['forwarder_list']);
373     }
374     if ($this->forward_dialog){
375       return($this->display_forward_dialog());
376     } 
378  
379     /****************
380       Alternate addresses
381      ****************/
383     if (isset($_POST['add_alternate'])){
384       $valid= FALSE;
385       if (!tests::is_email($_POST['alternate_address'])){
386         if ($this->is_template){
387           if (!(tests::is_email($_POST['alternate_address'], TRUE))){
388             msg_dialog::display(_("Error"),msgPool::invalid(_("Mail address"),
389                   "","","your-domain@your-domain.com"),     ERROR_DIALOG);
390           } else {
391             $valid= TRUE;
392           }
393         } else {
394           msg_dialog::display(_("Error"),msgPool::invalid(_("Mail address"),
395                 "","","your-domain@your-domain.com"),       ERROR_DIALOG);
396         }
397       } else {
398         $valid= TRUE;
399       }
400       if ($valid && ($user= $this->addAlternate ($_POST['alternate_address'])) != ""){
401         $ui= get_userinfo();
402         if ($user != $ui->username){
403           msg_dialog::display(_("Error"), msgPool::duplicated(_("Mail address"))."&nbsp;".
404               sprintf(_("Address is already in use by user '%s'."), $user), ERROR_DIALOG);
405         }
406       }
407     }
408     if (isset($_POST['delete_alternate']) && isset($_POST['alternates_list'])){
409       $this->delAlternate ($_POST['alternates_list']);
410     }
413     /****************
414       SMARTY- Assign smarty variables
415      ****************/
417     /* Load templating engine */
418     $smarty= get_smarty();
419     $smarty->assign("initially_was_account", $this->initially_was_account);
420     $smarty->assign("isModifyableMail", $this->mailMethod->isModifyableMail());
421     $smarty->assign("isModifyableServer", $this->mailMethod->isModifyableServer());
422     $smarty->assign("mailEqualsCN", $this->mailMethod->mailEqualsCN());
423     $smarty->assign("folder_acls" , $this->postable_acls());
424     $smarty->assign("AclTypes" ,    $this->AclTypes);
425   
426     $smarty->assign("quotaEnabled", $this->mailMethod->quotaEnabled());
427     if($this->mailMethod->quotaEnabled()){
428       $smarty->assign("gosaMailQuota",$this->gosaMailQuota);
429       $smarty->assign("quotaUsage",   mailMethod::quota_to_image($this->quotaUsage,$this->gosaMailQuota)); 
430     }
432     $smarty->assign("MailDomains", $this->mailDomainParts);
433     $smarty->assign("MailDomain" , $this->mailDomainPart);
434     $smarty->assign("MailServers", $this->mailMethod->getMailServers());
435     $smarty->assign("allowSieveManagement", $this->mailMethod->allowSieveManagement());
437     $smarty->assign("domainSelectionEnabled", $this->mailMethod->domainSelectionEnabled());
438     $smarty->assign("folderTypesEnabled",$this->mailMethod->folderTypesEnabled());
439     $smarty->assign("AvailableFolderTypes", $this->AvailableFolderTypes);
440     $smarty->assign("FolderType", $this->FolderType);
441  
442     if (is_numeric($this->gosaMailQuota) && $this->gosaMailQuota != 0){
443       if($this->acl_is_readable("gosaMailQuota")){
444         $smarty->assign("quotausage", progressbar(round(($this->quotaUsage * 100)/ $this->gosaMailQuota),100,15,true));
445         $smarty->assign("quotadefined", "true");
446       }else{
447         $smarty->assign("quotadefined", "true");
448         $smarty->assign("quotausage", "-");
449       }
450     } else {
451       $smarty->assign("quotadefined", "false");
452     }
454     /* Assign acls */
455     $tmp = $this->plInfo();
456     foreach($tmp['plProvidedAcls'] as $name => $translation) {
457       $smarty->assign($name."ACL",$this->getacl($name));
458     }
459     foreach($this->attributes as $name){
460       $smarty->assign($name,$this->$name);
461     }
465     $smarty->assign("mailServers", $this->mailMethod->getMailServers());
466     if (preg_match("/I/", $this->gosaMailDeliveryMode)) {
467       $smarty->assign("only_local", "checked");
468     }else{
469       $smarty->assign("only_local", "");
470     }
473     /******
474       Multi edit support 
475      ******/
476     foreach($this->attributes as $attr){
477       if(in_array($attr,$this->multi_boxes)){
478         $smarty->assign("use_".$attr,TRUE);
479       }else{
480         $smarty->assign("use_".$attr,FALSE);
481       }
482     }
484     /* Multiple support handling */
485     foreach(array("kolabFolderType") as $attr){
486       if(in_array($attr,$this->multi_boxes)){
487         $smarty->assign("use_".$attr,TRUE);
488       }else{
489         $smarty->assign("use_".$attr,FALSE);
490       }
491     }
493     $smarty->assign("Forward_all",$this->gosaMailForwardingAddress);
494     $smarty->assign("Forward_some",$this->gosaMailForwardingAddress_Some);
495     $smarty->assign("multiple_support",$this->multiple_support_active);
497     $display.= $smarty->fetch (get_template_path('mail.tpl', TRUE, dirname(__FILE__)));
498     return ($display);
499   }
502   /* remove object from parent */
503   function remove_from_parent()
504   {
505     if(!$this->initially_was_account){
506       return;
507     }
508  
509     /* If domain part was selectable, contruct mail address */
510     if($this->mailMethod->domainSelectionEnabled() || $this->mailMethod->mailEqualsCN()){
511       $this->mail = $this->mail."@".$this->mailDomainPart;
512     }
514     /* Remove GOsa attributes */
515     plugin::remove_from_parent();
517     /* Zero arrays */
518     $this->attrs['gosaMailAlternateAddress'] = array();
519     $this->attrs['gosaMailForwardingAddress']= array();
520     $this->attrs['gosaSharedFolderTarget']= array();
522     $this->mailMethod->fixAttributesOnRemove();
523     $this->cleanup();
524     $ldap = $this->config->get_ldap_link();
525     $ldap->cd($this->dn);
526     $ldap->modify ($this->attrs); 
527     if (!$ldap->success()){
528       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_MOD, get_class()));
529     }
531     new log("remove","groups/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
534     /* Let the mailMethod remove this mailbox, e.g. from imap and
535        update shared folder membership, ACL may need to be updated.
536      */
537     if (!$this->is_template && $this->remove_folder_from_imap){
539       if(!$this->mailMethod->connect()){
540         msg_dialog::display(_("Mail error"), sprintf(_("Mail method cannot connect: %s"),
541               $this->mailMethod->get_error()), ERROR_DIALOG);
542       }else{
543         if(!$this->mailMethod->deleteMailbox()){
544           msg_dialog::display(_("Mail error"), sprintf(_("Cannot remove mailbox: %s"),
545                 $this->mailMethod->get_error()), ERROR_DIALOG);
546         }
547         if(!$this->mailMethod->updateSharedFolder()){
548           msg_dialog::display(_("Mail error"), sprintf(_("Cannot update shared folder permissions: %s"),
549                 $this->mailMethod->get_error()), ERROR_DIALOG);
550         }
551       }
552     }
553     $this->mailMethod->disconnect();
556     /* Optionally execute a command after we're done */
557     $this->handle_post_events("remove");
558   }
561   /* Save data to object */
562   function save_object()
563   {
564     /* Check if user wants to remove the shared folder from imap too 
565      */
566     if($this->initially_was_account && !$this->is_account){
567       if(isset($_POST['remove_folder_from_imap'])){
568         $this->remove_folder_from_imap = true;
569       }else{
570         $this->remove_folder_from_imap = false;
571       }
572     }
573     if (isset($_POST['mailedit'])){
575       $mail = $this->mail;
576       $server = $this->gosaMailServer;
577       plugin::save_object();
579       if(!$this->mailMethod->isModifyableServer() && $this->initially_was_account){
580         $this->gosaMailServer = $server;
581       }
582       if(!$this->mailMethod->isModifyableMail() && $this->initially_was_account){
583         $this->mail = $mail;
584       }else{
586         if($this->mailMethod->mailEqualsCN()){
587           $this->mail = &$this->parent->by_object['group']->cn;
588           if(isset($_POST['MailDomain'])){
589             $this->mailDomainPart = get_post('MailDomain');
590           }
591         }
593       /* Get posted mail domain part, if necessary
594        */
595       if($this->mailMethod->domainSelectionEnabled() && isset($_POST['MailDomain'])){
596         if(in_array(get_post('MailDomain'), $this->mailDomainParts)){
597           $this->mailDomainPart = get_post('MailDomain');
598         }
599       }
600     }
602       /* Get folder type 
603        */
604       if($this->mailMethod->folderTypesEnabled()){
605         if(isset($_POST['FolderTypeCAT'])){
606         $this->FolderType['CAT']     = get_post('FolderTypeCAT');
607         }
608         if(isset($_POST['FolderTypeSUB_CAT'])){
609           $this->FolderType['SUB_CAT'] = get_post('FolderTypeSUB_CAT');
610         }
611       }
613       /* Handle posted ACL changes. 
614          Add/del member acls.
615        */
616       if(isset($_POST['mail_acls_posted'])){
617         $new_acls = array();
618         foreach(array("__anyone__","__member__") as $attr){
619           $pname = base64_encode($attr);
620           if(get_post('acl_value_'.$pname)){ 
621             $new_acls[$attr] = get_post('acl_value_'.$pname);
622           }else{
623             $new_acls[$attr] = $this->folder_acls[$attr];
624           }
625         }
627         foreach($this->folder_acls as $user => $acl){
628           $pname = base64_encode($user);
629           if($user == "__member__" || $user == "__anyone__") continue;
630           if(isset($_POST['remove_acl_user_'.$pname])){
631           }elseif(isset($_POST['acl_user_'.$pname])){
632             if($user != get_post('acl_user_'.$pname)){
633               $new_acls[get_post('acl_user_'.$pname)] = get_post('acl_value_'.$pname);
634             }else{
635               $new_acls[$user] = get_post('acl_value_'.$pname);
636             }
637           }else{
638             $new_acls[$user] = $acl;
639           }
640         }
641         if(isset($_POST['add_acl_user'])){
642           $new_acls[_('New')] = $this->folder_acls['__anyone__'];
643         }
644         $this->folder_acls = $new_acls;
645       }
647       /* Handle GOsa mail delivery flags.
648        */
650     /* Assemble mail delivery mode
651        The mode field in ldap consists of values between braces, this must
652        be called when 'mail' is set, because checkboxes may not be set when
653        we're in some other dialog.
655        Example for gosaMailDeliveryMode [LR        ]
656        L - Local delivery
657        R - Reject when exceeding mailsize limit
658        S - Use spam filter
659        V - Use vacation message
660        C - Use custom sieve script
661        I - Only insider delivery */
662       $tmp= preg_replace("/[^a-z]/i","",$this->gosaMailDeliveryMode);
663       if($this->acl_is_writeable("gosaMailDeliveryModeL")){
664         if(!preg_match("/L/",$tmp) && !isset($_POST['drop_own_mails'])){
665           $tmp.="L";
666         }elseif(preg_match("/L/",$tmp) && isset($_POST['drop_own_mails'])){
667           $tmp = preg_replace("/L/","",$tmp);
668         }
669       }
671       $opts = array(
672           "R"   => "use_mailsize_limit",
673           "S"   => "use_spam_filter",
674           "V"   => "use_vacation",
675           "C"   => "own_script",
676           "I"   => "only_local");
678       foreach($opts as $flag => $post){
679         if($this->acl_is_writeable("gosaMailDeliveryMode".$flag)){
680           if(!preg_match("/".$flag."/",$tmp) && isset($_POST[$post])){
681             $tmp.= $flag;
682           }elseif(preg_match("/".$flag."/",$tmp) && !isset($_POST[$post])){
683             $tmp = preg_replace("/".$flag."/","",$tmp);
684           }
685         }
686       }
688       $tmp= "[$tmp]";
689       if ($this->gosaMailDeliveryMode != $tmp){
690         $this->is_modified= TRUE;
691       }
692       $this->gosaMailDeliveryMode= $tmp;
693     }
694   }
697   /* Save data to LDAP, depending on is_account we save or delete */
698   function save()
699   {
700     $ldap= $this->config->get_ldap_link();
702     /* If domain part was selectable, contruct mail address */
703     if(!(!$this->mailMethod->isModifyableMail() && $this->initially_was_account)){
705       if($this->mailMethod->domainSelectionEnabled() || $this->mailMethod->mailEqualsCN()){
706         $this->mail = $this->mail."@".$this->mailDomainPart;
707       }
708     }
710     /* Enforce lowercase mail address and trim whitespaces
711      */
712     $this->mail = trim(strtolower($this->mail));
713     
715     /* Create acls 
716      */
717     $this->acl = array("anyone ".$this->folder_acls['__anyone__']);
718     $member = $this->get_member();
719     $new_folder_acls = array("anyone" => $this->folder_acls['__anyone__']);
720     foreach($member['mail'] as $uid => $mail){
722       /* Do not save overridden acls */
723       if(isset($this->folder_acls[$mail])){
724         continue;
725       }
727       $this->acl[] = $mail." ".$this->folder_acls['__member__'];
728       $new_folder_acls[$mail]=$this->folder_acls['__member__'];
729     }
730     foreach($this->folder_acls as $user => $acls){
731       if(preg_match("/^__/",$user)) continue;
732       $this->acl[] = $user." ".$acls;
733       $new_folder_acls[$user]=$acls;
734     }
735     $this->folder_acls = $new_folder_acls;
736     $this->acl = array_unique($this->acl);
737      
738     /* Call parents save to prepare $this->attrs */
739     plugin::save();
741     /* Save arrays */
742     $this->attrs['gosaMailAlternateAddress'] = $this->gosaMailAlternateAddress;
743     $this->attrs['gosaMailForwardingAddress']= $this->gosaMailForwardingAddress;
745     /* Map method attributes */
746     $this->mailMethod->fixAttributesOnStore();
748     /* Save data to LDAP */
749     $ldap->cd($this->dn);
750     $this->cleanup();
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     }
755     
756     if($this->initially_was_account){
757       new log("modify","groups/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
758     }else{
759       new log("create","groups/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());  
760     }
761     
762     /* Do imap/sieve actions,
763      */
764     $this->mailMethod->connect();
765     if(!$this->mailMethod->is_connected()){
766       msg_dialog::display(_("Mail error"), sprintf(_("Mail method cannot connect: %s"),
767             $this->mailMethod->get_error()), ERROR_DIALOG);
768     }else{
769       if(!$this->mailMethod->updateMailbox()){
770         msg_dialog::display(_("Mail error"), sprintf(_("Cannot update mailbox: %s"),
771               $this->mailMethod->get_error()), ERROR_DIALOG);
772       }
773       if(!$this->mailMethod->setQuota($this->gosaMailQuota)){
774         msg_dialog::display(_("Mail error"), sprintf(_("Cannot write quota settings: %s"),
775               $this->mailMethod->get_error()), ERROR_DIALOG);
776       }
777       /* Save Folder Types, if available 
778        */
779       if($this->mailMethod->folderTypesEnabled()){
780         $this->mailMethod->setFolderType($this->FolderType);
781       }
782       if(!$this->mailMethod->setFolderACLs($this->folder_acls)){
783         msg_dialog::display(_("Mail error"), sprintf(_("Cannot update shared folder permissions: %s"),
784               $this->mailMethod->get_error()), ERROR_DIALOG);
785       }
786     }
787     $this->mailMethod->disconnect();
789     /* Optionally execute a command after we're done */
790     if ($this->initially_was_account == $this->is_account){
791       if ($this->is_modified){
792         $this->handle_post_events("modify");
793       }
794     } else {
795       $this->handle_post_events("add");
796     }
797   }
801   /* Check formular input */
802   function check()
803   {
804     if(!$this->is_account) return array();
805     $ldap= $this->config->get_ldap_link();
808     /* Call common method to give check the hook */
809     $message= plugin::check();
811     /* Ensure that this group isn't renamed if the mailMethod enforces cn mailAttributes 
812      */
813     if($this->mailMethod->mailEqualsCN() && $this->initially_was_account){
814       if($this->cn != $this->orig_cn){
815         $message[] = sprintf(_("The groups 'cn' has changed!  The cn attribute can't be changed due to the fact that this mail method '%s' relies on it.")
816             ,get_class($this->mailMethod));
817       }
818     }
820     if(empty($this->gosaMailServer)){
821       $message[]= msgPool::noserver(_("Mail"));
822     }
824     /* Mail address checks */
825     if(!(!$this->mailMethod->isModifyableMail() && $this->initially_was_account)){
826       $mail = $this->mail;
827       if($this->mailMethod->domainSelectionEnabled() || $this->mailMethod->mailEqualsCN()){
828         $mail.= "@".$this->mailDomainPart;
829       }
830       if (empty($mail)){
831         $message[]= msgPool::required(_("Primary address"));
832       }elseif (!tests::is_email($mail)){
833         $message[]= msgPool::invalid(_("Mail address"),"","","your-address@your-domain.com");
834       }
835     }
836     
837     /* Check quota */
838     if ($this->gosaMailQuota != '' && $this->acl_is_writeable("gosaMailQuota")){
839       if (!is_numeric($this->gosaMailQuota)) {
840         $message[]= msgPool::invalid(_("Quota size"),$this->gosaMailQuota,"/[0-9]/");
841       } else {
842         $this->gosaMailQuota= (int) $this->gosaMailQuota;
843       }
844     }
846     /* Check rejectsize for integer */
847     if ($this->gosaMailMaxSize != '' && $this->acl_is_writeable("gosaMailQuota")){
848       if (!is_numeric($this->gosaMailMaxSize)){
849         $message[]= msgPool::invalid(_("Mail max size"));
850       } else {
851         $this->gosaMailMaxSize= (int) $this->gosaMailMaxSize;
852       }
853     }
855     /* Need gosaMailMaxSize if use_mailsize_limit is checked */
856     if (is_integer(strpos($this->gosaMailDeliveryMode, "reject")) && $this->gosaMailMaxSize == ""){
857       $message[]= _("You need to set the maximum mail size in order to reject anything.");
858     }
860     if(empty($this->gosaMailServer)){
861       $message[] = msgPool::required(_("Mail server"));
862     }
864     return ($message);
865   }
867   /* Adapt from template, using 'dn' */
868   function adapt_from_template($dn, $skip= array())
869   {
870     plugin::adapt_from_template($dn, $skip);
872     foreach (array("gosaMailAlternateAddress", "gosaMailForwardingAddress") as $val){
873  
874       if (in_array($val, $skip)){
875         continue;
876       }
878       $this->$val= array();
879       if (isset($this->attrs["$val"]["count"])){
880         for ($i= 0; $i<$this->attrs["$val"]["count"]; $i++){
881           $value= $this->attrs["$val"][$i];
882           foreach (array("sn", "givenName", "uid") as $repl){
883             if (preg_match("/%$repl/i", $value)){
884               $value= preg_replace ("/%$repl/i", $this->parent->$repl, $value);
885             }
886           }
887           array_push($this->$val, $value);
888         }
889       }
890     }
891   }
895   function make_name($attrs)
896   {
897     $name= "";
898     if (isset($attrs['sn'][0])){
899       $name= $attrs['sn'][0];
900     }
901     if (isset($attrs['givenName'][0])){
902       if ($name != ""){
903         $name.= ", ".$attrs['givenName'][0];
904       } else {
905         $name.= $attrs['givenName'][0];
906       }
907     }
908     if ($name != ""){
909       $name.= " ";
910     }
912     return ($name);
913   }
915   function getCopyDialog()
916   {
917     if(!$this->is_account) return("");
919     $smarty = get_smarty();
920     $smarty->assign("gosaMailAlternateAddress",$this->gosaMailAlternateAddress);
921     $smarty->assign("gosaMailForwardingAddress",$this->gosaMailForwardingAddress);
922     $smarty->assign("mail",$this->mail);
923     $display= $smarty->fetch (get_template_path('paste_mail.tpl', TRUE, dirname(__FILE__)));
924     $ret = array();
925     $ret['string'] = $display;
926     $ret['status'] = "";
927     return($ret);
928   }
930   function saveCopyDialog()
931   {
932     if(!$this->is_account) return;
934     /* Perform ADD / REMOVE ... for mail alternate / mail forwarding addresses 
935     */
936     $this->execute();
937     if(isset($_POST['mail'])){
938       $this->mail = $_POST['mail'];
939     }
940   }
943   function PrepareForCopyPaste($source)
944   {
945     plugin::PrepareForCopyPaste($source);
946  
947     /* Reset alternate mail addresses */
948     $this->gosaMailAlternateAddress = array();
949   }
952   /* Return plugin informations for acl handling  */
953   static function plInfo()
954   {
955     return (array(
956           "plShortName"   => _("Mail"),
957           "plDescription" => _("Group mail"),
958           "plSelfModify"  => FALSE,
959           "plDepends"     => array(),
960           "plPriority"    => 10,
961           "plSection"     => array("administration"),
962           "plCategory"    => array("groups"), 
963           "plProvidedAcls"=> array(
964             "mail"                      => _("Mail address"),
965             "gosaMailQuota"             => _("Quota size"),
966             "gosaMailServer"            => _("Mail server"),
967             "kolabFolderType"           => _("Folder type")." ("._("Kolab").")",
968             "gosaMailAlternateAddress"  => _("Alternate addresses"),
969             "gosaMailForwardingAddress" => _("Forwarding addresses"),
970             "gosaMailDeliveryModeI"     => _("Only local"),
971             "acl"                       => _("Permissions"))
972           ));
973   }
975   
976   /* Remove given ACL for given member (uid,mail) ..
977    */
978   function removeUserAcl($index )
979   {
980     if(isset($this->imapacl[$index])){
981       unset($this->imapacl[$index]);
982     }
983   }
985   function multiple_execute()
986   {
987     return($this->execute());
988   }
991   function init_multiple_support($attrs,$all)
992   {
993     plugin::init_multiple_support($attrs,$all);
995     $this->gosaMailForwardingAddress = array();
996     if(isset($attrs['gosaMailForwardingAddress'])){
997       for($i = 0 ; $i < $attrs['gosaMailForwardingAddress']['count'] ; $i++){
998         $this->gosaMailForwardingAddress[] = $attrs['gosaMailForwardingAddress'][$i];
999       }
1000     }
1002     $this->gosaMailForwardingAddress_Some = array();
1003     if(isset($all['gosaMailForwardingAddress'])){
1004       for($i = 0 ; $i < $all['gosaMailForwardingAddress']['count'] ; $i++){
1005         if(!in_array($all['gosaMailForwardingAddress'][$i],$this->gosaMailForwardingAddress)){
1006           $this->gosaMailForwardingAddress_Some[] = $all['gosaMailForwardingAddress'][$i];
1007         }
1008       }
1009     }
1010   }
1012   function multiple_save_object()
1013   {
1014     if(isset($_POST['multiple_mail_group_posted'])){
1015       plugin::multiple_save_object();
1016       
1017       foreach(array("kolabFolderType") as $attr){
1018         if(isset($_POST['use_'.$attr])){
1019           $this->multi_boxes[] = $attr;
1020         }
1021       }
1023       /* Add special kolab attributes */
1024       if(preg_match("/olab/i",$this->config->get_cfg_value("mailmethod"))){
1025         if(isset($_POST['kolabFolderTypeType']) && $this->acl_is_writeable("kolabFolderType")){
1026           $this->kolabFolderTypeType = get_post("kolabFolderTypeType");
1027           $this->kolabFolderTypeSubType = get_post("kolabFolderTypeSubType");
1028         }
1029       }
1031       /* Collect data and re-assign it to the imapacl array */
1032       if ($this->acl_is_writeable("acl")){
1033         $this->imapacl= array();
1034         $this->imapacl['%members%']= $_POST['member_permissions'];
1035         $this->imapacl['anyone']= $_POST['default_permissions'];
1036         foreach ($this->indexed_user as $nr => $user){
1037           if (!isset($_POST["user_$nr"])){
1038             continue;
1039           }
1040           if ($_POST["user_$nr"] != $user ||
1041               $_POST["perm_$nr"] != $this->indexed_acl[$nr]){
1042             $this->is_modified= TRUE;
1043           }
1044           $this->imapacl[$_POST["user_$nr"]]= $_POST["perm_$nr"];
1045         }
1046       }
1047     }
1048   }
1049   
1050   
1051   /* Return selected values for multiple edit */
1052   function get_multi_edit_values()
1053   {
1054     $ret = plugin::get_multi_edit_values();
1055     $ret['Forward_some'] = $this->gosaMailForwardingAddress_Some;    
1056     $ret['Forward_all'] = $this->gosaMailForwardingAddress;    
1057     if(in_array('kolabFolderType',$this->multi_boxes)){
1058       $ret['kolabFolderTypeType'] = $this->kolabFolderTypeType;
1059       $ret['kolabFolderTypeSubType'] = $this->kolabFolderTypeSubType;
1060     }
1061     if(in_array("acl",$this->multi_boxes)){
1062       $ret['imapacl'] = $this->imapacl;
1063     }
1064     return($ret);
1065   }
1067   function set_multi_edit_values($attrs)
1068   {
1069     $forward = array();
1070     foreach($attrs['Forward_some'] as $addr){
1071       if(in_array($addr,$this->gosaMailForwardingAddress)){
1072         $forward[] = $addr;
1073       }
1074     }
1075     foreach($attrs['Forward_all'] as $addr){
1076       $forward[] = $addr;
1077     }
1078     plugin::set_multi_edit_values($attrs);
1079     $this->gosaMailForwardingAddress = $forward;
1080   }
1083   /*! \brief  Displays a dialog that allows mail address selection.
1084    */
1085   function display_forward_dialog()
1086   {
1087     restore_error_handler();
1089     $smarty = get_smarty();
1090     $ldap= $this->config->get_ldap_link();
1092     /* Save data */
1093     $mailfilter= session::get("mailfilter");
1094     foreach( array("depselect", "muser", "regex") as $type){
1095       if (isset($_POST[$type])){
1096         $mailfilter[$type]= $_POST[$type];
1097       }
1098     }
1099     if (isset($_GET['search'])){
1100       $s= mb_substr($_GET['search'], 0, 1, "UTF8")."*";
1101       if ($s == "**"){
1102         $s= "*";
1103       }
1104       $mailfilter['regex']= $s;
1105     }
1106     session::set("mailfilter", $mailfilter);
1108     /* Get actual list */
1109     $mailusers= array ();
1110     if ($mailfilter['regex'] != '*' && $mailfilter['regex'] != ""){
1111       $regex= $mailfilter['regex'];
1112       $filter= "(|(mail=$regex)(gosaMailAlternateAddress=$regex))";
1113     } else {
1114       $filter= "";
1115     }
1116     if ($mailfilter['muser'] != ""){
1117       $user= $mailfilter['muser'];
1118       $filter= "$filter(|(uid=$user)(cn=$user)(givenName=$user)(sn=$user))";
1119     }
1121     /* Add already present people to the filter */
1122     $exclude= "";
1123     foreach ($this->gosaMailForwardingAddress as $mail){
1124       $exclude.= "(mail=$mail)";
1125     }
1126     if ($exclude != ""){
1127       $filter.= "(!(|$exclude))";
1128     }
1129     $res= get_list("(&(objectClass=gosaMailAccount)$filter)", "users", $mailfilter['depselect'],
1130         array("sn", "mail", "givenName"), GL_SIZELIMIT | GL_SUBSEARCH);
1131     $ldap->cd($mailfilter['depselect']);
1132     $ldap->search ("(&(objectClass=gosaMailAccount)$filter)", array("sn", "mail", "givenName"));
1133     while ($attrs= $ldap->fetch()){
1134       if(preg_match('/%/', $attrs['mail'][0])){
1135         continue;
1136       }
1137       $name= $this->make_name($attrs);
1138       $mailusers[$attrs['mail'][0]]= $name."&lt;".
1139         $attrs['mail'][0]."&gt;";
1140     }
1141     natcasesort ($mailusers);
1142     reset ($mailusers);
1144     /* Show dialog */
1145     $smarty->assign("search_image", get_template_path('images/lists/search.png'));
1146     $smarty->assign("usearch_image", get_template_path('images/lists/search-user.png'));
1147     $smarty->assign("tree_image", get_template_path('images/lists/search-subtree.png'));
1148     $smarty->assign("infoimage", get_template_path('images/info.png'));
1149     $smarty->assign("launchimage", get_template_path('images/lists/action.png'));
1150     $smarty->assign("mailusers", $mailusers);
1151     if (isset($_POST['depselect'])){
1152       $smarty->assign("depselect", $_POST['depselect']);
1153     }
1154     $smarty->assign("deplist", $this->config->idepartments);
1155     $smarty->assign("apply", apply_filter());
1156     $smarty->assign("alphabet", generate_alphabet());
1157     $smarty->assign("hint", print_sizelimit_warning());
1158     foreach( array("depselect", "muser", "regex") as $type){
1159       $smarty->assign("$type", $mailfilter[$type]);
1160     }
1161     $smarty->assign("hint", print_sizelimit_warning());
1162     $display= $smarty->fetch (get_template_path('mail_locals.tpl', TRUE, dirname(__FILE__)));
1163     return ($display);
1164   }
1167   /*! \brief  Add given mail address to the list of forwarders.
1168    */
1169   function addForwarder($address)
1170   {
1171     if(empty($address)) continue;
1172     $this->gosaMailForwardingAddress[]= $address;
1173     $this->gosaMailForwardingAddress= array_unique($this->gosaMailForwardingAddress);
1175     /* Update multiple edit values too */
1176     if($this->multiple_support_active){
1177       $this->gosaMailForwardingAddress_Some= 
1178         array_remove_entries (array($address),$this->gosaMailForwardingAddress_Some);
1179     }
1181     sort ($this->gosaMailForwardingAddress);
1182     reset ($this->gosaMailForwardingAddress);
1183     $this->is_modified= TRUE;
1184   }
1187   /*! \brief  Removes the given mail address from the forwarders 
1188    */
1189   function delForwarder($addresses)
1190   {
1191     if(empty($address)) continue;
1192     $this->gosaMailForwardingAddress= array_remove_entries ($addresses,
1193         $this->gosaMailForwardingAddress);
1195     /* Update multiple edit values too */
1196     if($this->multiple_support_active){
1197       $this->gosaMailForwardingAddress_Some = array_remove_entries ($addresses,
1198           $this->gosaMailForwardingAddress_Some);
1199     }
1200     $this->is_modified= TRUE;
1201   }
1204   /*! \brief  Add given mail address to the list of alternate adresses ,
1205     .          check if this mal address is used, skip adding in this case
1206    */
1207   function addAlternate($address)
1208   {
1209     if(empty($address)) continue;
1210     $ldap= $this->config->get_ldap_link();
1212     $address= strtolower($address);
1214     /* Is this address already assigned in LDAP? */
1215     $ldap->cd ($this->config->current['BASE']);
1216     $ldap->search ("(&(objectClass=gosaMailAccount)(|(mail=$address)".
1217         "(gosaMailAlternateAddress=$address)))");
1219     if ($ldap->count() > 0){
1220       $attrs= $ldap->fetch ();
1221       return ($attrs["uid"][0]);
1222     }
1224     /* Add to list of alternates */
1225     if (!in_array($address, $this->gosaMailAlternateAddress)){
1226       $this->gosaMailAlternateAddress[]= $address;
1227     }
1229     sort ($this->gosaMailAlternateAddress);
1230     reset ($this->gosaMailAlternateAddress);
1231     $this->is_modified= TRUE;
1233     return ("");
1234   }
1237   /*! \brief  Removes the given mail address from the alternate addresses  
1238    */
1239   function delAlternate($addresses)
1240   {
1241     if(empty($address)) continue;
1242     $this->gosaMailAlternateAddress= array_remove_entries ($addresses,
1243         $this->gosaMailAlternateAddress);
1244     $this->is_modified= TRUE;
1245   }
1248   function postable_acls()
1249   {
1250     $ret = array();
1251     foreach($this->folder_acls as $name => $acl){
1252       $ret[$name] = array("name" => $name,"acl" => $acl,"post_name" => base64_encode($name));
1253     }
1254     return($ret);
1255   }
1257   
1258   function allow_remove()
1259   {
1260     $resason = "";
1261     if(!$this->mailMethod->allow_remove($reason)){
1262       return($reason);
1263     }
1264     return("");
1265   }
1268   // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1269 ?>