Code

Updated trunk, introduced gosa-core
[gosa.git] / plugins / admin / users / class_userManagement.inc
index e77badd5531abb7be536650c30b4bdf3717fe15e..a031e89d9f783a2cbb19272ea867938b1bde2c65 100644 (file)
@@ -1,7 +1,7 @@
 <?php
 /*
    This code is part of GOsa (https://gosa.gonicus.de)
-   Copyright (C) 2003  Cajus Pollmeier
+   Copyright (C) 2003-2006 - Cajus Pollmeier <pollmeier@gonicus.de>
 
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  */
-require "tabs_user.inc";
 
 class userManagement extends plugin
 {
-  /* Definitions */
+  /* Plugin definitions */
   var $plHeadline= "Users";
   var $plDescription= "This does something";
 
   /* Dialog attributes */
-  var $usertab= NULL;
-  var $userlist= array();
-  var $ui= NULL;
-  var $acl= "";
-  var $templates= array();
-  var $got_uid= false;
-  var $departments=array();
-
-  function userManagement ($config, $ui)
+  var $usertab              = NULL;
+  var $ui                   = NULL;
+  var $templates            = array();
+  var $got_uid              = false;
+  var $CopyPasteHandler     = NULL;
+  var $CPPasswordChange     = ""; // Contains the entry id which should get a new password
+  var $DivListUsers;
+
+  var $pwd_change_queue     = array();
+
+  var $start_pasting_copied_objects = FALSE;
+  var $current_action ="";
+  var $msg_dialog= NULL;
+  
+  function userManagement(&$config, $ui)
   {
     /* Save configuration for internal use */
-    $this->config= $config;
-    $this->ui= $ui;
-
-    /* Get global filter config */
-    if (!isset($_SESSION["userfilter"])){
-      $base= get_base_from_people($ui->dn);
-      $userfilter= array( "mailusers"       => "checked",
-          "unixusers"       => "checked",
-          "templates"       => "",
-          "subsearch"       => "",
-          "proxyusers"      => "checked",
-          "sambausers"      => "checked",
-          "faxusers"        => "checked",
-          "functionalusers" => "checked",
-          "depselect"       => $base,
-          "regex"           => "*");
-      $_SESSION["userfilter"] = $userfilter;
+    $this->config= &$config;
+    $this->ui= &$ui;
+
+    /* Copy & Paste handler */
+    if ($this->config->boolValueIsTrue("main", "enableCopyPaste")){
+      $this->CopyPasteHandler= new CopyPasteHandler($this->config);
     }
+
+    /* Creat dialog object */
+    $this->DivListUsers = new divListUsers($this->config,$this);
+
   }
 
+
   function execute()
   {
-       /* Call parent execute */
-       plugin::execute();
-
-    $smarty       = get_smarty();             // Smarty instance
-    $userfilter   = get_global("userfilter"); // contains Filter Settings
-    $s_action     = "";                       // Contains the action to proceed
-    $s_entry      = "";                       // The value for s_action
-    $base_back    = "";                       // The Link for Backbutton
-
-    /* Start for New List Managment */
-    if(isset($_GET['act'])&&($_GET['act']=="dep_open")){
-      $s_action="open";
-      $s_entry = base64_decode($_GET['dep_id']);
-      $userfilter['depselect']= "".$this->config->departments[trim($s_entry)];
-    }
+    /* Call parent execute */
+    plugin::execute();
 
-    /* Test Posts */  
-    foreach($_POST as $key => $val){
-      // Post for delete
-      if(preg_match("/user_del.*/",$key)){
-        $s_action = "del";
-        $s_entry  = preg_replace("/user_".$s_action."_/i","",$key);
-        // Post for edit
-      }elseif(preg_match("/user_edit_.*/",$key)){
-        $s_action="edit";
-        $s_entry  = preg_replace("/user_".$s_action."_/i","",$key);
-        // Post for new
-      }elseif(preg_match("/dep_back.*/i",$key)){
-        $s_action="back";
-      }elseif(preg_match("/user_new.*/",$key)){
-        $s_action="new";
-      }elseif(preg_match("/dep_home.*/i",$key)){
-        $s_action="home";
-      }elseif(preg_match("/user_tplnew.*/i",$key)){
-        $s_action="new_tpl";
-      }elseif(preg_match("/user_chgpw.*/i",$key)){
-        $s_action="change_pw";
-        $s_entry  = preg_replace("/user_chgpw_/i","",$key);
-      }elseif(preg_match("/dep_root.*/i",$key)){
-        $s_action="root";
-      }elseif(preg_match("/userfrom_tpl.*/i",$key)){
-        $s_action="create_user_from_tpl";
-        $s_entry  = preg_replace("/userfrom_tpl_/i","",$key);
-      }
-    }
+    /* LOCK MESSAGE Vars */
+    $_SESSION['LOCK_VARS_TO_USE'] = array("/^act$/","/^id$/","/^user_edit_/","/^user_del_/","/^item_selected/","/^remove_multiple_users/","/^multiple_edit/","/menu_action/");
 
-    if((isset($_GET['act']))&&($_GET['act']=="edit_entry")){
-      $s_action = "edit";
-      $s_entry  = $_GET['id'];
+    $smarty       = get_smarty();                 // Smarty instance
+    $s_action     = "";                           // Contains the action to be taken
+    $s_entry      = "";                           // The value for s_action
+
+    /* Edit entry button pressed? */
+    if( isset($_GET['act']) && $_GET['act'] == "edit_entry" ){
+      $s_action= "edit";
+      $s_entry= validate($_GET['id']);
     }
 
-    $s_entry  = preg_replace("/_.$/","",$s_entry);
+    /* Test relevant POST values */  
+    foreach($_POST as $key => $val){
 
-    if(preg_match("/.*-.*/",$s_entry)){
-      $s_tab   = preg_replace("/^.*-/i","",$s_entry);
-      $s_entry = preg_replace("/-.*$/i","",$s_entry);
-    }else{
-      $s_tab   = "user";
-    };
+      /* Get every possible POST combination and set s_action/s_entry accordingly */
+      foreach(array("del"       => "user_del",    
+                    "edit"      => "user_edit",
+                    "new"       => "user_new",
+                    "new_tpl"   => "user_tplnew",
+                    "del_multiple" => "^remove_multiple_users",
+                    "create_user_from_tpl"          => "userfrom_tpl",
+                    "change_pw" => "user_chgpw", 
+                    "editPaste" => "editPaste",  
+                    "copy_multiple" => "multiple_copy_users",
+                    "multiple_edit" => "multiple_edit",
+                    "cut_multiple" => "multiple_cut_users",
+                    "multiple_password_change" => "multiple_password_change",
+                    "copy"      => "^copy",
+                    "toggle_lock_status" => "toggle_lock_status",
+                    "cut"       => "^cut") as $act => $name){
+
+        if (preg_match("/".$name.".*/", $key)){
+          $s_action= $act;
+          $s_entry= preg_replace("/".$name."_/i", "", $key);
+          break;
+        }
+      }
+      
+    } /* ...Test POST */
 
-    /* Department changed? */
-    if(isset($_POST['depselect']) && $_POST['depselect']){
-      $userfilter['depselect']= $_POST['depselect'];
-    }
+    /* Remove coordinate prefix from POST, required by some browsers */
+    $s_entry= preg_replace("/_.$/", "", $s_entry);
 
-    /* Homebutton is posted */
-    if($s_action=="home"){
-      $userfilter['depselect']=(preg_replace("/^[^,]+,/","",$this->ui->dn));
-      $userfilter['depselect']=(preg_replace("/^[^,]+,/","",$userfilter['depselect']));
+    /* Seperate possibly encoded tab and entry, default to tab "user" */
+    if(preg_match("/.*-.*/", $s_entry)){
+      $s_tab= preg_replace("/^[^-]*-/i", "" ,$s_entry);
+      $s_entry= preg_replace("/-[^-]*$/i", "", $s_entry);
+    }else{
+      $s_tab= "user";
     }
 
-    if($s_action=="root"){
-      $userfilter['depselect']=($this->config->current['BASE']);
+    if(!$this->config->search($s_tab, 'class',array('tabs'))){
+      $s_tab = "user";
     }
 
 
-    /* If Backbutton is Posted */
-    if($s_action=="back"){
-      $base_back          = preg_replace("/^[^,]+,/","",$userfilter['depselect']);
-      $base_back          = convert_department_dn($base_back);
-
-      if(isset($this->config->departments[trim($base_back)])){
-        $userfilter['depselect']= $this->config->departments[trim($base_back)];
-      }else{
-        $userfilter['depselect']= $this->config->departments["/"];
-      }
+    /* handle C&P from layers menu */
+    if(isset($_POST['menu_action']) && preg_match("/^multiple_copy_systems/",$_POST['menu_action'])){
+      $s_action = "copy_multiple";
+    }
+    if(isset($_POST['menu_action']) && preg_match("/^multiple_cut_systems/",$_POST['menu_action'])){
+      $s_action = "cut_multiple";
+    }
+    if(isset($_POST['menu_action']) && preg_match("/^editPaste/",$_POST['menu_action'])){
+      $s_action = "editPaste";
     }
 
-    /* End for new List Managment */
-
-    /* Save filter data if we are in the headpage */
-    if (!isset($this->usertab)){
-      if (isset($_POST['regexit'])){
-        $userfilter["regex"]= $_POST['regexit'];
-      }
+    /* Create options */
+    if(isset($_POST['menu_action']) && $_POST['menu_action'] == "user_new"){
+      $s_action = "new";
     }
-    if(isset($_POST['regexit'])){
-      foreach( array("functionalusers", "unixusers", "mailusers","sambausers", "proxyusers", "faxusers", "templates", "subsearch") as $type){
-        if (isset($_POST[$type])) {
-          $userfilter[$type]= "checked";
-        } else {
-          $userfilter[$type]= "";
-        }
-      }
+    if(isset($_POST['menu_action']) && $_POST['menu_action'] == "user_tplnew"){
+      $s_action = "new_tpl";
     }
-    if (isset($_GET['search'])){
-      $s= mb_substr($_GET['search'], 0, 1, "UTF8")."*";
-      if ($s == "**"){
-        $s= "*";
-      }
-      $userfilter['regex']= $s;
+    if(isset($_POST['menu_action']) && $_POST['menu_action'] == "multiple_edit"){
+      $s_action = "multiple_edit";
     }
-    register_global("userfilter", $userfilter);
-
-
-    /* React on user interaction here */
-    if (($_SERVER["REQUEST_METHOD"] == "POST")||($_SERVER["REQUEST_METHOD"]== "GET")){
-
-      /* User wants to edit data? */
-      if ($s_action=="edit"){
-
-        /* Get 'dn' from posted 'uid', must be unique */
-
-        $this->dn= $this->list[trim($s_entry)]['dn'];
-
-        /* Check locking, save current plugin in 'back_plugin', so
-           the dialog knows where to return. */
-        if (($user= get_lock($this->dn)) != ""){
-          return(gen_locked_message ($user, $this->dn));
-        }
 
-        /* Lock the current entry, so everyone will get the
-           above dialog */
-        add_lock ($this->dn, $this->ui->dn);
-
-        /* Set up the users ACL's for this 'dn' */
-        $acl= get_permissions ($this->dn, $this->ui->subtreeACL);
-
-        /* Register usertab to trigger edit dialog */
-        $this->usertab= new usertabs($this->config, 
-            $this->config->data['TABS']['USERTABS'], $this->dn);
-        //        $_POST[$s_tab]=$s_tab;
-
-        // This would be better
-        $this->usertab->current = $s_tab;
-        $this->usertab->set_acl($acl);
-
-        $_SESSION['objectinfo']= $this->dn;
-      }
+    /* handle remove from layers menu */
+    if(isset($_POST['menu_action']) && preg_match("/^multiple_password_change/",$_POST['menu_action'])){
+      $s_action = "multiple_password_change";
     }
 
-    /* Reset requested? */
-    if (isset($_POST['edit_cancel']) || isset($_POST['password_cancel'])){
-      if (isset($this->usertab)){
-        del_lock ($this->usertab->dn);
-        unset ($this->usertab);
-      }
-      $this->usertab= NULL;
-      $this->lognames= array();;
-      $this->sn= "";
-      $this->givenName= "";
-      $this->uid= "";
-      unset ($_SESSION['objectinfo']);
+    /* handle remove from layers menu */
+    if(isset($_POST['menu_action']) && preg_match("/^remove_multiple/",$_POST['menu_action'])){
+      $s_action = "del_multiple";
     }
 
-    /* Password change requested */
-    if ($s_action=="change_pw"){
-
-      /* Get 'dn' from posted 'uid' */
-      $this->dn= $this->list[trim($s_entry)]['dn'];
 
-      /* Load permissions for selected 'dn' and check if
-         we're allowed to remove this 'dn' */
-      $acl= get_permissions ($this->dn, $this->ui->subtreeACL);
-      $acl= get_module_permission($acl, "user", $this->dn);
-      if (chkacl($acl, "password") == ""){
+    /********************
+      Copy & Paste 
+     ********************/
 
-        /* User is allowed to change passwords, save 'dn' and 'acl' for next
-           dialog. */
-        $this->acl= $acl;
-        $_SESSION['objectinfo']= $this->dn;
-        return ($smarty->fetch(get_template_path('password.tpl', TRUE)));
-
-      } else {
-        /* User is not allowed. Show message and cancel. */
-        print_red (_("You are not allowed to set this users password!"));
+    /* Display the copy & paste dialog, if it is currently open */
+    if($this->CPPasswordChange == ""){
+      $ret = $this->copyPasteHandling_from_queue($s_action,$s_entry);
+      if($ret){
+        return($ret);
       }
     }
 
+
+    /********************
+      Change password confirmed
+     ********************/
+
     /* Perform password change */
     if (isset($_POST['password_finish'])){
 
       /* For security reasons, check if user is allowed to set password again */
-      if (chkacl($this->acl, "password") == "" || chkacl($this->acl, "create")){
+      $dn  = $this->dn;
+      $acl = $this->ui->get_permissions($dn, "users/password");
+      $cacl= $this->ui->get_permissions($dn, "users/user");
+
+      if (preg_match('/w/', $acl) || preg_match('/c/', $cacl)){
 
         /* Check input and feed errors into 'message' */
         $message= array();
@@ -270,7 +195,7 @@ class userManagement extends plugin
           }
         }
 
-        /* Errors, or change password? */
+        /* Errors, or password change? */
         if (count($message) != 0){
 
           /* Show error message and continue editing */
@@ -281,9 +206,11 @@ class userManagement extends plugin
         $config= $this->config;
         $ldap_ui= $this->config->get_ldap_link();
         if(isset($this->usertab->dn)){
-          $user = ($ldap_ui->fetch($ldap_ui->cat($this->usertab->dn)));
+          $ldap_ui->cat($this->usertab->dn,array("uid"));
+          $user = $ldap_ui->fetch();
         }else{
-          $user = ($ldap_ui->fetch($ldap_ui->cat($this->dn)));
+          $ldap_ui->cat($this->dn,array("uid"));
+          $user = $ldap_ui->fetch();
         }
         if((is_array($user))&&(isset($user['uid']))){
           $username= $user['uid'][0];
@@ -293,13 +220,11 @@ class userManagement extends plugin
         if ($this->usertab){
           if ($this->usertab->password_change_needed()){
             $obj= $this->usertab->by_object['user'];
-            change_password ($this->usertab->dn, $_POST['new_password'],
-                0, $obj->pw_storage);
+            change_password ($this->usertab->dn, $_POST['new_password'],0, $obj->pw_storage);
             if (isset($config->data['MAIN']['EXTERNALPWDHOOK'])){
               exec($config->data['MAIN']['EXTERNALPWDHOOK']." ".$username." ".$_POST['new_password'], $resarr);
             }
-
-            gosa_log ("Password for '".$this->usertab->dn."' has been changed");
+            new log("modify","users/".get_class($this),$this->usertab->dn,array(),"Password has been changed");
             unset($this->usertab);
             $this->usertab= NULL;
           }
@@ -308,18 +233,15 @@ class userManagement extends plugin
           if (isset($config->data['MAIN']['EXTERNALPWDHOOK'])){
             exec($config->data['MAIN']['EXTERNALPWDHOOK']." ".$username." ".$_POST['new_password'], $resarr);
           }
-
-          gosa_log ("Password for '".$this->dn."' has been changed");
+          new log("modify","users/".get_class($this),$this->dn,array(),"Password has been changed");
         }
       } else {
 
         /* Missing permissions, show message */
-        print_red (_("You are not allowed to set this users password!"));
+        msg_dialog::display(_("Password change failed."),_("You are not allowed to set this users password!"),WARNING_DIALOG);
       }
-
       /* Clean session, delete lock */
       del_lock ($this->dn);
-      $this->reload();
       unset ($this->usertab);
       $this->usertab= NULL;
       $this->lognames= array();;
@@ -330,64 +252,313 @@ class userManagement extends plugin
     }
 
 
-    /* Remove user was requested */
-    if ($s_action=="del"){
+    /********************
+     Change multiple passwords requested 
+     ********************/
+  
+    if($s_action == "multiple_password_change"){
+      $this->pwd_change_queue = $this->list_get_selected_items();
+    }    
+
+
+    /********************
+      Change password requested  
+     ********************/
+
+    /* Password change requested */
+    if (($s_action == "change_pw") || (!empty($this->CPPasswordChange)) || count($this->pwd_change_queue)){
+
+      /* Get users whose passwords should be changed. */
+      if(count($this->pwd_change_queue)){
+        $s_entry= array_pop($this->pwd_change_queue);
+      }
+
+      if(!empty($this->CPPasswordChange)){
+        $s_entry = $this->CPPasswordChange;
+        $this->CPPasswordChange = "";
+      }
 
       /* Get 'dn' from posted 'uid' */
       $this->dn= $this->list[trim($s_entry)]['dn'];
 
       /* Load permissions for selected 'dn' and check if
          we're allowed to remove this 'dn' */
-      $acl= get_permissions ($this->dn, $this->ui->subtreeACL);
-      $this->acl= get_module_permission($acl, "user", $this->dn);
-      if (chkacl($this->acl, "delete") == ""){
-
-        /* Check locking, save current plugin in 'back_plugin', so
-           the dialog knows where to return. */
-        if (($user= get_lock($this->dn)) != ""){
-          return(gen_locked_message ($user, $this->dn));
+      if (preg_match("/w/",$this->ui->get_permissions($this->dn,"users/password"))){
+
+        /* User is allowed to change passwords, save 'dn' and 'acl' for next
+           dialog. */
+        $_SESSION['objectinfo']= $this->dn;
+        return ($smarty->fetch(get_template_path('password.tpl', TRUE)));
+        
+
+      } else {
+        /* User is not allowed. Show message and cancel. */
+        msg_dialog::display(_("Password change"),_("You are not allowed to set this users password!"),WARNING_DIALOG);
+      }
+    }
+
+
+
+     /********************
+      Edit existing entry
+     ********************/
+
+    /* User wants to edit data? */
+    if (($s_action=="edit") && (!isset($this->usertab->config))){
+
+      /* Get 'dn' from posted 'uid', must be unique */
+      $this->dn= $this->list[trim($s_entry)]['dn'];
+
+      /* Check locking, save current plugin in 'back_plugin', so
+         the dialog knows where to return. */
+      if (($user= get_lock($this->dn)) != ""){
+        return(gen_locked_message ($user, $this->dn));
+      }
+
+      /* Lock the current entry, so everyone will get the
+         above dialog */
+      add_lock ($this->dn, $this->ui->dn);
+
+      /* Register usertab to trigger edit dialog */
+      $this->usertab= new usertabs($this->config,
+          $this->config->data['TABS']['USERTABS'], $this->dn);
+
+      /* Switch tab, if it was requested by the user */
+      $this->usertab->current = $s_tab;
+
+      /* Set ACL and move DN to the headline */
+      $this->usertab->set_acl_base($this->dn);
+      $_SESSION['objectinfo']= $this->dn;
+    }
+
+
+    /********************
+      Edit multiple entries
+     ********************/
+
+    /* User wants to edit data? */
+    if ($s_action == "multiple_edit" && !isset($this->usertab->config)){
+
+      $this->dn = array();
+      foreach($this->list_get_selected_items() as $id){
+        $this->dn[] = $this->list[$id]['dn'];;
+      }
+      $tmp = new multi_plug($this->config,"usertabs",$this->config->data['TABS']['USERTABS'],
+            $this->dn,$this->DivListUsers->selectedBase,"user");
+      if ($tmp->entries_locked()){
+        return($tmp->display_lock_message());
+      }
+      $tmp->lock_entries($this->ui->dn);
+      if($tmp->multiple_available()){
+        $this->usertab = $tmp;
+        $this->usertab->set_active_tab($s_tab);
+        $_SESSION['objectinfo']= $this->usertab->get_object_info();
+      }
+    }
+
+
+    /********************
+      Edit canceled 
+     ********************/
+
+    /* Reset all relevant data, if we get a _cancel request */
+    if (isset($_POST['edit_cancel']) || isset($_POST['password_cancel'])){
+      if (isset($this->usertab)){
+        del_lock ($this->usertab->dn);
+        unset ($this->usertab);
+      }
+      $this->usertab= NULL;
+      $this->lognames= array();;
+      $this->sn= "";
+      $this->givenName= "";
+      $this->uid= "";
+      unset ($_SESSION['objectinfo']);
+    }
+
+
+    /********************
+      Delete MULTIPLE entries requested, display confirm dialog
+     ********************/
+
+    if ($s_action=="del_multiple"){
+      $ids = $this->list_get_selected_items();
+      $this->dns = array();
+      if(count($ids)){
+
+        foreach($ids as $id){
+          $dn = $this->list[$id]['dn'];
+          if (($user= get_lock($dn)) != ""){
+            return(gen_locked_message ($user, $dn));
+          }
+          $this->dns[$id] = $dn; 
         }
 
+        $dns_names = "<br><pre>";
+        foreach($this->dns as $dn){
+          $dns_names .= $dn."\n";
+        }
+        $dns_names .="</pre>";
+
         /* Lock the current entry, so nobody will edit it during deletion */
-        add_lock ($this->dn, $this->ui->dn);
-        $smarty->assign("info", sprintf(_("You're about to delete the user %s."), $this->dn));
-        return($smarty->fetch(get_template_path('remove.tpl', TRUE)));
-      } else {
+        if (count($this->dns) == 1){
+          $info = sprintf(_("You're about to delete the following entry: %s"), @LDAP::fix($dns_names));
+        } else {
+          $info = sprintf(_("You're about to delete the following entries: %s"), @LDAP::fix($dns_names));
+        }
+        $this->msg_dialog = new msg_dialog(_("Delete users"),$info,CONFIRM_DIALOG);
+        $this->current_action = $s_action;
+      }
+    }
+
+
+    /********************
+      Delete MULTIPLE entries confirmed 
+     ********************/
+
+      /* Confirmation for deletion has been passed. Users should be deleted. */
+      if ($this->current_action == "del_multiple" && is_object($this->msg_dialog) && $this->msg_dialog->is_confirmed()){
+        
+        $this->current_action = "";  
+        
+        /* Remove user by user and check acls before removeing them */
+        foreach($this->dns as $key => $dn){
+
+          $acl = $this->ui->get_permissions($dn, "users/user"); 
+          if (preg_match('/d/', $acl)){
+
+            /* Delete request is permitted, perform LDAP action */
+            $this->usertab= new usertabs($this->config, $this->config->data['TABS']['USERTABS'],$dn);
+            $this->usertab->set_acl_base();
+            $this->usertab->delete ();
+            unset ($this->usertab);
+            $this->usertab= NULL;
+          } else {
+            msg_dialog::display(_("User delete"),sprintf(_("You are not allowed to delete the user '%s'!"),$dn),WARNING_DIALOG);
+            if(isset($this->ui->uid)){
+              new log("security","users/".get_class($this),$dn,array(),"Tried to trick deletion.");
+            }
+          }
+          /* Remove lock file after successfull deletion */
+          del_lock ($dn);
+          unset($this->dns[$key]);
+      }
+    }
+
+
+    /********************
+      Delete MULTIPLE entries Canceled 
+     ********************/
+
+    /* Remove lock */
+    if(isset($_POST['delete_multiple_user_cancel'])){
+      foreach($this->dns as $key => $dn){
+        del_lock ($dn);
+        unset($this->dns[$key]);
+      }
+    }
+  
+  
+    /********************
+      Toggle lock status for user
+     ********************/
+  
+    if($s_action == "toggle_lock_status" && isset($this->list[$s_entry])){
+
+      /* Get entry check current status */
+      $val = $this->list[$s_entry];
+      $pwd = $val['userPassword'][0];
 
-        /* Obviously the user isn't allowed to delete. Show message and
-           clean session. */
-        print_red (_("You are not allowed to delete this user!"));
+      if(!preg_match("/^\{[^\}]/",$pwd)){
+        trigger_error("Can not deactivate user which is using clear password encryption.");
+      }else{
+
+        $locked = false;
+        if(preg_match("/^[^\}]*+\}!/",$pwd)){
+          $locked = true;
+        }
+
+        /* Create ldap array to update status */
+        $attrs = array("userPassword" => $pwd);
+        if($locked){
+          $attrs['userPassword'] = preg_replace("/(^[^\}]+\})!(.*$)/","\\1\\2",$attrs['userPassword']);
+        }else{
+          $attrs['userPassword'] = preg_replace("/(^[^\}]+\})(.*$)/","\\1!\\2",$attrs['userPassword']);
+        }
+
+        /* Write new status back to ldap */
+        $ldap = $this->config->get_ldap_link();
+        $ldap->cd($val['dn']);
+        $ldap->modify($attrs);
+        if($locked){
+          show_ldap_error($ldap->get_error(),_("Could not set user status from locked to unlocked."));
+        }else{
+          show_ldap_error($ldap->get_error(),_("Could not set user status from unlocked to locked."));
+        }
       }
     }
 
 
+    /********************
+      Delete entry requested, display confirm dialog
+     ********************/
+
+    /* Remove user was requested */
+    if ($s_action=="del"){
+
+      /* Get 'dn' from posted 'uid' */
+      $this->dn= $this->list[trim($s_entry)]['dn'];
+
+      /* Load permissions for selected 'dn' and check if
+         we're allowed to remove this 'dn' */
+
+      /* Check locking, save current plugin in 'back_plugin', so
+         the dialog knows where to return. */
+      if (($user= get_lock($this->dn)) != ""){
+        return(gen_locked_message ($user, $this->dn));
+      }
+
+  
+      /* Lock the current entry, so nobody will edit it during deletion */
+#      add_lock ($this->dn, $this->ui->dn);
+#      $smarty->assign("info", sprintf(_("You're about to delete the user %s."), @LDAP::fix($this->dn)));
+#      $smarty->assign("multiple", false);
+#      return($smarty->fetch(get_template_path('remove.tpl', TRUE)));
+      $this->msg_dialog = new msg_dialog( _("Delete user"),sprintf(_("You're about to delete the user %s."), @LDAP::fix($this->dn)),CONFIRM_DIALOG);
+      $this->current_action = $s_action;
+    }
+
+
+    /********************
+      Delete entry confirmed 
+     ********************/
 
     /* Confirmation for deletion has been passed. User should be deleted. */
-    if (isset($_POST['delete_user_confirm'])){
+    if ($this->current_action == "del" && is_object($this->msg_dialog) && $this->msg_dialog->is_confirmed()){
 
+      $this->current_action = ""; 
       /* Some nice guy may send this as POST, so we've to check
          for the permissions again. */
-      if (chkacl($this->acl, "delete") == ""){
+
+      $acl = $this->ui->get_permissions($this->dn, "users/user"); 
+      if (preg_match('/d/', $acl)){
 
         /* Delete request is permitted, perform LDAP action */
-        $this->usertab= new usertabs($this->config, $this->config->data['TABS']['USERTABS'],
-            $this->dn);
-        $this->usertab->set_acl(array($this->acl));
+        $this->usertab= new usertabs($this->config, $this->config->data['TABS']['USERTABS'],$this->dn);
+        $this->usertab->set_acl_base();
         $this->usertab->delete ();
-        gosa_log ("User object '".$this->dn."' has been removed");
         unset ($this->usertab);
         $this->usertab= NULL;
-
-        /* User list has changed, reload it. */
-        $this->reload ();
+        msg_dialog::display(_("User delted"),_("User successfully removed."),INFO_DIALOG);
       } else {
 
         /* Normally this shouldn't be reached, send some extra
            logs to notify the administrator */
-        print_red (_("You are not allowed to delete this user!"));
+        msg_dialog::display(_("User delete"),_("You are not allowed to delete this user!"),WARNING_DIALOG);
 
         if(isset($this->ui->uid)){
-          gosa_log ("Warning: '".$this->ui->uid."' tried to trick user deletion.");
+          new log("security","users/".get_class($this),$this->dn,array(),"Tried to trick deletion.");
         }
       }
 
@@ -395,6 +566,10 @@ class userManagement extends plugin
       del_lock ($this->dn);
     }
 
+    
+    /********************
+      Delete entry Canceled 
+     ********************/
 
     /* Delete user canceled? */
     if (isset($_POST['delete_cancel'])){
@@ -402,10 +577,14 @@ class userManagement extends plugin
     }
 
 
+    /********************
+      Edit entry finished (Save) 
+     ********************/
+
     /* Finish user edit is triggered by the tabulator dialog, so
        the user wants to save edited data. Check and save at this
        point. */
-    if (isset($_POST['edit_finish'])){
+    if ((isset($_POST['edit_finish']) || isset($_POST['edit_apply'])) && (isset($this->usertab->config))){
 
       /* Check tabs, will feed message array */
       $this->usertab->last= $this->usertab->current;
@@ -426,31 +605,25 @@ class userManagement extends plugin
 
         /* Save user data to ldap */
         if($this->usertab->save() == 1){
-          gosa_log ("User object '".$this->dn."' saving failed.");
           return;
         }
-        gosa_log ("User object '".$this->dn."' has been saved");
 
-        /* User has been saved successfully, remove lock from
-           LDAP. */
-        if ($this->dn != "new"){
-          del_lock ($this->dn);
-        }
+        if (!isset($_POST['edit_apply'])){
+          /* User has been saved successfully, remove lock from LDAP. */
+          if ($this->dn != "new"){
+            del_lock ($this->dn);
+          }
 
-        /* In case of new users, ask for a password */
-        if (($set_pass || $this->usertab->password_change_needed()) &&
-            !$this->is_template){
+          /* In case of new users, ask for a password, skip this for templates */
+          if (($set_pass || $this->usertab->password_change_needed()) && !$this->is_template){
+            $this->dn = $this->usertab->dn;
+            return($smarty->fetch(get_template_path('password.tpl', TRUE)));
+          }
 
-          return($smarty->fetch(get_template_path('password.tpl', TRUE)));
+          unset ($this->usertab);
+          $this->usertab= NULL;
+          unset ($_SESSION['objectinfo']);
         }
-
-        /* There's no page reload so we have to read new users at
-           this point. */
-        $this->reload ();
-        unset ($this->usertab);
-        $this->usertab= NULL;
-        unset ($_SESSION['objectinfo']);
-
       } else {
         /* Ok. There seem to be errors regarding to the tab data,
            show message and continue as usual. */
@@ -458,22 +631,25 @@ class userManagement extends plugin
       }
     }
 
+
+    /********************
+      We want to create a new user, so fetch all available user templates 
+     ********************/
+
     /* Generate template list */
     if (($s_action=="new")||($s_action=="create_user_from_tpl")){
 
       $this->templates= array();
-
       $ldap= $this->config->get_ldap_link();
 
-      /* Create list of tempaltes */
+      /* Create list of templates */
       foreach ($this->config->departments as $key => $value){
     
         /* Get acls from different ou's */
-        $acl= get_permissions (get_people_ou().$value, $this->ui->subtreeACL);
-        $acl= get_module_permission($acl, "user", get_people_ou().$value);
-  
+        $acl = $this->ui->get_permissions("cn=dummy,".get_people_ou().$value,"users/user")       ; 
         /* If creation of a new user is allowed, append this template */
-        if (chkacl($acl, "create") == ""){
+        if (preg_match("/c/",$acl)){
           
           /* Search all templates from the current dn */
           $ldap->cd (get_people_ou().$value);
@@ -483,7 +659,7 @@ class userManagement extends plugin
           if ($ldap->count() != 0){
             while ($attrs= $ldap->fetch()){
               $this->templates[$ldap->getDN()]=
-                $attrs['uid'][0]." - $key";
+                $attrs['uid'][0]." - ".@LDAP::fix($key);
             }
             $this->templates['none']= _("none");
           }
@@ -495,11 +671,49 @@ class userManagement extends plugin
       reset ($this->templates);
     }
 
+
+    /********************
+      Create a new user,template, user from template 
+     ********************/
+
+    /* Check selected options for template */
+    if (isset($_POST['template_continue'])){
+      $message = array();
+      if(!isset($_POST['template']) || (empty($_POST['template']))){
+        $message[] = _("Please select a valid template.");
+      }
+      if(!isset($_POST['sn']) || (empty($_POST['sn']))){
+        $message[]= _("The required field 'Name' is not set.");
+      }
+      if(!isset($_POST['givenName']) || (empty($_POST['givenName']))){
+        $message[]= _("The required field 'Given name' is not set.");
+      }
+    
+      /* Show error message / continue editing */
+      if (count($message) > 0){
+        show_errors ($message);
+
+        foreach(array("sn", "givenName", "uid", "template") as $attr){
+          if(isset($_POST[$attr])){
+            $smarty->assign("$attr", $_POST[$attr]);
+          }else{
+            $smarty->assign("$attr", "");
+          }
+        }
+        $smarty->assign("templates",$this->templates);
+        $smarty->assign("got_uid",$this->got_uid);
+        $smarty->assign("edit_uid",false);
+        return($smarty->fetch(get_template_path('template.tpl', TRUE)));
+
+      }
+    }
+
     /* New user/template request */
     if (($s_action=="create_user_from_tpl")||($s_action=="new") || ($s_action=="new_tpl")){
       /* By default we set 'dn' to 'new', all relevant plugins will
          react on this. */
       $this->dn= "new";
+      
       if (isset($this->config->current['IDGEN'])){
         $this->got_uid= false;
       } else {
@@ -507,10 +721,9 @@ class userManagement extends plugin
       }
 
       /* Create new usertab object */
-      $this->usertab= new usertabs($this->config,
-          $this->config->data['TABS']['USERTABS'], $this->dn);
-      $this->usertab->set_acl(array(':all'));
-      $this->usertab->by_object['user']->base= $userfilter['depselect'];
+      $this->usertab= new usertabs($this->config,$this->config->data['TABS']['USERTABS'], $this->dn);
+      $this->usertab->by_object['user']->base= $this->DivListUsers->selectedBase;
+      $this->usertab->set_acl_base('dummy,'.$this->DivListUsers->selectedBase);
 
       /* Take care about templates */
       if ($s_action=="new_tpl"){
@@ -521,7 +734,6 @@ class userManagement extends plugin
       }
 
       /* Use template if there are any of them */
-  
       if ((count($this->templates) && ($s_action!='new_tpl'))||($s_action=="create_user_from_tpl")){
         foreach(array("sn", "givenName", "uid", "got_uid", "templates") as $attr){
           $smarty->assign("$attr", $this->$attr);
@@ -536,10 +748,15 @@ class userManagement extends plugin
       }
     }
 
+    /********************
+      Template selected continue edit
+     ********************/
+
     /* Continue template editing */
-    if ((isset($_POST['template_continue']) && $_POST['template'] != 'none' && !isset($_POST['uid']))){
-      $this->sn= $_POST['sn'];
-      $this->givenName= $_POST['givenName'];
+    if ((isset($_POST['template_continue'])) && ($_POST['template'] != 'none') && (!isset($_POST['uid']))){
+
+      $this->sn             = $_POST['sn'];
+      $this->givenName      = $_POST['givenName'];
 
       /* Check for requred values */
       $message= array();
@@ -554,7 +771,7 @@ class userManagement extends plugin
       $dn= preg_replace("/^[^,]+,/i", "", $_POST['template']);
       $ldap= $this->config->get_ldap_link();
       $ldap->cd ($dn);
-      $ldap->search ("(&(sn=".$this->sn.")(givenName=".$this->givenName."))", array("givenName"));
+      $ldap->search ("(&(sn=".normalizeLdap($this->sn).")(givenName=".normalizeLdap($this->givenName)."))", array("givenName"));
       if ($ldap->count () != 0){
         $message[]= _("A person with the choosen name is already used in this tree.");
       }
@@ -588,6 +805,10 @@ class userManagement extends plugin
       return($smarty->fetch(get_template_path('template.tpl', TRUE)));
     }
 
+    /********************
+      No template selected continue edit
+     ********************/
+
     /* No template. Ok. Lets fill data into the normal user dialog */
     if (isset($_POST['template_continue']) && $_POST['template'] == 'none'){
       foreach(array("sn", "givenName", "uid") as $attr){
@@ -597,6 +818,11 @@ class userManagement extends plugin
       }
     }
 
+
+    /********************
+      Template selected continue edit
+     ********************/
+
     /* Finish template preamble */
     if (isset($_POST['template_continue']) && $_POST['template'] != 'none' && (isset($_POST['uid']))){
 
@@ -611,479 +837,281 @@ class userManagement extends plugin
       $this->usertab->givenName = $this->givenName;
       $template_dn              = $_POST['template'];
       $this->usertab->adapt_from_template($template_dn);
-      $template_base            = preg_replace("/^[^,]+,".get_people_ou()."/", '', $template_dn);
+      $template_base            = preg_replace("/^[^,]+,".normalizePreg(get_people_ou())."/", '', $template_dn);
       $this->usertab->by_object['user']->base= $template_base;
-
-      /* Set up the users ACL's for this 'dn' */
-      $acl= get_permissions ($template_base, $this->ui->subtreeACL);
-      $this->usertab->set_acl($acl);
     }
-    
+   
+    /********************
+      If no template was selected set base
+     ********************/
+
     if (isset($_POST['template_continue']) && ($_POST['template'] == 'none')){
-      $this->usertab->by_object['user']->base= $userfilter['depselect'];
+      $this->usertab->by_object['user']->base= $this->DivListUsers->selectedBase;
     }
 
+
+    /********************
+      Display subdialog 
+     ********************/
+
     /* Show tab dialog if object is present */
-    if ($this->usertab){
+    if(isset($this->usertab->config)){
       $display= $this->usertab->execute();
 
       /* Don't show buttons if tab dialog requests this */
-      if (!$this->usertab->by_object[$this->usertab->current]->dialog){
-        $display.= "<p style=\"text-align:right\">\n";
-        $display.= "<input type=submit name=\"edit_finish\" value=\""._("Finish")."\">\n";
-        $display.= "&nbsp;\n";
-        $display.= "<input type=submit name=\"edit_cancel\" value=\""._("Cancel")."\">\n";
-        $display.= "</p>";
-      }
-      return ($display);
-    }
-
-    $smarty= get_smarty();
-
-    /* Check sorting variable */
-    if (!isset($this->usertab) &&
-        !isset($_POST['new_user']) &&
-        !isset($_POST['new_template']) &&
-        !isset($_POST['delete_user']) &&
-        !isset($_POST['setpass_user']) &&
-        !isset($_POST['select_user'])){
-      $this->reload();
-    }
-
-    /* Check for exeeded sizelimit */
-    if (($message= check_sizelimit()) != ""){
-      return($message);
-    }
-
-    /* Prepare departments */
-    $options= "";
-    foreach ($this->config->idepartments as $key => $value){
-      if ($userfilter['depselect'] == $key){
-        $options.= "<option selected value='$key'>$value</option>";
-      } else {
-        $options.= "<option value='$key'>$value</option>";
-      }
-    }
-
-    /* NEW LIST MANAGMENT */
-    $listhead = "<div style='background:#F0F0F9;padding:5px;'>".
-      " <input class='center' type='image' align='middle' src='images/list_back.png' title='"._("Go up one department")."' alt='"._("Up")."' name='dep_back'>&nbsp;".
-      " <input class='center' type='image' src='images/list_root.png' align='middle' title='"._("Go to root department")."' name='dep_root' alt='"._("Root")."'>&nbsp;".
-      " <input class='center' type='image' align='middle' src='images/list_home.png' title='"._("Go to users department")."' alt='"._("Home")."' name='dep_home'>&nbsp;".
-      " <img   class='center' src='images/list_seperator.png' align='middle' alt='' height='16' width='1'>&nbsp;".
-      " <input class='center' type='image' align='middle' src='images/list_new_user.png' title='"._("Create new user")."' alt='"._("New user")."' name='user_new'>&nbsp;".
-      " <input class='center' type='image' align='middle' src='images/list_new.png' title='"._("Create new template")."' alt='"._("New template")."' name='user_tplnew'>&nbsp;".
-      " <img   class='center' src='images/list_seperator.png' align='middle' alt='' height='16' width='1'>&nbsp;".
-      _("Current base")."&nbsp;<select name='depselect' onChange='mainform.submit()' class='center'>$options</select>".
-      " <input class='center' type='image' src='images/list_submit.png' align='middle' title='"._("Submit department")."' name='submit_department' alt='"._("Submit")."'>&nbsp;".
-      "</div>";
-
-    $action= "<input class='center' type='image' src='images/edit.png' alt='"._("edit")."'     name='user_edit_%KEY%' title='"._("Edit user")."'>";
-    $action.= "<input class='center' type='image' src='images/list_password.png' alt='"._("password")."' name='user_chgpw_%KEY%' title='"._("Change password")."'>";
-    $action.= "<input class='center' type='image' src='images/edittrash.png' alt='"._("delete")."'   name='user_del_%KEY%' title='"._("Delete user")."'>";
-
-
-
-    $divlist = new divlist("userstab");
-    $divlist->SetHeader(array(
-          array("string" => "&nbsp;", "attach" => "style='text-align:center;width:20px;'"),
-          array("string" => _("Username")." / "._("Department"), "attach" => "style=''"),
-          array("string" => _("Properties"), "attach" => "style='width:152px;'"),
-          array("string" => _("Actions"), "attach" => "style='width:60px;border-right:0px;text-align:right;'")));
-
-
-    $divlist->SetSummary(_("This table displays all users, in the selected tree."));
-    $divlist->SetEntriesPerPage(0);
-
-    // Defining Links 
-    $linkopen = "<a href='?plug=".$_GET['plug']."&amp;act=dep_open&amp;dep_id=%s'>%s</a>";
-
-    /* Insert departments in divlist*/
-    foreach($this->departments as $key=> $val){
-
-      if(!isset($this->config->departments[trim($key)])){
-        $this->config->departments[trim($key)]="";
-      }
-
-      $non_empty="";
-      $keys= str_replace("/","\/",$key);
-      foreach($this->config->departments as $keyd=>$vald ){
-        if(preg_match("/".$keys."\/.*/",$keyd)){
-          $non_empty="full";
-        }
-      }
-
-      $field1 = array("string" => "<img src='images/".$non_empty."folder.png' alt='department'>", "attach" => "style='text-align:center;width:20px;'");
-      $field2 = array("string" => sprintf($linkopen,base64_encode($key),$val), "attach" => "style=''");
-      $field3 = array("string" => "&nbsp;", "attach" => "style='width:152px;'");
-      $field4 = array("string" => "&nbsp;", "attach" => "style='width:60px;border-right:0px;text-align:right;'");
-
-
-      $divlist->AddEntry(array($field1,$field2,$field3,$field4));
-    }
-
-    /* Pictures for Extensions */
-    $usrimg   ="<input class='center' type='image' src='images/penguin.png' alt='"._("GOsa")."'   
-                    name='user_edit_%KEY%-user' title='"._("Edit generic properties")."'>";
-    $posiximg = "<input class='center' type='image' src='images/select_user.png' alt='"._("Posix")."'  
-                    name='user_edit_%KEY%-posixAccount' title='"._("Edit UNIX properties")."'>";
-    $eviroimg = "<input class='center' type='image' src='images/smallenv.png' alt='"._("Environment")."'  
-                    name='user_edit_%KEY%-environment' title='"._("Edit environment properties")."'>";
-    $mailimg  = "<input class='center' type='image' src='images/mailto.png' alt='"._("Mail")."'     
-                    name='user_edit_%KEY%-mailAccount' title='"._("Edit mail properties")."'>";
-    $fonimg   = "<input class='center' type='image' src='images/%image%' alt='"._("Phone")."'     
-                    name='user_edit_%KEY%-phoneAccount' title='"._("Edit phone properties")."%title%'>";
-    $faximg   = "<input class='center' type='image' src='images/fax_small.png' alt='"._("Fax")."'     
-                    name='user_edit_%KEY%-gofaxAccount' title='"._("Edit fax properies")."'>";
-    $sambaimg = "<input class='center' type='image' src='images/select_winstation.png' alt='"._("Samba")."'     
-                    name='user_edit_%KEY%-sambaAccount' title='"._("Edit samba properties")."'>"; 
-    $tplcreateuserimg  = "<input type='image' class='center' src='images/list_new.png' alt='"._("Create user from template")."'
-                    name='userfrom_tpl_%KEY%' title='"._("Create user with this template")."'>";   
-    
-
-    $empty    = "<img class='center' src='images/empty.png' style='width:16px;height:16px;' alt=''>"; 
-
-    // User and Template  Images  
-    $userimg  = "<img class='center' src='images/select_user.png' alt='User' title='%s'>";   
-    $tplimg   = "<img class='center' src='images/select_template.png' alt='Template' title='%s'>";   
-    $editlink = "<a href='?plug=".$_GET['plug']."&amp;id=%s&amp;act=edit_entry'>%s</a>";
-
-    // Defines Arrays to save User and Templates
-    $tpls = array();
-    $users= array();
-
-    /* Get Configuration for goFon DB (if it is set), to connect to the asterisk tables.
-     * Read Sip Table for specified account (for each user with phoneAccount).
-     * Check the attributes ip port and regseconds.
-     * If regseconds is set and >0 , the phone is logged in.
-     * Else the phone is currently not logged.
-     * If we can't read any Data from the DB or there is no goFon DB specified
-     * show old style without status icons.
-     */
-    $r_db   =false;
-    $r_con  =false;
-    if (isset($_SESSION['config']->data['SERVERS']['FON'])){
-      $a_SETUP= $_SESSION['config']->data['SERVERS']['FON'];
-      // Connect to DB server
-  
-      /* 
-        If you want to disable the status pictures, just comment out the next line
-      */
-      $r_con = false;
-      $r_db  = false;
-      if(is_callable("mysql_pconnect")){
-        $r_con= @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
-        // Check if we are  connected correctly
-        if($r_con){
-          $r_db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
+      
+        $dia = FALSE;
+        if(isset($this->usertab->by_object[$this->usertab->current]->dialog)){
+          $dia = $this->usertab->by_object[$this->usertab->current]->dialog;
         }
-      }
-    }
 
-    // Test Every Entry and generate divlist Array  
-    foreach($this->list as $key => $val){
-      $connected  = ""; // This string represents timestamp or offline status 
-      $ip_port    = ""; // String that will represent ip : port of the connected phone
-      if((in_array("goFonAccount"    ,$val['objectClass']))){
-  
-        /* Set defaults */
-        $fonac = preg_replace("/%image%/", "select_phone.png", $fonimg);
-        $fonac = preg_replace("/%KEY%/", "$key", $fonac);
-        $fonac = preg_replace("/%title%/", "", $fonac);
-
-        /* Database connection is ok ?*/
-        if(($r_db)&&(is_callable("mysql_query"))){
-          $res= @mysql_query("SELECT regseconds,name,port,ipaddr FROM ".$a_SETUP['SIP_TABLE']." WHERE (name='".$val['uid'][0]."')");
-          $mysql_entry = @mysql_fetch_row($res);
-          if(is_array($mysql_entry)){
-            if((isset($mysql_entry[0]))&&($mysql_entry[0]>1)){
-              $connected = " | "._("Online")." : ".gmdate("d.m.Y H:i:s",($mysql_entry[0]+(60*60)));
-              $fonac = preg_replace("/%image%/", "select_phone_connected.png", $fonimg);
-              $fonac = preg_replace("/%KEY%/", "$key", $fonac);
-              $fonac = preg_replace("/%title%/", $connected, $fonac);
-              $ip_port= " - ".$mysql_entry[3].":".$mysql_entry[2];
-            }
-            if((isset($mysql_entry[0]))&&($mysql_entry[0]==0)){
-              $connected = " | "._("Offline");
-              $fonac = preg_replace("/%image%/", "select_phone.png", $fonimg);
-              $fonac = preg_replace("/%KEY%/", "$key", $fonac);
-              $fonac = preg_replace("/%title%/", $connected, $fonac);
-            }
+        if(!is_object($dia) && $dia != TRUE){
+          $display.= "<p style=\"text-align:right\">\n";
+          $display.= "<input type=submit name=\"edit_finish\" style=\"width:80px\" value=\""._("Ok")."\">\n";
+          $display.= "&nbsp;\n";
+          if ($this->dn != "new"){
+            $display.= "<input type=submit name=\"edit_apply\" value=\""._("Apply")."\">\n";
+            $display.= "&nbsp;\n";
           }
+          $display.= "<input type=submit name=\"edit_cancel\" value=\""._("Cancel")."\">\n";
+          $display.= "</p>";
         }
-      }else{
-        $fonac=$empty;
-      }
-
-    
-
-      // Specify Pics for Extensions  
-      if(in_array("posixAccount"    ,$val['objectClass'])){ 
-        $posix = preg_replace("/%KEY%/", "$key", $posiximg);
-      }else{ 
-        $posix=$empty;
-      }
-      
-      if(in_array("gotoEnvironment"    ,$val['objectClass'])){ 
-        $enviro = preg_replace("/%KEY%/", "$key", $eviroimg);
-      }else{ 
-        $enviro =$empty;
-      }
-   
-      if(in_array("gosaMailAccount" ,$val['objectClass'])){ 
-        $maila = preg_replace("/%KEY%/", "$key", $mailimg);   
-      }else{ 
-        $maila=$empty;
-      } 
-  
-      if(in_array("goFaxAccount"    ,$val['objectClass'])){ 
-        $faxac = preg_replace("/%KEY%/", "$key", $faximg);    
-      }else{ 
-        $faxac=$empty;
-      } 
-
-      if(in_array("sambaSamAccount" ,$val['objectClass'])){ 
-        $samba = preg_replace("/%KEY%/", "$key", $sambaimg);  
-      }else{ 
-        $samba=$empty;
-      } 
-
-      if(in_array("gosaUserTemplate",$val['objectClass'])){ 
-        $tpl                          = preg_replace("/%KEY%/", "$key", $tplimg);   
-        $s_img_create_from_template   = preg_replace("/%KEY%/", "$key", $tplcreateuserimg);
-      }else{ 
-        $s_img_create_from_template   = "";
-        $tpl=$userimg;
-      }
-
-      $usrimg2 = preg_replace("/%KEY%/", "$key", $usrimg);
-
-      // Generate caption for rows
-      if (isset($val["sn"]) && isset($val["givenName"])){
-        $display= $val["sn"][0].", ".$val["givenName"][0]." [".$val["uid"][0]."]";
-      } else {
-        $display= "[".$val["uid"][0]."]";
-      }
-
-      /* Create each field */
-      $field1 = array("string" => sprintf($tpl,$val['dn']), "attach" => "style='text-align:center;width:20px;'");
-      $field2 = array("string" => sprintf($editlink,$key,$display).$ip_port, "attach" => "style='' title='".$val['dn']."'");
-      $field3 = array("string" => $usrimg2."&nbsp;".$posix."&nbsp;".$enviro."&nbsp;".$maila."&nbsp;".$fonac."&nbsp;".$faxac."&nbsp;".$samba."&nbsp;".$s_img_create_from_template, "attach" => "style='width:152px;'");
-      $field4 = array("string" => preg_replace("/%KEY%/", "$key", $action),"attach" => "style='width:60px;border-right:0px;text-align:right;'");
-
-      $add = array($field1,$field2,$field3,$field4);
-
-      // Template or User
-      if(in_array("gosaUserTemplate",$val['objectClass'])){
-        $tpls[strtolower( $val['sn']['0'].$val['uid']['0'])]=$add;
-      }else{
-        $users[strtolower( $val['sn']['0'].$val['uid']['0'])]=$add;
-      }
-    }
-
-    // Sort Entries 
-    ksort($users);
-    ksort($tpls);
-
-    // Append Templates
-    foreach($tpls as $key => $val){
-      $divlist->AddEntry( $val, array(""));
+      return ($display);
     }
-    // Append Users 
-    foreach($users as $key => $val){
-      $divlist->AddEntry( $val, array(""));
+    
+    /* Check if there is a snapshot dialog open */
+    $base = $this->DivListUsers->selectedBase;
+    if($str = $this->showSnapshotDialog($base,$this->get_used_snapshot_bases())){
+      return($str);
     }
-    /* Show main page */
-    //$smarty->assign("userlist",   nl2br(htmlentities($divlist->DrawList())));
-    $smarty->assign("userlist",   $divlist->DrawList());
-    $smarty->assign("userlisthead", $listhead);
-
-    /* END NEW LIST MANAGMENT
-     */  
-    $smarty->assign("search_image", get_template_path('images/search.png'));
-    $smarty->assign("tree_image", get_template_path('images/tree.png'));
-    $smarty->assign("infoimage", get_template_path('images/info.png'));
-    $smarty->assign("launchimage", get_template_path('images/launch.png'));
-    $smarty->assign("deplist", $this->config->idepartments);
-    foreach( array("depselect",  "functionalusers", "unixusers",
-          "mailusers", "sambausers", "proxyusers", 
-          "faxusers", "templates", "subsearch") as $type){
-
-      $smarty->assign("$type", $userfilter[$type]);
+  
+    /* Return rendered main page */
+        /* Display dialog with system list */
+    $this->DivListUsers->parent = $this;
+    $this->DivListUsers->execute();
+
+    /* Add departments if subsearch is disabled */
+    if(!$this->DivListUsers->SubSearch){
+      $this->DivListUsers->AddDepartments($this->DivListUsers->selectedBase,4,1);
     }
+    $this->reload();
+    $this->DivListUsers->setEntries($this->list);
+    return($this->DivListUsers->Draw());
+  }
 
-    $smarty->assign("regex", $userfilter["regex"]);
-    /* Extend if we are not using javascript */
-    $smarty->assign("apply", apply_filter());
-    $smarty->assign("alphabet", generate_alphabet());
-    $smarty->assign("hint", print_sizelimit_warning());
 
-    if((is_callable("mysql_close"))&&($r_con)){
-      @mysql_close($r_con);
-    }
-    return ($smarty->fetch(get_template_path('headpage.tpl', TRUE)));
-  }
+  /* Return departments, that will be included within snapshot detection */
+  function get_used_snapshot_bases()
+  {
+    return(array(get_people_ou().$this->DivListUsers->selectedBase));
+  }  
 
 
   function reload()
   {
-    /* Get config */
-    $userfilter= get_global('userfilter');
-
     /* Set base for all searches */
-    $base= $userfilter['depselect'];
-
-    /* Regex filter? */
-    if ($userfilter['regex'] != ""){
-      $regex= $userfilter['regex'];
-    } else {
-      $regex= "*";
-    }
-
-    /* Set filter depending on selection */
+    $base= $this->DivListUsers->selectedBase;
+    $this->list =array();
+
+    /* Get filter configuration */
+    $Regex                = $this->DivListUsers->Regex;
+    $SubSearch            = $this->DivListUsers->SubSearch;
+    $ShowTemplates        = $this->DivListUsers->ShowTemplates;
+    $ShowFunctionalUsers  = $this->DivListUsers->ShowFunctionalUsers;
+    $ShowUnixUsers        = $this->DivListUsers->ShowUnixUsers;
+    $ShowMailUsers        = $this->DivListUsers->ShowMailUsers;
+    $ShowSambaUsers       = $this->DivListUsers->ShowSambaUsers;
+    $ShowProxyUsers       = $this->DivListUsers->ShowProxyUsers;
+
+    /* Setup filter depending on selection */
+    $filter="";
     if ($this->config->current['SAMBAVERSION'] == 3){
       $samba= "sambaSamAccount";
     } else {
       $samba= "sambaAccount";
     }
 
-    $filter="";
-    if ($userfilter['functionalusers'] == "checked"){
-      $filter.= "(&(objectClass=gosaAccount)(!(|(objectClass=posixAccount)(objectClass=gosaMailAccount)(objectClass=$samba)(objectClass=goFaxAccount)(objectClass=gosaProxyAccount))))";
+    if ($ShowFunctionalUsers){
+      $filter.= "(&(objectClass=gosaAccount)(!(|(objectClass=posixAccount)".
+                "(objectClass=gosaMailAccount)(objectClass=$samba)".
+                "(objectClass=gosaProxyAccount))))";
     }
-    if ($userfilter['unixusers'] == "checked"){
+    if ($ShowUnixUsers){
       $filter.= "(objectClass=posixAccount)";
     }
-    if ($userfilter['mailusers'] == "checked"){
+    if ($ShowMailUsers){
       $filter.= "(objectClass=gosaMailAccount)";
     }
-    if ($userfilter['sambausers'] == "checked"){
+    if ($ShowSambaUsers){
       $filter.= "(objectClass=$samba)";
     }
-    if ($userfilter['proxyusers'] == "checked"){
+    if ($ShowProxyUsers){
       $filter.= "(objectClass=gosaProxyAccount)";
     }
-    if ($userfilter['faxusers'] == "checked"){
-      $filter.= "(objectClass=goFaxAccount)";
-    }
-
-    if ($userfilter['templates'] == "checked"){
+    if ($ShowTemplates){
       $filter= "(|(objectClass=gosaUserTemplate)(&(objectClass=gosaAccount)(|$filter)))";
     } else {
       $filter= "(&(objectClass=gosaAccount)(!(objectClass=gosaUserTemplate))(|$filter))";
     }
-    $filter= "(&(|(uid=$regex)(sn=$regex)(givenName=$regex))$filter)";
+    $filter= "(&(|(uid=".normalizeLdap($Regex).")(sn=".normalizeLdap($Regex).")(givenName=".normalizeLdap($Regex)."))$filter)";
 
     /* Generate userlist */
     $ldap= $this->config->get_ldap_link(TRUE);
-    if ($userfilter['subsearch'] == "checked"){
-      $this->list= get_list($this->ui->subtreeACL, "$filter", TRUE, $base, array("uid", "givenName", "sn", "objectClass"), TRUE);
+
+    if ($SubSearch){
+      $ListTemp =  get_list($filter, "users", $base,
+                            array("uid", "givenName", "sn", "objectClass","userPassword"), GL_SUBSEARCH | GL_SIZELIMIT);
     } else {
       $base= get_people_ou().$base;
-      $this->list= get_list($this->ui->subtreeACL, "$filter", FALSE, $base, array("uid", "givenName", "sn", "objectClass"), TRUE);
+      $ListTemp = get_list($filter, "users", $base, 
+                            array("uid", "givenName", "sn", "objectClass","userPassword"), GL_SIZELIMIT);
     }
+    $SortTemp = array();
+    $List = array();
+    foreach($ListTemp as $Key => $Entry){
+
+      /* Skip entries that are not located under the people ou (normaly 'ou=people,')
+       * Else winstations will be listed too, if you use the subtree flag. 
+       */
+      if(!preg_match("/".normalizePreg(get_people_ou())."/i",$Entry['dn'])){
+        continue;
+      }else{
 
+        // Generate caption for rows
+        if (isset($Entry["sn"]) && isset($Entry["givenName"])){
+          $display= $Entry["sn"][0].", ".$Entry["givenName"][0]." [".$Entry["uid"][0]."]";
+        } else {
+          $display= "[".$Entry["uid"][0]."]";
+        }
 
+        $display = strtolower($display);
+        $List[$display] = $Entry;
+        $SortTemp[$display] = $display;
+      }
+    }
+    sort($SortTemp);
+    reset($SortTemp);
 
-    /* NEW LIST MANAGMENT
-     * We also need to search for the departments
-     * So we are able to navigate like in konquerer 
-     */
-
-    /* Create base to search in */
-
-    $peopleOU = get_people_ou();
-    if(empty($peopleOU))  {
-      $base2 = $base;
-    }else{
-      $base2 = preg_replace("/".$peopleOU."/i","",$base);
+    $this->list = array();
+    foreach($SortTemp as $Key){
+      $this->list[] = $List[$Key];
     }
+  }
 
-    /* Get all departments within this subtree */
-    $res3 =  get_list2($this->ui->subtreeACL, "(&(|(ou=$regex)(description=$regex))(objectClass=gosaDepartment))",
-        TRUE, $base2, array("ou", "description"), TRUE);
+  function remove_lock()
+  {
+    /* Remove user lock if a DN is marked as "currently edited" */
+    if (isset($this->usertab->dn)){
+      del_lock ($this->usertab->dn);
+    }
+  }
 
-    $this->departments= array();
 
-    /* Create array with results */
-    $tmp = array();
-    foreach ($res3 as $value){
-      $tmp[strtolower($value['dn']).$value['dn']]=$value;
+  function copyPasteHandling_from_queue($s_action,$s_entry)
+  {
+    /* Check if Copy & Paste is disabled */
+    if(!is_object($this->CopyPasteHandler)){
+      return("");
     }
 
-    /* Sort array */
-    ksort($tmp);
-
-    /* Create result array */
-    foreach($tmp as $value){
-      if(isset($value['description'][0])){
-        $this->departments[$value['dn']]=convert_department_dn2($value['dn'])." - [".$value["description"][0]."]";
-      }else{
-        $this->departments[$value['dn']]=convert_department_dn2($value['dn']);
-      }
+    /* Add a single entry to queue */
+    if($s_action == "cut" || $s_action == "copy"){
+      /* Cleanup object queue */
+      $this->CopyPasteHandler->cleanup_queue();
+      $dn = $this->list[$s_entry]['dn'];
+      $this->CopyPasteHandler->add_to_queue($dn,$s_action,"usertabs","USERTABS","users");
     }
-    /* END NEW LIST MANAGMENT 
-     */
 
+    /* Add entries to queue */
+    if($s_action == "copy_multiple" || $s_action == "cut_multiple"){
+
+      /* Cleanup object queue */
+      $this->CopyPasteHandler->cleanup_queue();
 
-    $this->userlist= array();
+      /* Add new entries to CP queue */
+      foreach($this->list_get_selected_items() as $id){
+        $dn = $this->list[$id]['dn'];
 
-    foreach ($this->list as $value){
-      if (isset($value["uid"][0]) && !preg_match('/\$$/', $value["uid"][0])){
-        if (in_array_ics('gosaUserTemplate', $value['objectClass'])){
-          $this->userlist[$value["dn"]]= "* ".$value["uid"][0]." ("._("Template").")";
-          continue;
+        if($s_action == "copy_multiple"){
+          $this->CopyPasteHandler->add_to_queue($dn,"copy","usertabs","USERTABS","users");
         }
-        if (isset($value["givenName"][0]) && isset($value["sn"][0])){
-          $this->userlist[$value["dn"]]= $value["sn"][0].", ".
-            $value["givenName"][0].
-            " [".$value["uid"][0]."]";
-        } else {
-          $this->userlist[$value["dn"]]= "[".$value["uid"][0]."]";
+        if($s_action == "cut_multiple"){
+          $this->CopyPasteHandler->add_to_queue($dn,"cut","usertabs","USERTABS","users");
         }
       }
     }
+    
+    /* Start pasting entries */
+    if($s_action == "editPaste"){
+      $this->start_pasting_copied_objects = TRUE;
+    }
 
-    natcasesort ($this->userlist);
-    reset ($this->userlist);
-  }
-
-  function remove_from_parent()
-  {
-  }
-
-
-  /* Check values */
-  function check()
-  {
-  }
-
+    /* Return C&P dialog */ 
+    if($this->start_pasting_copied_objects && $this->CopyPasteHandler->entries_queued()){
+   
+      /* Load entry from queue and set base */
+      $this->CopyPasteHandler->load_entry_from_queue();
+      $this->CopyPasteHandler->SetVar("base",$this->DivListUsers->selectedBase); 
+
+      /* Get dialog */
+      $data = $this->CopyPasteHandler->execute();
+
+      /* Set CPPasswordChange to s_entry which indicates that this entry requires a new password. */
+      if(isset($_POST['passwordTodo']) && ($_POST['passwordTodo'] == "new")){
+        $s_entry = $this->CopyPasteHandler->last_entry();
+        $this->reload();
+        foreach($this->list as $key => $entry){
+          if($entry['dn'] == $s_entry){
+            $this->CPPasswordChange = $key;
+          }
+        }
+      }
 
-  /* Save to LDAP */
-  function save()
-  {
-  }
+      /* Return dialog data */
+      if(!empty($data) && $this->CPPasswordChange == ""){
+        return($data);
+      }
+    }
 
-  function adapt_from_template($dn)
-  {
+    /* Automatically disable status for pasting */ 
+    if(!$this->CopyPasteHandler->entries_queued()){
+      $this->start_pasting_copied_objects = FALSE;
+    }
+    return("");
   }
 
-  function password_change_needed()
-  {
-  }
 
-  function show_header($button_text, $text, $disabled= FALSE)
+  function save_object()
   {
+    /* Handle divlist filter && department selection*/
+    if(!is_object($this->usertab)){
+      $this->DivListUsers->save_object();
+    }
   }
 
-  function remove_lock()
+    
+  function list_get_selected_items()
   {
-    if (isset($this->usertab->dn)){
-      del_lock ($this->usertab->dn);
+    $ids = array();
+    foreach($_POST as $name => $value){
+      if(preg_match("/^item_selected_[0-9]*$/",$name)){
+        $id   = preg_replace("/^item_selected_/","",$name);
+        $ids[$id] = $id;
+      }
     }
+    return($ids);
   }
+  
 
-}
+  /* A set of disabled and therefore overloaded functions. They are
+     not needed in this class. */
+  function remove_from_parent() { } 
+  function check() { } 
+  function save() { } 
+  function adapt_from_template($dn) { } 
+  function password_change_needed() { } 
 
+} /* ... class userManagement */
 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
 ?>