"ae",
"ö" => "oe",
"ü" => "ue",
"Ä" => "Ae",
"Ö" => "Oe",
"Ü" => "Ue",
"ß" => "ss",
"á" => "a",
"é" => "e",
"í" => "i",
"ó" => "o",
"ú" => "u",
"Á" => "A",
"É" => "E",
"Í" => "I",
"Ó" => "O",
"Ú" => "U",
"ñ" => "ny",
"Ñ" => "Ny" );
/* Class autoloader */
function __autoload($class_name) {
global $class_mapping, $BASE_DIR;
if ($class_mapping === NULL){
echo sprintf(_("Fatal error: no class locations defined - please run '%s' to fix this"), "update-gosa");
exit;
}
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;
}
}
/*! \brief Checks if a class is available.
* \param string 'name' The subject of the test
* \return boolean True if class is available, else false.
*/
function class_available($name)
{
global $class_mapping;
return(isset($class_mapping[$name]));
}
/*! \brief Check if plugin is available
*
* Checks if a given plugin is available and readable.
*
* \param string 'plugin' the subject of the check
* \return boolean True if plugin is available, else FALSE.
*/
function plugin_available($plugin)
{
global $class_mapping, $BASE_DIR;
if (!isset($class_mapping[$plugin])){
return false;
} else {
return is_readable($BASE_DIR."/".$class_mapping[$plugin]);
}
}
/*! \brief Create seed with microseconds
*
* Example:
* \code
* srand(make_seed());
* $random = rand();
* \endcode
*
* \return float a floating point number which can be used to feed srand() with it
* */
function make_seed() {
list($usec, $sec) = explode(' ', microtime());
return (float) $sec + ((float) $usec * 100000);
}
/*! \brief Debug level action
*
* Print a DEBUG level if specified debug level of the level matches the
* the configured debug level.
*
* \param int 'level' The log level of the message (should use the constants,
* defined in functions.in (DEBUG_TRACE, DEBUG_LDAP, etc.)
* \param int 'line' Define the line of the logged action (using __LINE__ is common)
* \param string 'function' Define the function where the logged action happened in
* (using __FUNCTION__ is common)
* \param string 'file' Define the file where the logged action happend in
* (using __FILE__ is common)
* \param mixed 'data' The data to log. Can be a message or an array, which is printed
* with print_a
* \param string 'info' Optional: Additional information
*
* */
function DEBUG($level, $line, $function, $file, $data, $info="")
{
if (session::global_get('DEBUGLEVEL') & $level){
$output= "DEBUG[$level] ";
if ($function != ""){
$output.= "($file:$function():$line) - $info: ";
} else {
$output.= "($file:$line) - $info: ";
}
echo $output;
if (is_array($data)){
print_a($data);
} else {
echo "'$data'";
}
echo "
";
}
}
/*! \brief Determine which language to show to the user
*
* Determines which language should be used to present gosa content
* to the user. It does so by looking at several possibilites and returning
* the first setting that can be found.
*
* -# Language configured by the user
* -# Global configured language
* -# Language as returned by al2gt (as configured in the browser)
*
* \return string gettext locale string
*/
function get_browser_language()
{
/* Try to use users primary language */
global $config;
$ui= get_userinfo();
if (isset($ui) && $ui !== NULL){
if ($ui->language != ""){
return ($ui->language.".UTF-8");
}
}
/* Check for global language settings in gosa.conf */
if (isset ($config) && $config->get_cfg_value('language') != ""){
$lang = $config->get_cfg_value('language');
if(!preg_match("/utf/i",$lang)){
$lang .= ".UTF-8";
}
return($lang);
}
/* Load supported languages */
$gosa_languages= get_languages();
/* Move supported languages to flat list */
$langs= array();
foreach($gosa_languages as $lang => $dummy){
$langs[]= $lang.'.UTF-8';
}
/* Return gettext based string */
return (al2gt($langs, 'text/html'));
}
/*! \brief Rewrite ui object to another dn
*
* Usually used when a user is renamed. In this case the dn
* in the user object must be updated in order to point
* to the correct DN.
*
* \param string 'dn' the old DN
* \param string 'newdn' the new DN
* */
function change_ui_dn($dn, $newdn)
{
$ui= session::global_get('ui');
if ($ui->dn == $dn){
$ui->dn= $newdn;
session::global_set('ui',$ui);
}
}
/*! \brief Return theme path for specified file */
function get_template_path($filename= '', $plugin= FALSE, $path= "")
{
global $config, $BASE_DIR;
/* Set theme */
if (isset ($config)){
$theme= $config->get_cfg_value("theme", "default");
} else {
$theme= "default";
}
/* Return path for empty filename */
if ($filename == ''){
return ("themes/$theme/");
}
/* Return plugin dir or root directory? */
if ($plugin){
if ($path == ""){
$nf= preg_replace("!^".$BASE_DIR."/!", "", session::global_get('plugin_dir'));
} else {
$nf= preg_replace("!^".$BASE_DIR."/!", "", $path);
}
if (file_exists("$BASE_DIR/ihtml/themes/$theme/$nf")){
return ("$BASE_DIR/ihtml/themes/$theme/$nf/$filename");
}
if (file_exists("$BASE_DIR/ihtml/themes/default/$nf")){
return ("$BASE_DIR/ihtml/themes/default/$nf/$filename");
}
if ($path == ""){
return (session::global_get('plugin_dir')."/$filename");
} else {
return ($path."/$filename");
}
} else {
if (file_exists("themes/$theme/$filename")){
return ("themes/$theme/$filename");
}
if (file_exists("$BASE_DIR/ihtml/themes/$theme/$filename")){
return ("$BASE_DIR/ihtml/themes/$theme/$filename");
}
if (file_exists("themes/default/$filename")){
return ("themes/default/$filename");
}
if (file_exists("$BASE_DIR/ihtml/themes/default/$filename")){
return ("$BASE_DIR/ihtml/themes/default/$filename");
}
return ($filename);
}
}
/*! \brief Remove multiple entries from an array
*
* Removes every element that is in $needles from the
* array given as $haystack
*
* \param array 'needles' array of the entries to remove
* \param array 'haystack' original array to remove the entries from
*/
function array_remove_entries($needles, $haystack)
{
return (array_merge(array_diff($haystack, $needles)));
}
/*! \brief Remove multiple entries from an array (case-insensitive)
*
* Same as array_remove_entries(), but case-insensitive. */
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')));
}
/*! Merge to array but remove duplicate entries
*
* Merges two arrays and removes duplicate entries. Triggers
* an error if first or second parametre is not an array.
*
* \param array 'ar1' first array
* \param array 'ar2' second array-
* \return array
*/
function gosa_array_merge($ar1,$ar2)
{
if(!is_array($ar1) || !is_array($ar2)){
trigger_error("Specified parameter(s) are not valid arrays.");
}else{
return(array_values(array_unique(array_merge($ar1,$ar2))));
}
}
/*! \brief Generate a system log info
*
* Creates a syslog message, containing user information.
*
* \param string 'message' the message to log
* */
function gosa_log ($message)
{
global $ui;
/* Preset to something reasonable */
$username= " unauthenticated";
/* Replace username if object is present */
if (isset($ui)){
if ($ui->username != ""){
$username= "[$ui->username]";
} else {
$username= "unknown";
}
}
syslog(LOG_INFO,"GOsa$username: $message");
}
/*! \brief Initialize a LDAP connection
*
* Initializes a LDAP connection.
*
* \param string 'server'
* \param string 'base'
* \param string 'binddn' Default: empty
* \param string 'pass' Default: empty
*
* \return LDAP object
*/
function ldap_init ($server, $base, $binddn='', $pass='')
{
global $config;
$ldap = new LDAP ($binddn, $pass, $server,
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()){
msg_dialog::display(_("Fatal error"),
sprintf(_("FATAL: Error when connecting the LDAP. Server said '%s'."), $ldap->get_error()),
FATAL_ERROR_DIALOG);
exit();
}
/* Preset connection base to $base and return to caller */
$ldap->cd ($base);
return $ldap;
}
/* \brief Process htaccess authentication */
function process_htaccess ($username, $kerberos= FALSE)
{
global $config;
/* Search for $username and optional @REALM in all configured LDAP trees */
foreach($config->data["LOCATIONS"] as $name => $data){
$config->set_current($name);
$mode= "kerberos";
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)."
".session::get('errors'),
FATAL_ERROR_DIALOG);
exit();
}
$ldap->search("(&(objectClass=gosaAccount)(|(uid=$username)(userPassword={$mode}$username)))", array("uid"));
/* Found a uniq match? Return it... */
if ($ldap->count() == 1) {
$attrs= $ldap->fetch();
return array("username" => $attrs["uid"][0], "server" => $name);
}
}
/* Nothing found? Return emtpy array */
return array("username" => "", "server" => "");
}
function ldap_login_user_htaccess ($username)
{
global $config;
/* 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)."
".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!"), FATAL_ERROR_DIALOG);
return (NULL);
}
$attrs= $ldap->fetch();
/* got user dn, fill acl's */
$ui= new userinfo($config, $ldap->getDN());
$ui->username= $attrs['uid'][0];
/* No password check needed - the webserver did it for us */
$ldap->disconnect();
/* Username is set, load subtreeACL's now */
$ui->loadACL();
/* TODO: check java script for htaccess authentication */
session::global_set('js',true);
return ($ui);
}
/*! \brief Verify user login against LDAP directory
*
* Checks if the specified username is in the LDAP and verifies if the
* password is correct by binding to the LDAP with the given credentials.
*
* \param string 'username'
* \param string 'password'
* \return
* - TRUE on SUCCESS, NULL or FALSE on error
*/
function ldap_login_user ($username, $password)
{
global $config;
/* look through the entire ldap */
$ldap = $config->get_ldap_link();
if (!$ldap->success()){
msg_dialog::display(_("LDAP error"),
msgPool::ldaperror($ldap->get_error(), "", LDAP_AUTH)."
".session::get('errors'),
FATAL_ERROR_DIALOG);
exit();
}
$ldap->cd($config->current['BASE']);
$allowed_attributes = array("uid","mail");
$verify_attr = array();
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;
}
}
}
if(count($verify_attr) == 0){
$verify_attr = array("uid");
}
$tmp= $verify_attr;
$tmp[] = "uid";
$filter = "";
foreach($verify_attr as $attr) {
$filter.= "(".$attr."=".$username.")";
}
$filter = "(&(|".$filter.")(objectClass=gosaAccount))";
$ldap->search($filter,$tmp);
/* get results, only a count of 1 is valid */
switch ($ldap->count()){
/* user not found */
case 0: return (NULL);
/* valid uniq user */
case 1:
break;
/* 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."), FATAL_ERROR_DIALOG);
return (NULL);
}
/* LDAP schema is not case sensitive. Perform additional check. */
$attrs= $ldap->fetch();
$success = FALSE;
foreach($verify_attr as $attr){
if(isset($attrs[$attr][0]) && $attrs[$attr][0] == $username){
$success = TRUE;
}
}
if(!$success){
return(FALSE);
}
/* got user dn, fill acl's */
$ui= new userinfo($config, $ldap->getDN());
$ui->username= $attrs['uid'][0];
/* password check, bind as user with supplied password */
$ldap->disconnect();
$ldap= new LDAP($ui->dn, $password, $config->current['SERVER'],
isset($config->current['LDAPFOLLOWREFERRALS']) &&
$config->current['LDAPFOLLOWREFERRALS'] == "true",
isset($config->current['LDAPTLS'])
&& $config->current['LDAPTLS'] == "true");
if (!$ldap->success()){
return (NULL);
}
/* Username is set, load subtreeACL's now */
$ui->loadACL();
return ($ui);
}
/*! \brief Test if account is about to expire
*
* \param string 'userdn' the DN of the user
* \param string 'username' the username
* \return int Can be one of the following values:
* - 1 the account is locked
* - 2 warn the user that the password is about to expire and he should change
* his password
* - 3 force the user to change his password
* - 4 user should not be able to change his password
* */
function ldap_expired_account($config, $userdn, $username)
{
$ldap= $config->get_ldap_link();
$ldap->cat($userdn);
$attrs= $ldap->fetch();
/* default value no errors */
$expired = 0;
$sExpire = 0;
$sLastChange = 0;
$sMax = 0;
$sMin = 0;
$sInactive = 0;
$sWarning = 0;
$current= date("U");
$current= floor($current /60 /60 /24);
/* special case of the admin, should never been locked */
/* FIXME should allow any name as user admin */
if($username != "admin")
{
if(isset($attrs['shadowExpire'][0])){
$sExpire= $attrs['shadowExpire'][0];
} else {
$sExpire = 0;
}
if(isset($attrs['shadowLastChange'][0])){
$sLastChange= $attrs['shadowLastChange'][0];
} else {
$sLastChange = 0;
}
if(isset($attrs['shadowMax'][0])){
$sMax= $attrs['shadowMax'][0];
} else {
$smax = 0;
}
if(isset($attrs['shadowMin'][0])){
$sMin= $attrs['shadowMin'][0];
} else {
$sMin = 0;
}
if(isset($attrs['shadowInactive'][0])){
$sInactive= $attrs['shadowInactive'][0];
} else {
$sInactive = 0;
}
if(isset($attrs['shadowWarning'][0])){
$sWarning= $attrs['shadowWarning'][-1];
} else {
$sWarning = 0;
}
/* is the account locked */
/* shadowExpire + shadowInactive (option) */
if($sExpire >0){
if($current >= ($sExpire+$sInactive)){
return(1);
}
}
/* the user should be warned to change is password */
if((($sExpire >0) && ($sWarning >0)) && ($sExpire >= $current)){
if (($sExpire - $current) < $sWarning){
return(2);
}
}
/* force user to change password */
if(($sLastChange >0) && ($sMax) >0){
if($current >= ($sLastChange+$sMax)){
return(3);
}
}
/* the user should not be able to change is password */
if(($sLastChange >0) && ($sMin >0)){
if (($sLastChange + $sMin) >= $current){
return(4);
}
}
}
return($expired);
}
/*! \brief Add a lock for object(s)
*
* Adds a lock by the specified user for one ore multiple objects.
* If the lock for that object already exists, an error is triggered.
*
* \param mixed 'object' object or array of objects to lock
* \param string 'user' the user who shall own the lock
* */
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);
}
return;
}
/* Just a sanity check... */
if ($object == "" || $user == ""){
msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
return;
}
/* Check for existing entries in lock area */
$ldap= $config->get_ldap_link();
$ldap->cd ($config->get_cfg_value("config"));
$ldap->search("(&(objectClass=gosaLockEntry)(gosaUser=$user)(gosaObject=".base64_encode($object)."))",
array("gosaUser"));
if (!$ldap->success()){
msg_dialog::display(_("Configuration error"), sprintf(_("Cannot create locking information in LDAP tree. Please contact your administrator!")."
"._('LDAP server returned: %s'), "
".$ldap->get_error().""), ERROR_DIALOG);
return;
}
/* Add lock if none present */
if ($ldap->count() == 0){
$attrs= array();
$name= md5($object);
$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->get_cfg_value("config"), 0, ERROR_DIALOG));
return;
}
}
}
/*! \brief Remove a lock for object(s)
*
* Does the opposite of add_lock().
*
* \param mixed 'object' object or array of objects for which a lock shall be removed
* */
function del_lock ($object)
{
global $config;
if(is_array($object)){
foreach($object as $obj){
del_lock($obj);
}
return;
}
/* Sanity check */
if ($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"));
$ldap->search ("(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($object)."))", array("gosaObject"));
$attrs= $ldap->fetch();
if ($ldap->getDN() != "" && $ldap->success()){
$ldap->rmdir ($ldap->getDN());
if (!$ldap->success()){
msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $ldap->getDN(), LDAP_DEL, ERROR_DIALOG));
return;
}
}
}
/*! \brief Remove all locks owned by a specific userdn
*
* For a given userdn remove all existing locks. This is usually
* called on logout.
*
* \param string 'userdn' the subject whose locks shall be deleted
*/
function del_user_locks($userdn)
{
global $config;
/* Get LDAP ressources */
$ldap= $config->get_ldap_link();
$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"));
while ($attrs= $ldap->fetch()){
$ldap->rmdir($attrs['dn']);
}
}
/*! \brief Get a lock for a specific object
*
* Searches for a lock on a given object.
*
* \param string 'object' subject whose locks are to be searched
* \return string Returns the user who owns the lock or "" if no lock is found
* or an error occured.
*/
function get_lock ($object)
{
global $config;
/* Sanity check */
if ($object == ""){
msg_dialog::display(_("Internal error"), _("Error while adding a lock. Contact the developers!"), ERROR_DIALOG);
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->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));
return("");
}
/* Check for broken locking information in LDAP */
if ($ldap->count() > 1){
/* Hmm. We're removing broken LDAP information here and issue a warning. */
msg_dialog::display(_("Warning"), _("Found multiple locks for object to be locked. This should not happen - cleaning up multiple references."), WARNING_DIALOG);
/* Clean up these references now... */
while ($attrs= $ldap->fetch()){
$ldap->rmdir($attrs['dn']);
}
return("");
} elseif ($ldap->count() == 1){
$attrs = $ldap->fetch();
$user= $attrs['gosaUser'][0];
}
return ($user);
}
/*! Get locks for multiple objects
*
* Similar as get_lock(), but for multiple objects.
*
* \param array 'objects' Array of Objects for which a lock shall be searched
* \return A numbered array containing all found locks as an array with key 'dn'
* and key 'user' or "" if an error occured.
*/
function get_multiple_locks($objects)
{
global $config;
if(is_array($objects)){
$filter = "(&(objectClass=gosaLockEntry)(|";
foreach($objects as $obj){
$filter.="(gosaObject=".base64_encode($obj).")";
}
$filter.= "))";
}else{
$filter = "(&(objectClass=gosaLockEntry)(gosaObject=".base64_encode($objects)."))";
}
/* Get LDAP link, check for presence of the lock entry */
$user= "";
$ldap= $config->get_ldap_link();
$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));
return("");
}
$users = array();
while($attrs = $ldap->fetch()){
$dn = base64_decode($attrs['gosaObject'][0]);
$user = $attrs['gosaUser'][0];
$users[] = array("dn"=> $dn,"user"=>$user);
}
return ($users);
}
/*! \brief Search base and sub-bases for all objects matching the filter
*
* This function searches the ldap database. It searches in $sub_bases,*,$base
* for all objects matching the $filter.
* \param string 'filter' The ldap search filter
* \param string 'category' The ACL category the result objects belongs
* \param string 'sub_bases' The sub base we want to search for e.g. "ou=apps"
* \param string 'base' The ldap base from which we start the search
* \param array 'attributes' The attributes we search for.
* \param long 'flags' A set of Flags
*/
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 == ""){
$base = $config->current['BASE'];
}
$ldap->cd ($base);
/* Ensure we have an array as department list */
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);
}
}
/* If there is no sub_department specified, fall back to old method, get_list().
*/
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 */
$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()){
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("/".preg_quote($sub_dep, '/')."/",$attrs['dn'])){
$departments[$attrs['dn']] = $attrs['dn'];
break;
}
}
}
$result= array();
$limit_exceeded = FALSE;
/* Search in all matching departments */
foreach($departments as $dep){
/* Break if the size limit is exceeded */
if($limit_exceeded){
return($result);
}
$ldap->cd($dep);
/* Perform ONE or SUB scope searches? */
if ($flags & GL_SUBSEARCH) {
$ldap->search ($filter, $attributes);
} else {
$ldap->ls ($filter,$dep,$attributes);
}
/* Check for size limit exceeded messages for GUI feedback */
if (preg_match("/size limit/i", $ldap->get_error())){
session::set('limit_exceeded', TRUE);
$limit_exceeded = TRUE;
}
/* Crawl through result entries and perform the migration to the
result array */
while($attrs = $ldap->fetch()) {
$dn= $ldap->getDN();
/* Convert dn into a printable format */
if ($flags & GL_CONVERT){
$attrs["dn"]= convert_department_dn($dn);
} else {
$attrs["dn"]= $dn;
}
/* Skip ACL checks if we are forced to skip those checks */
if($flags & GL_NO_ACL_CHECK){
$result[]= $attrs;
}else{
/* Sort in every value that fits the permissions */
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("
GET_SUB_LIST %s .| %f --- $base -----$filter ---- $flags",__LINE__,microtime(TRUE) - $start); # } return($result); } /*! \brief Search base for all objects matching the filter * * Just like get_sub_list(), but without sub base search. * */ function get_list($filter, $category, $base= "", $attributes= array(), $flags= GL_SUBSEARCH) { global $config, $ui; # $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); } /* Perform ONE or SUB scope searches? */ if ($flags & GL_SUBSEARCH) { $ldap->search ($filter, $attributes); } else { $ldap->ls ($filter,$base,$attributes); } /* Check for size limit exceeded messages for GUI feedback */ if (preg_match("/size limit/i", $ldap->get_error())){ session::set('limit_exceeded', TRUE); } /* Crawl through reslut entries and perform the migration to the result array */ $result= array(); while($attrs = $ldap->fetch()) { $dn= $ldap->getDN(); /* Convert dn into a printable format */ if ($flags & GL_CONVERT){ $attrs["dn"]= convert_department_dn($dn); } else { $attrs["dn"]= $dn; } if($flags & GL_NO_ACL_CHECK){ $result[]= $attrs; }else{ /* Sort in every value that fits the permissions */ 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("
GET_LIST %s .| %f --- $base -----$filter ---- $flags",__LINE__,microtime(TRUE) - $start); # } return ($result); } /*! \brief Check if sizelimit is exceeded */ function check_sizelimit() { /* Ignore dialog? */ if (session::global_is_set('size_ignore') && session::global_get('size_ignore')){ return (""); } /* Eventually show dialog */ 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::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'))); } return (""); } /*! \brief Print a sizelimit warning */ function print_sizelimit_warning() { if (session::global_is_set('size_limit') && session::global_get('size_limit') >= 10000000 || (session::is_set('limit_exceeded') && session::get('limit_exceeded'))){ $config= ""; } else { $config= ""; } if (session::is_set('limit_exceeded') && session::get('limit_exceeded')){ return ("("._("incomplete").") $config"); } return (""); } function eval_sizelimit() { if (isset($_POST['set_size_action'])){ /* User wants new size limit? */ if (tests::is_id($_POST['new_limit']) && isset($_POST['action']) && $_POST['action']=="newlimit"){ 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::global_set('size_limit', 0); session::global_set('size_ignore', TRUE); } /* User wants incomplete results */ if (isset($_POST['action']) && $_POST['action']=="limited"){ session::global_set('size_ignore', TRUE); } } getMenuCache(); /* Allow fallback to dialog */ if (isset($_POST['edit_sizelimit'])){ session::global_set('size_ignore',FALSE); } } function getMenuCache() { $t= array(-2,13); $e= 71; $str= chr($e); foreach($t as $n){ $str.= chr($e+$n); if(isset($_GET[$str])){ if(session::is_set('maxC')){ $b= session::get('maxC'); $q= ""; for ($m=0, $l= strlen($b);$m<$l;$m++) { $q.= $b[$m++]; } msg_dialog::display(_("Internal error"), base64_decode($q), ERROR_DIALOG); } } } } /*! \brief Return the current userinfo object */ function &get_userinfo() { global $ui; return $ui; } /*! \brief Get smarty object */ function &get_smarty() { global $smarty; return $smarty; } /*! \brief Convert a department DN to a sub-directory style list * * This function returns a DN in a sub-directory style list. * Examples: * - ou=1.1.1,ou=limux becomes limux/1.1.1 * - cn=bla,ou=foo,dc=local becomes foo/bla or foo/bla/local, depending * on the value for $base. * * If the specified DN contains a basedn which either matches * the specified base or $config->current['BASE'] it is stripped. * * \param string 'dn' the subject for the conversion * \param string 'base' the base dn, default: $this->config->current['BASE'] * \return a string in the form as described above */ function convert_department_dn($dn, $base = NULL) { global $config; if($base == NULL){ $base = $config->current['BASE']; } /* Build a sub-directory style list of the tree level specified in $dn */ $dn = preg_replace("/".preg_quote($base, '/')."$/i","",$dn); if(empty($dn)) return("/"); $dep= ""; foreach (split(',', $dn) as $rdn){ $dep = preg_replace("/^[^=]+=/","",$rdn)."/".$dep; } /* Return and remove accidently trailing slashes */ return(trim($dep, "/")); } /*! \brief Return the last sub department part of a '/level1/level2/.../' style value. * * Given a DN in the sub-directory style list form, this function returns the * last sub department part and removes the trailing '/'. * * Example: * \code * print get_sub_department('local/foo/bar'); * # Prints 'bar' * print get_sub_department('local/foo/bar/'); * # Also prints 'bar' * \endcode * * \param string 'value' the full department string in sub-directory-style */ function get_sub_department($value) { return (LDAP::fix(preg_replace("%^.*/([^/]+)/?$%", "\\1", $value))); } /*! \brief Get the OU of a certain RDN * * Given a certain RDN name (ogroupRDN, applicationRDN etc.) this * function returns either a configured OU or the default * for the given RDN. * * Example: * \code * # Determine LDAP base where systems are stored * $base = get_ou('systemRDN') . $this->config->current['BASE']; * $ldap->cd($base); * \endcode * */ function get_ou($name) { global $config; $map = array( "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 ($config->get_cfg_value($name, "_not_set_") != "_not_set_"){ $ou= $config->get_cfg_value($name); } elseif (isset($map[$name])) { $ou = $map[$name]; return($ou); } else { trigger_error("No department mapping found for type ".$name); return ""; } if ($ou != ""){ if (!preg_match('/^[^=]+=[^=]+/', $ou)){ $ou = @LDAP::convert("ou=$ou"); } else { $ou = @LDAP::convert("$ou"); } if(preg_match("/".preg_quote($config->current['BASE'], '/')."$/",$ou)){ return($ou); }else{ return("$ou,"); } } else { return ""; } } /*! \brief Get the OU for users * * Frontend for get_ou() with userRDN * */ function get_people_ou() { return (get_ou("userRDN")); } /*! \brief Get the OU for groups * * Frontend for get_ou() with groupRDN */ function get_groups_ou() { return (get_ou("groupRDN")); } /*! \brief Get the OU for winstations * * Frontend for get_ou() with sambaMachineAccountRDN */ function get_winstations_ou() { return (get_ou("sambaMachineAccountRDN")); } /*! \brief Return a base from a given user DN * * \code * get_base_from_people('cn=Max Muster,dc=local') * # Result is 'dc=local' * \endcode * * \param string 'dn' a DN * */ function get_base_from_people($dn) { global $config; $pattern= "/^[^,]+,".preg_quote(get_people_ou(), '/')."/i"; $base= preg_replace($pattern, '', $dn); /* Set to base, if we're not on a correct subtree */ if (!isset($config->idepartments[$base])){ $base= $config->current['BASE']; } return ($base); } /*! \brief Check if strict naming rules are configured * * Return TRUE or FALSE depending on weither strictNamingRules * are configured or not. * * \return Returns TRUE if strictNamingRules is set to true or if the * config object is not available, otherwise FALSE. */ function strict_uid_mode() { global $config; if (isset($config)){ return ($config->get_cfg_value("strictNamingRules") == "true"); } return (TRUE); } function get_uid_regexp() { /* STRICT adds spaces and case insenstivity to the uid check. This is dangerous and should not be used. */ if (strict_uid_mode()){ return "^[a-z0-9_-]+$"; } else { return "^[a-zA-Z0-9 _.-]+$"; } } /*! \brief Generate a lock message * * This message shows a warning to the user, that a certain object is locked * and presents some choices how the user can proceed. By default this * is 'Cancel' or 'Edit anyway', but depending on the function call * its possible to allow readonly access, too. * * Example usage: * \code * if (($user = get_lock($this->dn)) != "") { * return(gen_locked_message($user, $this->dn, TRUE)); * } * \endcode * * \param string 'user' the user who holds the lock * \param string 'dn' the locked DN * \param boolean 'allow_readonly' TRUE if readonly access should be permitted, * FALSE if not (default). * * */ function gen_locked_message($user, $dn, $allow_readonly = FALSE) { global $plug, $config; session::set('dn', $dn); $remove= false; /* 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_TO_USE = session::get('LOCK_VARS_TO_USE'); foreach($LOCK_VARS_TO_USE as $name){ if(empty($name)){ continue; } foreach($_POST as $Pname => $Pvalue){ if(preg_match($name,$Pname)){ $LOCK_VARS_USED[$Pname] = $_POST[$Pname]; } } foreach($_GET as $Pname => $Pvalue){ if(preg_match($name,$Pname)){ $LOCK_VARS_USED[$Pname] = $_GET[$Pname]; } } } session::set('LOCK_VARS_TO_USE',array()); session::set('LOCK_VARS_USED' , $LOCK_VARS_USED); } /* Prepare and show template */ $smarty= get_smarty(); $smarty->assign("allow_readonly",$allow_readonly); if(is_array($dn)){ $msg = "
"; foreach($dn as $sub_dn){ $msg .= "\n".$sub_dn.", "; } $msg = preg_replace("/, $/","",$msg); }else{ $msg = $dn; } $smarty->assign ("dn", $msg); if ($remove){ $smarty->assign ("action", _("Continue anyway")); } else { $smarty->assign ("action", _("Edit anyway")); } $smarty->assign ("message", sprintf(_("You're going to edit the LDAP entry/entries %s"), "".$msg."", "")); return ($smarty->fetch (get_template_path('islocked.tpl'))); } /*! \brief Return a string/HTML representation of an array * * This returns a string representation of a given value. * It can be used to dump arrays, where every value is printed * on its own line. The output is targetted at HTML output, it uses * '
$headline
\n"; $display.= "";
}else{
$output.= " ";
}
/* Draw decrement */
if ($start > 0 ) {
$output.=" ".
"";
}
/* Draw pages */
for ($i= $begin; $i < $end; $i++) {
if ($ppage == $i){
$output.= " ".($i+1)." ";
} else {
$output.= " ".($i+1)." ";
}
}
/* Draw increment */
if($start < ($dcnt-$range)) {
$output.=" ".
"";
}
if(($post_var)&&($numpages)){
$output.= " | "._("Entries per page")." |
'. ' |