X-Git-Url: https://git.tokkee.org/?a=blobdiff_plain;f=gosa-core%2Finclude%2Ffunctions.inc;h=aa28014a03cd8ab43c6e8719b85949cbd380c4f4;hb=806fdaa1d14d6d221f479e604cf090a0f02dc6ee;hp=9c2bbe8407db45560f3ba6ce416cf74cbb4d2717;hpb=7b0a3278f618c4ca532c6c5f842661e1b5d436b6;p=gosa.git diff --git a/gosa-core/include/functions.inc b/gosa-core/include/functions.inc index 9c2bbe840..aa28014a0 100644 --- a/gosa-core/include/functions.inc +++ b/gosa-core/include/functions.inc @@ -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 @@ -32,7 +32,7 @@ if(!isset($_SERVER['CONFIG_DIR'])){ } /* Allow setting the config file in the apache configuration - e.g. SetEnv CONFIG_FILE gosa.conf.2.5 + e.g. SetEnv CONFIG_FILE gosa.conf.2.6 */ if(!isset($_SERVER['CONFIG_FILE'])){ define ("CONFIG_FILE", "gosa.conf"); @@ -69,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"); @@ -87,6 +87,8 @@ 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 */ @@ -120,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, "update-gosa"); exit; @@ -163,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: "; @@ -218,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); } } @@ -246,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); } @@ -257,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"); } @@ -281,31 +283,14 @@ function get_template_path($filename= '', $plugin= FALSE, $path= "") function array_remove_entries($needles, $haystack) { - $tmp= array(); - - /* Loop through entries to be removed */ - foreach ($haystack as $entry){ - if (!in_array($entry, $needles)){ - $tmp[]= $entry; - } - } - - return ($tmp); + return (array_merge(array_diff($haystack, $needles))); } 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); + // strcasecmp will work, because we only compare ASCII values here + return (array_merge(array_udiff($haystack, $needles, 'strcasecmp'))); } @@ -420,6 +405,12 @@ function ldap_login_user_htaccess ($username) $ui= new userinfo($config, $ldap->getDN()); $ui->username= $attrs['uid'][0]; + /* Bail out if we have login restrictions set, for security reasons + the message is the same than failed user/pw */ + if (!$ui->loginAllowed()){ + return (NULL); + } + /* No password check needed - the webserver did it for us */ $ldap->disconnect(); @@ -427,7 +418,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); } @@ -500,6 +491,12 @@ function ldap_login_user ($username, $password) $ui= new userinfo($config, $ldap->getDN()); $ui->username= $attrs['uid'][0]; + /* Bail out if we have login restrictions set, for security reasons + the message is the same than failed user/pw */ + if (!$ui->loginAllowed()){ + return (NULL); + } + /* password check, bind as user with supplied password */ $ldap->disconnect(); $ldap= new LDAP($ui->dn, $password, $config->current['SERVER'], @@ -612,10 +609,16 @@ 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("")); + } if(is_array($object)){ foreach($object as $obj){ add_lock($obj,$user); @@ -623,6 +626,16 @@ function add_lock ($object, $user) return; } + $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]); + } + + /* Just a sanity check... */ if ($object == "" || $user == ""){ msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG); @@ -673,6 +686,17 @@ 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->get_cfg_value("config")); @@ -715,6 +739,9 @@ 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(); @@ -870,7 +897,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; } @@ -1012,7 +1039,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 (""); } @@ -1020,8 +1047,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"), '')); + 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"), '')); return($smarty->fetch(get_template_path('sizelimit.tpl'))); } @@ -1031,7 +1058,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= ""; } else { @@ -1052,25 +1079,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); } } @@ -1088,7 +1115,7 @@ function getMenuCache() if(session::is_set('maxC')){ $b= session::get('maxC'); $q= ""; - for ($m=0;$m "ou=groups,", - "applicationou" => "ou=apps,", + "roleRDN" => "ou=roles,", + "ogroupRDN" => "ou=groups,", + "applicationRDN" => "ou=apps,", "systemRDN" => "ou=systems,", "serverRDN" => "ou=servers,ou=systems,", "terminalRDN" => "ou=terminals,ou=systems,", @@ -1164,21 +1192,23 @@ function get_ou($name) "faxBlocklistRDN" => "ou=gofax,ou=systems,", "systemIncomingRDN" => "ou=incoming,", - "aclroleou" => "ou=aclroles,", - "macroou" => "ou=macros,ou=asterisk,ou=configs,ou=systems,", + "aclRoleRDN" => "ou=aclroles,", + "phoneMacroRDN" => "ou=macros,ou=asterisk,ou=configs,ou=systems,", "phoneConferenceRDN" => "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,", + "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,", - "deviceou" => "ou=devices,", - "mimetypeou" => "ou=mime,"); + "sudoRDN" => "ou=sudoers,", + + "deviceRDN" => "ou=devices,", + "mimetypeRDN" => "ou=mime,"); /* Preset ou... */ if ($config->get_cfg_value($name, "_not_set_") != "_not_set_"){ @@ -1199,7 +1229,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,"); @@ -1213,19 +1243,19 @@ function get_ou($name) function get_people_ou() { - return (get_ou("USERRDN")); + return (get_ou("userRDN")); } function get_groups_ou() { - return (get_ou("GROUPRDN")); + return (get_ou("groupRDN")); } function get_winstations_ou() { - return (get_ou("SAMBAMACHINEACCOUNTRDN")); + return (get_ou("sambaMachineAccountRDN")); } @@ -1233,7 +1263,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 */ @@ -1268,7 +1298,7 @@ function get_uid_regexp() } -function gen_locked_message($user, $dn) +function gen_locked_message($user, $dn, $allow_readonly = FALSE) { global $plug, $config; @@ -1278,7 +1308,9 @@ function gen_locked_message($user, $dn) /* Save variables from LOCK_VARS_TO_USE in session - for further editing */ if( session::is_set('LOCK_VARS_TO_USE') && count(session::get('LOCK_VARS_TO_USE'))){ - $LOCK_VARS_USED = array(); + $LOCK_VARS_USED_GET = array(); + $LOCK_VARS_USED_POST = array(); + $LOCK_VARS_USED_REQUEST = array(); $LOCK_VARS_TO_USE = session::get('LOCK_VARS_TO_USE'); foreach($LOCK_VARS_TO_USE as $name){ @@ -1289,23 +1321,31 @@ function gen_locked_message($user, $dn) foreach($_POST as $Pname => $Pvalue){ if(preg_match($name,$Pname)){ - $LOCK_VARS_USED[$Pname] = $_POST[$Pname]; + $LOCK_VARS_USED_POST[$Pname] = $_POST[$Pname]; } } foreach($_GET as $Pname => $Pvalue){ if(preg_match($name,$Pname)){ - $LOCK_VARS_USED[$Pname] = $_GET[$Pname]; + $LOCK_VARS_USED_GET[$Pname] = $_GET[$Pname]; + } + } + + foreach($_REQUEST as $Pname => $Pvalue){ + if(preg_match($name,$Pname)){ + $LOCK_VARS_USED_REQUEST[$Pname] = $_REQUEST[$Pname]; } } } session::set('LOCK_VARS_TO_USE',array()); - session::set('LOCK_VARS_USED' , $LOCK_VARS_USED); + session::set('LOCK_VARS_USED_GET' , $LOCK_VARS_USED_GET); + session::set('LOCK_VARS_USED_POST' , $LOCK_VARS_USED_POST); + session::set('LOCK_VARS_USED_REQUEST' , $LOCK_VARS_USED_REQUEST); } /* Prepare and show template */ $smarty= get_smarty(); - + $smarty->assign("allow_readonly",$allow_readonly); if(is_array($dn)){ $msg = "
";
     foreach($dn as $sub_dn){
@@ -1360,7 +1400,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);
@@ -1611,7 +1651,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));
   }
 
