Code

Updated a couple of values
[gosa.git] / gosa-core / include / functions.inc
index 193524d263219379ac87708c253ead23e821fedf..f58ed2a2e60ab73da2d552bd8bbf1711abc85f30 100644 (file)
@@ -1,7 +1,9 @@
 <?php
 /*
- * This code is part of GOsa (https://gosa.gonicus.de)
- * Copyright (C) 2003 Cajus Pollmeier
+ * This code is part of GOsa (http://www.gosa-project.org)
+ * Copyright (C) 2003-2008 GONICUS GmbH
+ *
+ * ID: $$Id$$
  *
  * 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.5
+ */
+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);
@@ -50,8 +69,8 @@ define('DES3_CBC_MD5',5);
 define('DES3_CBC_SHA1',16);
 
 /* Define globals for revision comparing */
-$svn_path = '$HeadURL$';
-$svn_revision = '$Revision$';
+$svn_path = '$HeadURL: https://oss.gonicus.de/repositories/gosa/trunk/gosa-core/include/functions.inc $';
+$svn_revision = '$Revision: 9246 $';
 
 /* Include required files */
 require_once("class_location.inc");
@@ -67,6 +86,7 @@ define ("DEBUG_POST",   16);
 define ("DEBUG_SESSION",32);
 define ("DEBUG_CONFIG", 64);
 define ("DEBUG_ACL",    128);
+define ("DEBUG_SI",     256);
 
 /* Rewrite german 'umlauts' and spanish 'accents'
    to get better results */
@@ -173,8 +193,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";
     }
@@ -211,10 +231,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 */
@@ -273,6 +294,21 @@ function array_remove_entries($needles, $haystack)
 }
 
 
+function array_remove_entries_ics($needles, $haystack)
+{
+  $tmp= array();
+
+  /* Loop through entries to be removed */
+  foreach ($haystack as $entry){
+    if (!in_array_ics($entry, $needles)){
+      $tmp[]= $entry;
+    }
+  }
+
+  return ($tmp);
+}
+
+
 function gosa_array_merge($ar1,$ar2)
 {
   if(!is_array($ar1) || !is_array($ar2)){
@@ -312,8 +348,10 @@ function ldap_init ($server, $base, $binddn='', $pass='')
       isset($config->current['TLS']) && $config->current['TLS'] == "true");
 
   /* Sadly we've no proper return values here. Use the error message instead. */
-  if (!preg_match("/Success/i", $ldap->error)){
-    echo sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error());
+  if (!$ldap->success()){
+    msg_dialog::display(_("Fatal error"),
+        sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error()),
+        FATAL_ERROR_DIALOG);
     exit();
   }
 
@@ -332,17 +370,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("krbsasl") == "true"){
       $mode= "sasl";
     }
 
     /* Look for entry or realm */
     $ldap= $config->get_ldap_link();
