Code

Added some logging
[gosa.git] / plugins / admin / groups / class_groupMail.inc
1 <?php
3 class mailgroup extends plugin
4 {
5   /* CLI vars */
6   var $cli_summary        = "Manage mail groups/shared folders";
7   var $cli_description    = "Some longer text\nfor help";
8   var $cli_parameters     = array("eins" => "Eins ist toll", "zwei" => "Zwei ist noch besser");
10   var $uid                        = "";       // User id 
11   var $cn                         = "";       // cn
12   var $orig_cn                    = "";       // cn
14   var $method                     = "mailMethod"; // Used Mail method 
15   var $mmethod                    = "";           // Contains the gosa.conf MAILMETHOD
16   var $mail                       = "";           // Default mail address 
18   var $gosaMailAlternateAddress   = array();  // Set default Alternate Mail Adresses to empty array
19   var $gosaMailForwardingAddress  = array();  // Forwarding also empty
21   var $gosaMailServer             = "";       // Selected mailserver 
22   var $gosaMailQuota              = "";       // Defined Quota 
23   var $quotaUsage                 = 0;        // Currently used quota
25   var $gosaVacationMessage        = "";       // Vocation message 
27   var $imapacl                    = array('anyone'    => 'p',     // Set acls for everyone
28       '%members%' => 'lrswp',  // %members% are all group-members
29       ''          => 'p');    // Every user added gets this right
32   var $gosaSpamSortLevel          = "";     
33   var $gosaSpamMailbox            = "";
34   var $gosaSharedFolderTarget     ;
36   var $forward_dialog             = FALSE;    
38   var $members                    = array();  // Group members
40   var $mailusers                  = array();
41   var $perms                      = array();
42   var $gosaMailDeliveryMode       = "[L        ]";   // 
43   var $gosaMailMaxSize            = "";       // 
44   
45   var $remove_folder_from_imap    = true;
47   /* Helper */
48   var $indexed_acl= array();
49   var $indexed_user= array();
51   var $view_logged = FALSE;
53   /* attribute list for save action */
54   var $attributes= array( "mail",   "gosaMailServer", "gosaMailQuota", "gosaMailMaxSize",
55       "gosaMailAlternateAddress", "gosaMailForwardingAddress",
56       "gosaMailDeliveryMode", "gosaSpamSortLevel", "gosaSpamMailbox",
57       "acl","gosaSharedFolderTarget", "gosaVacationMessage");
59   var $objectclasses= array("gosaMailAccount");
60   var $CopyPasteVars          = array("quotaUsage","imapacl");
62   function mailgroup ($config, $dn= NULL, $ui= NULL)
63   {
64     /* Initialise all available attributes ... if possible
65      */
66     plugin::plugin($config, $dn);
67     $this->orig_cn = $this->cn;
69     /* Set mailMethod to the one defined in gosa.conf 
70      */
71     if (isset($this->config->current['MAILMETHOD'])){
72       $this->mmethod= $this->config->current['MAILMETHOD'];
73     }
75     /* Check if selected mail method exists 
76      */
77     if (class_exists("mailMethod$this->mmethod")){
78       $this->method= "mailMethod$this->mmethod";
79     } else {
80       print_red(sprintf(_("There is no mail method '%s' specified in your gosa.conf available."), $this->mmethod));
81     }
83     /* Load Mailserver  
84      */
85     if(isset($this->attrs['gosaMailServer'][0])){
86       $this->gosaMailServer =  $this->attrs['gosaMailServer'][0];
87     }
89     /* Convert cn to uid in case of existing entry
90      */
91     if (isset($this->attrs['cn'][0])){
92       $this->uid= $this->attrs['cn'][0];
93     }
96     /* If this ins't new mailgroup, read all required data from ldap
97      */
98     if (($dn != "new")&&($dn != NULL)){
100       /* Load attributes which represent multiple entries  
101        */
102       foreach (array("gosaMailAlternateAddress", "gosaMailForwardingAddress") as $val){
103         $this->$val = array();
104         if (isset($this->attrs["$val"]["count"])){
105           for ($i= 0; $i<$this->attrs["$val"]["count"]; $i++){
106             array_push($this->$val, $this->attrs["$val"][$i]);
107           }
108         }
109       }
111       /* Only do IMAP actions if gosaMailServer attribute is set 
112        */
113       if (isset ($this->attrs["gosaMailServer"][0])){
115         /* Create new instance of our defined mailclass
116          */
117         $method= new $this->method($this->config);
119         if ($method->connect($this->attrs["gosaMailServer"][0])){
120         
122           /* Maybe the entry is not saved in new style, get
123              permissions from IMAP and convert them to acl attributes */
124           if (!isset($this->attrs['acl'])){
125             $this->imapacl=  $method->getSharedFolderPermissions($this->uid);
127             /* Need to filter what a member acl could be... */
128             $vote= array();
129             $peak= 0;
130             $leader= "";
131             foreach ($this->imapacl as $user => $acl){
133               if ($user != "anyone" ){
134                 if (!isset($vote[$acl])){
135                   $vote[$acl]= 1;
136                 } else {
137                   $vote[$acl]++;
138                 }
139                 if ($vote[$acl] > $peak){
140                   $leader= $acl;
141                   $peek= $vote[$acl];
142                 }
143               }
145             }
147             /* Highest count wins as %members%, remove all members
148                with the same acl */
149             if(!empty($leader)){
150               $this->imapacl['%members%']= $leader;
151             }
152             foreach ($this->imapacl as $user => $acl){
153               if ($this->acl == $leader && in_array($user, $this->attrs['memberUid'])){
154                 unset($this->imapacl[$user]);
155               }
156             }
158           } // ENDE ! isset ($this->attrs['acl'])
159           
160           /* Adapt attributes if needed */
161           $method->fixAttributesOnLoad($this);
162           
163           /*  get Quota */
164           $quota= $method->getQuota($this->uid);
166           /* Update quota values */
167           if(is_array($quota)){
168             if ($quota['gosaMailQuota'] == 2147483647){
169               $this->quotaUsage= "";
170               $this->gosaMailQuota= "";
171             } else {
172               $this->quotaUsage= $quota['quotaUsage'];
173               $this->gosaMailQuota= $quota['gosaMailQuota'];
174             }
175           }else{
176             $this->quotaUsage     = "";
177             $this->gosaMailQuota  = "";
178 //            print_red(sprintf(_("Can't get quota information for '%s'."),$this->uid));
179           }
180           $method->disconnect();
181         }   // ENDE $method->connect($this->attrs["gosaMailServer"][0])){
183       }   // ENDE gosaMailServer
185     }   // ENDE dn != "new"
188     /* Get global filter config */
189     if (!is_global("gmailfilter")){
190       $ui= get_userinfo();
191       $base= get_base_from_people($ui->dn);
192       $gmailfilter= array( "depselect"       => $base,
193           "muser"            => "",
194           "regex"           => "*");
195       register_global("gmailfilter", $gmailfilter);
196     }
198     /* Load permissions */
199     $tmp = array();
200     if(preg_match("/olab/i",$this->mmethod)){
201       $ldap = $this->config->get_ldap_link();
203       if (isset($this->attrs['acl'])){
205         for ($i= 0; $i<$this->attrs['acl']['count']; $i++){
206           list($user, $permission)= split(' ', $this->attrs['acl'][$i]);
208           /* Add to list */
209           $this->imapacl[$user]= $permission;
211           /* Get all user permissions sorted by acl, to detect the most used acl
212              This acl is then used for %members%
213            */
214           if ($user != "anyone" && $user != "%members%"){
215             $tmp[$permission][] = $user;
216           }
218           /* There is an entry in $this->imapacl like this this ... 
219              $this->attrs['imapacl']['anyone'] = "p";
220              $this->attrs['imapacl']['%members%'] = "lprs";
221              $this->attrs['imapacl'][''] = ""; <------ This is used to diplay an empty 
222              Field for special acls in our template.
223              If there is at least one special acl in out imapacl,
224              we don't need this entry anymore, because it is already displayed. 
225            */
226           if ($user != "anyone" && $user != "%members%"){
227             unset($this->imapacl['']);
228           }
229         }
230       }
232       /* In this section we dectect which acl is tho most used 
233          This will be used as %members% acl  
234        */
235       $tmp2 = array(); 
236       foreach($tmp as $acl => $user){
237         $tmp2[count($tmp[$acl])]=$acl;
238       }
239       /* Most used at last 
240        */
241       ksort($tmp2);      
242   
243       /* Assign last (most used acl) to %members% acl 
244        */
245       $str = array_pop($tmp2);
246       if(!empty($str)) {
247         $this->imapacl['%members%']=$str;
248       }
250       /* Open ldap connection 
251        */
252       $ldap = $this->config->get_ldap_link();
253       $ldap->cd($this->config->current['BASE']);
255       /* Remove those users, that use %members% acl && are member of this group. */
256       foreach($this->imapacl as $mail => $permission){
257         $ldap->search("(&(objectClass=person)(mail=".$mail."))",array("uid"));
258         $atr = $ldap->fetch();
259         if((isset($this->attrs['memberUid'])) && (is_array($this->attrs['memberUid']))){
260           if((isset($atr['uid'][0]))&&(in_array($atr['uid'][0],$this->attrs['memberUid']))&&($permission == $this->imapacl['%members%'])){
261             unset($this->imapacl[$mail]);
262           }
263         }
264       }
265       /* Append an empty entry, for special acl handling */
266       if(count($this->imapacl)==2){
267         $this->imapacl[''] ="";
268       }
269   
270     }else{ // Not kolab 
271       /* Load permissions */ 
272       if (isset($this->attrs['acl'])){
273         for ($i= 0; $i<$this->attrs['acl']['count']; $i++){
274           list($user, $permission)= split(' ', $this->attrs['acl'][$i]);
275           $this->imapacl[$user]= $permission;
276           if ($user != "anyone" && $user != "%members%"){
277             unset($this->imapacl['']);
278           }
279         }
280       }
281     }
283     /* Load Mailserver  
284      */
285     if(isset($this->attrs['gosaMailServer'][0])){
286       $this->gosaMailServer =  $this->attrs['gosaMailServer'][0];
287     }
288     /* Fill translations */
289     $this->perms["lrsw"]= _("read");
290     $this->perms["lrspw"]= _("post");
291     $this->perms["p"]= _("external post");
292     $this->perms["lrsipw"]= _("append");
293     $this->perms["lrswipcd"]= _("write");
294     $this->perms["lrswipcda"]= _("admin");
295     $this->perms[""]= _("none");
296   }
298   function execute()
299   {
300     /* Call parent execute */
301     //plugin::execute();
303     /* Log view */
304     if($this->is_account && !$this->view_logged){
305       $this->view_logged = TRUE;
306       @log::log("view","groups/".get_class($this),$this->dn);
307     }
309     /* Load templating engine */
310     $smarty= get_smarty();
312     /* Assign acls */
313     $tmp = $this->plInfo();
314     foreach($tmp['plProvidedAcls'] as $name => $translation) {
315       $smarty->assign($name."ACL",$this->getacl($name));
316     }
318     if ($_SESSION['js']==FALSE){
319       $smarty->assign("javascript", "false");
320     } else {
321       $smarty->assign("javascript", "true");
322     }
324     /* Do we need to flip is_account state? */
325     if(isset($_POST['modify_state'])){
326       if($this->is_account && $this->acl_is_removeable()){
327         $this->is_account= FALSE;
328       }elseif(!$this->is_account && $this->acl_is_createable()){
329         $this->is_account= TRUE;
330       }
331     }
333     $display = "";
335     /* Do we represent a valid account? */
336     if (!$this->is_account && $this->parent == NULL){
338       $display.= "<img alt=\"\" src=\"images/stop.png\" align=middle>&nbsp;<b>".
339         _("This 'dn' has no valid mail extensions.")."</b>";
340       return ($display);
341     }
343     /* Show tab dialog headers */
344     $display= "";
345     if ($this->parent != NULL){
346       if ($this->is_account){
347         $display.= $this->show_disable_header(_("Remove mail account"),
348             _("This account has mail features enabled. You can disable them by clicking below."));
349       } else {
350         $display.= $this->show_enable_header(_("Create mail account"),
351             _("This account has mail features disabled. You can enable them by clicking below."));
352   
353         /* Show checkbox that allows us to remove imap entry too*/
354         if($this->initially_was_account){
355           $c = "";
356           if($this->remove_folder_from_imap){
357             $c= " checked ";
358           }
359           $display .= "<h2>Shared folder delete options</h2>
360                        <input class='center' type='checkbox' name='remove_folder_from_imap' value='1' ".$c."
361                         title='"._("Remove shared folder from mail server database when entry gets removed in LDAP")."'>";
362           $display .= _("Remove the shared folder and all its contents after saving this account");
363         }
364         return ($display);
365       }
366     }
368     /* Add ACL? */
369     if($this->acl_is_writeable("acl")){
370       foreach ($this->indexed_user as $nr => $user){
371         if (isset($_POST["add_$nr"])){
372           $this->imapacl[""]= "l";
373         }
374         if (isset($_POST["del_$nr"])){
375           unset ($this->imapacl[$user]);
376         }
377       }
378     }
380     /* Trigger forward add dialog? */
381     if($this->acl_is_writeable("gosaMailForwardingAddress")){
382       if (isset($_POST['add_local_forwarder'])){
383         $this->forward_dialog= TRUE;
384         $this->dialog= TRUE;
385       }
386     }
388     /* Cancel forward add dialog? */
389     if($this->acl_is_writeable("gosaMailForwardingAddress")){
390       if (isset($_POST['add_locals_cancel'])){
391         $this->forward_dialog= FALSE;
392         $this->dialog= FALSE;
393       }
394     }
396     /* Finished adding of locals? */
397     if ((isset($_POST['add_locals_finish'])) && ($this->acl_is_writeable("gosaMailForwardingAddress"))) {
398       if (count ($_POST['local_list']) && $this->acl_is_writeable("gosaMailForwardingAddress")){
400         /* Walk through list of forwarders, ignore own addresses */
401         foreach ($_POST['local_list'] as $val){
402           if (!in_array ($val, $this->gosaMailAlternateAddress) &&
403               $val != $this->mail){
405             $this->addForwarder($val);
406           }
407         }
408       }
409       $this->forward_dialog= FALSE;
410       $this->dialog= FALSE;
411     }
413     /* Add forward email addresses */
414     if ((isset($_POST['add_forwarder'])) && ($this->acl_is_writeable("gosaMailForwardingAddress"))){
415       if ($_POST['forward_address'] != ""){
417         /* Valid email address specified? */
418         $address= $_POST['forward_address'];
419         if (!is_email($address)){
421           print_red (_("You're trying to add an invalid email address ".
422                 "to the list of forwarders."));
424         } elseif ($address == $this->mail
425             || in_array($address, $this->gosaMailAlternateAddress)) {
427           print_red (_("Adding your one of your own addresses to the forwarders makes no sense."));
429         } else {
431           /* Add it */
432           if ($this->acl_is_writeable("gosaMailForwardingAddress")){
433             $this->addForwarder ($address);
434           }
436         }
437       }
438     }
440     /* Delete forward email addresses */
441     if (isset($_POST['delete_forwarder']) && ($this->acl_is_writeable("gosaMailForwardingAddress"))){
442       if (count($_POST['forwarder_list'])&& $this->acl_is_writeable("gosaMailForwardingAddress")){
444         $this->delForwarder ($_POST['forwarder_list']);
445       }
446     }
448     /* Add alternate email addresses */
449     if (isset($_POST['add_alternate'])){
450       if ($_POST['alternate_address'] != "" && $this->acl_is_writeable("gosaMailAlternateAddress")){
452         if (!is_email($_POST['alternate_address'])){
453           print_red (_("You're trying to add an invalid email address to the list of alternate addresses."));
455         } elseif (($user= $this->addAlternate ($_POST['alternate_address'])) != ""){
456           $ui= get_userinfo();
457           if ($user != $ui->username){
458             print_red (_("The address you're trying to add is already used by user")." '$user'.");
459           }
460         }
461       }
462     }
464     /* Delete alternate email addresses */
465     if($this->acl_is_writeable("gosaMailAlternateAddress")){
466       if (isset($_POST['delete_alternate']) && isset ($_POST['alternates_list'])){
467         if (count($_POST['alternates_list']) && $this->acl_is_writeable("gosaMailAlternateAddress")){
468           $this->delAlternate ($_POST['alternates_list']);
469         }
470       }
471     }
473     /* Show forward add dialog */
474     if ($this->forward_dialog){
475       $ldap= $this->config->get_ldap_link();
477       /* Save data */
478       $gmailfilter= get_global("gmailfilter");
479       foreach( array("depselect", "muser", "regex") as $type){
480         if (isset($_POST[$type])){
481           $gmailfilter[$type]= $_POST[$type];
482         }
483       }
484       if (isset($_GET['search'])){
485         $s= mb_substr($_GET['search'], 0, 1, "UTF8")."*";
486         if ($s == "**"){
487           $s= "*";
488         }
489         $gmailfilter['regex']= $s;
490       }
491       register_global("gmailfilter", $gmailfilter);
493       /* Get actual list */
494       $mailusers= array ();
495       if ($gmailfilter['regex'] != '*' && $gmailfilter['regex'] != ""){
496         $regex= $gmailfilter['regex'];
497         $filter= "(|(mail=$regex)(gosaMailAlternateAddress=$regex))";
498       } else {
499         $filter= "";
500       }
501       if ($gmailfilter['muser'] != ""){
502         $user= $gmailfilter['muser'];
503         $filter= "$filter(|(uid=$user)(cn=$user)(givenName=$user)(sn=$user))";
504       }
506       /* Add already present people to the filter */
507       $exclude= "";
508       foreach ($this->gosaMailForwardingAddress as $mail){
509         $exclude.= "(mail=$mail)";
510       }
511       if ($exclude != ""){
512         $filter.= "(!(|$exclude))";
513       }
515       $res= get_list("(&(objectClass=gosaMailAccount)$filter)", "users", $gmailfilter['depselect'],
516                      array("sn", "mail", "givenName"), GL_SUBSEARCH | GL_SIZELIMIT);
517       $ldap->cd($gmailfilter['depselect']);
518       $ldap->search ("(&(objectClass=gosaMailAccount)$filter)", array("sn", "mail", "givenName"));
519       error_reporting (0);
520       while ($attrs= $ldap->fetch()){
521         if(preg_match('/%/', $attrs['mail'][0])){
522           continue;
523         }
524         $name= $this->make_name($attrs);
525         $mailusers[$attrs['mail'][0]]= $name."&lt;".
526           $attrs['mail'][0]."&gt;";
527       }
528       error_reporting (E_ALL);
529       natcasesort ($mailusers);
530       reset ($mailusers);
532       /* Show dialog */
533       $smarty->assign("search_image", get_template_path('images/search.png'));
534       $smarty->assign("usearch_image", get_template_path('images/search_user.png'));
535       $smarty->assign("tree_image", get_template_path('images/tree.png'));
536       $smarty->assign("infoimage", get_template_path('images/info.png'));
537       $smarty->assign("launchimage", get_template_path('images/small_filter.png'));
538       $smarty->assign("mailusers", $mailusers);
539       $smarty->assign("deplist", $this->config->idepartments);
540       $smarty->assign("apply", apply_filter());
541       $smarty->assign("alphabet", generate_alphabet());
542       $smarty->assign("hint", print_sizelimit_warning());
543       foreach( array("depselect", "muser", "regex") as $type){
544         $smarty->assign("$type", $gmailfilter[$type]);
545       }
546       $smarty->assign("hint", print_sizelimit_warning());
547       $display.= $smarty->fetch (get_template_path('mail_locals.tpl', TRUE));
548       return ($display);
549     }
551     /* Assemble normal permissions */
552     if (isset($this->imapacl['anyone'])){
553       $smarty->assign("default_permissions", $this->imapacl['anyone']);
554     }
555     $smarty->assign("member_permissions", "lrsp");
556     if (isset($this->imapacl['%members%'])){
557       $smarty->assign("member_permissions", $this->imapacl['%members%']);
558     }
560     /* Assemble extra attributes */
561     $perm= $this->getacl( "permissions");
562     $tmp= "";
563     $nr= 0;
564     $count= count($this->imapacl);
565     $this->indexed_user= array();
566     $this->indexed_acl= array();
567     foreach($this->imapacl as $user => $acl){
569       /* Add additional acl settings */
570       if ($user != "anyone" && $user != "%members%"){
572         $Dis  = "";
573         if(!preg_match("/w/",$perm)){
574           $Dis = " disabled ";
575         }
576   
577         /* Reset given Acls to ensure that nobody can read username and acls if not allwoed */
578         if(!preg_match("/r/",$perm)){
579           $user = "";
580           $nr   = "none";
581           $key  = "none";  
582         }
584         $tmp.= "<tr>  
585                  <td>
586                   <input name=\"user_$nr\" size=20 maxlength=60 value=\"$user\" ".$Dis.">
587                  </td>
588                  <td>
589                  <select size=\"1\" name=\"perm_$nr\" ".$Dis.">";
591         /* Add acl options for this additional acl setting */
592         if(preg_match("/r/",$perm)){
593           foreach ($this->perms as $key => $value){
594             if ($acl == $key){
595               $tmp.= "<option value=\"$key\" selected>$value</option>";
596             } else {
597               $tmp.= "<option value=\"$key\">$value</option>";
598             }
599           }
600         }
601         $tmp.= "</select>&nbsp;";
604         
605         if ($nr == $count - 1){
606           if($this->acl_is_writeable("acl")){
607             $tmp.= "<input type=submit value=\""._("Add")."\" ".
608               "name=\"add_$nr\" >";
609           }
610         }
611         if ($count > 3){
612           if($this->acl_is_writeable("acl")){
613             $tmp.= "<input type=submit value=\""._("Remove")."\" ".
614               "name=\"del_$nr\" ></td></tr>";        
615           }
616         }
617       }
618       $this->indexed_user[$nr]= $user;
619       $this->indexed_acl[$nr++]= $acl;
620     }
621     $smarty->assign("plusattributes", $tmp);
623     /* Show main page */
624     $mailserver= array();
625     foreach ($this->config->data['SERVERS']['IMAP'] as $key => $val){
626       $mailserver[]= $key;
627     }
628     $smarty->assign("mailServers", $mailserver);
629     foreach(array("gosaMailServer", "gosaMailQuota", "perms", "mail",
630           "gosaMailAlternateAddress", "gosaMailForwardingAddress") as $val){
631       $smarty->assign("$val", $this->$val);
632     }
633     if (is_numeric($this->gosaMailQuota) && $this->gosaMailQuota != 0){
634       if($this->acl_is_readable("gosaMailQuota")){
635         $smarty->assign("quotausage", progressbar(round(($this->quotaUsage * 100)/ $this->gosaMailQuota),100,15,true));
636         $smarty->assign("quotadefined", "true");
637       }else{
638         $smarty->assign("quotadefined", "true");
639         $smarty->assign("quotausage", "-");
640       }
641     } else {
642       $smarty->assign("quotadefined", "false");
643     }
645     $display.= $smarty->fetch (get_template_path('mail.tpl', TRUE));
646     return ($display);
647   }
650   /* remove object from parent */
651   function remove_from_parent()
652   {
653     if(!$this->initially_was_account){
654       return;
655     }
656   
657     /* Added these ObjectClass and Attributes, because they were not 
658        removed correctly, only in case of kolab ... 
659      */
660     if(isset($this->config->current['MAILMETHOD'])&&preg_match("/olab/i",$this->config->current['MAILMETHOD'])){
661       $this->attributes[]="acl";
662       $this->objectclasses[] = "kolabSharedFolder";
663     }
664     /* include global link_info */
665     $ldap= $this->config->get_ldap_link();
667     /* Remove and write to LDAP */
668     plugin::remove_from_parent();
670     /* Zero arrays */
671     $this->attrs['gosaMailAlternateAddress']= array();
672     $this->attrs['gosaMailForwardingAddress']= array();
673     $this->attrs['gosaSharedFolderTarget']= array();
675     /* Connect to IMAP server for account deletion */
676     if ($this->initially_was_account){
677  
678       $method= new $this->method($this->config);
679       $method->fixAttributesOnRemove($this);
680       if ($method->connect($this->gosaMailServer) && $this->remove_folder_from_imap){
682         /* Remove account from IMAP server */
683         $method->deleteMailbox($this->uid);
684         $method->disconnect();
685       }
686     }
687     /* Keep uid */
688     unset ($this->attrs['uid']);
690     $ldap->cd($this->dn);
691     $ldap->modify ($this->attrs); 
692     show_ldap_error($ldap->get_error(), sprintf(_("Removing of groups/mail with dn '%s' failed."),$this->dn));
695     @log::log("remove","groups/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
697     /* Optionally execute a command after we're done */
698     $this->handle_post_events("remove");
699   }
702   /* Save data to object */
703   function save_object()
704   {
706     /* Check if user wants to remove the shared folder from imap too */
707     if($this->initially_was_account && !$this->is_account){
708       if(isset($_POST['remove_folder_from_imap'])){
709         $this->remove_folder_from_imap = true;
710       }else{
711         $this->remove_folder_from_imap = false;
712       }
713     }
715     /* Assemble mail delivery mode
716        The mode field in ldap consists of values between braces, this must
717        be called when 'mail' is set, because checkboxes may not be set when
718        we're in some other dialog.
720        Example for gosaMailDeliveryMode [LR        ]
721 L: Local delivery
722 R: Reject when exceeding mailsize limit
723 S: Use spam filter
724 V: Use vacation message
725 C: Use custom sieve script
726 I: Only insider delivery */
727     if (isset($_POST['mailedit'])){
729       plugin::save_object();
731       $tmp= preg_replace("/[^a-z]/i","",$this->gosaMailDeliveryMode);
733       /* Handle delivery flags */
734       if($this->acl_is_writeable("gosaMailDeliveryModeL")){
735         if(!preg_match("/L/",$tmp) && !isset($_POST['drop_own_mails'])){
736           $tmp.="L";
737         }elseif(preg_match("/L/",$tmp) && isset($_POST['drop_own_mails'])){
738           $tmp = preg_replace("/L/","",$tmp);
739         }
740       }
742       $opts = array(
743           "R"   => "use_mailsize_limit",
744           "S"   => "use_spam_filter",
745           "V"   => "use_vacation",
746           "C"   => "own_script",
747           "I"   => "only_local");
749       foreach($opts as $flag => $post){
750         if($this->acl_is_writeable("gosaMailDeliveryMode".$flag)){
751           if(!preg_match("/".$flag."/",$tmp) && isset($_POST[$post])){
752             $tmp.= $flag;
753           }elseif(preg_match("/".$flag."/",$tmp) && !isset($_POST[$post])){
754             $tmp = preg_replace("/".$flag."/","",$tmp);
755           }
756         }
757       }
759       $tmp= "[$tmp]";
760       if ($this->gosaMailDeliveryMode != $tmp){
761         $this->is_modified= TRUE;
762       }
763       $this->gosaMailDeliveryMode= $tmp;
765       /* Collect data and re-assign it to the imapacl array */
766       if ($this->acl_is_writeable("acl")){
767         $this->imapacl= array();
768         $this->imapacl['%members%']= $_POST['member_permissions'];
769         $this->imapacl['anyone']= $_POST['default_permissions'];
770         foreach ($this->indexed_user as $nr => $user){
771           if (!isset($_POST["user_$nr"])){
772             continue;
773           }
774           if ($_POST["user_$nr"] != $user ||
775               $_POST["perm_$nr"] != $this->indexed_acl[$nr]){
776             $this->is_modified= TRUE;
777           }
778           $this->imapacl[$_POST["user_$nr"]]= $_POST["perm_$nr"];
779         }
780       }
781     }
783   }
787   /* Save data to LDAP, depending on is_account we save or delete */
788   function save()
789   {
790     $ldap= $this->config->get_ldap_link();
791     $ldap->cd($this->config->current['BASE']);
793     /* Call parents save to prepare $this->attrs */
794     plugin::save();
796     /* Save arrays */
797     $this->attrs['gosaMailAlternateAddress']  = $this->gosaMailAlternateAddress;
798     $this->attrs['gosaMailForwardingAddress'] = $this->gosaMailForwardingAddress;
799     $this->attrs['gosaSharedFolderTarget']    = "share+".$this->uid;
801     if(preg_match("/olab/i",$this->mmethod)){
802       /* Save acl's */
803       $this->attrs['acl']= array();
804       foreach ($this->imapacl as $user => $acl){
805         if ($user == ""){
806           continue;
807         }
808         $ldap->search("(&(objectClass=person)(|(uid=".$user.")(mail=".$user.")))",array("mail"));
809         $mail = $ldap->fetch();
810         if($mail){
811           if(isset($mail['mail'][0])){
812             $this->attrs['acl'][]= $mail['mail'][0]." $acl";
813           }
814         }else{
815           $this->attrs['acl'][]= "$user $acl";
816         }
817       }
818     }else{
819       /* Save acl's */
820       $this->attrs['acl']= array();
821       foreach ($this->imapacl as $user => $acl){
822         if ($user == ""){
823           continue;
824         }
825         $this->attrs['acl'][]= "$user $acl";
826       }
827     }
829     /* Only do IMAP actions if we are not a template */
830     if(preg_match("/olab/i",$this->mmethod)){
831       if (empty($this->gosaMailServer)||is_array($this->gosaMailServer)){
832         if(isset($this->attrs['gosaMailServer'][0])){
833           $this->gosaMailServer = $this->attrs['gosaMailServer'][0];
834         }
835       }
836     }  
839     /* Exchange '%member%' pseudo entry */
840     $memberacl= $this->imapacl['%members%'];
842     foreach ($this->members as $user){
843       if(preg_match("/olab/i",$this->mmethod)){
844         $ldap->cd($this->config->current['BASE']);
845         $ldap->search("(&(objectClass=person)(|(mail=".$user.")(uid=".$user.")))",array("mail"));
846         $at = $ldap->fetch();
847         if(isset($at['mail'][0])){
848           $user = $at['mail'][0];
849         }
850       }
851       if (!isset($this->imapacl[$user])){
852         $this->imapacl[$user]= $memberacl;
853       }
854     }
855     $this->attrs['acl'] = array();
856     
857     
858     foreach($this->imapacl as $user => $acl){
860       /* Remove empty user entry, to avoid entry like this im imap 
861        *   "" lrs
862        */
863       if(empty($user)){
864         unset($this->imapacl[$user]);
865       }
866    
867       /* Skip invalid values */
868       if(preg_match("/%members%/",$user) || empty($user)){
869         continue;
870       }
872       /* Append ldap acl entries */
873       $this->attrs['acl'][] = $user." ".$acl;
874     }
876     if ((!$this->is_template)&&(!empty($this->gosaMailServer))){
877       $method= new $this->method($this->config);
878       $method->fixAttributesOnStore($this);
879       if (($method->connect($this->gosaMailServer))){
880         $method->updateMailbox($this->uid);
881         $method->setQuota($this->uid, $this->gosaMailQuota);
882         $method->setSharedFolderPermissions($this->uid, $this->imapacl);
883         $method->disconnect();
884       }
885     }
887     /* Save data to LDAP */
888     $ldap->cd($this->dn);
889     $this->cleanup();
890     $ldap->modify ($this->attrs); 
891     show_ldap_error($ldap->get_error(), sprintf(_("Saving of groups/mail with dn '%s' failed."),$this->dn));
892     
893     if($this->initially_was_account){
894       @log::log("modify","groups/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
895     }else{
896       @log::log("create","groups/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());  
897     }
898     
900     /* Optionally execute a command after we're done */
901     if ($this->initially_was_account == $this->is_account){
902       if ($this->is_modified){
903         $this->handle_post_events("modify");
904       }
905     } else {
906       $this->handle_post_events("add");
907     }
908   }
910   /* Check formular input */
911   function check()
912   {
913     $ldap= $this->config->get_ldap_link();
915     /* Call common method to give check the hook */
916     $message= plugin::check();
918     if(!$this->is_account) return array();
919     
920     //$message[] = $str;      
922     /* must: mail */
923     if ($this->mail == ""){
924       $message[]= _("The required field 'Primary address' is not set.");
925     }
926     if (!is_email($this->mail)){
927       $message[]= _("Please enter a valid email addres in 'Primary address' field.");
928     }
929     $ldap->cd($this->config->current['BASE']);
930     $ldap->search ("(&(!(objectClass=gosaUserTemplate))(objectClass=gosaMailAccount)(|(mail=".$this->mail.")(gosaMailAlternateAddress=".
931         $this->mail."))(!(uid=".$this->orig_cn."))(!(cn=".$this->orig_cn.")))");
932     if ($ldap->count() != 0){
933       $message[]= _("The primary address you've entered is already in use.");
934     }
935   
936     /* Check quota */
937     if ($this->gosaMailQuota != '' && $this->acl_is_writeable("gosaMailQuota")){
938       if (!is_numeric($this->gosaMailQuota)) {
939         $message[]= _("Value in 'Quota size' is not valid.");
940       } else {
941         $this->gosaMailQuota= (int) $this->gosaMailQuota;
942       }
943     }
945     /* Check rejectsize for integer */
946     if ($this->gosaMailMaxSize != '' && $this->acl_is_writeable("gosaMailQuota")){
947       if (!is_numeric($this->gosaMailMaxSize)){
948         $message[]= _("Please specify a vaild mail size for mails to be rejected.");
949       } else {
950         $this->gosaMailMaxSize= (int) $this->gosaMailMaxSize;
951       }
952     }
954     /* Need gosaMailMaxSize if use_mailsize_limit is checked */
955     if (is_integer(strpos($this->gosaMailDeliveryMode, "reject")) && $this->gosaMailMaxSize == ""){
956       $message[]= _("You need to set the maximum mail size in order to reject anything.");
957     }
959     if(ord($this->imapacl['anyone'][0])==194){
960       $message[] = _("Please choose valid permission settings. Default permission can't be emtpy.");
961     }
963     if(empty($this->gosaMailServer)){
964       $message[] = _("Please select a valid mail server.");
965     }
967     return ($message);
968   }
970   /* Adapt from template, using 'dn' */
971   function adapt_from_template($dn)
972   {
973     plugin::adapt_from_template($dn);
975     foreach (array("gosaMailAlternateAddress", "gosaMailForwardingAddress") as $val){
976       $this->$val= array();
977       if (isset($this->attrs["$val"]["count"])){
978         for ($i= 0; $i<$this->attrs["$val"]["count"]; $i++){
979           $value= $this->attrs["$val"][$i];
980           foreach (array("sn", "givenName", "uid") as $repl){
981             if (preg_match("/%$repl/i", $value)){
982               $value= preg_replace ("/%$repl/i", $this->parent->$repl, $value);
983             }
984           }
985           array_push($this->$val, $value);
986         }
987       }
988     }
989   }
991   /* Add entry to forwarder list */
992   function addForwarder($address)
993   {
994     $this->gosaMailForwardingAddress[]= $address;
995     $this->gosaMailForwardingAddress= array_unique ($this->gosaMailForwardingAddress);
997     sort ($this->gosaMailForwardingAddress);
998     reset ($this->gosaMailForwardingAddress);
999     $this->is_modified= TRUE;
1000   }
1002   /* Remove list of addresses from forwarder list */
1003   function delForwarder($addresses)
1004   {
1005     $this->gosaMailForwardingAddress= array_remove_entries ($addresses,
1006         $this->gosaMailForwardingAddress);
1007     $this->is_modified= TRUE;
1008   }
1012   function addAlternate($address)
1013   {
1014     $ldap= $this->config->get_ldap_link();
1016     $address= strtolower($address);
1018     /* Is this address already assigned in LDAP? */
1019     $ldap->cd ($this->config->current['BASE']);
1020     $ldap->search ("(&(objectClass=gosaMailAccount)(|(mail=$address)".
1021         "(gosaMailAlternateAddress=$address)))");
1023     if ($ldap->count() > 0){
1024       $attrs= $ldap->fetch ();
1025       return ($attrs["uid"][0]);
1026     }
1028     /* Add to list of alternates */
1029     if (!in_array($address, $this->gosaMailAlternateAddress)){
1030       $this->gosaMailAlternateAddress[]= $address;
1031     }
1033     sort ($this->gosaMailAlternateAddress);
1034     reset ($this->gosaMailAlternateAddress);
1035     $this->is_modified= TRUE;
1037     return ("");
1038   }
1041   function delAlternate($addresses)
1042   {
1043     $this->gosaMailAlternateAddress= array_remove_entries ($addresses,
1044         $this->gosaMailAlternateAddress);
1045     $this->is_modified= TRUE;
1046   }
1049   function make_name($attrs)
1050   {
1051     $name= "";
1052     if (isset($attrs['sn'][0])){
1053       $name= $attrs['sn'][0];
1054     }
1055     if (isset($attrs['givenName'][0])){
1056       if ($name != ""){
1057         $name.= ", ".$attrs['givenName'][0];
1058       } else {
1059         $name.= $attrs['givenName'][0];
1060       }
1061     }
1062     if ($name != ""){
1063       $name.= " ";
1064     }
1066     return ($name);
1067   }
1069   function getCopyDialog()
1070   {
1071     if(!$this->is_account) return("");
1073     $smarty = get_smarty();
1074     $smarty->assign("gosaMailAlternateAddress",$this->gosaMailAlternateAddress);
1075     $smarty->assign("gosaMailForwardingAddress",$this->gosaMailForwardingAddress);
1076     $smarty->assign("mail",$this->mail);
1077     $display= $smarty->fetch (get_template_path('paste_mail.tpl', TRUE));
1078     $ret = array();
1079     $ret['string'] = $display;
1080     $ret['status'] = "";
1081     return($ret);
1082   }
1084   function saveCopyDialog()
1085   {
1086     if(!$this->is_account) return;
1088     /* Perform ADD / REMOVE ... for mail alternate / mail forwarding addresses 
1089     */
1090     $this->execute();
1091     if(isset($_POST['mail'])){
1092       $this->mail = $_POST['mail'];
1093     }
1094   }
1097   function PrepareForCopyPaste($source)
1098   {
1099     plugin::PrepareForCopyPaste($source);
1100  
1101     /* Reset alternate mail addresses */
1102     $this->gosaMailAlternateAddress = array();
1103   }
1106   /* Return plugin informations for acl handling  */
1107   function plInfo()
1108   {
1109     return (array(
1110           "plShortName"   => _("Mail"),
1111           "plDescription" => _("Group mail"),
1112           "plSelfModify"  => FALSE,
1113           "plDepends"     => array(),
1114           "plPriority"    => 0,
1115           "plSection"     => array("administration"),
1116           "plCategory"    => array("groups"), 
1117           "plProvidedAcls"=> array(
1118             "mail"                      => _("Mail address"),
1119             "gosaMailAlternateAddress"  => _("Alternate addresses"),
1120             "gosaMailForwardingAddress" => _("Forwarding addresses"),
1121             "gosaMailQuota"             => _("Quota size"),
1122             "gosaMailServer"            => _("Mail server"),
1123             "acl"                       => _("Permissions"))
1124           ));
1125   }
1128 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1129 ?>