@@ -1622,14 +1662,14 @@ function recurse($rule, $variables)
 function expand_id($rule, $attributes)
 {
   /* Check for id rule */
-  if(preg_match('/^id(:|#)\d+$/',$rule)){
-    return (array("\{$rule}"));
+  if(preg_match('/^id(:|#|!)\d+$/',$rule)){
+    return (array("{$rule}"));
   }
 
   /* 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));
   }
 
@@ -1637,7 +1677,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);
 
@@ -1665,7 +1705,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;
@@ -1691,54 +1731,64 @@ function gen_uids($rule, $attributes)
   $proposed= recurse($stripped, $variables);
 
   /* Get list of used ID's */
-  $used= array();
   $ldap= $config->get_ldap_link();
   $ldap->cd($config->current['BASE']);
-  $ldap->search('(uid=*)');
-
-  while($attrs= $ldap->fetch()){
-    $used[]= $attrs['uid'][0];
-  }
 
   /* Remove used uids and watch out for id tags */
   $ret= array();
   foreach($proposed as $uid){
 
     /* Check for id tag and modify uid if needed */
-    if(preg_match('/\{id:\d+}/',$uid)){
-      $size= preg_replace('/^.*{id:(\d+)}.*$/', '\\1', $uid);
+    if(preg_match('/\{id(:|!)\d+}/',$uid, $m)){
+      $size= preg_replace('/^.*{id(:|!)(\d+)}.*$/', '\\2', $uid);
 
-      for ($i= 0; $i < pow(10,$size); $i++){
-        $number= sprintf("%0".$size."d", $i);
-        $res= preg_replace('/{id:(\d+)}/', $number, $uid);
-        if (!in_array($res, $used)){
+      $start= $m[1]==":"?0:-1;
+      for ($i= $start, $p= pow(10,$size)-1; $i < $p; $i++){
+        if ($i == -1) {
+          $number= "";
+        } else {
+          $number= sprintf("%0".$size."d", $i+1);
+        }
+        $res= preg_replace('/{id(:|!)\d+}/', $number, $uid);
+
+        $ldap->search("(uid=".preg_replace('/[{}]/', '', $res).")",array('dn'));
+        if($ldap->count() == 0){
           $uid= $res;
           break;
         }
       }
+
+      /* Remove link if nothing has been found */
+      $uid= preg_replace('/{id(:|!)\d+}/', '', $uid);
     }
 
-  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);
+        $ldap->search("(uid=".preg_replace('/[{}]/', '', $res).")",array('dn'));
+        if($ldap->count() == 0){
+          $uid= $res;
+          break;
+        }
       }
+
+      /* Remove link if nothing has been found */
+      $uid= preg_replace('/{id#\d+}/', '', $uid);
     }
-  }
 
-/* Don't assign used ones */
-if (!in_array($uid, $used)){
-  $ret[]= $uid;
-}
-}
+    /* Don't assign used ones */
+    $ldap->search("(uid=".preg_replace('/[{}]/', '', $uid).")",array('dn'));
+    if($ldap->count() == 0){
+      /* Add uid, but remove {} first. These are invalid anyway. */
+      $ret[]= preg_replace('/[{}]/', '', $uid);
+    }
+  }
 
