diff --git a/apps/user_ldap/ajax/deleteConfiguration.php b/apps/user_ldap/ajax/deleteConfiguration.php new file mode 100644 index 0000000000..b7d633a049 --- /dev/null +++ b/apps/user_ldap/ajax/deleteConfiguration.php @@ -0,0 +1,35 @@ +. + * + */ + +// Check user and app status +OCP\JSON::checkAdminUser(); +OCP\JSON::checkAppEnabled('user_ldap'); +OCP\JSON::callCheck(); + +$prefix = $_POST['ldap_serverconfig_chooser']; +if(\OCA\user_ldap\lib\Helper::deleteServerConfiguration($prefix)){ + OCP\JSON::success(); +} else { + $l=OC_L10N::get('user_ldap'); + OCP\JSON::error(array('message' => $l->t('Failed to delete the server configuration'))); +} \ No newline at end of file diff --git a/apps/user_ldap/ajax/getConfiguration.php b/apps/user_ldap/ajax/getConfiguration.php new file mode 100644 index 0000000000..dfae68d2dc --- /dev/null +++ b/apps/user_ldap/ajax/getConfiguration.php @@ -0,0 +1,31 @@ +. + * + */ + +// Check user and app status +OCP\JSON::checkAdminUser(); +OCP\JSON::checkAppEnabled('user_ldap'); +OCP\JSON::callCheck(); + +$prefix = $_POST['ldap_serverconfig_chooser']; +$connection = new \OCA\user_ldap\lib\Connection($prefix); +OCP\JSON::success(array('configuration' => $connection->getConfiguration())); \ No newline at end of file diff --git a/apps/user_ldap/ajax/getNewServerConfigPrefix.php b/apps/user_ldap/ajax/getNewServerConfigPrefix.php new file mode 100644 index 0000000000..17e78f8707 --- /dev/null +++ b/apps/user_ldap/ajax/getNewServerConfigPrefix.php @@ -0,0 +1,34 @@ +. + * + */ + +// Check user and app status +OCP\JSON::checkAdminUser(); +OCP\JSON::checkAppEnabled('user_ldap'); +OCP\JSON::callCheck(); + +$serverConnections = \OCA\user_ldap\lib\Helper::getServerConfigurationPrefixes(); +sort($serverConnections); +$lk = array_pop($serverConnections); +$ln = intval(str_replace('s', '', $lk)); +$nk = 's'.str_pad($ln+1, 2, '0', STR_PAD_LEFT); +OCP\JSON::success(array('configPrefix' => $nk)); \ No newline at end of file diff --git a/apps/user_ldap/ajax/setConfiguration.php b/apps/user_ldap/ajax/setConfiguration.php new file mode 100644 index 0000000000..206487c7e0 --- /dev/null +++ b/apps/user_ldap/ajax/setConfiguration.php @@ -0,0 +1,33 @@ +. + * + */ + +// Check user and app status +OCP\JSON::checkAdminUser(); +OCP\JSON::checkAppEnabled('user_ldap'); +OCP\JSON::callCheck(); + +$prefix = $_POST['ldap_serverconfig_chooser']; +$connection = new \OCA\user_ldap\lib\Connection($prefix); +$connection->setConfiguration($_POST); +$connection->saveConfiguration(); +OCP\JSON::success(); \ No newline at end of file diff --git a/apps/user_ldap/ajax/testConfiguration.php b/apps/user_ldap/ajax/testConfiguration.php index a82f7e4c17..f8038e3146 100644 --- a/apps/user_ldap/ajax/testConfiguration.php +++ b/apps/user_ldap/ajax/testConfiguration.php @@ -4,7 +4,7 @@ * ownCloud - user_ldap * * @author Arthur Schiwon - * @copyright 2012 Arthur Schiwon blizzz@owncloud.com + * @copyright 2012, 2013 Arthur Schiwon blizzz@owncloud.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE @@ -26,14 +26,16 @@ OCP\JSON::checkAdminUser(); OCP\JSON::checkAppEnabled('user_ldap'); OCP\JSON::callCheck(); -$connection = new \OCA\user_ldap\lib\Connection(null); +$l=OC_L10N::get('user_ldap'); + +$connection = new \OCA\user_ldap\lib\Connection('', null); if($connection->setConfiguration($_POST)) { //Configuration is okay if($connection->bind()) { - OCP\JSON::success(array('message' => 'The configuration is valid and the connection could be established!')); + OCP\JSON::success(array('message' => $l->t('The configuration is valid and the connection could be established!'))); } else { - OCP\JSON::error(array('message' => 'The configuration is valid, but the Bind failed. Please check the server settings and credentials.')); + OCP\JSON::error(array('message' => $l->t('The configuration is valid, but the Bind failed. Please check the server settings and credentials.'))); } } else { - OCP\JSON::error(array('message' => 'The configuration is invalid. Please look in the ownCloud log for further details.')); + OCP\JSON::error(array('message' => $l->t('The configuration is invalid. Please look in the ownCloud log for further details.'))); } diff --git a/apps/user_ldap/appinfo/app.php b/apps/user_ldap/appinfo/app.php index ce3079da0b..dec87684c9 100644 --- a/apps/user_ldap/appinfo/app.php +++ b/apps/user_ldap/appinfo/app.php @@ -23,15 +23,23 @@ OCP\App::registerAdmin('user_ldap', 'settings'); -$connector = new OCA\user_ldap\lib\Connection('user_ldap'); -$userBackend = new OCA\user_ldap\USER_LDAP(); -$userBackend->setConnector($connector); -$groupBackend = new OCA\user_ldap\GROUP_LDAP(); -$groupBackend->setConnector($connector); +$configPrefixes = OCA\user_ldap\lib\Helper::getServerConfigurationPrefixes(true); +if(count($configPrefixes) == 1) { + $connector = new OCA\user_ldap\lib\Connection($configPrefixes[0]); + $userBackend = new OCA\user_ldap\USER_LDAP(); + $userBackend->setConnector($connector); + $groupBackend = new OCA\user_ldap\GROUP_LDAP(); + $groupBackend->setConnector($connector); +} else { + $userBackend = new OCA\user_ldap\User_Proxy($configPrefixes); + $groupBackend = new OCA\user_ldap\Group_Proxy($configPrefixes); +} -// register user backend -OC_User::useBackend($userBackend); -OC_Group::useBackend($groupBackend); +if(count($configPrefixes) > 0) { + // register user backend + OC_User::useBackend($userBackend); + OC_Group::useBackend($groupBackend); +} // add settings page to navigation $entry = array( diff --git a/apps/user_ldap/appinfo/update.php b/apps/user_ldap/appinfo/update.php index 9b54ba18b6..f9681e38e6 100644 --- a/apps/user_ldap/appinfo/update.php +++ b/apps/user_ldap/appinfo/update.php @@ -5,7 +5,7 @@ //ATTENTION //Upgrade from ownCloud 3 (LDAP backend 0.1) to ownCloud 4.5 (LDAP backend 0.3) is not supported!! //You must do upgrade to ownCloud 4.0 first! -//The upgrade stuff in the section from 0.1 to 0.2 is just to minimize the bad efffects. +//The upgrade stuff in the section from 0.1 to 0.2 is just to minimize the bad effects. //settings $pw = OCP\Config::getAppValue('user_ldap', 'ldap_password'); @@ -22,12 +22,10 @@ if($state == 'unset') { OCP\Config::setSystemValue('ldapIgnoreNamingRules', false); } -// ### SUPPORTED upgrade path starts here ### - //from version 0.2 to 0.3 (0.2.0.x dev version) $objects = array('user', 'group'); -$connector = new \OCA\user_ldap\lib\Connection('user_ldap'); +$connector = new \OCA\user_ldap\lib\Connection(); $userBE = new \OCA\user_ldap\USER_LDAP(); $userBE->setConnector($connector); $groupBE = new \OCA\user_ldap\GROUP_LDAP(); @@ -80,3 +78,13 @@ function escapeDN($dn) { return $dn; } + + +// SUPPORTED UPGRADE FROM Version 0.3 (ownCloud 4.5) to 0.4 (ownCloud 5) + +if(!isset($connector)) { + $connector = new \OCA\user_ldap\lib\Connection(); +} +//it is required, that connections do have ldap_configuration_active setting stored in the database +$connector->getConfiguration(); +$connector->saveConfiguration(); \ No newline at end of file diff --git a/apps/user_ldap/appinfo/version b/apps/user_ldap/appinfo/version index b1a5f4781d..705e30728e 100644 --- a/apps/user_ldap/appinfo/version +++ b/apps/user_ldap/appinfo/version @@ -1 +1 @@ -0.3.0.1 \ No newline at end of file +0.3.9.0 \ No newline at end of file diff --git a/apps/user_ldap/group_ldap.php b/apps/user_ldap/group_ldap.php index 6343731008..02ceecaea0 100644 --- a/apps/user_ldap/group_ldap.php +++ b/apps/user_ldap/group_ldap.php @@ -171,7 +171,6 @@ class GROUP_LDAP extends lib\Access implements \OCP\GroupInterface { return array(); } - $search = empty($search) ? '*' : '*'.$search.'*'; $groupUsers = array(); $isMemberUid = (strtolower($this->connection->ldapGroupMemberAssocAttr) == 'memberuid'); foreach($members as $member) { @@ -179,7 +178,7 @@ class GROUP_LDAP extends lib\Access implements \OCP\GroupInterface { //we got uids, need to get their DNs to 'tranlsate' them to usernames $filter = $this->combineFilterWithAnd(array( \OCP\Util::mb_str_replace('%uid', $member, $this->connection>ldapLoginFilter, 'UTF-8'), - $this->connection->ldapUserDisplayName.'='.$search + $this->getFilterPartForUserSearch($search) )); $ldap_users = $this->fetchListOfUsers($filter, 'dn'); if(count($ldap_users) < 1) { @@ -188,8 +187,8 @@ class GROUP_LDAP extends lib\Access implements \OCP\GroupInterface { $groupUsers[] = $this->dn2username($ldap_users[0]); } else { //we got DNs, check if we need to filter by search or we can give back all of them - if($search != '*') { - if(!$this->readAttribute($member, $this->connection->ldapUserDisplayName, $this->connection->ldapUserDisplayName.'='.$search)) { + if(!empty($search)) { + if(!$this->readAttribute($member, $this->connection->ldapUserDisplayName, $this->getFilterPartForUserSearch($search))) { continue; } } @@ -230,10 +229,9 @@ class GROUP_LDAP extends lib\Access implements \OCP\GroupInterface { if($limit <= 0) { $limit = null; } - $search = empty($search) ? '*' : '*'.$search.'*'; $filter = $this->combineFilterWithAnd(array( $this->connection->ldapGroupFilter, - $this->connection->ldapGroupDisplayName.'='.$search + $this->getFilterPartForGroupSearch($search) )); \OCP\Util::writeLog('user_ldap', 'getGroups Filter '.$filter, \OCP\Util::DEBUG); $ldap_groups = $this->fetchListOfGroups($filter, array($this->connection->ldapGroupDisplayName, 'dn'), $limit, $offset); diff --git a/apps/user_ldap/group_proxy.php b/apps/user_ldap/group_proxy.php new file mode 100644 index 0000000000..5aa1aef0e0 --- /dev/null +++ b/apps/user_ldap/group_proxy.php @@ -0,0 +1,178 @@ +. + * + */ + +namespace OCA\user_ldap; + +class Group_Proxy extends lib\Proxy implements \OCP\GroupInterface { + private $backends = array(); + private $refBackend = null; + + /** + * @brief Constructor + * @param $serverConfigPrefixes array containing the config Prefixes + */ + public function __construct($serverConfigPrefixes) { + parent::__construct(); + foreach($serverConfigPrefixes as $configPrefix) { + $this->backends[$configPrefix] = new \OCA\user_ldap\GROUP_LDAP(); + $connector = $this->getConnector($configPrefix); + $this->backends[$configPrefix]->setConnector($connector); + if(is_null($this->refBackend)) { + $this->refBackend = &$this->backends[$configPrefix]; + } + } + } + + /** + * @brief Tries the backends one after the other until a positive result is returned from the specified method + * @param $gid string, the gid connected to the request + * @param $method string, the method of the group backend that shall be called + * @param $parameters an array of parameters to be passed + * @return mixed, the result of the method or false + */ + protected function walkBackends($gid, $method, $parameters) { + $cacheKey = $this->getGroupCacheKey($gid); + foreach($this->backends as $configPrefix => $backend) { + if($result = call_user_func_array(array($backend, $method), $parameters)) { + $this->writeToCache($cacheKey, $configPrefix); + return $result; + } + } + return false; + } + + /** + * @brief Asks the backend connected to the server that supposely takes care of the gid from the request. + * @param $gid string, the gid connected to the request + * @param $method string, the method of the group backend that shall be called + * @param $parameters an array of parameters to be passed + * @return mixed, the result of the method or false + */ + protected function callOnLastSeenOn($gid, $method, $parameters) { + $cacheKey = $this->getGroupCacheKey($gid);; + $prefix = $this->getFromCache($cacheKey); + //in case the uid has been found in the past, try this stored connection first + if(!is_null($prefix)) { + if(isset($this->backends[$prefix])) { + $result = call_user_func_array(array($this->backends[$prefix], $method), $parameters); + if(!$result) { + //not found here, reset cache to null + $this->writeToCache($cacheKey, null); + } + return $result; + } + } + return false; + } + + /** + * @brief is user in group? + * @param $uid uid of the user + * @param $gid gid of the group + * @returns true/false + * + * Checks whether the user is member of a group or not. + */ + public function inGroup($uid, $gid) { + return $this->handleRequest($gid, 'inGroup', array($uid, $gid)); + } + + /** + * @brief Get all groups a user belongs to + * @param $uid Name of the user + * @returns array with group names + * + * This function fetches all groups a user belongs to. It does not check + * if the user exists at all. + */ + public function getUserGroups($uid) { + $groups = array(); + + foreach($this->backends as $backend) { + $backendGroups = $backend->getUserGroups($uid); + if (is_array($backendGroups)) { + $groups = array_merge($groups, $backendGroups); + } + } + + return $groups; + } + + /** + * @brief get a list of all users in a group + * @returns array with user ids + */ + public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) { + $users = array(); + + foreach($this->backends as $backend) { + $backendUsers = $backend->usersInGroup($gid, $search, $limit, $offset); + if (is_array($backendUsers)) { + $users = array_merge($users, $backendUsers); + } + } + + return $users; + } + + /** + * @brief get a list of all groups + * @returns array with group names + * + * Returns a list with all groups + */ + public function getGroups($search = '', $limit = -1, $offset = 0) { + $groups = array(); + + foreach($this->backends as $backend) { + $backendGroups = $backend->getGroups($search, $limit, $offset); + if (is_array($backendGroups)) { + $groups = array_merge($groups, $backendGroups); + } + } + + return $groups; + } + + /** + * check if a group exists + * @param string $gid + * @return bool + */ + public function groupExists($gid) { + return $this->handleRequest($gid, 'groupExists', array($gid)); + } + + /** + * @brief Check if backend implements actions + * @param $actions bitwise-or'ed actions + * @returns boolean + * + * Returns the supported actions as int to be + * compared with OC_USER_BACKEND_CREATE_USER etc. + */ + public function implementsActions($actions) { + //it's the same across all our user backends obviously + return $this->refBackend->implementsActions($actions); + } +} \ No newline at end of file diff --git a/apps/user_ldap/js/settings.js b/apps/user_ldap/js/settings.js index 7063eead96..166761bc1f 100644 --- a/apps/user_ldap/js/settings.js +++ b/apps/user_ldap/js/settings.js @@ -1,6 +1,113 @@ +var LdapConfiguration = { + refreshConfig: function() { + if($('#ldap_serverconfig_chooser option').length < 2) { + LdapConfiguration.addConfiguration(true); + return; + } + $.post( + OC.filePath('user_ldap','ajax','getConfiguration.php'), + $('#ldap_serverconfig_chooser').serialize(), + function (result) { + if(result.status == 'success') { + $.each(result.configuration, function(configkey, configvalue) { + elementID = '#'+configkey; + + //deal with Checkboxes + if($(elementID).is('input[type=checkbox]')) { + if(configvalue == 1) { + $(elementID).attr('checked', 'checked'); + } else { + $(elementID).removeAttr('checked'); + } + return; + } + + //On Textareas, Multi-Line Settings come as array + if($(elementID).is('textarea') && $.isArray(configvalue)) { + configvalue = configvalue.join("\n"); + } + + // assign the value + $('#'+configkey).val(configvalue); + }); + } + } + ); + }, + + resetDefaults: function() { + $('#ldap').find('input[type=text], input[type=number], input[type=password], textarea, select').each(function() { + if($(this).attr('id') == 'ldap_serverconfig_chooser') { + return; + } + $(this).val($(this).attr('data-default')); + }); + $('#ldap').find('input[type=checkbox]').each(function() { + if($(this).attr('data-default') == 1) { + $(this).attr('checked', 'checked'); + } else { + $(this).removeAttr('checked'); + } + }); + }, + + deleteConfiguration: function() { + $.post( + OC.filePath('user_ldap','ajax','deleteConfiguration.php'), + $('#ldap_serverconfig_chooser').serialize(), + function (result) { + if(result.status == 'success') { + $('#ldap_serverconfig_chooser option:selected').remove(); + $('#ldap_serverconfig_chooser option:first').select(); + LdapConfiguration.refreshConfig(); + } else { + OC.dialogs.alert( + result.message, + t('user_ldap', 'Deletion failed') + ); + } + } + ); + }, + + addConfiguration: function(doNotAsk) { + $.post( + OC.filePath('user_ldap','ajax','getNewServerConfigPrefix.php'), + function (result) { + if(result.status == 'success') { + if(doNotAsk) { + LdapConfiguration.resetDefaults(); + } else { + OC.dialogs.confirm( + t('user_ldap', 'Take over settings from recent server configuration?'), + t('user_ldap', 'Keep settings?'), + function(keep) { + if(!keep) { + LdapConfiguration.resetDefaults(); + } + } + ); + } + $('#ldap_serverconfig_chooser option:selected').removeAttr('selected'); + var html = ''; + $('#ldap_serverconfig_chooser option:last').before(html); + } else { + OC.dialogs.alert( + result.message, + t('user_ldap', 'Cannot add server configuration') + ); + } + } + ); + } +} + $(document).ready(function() { $('#ldapSettings').tabs(); + $('#ldap_submit').button(); $('#ldap_action_test_connection').button(); + $('#ldap_action_delete_configuration').button(); + LdapConfiguration.refreshConfig(); $('#ldap_action_test_connection').click(function(event){ event.preventDefault(); $.post( @@ -10,15 +117,60 @@ $(document).ready(function() { if (result.status == 'success') { OC.dialogs.alert( result.message, - 'Connection test succeeded' + t('user_ldap', 'Connection test succeeded') ); } else { OC.dialogs.alert( result.message, - 'Connection test failed' + t('user_ldap', 'Connection test failed') ); } } ); }); + + $('#ldap_action_delete_configuration').click(function(event) { + event.preventDefault(); + OC.dialogs.confirm( + t('user_ldap', 'Do you really want to delete the current Server Configuration?'), + t('user_ldap', 'Confirm Deletion'), + function(deleteConfiguration) { + if(deleteConfiguration) { + LdapConfiguration.deleteConfiguration(); + } + } + ); + }); + + $('#ldap_submit').click(function(event) { + event.preventDefault(); + $.post( + OC.filePath('user_ldap','ajax','setConfiguration.php'), + $('#ldap').serialize(), + function (result) { + bgcolor = $('#ldap_submit').css('background'); + if (result.status == 'success') { + //the dealing with colors is a but ugly, but the jQuery version in use has issues with rgba colors + $('#ldap_submit').css('background', '#fff'); + $('#ldap_submit').effect('highlight', {'color':'#A8FA87'}, 5000, function() { + $('#ldap_submit').css('background', bgcolor); + }); + } else { + $('#ldap_submit').css('background', '#fff'); + $('#ldap_submit').effect('highlight', {'color':'#E97'}, 5000, function() { + $('#ldap_submit').css('background', bgcolor); + }); + } + } + ); + }); + + $('#ldap_serverconfig_chooser').change(function(event) { + value = $('#ldap_serverconfig_chooser option:selected:first').attr('value'); + if(value == 'NEW') { + LdapConfiguration.addConfiguration(false); + } else { + LdapConfiguration.refreshConfig(); + } + }); }); \ No newline at end of file diff --git a/apps/user_ldap/lib/access.php b/apps/user_ldap/lib/access.php index 422e43fc00..68cbe4a5e7 100644 --- a/apps/user_ldap/lib/access.php +++ b/apps/user_ldap/lib/access.php @@ -719,6 +719,50 @@ abstract class Access { return $combinedFilter; } + /** + * @brief creates a filter part for to perfrom search for users + * @param string $search the search term + * @return string the final filter part to use in LDAP searches + */ + public function getFilterPartForUserSearch($search) { + return $this->getFilterPartForSearch($search, $this->connection->ldapAttributesForUserSearch, $this->connection->ldapUserDisplayName); + } + + /** + * @brief creates a filter part for to perfrom search for groups + * @param string $search the search term + * @return string the final filter part to use in LDAP searches + */ + public function getFilterPartForGroupSearch($search) { + return $this->getFilterPartForSearch($search, $this->connection->ldapAttributesForGroupSearch, $this->connection->ldapGroupDisplayName); + } + + /** + * @brief creates a filter part for searches + * @param string $search the search term + * @param string $fallbackAttribute a fallback attribute in case the user + * did not define search attributes. Typically the display name attribute. + * @returns string the final filter part to use in LDAP searches + */ + private function getFilterPartForSearch($search, $searchAttributes, $fallbackAttribute) { + $filter = array(); + $search = empty($search) ? '*' : '*'.$search.'*'; + if(!is_array($searchAttributes) || count($searchAttributes) == 0) { + if(empty($fallbackAttribute)) { + return ''; + } + $filter[] = $fallbackAttribute . '=' . $search; + } else { + foreach($searchAttributes as $attribute) { + $filter[] = $attribute . '=' . $search; + } + } + if(count($filter) == 1) { + return '('.$filter[0].')'; + } + return $this->combineFilterWithOr($filter); + } + public function areCredentialsValid($name, $password) { $name = $this->DNasBaseParameter($name); $testConnection = clone $this->connection; @@ -912,7 +956,7 @@ abstract class Access { $reOffset = ($offset - $limit) < 0 ? 0 : $offset - $limit; //a bit recursive, $offset of 0 is the exit \OCP\Util::writeLog('user_ldap', 'Looking for cookie L/O '.$limit.'/'.$reOffset, \OCP\Util::INFO); - $this->search($filter, $base, $attr, $limit, $reOffset, true); + $this->search($filter, array($base), $attr, $limit, $reOffset, true); $cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset); //still no cookie? obviously, the server does not like us. Let's skip paging efforts. //TODO: remember this, probably does not change in the next request... diff --git a/apps/user_ldap/lib/connection.php b/apps/user_ldap/lib/connection.php index 7046cbbfc7..acc33e047c 100644 --- a/apps/user_ldap/lib/connection.php +++ b/apps/user_ldap/lib/connection.php @@ -4,7 +4,7 @@ * ownCloud – LDAP Access * * @author Arthur Schiwon - * @copyright 2012 Arthur Schiwon blizzz@owncloud.com + * @copyright 2012, 2013 Arthur Schiwon blizzz@owncloud.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE @@ -25,6 +25,7 @@ namespace OCA\user_ldap\lib; class Connection { private $ldapConnectionRes = null; + private $configPrefix; private $configID; private $configured = false; @@ -35,6 +36,8 @@ class Connection { protected $config = array( 'ldapHost' => null, 'ldapPort' => null, + 'ldapBackupHost' => null, + 'ldapBackupPort' => null, 'ldapBase' => null, 'ldapBaseUsers' => null, 'ldapBaseGroups' => null, @@ -48,6 +51,7 @@ class Connection { 'ldapUserFilter' => null, 'ldapGroupFilter' => null, 'ldapGroupDisplayName' => null, + 'ldapGroupMemberAssocAttr' => null, 'ldapLoginFilter' => null, 'ldapQuotaAttribute' => null, 'ldapQuotaDefault' => null, @@ -55,15 +59,24 @@ class Connection { 'ldapCacheTTL' => null, 'ldapUuidAttribute' => null, 'ldapOverrideUuidAttribute' => null, + 'ldapOverrideMainServer' => false, + 'ldapConfigurationActive' => false, + 'ldapAttributesForUserSearch' => null, + 'ldapAttributesForGroupSearch' => null, 'homeFolderNamingRule' => null, 'hasPagedResultSupport' => false, ); - public function __construct($configID = 'user_ldap') { + /** + * @brief Constructor + * @param $configPrefix a string with the prefix for the configkey column (appconfig table) + * @param $configID a string with the value for the appid column (appconfig table) or null for on-the-fly connections + */ + public function __construct($configPrefix = '', $configID = 'user_ldap') { + $this->configPrefix = $configPrefix; $this->configID = $configID; $this->cache = \OC_Cache::getGlobalCache(); $this->config['hasPagedResultSupport'] = (function_exists('ldap_control_paged_result') && function_exists('ldap_control_paged_result_response')); - \OCP\Util::writeLog('user_ldap', 'PHP supports paged results? '.print_r($this->config['hasPagedResultSupport'], true), \OCP\Util::INFO); } public function __destruct() { @@ -84,12 +97,12 @@ class Connection { public function __set($name, $value) { $changed = false; - //omly few options are writable + //only few options are writable if($name == 'ldapUuidAttribute') { \OCP\Util::writeLog('user_ldap', 'Set config ldapUuidAttribute to '.$value, \OCP\Util::DEBUG); $this->config[$name] = $value; if(!empty($this->configID)) { - \OCP\Config::setAppValue($this->configID, 'ldap_uuid_attribute', $value); + \OCP\Config::setAppValue($this->configID, $this->configPrefix.'ldap_uuid_attribute', $value); } $changed = true; } @@ -126,7 +139,7 @@ class Connection { } private function getCacheKey($key) { - $prefix = 'LDAP-'.$this->configID.'-'; + $prefix = 'LDAP-'.$this->configID.'-'.$this->configPrefix.'-'; if(is_null($key)) { return $prefix; } @@ -164,7 +177,8 @@ class Connection { if(!$this->configured) { $this->readConfiguration(); } - if(!$this->config['ldapCacheTTL']) { + if(!$this->config['ldapCacheTTL'] + || !$this->config['ldapConfigurationActive']) { return null; } $key = $this->getCacheKey($key); @@ -176,42 +190,96 @@ class Connection { $this->cache->clear($this->getCacheKey(null)); } + private function getValue($varname) { + static $defaults; + if(is_null($defaults)){ + $defaults = $this->getDefaults(); + } + return \OCP\Config::getAppValue($this->configID, + $this->configPrefix.$varname, + $defaults[$varname]); + } + + private function setValue($varname, $value) { + \OCP\Config::setAppValue($this->configID, + $this->configPrefix.$varname, + $value); + } + /** * Caches the general LDAP configuration. */ private function readConfiguration($force = false) { - \OCP\Util::writeLog('user_ldap', 'Checking conf state: isConfigured? '.print_r($this->configured, true).' isForce? '.print_r($force, true).' configID? '.print_r($this->configID, true), \OCP\Util::DEBUG); if((!$this->configured || $force) && !is_null($this->configID)) { - \OCP\Util::writeLog('user_ldap', 'Reading the configuration', \OCP\Util::DEBUG); - $this->config['ldapHost'] = \OCP\Config::getAppValue($this->configID, 'ldap_host', ''); - $this->config['ldapPort'] = \OCP\Config::getAppValue($this->configID, 'ldap_port', 389); - $this->config['ldapAgentName'] = \OCP\Config::getAppValue($this->configID, 'ldap_dn', ''); - $this->config['ldapAgentPassword'] = base64_decode(\OCP\Config::getAppValue($this->configID, 'ldap_agent_password', '')); - $this->config['ldapBase'] = preg_split('/\r\n|\r|\n/', \OCP\Config::getAppValue($this->configID, 'ldap_base', '')); - $this->config['ldapBaseUsers'] = preg_split('/\r\n|\r|\n/', \OCP\Config::getAppValue($this->configID, 'ldap_base_users', $this->config['ldapBase'])); - $this->config['ldapBaseGroups'] = preg_split('/\r\n|\r|\n/', \OCP\Config::getAppValue($this->configID, 'ldap_base_groups', $this->config['ldapBase'])); - $this->config['ldapTLS'] = \OCP\Config::getAppValue($this->configID, 'ldap_tls', 0); - $this->config['ldapNoCase'] = \OCP\Config::getAppValue($this->configID, 'ldap_nocase', 0); - $this->config['turnOffCertCheck'] = \OCP\Config::getAppValue($this->configID, 'ldap_turn_off_cert_check', 0); - $this->config['ldapUserDisplayName'] = mb_strtolower(\OCP\Config::getAppValue($this->configID, 'ldap_display_name', 'uid'), 'UTF-8'); - $this->config['ldapUserFilter'] = \OCP\Config::getAppValue($this->configID, 'ldap_userlist_filter', 'objectClass=person'); - $this->config['ldapGroupFilter'] = \OCP\Config::getAppValue($this->configID, 'ldap_group_filter', '(objectClass=posixGroup)'); - $this->config['ldapLoginFilter'] = \OCP\Config::getAppValue($this->configID, 'ldap_login_filter', '(uid=%uid)'); - $this->config['ldapGroupDisplayName'] = mb_strtolower(\OCP\Config::getAppValue($this->configID, 'ldap_group_display_name', 'uid'), 'UTF-8'); - $this->config['ldapQuotaAttribute'] = \OCP\Config::getAppValue($this->configID, 'ldap_quota_attr', ''); - $this->config['ldapQuotaDefault'] = \OCP\Config::getAppValue($this->configID, 'ldap_quota_def', ''); - $this->config['ldapEmailAttribute'] = \OCP\Config::getAppValue($this->configID, 'ldap_email_attr', ''); - $this->config['ldapGroupMemberAssocAttr'] = \OCP\Config::getAppValue($this->configID, 'ldap_group_member_assoc_attribute', 'uniqueMember'); - $this->config['ldapIgnoreNamingRules'] = \OCP\Config::getSystemValue('ldapIgnoreNamingRules', false); - $this->config['ldapCacheTTL'] = \OCP\Config::getAppValue($this->configID, 'ldap_cache_ttl', 10*60); - $this->config['ldapUuidAttribute'] = \OCP\Config::getAppValue($this->configID, 'ldap_uuid_attribute', 'auto'); - $this->config['ldapOverrideUuidAttribute'] = \OCP\Config::getAppValue($this->configID, 'ldap_override_uuid_attribute', 0); - $this->config['homeFolderNamingRule'] = \OCP\Config::getAppValue($this->configID, 'home_folder_naming_rule', 'opt:username'); + $defaults = $this->getDefaults(); + $v = 'getValue'; + $this->config['ldapHost'] = $this->$v('ldap_host'); + $this->config['ldapBackupHost'] = $this->$v('ldap_backup_host'); + $this->config['ldapPort'] = $this->$v('ldap_port'); + $this->config['ldapBackupPort'] = $this->$v('ldap_backup_port'); + $this->config['ldapOverrideMainServer'] + = $this->$v('ldap_override_main_server'); + $this->config['ldapAgentName'] = $this->$v('ldap_dn'); + $this->config['ldapAgentPassword'] + = base64_decode($this->$v('ldap_agent_password')); + $rawLdapBase = $this->$v('ldap_base'); + $this->config['ldapBase'] + = preg_split('/\r\n|\r|\n/', $rawLdapBase); + $this->config['ldapBaseUsers'] + = preg_split('/\r\n|\r|\n/', ($this->$v('ldap_base_users'))); + $this->config['ldapBaseGroups'] + = preg_split('/\r\n|\r|\n/', $this->$v('ldap_base_groups')); + unset($rawLdapBase); + $this->config['ldapTLS'] = $this->$v('ldap_tls'); + $this->config['ldapNoCase'] = $this->$v('ldap_nocase'); + $this->config['turnOffCertCheck'] + = $this->$v('ldap_turn_off_cert_check'); + $this->config['ldapUserDisplayName'] + = mb_strtolower($this->$v('ldap_display_name'),'UTF-8'); + $this->config['ldapUserFilter'] + = $this->$v('ldap_userlist_filter'); + $this->config['ldapGroupFilter'] = $this->$v('ldap_group_filter'); + $this->config['ldapLoginFilter'] = $this->$v('ldap_login_filter'); + $this->config['ldapGroupDisplayName'] + = mb_strtolower($this->$v('ldap_group_display_name'), 'UTF-8'); + $this->config['ldapQuotaAttribute'] + = $this->$v('ldap_quota_attr'); + $this->config['ldapQuotaDefault'] + = $this->$v('ldap_quota_def'); + $this->config['ldapEmailAttribute'] + = $this->$v('ldap_email_attr'); + $this->config['ldapGroupMemberAssocAttr'] + = $this->$v('ldap_group_member_assoc_attribute'); + $this->config['ldapIgnoreNamingRules'] + = \OCP\Config::getSystemValue('ldapIgnoreNamingRules', false); + $this->config['ldapCacheTTL'] = $this->$v('ldap_cache_ttl'); + $this->config['ldapUuidAttribute'] + = $this->$v('ldap_uuid_attribute'); + $this->config['ldapOverrideUuidAttribute'] + = $this->$v('ldap_override_uuid_attribute'); + $this->config['homeFolderNamingRule'] + = $this->$v('home_folder_naming_rule'); + $this->config['ldapConfigurationActive'] + = $this->$v('ldap_configuration_active'); + $this->config['ldapAttributesForUserSearch'] + = preg_split('/\r\n|\r|\n/', $this->$v('ldap_attributes_for_user_search')); + $this->config['ldapAttributesForGroupSearch'] + = preg_split('/\r\n|\r|\n/', $this->$v('ldap_attributes_for_group_search')); $this->configured = $this->validateConfiguration(); } } + /** + * @return returns an array that maps internal variable names to database fields + */ + private function getConfigTranslationArray() { + static $array = array('ldap_host'=>'ldapHost', 'ldap_port'=>'ldapPort', 'ldap_backup_host'=>'ldapBackupHost', 'ldap_backup_port'=>'ldapBackupPort', 'ldap_override_main_server' => 'ldapOverrideMainServer', 'ldap_dn'=>'ldapAgentName', 'ldap_agent_password'=>'ldapAgentPassword', 'ldap_base'=>'ldapBase', 'ldap_base_users'=>'ldapBaseUsers', 'ldap_base_groups'=>'ldapBaseGroups', 'ldap_userlist_filter'=>'ldapUserFilter', 'ldap_login_filter'=>'ldapLoginFilter', 'ldap_group_filter'=>'ldapGroupFilter', 'ldap_display_name'=>'ldapUserDisplayName', 'ldap_group_display_name'=>'ldapGroupDisplayName', + + 'ldap_tls'=>'ldapTLS', 'ldap_nocase'=>'ldapNoCase', 'ldap_quota_def'=>'ldapQuotaDefault', 'ldap_quota_attr'=>'ldapQuotaAttribute', 'ldap_email_attr'=>'ldapEmailAttribute', 'ldap_group_member_assoc_attribute'=>'ldapGroupMemberAssocAttr', 'ldap_cache_ttl'=>'ldapCacheTTL', 'home_folder_naming_rule' => 'homeFolderNamingRule', 'ldap_turn_off_cert_check' => 'turnOffCertCheck', 'ldap_configuration_active' => 'ldapConfigurationActive', 'ldap_attributes_for_user_search' => 'ldapAttributesForUserSearch', 'ldap_attributes_for_group_search' => 'ldapAttributesForGroupSearch'); + return $array; + } + /** * @brief set LDAP configuration with values delivered by an array, not read from configuration * @param $config array that holds the config parameters in an associated array @@ -223,9 +291,7 @@ class Connection { return false; } - $params = array('ldap_host'=>'ldapHost', 'ldap_port'=>'ldapPort', 'ldap_dn'=>'ldapAgentName', 'ldap_agent_password'=>'ldapAgentPassword', 'ldap_base'=>'ldapBase', 'ldap_base_users'=>'ldapBaseUsers', 'ldap_base_groups'=>'ldapBaseGroups', 'ldap_userlist_filter'=>'ldapUserFilter', 'ldap_login_filter'=>'ldapLoginFilter', 'ldap_group_filter'=>'ldapGroupFilter', 'ldap_display_name'=>'ldapUserDisplayName', 'ldap_group_display_name'=>'ldapGroupDisplayName', - - 'ldap_tls'=>'ldapTLS', 'ldap_nocase'=>'ldapNoCase', 'ldap_quota_def'=>'ldapQuotaDefault', 'ldap_quota_attr'=>'ldapQuotaAttribute', 'ldap_email_attr'=>'ldapEmailAttribute', 'ldap_group_member_assoc_attribute'=>'ldapGroupMemberAssocAttr', 'ldap_cache_ttl'=>'ldapCacheTTL', 'home_folder_naming_rule' => 'homeFolderNamingRule'); + $params = $this->getConfigTranslationArray(); foreach($config as $parameter => $value) { if(isset($this->config[$parameter])) { @@ -246,6 +312,71 @@ class Connection { return $this->configured; } + /** + * @brief saves the current Configuration in the database + */ + public function saveConfiguration() { + $trans = array_flip($this->getConfigTranslationArray()); + foreach($this->config as $key => $value) { + \OCP\Util::writeLog('user_ldap', 'LDAP: storing key '.$key.' value '.$value, \OCP\Util::DEBUG); + switch ($key) { + case 'ldapAgentPassword': + $value = base64_encode($value); + break; + case 'homeFolderNamingRule': + $value = empty($value) ? 'opt:username' : 'attr:'.$value; + break; + case 'ldapBase': + case 'ldapBaseUsers': + case 'ldapBaseGroups': + case 'ldapAttributesForUserSearch': + case 'ldapAttributesForGroupSearch': + if(is_array($value)){ + $value = implode("\n", $value); + } + break; + case 'ldapIgnoreNamingRules': + case 'ldapOverrideUuidAttribute': + case 'ldapUuidAttribute': + case 'hasPagedResultSupport': + continue 2; + } + if(is_null($value)) { + $value = ''; + } + + $this->setValue($trans[$key], $value); + } + $this->clearCache(); + } + + /** + * @brief get the current LDAP configuration + * @return array + */ + public function getConfiguration() { + $this->readConfiguration(); + $trans = $this->getConfigTranslationArray(); + $config = array(); + foreach($trans as $dbKey => $classKey) { + if($classKey == 'homeFolderNamingRule') { + if(strpos($this->config[$classKey], 'opt') === 0) { + $config[$dbKey] = ''; + } else { + $config[$dbKey] = substr($this->config[$classKey], 5); + } + continue; + } else if((strpos($classKey, 'ldapBase') !== false) + || (strpos($classKey, 'ldapAttributes') !== false)) { + $config[$dbKey] = implode("\n", $this->config[$classKey]); + continue; + } + $config[$dbKey] = $this->config[$classKey]; + } + + return $config; + } + /** * @brief Validates the user specified configuration * @returns true if configuration seems OK, false otherwise @@ -264,9 +395,21 @@ class Connection { \OCP\Util::writeLog('user_ldap', 'No group filter is specified, LDAP group feature will not be used.', \OCP\Util::INFO); } if(!in_array($this->config['ldapUuidAttribute'], array('auto', 'entryuuid', 'nsuniqueid', 'objectguid')) && (!is_null($this->configID))) { - \OCP\Config::setAppValue($this->configID, 'ldap_uuid_attribute', 'auto'); + \OCP\Config::setAppValue($this->configID, $this->configPrefix.'ldap_uuid_attribute', 'auto'); \OCP\Util::writeLog('user_ldap', 'Illegal value for the UUID Attribute, reset to autodetect.', \OCP\Util::INFO); } + if(empty($this->config['ldapBackupPort'])) { + //force default + $this->config['ldapBackupPort'] = $this->config['ldapPort']; + } + foreach(array('ldapAttributesForUserSearch', 'ldapAttributesForGroupSearch') as $key) { + if(is_array($this->config[$key]) + && count($this->config[$key]) == 1 + && empty($this->config[$key][0])) { + $this->config[$key] = array(); + } + } + //second step: critical checks. If left empty or filled wrong, set as unconfigured and give a warning. @@ -310,10 +453,51 @@ class Connection { return $configurationOK; } + /** + * @returns an associative array with the default values. Keys are correspond + * to config-value entries in the database table + */ + public function getDefaults() { + return array( + 'ldap_host' => '', + 'ldap_port' => '389', + 'ldap_backup_host' => '', + 'ldap_backup_port' => '', + 'ldap_override_main_server' => '', + 'ldap_dn' => '', + 'ldap_agent_password' => '', + 'ldap_base' => '', + 'ldap_base_users' => '', + 'ldap_base_groups' => '', + 'ldap_userlist_filter' => 'objectClass=person', + 'ldap_login_filter' => 'uid=%uid', + 'ldap_group_filter' => 'objectClass=posixGroup', + 'ldap_display_name' => 'cn', + 'ldap_group_display_name' => 'cn', + 'ldap_tls' => 1, + 'ldap_nocase' => 0, + 'ldap_quota_def' => '', + 'ldap_quota_attr' => '', + 'ldap_email_attr' => '', + 'ldap_group_member_assoc_attribute' => 'uniqueMember', + 'ldap_cache_ttl' => 600, + 'ldap_uuid_attribute' => 'auto', + 'ldap_override_uuid_attribute' => 0, + 'home_folder_naming_rule' => 'opt:username', + 'ldap_turn_off_cert_check' => 0, + 'ldap_configuration_active' => 1, + 'ldap_attributes_for_user_search' => '', + 'ldap_attributes_for_group_search' => '', + ); + } + /** * Connects and Binds to LDAP */ private function establishConnection() { + if(!$this->config['ldapConfigurationActive']) { + return null; + } static $phpLDAPinstalled = true; if(!$phpLDAPinstalled) { return false; @@ -336,16 +520,40 @@ class Connection { \OCP\Util::writeLog('user_ldap', 'Could not turn off SSL certificate validation.', \OCP\Util::WARN); } } - $this->ldapConnectionRes = ldap_connect($this->config['ldapHost'], $this->config['ldapPort']); - if(ldap_set_option($this->ldapConnectionRes, LDAP_OPT_PROTOCOL_VERSION, 3)) { - if(ldap_set_option($this->ldapConnectionRes, LDAP_OPT_REFERRALS, 0)) { - if($this->config['ldapTLS']) { - ldap_start_tls($this->ldapConnectionRes); - } - } + if(!$this->config['ldapOverrideMainServer'] && !$this->getFromCache('overrideMainServer')) { + $this->doConnect($this->config['ldapHost'], $this->config['ldapPort']); + $bindStatus = $this->bind(); + $error = ldap_errno($this->ldapConnectionRes); + } else { + $bindStatus = false; + $error = null; } - return $this->bind(); + $error = null; + //if LDAP server is not reachable, try the Backup (Replica!) Server + if((!$bindStatus && ($error == -1)) + || $this->config['ldapOverrideMainServer'] + || $this->getFromCache('overrideMainServer')) { + $this->doConnect($this->config['ldapBackupHost'], $this->config['ldapBackupPort']); + $bindStatus = $this->bind(); + if($bindStatus && $error == -1) { + //when bind to backup server succeeded and failed to main server, + //skip contacting him until next cache refresh + $this->writeToCache('overrideMainServer', true); + } + } + return $bindStatus; + } + } + + private function doConnect($host, $port) { + $this->ldapConnectionRes = ldap_connect($host, $port); + if(ldap_set_option($this->ldapConnectionRes, LDAP_OPT_PROTOCOL_VERSION, 3)) { + if(ldap_set_option($this->ldapConnectionRes, LDAP_OPT_REFERRALS, 0)) { + if($this->config['ldapTLS']) { + ldap_start_tls($this->ldapConnectionRes); + } + } } } @@ -353,6 +561,9 @@ class Connection { * Binds to LDAP */ public function bind() { + if(!$this->config['ldapConfigurationActive']) { + return false; + } $ldapLogin = @ldap_bind($this->getConnectionResource(), $this->config['ldapAgentName'], $this->config['ldapAgentPassword']); if(!$ldapLogin) { \OCP\Util::writeLog('user_ldap', 'Bind failed: ' . ldap_errno($this->ldapConnectionRes) . ': ' . ldap_error($this->ldapConnectionRes), \OCP\Util::ERROR); diff --git a/apps/user_ldap/lib/helper.php b/apps/user_ldap/lib/helper.php new file mode 100644 index 0000000000..29ce998dae --- /dev/null +++ b/apps/user_ldap/lib/helper.php @@ -0,0 +1,105 @@ +. + * + */ + +namespace OCA\user_ldap\lib; + +class Helper { + + /** + * @brief returns prefixes for each saved LDAP/AD server configuration. + * @param bool optional, whether only active configuration shall be + * retrieved, defaults to false + * @return array with a list of the available prefixes + * + * Configuration prefixes are used to set up configurations for n LDAP or + * AD servers. Since configuration is stored in the database, table + * appconfig under appid user_ldap, the common identifiers in column + * 'configkey' have a prefix. The prefix for the very first server + * configuration is empty. + * Configkey Examples: + * Server 1: ldap_login_filter + * Server 2: s1_ldap_login_filter + * Server 3: s2_ldap_login_filter + * + * The prefix needs to be passed to the constructor of Connection class, + * except the default (first) server shall be connected to. + * + */ + static public function getServerConfigurationPrefixes($activeConfigurations = false) { + $referenceConfigkey = 'ldap_configuration_active'; + + $query = ' + SELECT DISTINCT `configkey` + FROM `*PREFIX*appconfig` + WHERE `configkey` LIKE ? + '; + if($activeConfigurations) { + $query .= ' AND `configvalue` = 1'; + } + $query = \OCP\DB::prepare($query); + + $serverConfigs = $query->execute(array('%'.$referenceConfigkey))->fetchAll(); + $prefixes = array(); + + foreach($serverConfigs as $serverConfig) { + $len = strlen($serverConfig['configkey']) - strlen($referenceConfigkey); + $prefixes[] = substr($serverConfig['configkey'], 0, $len); + } + + return $prefixes; + } + + /** + * @brief deletes a given saved LDAP/AD server configuration. + * @param string the configuration prefix of the config to delete + * @return bool true on success, false otherwise + */ + static public function deleteServerConfiguration($prefix) { + //just to be on the safe side + \OCP\User::checkAdminUser(); + + if(!in_array($prefix, self::getServerConfigurationPrefixes())) { + return false; + } + + $query = \OCP\DB::prepare(' + DELETE + FROM `*PREFIX*appconfig` + WHERE `configkey` LIKE ? + AND `appid` = "user_ldap" + AND `configkey` NOT IN ("enabled", "installed_version", "types", "bgjUpdateGroupsLastRun") + '); + $res = $query->execute(array($prefix.'%')); + + if(\OCP\DB::isError($res)) { + return false; + } + + if($res->numRows() == 0) { + return false; + } + + return true; + } +} + diff --git a/apps/user_ldap/lib/proxy.php b/apps/user_ldap/lib/proxy.php new file mode 100644 index 0000000000..c80e216347 --- /dev/null +++ b/apps/user_ldap/lib/proxy.php @@ -0,0 +1,104 @@ +. + * + */ + +namespace OCA\user_ldap\lib; + +abstract class Proxy { + static private $connectors = array(); + + public function __construct() { + $this->cache = \OC_Cache::getGlobalCache(); + } + + private function addConnector($configPrefix) { + self::$connectors[$configPrefix] = new \OCA\user_ldap\lib\Connection($configPrefix); + } + + protected function getConnector($configPrefix) { + if(!isset(self::$connectors[$configPrefix])) { + $this->addConnector($configPrefix); + } + return self::$connectors[$configPrefix]; + } + + protected function getConnectors() { + return self::$connectors; + } + + protected function getUserCacheKey($uid) { + return 'user-'.$uid.'-lastSeenOn'; + } + + protected function getGroupCacheKey($gid) { + return 'group-'.$gid.'-lastSeenOn'; + } + + abstract protected function callOnLastSeenOn($id, $method, $parameters); + abstract protected function walkBackends($id, $method, $parameters); + + /** + * @brief Takes care of the request to the User backend + * @param $uid string, the uid connected to the request + * @param $method string, the method of the user backend that shall be called + * @param $parameters an array of parameters to be passed + * @return mixed, the result of the specified method + */ + protected function handleRequest($id, $method, $parameters) { + if(!$result = $this->callOnLastSeenOn($id, $method, $parameters)) { + $result = $this->walkBackends($id, $method, $parameters); + } + return $result; + } + + private function getCacheKey($key) { + $prefix = 'LDAP-Proxy-'; + if(is_null($key)) { + return $prefix; + } + return $prefix.md5($key); + } + + public function getFromCache($key) { + if(!$this->isCached($key)) { + return null; + } + $key = $this->getCacheKey($key); + + return unserialize(base64_decode($this->cache->get($key))); + } + + public function isCached($key) { + $key = $this->getCacheKey($key); + return $this->cache->hasKey($key); + } + + public function writeToCache($key, $value) { + $key = $this->getCacheKey($key); + $value = base64_encode(serialize($value)); + $this->cache->set($key, $value, '2592000'); + } + + public function clearCache() { + $this->cache->clear($this->getCacheKey(null)); + } +} \ No newline at end of file diff --git a/apps/user_ldap/settings.php b/apps/user_ldap/settings.php index 58ec8e7f7a..d5d2f648b3 100644 --- a/apps/user_ldap/settings.php +++ b/apps/user_ldap/settings.php @@ -23,58 +23,46 @@ OC_Util::checkAdminUser(); -$params = array('ldap_host', 'ldap_port', 'ldap_dn', 'ldap_agent_password', 'ldap_base', 'ldap_base_users', 'ldap_base_groups', 'ldap_userlist_filter', 'ldap_login_filter', 'ldap_group_filter', 'ldap_display_name', 'ldap_group_display_name', 'ldap_tls', 'ldap_turn_off_cert_check', 'ldap_nocase', 'ldap_quota_def', 'ldap_quota_attr', 'ldap_email_attr', 'ldap_group_member_assoc_attribute', 'ldap_cache_ttl', 'home_folder_naming_rule'); +$params = array('ldap_host', 'ldap_port', 'ldap_backup_host', + 'ldap_backup_port', 'ldap_override_main_server', 'ldap_dn', + 'ldap_agent_password', 'ldap_base', 'ldap_base_users', + 'ldap_base_groups', 'ldap_userlist_filter', + 'ldap_login_filter', 'ldap_group_filter', 'ldap_display_name', + 'ldap_group_display_name', 'ldap_tls', + 'ldap_turn_off_cert_check', 'ldap_nocase', 'ldap_quota_def', + 'ldap_quota_attr', 'ldap_email_attr', + 'ldap_group_member_assoc_attribute', 'ldap_cache_ttl', + 'home_folder_naming_rule' + ); OCP\Util::addscript('user_ldap', 'settings'); OCP\Util::addstyle('user_ldap', 'settings'); -if ($_POST) { - $clearCache = false; - foreach($params as $param) { - if(isset($_POST[$param])) { - $clearCache = true; - if('ldap_agent_password' == $param) { - OCP\Config::setAppValue('user_ldap', $param, base64_encode($_POST[$param])); - } elseif('home_folder_naming_rule' == $param) { - $value = empty($_POST[$param]) ? 'opt:username' : 'attr:'.$_POST[$param]; - OCP\Config::setAppValue('user_ldap', $param, $value); - } else { - OCP\Config::setAppValue('user_ldap', $param, $_POST[$param]); - } - } - elseif('ldap_tls' == $param) { - // unchecked checkboxes are not included in the post paramters - OCP\Config::setAppValue('user_ldap', $param, 0); - } - elseif('ldap_nocase' == $param) { - OCP\Config::setAppValue('user_ldap', $param, 0); - } - elseif('ldap_turn_off_cert_check' == $param) { - OCP\Config::setAppValue('user_ldap', $param, 0); - } - } - if($clearCache) { - $ldap = new \OCA\user_ldap\lib\Connection('user_ldap'); - $ldap->clearCache(); - } -} - // fill template -$tmpl = new OCP\Template( 'user_ldap', 'settings'); -foreach($params as $param) { - $value = OCP\Config::getAppValue('user_ldap', $param, ''); - $tmpl->assign($param, $value); +$tmpl = new OCP\Template('user_ldap', 'settings'); + +$prefixes = \OCA\user_ldap\lib\Helper::getServerConfigurationPrefixes(); +$scoHtml = ''; +$i = 1; +$sel = ' selected'; +foreach($prefixes as $prefix) { + $scoHtml .= ''; + $sel = ''; +} +if(count($prefixes) == 0) { + $scoHtml .= ''; +} +$tmpl->assign('serverConfigurationOptions', $scoHtml, false); + +// assign default values +if(!isset($ldap)) { + $ldap = new \OCA\user_ldap\lib\Connection(); +} +$defaults = $ldap->getDefaults(); +foreach($defaults as $key => $default) { + $tmpl->assign($key.'_default', $default); } -// settings with default values -$tmpl->assign( 'ldap_port', OCP\Config::getAppValue('user_ldap', 'ldap_port', '389')); -$tmpl->assign( 'ldap_display_name', OCP\Config::getAppValue('user_ldap', 'ldap_display_name', 'uid')); -$tmpl->assign( 'ldap_group_display_name', OCP\Config::getAppValue('user_ldap', 'ldap_group_display_name', 'cn')); -$tmpl->assign( 'ldap_group_member_assoc_attribute', OCP\Config::getAppValue('user_ldap', 'ldap_group_member_assoc_attribute', 'uniqueMember')); -$tmpl->assign( 'ldap_agent_password', base64_decode(OCP\Config::getAppValue('user_ldap', 'ldap_agent_password'))); -$tmpl->assign( 'ldap_cache_ttl', OCP\Config::getAppValue('user_ldap', 'ldap_cache_ttl', '600')); -$hfnr = OCP\Config::getAppValue('user_ldap', 'home_folder_naming_rule', 'opt:username'); -$hfnr = ($hfnr == 'opt:username') ? '' : substr($hfnr, strlen('attr:')); -$tmpl->assign( 'home_folder_naming_rule', $hfnr, ''); +// $tmpl->assign(); return $tmpl->fetchPage(); diff --git a/apps/user_ldap/templates/settings.php b/apps/user_ldap/templates/settings.php index b24c6e2f02..e6fa91cc85 100644 --- a/apps/user_ldap/templates/settings.php +++ b/apps/user_ldap/templates/settings.php @@ -12,31 +12,43 @@ } ?>
-

