Code

Updated table summary
[gosa.git] / gosa-plugins / mail / personal / mail / class_mailAccount.inc
index 147802851934d2613dc958147301fb05976c17ea..5be08f55851775a09c7fd643d8aca6760119ac26 100644 (file)
@@ -23,7 +23,6 @@ Functions :
  - addAlternate($address)
  - delAlternate($addresses)
  - prepare_vacation_template($contents)
- - display_forward_dialog()
  - remove_from_parent()
  - save()
  - check()
@@ -55,8 +54,8 @@ class mailAccount extends plugin
 
   /* 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 +67,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 +90,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 +122,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();
     }
@@ -126,23 +141,24 @@ class mailAccount extends plugin
 
         /* 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! Error was: %s."), 
+          msg_dialog::display(_("Mail error"), sprintf(_("Cannot read quota settings: %s"), 
                 $this->mailMethod->get_error()), ERROR_DIALOG);
         }
         
         /* Read mailboxes */
         $this->MailBoxes = $this->mailMethod->getMailboxList($this->MailBoxes);
         if($this->mailMethod->is_error()){
-          msg_dialog::display(_("Mail error"), sprintf(_("Cannot get list of mailboxes! Error was: %s."), 
+          msg_dialog::display(_("Mail error"), sprintf(_("Cannot get list of mailboxes: %s"), 
                 $this->mailMethod->get_error()), ERROR_DIALOG);
         }
           
       }elseif(!$this->mailMethod->is_connected()){
-        msg_dialog::display(_("Mail error"), sprintf(_("Cannot connect mail method! Error was: %s."), 
+        msg_dialog::display(_("Mail error"), sprintf(_("Mail method cannot connect: %s"), 
               $this->mailMethod->get_error()), ERROR_DIALOG);
       }elseif(!$this->mailMethod->account_exists()){
-        msg_dialog::display(_("Mail error"), sprintf(_("Mailbox '%s' doesn't exists on mail server: %s."), 
+        msg_dialog::display(_("Mail error"), sprintf(_("Mailbox '%s' doesn't exists on mail server: %s"), 
               $this->mailMethod->get_account_id(),$this->gosaMailServer), ERROR_DIALOG);
       }
 
@@ -175,25 +191,20 @@ 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);
   }
 
 
   function execute()
   {
+
     /* Call parent execute */
     $display = plugin::execute();
 
@@ -233,9 +244,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);
         }
@@ -268,31 +279,45 @@ 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 ($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($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'])){
       if ($_POST['forward_address'] != ""){
         $address= $_POST['forward_address'];
@@ -323,8 +348,9 @@ class mailAccount extends plugin
     if (isset($_POST['delete_forwarder'])){
       $this->delForwarder ($_POST['forwarder_list']);
     }
-    if ($this->forward_dialog){
-      return($this->display_forward_dialog());
+    if ($this->mailAddressSelect instanceOf mailAddressSelect){
+    
+      return($this->mailAddressSelect->execute());
     }
 
 
@@ -349,10 +375,14 @@ class mailAccount extends plugin
       }
       if ($valid && ($user= $this->addAlternate ($_POST['alternate_address'])) != ""){
         $ui= get_userinfo();
-        if ($user != $ui->username){
-          msg_dialog::display(_("Error"), msgPool::duplicated(_("Mail address"))." ".
-              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'])){
@@ -363,25 +393,24 @@ class mailAccount extends plugin
       SMARTY- Assign smarty variables 
      ****************/
     $smarty = get_smarty();
+    $smarty->assign("usePrototype", "true");
     $smarty->assign("initially_was_account", $this->initially_was_account);
-    $smarty->assign("isModifyableMail", $this->mailMethod->isModifyableMail());
+    $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("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",$this->gosaMailQuota);
     }
-    $smarty->assign("gosaMailQuota",$this->gosaMailQuota);
     $smarty->assign("domainSelectionEnabled", $this->mailMethod->domainSelectionEnabled());
     $smarty->assign("MailDomains", $this->mailDomainParts);
     $smarty->assign("MailDomain" , $this->mailDomainPart);
@@ -389,8 +418,6 @@ class mailAccount extends plugin
     $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;
@@ -445,37 +472,6 @@ 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 
@@ -495,9 +491,14 @@ class mailAccount extends plugin
     if (isset($_POST['mailTab'])){
 
       /* Save ldap attributes */
-      $mail = $this->mail;
+      $mail   = $this->mail;
+      $server = $this->gosaMailServer;
       plugin::save_object();
 
+      if(!$this->mailMethod->isModifyableServer() && $this->initially_was_account){
+        $this->gosaMailServer = $server;
+      }
+
       if(!$this->mailMethod->isModifyableMail() && $this->initially_was_account){
         $this->mail = $mail;
       }else{
@@ -577,6 +578,9 @@ 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'])){
@@ -670,9 +674,12 @@ 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)){
@@ -719,7 +726,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);
@@ -729,13 +758,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 ");
@@ -743,90 +765,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()
@@ -841,6 +779,25 @@ class mailAccount extends plugin
       $this->mail = $this->mail."@".$this->mailDomainPart;
     }
 
+    /* Update sharedFolder dependencies. 
+       Open each shared folder and remove this account. 
+       Then Save the group to ensure that all necessary 
+        actions will be taken (imap acls updated aso.).
+     */
+    $ldap = $this->config->get_ldap_link();    
+    $ldap->cd($this->config->current['BASE']);
+    $ldap->search("(&(objectClass=posixGroup)(objectClass=gosaMailAccount)(memberUid=".$this->uid."))",array("dn"));
+    while($attrs = $ldap->fetch()){
+      $grp = new grouptabs($this->config, $this->config->data['TABS']['GROUPTABS'], $attrs['dn']);
+      if(isset($grp->by_object['mailgroup']) && isset($grp->by_object['group'])){
+        $grp->by_object['group']->removeUser($this->uid);
+
+        /* Do not save the complete group! This will quit the complete membership 
+         */
+        $grp->by_object['mailgroup']->save();
+      } 
+    }
+
     /* Remove GOsa attributes */
     plugin::remove_from_parent();
 
@@ -869,15 +826,11 @@ class mailAccount extends plugin
     if (!$this->is_template){
 
       if(!$this->mailMethod->connect()){
-        msg_dialog::display(_("Mail error"), sprintf(_("Cannot connect mail method! Error was: %s."), 
+        msg_dialog::display(_("Mail error"), sprintf(_("Mail method cannot connect: %s"), 
               $this->mailMethod->get_error()), ERROR_DIALOG);
       }else{
         if(!$this->mailMethod->deleteMailbox()){
-          msg_dialog::display(_("Mail error"), sprintf(_("Cannot remove mailbox! Error was: %s."), 
-                $this->mailMethod->get_error()), ERROR_DIALOG);
-        }
-        if(!$this->mailMethod->updateSharedFolder()){
-          msg_dialog::display(_("Mail error"), sprintf(_("Cannot update shared folder permissions! Error was: %s."), 
+          msg_dialog::display(_("Mail error"), sprintf(_("Cannot remove mailbox: %s"), 
                 $this->mailMethod->get_error()), ERROR_DIALOG);
         }
       }
@@ -920,6 +873,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 */ 
@@ -929,8 +888,6 @@ class mailAccount extends plugin
     $ldap->cd($this->dn);
     $this->cleanup();
     $ldap->modify ($this->attrs);
-  
-
 
     if (!$ldap->success()){
       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_MOD, get_class()));
@@ -947,21 +904,20 @@ class mailAccount extends plugin
     if (!$this->is_template){
       $this->mailMethod->connect();
       if(!$this->mailMethod->is_connected()){
-        msg_dialog::display(_("Mail error"), sprintf(_("Cannot connect mail method! Error was: %s."), 
+        msg_dialog::display(_("Mail error"), sprintf(_("Mail method cannot connect: %s"), 
               $this->mailMethod->get_error()), ERROR_DIALOG);
       }else{
         if(!$this->mailMethod->updateMailbox()){
-          msg_dialog::display(_("Mail error"), sprintf(_("Cannot update mailbox! Error was: %s."), 
+          msg_dialog::display(_("Mail error"), sprintf(_("Cannot update mailbox: %s"), 
                 $this->mailMethod->get_error()), ERROR_DIALOG);
         }
         if(!$this->mailMethod->setQuota($this->gosaMailQuota)){
-          msg_dialog::display(_("Mail error"), sprintf(_("Cannot write quota settings! Error was: %s."), 
+          msg_dialog::display(_("Mail error"), sprintf(_("Cannot write quota settings: %s"), 
                 $this->mailMethod->get_error()), ERROR_DIALOG);
         }
 
         if (!is_integer(strpos($this->gosaMailDeliveryMode, "C"))){
 
-
           /* Do not write sieve settings if this account is new and 
              doesn't seem to exist.
            */
@@ -970,24 +926,38 @@ 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();
+          }
         }
+      }
+    }
+    $this->mailMethod->disconnect();
 
-        if(!$this->mailMethod->updateSharedFolder()){
-          msg_dialog::display(_("Mail error"), sprintf(_("Cannot update shared folder permissions! Error was: %s."), 
-                $this->mailMethod->get_error()), ERROR_DIALOG);
+    /* Update sharedFolder dependencies.
+       Open each shared folder and remove this account.
+       Then Save the group to ensure that all necessary
+       actions will be taken (imap acls updated aso.).
+     */
+    if(!$this->initially_was_account){
+      $ldap = $this->config->get_ldap_link();
+      $ldap->cd($this->config->current['BASE']);
+      $ldap->search("(&(objectClass=posixGroup)(objectClass=gosaMailAccount)(memberUid=".$this->uid."))",array("dn"));
+      while($attrs = $ldap->fetch()){
+        $grp = new grouptabs($this->config, $this->config->data['TABS']['GROUPTABS'], $attrs['dn']);
+        if(isset($grp->by_object['mailgroup'])){
+          /* Do not save the complete group! This will quit the complete membership
+           */
+          $grp->by_object['mailgroup']->save();
         }
       }
     }
-    $this->mailMethod->disconnect();
 
     /* Optionally execute a command after we're done */
     if ($this->initially_was_account == $this->is_account){
@@ -1043,9 +1013,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>";
       }
     }
 
@@ -1077,10 +1054,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);
   }
@@ -1112,6 +1108,15 @@ class mailAccount extends plugin
       }
     }
     $this->mail= strtolower(rewrite($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($this->mailDomainPart,$this->mailDomainParts)){
+        $this->mailDomainParts[] = $this->mailDomainPart;
+      }
+    }
   }
 
 
@@ -1187,9 +1192,7 @@ 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'];
@@ -1231,9 +1234,29 @@ class mailAccount extends plugin
       $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);
   }
@@ -1336,6 +1359,17 @@ class mailAccount extends plugin
   }
 
 
+  function allow_remove()
+  {
+    $resason = "";
+    if(!$this->mailMethod->allow_remove($reason)){
+      return($reason);
+    }
+    return("");
+  }
+
+
+
   /*! \brief  ACL settings 
    */
   static function plInfo()