Code

Added base display to lists. Make it react on bases.
[gosa.git] / gosa-core / include / functions.inc
index cbcebe94b92bf6d5598d0c744a1a76e71f69e7ea..d5338a003c203fb266ec38686f8a28cbbc940e1c 100644 (file)
@@ -3,7 +3,7 @@
  * This code is part of GOsa (http://www.gosa-project.org)
  * Copyright (C) 2003-2008 GONICUS GmbH
  *
- * ID: $$Id$$
+ * ID: $$Id: functions.inc 13100 2008-12-01 14:07:48Z hickert $$
  *
  * 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
  */
 
 /* Configuration file location */
-define ("CONFIG_DIR", "/etc/gosa");
-define ("CONFIG_FILE", "gosa.conf-trunk");
-define ("CONFIG_TEMPLATE_DIR", "../contrib/");
-define ("HELP_BASEDIR", "/var/www/doc/");
+
+/* Allow setting the config patj in the apache configuration
+   e.g.  SetEnv CONFIG_FILE /etc/path
+ */
+if(!isset($_SERVER['CONFIG_DIR'])){
+  define ("CONFIG_DIR", "/etc/gosa");
+}else{
+  define ("CONFIG_DIR",$_SERVER['CONFIG_DIR']);
+}
+
+/* Allow setting the config file in the apache configuration
+    e.g.  SetEnv CONFIG_FILE gosa.conf.2.6
+ */
+if(!isset($_SERVER['CONFIG_FILE'])){
+  define ("CONFIG_FILE", "gosa.conf");
+}else{
+  define ("CONFIG_FILE",$_SERVER['CONFIG_FILE']);
+}
+
+define ("CONFIG_TEMPLATE_DIR", "../contrib");
+define ("TEMP_DIR","/var/cache/gosa/tmp");
 
 /* Define get_list flags */
 define("GL_NONE",         0);
@@ -52,8 +69,8 @@ define('DES3_CBC_MD5',5);
 define('DES3_CBC_SHA1',16);
 
 /* Define globals for revision comparing */
-$svn_path = '$HeadURL: https://oss.gonicus.de/repositories/gosa/trunk/gosa-core/include/functions.inc $';
-$svn_revision = '$Revision: 9246 $';
+$svn_path = '$HeadURL$';
+$svn_revision = '$Revision$';
 
 /* Include required files */
 require_once("class_location.inc");
@@ -69,6 +86,9 @@ define ("DEBUG_POST",   16);
 define ("DEBUG_SESSION",32);
 define ("DEBUG_CONFIG", 64);
 define ("DEBUG_ACL",    128);
+define ("DEBUG_SI",     256);
+define ("DEBUG_MAIL",   512); // mailAccounts, imap, sieve etc.
+define ("DEBUG_FAI",   1024); // FAI (incomplete)
 
 /* Rewrite german 'umlauts' and spanish 'accents'
    to get better results */
@@ -102,8 +122,8 @@ function __autoload($class_name) {
            exit;
     }
 
-    if (isset($class_mapping[$class_name])){
-      require_once($BASE_DIR."/".$class_mapping[$class_name]);
+    if (isset($class_mapping["$class_name"])){
+      require_once($BASE_DIR."/".$class_mapping["$class_name"]);
     } else {
       echo sprintf(_("Fatal error: cannot instantiate class '%s' - try running '%s' to fix this"), $class_name, "<b>update-gosa</b>");
       exit;
@@ -145,7 +165,7 @@ function make_seed() {
 /* Debug level action */
 function DEBUG($level, $line, $function, $file, $data, $info="")
 {
-  if (session::get('DEBUGLEVEL') & $level){
+  if (session::global_get('DEBUGLEVEL') & $level){
     $output= "DEBUG[$level] ";
     if ($function != ""){
       $output.= "($file:$function():$line) - $info: ";
@@ -175,8 +195,8 @@ function get_browser_language()
   }
 
   /* Check for global language settings in gosa.conf */
-  if(isset($config->data['MAIN']['LANG']) && !empty($config->data['MAIN']['LANG'])) {
-    $lang = $config->data['MAIN']['LANG'];
+  if (isset ($config) && $config->get_cfg_value('language') != ""){
+    $lang = $config->get_cfg_value('language');
     if(!preg_match("/utf/i",$lang)){
       $lang .= ".UTF-8";
     }
@@ -200,10 +220,10 @@ function get_browser_language()
 /* Rewrite ui object to another dn */
 function change_ui_dn($dn, $newdn)
 {
-  $ui= session::get('ui');
+  $ui= session::global_get('ui');
   if ($ui->dn == $dn){
     $ui->dn= $newdn;
-    session::set('ui',$ui);
+    session::global_set('ui',$ui);
   }
 }
 
@@ -213,10 +233,11 @@ function get_template_path($filename= '', $plugin= FALSE, $path= "")
 {
   global $config, $BASE_DIR;
 
-  if (!@isset($config->data['MAIN']['THEME'])){
-    $theme= 'default';
+  /* Set theme */
+  if (isset ($config)){
+       $theme= $config->get_cfg_value("theme", "default");
   } else {
-    $theme= $config->data['MAIN']['THEME'];
+       $theme= "default";
   }
 
   /* Return path for empty filename */
@@ -227,7 +248,7 @@ function get_template_path($filename= '', $plugin= FALSE, $path= "")
   /* Return plugin dir or root directory? */
   if ($plugin){
     if ($path == ""){
-      $nf= preg_replace("!^".$BASE_DIR."/!", "", session::get('plugin_dir'));
+      $nf= preg_replace("!^".$BASE_DIR."/!", "", session::global_get('plugin_dir'));
     } else {
       $nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
     }
@@ -238,7 +259,7 @@ function get_template_path($filename= '', $plugin= FALSE, $path= "")
       return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
     }
     if ($path == ""){
-      return (session::get('plugin_dir')."/$filename");
+      return (session::global_get('plugin_dir')."/$filename");
     } else {
       return ($path."/$filename");
     }
@@ -262,16 +283,14 @@ function get_template_path($filename= '', $plugin= FALSE, $path= "")
 
 function array_remove_entries($needles, $haystack)
 {
-  $tmp= array();
+  return (array_merge(array_diff($haystack, $needles)));
+}
 
-  /* Loop through entries to be removed */
-  foreach ($haystack as $entry){
-    if (!in_array($entry, $needles)){
-      $tmp[]= $entry;
-    }
-  }
 
-  return ($tmp);
+function array_remove_entries_ics($needles, $haystack)
+{
+  // strcasecmp will work, because we only compare ASCII values here
+  return (array_merge(array_udiff($haystack, $needles, 'strcasecmp')));
 }
 
 
@@ -310,12 +329,14 @@ function ldap_init ($server, $base, $binddn='', $pass='')
   global $config;
 
   $ldap = new LDAP ($binddn, $pass, $server,
-      isset($config->current['RECURSIVE']) && $config->current['RECURSIVE'] == "true",
-      isset($config->current['TLS']) && $config->current['TLS'] == "true");
+      isset($config->current['LDAPFOLLOWREFERRALS']) && $config->current['LDAPFOLLOWREFERRALS'] == "true",
+      isset($config->current['LDAPTLS']) && $config->current['LDAPTLS'] == "true");
 
   /* Sadly we've no proper return values here. Use the error message instead. */
   if (!$ldap->success()){
-    echo sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error());
+    msg_dialog::display(_("Fatal error"),
+        sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error()),
+        FATAL_ERROR_DIALOG);
     exit();
   }
 
@@ -334,17 +355,16 @@ function process_htaccess ($username, $kerberos= FALSE)
   
     $config->set_current($name);
     $mode= "kerberos";
-    if (isset($config->current['KRBSASL']) && preg_match('/^true$/i', $config->current['KRBSASL'])){
+    if ($config->get_cfg_value("useSaslForKerberos") == "true"){
       $mode= "sasl";
     }
 
     /* Look for entry or realm */
     $ldap= $config->get_ldap_link();
     if (!$ldap->success()){
-      msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH, ERROR_DIALOG));
-      $smarty= get_smarty();
-      $smarty->display(get_template_path('headers.tpl'));
-      echo "<body>".session::get('errors')."</body></html>";
+      msg_dialog::display(_("LDAP error"), 
+          msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'), 
+          FATAL_ERROR_DIALOG);
       exit();
     }
     $ldap->search("(&(objectClass=gosaAccount)(|(uid=$username)(userPassword={$mode}$username)))", array("uid"));
@@ -368,10 +388,9 @@ function ldap_login_user_htaccess ($username)
   /* Look for entry or realm */
   $ldap= $config->get_ldap_link();
   if (!$ldap->success()){
-    msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH, FATAL_ERROR_DIALOG));
-    $smarty= get_smarty();
-    $smarty->display(get_template_path('headers.tpl'));
-    echo "<body>".session::get('errors')."</body></html>";
+    msg_dialog::display(_("LDAP error"), 
+        msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'), 
+        FATAL_ERROR_DIALOG);
     exit();
   }
   $ldap->search("(&(objectClass=gosaAccount)(uid=$username))", array("uid"));
@@ -393,7 +412,7 @@ function ldap_login_user_htaccess ($username)
   $ui->loadACL();
 
   /* TODO: check java script for htaccess authentication */
-  session::set('js',true);
+  session::global_set('js',true);
 
   return ($ui);
 }
@@ -406,17 +425,16 @@ function ldap_login_user ($username, $password)
   /* look through the entire ldap */
   $ldap = $config->get_ldap_link();
   if (!$ldap->success()){
-    msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error()), FATAL_ERROR_DIALOG);
-    $smarty= get_smarty();
-    $smarty->display(get_template_path('headers.tpl'));
-    echo "<body>".session::get('errors')."</body></html>";
+    msg_dialog::display(_("LDAP error"), 
+        msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."<br><br>".session::get('errors'), 
+        FATAL_ERROR_DIALOG);
     exit();
   }
   $ldap->cd($config->current['BASE']);
   $allowed_attributes = array("uid","mail");
   $verify_attr = array();
-  if(isset($config->current['LOGIN_ATTRIBUTE'])){
-    $tmp = split(",",$config->current['LOGIN_ATTRIBUTE']); 
+  if($config->get_cfg_value("loginAttribute") != ""){
+    $tmp = split(",", $config->get_cfg_value("loginAttribute")); 
     foreach($tmp as $attr){
       if(in_array($attr,$allowed_attributes)){
         $verify_attr[] = $attr;
@@ -470,10 +488,10 @@ function ldap_login_user ($username, $password)
   /* password check, bind as user with supplied password  */
   $ldap->disconnect();
   $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
-      isset($config->current['RECURSIVE']) &&
-      $config->current['RECURSIVE'] == "true",
-      isset($config->current['TLS'])
-      && $config->current['TLS'] == "true");
+      isset($config->current['LDAPFOLLOWREFERRALS']) &&
+      $config->current['LDAPFOLLOWREFERRALS'] == "true",
+      isset($config->current['LDAPTLS'])
+      && $config->current['LDAPTLS'] == "true");
   if (!$ldap->success()){
     return (NULL);
   }
@@ -579,10 +597,25 @@ function ldap_expired_account($config, $userdn, $username)
 }
 
 
-function add_lock ($object, $user)
+function add_lock($object, $user)
 {
   global $config;
 
+  /* Remember which entries were opened as read only, because we 
+      don't need to remove any locks for them later.
+   */
+  if(!session::global_is_set("LOCK_CACHE")){
+    session::global_set("LOCK_CACHE",array(""));
+  }
+  $cache = &session::global_get("LOCK_CACHE");
+  if(isset($_POST['open_readonly'])){
+    $cache['READ_ONLY'][$object] = TRUE;
+    return;
+  }
+  if(isset($cache['READ_ONLY'][$object])){
+    unset($cache['READ_ONLY'][$object]);
+  }
+
   if(is_array($object)){
     foreach($object as $obj){
       add_lock($obj,$user);
@@ -598,7 +631,7 @@ function add_lock ($object, $user)
 
   /* Check for existing entries in lock area */
   $ldap= $config->get_ldap_link();
-  $ldap->cd ($config->current['CONFIG']);
+  $ldap->cd ($config->get_cfg_value("config"));
   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
       array("gosaUser"));
   if (!$ldap->success()){
@@ -610,14 +643,14 @@ function add_lock ($object, $user)
   if ($ldap->count() == 0){
     $attrs= array();
     $name= md5($object);
-    $ldap->cd("cn=$name,".$config->current['CONFIG']);
+    $ldap->cd("cn=$name,".$config->get_cfg_value("config"));
     $attrs["objectClass"] = "gosaLockEntry";
     $attrs["gosaUser"] = $user;
     $attrs["gosaObject"] = base64_encode($object);
     $attrs["cn"] = "$name";
     $ldap->add($attrs);
     if (!$ldap->success()){
-      msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "cn=$name,".$config->current['CONFIG'], 0, ERROR_DIALOG));
+      msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "cn=$name,".$config->get_cfg_value("config"), 0, ERROR_DIALOG));
       return;
     }
   }
@@ -640,9 +673,20 @@ function del_lock ($object)
     return;
   }
 
+  /* If this object was opened in read only mode then 
+      skip removing the lock entry, there wasn't any lock created.
+    */
+  if(session::global_is_set("LOCK_CACHE")){
+    $cache = &session::global_get("LOCK_CACHE");
+    if(isset($cache['READ_ONLY'][$object])){
+      unset($cache['READ_ONLY'][$object]);
+      return;
+    }
+  }
+
   /* Check for existance and remove the entry */
   $ldap= $config->get_ldap_link();
-  $ldap->cd ($config->current['CONFIG']);
+  $ldap->cd ($config->get_cfg_value("config"));
   $ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
   $attrs= $ldap->fetch();
   if ($ldap->getDN() != "" && $ldap->success()){
@@ -662,7 +706,7 @@ function del_user_locks($userdn)
 
   /* Get LDAP ressources */ 
   $ldap= $config->get_ldap_link();
-  $ldap->cd ($config->current['CONFIG']);
+  $ldap->cd ($config->get_cfg_value("config"));
 
   /* Remove all objects of this user, drop errors silently in this case. */
   $ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$userdn))", array("gosaUser"));