-

-

-

-


t('use %%uid placeholder, e.g. "uid=%%uid"');?>

-


t('without any placeholder, e.g. "objectClass=person".');?>

-


t('without any placeholder, e.g. "objectClass=posixGroup".');?>

+

+ +

+

+

+

+

+


t('use %%uid placeholder, e.g. "uid=%%uid"');?>

+


t('without any placeholder, e.g. "objectClass=person".');?>

+


t('without any placeholder, e.g. "objectClass=posixGroup".');?>

-

-

-

-

-

title="t('Do not use it for SSL connections, it will fail.');?>" />

-

>

-

>
t('Not recommended, use for testing only.');?>

-

-

-

-

-

-

-

+

+

+

+

+

+

+

+

+

+

+

+

>

+


t('Not recommended, use for testing only.');?>

+

+

+

+

+

+

+

- t('Help');?> + t('Help');?> diff --git a/apps/user_ldap/user_ldap.php b/apps/user_ldap/user_ldap.php index b3180e1135..6aa8cd9b83 100644 --- a/apps/user_ldap/user_ldap.php +++ b/apps/user_ldap/user_ldap.php @@ -116,10 +116,9 @@ class USER_LDAP extends lib\Access implements \OCP\UserInterface { if($limit <= 0) { $limit = null; } - $search = empty($search) ? '*' : '*'.$search.'*'; $filter = $this->combineFilterWithAnd(array( $this->connection->ldapUserFilter, - $this->connection->ldapUserDisplayName.'='.$search + $this->getFilterPartForUserSearch($search) )); \OCP\Util::writeLog('user_ldap', 'getUsers: Options: search '.$search.' limit '.$limit.' offset '.$offset.' Filter: '.$filter, \OCP\Util::DEBUG); diff --git a/apps/user_ldap/user_proxy.php b/apps/user_ldap/user_proxy.php new file mode 100644 index 0000000000..47f901ddb5 --- /dev/null +++ b/apps/user_ldap/user_proxy.php @@ -0,0 +1,159 @@ +. + * + */ + +namespace OCA\user_ldap; + +class User_Proxy extends lib\Proxy implements \OCP\UserInterface { + private $backends = array(); + private $refBackend = null; + + /** + * @brief Constructor + * @param $serverConfigPrefixes array containing the config Prefixes + */ + public function __construct($serverConfigPrefixes) { + parent::__construct(); + foreach($serverConfigPrefixes as $configPrefix) { + $this->backends[$configPrefix] = new \OCA\user_ldap\USER_LDAP(); + $connector = $this->getConnector($configPrefix); + $this->backends[$configPrefix]->setConnector($connector); + if(is_null($this->refBackend)) { + $this->refBackend = &$this->backends[$configPrefix]; + } + } + } + + /** + * @brief Tries the backends one after the other until a positive result is returned from the specified method + * @param $uid string, the uid connected to the request + * @param $method string, the method of the user backend that shall be called + * @param $parameters an array of parameters to be passed + * @return mixed, the result of the method or false + */ + protected function walkBackends($uid, $method, $parameters) { + $cacheKey = $this->getUserCacheKey($uid); + foreach($this->backends as $configPrefix => $backend) { + if($result = call_user_func_array(array($backend, $method), $parameters)) { + $this->writeToCache($cacheKey, $configPrefix); + return $result; + } + } + return false; + } + + /** + * @brief Asks the backend connected to the server that supposely takes care of the uid from the request. + * @param $uid string, the uid connected to the request + * @param $method string, the method of the user backend that shall be called + * @param $parameters an array of parameters to be passed + * @return mixed, the result of the method or false + */ + protected function callOnLastSeenOn($uid, $method, $parameters) { + $cacheKey = $this->getUserCacheKey($uid); + $prefix = $this->getFromCache($cacheKey); + //in case the uid has been found in the past, try this stored connection first + if(!is_null($prefix)) { + if(isset($this->backends[$prefix])) { + $result = call_user_func_array(array($this->backends[$prefix], $method), $parameters); + if(!$result) { + //not found here, reset cache to null + $this->writeToCache($cacheKey, null); + } + return $result; + } + } + return false; + } + + /** + * @brief Check if backend implements actions + * @param $actions bitwise-or'ed actions + * @returns boolean + * + * Returns the supported actions as int to be + * compared with OC_USER_BACKEND_CREATE_USER etc. + */ + public function implementsActions($actions) { + //it's the same across all our user backends obviously + return $this->refBackend->implementsActions($actions); + } + + /** + * @brief Get a list of all users + * @returns array with all uids + * + * Get a list of all users. + */ + public function getUsers($search = '', $limit = 10, $offset = 0) { + //we do it just as the /OC_User implementation: do not play around with limit and offset but ask all backends + $users = array(); + foreach($this->backends as $backend) { + $backendUsers = $backend->getUsers($search, $limit, $offset); + if (is_array($backendUsers)) { + $users = array_merge($users, $backendUsers); + } + } + return $users; + } + + /** + * @brief check if a user exists + * @param string $uid the username + * @return boolean + */ + public function userExists($uid) { + return $this->handleRequest($uid, 'userExists', array($uid)); + } + + /** + * @brief Check if the password is correct + * @param $uid The username + * @param $password The password + * @returns true/false + * + * Check if the password is correct without logging in the user + */ + public function checkPassword($uid, $password) { + return $this->handleRequest($uid, 'checkPassword', array($uid, $password)); + } + + /** + * @brief get the user's home directory + * @param string $uid the username + * @return boolean + */ + public function getHome($uid) { + return $this->handleRequest($uid, 'getHome', array($uid)); + } + + /** + * @brief delete a user + * @param $uid The username of the user to delete + * @returns true/false + * + * Deletes a user + */ + public function deleteUser($uid) { + return false; + } +} \ No newline at end of file