Code

Backport from trunk
[gosa.git] / gosa-plugins / mail / personal / mail / class_mailAccount.inc
index 1516411ab1ab004604809cc837bba2d82cffc08b..1d3993a1dca3468f42cd1e203e80e3ace9dc3d26 100644 (file)
@@ -23,7 +23,6 @@ Functions :
  - addAlternate($address)
  - delAlternate($addresses)
  - prepare_vacation_template($contents)
- - display_forward_dialog()
  - remove_from_parent()
  - save()
  - check()
@@ -44,19 +43,38 @@ Functions :
 
  */
 
+/*
+
+    FLAG    POSTNAME                DESC
+    ####################################################################################################
+    L  (!)  only_local              Enables: "User is only allowed to send and receive local mails"
+
+                                    <REVERSED> If checked in the ui, the flag is not present in the 
+                                     gosaMailDeliveryMode attribute. If its unchecked in the ui, the 
+                                     character 'L' is added to the delivery flags.
+
+    R       use_mailsize_limit      Enables rule: "Reject mails bigger than [n] MB";
+    S       use_spam_filter         Enables rule: "Move mails tagged with SPAM level greater than [n] 
+                                     to folder [x]"
+    V       use_vacation            Enables: "Vacation message"
+    C       own_script              Enables: "Use custom sieve script (disables all Mail options!)"
+    I       drop_own_mails          Enables: "No delivery to own mailbox."
+
+*/
+
 class mailAccount extends plugin
 {
   /* Definitions */
   var $plHeadline     = "Mail";
-  var $plDescription  = "This does something";
+  var $plDescription  = "Manage personal mail settings";
   var $view_logged    = FALSE;
   var $is_account     = FALSE;
   var $initially_was_account = FALSE;
 
   /* GOsa mail attributes */
   var $mail                               = "";
-  var $gosaVacationStart                  = 0;
-  var $gosaVacationStop                   = 0;
+  var $gosaVacationStart                  = "";
+  var $gosaVacationStop                   = "";
   var $gosaMailAlternateAddress           = array();
   var $gosaMailForwardingAddress          = array();
   var $gosaMailDeliveryMode               = "[L        ]";
@@ -68,12 +86,14 @@ class mailAccount extends plugin
   var $gosaSpamMailbox                    = "";
 
   /* The methods defaults */
+  var $quotaUsage     = -1; // Means unknown
+
   var $mailMethod      = NULL;
   var $MailDomain      = "";
   var $sieveManagementUsed = FALSE;
   var $vacationTemplates = array();
   var $sieve_management = NULL;
-  var $forward_dialog = FALSE;
+  var $mailAddressSelect = FALSE;
   var $initial_uid    = "";
   var $mailDomainPart = "";
   var $mailDomainParts = array();
@@ -89,12 +109,26 @@ class mailAccount extends plugin
 
   var $multiple_support = TRUE;
 
+  var $uid = "";
+  var $cn  = "";
+
+
   /*! \brief  Initialize the mailAccount 
    */
   function __construct (&$config, $dn= NULL)
   {
     plugin::plugin($config,$dn); 
 
+    /* Get attributes from parent object 
+     */
+    foreach(array("uid","cn") as $attr){
+      if(isset($this->parent->by_object['group']) && isset($this->parent->by_object['group']->$attr)){
+        $this->$attr = &$this->parent->by_object['group']->$attr;
+      }elseif(isset($this->attrs[$attr])){
+        $this->$attr = $this->attrs[$attr][0];
+      }
+    }
+
     /* Intialize the used mailMethod
      */
     $tmp = new mailMethod($config,$this);
@@ -107,9 +141,9 @@ class mailAccount extends plugin
      */
     $this->initially_was_account = $this->is_account;
 
-    /* Initialize vacation settings 
+    /* Initialize vacation settings, if enabled.
      */   
-    if(empty($this->gosaVacationStart)){
+    if(empty($this->gosaVacationStart) && $this->mailMethod->vacationRangeEnabled()){
       $this->gosaVacationStart = time();
       $this->gosaVacationStop = time();
     }
@@ -120,12 +154,13 @@ class mailAccount extends plugin
 
     /* Initialize configured values 
      */ 
-    if($this->is_account){
+    if($this->is_account && !$this->is_template){
 
       if($this->mailMethod->connect() && $this->mailMethod->account_exists()){
 
         /* Read quota */
         $this->gosaMailQuota = $this->mailMethod->getQuota($this->gosaMailQuota);
+        $this->quotaUsage    = $this->mailMethod->getQuotaUsage($this->quotaUsage);
         if($this->mailMethod->is_error()){
           msg_dialog::display(_("Mail error"), sprintf(_("Cannot read quota settings: %s"), 
                 $this->mailMethod->get_error()), ERROR_DIALOG);
@@ -152,7 +187,7 @@ class mailAccount extends plugin
         if($this->mailMethod->domainSelectionEnabled()){
           $this->mailDomainPart = preg_replace("/^[^@]*+@/","",$this->mail);
           $this->mail = preg_replace("/@.*$/","\\1",$this->mail);
-          if(!in_array($this->mailDomainPart,$this->mailDomainParts)){
+          if(!in_array_strict($this->mailDomainPart,$this->mailDomainParts)){
             $this->mailDomainParts[] = $this->mailDomainPart;
           }
         }
@@ -175,20 +210,14 @@ class mailAccount extends plugin
       $this->sieve_management = new sieveManagement($this->config,$this->dn,$this,$this->mailMethod->getUAttrib());
     }
 
-    /* Get global filter config used in add local forward
-     */
-    if (!session::is_set("mailfilter")){
-      $ui= get_userinfo();
-      $base= get_base_from_people($ui->dn);
-      $mailfilter= array( "depselect"       => $base,
-          "muser"            => "",
-          "regex"           => "*");
-      session::set("mailfilter", $mailfilter);
-    }
-
     /* Disconnect mailMethod. Connect on demand later. 
      */
     $this->mailMethod->disconnect();
+
+    /* Convert start/stop dates */
+    #TODO: use date format
+    $this->gosaVacationStart= date('d.m.Y', $this->gosaVacationStart);
+    $this->gosaVacationStop= date('d.m.Y', $this->gosaVacationStop);
   }
 
 
@@ -234,9 +263,9 @@ class mailAccount extends plugin
         } else {
           $reason = "";
           if(!$this->mailMethod->accountCreateable($reason)){
-            $display= $this->show_disable_header(msgPool::addFeaturesButton(_("Mail")),$reason ,TRUE,TRUE);
+            $display= $this->show_enable_header(msgPool::addFeaturesButton(_("Mail")),$reason ,TRUE,TRUE);
           }else{
-            $display= $this->show_disable_header(msgPool::addFeaturesButton(_("Mail")),msgPool::featuresDisabled(_("Mail")));
+            $display= $this->show_enable_header(msgPool::addFeaturesButton(_("Mail")),msgPool::featuresDisabled(_("Mail")));
           }
           return ($display);
         }
@@ -269,34 +298,48 @@ class mailAccount extends plugin
     /****************
       Forward addresses 
      ****************/
+
     if (isset($_POST['add_local_forwarder'])){
-      $this->forward_dialog= TRUE;
+      $this->mailAddressSelect=  new mailAddressSelect($this->config, get_userinfo());
       $this->dialog= TRUE;
     }
-    if (isset($_POST['add_locals_cancel'])){
-      $this->forward_dialog= FALSE;
+    if (isset($_POST['mailAddressSelect_cancel'])){
+      $this->mailAddressSelect= FALSE;
       $this->dialog= FALSE;
     }
-    if (isset($_POST['add_locals_finish'])){
-      if (isset($_POST['local_list'])){
-        if($this->acl_is_writeable("gosaMailForwardingAddress")){
-          foreach ($_POST['local_list'] as $val){
-            if (!in_array ($val, $this->gosaMailAlternateAddress) &&
-                $val != $this->mail){
-              $this->addForwarder($val);
-              $this->is_modified= TRUE;
-            }
+
+    if (isset($_POST['mailAddressSelect_save']) && $this->mailAddressSelect instanceOf mailAddressSelect){
+
+      if($this->acl_is_writeable("gosaMailForwardingAddress")){
+        $list = $this->mailAddressSelect->save();
+        foreach ($list as $entry){
+          $val = $entry['mail'][0];
+          if (!in_array_strict($val, $this->gosaMailAlternateAddress) && $val != $this->mail){
+            $this->addForwarder($val);
+            $this->is_modified= TRUE;
           }
         }
-        $this->forward_dialog= FALSE;
+        $this->mailAddressSelect= FALSE;
         $this->dialog= FALSE;
       } else {
         msg_dialog::display(_("Error"), _("Please select an entry!"), ERROR_DIALOG);
       }
     }
-    if (isset($_POST['add_forwarder'])){
-      if ($_POST['forward_address'] != ""){
-        $address= $_POST['forward_address'];
+
+    if($this->mailAddressSelect instanceOf mailAddressSelect){
+      $used  = array();
+      $used['mail'] = array_values($this->gosaMailAlternateAddress);  
+      $used['mail'] = array_merge($used['mail'], array_values($this->gosaMailForwardingAddress));  
+      $used['mail'][] = $this->mail;
+
+      // Build up blocklist
+      session::set('filterBlacklist', $used);
+      return($this->mailAddressSelect->execute());
+    }
+
+    if (isset($_POST['add_forwarder']) && isset($_POST['forward_address'])){
+      if (!empty($_POST['forward_address'])){
+        $address= get_post('forward_address');
         $valid= FALSE;
         if (!tests::is_email($address)){
           if (!tests::is_email($address, TRUE)){
@@ -308,7 +351,7 @@ class mailAccount extends plugin
             }
           }
         } elseif ($address == $this->mail
-            || in_array($address, $this->gosaMailAlternateAddress)) {
+            || in_array_strict($address, $this->gosaMailAlternateAddress)) {
           msg_dialog::display(_("Error"),_("Cannot add primary address to the list of forwarders!") , ERROR_DIALOG);
         } else {
           $valid= TRUE;
@@ -321,11 +364,12 @@ class mailAccount extends plugin
         }
       }
     }
-    if (isset($_POST['delete_forwarder'])){
+    if (isset($_POST['delete_forwarder']) && isset($_POST['forwarder_list'])){
       $this->delForwarder ($_POST['forwarder_list']);
     }
-    if ($this->forward_dialog){
-      return($this->display_forward_dialog());
+    if ($this->mailAddressSelect instanceOf mailAddressSelect){
+    
+      return($this->mailAddressSelect->execute());
     }
 
 
@@ -348,12 +392,16 @@ class mailAccount extends plugin
       } else {
         $valid= TRUE;
       }
-      if ($valid && ($user= $this->addAlternate ($_POST['alternate_address'])) != ""){
+      if ($valid && ($user= $this->addAlternate (get_post('alternate_address'))) != ""){
         $ui= get_userinfo();
-        if ($user != $ui->username){
-          msg_dialog::display(_("Error"), msgPool::duplicated(_("Mail address"))."&nbsp;".
-              sprintf(_("Address is already in use by user '%s'."), $user), ERROR_DIALOG);
+        $addon= "";
+        if ($user[0] == "!") {
+          $addon= sprintf(_("Address is already in use by group '%s'."), mb_substr($user, 1));
+        } else {
+          $addon= sprintf(_("Address is already in use by user '%s'."), $user);
         }
+        msg_dialog::display(_("Error"), msgPool::duplicated(_("Mail address"))."<br><br><i>".
+            "$addon</i>", ERROR_DIALOG);
       }
     }
     if (isset($_POST['delete_alternate']) && isset($_POST['alternates_list'])){
@@ -364,43 +412,39 @@ class mailAccount extends plugin
       SMARTY- Assign smarty variables 
      ****************/
     $smarty = get_smarty();
+
     $smarty->assign("initially_was_account", $this->initially_was_account);
     $smarty->assign("isModifyableMail"  , $this->mailMethod->isModifyableMail());
     $smarty->assign("isModifyableServer", $this->mailMethod->isModifyableServer());
     $smarty->assign("mailEqualsCN", $this->mailMethod->mailEqualsCN());
 
-    $SkipWrite = (!isset($this->parent) || !$this->parent) && !session::is_set('edit');
     $tmp  = $this->plInfo();
     foreach($tmp['plProvidedAcls'] as $name => $transl){
-      $smarty->assign("$name"."ACL", $this->getacl($name,$SkipWrite));
+      $smarty->assign("$name"."ACL", $this->getacl($name));
     }
     foreach($this->attributes as $attr){
-      $smarty->assign($attr,$this->$attr);
+      $smarty->assign($attr,set_post($this->$attr));
     }
     $smarty->assign("quotaEnabled", $this->mailMethod->quotaEnabled());
-    if($this->mailMethod->is_connected()){
-      $smarty->assign("quotaUsage",   $this->mailMethod->getQuotaUsage());
-    }else{
-      $smarty->assign("quotaUsage",   _("Unknown"));
+    if($this->mailMethod->quotaEnabled()){
+      $smarty->assign("quotaUsage",   mailMethod::quota_to_image($this->quotaUsage,$this->gosaMailQuota));
+      $smarty->assign("gosaMailQuota",set_post($this->gosaMailQuota));
     }
-    $smarty->assign("gosaMailQuota",$this->gosaMailQuota);
     $smarty->assign("domainSelectionEnabled", $this->mailMethod->domainSelectionEnabled());
-    $smarty->assign("MailDomains", $this->mailDomainParts);
-    $smarty->assign("MailDomain" , $this->mailDomainPart);
-    $smarty->assign("MailServers", $this->mailMethod->getMailServers());
+    $smarty->assign("MailDomains", set_post($this->mailDomainParts));
+    $smarty->assign("MailDomain" , set_post($this->mailDomainPart));
+    $smarty->assign("MailServers", set_post($this->mailMethod->getMailServers()));
     $smarty->assign("allowSieveManagement", $this->mailMethod->allowSieveManagement());
     $smarty->assign("own_script",  $this->sieveManagementUsed);
 
-    print_a($this->multi_boxes);
-
     /* _Multiple users vars_ */
     foreach($this->attributes as $attr){
       $u_attr = "use_".$attr;
-      $smarty->assign($u_attr,in_array($attr,$this->multi_boxes));
+      $smarty->assign($u_attr,in_array_strict($attr,$this->multi_boxes));
     }
     foreach(array("only_local","gosaMailForwardingAddress","use_mailsize_limit","drop_own_mails","use_vacation","use_spam_filter") as $attr){
       $u_attr = "use_".$attr;
-      $smarty->assign($u_attr,in_array($attr,$this->multi_boxes));
+      $smarty->assign($u_attr,in_array_strict($attr,$this->multi_boxes));
     }
 
 
@@ -435,9 +479,9 @@ class mailAccount extends plugin
     $smarty->assign("template", "");
     if (count($this->vacationTemplates)){
       $smarty->assign("show_templates", "true");
-      $smarty->assign("vacationtemplates", $this->vacationTemplates);
+      $smarty->assign("vacationtemplates", set_post($this->vacationTemplates));
       if (isset($_POST['vacation_template'])){
-        $smarty->assign("template", $_POST['vacation_template']);
+        $smarty->assign("template", set_post(get_post('vacation_template')));
       }
     } else {
       $smarty->assign("show_templates", "false");
@@ -447,44 +491,13 @@ class mailAccount extends plugin
      */
     if($this->mailMethod->vacationRangeEnabled()){
       $smarty->assign("rangeEnabled", TRUE);
-      if($this->gosaVacationStop ==0){
-        $date= getdate(time());
-        $date["mday"]++;
-      }else{
-        $date= getdate($this->gosaVacationStop);
-      }
-      $smarty->assign("end_day", $date["mday"]);
-      $smarty->assign("end_month", $date["mon"]-1);
-      $smarty->assign("end_year", $date["year"]);
-
-      if($this->gosaVacationStart == 0){
-        $date= getdate(time());
-      }else{
-        $date= getdate($this->gosaVacationStart);
-      }
-      $smarty->assign("start_day", $date["mday"]);
-      $smarty->assign("start_month", $date["mon"]-1);
-      $smarty->assign("start_year", $date["year"]);
-      $days= array();
-      for($d= 1; $d<32; $d++){
-        $days[$d]= $d;
-      }
-      $years= array();
-      for($y= $date['year']-10; $y<$date['year']+10; $y++){
-        $years[]= $y;
-      }
-      $months= msgPool::months();
-      $smarty->assign("months", $months);
-      $smarty->assign("years", $years);
-      $smarty->assign("days", $days);
-
     }
 
     /* fill filter settings 
      */
     $smarty->assign("spamlevel", $this->SpamLevels);
     $smarty->assign("spambox"  , $this->MailBoxes);
-
+    $smarty->assign("is_template", $this->is_template);
     $smarty->assign("multiple_support",$this->multiple_support_active);  
     return($display.$smarty->fetch(get_template_path("generic.tpl",TRUE,dirname(__FILE__))));
   }
@@ -501,18 +514,18 @@ class mailAccount extends plugin
       $server = $this->gosaMailServer;
       plugin::save_object();
 
-      if(!$this->mailMethod->isModifyableServer() && $this->initially_was_account){
+      if(!$this->mailMethod->isModifyableServer() && $this->initially_was_account && !$this->is_template){
         $this->gosaMailServer = $server;
       }
 
-      if(!$this->mailMethod->isModifyableMail() && $this->initially_was_account){
+      if(!$this->mailMethod->isModifyableMail() && $this->initially_was_account && !$this->is_template){
         $this->mail = $mail;
       }else{
 
         /* Get posted mail domain part, if necessary  
          */
         if($this->mailMethod->domainSelectionEnabled() && isset($_POST['MailDomain'])){
-          if(in_array(get_post('MailDomain'), $this->mailDomainParts)){
+          if(in_array_strict(get_post('MailDomain'), $this->mailDomainParts)){
             $this->mailDomainPart = get_post('MailDomain');
           }
         }
@@ -522,9 +535,9 @@ class mailAccount extends plugin
        */
       if (isset($_POST["import_vacation"]) && isset($this->vacationTemplates[$_POST["vacation_template"]])){
         if($this->multiple_support_active){
-          $contents = ltrim(preg_replace("/^DESC:.*$/m","",file_get_contents($_POST["vacation_template"])));
+          $contents = ltrim(preg_replace("/^DESC:.*$/m","",file_get_contents(get_post("vacation_template"))));
         }else{
-          $contents = $this->prepare_vacation_template(file_get_contents($_POST["vacation_template"]));
+          $contents = $this->prepare_vacation_template(file_get_contents(get_post("vacation_template")));
         }
         $this->gosaVacationMessage= htmlspecialchars($contents);
       }
@@ -584,13 +597,16 @@ class mailAccount extends plugin
           $this->is_modified= TRUE;
         }
         $this->gosaMailDeliveryMode= $tmp;
+
+        /* Get start/stop values for vacation scope of application
+         */
         if($this->mailMethod->vacationRangeEnabled()){
           if($this->acl_is_writeable("gosaVacationMessage") && preg_match("/V/",$this->gosaMailDeliveryMode)){
             if(isset($_POST['gosaVacationStart'])){
-              $this->gosaVacationStart = $_POST['gosaVacationStart'];
+              $this->gosaVacationStart = get_post('gosaVacationStart');
             }
             if(isset($_POST['gosaVacationStop'])){
-              $this->gosaVacationStop = $_POST['gosaVacationStop'];
+              $this->gosaVacationStop = get_post('gosaVacationStop');
             }
           }
         }
@@ -607,8 +623,8 @@ class mailAccount extends plugin
   function get_vacation_templates()
   {
     $vct = array();
-    if ($this->config->get_cfg_value("vacationTemplateDirectory") != ""){
-      $dir= $this->config->get_cfg_value("vacationTemplateDirectory");
+    if ($this->config->get_cfg_value("core","vacationTemplateDirectory") != ""){
+      $dir= $this->config->get_cfg_value("core","vacationTemplateDirectory");
       if (is_dir($dir) && is_readable($dir)){
         $dh = opendir($dir);
         while($file = readdir($dh)){
@@ -677,12 +693,15 @@ class mailAccount extends plugin
       /* Is this address already assigned in LDAP? */
       $ldap->cd ($this->config->current['BASE']);
       $ldap->search ("(&(!(objectClass=gosaUserTemplate))(objectClass=gosaMailAccount)(|(mail=$address)".
-          "(alias=$address)(gosaMailAlternateAddress=$address)))", array("uid"));
+          "(alias=$address)(gosaMailAlternateAddress=$address)))", array("uid", "cn"));
       if ($ldap->count() > 0){
         $attrs= $ldap->fetch ();
+        if (!isset($attrs["uid"])) {
+          return ("!".$attrs["cn"][0]);
+        }
         return ($attrs["uid"][0]);
       }
-      if (!in_array($address, $this->gosaMailAlternateAddress)){
+      if (!in_array_strict($address, $this->gosaMailAlternateAddress)){
         $this->gosaMailAlternateAddress[]= $address;
         $this->is_modified= TRUE;
       }
@@ -726,7 +745,29 @@ class mailAccount extends plugin
       $attrs  = $obj->attributes;
     }
     if($obj){
+
+      /* Replace vacation start and end time */
+      if($this->mailMethod->vacationRangeEnabled()){
+        if(preg_match("/%start/",$contents)){
+          $contents = preg_replace("/%start/",$this->gosaVacationStart,$contents);
+        }
+        if(preg_match("/%end/",$contents)){
+          $contents = preg_replace("/%end/",$this->gosaVacationStop,$contents);
+        }
+      }else{
+        if(preg_match("/%start/",$contents)){
+          $contents = preg_replace("/%start/", _("unknown"),$contents);
+        }
+        if(preg_match("/%end/",$contents)){
+          $contents = preg_replace("/%end/", _("unknown"), $contents);
+        }
+      }
+
       foreach ($attrs as $val){
+
+        // We can only replace strings here
+        if(!is_string($obj->$val)) continue;
+
         if(preg_match("/dateOfBirth/",$val)){
           if($obj->use_dob){
             $contents= preg_replace("/%$val/",date("Y-d-m",$obj->dateOfBirth),$contents);
@@ -736,13 +777,6 @@ class mailAccount extends plugin
               $obj->$val, $contents);
         }
 
-        /* Replace vacation start and end time */
-        if(preg_match("/%start/",$contents)){
-          $contents = preg_replace("/%start/",date("d.m.Y",$this->gosaVacationStart),$contents);
-        }
-        if(preg_match("/%end/",$contents)){
-          $contents = preg_replace("/%end/",date("d.m.Y",$this->gosaVacationStop),$contents);
-        }
       }
     }
     $contents = ltrim(preg_replace("/^DESC:.*$/m","",$contents),"\n ");
@@ -750,90 +784,6 @@ class mailAccount extends plugin
   }
 
 
-  /*! \brief  Displays a dialog that allows mail address selection.
-   */ 
-  function display_forward_dialog()
-  {
-    restore_error_handler();
-
-    $smarty = get_smarty();
-    $ldap= $this->config->get_ldap_link();
-
-    /* Save data */
-    $mailfilter= session::get("mailfilter");
-    foreach( array("depselect", "muser", "regex") as $type){
-      if (isset($_POST[$type])){
-        $mailfilter[$type]= $_POST[$type];
-      }
-    }
-    if (isset($_GET['search'])){
-      $s= mb_substr($_GET['search'], 0, 1, "UTF8")."*";
-      if ($s == "**"){
-        $s= "*";
-      }
-      $mailfilter['regex']= $s;
-    }
-    session::set("mailfilter", $mailfilter);
-
-    /* Get actual list */
-    $mailusers= array ();
-    if ($mailfilter['regex'] != '*' && $mailfilter['regex'] != ""){
-      $regex= $mailfilter['regex'];
-      $filter= "(|(mail=$regex)(gosaMailAlternateAddress=$regex))";
-    } else {
-      $filter= "";
-    }
-    if ($mailfilter['muser'] != ""){
-      $user= $mailfilter['muser'];
-      $filter= "$filter(|(uid=$user)(cn=$user)(givenName=$user)(sn=$user))";
-    }
-
-    /* Add already present people to the filter */
-    $exclude= "";
-    foreach ($this->gosaMailForwardingAddress as $mail){
-      $exclude.= "(mail=$mail)";
-    }
-    if ($exclude != ""){
-      $filter.= "(!(|$exclude))";
-    }
-    $res= get_list("(&(objectClass=gosaMailAccount)$filter)", "users", $mailfilter['depselect'],
-        array("sn", "mail", "givenName"), GL_SIZELIMIT | GL_SUBSEARCH);
-    $ldap->cd($mailfilter['depselect']);
-    $ldap->search ("(&(objectClass=gosaMailAccount)$filter)", array("sn", "mail", "givenName"));
-    while ($attrs= $ldap->fetch()){
-      if(preg_match('/%/', $attrs['mail'][0])){
-        continue;
-      }
-      $name= $this->make_name($attrs);
-      $mailusers[$attrs['mail'][0]]= $name."&lt;".
-        $attrs['mail'][0]."&gt;";
-    }
-    natcasesort ($mailusers);
-    reset ($mailusers);
-
-    /* Show dialog */
-    $smarty->assign("search_image", get_template_path('images/lists/search.png'));
-    $smarty->assign("usearch_image", get_template_path('images/lists/search-user.png'));
-    $smarty->assign("tree_image", get_template_path('images/lists/search-subtree.png'));
-    $smarty->assign("infoimage", get_template_path('images/info.png'));
-    $smarty->assign("launchimage", get_template_path('images/lists/action.png'));
-    $smarty->assign("mailusers", $mailusers);
-    if (isset($_POST['depselect'])){
-      $smarty->assign("depselect", $_POST['depselect']);
-    }
-    $smarty->assign("deplist", $this->config->idepartments);
-    $smarty->assign("apply", apply_filter());
-    $smarty->assign("alphabet", generate_alphabet());
-    $smarty->assign("hint", print_sizelimit_warning());
-    foreach( array("depselect", "muser", "regex") as $type){
-      $smarty->assign("$type", $mailfilter[$type]);
-    }
-    $smarty->assign("hint", print_sizelimit_warning());
-    $display= $smarty->fetch (get_template_path('mail_locals.tpl', TRUE, dirname(__FILE__)));
-    return ($display);
-  }
-
-
   /*! \brief  Removes the mailAccount extension from ldap 
    */  
   function remove_from_parent()
@@ -867,6 +817,16 @@ class mailAccount extends plugin
       } 
     }
 
+    // Do NOT remove the mail attribute while it is used in the Fax Account.
+    if(isset($this->parent->by_object['gofaxAccount'])){
+        $fax = $this->parent->by_object['gofaxAccount'];
+
+        // Fax delivery to the mail account is activated, keep the mail attribute.
+        if($fax->goFaxDeliveryMode & 32){
+           $this->attributes = array_remove_entries(array('mail'), $this->attributes)  ;
+        }
+    }
+
     /* Remove GOsa attributes */
     plugin::remove_from_parent();
 
@@ -942,6 +902,12 @@ class mailAccount extends plugin
     }elseif (!preg_match('/V/', $this->gosaMailDeliveryMode)){
       unset($this->attrs['gosaVacationStart']);
       unset($this->attrs['gosaVacationStop']);
+    } else {
+      /* Adapt values to be timestamps */
+      list($day, $month, $year)= explode('.', $this->gosaVacationStart);
+      $this->attrs['gosaVacationStart']= mktime(0,0,0,$month, $day, $year);
+      list($day, $month, $year)= explode('.', $this->gosaVacationStop);
+      $this->attrs['gosaVacationStop']= mktime(0,0,0,$month, $day, $year);
     }
 
     /* Map method attributes */ 
@@ -989,13 +955,15 @@ class mailAccount extends plugin
                 "Skipping sieve settings, the account doesn't seem to be created already.</b>","");
           }else{
             if(!$this->mailMethod->saveSieveSettings()){
-              msg_dialog::display(_("Mail error"), $this->mailMethod->get_error(), ERROR_DIALOG);
+              msg_dialog::display(_("Mail error saving sieve settings"), $this->mailMethod->get_error(), ERROR_DIALOG);
             }
           }
         }else{
-         echo "Check sieve management here";
-          @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__, 
-              "User uses an own sieve script, skipping sieve update.".$str."</b>","");
+          if ($this->sieve_management) {
+            @DEBUG (DEBUG_MAIL, __LINE__, __FUNCTION__, __FILE__, 
+                "User uses an own sieve script, skipping sieve update.".$str."</b>","");
+            $this->sieve_management->save();
+          }
         }
       }
     }
@@ -1061,7 +1029,7 @@ class mailAccount extends plugin
       }
       if ($this->is_template){
         if (!tests::is_email($mail, TRUE)){
-          $message[]= msgPool::invalid(_("Mail address"),"","","%givenName.%sn@your-domain.com");
+          $message[]= msgPool::invalid(_("Mail address"),"","","{%givenName}.{%sn}@your-domain.com");
         }
       } else {
         if (!tests::is_email($mail)){
@@ -1074,9 +1042,16 @@ class mailAccount extends plugin
       $filter = "(&(!(objectClass=gosaUserTemplate))(!(uid=".$this->uid."))".
         "(objectClass=gosaMailAccount)".
         "(|(mail=".$mail.")(alias=".$mail.")(gosaMailAlternateAddress=".$mail.")))";
-      $ldap->search($filter,array("uid"));
+      $ldap->search($filter,array("uid", "cn"));
       if ($ldap->count() != 0){
-        $message[]= msgPool::duplicated(_("Mail address"));
+        $entry= $ldap->fetch();
+        $addon= "";
+        if (!isset($entry['uid'])) {
+           $addon= sprintf(_("Address is already in use by group '%s'."), $entry['cn'][0]);
+        } else {
+           $addon= sprintf(_("Address is already in use by user '%s'."), $entry['uid'][0]);
+        }
+        $message[]= msgPool::duplicated(_("Mail address"))."<br><br><i>$addon</i>";
       }
     }
 
@@ -1108,10 +1083,29 @@ class mailAccount extends plugin
       $message[]= msgPool::required(_("Spam folder"));
     }
 
-    if ($this->mailMethod->vacationRangeEnabled() 
-        && preg_match('/V/', $this->gosaMailDeliveryMode) 
-        && $this->gosaVacationStart > $this->gosaVacationStop){
-      $message[]= msgPool::invalid(_("Vacation interval"));
+    if ($this->mailMethod->vacationRangeEnabled() && preg_match('/V/', $this->gosaMailDeliveryMode)){ 
+
+      /* Check date strings */
+      $state= true;
+      if ($this->gosaVacationStart == "" || !tests::is_date($this->gosaVacationStart)) {
+        $message[]= msgPool::invalid(_("from"),$this->gosaVacationStart);
+        $state= false;
+      }
+      if ($this->gosaVacationStart == "" || !tests::is_date($this->gosaVacationStop)) {
+        $message[]= msgPool::invalid(_("to"),$this->gosaVacationStop);
+        $state= false;
+      }
+
+      #TODO: take care of date format
+      if ($state) {
+        list($day, $month, $year)= explode('.', $this->gosaVacationStart);
+        $start= mktime(0,0,0,$month, $day, $year);
+        list($day, $month, $year)= explode('.', $this->gosaVacationStop);
+        $stop= mktime(0,0,0,$month, $day, $year);
+        if($start > $stop){
+          $message[]= msgPool::invalid(_("Vacation interval"));
+        }
+      }
     }
     return($message);
   }
@@ -1125,7 +1119,7 @@ class mailAccount extends plugin
 
     foreach (array("gosaMailAlternateAddress", "gosaMailForwardingAddress") as $val){
 
-      if (in_array($val, $skip)){
+      if (in_array_strict($val, $skip)){
         continue;
       }
 
@@ -1138,11 +1132,34 @@ class mailAccount extends plugin
               $value= preg_replace ("/%$repl/i", $this->parent->$repl, $value);
             }
           }
+            
+          // Remove non ASCII charcters
+          $value = iconv('UTF-8', 'US-ASCII//TRANSLIT', $value);
+          $value = preg_replace('/[^(\x20-\x7F)]*/','',$value);
+
+          // No spaces are allowed here
+          $value = preg_replace("/[ ]/","", $value);
           array_push($this->$val, strtolower(rewrite($value)));
         }
       }
     }
     $this->mail= strtolower(rewrite($this->mail));
+
+    // Remove non ASCII charcters
+    $this->mail= iconv('UTF-8', 'US-ASCII//TRANSLIT', $this->mail);
+    $this->mail= preg_replace('/[^(\x20-\x7F)]*/','',$this->mail);
+
+    // No spaces are allowed here
+    $this->mail = preg_replace("/[ ]/","", $this->mail);
+
+    // Fix mail address when using templates
+    if($this->is_account && $this->mailMethod->domainSelectionEnabled()){
+      $this->mailDomainPart = preg_replace("/^[^@]*+@/","",$this->mail);
+      $this->mail = preg_replace("/@.*$/","\\1",$this->mail);
+      if(!in_array_strict($this->mailDomainPart,$this->mailDomainParts)){
+        $this->mailDomainParts[] = $this->mailDomainPart;
+      }
+    }
   }
 
 
@@ -1150,42 +1167,69 @@ class mailAccount extends plugin
    */ 
   function getCopyDialog()
   {
-    if(!$this->is_account) return("");
-    $smarty = get_smarty();
-    $smarty->assign("mail",$this->mail);
-    $smarty->assign("gosaMailAlternateAddress",$this->gosaMailAlternateAddress);
-    $smarty->assign("gosaMailForwardingAddress",$this->gosaMailForwardingAddress);
+      if(!$this->is_account) return("");
+      $smarty = get_smarty();
+      $smarty->assign("mail",$this->mail);
+      $smarty->assign("gosaMailAlternateAddress",$this->gosaMailAlternateAddress);
+      $smarty->assign("gosaMailForwardingAddress",$this->gosaMailForwardingAddress);
+
+      $smarty->assign("domainSelectionEnabled", $this->mailMethod->domainSelectionEnabled());
+      $smarty->assign("MailDomains", $this->mailDomainParts);
+      $smarty->assign("MailDomain" , $this->mailDomainPart);
+      $smarty->assign("MailServers", $this->mailMethod->getMailServers());
+      $smarty->assign("isModifyableMail"  , $this->mailMethod->isModifyableMail());
+      $smarty->assign("initially_was_account", $this->initially_was_account);
+
     $str = $smarty->fetch(get_template_path("copypaste.tpl",TRUE, dirname(__FILE__)));
 
-    $ret = array();
-    $ret['status'] = "";
-    $ret['string'] = $str;
-    return($ret);
+      $ret = array();
+      $ret['status'] = "";
+      $ret['string'] = $str;
+      return($ret);
   }
 
-    
+
   /*! \brief  save_object for copy&paste vars 
    */  
   function saveCopyDialog()
   {
-    if(!$this->is_account) return;
+      if(!$this->is_account) return;
 
-    /* Execute to save mailAlternateAddress && gosaMailForwardingAddress */
-    $this->execute();
-    if(isset($_POST['mail'])){
-      $this->mail = $_POST['mail'];
-    }
+      /* Execute to save mailAlternateAddress && gosaMailForwardingAddress */
+      $this->execute();
+      if(isset($_POST['mail'])){
+          $this->mail = get_post('mail');
+      }
   }
 
-  
+
   /*! \brief  Prepare this account to be copied 
    */
   function PrepareForCopyPaste($source)
   {
-    plugin::PrepareForCopyPaste($source);
+      plugin::PrepareForCopyPaste($source);
+
+      /* Reset alternate mail addresses */
+      $this->gosaMailAlternateAddress = array();
+
 
-    /* Reset alternate mail addresses */
-    $this->gosaMailAlternateAddress = array();
+      /* If the doamin part is selectable, we have to split the mail address
+       */
+      if($this->mailMethod->domainSelectionEnabled()){
+          $this->mailDomainPart = preg_replace("/^[^@]*+@/","",$this->mail);
+          $this->mail = preg_replace("/@.*$/","\\1",$this->mail);
+          if(!in_array_strict($this->mailDomainPart,$this->mailDomainParts)){
+              $this->mailDomainParts[] = $this->mailDomainPart;
+          }
+      }
+
+      // Initialize Vacation start/stop times 
+      // This value is set to 'dd.mm.YYYY' if no times are set in the source object. 
+      // But if they are set, then this values contain timestamps.
+      if(isset($source['gosaVacationStart'][0])){
+          $this->gosaVacationStart= date('d.m.Y', $source['gosaVacationStart'][0]);
+          $this->gosaVacationStop= date('d.m.Y', $source['gosaVacationStop'][0]);
+      }
   }
 
 
@@ -1194,7 +1238,7 @@ class mailAccount extends plugin
   function get_multi_edit_values()
   {
     $ret = plugin::get_multi_edit_values();
-    if(in_array("gosaMailQuota",$this->multi_boxes)){
+    if(in_array_strict("gosaMailQuota",$this->multi_boxes)){
       $ret['gosaMailQuota'] = $this->gosaMailQuota;
     }
     $flag_add = $flag_remove = array();
@@ -1207,7 +1251,7 @@ class mailAccount extends plugin
         "C"   => "own_script",
         "I"   => "drop_own_mails");
     foreach($opts as $flag => $post){
-      if(in_array($post, $this->multi_boxes)){
+      if(in_array_strict($post, $this->multi_boxes)){
         if(preg_match("/".$flag."/",$tmp)){
           $flag_add[] = $flag;
         }else{
@@ -1218,12 +1262,10 @@ class mailAccount extends plugin
     $ret['flag_add'] = $flag_add;
     $ret['flag_remove'] = $flag_remove;
 
-    echo "1";
     if($this->mailMethod->vacationRangeEnabled()){
-      echo "2";
-      if(in_array("V",$flag_add)){
-        $ret['gosaVacationStart'] =  $this->gosaVacationStart = $_POST['gosaVacationStart'];
-        $ret['gosaVacationStop'] =  $this->gosaVacationStop = $_POST['gosaVacationStop'];
+      if(in_array_strict("V",$flag_add)){
+        $ret['gosaVacationStart'] =  $this->gosaVacationStart = get_post('gosaVacationStart');
+        $ret['gosaVacationStop'] =  $this->gosaVacationStop = get_post('gosaVacationStop');
       }
     }
     return($ret);
@@ -1236,12 +1278,12 @@ class mailAccount extends plugin
   {
     $message = plugin::multiple_check();
 
-    if(empty($this->gosaMailServer) && in_array("gosaMailServer",$this->multi_boxes)){
+    if(empty($this->gosaMailServer) && in_array_strict("gosaMailServer",$this->multi_boxes)){
       $message[]= msgPool::noserver(_("Mail"));
     }
 
     /* Check quota */
-    if ($this->gosaMailQuota != ''  && in_array("gosaMailQuota",$this->multi_boxes)){
+    if ($this->gosaMailQuota != ''  && in_array_strict("gosaMailQuota",$this->multi_boxes)){
       if (!is_numeric($this->gosaMailQuota)) {
         $message[]= msgPool::invalid(_("Quota size"),$this->gosaMailQuota,"/^[0-9]*/");
       } else {
@@ -1250,7 +1292,7 @@ class mailAccount extends plugin
     }
 
     /* Check rejectsize for integer */
-    if ($this->gosaMailMaxSize != '' && in_array("gosaMailMaxSize",$this->multi_boxes)){
+    if ($this->gosaMailMaxSize != '' && in_array_strict("gosaMailMaxSize",$this->multi_boxes)){
       if (!is_numeric($this->gosaMailMaxSize)){
         $message[]= msgPool::invalid(_("Mail reject size"),$this->gosaMailMaxSize,"/^[0-9]*/");
       } else {
@@ -1258,13 +1300,33 @@ class mailAccount extends plugin
       }
     }
 
-    if(empty($this->gosaSpamMailbox) && in_array("gosaSpamMailbox",$this->multi_boxes)){
+    if(empty($this->gosaSpamMailbox) && in_array_strict("gosaSpamMailbox",$this->multi_boxes)){
       $message[]= msgPool::required(_("Spam folder"));
     }
 
-    if (  in_array("use_vacation",$this->multi_boxes) &&
-        preg_match('/V/', $this->gosaMailDeliveryMode) && $this->gosaVacationStart > $this->gosaVacationStop){
-      $message[]= msgPool::invalid(_("Vacation interval"));
+    if ($this->mailMethod->vacationRangeEnabled() && preg_match('/V/', $this->gosaMailDeliveryMode)){ 
+
+      /* Check date strings */
+      $state= true;
+      if ($this->gosaVacationStart == "" || !tests::is_date($this->gosaVacationStart)) {
+        $message[]= msgPool::invalid(_("from"),$this->gosaVacationStart);
+        $state= false;
+      }
+      if ($this->gosaVacationStart == "" || !tests::is_date($this->gosaVacationStop)) {
+        $message[]= msgPool::invalid(_("to"),$this->gosaVacationStop);
+        $state= false;
+      }
+
+      #TODO: take care of date format
+      if ($state) {
+        list($day, $month, $year)= explode('.', $this->gosaVacationStart);
+        $start= mktime(0,0,0,$month, $day, $year);
+        list($day, $month, $year)= explode('.', $this->gosaVacationStop);
+        $stop= mktime(0,0,0,$month, $day, $year);
+        if($start > $stop){
+          $message[]= msgPool::invalid(_("Vacation interval"));
+        }
+      }
     }
     return($message);
   }
@@ -1382,41 +1444,71 @@ class mailAccount extends plugin
    */
   static function plInfo()
   {
-    return (array(
-          "plShortName"     => _("Mail"),
-          "plDescription"   => _("Mail settings"),
-          "plSelfModify"    => TRUE,
-          "plDepends"       => array("user"),                     // This plugin depends on
-          "plPriority"      => 4,                                 // Position in tabs
-          "plSection"     => array("personal" => _("My account")),
-          "plCategory"    => array("users"),
-          "plOptions"       => array(),
-
-          "plProvidedAcls"  => array(
-            "mail"                      =>  _("Mail address"),
-            "gosaMailServer"            =>  _("Mail server"),
-            "gosaMailQuota"             =>  _("Quota size"),
-
-            "gosaMailDeliveryModeV"     =>  _("Add vacation information"),  // This is flag of gosaMailDeliveryMode
-            "gosaVacationMessage"       =>  _("Vacation message"),
-
-            "gosaMailDeliveryModeS"     =>  _("Use spam filter"),           // This is flag of gosaMailDeliveryMode
-            "gosaSpamSortLevel"         =>  _("Spam level"),
-            "gosaSpamMailbox"           =>  _("Spam mail box"),
-
-            "sieveManagement"           =>  _("Sieve management"),
-
-            "gosaMailDeliveryModeR"     =>  _("Reject due to mailsize"),    // This is flag of gosaMailDeliveryMode
-            "gosaMailMaxSize"           =>  _("Mail max size"),
-
-            "gosaMailForwardingAddress" =>  _("Forwarding address"),
-            "gosaMailDeliveryModeL"     =>  _("Local delivery"),            // This is flag of gosaMailDeliveryMode
-            "gosaMailDeliveryModeI"     =>  _("No delivery to own mailbox "),     // This is flag of gosaMailDeliveryMode
-            "gosaMailAlternateAddress"  =>  _("Mail alternative addresses"),
-
-            "gosaMailForwardingAddress" =>  _("Forwarding address"),
-            "gosaMailDeliveryModeC"     =>  _("Use custom sieve script"))   // This is flag of gosaMailDeliveryMode
-              ));
+      return (array(
+                  "plShortName"     => _("Mail"),
+                  "plDescription"   => _("Mail settings"),
+                  "plSelfModify"    => TRUE,
+                  "plDepends"       => array("user"),                     // This plugin depends on
+                  "plPriority"      => 4,                                 // Position in tabs
+                  "plSection"     => array("personal" => _("My account")),
+                  "plCategory"    => array("users"),
+                  "plOptions"       => array(),
+
+                  "plRequirements"=> array(
+                      'ldapSchema' => array('gosaMailAccount' => '>=2.7'),
+                      'onFailureDisablePlugin' => array(get_class())
+                      ),
+    
+                  "plProperties"  =>
+                  array(
+                      array(
+                          "name"          => "cyrusDeleteMailbox",
+                          "type"          => "bool",
+                          "default"       => 'true',
+                          "description"   => _("Remove mail boxes from the IMAP storage after they their user gets removed."),
+                          "check"         => "gosaProperty::isBool",
+                          "migrate"       => "",
+                          "group"         => "mail",
+                          "mandatory"     => FALSE
+                          ),
+                      array(
+                          "name"          => "cyrusAutocreateFolders",
+                          "type"          => "string",
+                          "default"       => "",
+                          "description"   => _("Comma separated list of folders to be automatically created on user creation."),
+                          "check"         => "gosaProperty::isString",
+                          "migrate"       => "",
+                          "group"         => "mail",
+                          "mandatory"     => FALSE
+                          )
+                          ),
+
+
+                      "plProvidedAcls"  => array(
+                              "mail"                      =>  _("Mail address"),
+                              "gosaMailServer"            =>  _("Mail server"),
+                              "gosaMailQuota"             =>  _("Quota size"),
+
+                              "gosaMailDeliveryModeV"     =>  _("Add vacation information"),  // This is flag of gosaMailDeliveryMode
+                              "gosaVacationMessage"       =>  _("Vacation message"),
+
+                              "gosaMailDeliveryModeS"     =>  _("Use SPAM filter"),           // This is flag of gosaMailDeliveryMode
+                              "gosaSpamSortLevel"         =>  _("SPAM level"),
+                              "gosaSpamMailbox"           =>  _("SPAM mail box"),
+
+                              "sieveManagement"           =>  _("Sieve management"),
+
+                              "gosaMailDeliveryModeR"     =>  _("Reject due to mail size"),    // This is flag of gosaMailDeliveryMode
+                              "gosaMailMaxSize"           =>  _("Mail max size"),
+
+                              "gosaMailForwardingAddress" =>  _("Forwarding address"),
+                              "gosaMailDeliveryModeL"     =>  _("Local delivery"),            // This is flag of gosaMailDeliveryMode
+                              "gosaMailDeliveryModeI"     =>  _("No delivery to own mailbox "),     // This is flag of gosaMailDeliveryMode
+                              "gosaMailAlternateAddress"  =>  _("Mail alternative addresses"),
+
+                              "gosaMailForwardingAddress" =>  _("Forwarding address"),
+                              "gosaMailDeliveryModeC"     =>  _("Use custom sieve script"))   // This is flag of gosaMailDeliveryMode
+                                  ));
   }