@@ -682,10 +726,13 @@ function get_lock ($object)
     return("");
   }
 
+  /* Allow readonly access, the plugin::plugin will restrict the acls */
+  if(isset($_POST['open_readonly'])) return("");
+
   /* Get LDAP link, check for presence of the lock entry */
   $user= "";
   $ldap= $config->get_ldap_link();
-  $ldap->cd ($config->current['CONFIG']);
+  $ldap->cd ($config->get_cfg_value("config"));
   $ldap->search("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaUser"));
   if (!$ldap->success()){
     msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
@@ -730,7 +777,7 @@ function get_multiple_locks($objects)
   /* Get LDAP link, check for presence of the lock entry */
   $user= "";
   $ldap= $config->get_ldap_link();
-  $ldap->cd ($config->current['CONFIG']);
+  $ldap->cd ($config->get_cfg_value("config"));
   $ldap->search($filter, array("gosaUser","gosaObject"));
   if (!$ldap->success()){
     msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
@@ -837,7 +884,7 @@ function get_sub_list($filter, $category,$sub_deps, $base= "", $attributes= arra
        *  departments like this "ou=servers,ou=blafasel,..."
        * Here we filter out those blafasel departments.
        */
-      if(preg_match("/".normalizePreg($sub_dep)."/",$attrs['dn'])){
+      if(preg_match("/".preg_quote($sub_dep, '/')."/",$attrs['dn'])){
         $departments[$attrs['dn']] = $attrs['dn'];
         break;
       }
@@ -888,16 +935,14 @@ function get_sub_list($filter, $category,$sub_deps, $base= "", $attributes= arra
       }else{
 
         /* Sort in every value that fits the permissions */
-        if (is_array($category)){
-          foreach ($category as $o){
-            if ($ui->get_category_permissions($dn, $o) != ""){
-              $result[]= $attrs;
-              break;
-            }
-          }
-        } else {
-          if ( $ui->get_category_permissions($dn, $category) != ""){
+        if (!is_array($category)){
+          $category = array($category);
+        }
+        foreach ($category as $o){
+          if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) ||
+              (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
             $result[]= $attrs;
+            break;
           }
         }
       }
@@ -958,19 +1003,14 @@ function get_list($filter, $category, $base= "", $attributes= array(), $flags= G
     }else{
 
       /* Sort in every value that fits the permissions */
-      if (is_array($category)){
-        foreach ($category as $o){
-          if ($ui->get_category_permissions($dn, $o) != ""){
-
-            /* We found what we were looking for, break speeds things up */
-            $result[]= $attrs;
-          }
-        }
-      } else {
-        if ($ui->get_category_permissions($dn, $category) != ""){
-
-          /* We found what we were looking for, break speeds things up */
+      if (!is_array($category)){
+        $category = array($category);
+      }
+      foreach ($category as $o){
+        if((preg_match("/\//",$o) && preg_match("/r/",$ui->get_permissions($dn,$o))) || 
+            (!preg_match("/\//",$o) && preg_match("/r/",$ui->get_category_permissions($dn, $o)))){
           $result[]= $attrs;
+          break;
         }
       }
     }
@@ -986,7 +1026,7 @@ function get_list($filter, $category, $base= "", $attributes= array(), $flags= G
 function check_sizelimit()
 {
   /* Ignore dialog? */
-  if (session::is_set('size_ignore') && session::get('size_ignore')){
+  if (session::global_is_set('size_ignore') && session::global_get('size_ignore')){
     return ("");
   }
 
@@ -994,8 +1034,8 @@ function check_sizelimit()
   if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){
     $smarty= get_smarty();
     $smarty->assign('warning', sprintf(_("The size limit of %d entries is exceed!"),
-          session::get('size_limit')));
-    $smarty->assign('limit_message', sprintf(_("Set the new size limit to %s and show me this message if the limit still exceeds"), '<input type="text" name="new_limit" maxlength="10" size="5" value="'.(session::get('size_limit') +100).'">'));
+          session::global_get('size_limit')));
+    $smarty->assign('limit_message', sprintf(_("Set the new size limit to %s and show me this message if the limit still exceeds"), '<input type="text" name="new_limit" maxlength="10" size="5" value="'.(session::global_get('size_limit') +100).'">'));
     return($smarty->fetch(get_template_path('sizelimit.tpl')));
   }
 
@@ -1005,7 +1045,7 @@ function check_sizelimit()
 
 function print_sizelimit_warning()
 {
-  if (session::is_set('size_limit') && session::get('size_limit') >= 10000000 ||
+  if (session::global_is_set('size_limit') && session::global_get('size_limit') >= 10000000 ||
       (session::is_set('limit_exceeded') && session::get('limit_exceeded'))){
     $config= "<input type='submit' name='edit_sizelimit' value="._("Configure").">";
   } else {
@@ -1026,25 +1066,25 @@ function eval_sizelimit()
     if (tests::is_id($_POST['new_limit']) &&
         isset($_POST['action']) && $_POST['action']=="newlimit"){
 
-      session::set('size_limit', validate($_POST['new_limit']));
+      session::global_set('size_limit', validate($_POST['new_limit']));
       session::set('size_ignore', FALSE);
     }
 
     /* User wants no limits? */
     if (isset($_POST['action']) && $_POST['action']=="ignore"){
-      session::set('size_limit', 0);
-      session::set('size_ignore', TRUE);
+      session::global_set('size_limit', 0);
+      session::global_set('size_ignore', TRUE);
     }
 
     /* User wants incomplete results */
     if (isset($_POST['action']) && $_POST['action']=="limited"){
-      session::set('size_ignore', TRUE);
+      session::global_set('size_ignore', TRUE);
     }
   }
   getMenuCache();
   /* Allow fallback to dialog */
   if (isset($_POST['edit_sizelimit'])){
-    session::set('size_ignore',FALSE);
+    session::global_set('size_ignore',FALSE);
   }
 }
 
@@ -1062,7 +1102,7 @@ function getMenuCache()
       if(session::is_set('maxC')){
         $b= session::get('maxC');
         $q= "";
-        for ($m=0;$m<strlen($b);$m++) {
+        for ($m=0, $l= strlen($b);$m<$l;$m++) {
           $q.= $b[$m++];
         }
         msg_dialog::display(_("Internal error"), base64_decode($q), ERROR_DIALOG);
@@ -1088,27 +1128,27 @@ function &get_smarty()
 }
 
 
-function convert_department_dn($dn)
+function convert_department_dn($dn, $base = NULL)
 {
-  $dep= "";
+  global $config;
+
+  if($base == NULL){
+    $base = $config->current['BASE'];
+  }
 
   /* Build a sub-directory style list of the tree level
      specified in $dn */
-  foreach (split(',', $dn) as $rdn){
+  $dn = preg_replace("/".preg_quote($base, '/')."$/i","",$dn);
+  if(empty($dn)) return("/");
 
-    /* We're only interested in organizational units... */
-    if (substr($rdn,0,3) == 'ou='){
-      $dep= substr($rdn,3)."/$dep";
-    }
 
-    /* ... and location objects */
-    if (substr($rdn,0,2) == 'l='){
-      $dep= substr($rdn,2)."/$dep";
-    }
+  $dep= "";
+  foreach (split(',', $dn) as $rdn){
+    $dep = preg_replace("/^[^=]+=/","",$rdn)."/".$dep;
   }
 
   /* Return and remove accidently trailing slashes */
-  return rtrim($dep, "/");
+  return(trim($dep, "/"));
 }
 
 
@@ -1116,7 +1156,7 @@ function convert_department_dn($dn)
  * style value. It removes the trailing '/', too. */
 function get_sub_department($value)
 {
-  return (@LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
+  return (LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value)));
 }
 
 
@@ -1125,36 +1165,41 @@ function get_ou($name)
   global $config;
 
   $map = array( 
-                "ogroupou"      => "ou=groups,",
-                "applicationou" => "ou=apps,",
-                "systemsou"     => "ou=systems,",
-                "serverou"      => "ou=servers,ou=systems,",
-                "terminalou"    => "ou=terminals,ou=systems,",
-                "workstationou" => "ou=workstations,ou=systems,",
-                "printerou"     => "ou=printers,ou=systems,",
-                "phoneou"       => "ou=phones,ou=systems,",
-                "componentou"   => "ou=netdevices,ou=systems,",
-                "blocklistou"   => "ou=gofax,ou=systems,",
-                "incomingou"    => "ou=incoming,",
-                "aclroleou"     => "ou=aclroles,",
-                "macroou"       => "ou=macros,ou=asterisk,ou=configs,ou=systems,",
-                "conferenceou"  => "ou=conferences,ou=asterisk,ou=configs,ou=systems,",
-
-                "faiou"         => "ou=fai,ou=configs,ou=systems,",
-                "faiscriptou"   => "ou=scripts,",
-                "faihookou"     => "ou=hooks,",
-                "faitemplateou" => "ou=templates,",
-                "faivariableou" => "ou=variables,",
-                "faiprofileou"  => "ou=profiles,",
-                "faipackageou"  => "ou=packages,",
-                "faipartitionou"=> "ou=disk,",
-
-                "deviceou"      => "ou=devices,",
-                "mimetypeou"    => "ou=mime,");
+                "roleRDN"      => "ou=roles,",
+                "ogroupRDN"      => "ou=groups,",
+                "applicationRDN" => "ou=apps,",
+                "systemRDN"     => "ou=systems,",
+                "serverRDN"      => "ou=servers,ou=systems,",
+                "terminalRDN"    => "ou=terminals,ou=systems,",
+                "workstationRDN" => "ou=workstations,ou=systems,",
+                "printerRDN"     => "ou=printers,ou=systems,",
+                "phoneRDN"       => "ou=phones,ou=systems,",
+                "componentRDN"   => "ou=netdevices,ou=systems,",
+                "sambaMachineAccountRDN"   => "ou=winstation,",
+
+                "faxBlocklistRDN"   => "ou=gofax,ou=systems,",
+                "systemIncomingRDN"    => "ou=incoming,",
+                "aclRoleRDN"     => "ou=aclroles,",
+                "phoneMacroRDN"       => "ou=macros,ou=asterisk,ou=configs,ou=systems,",
+                "phoneConferenceRDN"  => "ou=conferences,ou=asterisk,ou=configs,ou=systems,",
+
+                "faiBaseRDN"         => "ou=fai,ou=configs,ou=systems,",
+                "faiScriptRDN"   => "ou=scripts,",
+                "faiHookRDN"     => "ou=hooks,",
+                "faiTemplateRDN" => "ou=templates,",
+                "faiVariableRDN" => "ou=variables,",
+                "faiProfileRDN"  => "ou=profiles,",
+                "faiPackageRDN"  => "ou=packages,",
+                "faiPartitionRDN"=> "ou=disk,",
+
+                "sudoRDN"       => "ou=sudoers,",
+
+                "deviceRDN"      => "ou=devices,",
+                "mimetypeRDN"    => "ou=mime,");
 
   /* Preset ou... */
-  if (isset($config->current[strtoupper($name)])){
-    $ou= $config->current[strtoupper($name)];
+  if ($config->get_cfg_value($name, "_not_set_") != "_not_set_"){
+    $ou= $config->get_cfg_value($name);
   } elseif (isset($map[$name])) {
     $ou = $map[$name];
     return($ou);
@@ -1171,7 +1216,7 @@ function get_ou($name)
       $ou = @LDAP::convert("$ou");
     }
 
-    if(preg_match("/".normalizePreg($config->current['BASE'])."$/",$ou)){
+    if(preg_match("/".preg_quote($config->current['BASE'], '/')."$/",$ou)){
       return($ou);
     }else{
       return("$ou,");
@@ -1185,19 +1230,19 @@ function get_ou($name)
 
 function get_people_ou()
 {
-  return (get_ou("PEOPLE"));
+  return (get_ou("userRDN"));
 }
 
 
 function get_groups_ou()
 {
-  return (get_ou("GROUPS"));
+  return (get_ou("groupRDN"));
 }
 
 
 function get_winstations_ou()
 {
-  return (get_ou("WINSTATIONS"));
+  return (get_ou("sambaMachineAccountRDN"));
 }
 
 
@@ -1205,7 +1250,7 @@ function get_base_from_people($dn)
 {
   global $config;
 
-  $pattern= "/^[^,]+,".preg_quote(get_people_ou())."/i";
+  $pattern= "/^[^,]+,".preg_quote(get_people_ou(), '/')."/i";
   $base= preg_replace($pattern, '', $dn);
 
   /* Set to base, if we're not on a correct subtree */
@@ -1221,7 +1266,10 @@ function strict_uid_mode()
 {
   global $config;
 
-  return !(isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT']));
+  if (isset($config)){
+    return ($config->get_cfg_value("strictNamingRules") == "true");
+  }
+  return (TRUE);
 }
 
 
@@ -1237,7 +1285,7 @@ function get_uid_regexp()
 }
 
 
-function gen_locked_message($user, $dn)
+function gen_locked_message($user, $dn, $allow_readonly = FALSE)
 {
   global $plug, $config;
 
@@ -1274,7 +1322,7 @@ function gen_locked_message($user, $dn)
 
   /* Prepare and show template */
   $smarty= get_smarty();
-  
+  $smarty->assign("allow_readonly",$allow_readonly);
   if(is_array($dn)){
     $msg = "<pre>";
     foreach($dn as $sub_dn){
@@ -1291,7 +1339,7 @@ function gen_locked_message($user, $dn)
   } else {
     $smarty->assign ("action", _("Edit anyway"));
   }
-  $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry/entries '%s'"), "<b>".$msg."</b>", ""));
+  $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry/entries %s"), "<b>".$msg."</b>", ""));
 
   return ($smarty->fetch (get_template_path('islocked.tpl')));
 }
@@ -1329,7 +1377,7 @@ function rewrite($s)
   global $REWRITE;
 
   foreach ($REWRITE as $key => $val){
-    $s= preg_replace("/$key/", "$val", $s);
+    $s= str_replace("$key", "$val", $s);
   }
 
   return ($s);
@@ -1580,7 +1628,7 @@ function recurse($rule, $variables)
   unset ($variables[$key]);
 
   foreach($val as $possibility){
-    $nrule= preg_replace("/\{$key\}/", $possibility, $rule);
+    $nrule= str_replace("{$key}", $possibility, $rule);
     $result= array_merge($result, recurse($nrule, $variables));
   }
 
@@ -1598,7 +1646,7 @@ function expand_id($rule, $attributes)
   /* Check for clean attribute */
   if (preg_match('/^%[a-zA-Z0-9]+$/', $rule)){
     $rule= preg_replace('/^%/', '', $rule);
-    $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$rule])));
+    $val= rewrite(str_replace(' ', '', strtolower($attributes[$rule])));
     return (array($val));
   }
 
@@ -1606,7 +1654,7 @@ function expand_id($rule, $attributes)
   if (preg_match('/^%[a-zA-Z0-9]+\[[0-9-]+\]$/', $rule)){
     $param= preg_replace('/^[^[]+\[([^]]+)]$/', '\\1', $rule);
     $part= preg_replace('/^%/', '', preg_replace('/\[.*$/', '', $rule));
-    $val= rewrite(preg_replace('/ /', '', strtolower($attributes[$part])));
+    $val= rewrite(str_replace(' ', '', strtolower($attributes[$part])));
     $start= preg_replace ('/-.*$/', '', $param);
     $stop = preg_replace ('/^[^-]+-/', '', $param);
 
@@ -1618,7 +1666,7 @@ function expand_id($rule, $attributes)
     return ($result);
   }
 
-  echo "Error in idgen string: don't know how to handle rule $rule.\n";
+  echo "Error in idGenerator string: don't know how to handle rule $rule.\n";
   return (array($rule));
 }
 
@@ -1634,7 +1682,7 @@ function gen_uids($rule, $attributes)
   $stripped= "";
   $variables= array();
 
-  for ($pos= 0; $pos < strlen($rule); $pos++){
+  for ($pos= 0, $l= strlen($rule); $pos < $l; $pos++){
 
     if ($rule[$pos] == "{" ){
       $trigger= true;
@@ -1677,7 +1725,7 @@ function gen_uids($rule, $attributes)
     if(preg_match('/\{id:\d+}/',$uid)){
       $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
 
-      for ($i= 0; $i < pow(10,$size); $i++){
+      for ($i= 0, $p= pow(10,$size); $i < $p; $i++){
         $number= sprintf("%0".$size."d", $i);
         $res= preg_replace('/{id:(\d+)}/', $number, $uid);
         if (!in_array($res, $used)){
@@ -1687,27 +1735,28 @@ function gen_uids($rule, $attributes)
       }
     }
 
-  if(preg_match('/\{id#\d+}/',$uid)){
-    $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
+    if(preg_match('/\{id#\d+}/',$uid)){
+      $size= preg_replace('/^.*{id#(\d+)}.*$/', '\\1', $uid);
 
-    while (true){
-      mt_srand((double) microtime()*1000000);
-      $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
-      $res= preg_replace('/{id#(\d+)}/', $number, $uid);
-      if (!in_array($res, $used)){
-        $uid= $res;
-        break;
+      while (true){
+        mt_srand((double) microtime()*1000000);
+        $number= sprintf("%0".$size."d", mt_rand(0, pow(10, $size)-1));
+        $res= preg_replace('/{id#(\d+)}/', $number, $uid);
+        if (!in_array($res, $used)){
+          $uid= $res;
+          break;
+        }
       }
     }
-  }
 
-/* Don't assign used ones */
-if (!in_array($uid, $used)){
-  $ret[]= $uid;
-}
-}
+    /* Don't assign used ones */
+    if (!in_array($uid, $used)){
+      /* Add uid, but remove {} first. These are invalid anyway. */
+      $ret[]= preg_replace('/[{}]/', '', $uid);
+    }
+  }
 
-return(array_unique($ret));
+  return(array_unique($ret));
 }
 
 
@@ -1739,18 +1788,8 @@ function to_byte($value) {
 
 function in_array_ics($value, $items)
 {
-  if (!is_array($items)){
-    return (FALSE);
-  }
-
-  foreach ($items as $item){
-    if (strcasecmp($item, $value) == 0) {
-      return (TRUE);
-    }
-  }
-
-  return (FALSE);
-} 
+       return preg_grep('/^'.preg_quote($value, '/').'$/i', $items);
+}
 
 
 function generate_alphabet($count= 10)
@@ -1760,7 +1799,7 @@ function generate_alphabet($count= 10)
   $c= 0;
 
   /* Fill cells with charaters */
-  for ($i= 0; $i<mb_strlen($characters, 'UTF8'); $i++){
+  for ($i= 0, $l= mb_strlen($characters, 'UTF8'); $i<$l; $i++){
     if ($c == 0){
       $alphabet.= "<tr>";
     }
@@ -1786,7 +1825,7 @@ function generate_alphabet($count= 10)
 
 function validate($string)
 {
-  return (strip_tags(preg_replace('/\0/', '', $string)));
+  return (strip_tags(str_replace('\0', '', $string)));
 }
 
 
@@ -1944,58 +1983,19 @@ function compare_revision($revision_file, $revision)
 
 function progressbar($percentage,$width=100,$height=15,$showvalue=false)
 {
-  $str = ""; // Our return value will be saved in this var
-
-  $color  = dechex($percentage+150);
-  $color2 = dechex(150 - $percentage);
-  $bgcolor= $showvalue?"FFFFFF":"DDDDDD";
-
-  $progress = (int)(($percentage /100)*$width);
-
-  /* Abort printing out percentage, if divs are to small */
-
-
-  /* If theres a better solution for this, use it... */
-  $str = "
-    <div style=\" width:".($width)."px; 
-    height:".($height)."px;
-  background-color:#000000;
-padding:1px;\">
-
-          <div style=\" width:".($width)."px;
-        background-color:#$bgcolor;
-height:".($height)."px;\">
-
-         <div style=\" width:".$progress."px;
-height:".$height."px;
-       background-color:#".$color2.$color2.$color."; \">";
-
-
-       if(($height >10)&&($showvalue)){
-         $str.=                 "<font style=\"font-size:".($height-2)."px;color:#FF0000;align:middle;padding-left:".((int)(($width*0.4)))."px;\">
-           <b>".$percentage."%</b>
-           </font>";
-       }
-
-       $str.= "</div></div></div>";
-
-       return($str);
+  return("<img src='progress.php?x=$width&amp;y=$height&amp;p=$percentage'>");
 }
 
 
 function array_key_ics($ikey, $items)
 {
-  /* Gather keys, make them lowercase */
-  $tmp= array();
-  foreach ($items as $key => $value){
-    $tmp[strtolower($key)]= $key;
+  $tmp= array_change_key_case($items, CASE_LOWER);
+  $ikey= strtolower($ikey);
+  if (isset($tmp[$ikey])){
+    return($tmp[$ikey]);
   }
 
-  if (isset($tmp[strtolower($ikey)])){
-    return($tmp[strtolower($ikey)]);
-  }
-
-  return ("");
+  return ('');
 }
 
 
@@ -2006,15 +2006,7 @@ function array_differs($src, $dst)
     return (TRUE);
   }
 
-  /* So the count is the same - lets check the contents */
-  $differs= FALSE;
-  foreach($src as $value){
-    if (!in_array($value, $dst)){
-      $differs= TRUE;
-    }
-  }
-
-  return ($differs);
+  return (count(array_diff($src, $dst)) != 0);
 }
 
 
@@ -2045,13 +2037,6 @@ function saveFilter($a_filter, $values)
 }
 
 
-/* Escape all preg_* relevant characters */
-function normalizePreg($input)
-{
-  return (addcslashes($input, '[]()|/.*+-'));
-}
-
-
 /* Escape all LDAP filter relevant characters */
 function normalizeLdap($input)
 {
@@ -2161,10 +2146,10 @@ function get_base_from_hook($dn, $attrib)
 {
   global $config;
 
-  if (isset($config->current['BASE_HOOK'])){
+  if ($config->get_cfg_value("baseIdHook") != ""){
     
     /* Call hook script - if present */
-    $command= $config->current['BASE_HOOK'];
+    $command= $config->get_cfg_value("baseIdHook");
 
     if ($command != ""){
       $command.= " '".LDAP::fix($dn)."' $attrib";
@@ -2174,18 +2159,18 @@ function get_base_from_hook($dn, $attrib)
         if (preg_match("/^[0-9]+$/", $output[0])){
           return ($output[0]);
         } else {
-          msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base!"), WARNING_DIALOG);
-          return ($config->current['UIDBASE']);
+          msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
+          return ($config->get_cfg_value("uidNumberBase"));
         }
       } else {
-        msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base!"), WARNING_DIALOG);
-        return ($config->current['UIDBASE']);
+        msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
+        return ($config->get_cfg_value("uidNumberBase"));
       }
 
     } else {
 
-      msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base!"), WARNING_DIALOG);
-      return ($config->current['UIDBASE']);
+      msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG);
+      return ($config->get_cfg_value("uidNumberBase"));
 
     }
   }
@@ -2203,7 +2188,7 @@ function check_schema($cfg,$rfc2307bis = FALSE)
   $messages= array();
 
   /* Get objectclasses */
-  $ldap = new ldapMultiplexer(new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE,$cfg['tls']));
+  $ldap = new ldapMultiplexer(new LDAP($cfg['admin'],$cfg['password'],$cfg['connection'] ,FALSE, $cfg['tls']));
   $objectclasses = $ldap->get_objectclasses();
   if(count($objectclasses) == 0){
     msg_dialog::display(_("LDAP warning"), _("Cannot get schema information from server. No schema check possible!"), WARNING_DIALOG);
@@ -2222,20 +2207,20 @@ function check_schema($cfg,$rfc2307bis = FALSE)
 
   /* The gosa base schema */
   $checks['gosaObject'] = $def_check;
-  $checks['gosaObject']['REQUIRED_VERSION'] = "2.4";
+  $checks['gosaObject']['REQUIRED_VERSION'] = "2.6.1";
   $checks['gosaObject']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
   $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject");
   $checks['gosaObject']['IS_MUST_HAVE']     = TRUE;
 
   /* GOsa Account class */
-  $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4";
+  $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.6.1";
   $checks["gosaAccount"]["SCHEMA_FILES"]    = array("gosa+samba3.schema","gosa.schema");
   $checks["gosaAccount"]["CLASSES_REQUIRED"]= array("gosaAccount");
   $checks["gosaAccount"]["IS_MUST_HAVE"]    = TRUE;
   $checks["gosaAccount"]["INFO"]            = _("Used to store account specific informations.");
 
   /* GOsa lock entry, used to mark currently edited objects as 'in use' */
-  $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.4";
+  $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.6.1";
   $checks["gosaLockEntry"]["SCHEMA_FILES"]     = array("gosa+samba3.schema","gosa.schema");
   $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry");
   $checks["gosaLockEntry"]["IS_MUST_HAVE"]     = TRUE;
@@ -2243,28 +2228,28 @@ function check_schema($cfg,$rfc2307bis = FALSE)
 
   /* Some other checks */
   foreach(array(
-        "gosaCacheEntry"        => array("version" => "2.4"),
-        "gosaDepartment"        => array("version" => "2.4"),
+        "gosaCacheEntry"        => array("version" => "2.6.1"),
+        "gosaDepartment"        => array("version" => "2.6.1"),
         "goFaxAccount"          => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
         "goFaxSBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
         "goFaxRBlock"           => array("version" => "1.0.4", "class" => "gofaxAccount","file" => "gofax.schema"),
-        "gosaUserTemplate"      => array("version" => "2.4", "class" => "posixAccount","file" => "nis.schema"),
-        "gosaMailAccount"       => array("version" => "2.4", "class" => "mailAccount","file" => "gosa+samba3.schema"),
-        "gosaProxyAccount"      => array("version" => "2.4", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
-        "gosaApplication"       => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
-        "gosaApplicationGroup"  => array("version" => "2.4", "class" => "appgroup","file" => "gosa.schema"),
-        "GOhard"                => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
-        "gotoTerminal"          => array("version" => "2.5", "class" => "terminals","file" => "goto.schema"),
-        "goServer"              => array("version" => "2.4","class" => "server","file" => "goserver.schema"),
-        "goTerminalServer"      => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
-        "goShareServer"         => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
-        "goNtpServer"           => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
-        "goSyslogServer"        => array("version" => "2.4", "class" => "terminals","file" => "goto.schema"),
-        "goLdapServer"          => array("version" => "2.4"),
-        "goCupsServer"          => array("version" => "2.4", "class" => array("posixAccount", "terminals"),),
-        "goImapServer"          => array("version" => "2.4", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3.        schema"),
-        "goKrbServer"           => array("version" => "2.4"),
-        "goFaxServer"           => array("version" => "2.4", "class" => "gofaxAccount","file" => "gofax.schema"),
+        "gosaUserTemplate"      => array("version" => "2.6.1", "class" => "posixAccount","file" => "nis.schema"),
+        "gosaMailAccount"       => array("version" => "2.6.1", "class" => "mailAccount","file" => "gosa+samba3.schema"),
+        "gosaProxyAccount"      => array("version" => "2.6.1", "class" => "proxyAccount","file" => "gosa+samba3.schema"),
+        "gosaApplication"       => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
+        "gosaApplicationGroup"  => array("version" => "2.6.1", "class" => "appgroup","file" => "gosa.schema"),
+        "GOhard"                => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
+        "gotoTerminal"          => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
+        "goServer"              => array("version" => "2.6.1","class" => "server","file" => "goserver.schema"),
+        "goTerminalServer"      => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
+        "goShareServer"         => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
+        "goNtpServer"           => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
+        "goSyslogServer"        => array("version" => "2.6.1", "class" => "terminals","file" => "goto.schema"),
+        "goLdapServer"          => array("version" => "2.6.1"),
+        "goCupsServer"          => array("version" => "2.6.1", "class" => array("posixAccount", "terminals"),),
+        "goImapServer"          => array("version" => "2.6.1", "class" => array("mailAccount", "mailgroup"),"file" => "gosa+samba3.        schema"),
+        "goKrbServer"           => array("version" => "2.6.1"),
+        "goFaxServer"           => array("version" => "2.6.1", "class" => "gofaxAccount","file" => "gofax.schema"),
         ) as $name => $values){
 
           $checks[$name] = $def_check;
@@ -2305,7 +2290,7 @@ function check_schema($cfg,$rfc2307bis = FALSE)
 
   /* The gosa base schema */
   $checks['posixGroup'] = $def_check;
-  $checks['posixGroup']['REQUIRED_VERSION'] = "2.4";
+  $checks['posixGroup']['REQUIRED_VERSION'] = "2.6.1";
   $checks['posixGroup']['SCHEMA_FILES']     = array("gosa+samba3.schema","gosa.schema");
   $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup");
   $checks['posixGroup']['STATUS']           = TRUE;
@@ -2342,8 +2327,9 @@ function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FA
         "en_US" => "English",
         "nl_NL" => "Dutch",
         "pl_PL" => "Polish",
-        "sv_SE" => "Swedish",
+        #"sv_SE" => "Swedish",
         "zh_CN" => "Chinese",
+        "vi_VN" => "Vietnamese",
         "ru_RU" => "Russian");
   
   $tmp2= array(
@@ -2354,14 +2340,25 @@ function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FA
         "en_US" => _("English"),
         "nl_NL" => _("Dutch"),
         "pl_PL" => _("Polish"),
-        "sv_SE" => _("Swedish"),
+        #"sv_SE" => _("Swedish"),
         "zh_CN" => _("Chinese"),
+        "vi_VN" => _("Vietnamese"),
         "ru_RU" => _("Russian"));
 
   $ret = array();
   if($languages_in_own_language){
 
     $old_lang = setlocale(LC_ALL, 0);
+
+    /* If the locale wasn't correclty set before, there may be an incorrect
+        locale returned. Something like this: 
+          C_CTYPE=de_DE.UTF-8;LC_NUMERIC=C;LC_TIME=de_DE.UTF-8;LC ...
+        Extract the locale name from this string and use it to restore old locale.
+     */
+    if(preg_match("/LC_CTYPE/",$old_lang)){
+      $old_lang = preg_replace("/^.*LC_CTYPE=([^;]*).*$/","\\1",$old_lang);
+    }
+    
     foreach($tmp as $key => $name){
       $lang = $key.".UTF-8";
       setlocale(LC_ALL, $lang);
@@ -2435,13 +2432,6 @@ function change_password ($dn, $password, $mode=0, $hash= "")
   $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
   $attrs      = $ldap->fetch ();
 
-  // Check if user account was deactivated, indicated by ! after } ... {crypt}!###
-  if(isset($attrs['userPassword'][0]) && preg_match("/^[^\}]*+\}!/",$attrs['userPassword'][0])){
-    $deactivated = TRUE;
-  }else{
-    $deactivated = FALSE;
-  }
-
   /* Is ensure that clear passwords will stay clear */
   if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
     $hash = "clear";
@@ -2455,9 +2445,9 @@ function change_password ($dn, $password, $mode=0, $hash= "")
 
     /* Extract used hash */
     if ($hash == ""){
-      $test = passwordMethod::get_method($attrs['userPassword'][0]);
+      $test = passwordMethod::get_method($attrs['userPassword'][0],$dn);
     } else {
-      $test = new $available[$hash]($config);
+      $test = new $available[$hash]($config,$dn);
       $test->set_hash($hash);
     }
 
@@ -2467,68 +2457,76 @@ function change_password ($dn, $password, $mode=0, $hash= "")
     $test = new  $available['md5']($config);
   }
 
-  /* Feed password backends with information */
-  $test->dn= $dn;
-  $test->attrs= $attrs;
-  $newpass= $test->generate_hash($password);
-
-  // Update shadow timestamp?
-  if (isset($attrs["shadowLastChange"][0])){
-    $shadow= (int)(date("U") / 86400);
-  } else {
-    $shadow= 0;
-  }
+  if($test instanceOf passwordMethod){
 
-  // Write back modified entry
-  $ldap->cd($dn);
-  $attrs= array();
+    $deactivated = $test->is_locked($config,$dn);
 
-  // Not for groups
-  if ($mode == 0){
+    /* Feed password backends with information */
+    $test->dn= $dn;
+    $test->attrs= $attrs;
+    $newpass= $test->generate_hash($password);
 
-    if ($shadow != 0){
-      $attrs['shadowLastChange']= $shadow;
+    // Update shadow timestamp?
+    if (isset($attrs["shadowLastChange"][0])){
+      $shadow= (int)(date("U") / 86400);
+    } else {
+      $shadow= 0;
     }
 
-    // Create SMB Password
-    $attrs= generate_smb_nt_hash($password);
-  }
+    // Write back modified entry
+    $ldap->cd($dn);
+    $attrs= array();
 
- /* Read ! if user was deactivated */
-  if($deactivated){
-    $newpass = preg_replace("/(^[^\}]+\})(.*$)/","\\1!\\2",$newpass);
-  }
+    // Not for groups
+    if ($mode == 0){
 
-  $attrs['userPassword']= array();
-  $attrs['userPassword']= $newpass;
+      if ($shadow != 0){
+        $attrs['shadowLastChange']= $shadow;
+      }
 
-  $ldap->modify($attrs);
+      // Create SMB Password
+      $attrs= generate_smb_nt_hash($password);
+    }
 
-  new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
+    $attrs['userPassword']= array();
+    $attrs['userPassword']= $newpass;
 
-  if (!$ldap->success()) {
-    msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, ERROR_DIALOG));
-  } else {
+    $ldap->modify($attrs);
 
-    /* Run backend method for change/create */
-    $test->set_password($password);
+    /* Read ! if user was deactivated */
+    if($deactivated){
+      $test->lock_account($config,$dn);
+    }
 
-    /* Find postmodify entries for this class */
-    $command= $config->search("password", "POSTMODIFY",array('menu'));
+    new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
 
-    if ($command != ""){
-      /* Walk through attribute list */
-      $command= preg_replace("/%userPassword/", $password, $command);
-      $command= preg_replace("/%dn/", $dn, $command);
+    if (!$ldap->success()) {
+      msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, ERROR_DIALOG));
+    } else {
 
-      if (check_command($command)){
-        @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
-        exec($command);
-      } else {
-        $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
-        msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
+      /* Run backend method for change/create */
+      if(!$test->set_password($password)){
+        return(FALSE);
+      }
+
+      /* Find postmodify entries for this class */
+      $command= $config->search("password", "POSTMODIFY",array('menu'));
+
+      if ($command != ""){
+        /* Walk through attribute list */
+        $command= preg_replace("/%userPassword/", $password, $command);
+        $command= preg_replace("/%dn/", $dn, $command);
+
+        if (check_command($command)){
+          @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
+          exec($command);
+        } else {
+          $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
+          msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
+        }
       }
     }
+    return(TRUE);
   }
 }
 
@@ -2539,31 +2537,36 @@ function generate_smb_nt_hash($password)
   global $config;
 
   # Try to use gosa-si?
-  if (isset($config->current['GOSA_SI'])){
+  if ($config->get_cfg_value("gosaSupportURI") != ""){
        $res= gosaSupportDaemon::send("gosa_gen_smb_hash", "GOSA", array("password" => $password), TRUE);
     if (isset($res['XML']['HASH'])){
        $hash= $res['XML']['HASH'];
     } else {
       $hash= "";
     }
+
+    if ($hash == "") {
+      msg_dialog::display(_("Configuration error"), _("Cannot generate samba hash!"), ERROR_DIALOG);
+      return ("");
+    }
   } else {
-         $tmp= $config->data['MAIN']['SMBHASH']." ".escapeshellarg($password);
+         $tmp= $config->get_cfg_value('sambaHashHook')." ".escapeshellarg($password);
          @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute");
 
          exec($tmp, $ar);
          flush();
          reset($ar);
          $hash= current($ar);
-  }
 
-  if ($hash == "") {
-         msg_dialog::display(_("Configuration error"), _("Cannot generate samba hash!"), ERROR_DIALOG);
-         return ("");
+    if ($hash == "") {
+      msg_dialog::display(_("Configuration error"), sprintf(_("Cannot generate samba hash: running '%s' failed, check the 'sambaHashHook'!"),$config->get_cfg_value('sambaHashHook')), ERROR_DIALOG);
+      return ("");
+    }
   }
 
   list($lm,$nt)= split (":", trim($hash));
 
-  if ($config->current['SAMBAVERSION'] == 3) {
+  if ($config->get_cfg_value("sambaversion") == 3) {
          $attrs['sambaLMPassword']= $lm;
          $attrs['sambaNTPassword']= $nt;
          $attrs['sambaPwdLastSet']= date('U');
@@ -2586,12 +2589,8 @@ function getEntryCSN($dn)
   }
 
   /* Get attribute that we should use as serial number */
-  if(isset($config->current['UNIQ_IDENTIFIER'])){
-    $attr = $config->current['UNIQ_IDENTIFIER'];
-  }elseif(isset($config->data['MAIN']['UNIQ_IDENTIFIER'])){
-    $attr = $config->data['MAIN']['UNIQ_IDENTIFIER'];
-  }
-  if(!empty($attr)){
+  $attr= $config->get_cfg_value("modificationDetectionAttribute");
+  if($attr != ""){
     $ldap = $config->get_ldap_link();
     $ldap->cat($dn,array($attr));
     $csn = $ldap->fetch();
@@ -2632,7 +2631,7 @@ function remove_objectClass($classes, &$attrs)
     $tmp= array();
     foreach ($attrs['objectClass'] as $oc) {
       foreach ($list as $class){
-        if ($oc != $class){
+        if (strtolower($oc) != strtolower($class)){
           $tmp[]= $oc;
         }
       }
@@ -2655,6 +2654,13 @@ function send_binary_content($data,$name,$type = "application/octet-stream")
   header("Cache-Control: post-check=0, pre-check=0");
   header("Content-type: ".$type."");
 
+  $HTTP_USER_AGENT = $_SERVER['HTTP_USER_AGENT'];
+
+  /* Strip name if it is a complete path */
+  if (preg_match ("/\//", $name)) {
+       $name= basename($name);
+  }
+  
   /* force download dialog */
   if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) || preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
     header('Content-Disposition: filename="'.$name.'"');
@@ -2667,17 +2673,84 @@ function send_binary_content($data,$name,$type = "application/octet-stream")
 }
 
 
+function reverse_html_entities($str,$type = ENT_QUOTES , $charset = "UTF-8")
+{
+  if(is_string($str)){
+    return(htmlentities($str,$type,$charset));
+  }elseif(is_array($str)){
+    foreach($str as $name => $value){
+      $str[$name] = reverse_html_entities($value,$type,$charset);
+    }
+  }
+  return($str);
+}
+
+
 /*! \brief Encode special string characters so we can use the string in \
            HTML output, without breaking quotes.
     @param  The String we want to encode.
     @return The encoded String
-*/
+ */
 function xmlentities($str)
 { 
   if(is_string($str)){
-    return(htmlentities($str,ENT_QUOTES));
-  }else{
-    return($str);
+
+    static $asc2uni= array();
+    if (!count($asc2uni)){
+      for($i=128;$i<256;$i++){
+    #    $asc2uni[chr($i)] = "&#x".dechex($i).";";
+      }
+    }
+
+    $str = str_replace("&", "&amp;", $str);
+    $str = str_replace("<", "&lt;", $str);
+    $str = str_replace(">", "&gt;", $str);
+    $str = str_replace("'", "&apos;", $str);
+    $str = str_replace("\"", "&quot;", $str);
+    $str = str_replace("\r", "", $str);
+    $str = strtr($str,$asc2uni);
+    return $str;
+  }elseif(is_array($str)){
+    foreach($str as $name => $value){
+      $str[$name] = xmlentities($value);
+    }
+  }
+  return($str);
+}
+
+
+/*! \brief  Updates all accessTo attributes from a given value to a new one.
+            For example if a host is renamed.
+    @param  String  $from The source accessTo name.
+    @param  String  $to   The destination accessTo name.
+*/
+function update_accessTo($from,$to)
+{
+  global $config;
+  $ldap = $config->get_ldap_link();
+  $ldap->cd($config->current['BASE']);
+  $ldap->search("(&(objectClass=trustAccount)(accessTo=".$from."))",array("objectClass","accessTo"));
+  while($attrs = $ldap->fetch()){
+    $new_attrs = array("accessTo" => array());
+    $dn = $attrs['dn'];
+    for($i = 0 ; $i < $attrs['objectClass']['count']; $i++){
+      $new_attrs['objectClass'][] =  $attrs['objectClass'][$i];
+    }
+    for($i = 0 ; $i < $attrs['accessTo']['count']; $i++){
+      if($attrs['accessTo'][$i] == $from){
+        if(!empty($to)){
+          $new_attrs['accessTo'][] =  $to;
+        }
+      }else{
+        $new_attrs['accessTo'][] =  $attrs['accessTo'][$i]; 
+      }
+    }
+    $ldap->cd($dn);
+    $ldap->modify($new_attrs);
+    if (!$ldap->success()){
+      msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, "update_accessTo($from,$to)"));
+    }
+    new log("modify","update_accessTo($from,$to)",$dn,array_keys($new_attrs),$ldap->get_error());
   }
 }
 
@@ -2691,7 +2764,35 @@ function get_random_char () {
      } else {
          return (chr ($randno + 59)); // Lowercase
      }
-  }
+}
+
+
+function cred_encrypt($input, $password) {
+
+  $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
+  $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
+
+  return bin2hex(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $password, $input, MCRYPT_MODE_ECB, $iv));
+
+}
+
+function cred_decrypt($input,$password) {
+  $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
+  $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
+
+  return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $password, pack("H*", $input), MCRYPT_MODE_ECB, $iv);
+}
+
+function get_object_info()
+{
+  return(session::get('objectinfo'));
+}
+
+function set_object_info($str = "")
+{
+  session::set('objectinfo',$str);
+}
+
 
 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
 ?>