Code

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