-    if (!preg_match("/Success/i", $ldap->error)){
-      msg_dialog::display(_("LDAP error"), sprintf(_('User login failed.').'<br><br>'._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
-      $smarty= get_smarty();
-      $smarty->display(get_template_path('headers.tpl'));
-      echo "<body>".session::get('errors')."</body></html>";
+    if (!$ldap->success()){
+      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"));
@@ -365,17 +402,16 @@ function ldap_login_user_htaccess ($username)
 
   /* Look for entry or realm */
   $ldap= $config->get_ldap_link();
-  if (!preg_match("/Success/i", $ldap->error)){
-    msg_dialog::display(_("LDAP error"), sprintf(_('User login failed.').'<br><br>'._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
-    $smarty= get_smarty();
-    $smarty->display(get_template_path('headers.tpl'));
-    echo "<body>".session::get('errors')."</body></html>";
+  if (!$ldap->success()){
+    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"));
   /* Found no uniq match? Strange, because we did above... */
   if ($ldap->count() != 1) {
-    msg_dialog::display(_("LDAP error"), _("Username / UID is not unique inside the LDAP tree. Please contact your Administrator."), ERROR_DIALOG);
+    msg_dialog::display(_("LDAP error"), _("Username / UID is not unique inside the LDAP tree!"), FATAL_ERROR_DIALOG);
     return (NULL);
   }
   $attrs= $ldap->fetch();
@@ -403,18 +439,17 @@ function ldap_login_user ($username, $password)
 
   /* look through the entire ldap */
   $ldap = $config->get_ldap_link();
-  if (!preg_match("/Success/i", $ldap->error)){
-    msg_dialog::display(_("LDAP error"), sprintf(_("User login failed.")."<br><br>"._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
-    $smarty= get_smarty();
-    $smarty->display(get_template_path('headers.tpl'));
-    echo "<body>".session::get('errors')."</body></html>";
+  if (!$ldap->success()){
+    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("login_attribute") != ""){
+    $tmp = split(",", $config->get_cfg_value("login_attribute")); 
     foreach($tmp as $attr){
       if(in_array($attr,$allowed_attributes)){
         $verify_attr[] = $attr;
@@ -445,7 +480,7 @@ function ldap_login_user ($username, $password)
 
             /* found more than one matching id */
     default:
-            msg_dialog::display(_("Internal error"), _("Username / UID is not unique inside the LDAP tree. Please contact your Administrator."), ERROR_DIALOG);
+            msg_dialog::display(_("Internal error"), _("Username / UID is not unique inside the LDAP tree. Please contact your Administrator."), FATAL_ERROR_DIALOG);
             return (NULL);
   }
 
@@ -472,7 +507,7 @@ function ldap_login_user ($username, $password)
       $config->current['RECURSIVE'] == "true",
       isset($config->current['TLS'])
       && $config->current['TLS'] == "true");
-  if (!preg_match("/Success/i", $ldap->error)){
+  if (!$ldap->success()){
     return (NULL);
   }
 
@@ -596,10 +631,10 @@ 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 (!preg_match("/Success/i", $ldap->error)){
+  if (!$ldap->success()){
     msg_dialog::display(_("Configuration error"), sprintf(_("Cannot create locking information in LDAP tree. Please contact your administrator!")."<br><br>"._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
     return;
   }
@@ -608,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 (!preg_match("/Success/i", $ldap->error)){
-      msg_dialog::display(_("Internal error"), sprintf(_("Adding a lock failed.")."<br><br>"._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
+    if (!$ldap->success()){
+      msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "cn=$name,".$config->get_cfg_value("config"), 0, ERROR_DIALOG));
       return;
     }
   }
@@ -640,14 +675,14 @@ function del_lock ($object)
 
   /* 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() != "" && preg_match("/Success/i", $ldap->error)){
+  if ($ldap->getDN() != "" && $ldap->success()){
     $ldap->rmdir ($ldap->getDN());
 
-    if (!preg_match("/Success/i", $ldap->error)){
-      msg_dialog::display(_("LDAP error"), sprintf(_("Removing a lock failed.")."<br><br>"._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
+    if (!$ldap->success()){
+      msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $ldap->getDN(), LDAP_DEL, ERROR_DIALOG));
       return;
     }
   }
@@ -660,7 +695,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"));
@@ -683,10 +718,10 @@ function get_lock ($object)
   /* 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 (!preg_match("/Success/i", $ldap->error)){
-    msg_dialog::display(_("LDAP error"), sprintf(_("Cannot get locking information from LDAP tree!")."<br><br>"._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
+  if (!$ldap->success()){
+    msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
     return("");
   }
 
@@ -728,10 +763,10 @@ 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 (!preg_match("/Success/i", $ldap->error)){
-    msg_dialog::display(_("LDAP error"), sprintf(_("Cannot get locking information from LDAP tree!")."<br><br>"._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
+  if (!$ldap->success()){
+    msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "", LDAP_SEARCH, ERROR_DIALOG));
     return("");
   }
 
@@ -755,51 +790,91 @@ function get_multiple_locks($objects)
     @param $attributes Array The attributes we search for.
     @param $flags     Long   A set of Flags
  */
-function get_sub_list($filter, $category,$sub_bases, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
+function get_sub_list($filter, $category,$sub_deps, $base= "", $attributes= array(), $flags= GL_SUBSEARCH)
 {
   global $config, $ui;
+  $departments = array();
+
+#  $start = microtime(TRUE);
 
   /* Get LDAP link */
   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
 
   /* Set search base to configured base if $base is empty */
   if ($base == ""){
-    $ldap->cd ($config->current['BASE']);
-  } else {
-    $ldap->cd ($base);
+    $base = $config->current['BASE'];
   }
+  $ldap->cd ($base);
 
   /* Ensure we have an array as department list */
-  if(is_string($sub_bases)){
-    $sub_bases = array($sub_bases);
-  }
-
-  /* Remove , ("ou=1,ou=2.." => "ou=1") */
-  foreach($sub_bases as $key => $sub_base){
-    $sub_bases[$key] = preg_replace("/,.*$/","",$sub_base);
+  if(is_string($sub_deps)){
+    $sub_deps = array($sub_deps);
+  }
+
+  /* Remove ,.*$ ("ou=1,ou=2.." => "ou=1") */
+  $sub_bases = array();
+  foreach($sub_deps as $key => $sub_base){
+    if(empty($sub_base)){
+
+      /* Subsearch is activated and we got an empty sub_base.
+       *  (This may be the case if you have empty people/group ous).
+       * Fall back to old get_list(). 
+       * A log entry will be written.
+       */
+      if($flags & GL_SUBSEARCH){
+        $sub_bases = array();
+        break;
+      }else{
+        
+        /* Do NOT search within subtrees is requeste and the sub base is empty. 
+         * Append all known departments that matches the base.
+         */
+        $departments[$base] = $base;
+      }
+    }else{
+      $sub_bases[$key] = preg_replace("/,.*$/","",$sub_base);
+    }
   }
-
-  /* Check if we have enabled the sub_dir search support AND 
-   *  if there is a sub department specified.
-   * If not, fall back to old method, get_list().
+  
+   /* If there is no sub_department specified, fall back to old method, get_list().
    */
-  $sub_enabled = isset($config->current['SUB_LIST_SUPPORT']) && preg_match("/true/i",$config->current['SUB_LIST_SUPPORT']);
-  if($sub_bases == "" || !$sub_enabled){
-    return(get_list($filter, $category,$base,$attributes,$flags));
+  if(!count($sub_bases) && !count($departments)){
+    
+    /* Log this fall back, it may be an unpredicted behaviour.
+     */
+    if(!count($sub_bases) && !count($departments)){
+      // log($action,$objecttype,$object,$changes_array = array(),$result = "") 
+      new log("debug","all",__FILE__,$attributes,
+          sprintf("get_sub_list(): Falling back to get_list(), due to empty sub_bases parameter.".
+            " This may slow down GOsa. Search was: '%s'",$filter));
+    }
+    $tmp = get_list($filter, $category,$base,$attributes,$flags);
+    return($tmp);
   }
 
   /* Get all deparments matching the given sub_bases */
-  $departments = array();
-  
   $base_filter= "";
   foreach($sub_bases as $sub_base){
     $base_filter .= "(".$sub_base.")";
   }
   $base_filter = "(&(objectClass=organizationalUnit)(|".$base_filter."))";
-
   $ldap->search($base_filter,array("dn"));
   while($attrs = $ldap->fetch()){
-    $departments[$attrs['dn']] = $attrs['dn'];
+    foreach($sub_deps as $sub_dep){
+
+      /* Only add those departments that match the reuested list of departments.
+       *
+       * e.g.   sub_deps = array("ou=servers,ou=systems,");
+       *  
+       * In this case we have search for "ou=servers" and we may have also fetched 
+       *  departments like this "ou=servers,ou=blafasel,..."
+       * Here we filter out those blafasel departments.
+       */
+      if(preg_match("/".normalizePreg($sub_dep)."/",$attrs['dn'])){
+        $departments[$attrs['dn']] = $attrs['dn'];
+        break;
+      }
+    }
   }
 
   $result= array();
@@ -823,7 +898,7 @@ function get_sub_list($filter, $category,$sub_bases, $base= "", $attributes= arr
     }
 
     /* Check for size limit exceeded messages for GUI feedback */
-    if (preg_match("/size limit/i", $ldap->error)){
+    if (preg_match("/size limit/i", $ldap->get_error())){
       session::set('limit_exceeded', TRUE);
       $limit_exceeded = TRUE;
     }
@@ -846,21 +921,22 @@ function get_sub_list($filter, $category,$sub_bases, $base= "", $attributes= arr
       }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;
           }
         }
       }
     }
   }
+#  if(microtime(TRUE) - $start > 0.1){
+#    echo sprintf("<pre>GET_SUB_LIST  %s .| %f  --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
+#  }
   return($result);
 }
 
@@ -869,6 +945,8 @@ function get_list($filter, $category, $base= "", $attributes= array(), $flags= G
 {
   global $config, $ui;
 
+#  $start = microtime(TRUE);
+
   /* Get LDAP link */
   $ldap= $config->get_ldap_link($flags & GL_SIZELIMIT);
 
@@ -887,7 +965,7 @@ function get_list($filter, $category, $base= "", $attributes= array(), $flags= G
   }
 
   /* Check for size limit exceeded messages for GUI feedback */
-  if (preg_match("/size limit/i", $ldap->error)){
+  if (preg_match("/size limit/i", $ldap->get_error())){
     session::set('limit_exceeded', TRUE);
   }
 
@@ -896,6 +974,7 @@ function get_list($filter, $category, $base= "", $attributes= array(), $flags= G
   $result= array();
 
   while($attrs = $ldap->fetch()) {
+
     $dn= $ldap->getDN();
 
     /* Convert dn into a printable format */
@@ -910,24 +989,22 @@ 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;
         }
       }
     }
   }
-
+#  if(microtime(TRUE) - $start > 0.1){
+#    echo sprintf("<pre>GET_LIST %s .| %f  --- $base -----$filter ---- $flags</pre>",__LINE__,microtime(TRUE) - $start);
+#  }
   return ($result);
 }
 
@@ -1037,27 +1114,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("/".normalizePreg($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, "/"));
 }
 
 
@@ -1073,6 +1150,8 @@ function get_ou($name)
 {
   global $config;
 
+  $name= strtolower($name);
+
   $map = array( 
                 "ogroupou"      => "ou=groups,",
                 "applicationou" => "ou=apps,",
@@ -1083,6 +1162,8 @@ function get_ou($name)
                 "printerou"     => "ou=printers,ou=systems,",
                 "phoneou"       => "ou=phones,ou=systems,",
                 "componentou"   => "ou=netdevices,ou=systems,",
+                "winstations"   => "ou=winstation,",
+
                 "blocklistou"   => "ou=gofax,ou=systems,",
                 "incomingou"    => "ou=incoming,",
                 "aclroleou"     => "ou=aclroles,",
@@ -1102,8 +1183,8 @@ function get_ou($name)
                 "mimetypeou"    => "ou=mime,");
 
   /* Preset ou... */
-  if (isset($config->current[$name])){
-    $ou= $config->current[$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);
@@ -1115,10 +1196,17 @@ function get_ou($name)
  
   if ($ou != ""){
     if (!preg_match('/^[^=]+=[^=]+/', $ou)){
-      return @LDAP::convert("ou=$ou,");
+      $ou = @LDAP::convert("ou=$ou");
     } else {
-      return @LDAP::convert("$ou,");
+      $ou = @LDAP::convert("$ou");
+    }
+
+    if(preg_match("/".normalizePreg($config->current['BASE'])."$/",$ou)){
+      return($ou);
+    }else{
+      return("$ou,");
     }
+  
   } else {
     return "";
   }
@@ -1127,7 +1215,7 @@ function get_ou($name)
 
 function get_people_ou()
 {
-  return (get_ou("PEOPLE"));
+  return (get_ou("USERRDN"));
 }
 
 
@@ -1161,7 +1249,12 @@ function get_base_from_people($dn)
 
 function strict_uid_mode()
 {
-  return !(isset($config->current['STRICT']) && preg_match('/^(no|false)$/i', $config->current['STRICT']));
+  global $config;
+
+  if (isset($config)){
+    return ($config->get_cfg_value("strict") == "true");
+  }
+  return (TRUE);
 }
 
 
@@ -1177,48 +1270,6 @@ function get_uid_regexp()
 }
 
 
-function print_red()
-{
-  trigger_error("Use of obsolete print_red");
-  /* Check number of arguments */
-  if (func_num_args() < 1){
-    return;
-  }
-
-  /* Get arguments, save string */
-  $array = func_get_args();
-  $string= $array[0];
-
-  /* Step through arguments */
-  for ($i= 1; $i<count($array); $i++){
-    $string= preg_replace ("/%s/", $array[$i], $string, 1);
-  }
-
-  /* If DEBUGLEVEL is set, we're in web mode, use textual output in
-     the other case... */
-  if($string !== NULL){
-    if (preg_match("/"._("LDAP error:")."/", $string)){
-      $addmsg= _("Problems with the LDAP server mean that you probably lost the last changes. Please check your LDAP setup for possible errors and try again.");
-    } else {
-      if (!preg_match('/[.!?]$/', $string)){
-        $string.= ".";
-      }
-      $string= preg_replace('/<br>/', ' ', $string);
-      $addmsg= _("Please check your input and fix the error. Press 'OK' to close this message box.");
-      $addmsg = "";
-    }
-    if(empty($addmsg)){
-      $addmsg = _("Error");
-    }
-    msg_dialog::display($addmsg, $string,ERROR_DIALOG);
-    return;
-  }else{
-    return;
-  }
-
-}
-
-
 function gen_locked_message($user, $dn)
 {
   global $plug, $config;
@@ -1273,7 +1324,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')));
 }
@@ -1306,41 +1357,6 @@ function get_printer_list()
 }
 
 
-function show_errors($message)
-{
-  $complete= "";
-
-  /* Assemble the message array to a plain string */
-  foreach ($message as $error){
-    if ($complete == ""){
-      $complete= $error;
-    } else {
-      $complete= "$error<br>$complete";
-    }
-  }
-
-  /* Fill ERROR variable with nice error dialog */
-  msg_dialog::display(_("Error"), $complete, ERROR_DIALOG);
-}
-
-
-function show_ldap_error($message, $addon= "")
-{
-  if (!preg_match("/Success/i", $message)){
-    if ($addon == ""){
-      msg_dialog::display(_("LDAP error:"), $message, ERROR_DIALOG);
-    } else {
-      if(!preg_match("/No such object/i",$message)){
-        msg_dialog::display(_("LDAP error"), sprintf(_("Plugin '%s':%s"),"<i>".$addon."</i>", "<br><br>$message"),ERROR_DIALOG);
-      }
-    }
-    return TRUE;
-  } else {
-    return FALSE;
-  }
-}
-
-
 function rewrite($s)
 {
   global $REWRITE;
@@ -1529,7 +1545,7 @@ function apply_filter()
 function back_to_main()
 {
   $string= '<br><p class="plugbottom"><input type=submit name="password_back" value="'.
-    _("Back").'"></p><input type="hidden" name="ignore">';
+    msgPool::backButton().'"></p><input type="hidden" name="ignore">';
 
   return ($string);
 }
@@ -1969,34 +1985,32 @@ function progressbar($percentage,$width=100,$height=15,$showvalue=false)
 
   $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;\">
+  $str = "\n   <div style=\" width:".($width)."px; ";
+  $str.= "\n       height:".($height)."px; ";
+  $str.= "\n       background-color:#000000; ";
+  $str.= "\n       padding:1px;\" > ";
 
-         <div style=\" width:".$progress."px;
-height:".$height."px;
-       background-color:#".$color2.$color2.$color."; \">";
+  $str.= "\n     <div style=\" width:".($width)."px; ";
+  $str.= "\n         background-color:#$bgcolor; ";
+  $str.= "\n         height:".($height)."px;\" > ";
 
+  if(($height >10)&&($showvalue)){
+    $str.= "\n   <font style=\"font-size:".($height-2)."px; ";
+    $str.= "\n     color:#FF0000; align:middle; ";
+    $str.= "\n     padding-left:".((int)(($width*0.4)))."px; \"> ";
+    $str.= "\n     <b>".$percentage."%</b> ";
+    $str.= "\n   </font> ";
+  }
 
-       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>";
+  $str.= "\n       <div style=\" width:".$progress."px; ";
+  $str.= "\n         height:".$height."px; ";
+  $str.= "\n         background-color:#".$color2.$color2.$color."; \" >";
+  $str.= "\n       </div>";
+  $str.= "\n     </div>";
+  $str.= "\n   </div>";
 
-       return($str);
+  return($str);
 }
 
 
@@ -2178,10 +2192,10 @@ function get_base_from_hook($dn, $attrib)
 {
   global $config;
 
-  if (isset($config->current['BASE_HOOK'])){
+  if ($config->get_cfg_value("base_hook") != ""){
     
     /* Call hook script - if present */
-    $command= $config->current['BASE_HOOK'];
+    $command= $config->get_cfg_value("base_hook");
 
     if ($command != ""){
       $command.= " '".LDAP::fix($dn)."' $attrib";
@@ -2191,18 +2205,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"), _("'base_hook' is not available. Using default base!"), WARNING_DIALOG);
+          return ($config->get_cfg_value("uidbase"));
         }
       } else {
-        msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
-        return ($config->current['UIDBASE']);
+        msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base!"), WARNING_DIALOG);
+        return ($config->get_cfg_value("uidbase"));
       }
 
     } else {
 
-      msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base."), WARNING_DIALOG);
-      return ($config->current['UIDBASE']);
+      msg_dialog::display(_("Warning"), _("'base_hook' is not available. Using default base!"), WARNING_DIALOG);
+      return ($config->get_cfg_value("uidbase"));
 
     }
   }
@@ -2220,7 +2234,7 @@ function check_schema($cfg,$rfc2307bis = FALSE)
   $messages= array();
 
   /* Get objectclasses */
-  $ldap = 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);
@@ -2361,6 +2375,7 @@ function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FA
         "pl_PL" => "Polish",
         "sv_SE" => "Swedish",
         "zh_CN" => "Chinese",
+        "vi_VN" => "Vietnamese",
         "ru_RU" => "Russian");
   
   $tmp2= array(
@@ -2373,12 +2388,23 @@ function get_languages($languages_in_own_language = FALSE,$strip_region_tag = FA
         "pl_PL" => _("Polish"),
         "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);
@@ -2444,8 +2470,8 @@ function change_password ($dn, $password, $mode=0, $hash= "")
   // Get all available encryption Methods
 
   // NON STATIC CALL :)
-  $tmp = new passwordMethod(session::get('config'));
-  $available = $tmp->get_available_methods();
+  $methods = new passwordMethod(session::get('config'));
+  $available = $methods->get_available_methods();
 
   // read current password entry for $dn, to detect the encryption Method
   $ldap       = $config->get_ldap_link();
@@ -2472,11 +2498,12 @@ function change_password ($dn, $password, $mode=0, $hash= "")
 
     /* Extract used hash */
     if ($hash == ""){
-      $hash= strtolower($matches[1]);
+      $test = passwordMethod::get_method($attrs['userPassword'][0],$dn);
+    } else {
+      $test = new $available[$hash]($config,$dn);
+      $test->set_hash($hash);
     }
 
-    $test = new  $available[$hash]($config);
-
   } else {
     // User MD5 by default
     $hash= "md5";
@@ -2510,7 +2537,7 @@ function change_password ($dn, $password, $mode=0, $hash= "")
     $attrs= generate_smb_nt_hash($password);
   }
 
- /* Readd ! if user was deactivated */
+ /* Read ! if user was deactivated */
   if($deactivated){
     $newpass = preg_replace("/(^[^\}]+\})(.*$)/","\\1!\\2",$newpass);
   }
@@ -2522,12 +2549,14 @@ function change_password ($dn, $password, $mode=0, $hash= "")
 
   new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
 
-  if ($ldap->error != 'Success') {
-    msg_dialog::display(_("LDAP error"), sprintf(_('Setting the password failed!').'<br><br>'._('LDAP server returned: %s'), "<br><br><i>".$ldap->get_error()."</i>"), ERROR_DIALOG);
+  if (!$ldap->success()) {
+    msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, ERROR_DIALOG));
   } else {
 
     /* Run backend method for change/create */
-    $test->set_password($password);
+    if(!$test->set_password($password)){
+      return(FALSE);
+    }
 
     /* Find postmodify entries for this class */
     $command= $config->search("password", "POSTMODIFY",array('menu'));
@@ -2546,6 +2575,7 @@ function change_password ($dn, $password, $mode=0, $hash= "")
       }
     }
   }
+  return(TRUE);
 }
 
 
@@ -2555,11 +2585,15 @@ function generate_smb_nt_hash($password)
   global $config;
 
   # Try to use gosa-si?
-  if (isset($config->current['GOSA_SI'])){
-       $res= gosaSupportDaemon::send("gosa_gen_smb_hash", "GOSA", array("password" => $password), TRUE);
-       $hash= $res['XML']['HASH'];
+  if ($config->get_cfg_value("gosa_si") != ""){
+       $res= gosaSupportDaemon::send("gosa_gen_smb_hash", "GOSA", array("password" => $password), TRUE);
+    if (isset($res['XML']['HASH'])){
+       $hash= $res['XML']['HASH'];
+    } else {
+      $hash= "";
+    }
   } 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);
@@ -2575,7 +2609,7 @@ function generate_smb_nt_hash($password)
 
   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');
@@ -2590,12 +2624,6 @@ function generate_smb_nt_hash($password)
 }
 
 
-function crypt_single($string,$enc_type )
-{
-  return( passwordMethod::crypt_single_str($string,$enc_type));
-}
-
-
 function getEntryCSN($dn)
 {
   global $config;
@@ -2604,12 +2632,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();
@@ -2650,7 +2674,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;
         }
       }
@@ -2673,6 +2697,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.'"');
@@ -2684,5 +2715,117 @@ function send_binary_content($data,$name,$type = "application/octet-stream")
   exit();
 }
 
+
+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)){
+
+    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());
+  }
+}
+
+
+function get_random_char () {
+     $randno = rand (0, 63);
+     if ($randno < 12) {
+         return (chr ($randno + 46)); // Digits, '/' and '.'
+     } else if ($randno < 38) {
+         return (chr ($randno + 53)); // Uppercase
+     } 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);
+}
+
+
 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
 ?>