-return(array_unique($ret));
+  return(array_unique($ret));
 }
 
 
@@ -1770,18 +1820,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)
@@ -1791,7 +1831,7 @@ function generate_alphabet($count= 10)
   $c= 0;
 
   /* Fill cells with charaters */
-  for ($i= 0; $i ";
-
-  $str.= "\n     
"; - - if(($height >10)&&($showvalue)){ - $str.= "\n "; - $str.= "\n ".$percentage."% "; - $str.= "\n "; - } - - $str.= "\n
"; - $str.= "\n
"; - $str.= "\n
"; - $str.= "\n "; - - return($str); + return(""); } 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 (''); } @@ -2035,15 +2038,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); } @@ -2074,13 +2069,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) { @@ -2190,10 +2178,10 @@ function get_base_from_hook($dn, $attrib) { global $config; - if ($config->get_cfg_value("nextIdHook") != ""){ + if ($config->get_cfg_value("baseIdHook") != ""){ /* Call hook script - if present */ - $command= $config->get_cfg_value("nextIdHook"); + $command= $config->get_cfg_value("baseIdHook"); if ($command != ""){ $command.= " '".LDAP::fix($dn)."' $attrib"; @@ -2203,17 +2191,17 @@ function get_base_from_hook($dn, $attrib) if (preg_match("/^[0-9]+$/", $output[0])){ return ($output[0]); } else { - msg_dialog::display(_("Warning"), _("'nextIdHook' is not available. Using default base!"), WARNING_DIALOG); + msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG); return ($config->get_cfg_value("uidNumberBase")); } } else { - msg_dialog::display(_("Warning"), _("'nextIdHook' is not available. Using default base!"), WARNING_DIALOG); + msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG); return ($config->get_cfg_value("uidNumberBase")); } } else { - msg_dialog::display(_("Warning"), _("'nextIdHook' is not available. Using default base!"), WARNING_DIALOG); + msg_dialog::display(_("Warning"), _("'baseIdHook' is not available. Using default base!"), WARNING_DIALOG); return ($config->get_cfg_value("uidNumberBase")); } @@ -2251,49 +2239,49 @@ function check_schema($cfg,$rfc2307bis = FALSE) /* The gosa base schema */ $checks['gosaObject'] = $def_check; - $checks['gosaObject']['REQUIRED_VERSION'] = "2.4"; - $checks['gosaObject']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema"); + $checks['gosaObject']['REQUIRED_VERSION'] = "2.6.1"; + $checks['gosaObject']['SCHEMA_FILES'] = array("gosa-samba3.schema","gosa-samba2.schema"); $checks['gosaObject']['CLASSES_REQUIRED'] = array("gosaObject"); $checks['gosaObject']['IS_MUST_HAVE'] = TRUE; /* GOsa Account class */ - $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.4"; - $checks["gosaAccount"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema"); + $checks["gosaAccount"]["REQUIRED_VERSION"]= "2.6.6"; + $checks["gosaAccount"]["SCHEMA_FILES"] = array("gosa-samba3.schema","gosa-samba2.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"]["SCHEMA_FILES"] = array("gosa+samba3.schema","gosa.schema"); + $checks["gosaLockEntry"]["REQUIRED_VERSION"] = "2.6.1"; + $checks["gosaLockEntry"]["SCHEMA_FILES"] = array("gosa-samba3.schema","gosa-samba2.schema"); $checks["gosaLockEntry"]["CLASSES_REQUIRED"] = array("gosaLockEntry"); $checks["gosaLockEntry"]["IS_MUST_HAVE"] = TRUE; $checks["gosaLockEntry"]["INFO"] = _("Used to lock currently edited entries to avoid multiple changes at the same time."); /* Some other checks */ foreach(array( - "gosaCacheEntry" => array("version" => "2.4"), - "gosaDepartment" => array("version" => "2.4"), + "gosaCacheEntry" => array("version" => "2.6.1", "class" => "gosaAccount"), + "gosaDepartment" => array("version" => "2.6.1", "class" => "gosaAccount"), "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", "class" => "goServer"), + "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", "class" => "goServer"), + "goFaxServer" => array("version" => "2.6.1", "class" => "gofaxAccount","file" => "gofax.schema"), ) as $name => $values){ $checks[$name] = $def_check; @@ -2303,26 +2291,25 @@ function check_schema($cfg,$rfc2307bis = FALSE) if(isset($values['file'])){ $checks[$name]["SCHEMA_FILES"] = array($values['file']); } - $checks[$name]["CLASSES_REQUIRED"] = array($name); + if (isset($values['class'])) { + $checks[$name]["CLASSES_REQUIRED"] = is_array($values['class'])?$values['class']:array($values['class']); + } } foreach($checks as $name => $value){ foreach($value['CLASSES_REQUIRED'] as $class){ if(!isset($objectclasses[$name])){ - $checks[$name]['STATUS'] = FALSE; if($value['IS_MUST_HAVE']){ + $checks[$name]['STATUS'] = FALSE; $checks[$name]['MSG'] = sprintf(_("Missing required object class '%s'!"),$class); - }else{ + } else { + $checks[$name]['STATUS'] = TRUE; $checks[$name]['MSG'] = sprintf(_("Missing optional object class '%s'!"),$class); } }elseif(!check_schema_version($objectclasses[$name],$value['REQUIRED_VERSION'])){ $checks[$name]['STATUS'] = FALSE; - if($value['IS_MUST_HAVE']){ - $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']); - }else{ - $checks[$name]['MSG'] = sprintf(_("Version mismatch for optional object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']); - } + $checks[$name]['MSG'] = sprintf(_("Version mismatch for required object class '%s' (!=%s)!"), $class, $value['REQUIRED_VERSION']); }else{ $checks[$name]['STATUS'] = TRUE; $checks[$name]['MSG'] = sprintf(_("Class(es) available")); @@ -2334,8 +2321,8 @@ function check_schema($cfg,$rfc2307bis = FALSE) /* The gosa base schema */ $checks['posixGroup'] = $def_check; - $checks['posixGroup']['REQUIRED_VERSION'] = "2.4"; - $checks['posixGroup']['SCHEMA_FILES'] = array("gosa+samba3.schema","gosa.schema"); + $checks['posixGroup']['REQUIRED_VERSION'] = "2.6.1"; + $checks['posixGroup']['SCHEMA_FILES'] = array("gosa-samba3.schema","gosa-samba2.schema"); $checks['posixGroup']['CLASSES_REQUIRED'] = array("posixGroup"); $checks['posixGroup']['STATUS'] = TRUE; $checks['posixGroup']['IS_MUST_HAVE'] = TRUE; @@ -2371,7 +2358,7 @@ 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"); @@ -2384,7 +2371,7 @@ 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")); @@ -2476,13 +2463,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"; @@ -2508,72 +2488,77 @@ 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 */ - if(!$test->set_password($password)){ - return(FALSE); + /* 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); } - return(TRUE); } @@ -2590,6 +2575,11 @@ function generate_smb_nt_hash($password) } else { $hash= ""; } + + if ($hash == "") { + msg_dialog::display(_("Configuration error"), _("Cannot generate samba hash!"), ERROR_DIALOG); + return (""); + } } else { $tmp= $config->get_cfg_value('sambaHashHook')." ".escapeshellarg($password); @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__, $tmp, "Execute"); @@ -2598,26 +2588,20 @@ function generate_smb_nt_hash($password) 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->get_cfg_value("sambaversion") == 3) { - $attrs['sambaLMPassword']= $lm; - $attrs['sambaNTPassword']= $nt; - $attrs['sambaPwdLastSet']= date('U'); - $attrs['sambaBadPasswordCount']= "0"; - $attrs['sambaBadPasswordTime']= "0"; - } else { - $attrs['lmPassword']= $lm; - $attrs['ntPassword']= $nt; - $attrs['pwdLastSet']= date('U'); - } + $attrs['sambaLMPassword']= $lm; + $attrs['sambaNTPassword']= $nt; + $attrs['sambaPwdLastSet']= date('U'); + $attrs['sambaBadPasswordCount']= "0"; + $attrs['sambaBadPasswordTime']= "0"; return($attrs); } @@ -2817,6 +2801,7 @@ function cred_encrypt($input, $password) { } + function cred_decrypt($input,$password) { $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC); $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM); @@ -2825,5 +2810,198 @@ function cred_decrypt($input,$password) { } +function get_object_info() +{ + return(session::get('objectinfo')); +} + + +function set_object_info($str = "") +{ + session::set('objectinfo',$str); +} + + +function isIpInNet($ip, $net, $mask) { + // Move to long ints + $ip= ip2long($ip); + $net= ip2long($net); + $mask= ip2long($mask); + + // Mask given IP with mask. If it returns "net", we're in... + $res= $ip & $mask; + + return ($res == $net); +} + + +function get_next_id($attrib, $dn) +{ + global $config; + + switch ($config->get_cfg_value("idAllocationMethod", "traditional")){ + case "pool": + return get_next_id_pool($attrib); + case "traditional": + return get_next_id_traditional($attrib, $dn); + } + + msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." "._("unknown idAllocation method!"), ERROR_DIALOG); + return null; +} + + +function get_next_id_pool($attrib) { + global $config; + + /* Fill informational values */ + $min= $config->get_cfg_value("${attrib}PoolMin", 10000); + $max= $config->get_cfg_value("${attrib}PoolMax", 40000); + + /* Sanity check */ + if ($min >= $max) { + msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." ".sprintf(_("%sPoolMin >= %sPoolMax!"), $attrib), ERROR_DIALOG); + return null; + } + + /* ID to skip */ + $ldap= $config->get_ldap_link(); + $id= null; + + /* Try to allocate the ID several times before failing */ + $tries= 3; + while ($tries--) { + + /* Look for ID map entry */ + $ldap->cd ($config->current['BASE']); + $ldap->search ("(&(objectClass=sambaUnixIdPool)($attrib=*))", array("$attrib")); + + /* If it does not exist, create one with these defaults */ + if ($ldap->count() == 0) { + /* Fill informational values */ + $minUserId= $config->get_cfg_value("uidPoolMin", 10000); + $minGroupId= $config->get_cfg_value("gidPoolMin", 10000); + + /* Add as default */ + $attrs= array("objectClass" => array("organizationalUnit", "sambaUnixIdPool")); + $attrs["ou"]= "idmap"; + $attrs["uidNumber"]= $minUserId; + $attrs["gidNumber"]= $minGroupId; + $ldap->cd("ou=idmap,".$config->current['BASE']); + $ldap->add($attrs); + if ($ldap->error != "Success") { + msg_dialog::display(_("Error"), _("Cannot create sambaUnixIdPool entry!"), ERROR_DIALOG); + return null; + } + $tries++; + continue; + } + /* Bail out if it's not unique */ + if ($ldap->count() != 1) { + msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." "._("sambaUnixIdPool is not unique!"), ERROR_DIALOG); + return null; + } + + /* Store old attrib and generate new */ + $attrs= $ldap->fetch(); + $dn= $ldap->getDN(); + $oldAttr= $attrs[$attrib][0]; + $newAttr= $oldAttr + 1; + + /* Sanity check */ + if ($newAttr >= $max) { + msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." "._("no ID available!"), ERROR_DIALOG); + return null; + } + if ($newAttr < $min) { + msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." "._("no ID available!"), ERROR_DIALOG); + return null; + } + + #FIXME: PHP is not able to do a modification of "del: .../add: ...", so this + # is completely unsafe in the moment. + #/* Remove old attr, add new attr */ + #$attrs= array($attrib => $oldAttr); + #$ldap->rm($attrs, $dn); + #if ($ldap->error != "Success") { + # continue; + #} + $ldap->cd($dn); + $ldap->modify(array($attrib => $newAttr)); + if ($ldap->error != "Success") { + msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." ".$ldap->get_error(), ERROR_DIALOG); + return null; + } else { + return $oldAttr; + } + } + + /* Bail out if we had problems getting the next id */ + if (!$tries) { + msg_dialog::display(_("Error"), _("Cannot allocate a free ID:")." "._("maximum tries exceeded!"), ERROR_DIALOG); + } + + return $id; +} + +function get_next_id_traditional($attrib, $dn) +{ + global $config; + + $ids= array(); + $ldap= $config->get_ldap_link(); + + $ldap->cd ($config->current['BASE']); + if (preg_match('/gidNumber/i', $attrib)){ + $oc= "posixGroup"; + } else { + $oc= "posixAccount"; + } + $ldap->search ("(&(objectClass=$oc)($attrib=*))", array("$attrib")); + + /* Get list of ids */ + while ($attrs= $ldap->fetch()){ + $ids[]= (int)$attrs["$attrib"][0]; + } + + /* Add the nobody id */ + $ids[]= 65534; + + /* get the ranges */ + $tmp = array('0'=> 1000); + if (preg_match('/posixAccount/', $oc) && $config->get_cfg_value("uidNumberBase") != ""){ + $tmp= split('-',$config->get_cfg_value("uidNumberBase")); + } elseif($config->get_cfg_value("gidNumberBase") != ""){ + $tmp= split('-',$config->get_cfg_value("gidNumberBase")); + } + + /* Set hwm to max if not set - for backward compatibility */ + $lwm= $tmp[0]; + if (isset($tmp[1])){ + $hwm= $tmp[1]; + } else { + $hwm= pow(2,32); + } + /* Find out next free id near to UID_BASE */ + if ($config->get_cfg_value("baseIdHook") == ""){ + $base= $lwm; + } else { + /* Call base hook */ + $base= get_base_from_hook($dn, $attrib); + } + for ($id= $base; $id++; $id < pow(2,32)){ + if (!in_array($id, $ids)){ + return ($id); + } + } + + /* Should not happen */ + if ($id == $hwm){ + msg_dialog::display(_("Error"), _("Cannot allocate a free ID!"), ERROR_DIALOG); + exit; + } +} + + // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler: ?>