Code

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