PageRenderTime 223ms CodeModel.GetById 50ms app.highlight 86ms RepoModel.GetById 75ms app.codeStats 1ms

/apps/user_ldap/lib/access.php

https://github.com/sezuan/core
PHP | 1124 lines | 730 code | 102 blank | 292 comment | 117 complexity | f10bc74d04f1ed58df6f686005496b0f MD5 | raw file
   1<?php
   2
   3/**
   4 * ownCloud – LDAP Access
   5 *
   6 * @author Arthur Schiwon
   7 * @copyright 2012, 2013 Arthur Schiwon blizzz@owncloud.com
   8 *
   9 * This library is free software; you can redistribute it and/or
  10 * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
  11 * License as published by the Free Software Foundation; either
  12 * version 3 of the License, or any later version.
  13 *
  14 * This library is distributed in the hope that it will be useful,
  15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  17 * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
  18 *
  19 * You should have received a copy of the GNU Affero General Public
  20 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
  21 *
  22 */
  23
  24namespace OCA\user_ldap\lib;
  25
  26abstract class Access {
  27	protected $connection;
  28	//never ever check this var directly, always use getPagedSearchResultState
  29	protected $pagedSearchedSuccessful;
  30
  31	public function setConnector(Connection &$connection) {
  32		$this->connection = $connection;
  33	}
  34
  35	private function checkConnection() {
  36		return ($this->connection instanceof Connection);
  37	}
  38
  39	/**
  40	 * @brief reads a given attribute for an LDAP record identified by a DN
  41	 * @param $dn the record in question
  42	 * @param $attr the attribute that shall be retrieved
  43	 *        if empty, just check the record's existence
  44	 * @returns an array of values on success or an empty
  45	 *          array if $attr is empty, false otherwise
  46	 *
  47	 * Reads an attribute from an LDAP entry or check if entry exists
  48	 */
  49	public function readAttribute($dn, $attr, $filter = 'objectClass=*') {
  50		if(!$this->checkConnection()) {
  51			\OCP\Util::writeLog('user_ldap',
  52				'No LDAP Connector assigned, access impossible for readAttribute.',
  53				\OCP\Util::WARN);
  54			return false;
  55		}
  56		$cr = $this->connection->getConnectionResource();
  57		if(!is_resource($cr)) {
  58			//LDAP not available
  59			\OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', \OCP\Util::DEBUG);
  60			return false;
  61		}
  62		$dn = $this->DNasBaseParameter($dn);
  63		$rr = @ldap_read($cr, $dn, $filter, array($attr));
  64		if(!is_resource($rr)) {
  65			if(!empty($attr)) {
  66				//do not throw this message on userExists check, irritates
  67				\OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN '.$dn, \OCP\Util::DEBUG);
  68			}
  69			//in case an error occurs , e.g. object does not exist
  70			return false;
  71		}
  72		if (empty($attr)) {
  73			\OCP\Util::writeLog('user_ldap', 'readAttribute: '.$dn.' found', \OCP\Util::DEBUG);
  74			return array();
  75		}
  76		$er = ldap_first_entry($cr, $rr);
  77		if(!is_resource($er)) {
  78			//did not match the filter, return false
  79			return false;
  80		}
  81		//LDAP attributes are not case sensitive
  82		$result = \OCP\Util::mb_array_change_key_case(ldap_get_attributes($cr, $er), MB_CASE_LOWER, 'UTF-8');
  83		$attr = mb_strtolower($attr, 'UTF-8');
  84
  85		if(isset($result[$attr]) && $result[$attr]['count'] > 0) {
  86			$values = array();
  87			for($i=0;$i<$result[$attr]['count'];$i++) {
  88				if($this->resemblesDN($attr)) {
  89					$values[] = $this->sanitizeDN($result[$attr][$i]);
  90				} elseif(strtolower($attr) === 'objectguid' || strtolower($attr) === 'guid') {
  91					$values[] = $this->convertObjectGUID2Str($result[$attr][$i]);
  92				} else {
  93					$values[] = $result[$attr][$i];
  94				}
  95			}
  96			return $values;
  97		}
  98		\OCP\Util::writeLog('user_ldap', 'Requested attribute '.$attr.' not found for '.$dn, \OCP\Util::DEBUG);
  99		return false;
 100	}
 101
 102	/**
 103	 * @brief checks wether the given attribute`s valua is probably a DN
 104	 * @param $attr the attribute in question
 105	 * @return if so true, otherwise false
 106	 */
 107	private function resemblesDN($attr) {
 108		$resemblingAttributes = array(
 109			'dn',
 110			'uniquemember',
 111			'member'
 112		);
 113		return in_array($attr, $resemblingAttributes);
 114	}
 115
 116	/**
 117	 * @brief sanitizes a DN received from the LDAP server
 118	 * @param $dn the DN in question
 119	 * @return the sanitized DN
 120	 */
 121	private function sanitizeDN($dn) {
 122		//treating multiple base DNs
 123		if(is_array($dn)) {
 124			$result = array();
 125			foreach($dn as $singleDN) {
 126			    $result[] = $this->sanitizeDN($singleDN);
 127			}
 128			return $result;
 129		}
 130
 131		//OID sometimes gives back DNs with whitespace after the comma
 132		// a la "uid=foo, cn=bar, dn=..." We need to tackle this!
 133		$dn = preg_replace('/([^\\\]),(\s+)/u', '\1,', $dn);
 134
 135		//make comparisons and everything work
 136		$dn = mb_strtolower($dn, 'UTF-8');
 137
 138		//escape DN values according to RFC 2253 – this is already done by ldap_explode_dn
 139		//to use the DN in search filters, \ needs to be escaped to \5c additionally
 140		//to use them in bases, we convert them back to simple backslashes in readAttribute()
 141		$replacements = array(
 142			'\,' => '\5c2C',
 143			'\=' => '\5c3D',
 144			'\+' => '\5c2B',
 145			'\<' => '\5c3C',
 146			'\>' => '\5c3E',
 147			'\;' => '\5c3B',
 148			'\"' => '\5c22',
 149			'\#' => '\5c23',
 150			'('  => '\28',
 151			')'  => '\29',
 152			'*'  => '\2A',
 153		);
 154		$dn = str_replace(array_keys($replacements), array_values($replacements), $dn);
 155
 156		return $dn;
 157	}
 158
 159	/**
 160	 * gives back the database table for the query
 161	 */
 162	private function getMapTable($isUser) {
 163		if($isUser) {
 164			return '*PREFIX*ldap_user_mapping';
 165		} else {
 166			return '*PREFIX*ldap_group_mapping';
 167		}
 168	}
 169
 170	/**
 171	 * @brief returns the LDAP DN for the given internal ownCloud name of the group
 172	 * @param $name the ownCloud name in question
 173	 * @returns string with the LDAP DN on success, otherwise false
 174	 *
 175	 * returns the LDAP DN for the given internal ownCloud name of the group
 176	 */
 177	public function groupname2dn($name) {
 178		$dn = $this->ocname2dn($name, false);
 179
 180		if($dn) {
 181			return $dn;
 182		}
 183
 184		return false;
 185	}
 186
 187	/**
 188	 * @brief returns the LDAP DN for the given internal ownCloud name of the user
 189	 * @param $name the ownCloud name in question
 190	 * @returns string with the LDAP DN on success, otherwise false
 191	 *
 192	 * returns the LDAP DN for the given internal ownCloud name of the user
 193	 */
 194	public function username2dn($name) {
 195		$dn = $this->ocname2dn($name, true);
 196		if($dn) {
 197			return $dn;
 198		}
 199
 200		return false;
 201	}
 202
 203	/**
 204	 * @brief returns the LDAP DN for the given internal ownCloud name
 205	 * @param $name the ownCloud name in question
 206	 * @param $isUser is it a user? otherwise group
 207	 * @returns string with the LDAP DN on success, otherwise false
 208	 *
 209	 * returns the LDAP DN for the given internal ownCloud name
 210	 */
 211	private function ocname2dn($name, $isUser) {
 212		$table = $this->getMapTable($isUser);
 213
 214		$query = \OCP\DB::prepare('
 215			SELECT `ldap_dn`
 216			FROM `'.$table.'`
 217			WHERE `owncloud_name` = ?
 218		');
 219
 220		$record = $query->execute(array($name))->fetchOne();
 221		return $record;
 222	}
 223
 224	/**
 225	 * @brief returns the internal ownCloud name for the given LDAP DN of the group
 226	 * @param $dn the dn of the group object
 227	 * @param $ldapname optional, the display name of the object
 228	 * @returns string with with the name to use in ownCloud, false on DN outside of search DN
 229	 *
 230	 * returns the internal ownCloud name for the given LDAP DN of the
 231	 * group, false on DN outside of search DN or failure
 232	 */
 233	public function dn2groupname($dn, $ldapname = null) {
 234		//To avoid bypassing the base DN settings under certain circumstances
 235		//with the group support, check whether the provided DN matches one of
 236		//the given Bases
 237		if(!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) {
 238			return false;
 239		}
 240
 241		return $this->dn2ocname($dn, $ldapname, false);
 242	}
 243
 244	/**
 245	 * @brief returns the internal ownCloud name for the given LDAP DN of the user
 246	 * @param $dn the dn of the user object
 247	 * @param $ldapname optional, the display name of the object
 248	 * @returns string with with the name to use in ownCloud
 249	 *
 250	 * returns the internal ownCloud name for the given LDAP DN of the user, false on DN outside of search DN or failure
 251	 */
 252	public function dn2username($dn, $ldapname = null) {
 253		//To avoid bypassing the base DN settings under certain circumstances
 254		//with the group support, check whether the provided DN matches one of
 255		//the given Bases
 256		if(!$this->isDNPartOfBase($dn, $this->connection->ldapBaseUsers)) {
 257			return false;
 258		}
 259
 260		return $this->dn2ocname($dn, $ldapname, true);
 261	}
 262
 263	/**
 264	 * @brief returns an internal ownCloud name for the given LDAP DN
 265	 * @param $dn the dn of the user object
 266	 * @param $ldapname optional, the display name of the object
 267	 * @param $isUser optional, wether it is a user object (otherwise group assumed)
 268	 * @returns string with with the name to use in ownCloud
 269	 *
 270	 * returns the internal ownCloud name for the given LDAP DN of the user, false on DN outside of search DN
 271	 */
 272	public function dn2ocname($dn, $ldapname = null, $isUser = true) {
 273		$table = $this->getMapTable($isUser);
 274		if($isUser) {
 275			$fncFindMappedName = 'findMappedUser';
 276			$nameAttribute = $this->connection->ldapUserDisplayName;
 277		} else {
 278			$fncFindMappedName = 'findMappedGroup';
 279			$nameAttribute = $this->connection->ldapGroupDisplayName;
 280		}
 281
 282		//let's try to retrieve the ownCloud name from the mappings table
 283		$ocname = $this->$fncFindMappedName($dn);
 284		if($ocname) {
 285			return $ocname;
 286		}
 287
 288		//second try: get the UUID and check if it is known. Then, update the DN and return the name.
 289		$uuid = $this->getUUID($dn);
 290		if($uuid) {
 291			$query = \OCP\DB::prepare('
 292				SELECT `owncloud_name`
 293				FROM `'.$table.'`
 294				WHERE `directory_uuid` = ?
 295			');
 296			$component = $query->execute(array($uuid))->fetchOne();
 297			if($component) {
 298				$query = \OCP\DB::prepare('
 299					UPDATE `'.$table.'`
 300					SET `ldap_dn` = ?
 301					WHERE `directory_uuid` = ?
 302				');
 303				$query->execute(array($dn, $uuid));
 304				return $component;
 305			}
 306		} else {
 307			//If the UUID can't be detected something is foul.
 308			\OCP\Util::writeLog('user_ldap', 'Cannot determine UUID for '.$dn.'. Skipping.', \OCP\Util::INFO);
 309			return false;
 310		}
 311
 312		if(is_null($ldapname)) {
 313			$ldapname = $this->readAttribute($dn, $nameAttribute);
 314			if(!isset($ldapname[0]) && empty($ldapname[0])) {
 315				\OCP\Util::writeLog('user_ldap', 'No or empty name for '.$dn.'.', \OCP\Util::INFO);
 316				return false;
 317			}
 318			$ldapname = $ldapname[0];
 319		}
 320
 321		if($isUser) {
 322			$usernameAttribute = $this->connection->ldapExpertUsernameAttr;
 323			if(!emptY($usernameAttribute)) {
 324				$username = $this->readAttribute($dn, $usernameAttribute);
 325				$username = $username[0];
 326			} else {
 327				$username = $uuid;
 328			}
 329			$intname = $this->sanitizeUsername($username);
 330		} else {
 331			$intname = $ldapname;
 332		}
 333
 334		//a new user/group! Add it only if it doesn't conflict with other backend's users or existing groups
 335		//disabling Cache is required to avoid that the new user is cached as not-existing in fooExists check
 336		$originalTTL = $this->connection->ldapCacheTTL;
 337		$this->connection->setConfiguration(array('ldapCacheTTL' => 0));
 338		if(($isUser && !\OCP\User::userExists($intname))
 339			|| (!$isUser && !\OC_Group::groupExists($intname))) {
 340			if($this->mapComponent($dn, $intname, $isUser)) {
 341				$this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
 342				return $intname;
 343			}
 344		}
 345		$this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
 346
 347		$altname = $this->createAltInternalOwnCloudName($intname, $isUser);
 348		if($this->mapComponent($dn, $altname, $isUser)) {
 349			return $altname;
 350		}
 351
 352		//if everything else did not help..
 353		\OCP\Util::writeLog('user_ldap', 'Could not create unique ownCloud name for '.$dn.'.', \OCP\Util::INFO);
 354		return false;
 355	}
 356
 357	/**
 358	 * @brief gives back the user names as they are used ownClod internally
 359	 * @param $ldapGroups an array with the ldap Users result in style of array ( array ('dn' => foo, 'uid' => bar), ... )
 360	 * @returns an array with the user names to use in ownCloud
 361	 *
 362	 * gives back the user names as they are used ownClod internally
 363	 */
 364	public function ownCloudUserNames($ldapUsers) {
 365		return $this->ldap2ownCloudNames($ldapUsers, true);
 366	}
 367
 368	/**
 369	 * @brief gives back the group names as they are used ownClod internally
 370	 * @param $ldapGroups an array with the ldap Groups result in style of array ( array ('dn' => foo, 'cn' => bar), ... )
 371	 * @returns an array with the group names to use in ownCloud
 372	 *
 373	 * gives back the group names as they are used ownClod internally
 374	 */
 375	public function ownCloudGroupNames($ldapGroups) {
 376		return $this->ldap2ownCloudNames($ldapGroups, false);
 377	}
 378
 379	private function findMappedUser($dn) {
 380		static $query = null;
 381		if(is_null($query)) {
 382			$query = \OCP\DB::prepare('
 383				SELECT `owncloud_name`
 384				FROM `'.$this->getMapTable(true).'`
 385				WHERE `ldap_dn` = ?'
 386			);
 387		}
 388		$res = $query->execute(array($dn))->fetchOne();
 389		if($res) {
 390			return  $res;
 391		}
 392		return false;
 393	}
 394
 395	private function findMappedGroup($dn) {
 396		static $query = null;
 397		if(is_null($query)) {
 398			$query = \OCP\DB::prepare('
 399					SELECT `owncloud_name`
 400					FROM `'.$this->getMapTable(false).'`
 401					WHERE `ldap_dn` = ?'
 402			);
 403		}
 404		$res = $query->execute(array($dn))->fetchOne();
 405		if($res) {
 406			return  $res;
 407		}
 408		return false;
 409	}
 410
 411
 412	private function ldap2ownCloudNames($ldapObjects, $isUsers) {
 413		if($isUsers) {
 414			$nameAttribute = $this->connection->ldapUserDisplayName;
 415		} else {
 416			$nameAttribute = $this->connection->ldapGroupDisplayName;
 417		}
 418		$ownCloudNames = array();
 419
 420		foreach($ldapObjects as $ldapObject) {
 421			$nameByLDAP = isset($ldapObject[$nameAttribute]) ? $ldapObject[$nameAttribute] : null;
 422			$ocname = $this->dn2ocname($ldapObject['dn'], $nameByLDAP, $isUsers);
 423			if($ocname) {
 424				$ownCloudNames[] = $ocname;
 425			}
 426			continue;
 427		}
 428		return $ownCloudNames;
 429	}
 430
 431	/**
 432	 * @brief creates a unique name for internal ownCloud use for users. Don't call it directly.
 433	 * @param $name the display name of the object
 434	 * @returns string with with the name to use in ownCloud or false if unsuccessful
 435	 *
 436	 * Instead of using this method directly, call
 437	 * createAltInternalOwnCloudName($name, true)
 438	 */
 439	private function _createAltInternalOwnCloudNameForUsers($name) {
 440		$attempts = 0;
 441		//while loop is just a precaution. If a name is not generated within
 442		//20 attempts, something else is very wrong. Avoids infinite loop.
 443		while($attempts < 20){
 444			$altName = $name . '_' . rand(1000,9999);
 445			if(!\OCP\User::userExists($altName)) {
 446				return $altName;
 447			}
 448			$attempts++;
 449		}
 450		return false;
 451	}
 452
 453	/**
 454	 * @brief creates a unique name for internal ownCloud use for groups. Don't call it directly.
 455	 * @param $name the display name of the object
 456	 * @returns string with with the name to use in ownCloud or false if unsuccessful.
 457	 *
 458	 * Instead of using this method directly, call
 459	 * createAltInternalOwnCloudName($name, false)
 460	 *
 461	 * Group names are also used as display names, so we do a sequential
 462	 * numbering, e.g. Developers_42 when there are 41 other groups called
 463	 * "Developers"
 464	 */
 465	private function _createAltInternalOwnCloudNameForGroups($name) {
 466		$query = \OCP\DB::prepare('
 467			SELECT `owncloud_name`
 468			FROM `'.$this->getMapTable(false).'`
 469			WHERE `owncloud_name` LIKE ?
 470		');
 471
 472		$usedNames = array();
 473		$res = $query->execute(array($name.'_%'));
 474		while($row = $res->fetchRow()) {
 475			$usedNames[] = $row['owncloud_name'];
 476		}
 477		if(!($usedNames) || count($usedNames) === 0) {
 478			$lastNo = 1; //will become name_2
 479		} else {
 480			natsort($usedNames);
 481			$lastname = array_pop($usedNames);
 482			$lastNo = intval(substr($lastname, strrpos($lastname, '_') + 1));
 483		}
 484		$altName = $name.'_'.strval($lastNo+1);
 485		unset($usedNames);
 486
 487		$attempts = 1;
 488		while($attempts < 21){
 489			//Pro forma check to be really sure it is unique
 490			//while loop is just a precaution. If a name is not generated within
 491			//20 attempts, something else is very wrong. Avoids infinite loop.
 492			if(!\OC_Group::groupExists($altName)) {
 493				return $altName;
 494			}
 495			$altName = $name . '_' . $lastNo + $attempts;
 496			$attempts++;
 497		}
 498		return false;
 499	}
 500
 501	/**
 502	 * @brief creates a unique name for internal ownCloud use.
 503	 * @param $name the display name of the object
 504	 * @param $isUser boolean, whether name should be created for a user (true) or a group (false)
 505	 * @returns string with with the name to use in ownCloud or false if unsuccessful
 506	 */
 507	private function createAltInternalOwnCloudName($name, $isUser) {
 508		$originalTTL = $this->connection->ldapCacheTTL;
 509		$this->connection->setConfiguration(array('ldapCacheTTL' => 0));
 510		if($isUser) {
 511			$altName = $this->_createAltInternalOwnCloudNameForUsers($name);
 512		} else {
 513			$altName = $this->_createAltInternalOwnCloudNameForGroups($name);
 514		}
 515		$this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
 516
 517		return $altName;
 518	}
 519
 520	/**
 521	 * @brief retrieves all known groups from the mappings table
 522	 * @returns array with the results
 523	 *
 524	 * retrieves all known groups from the mappings table
 525	 */
 526	private function mappedGroups() {
 527		return $this->mappedComponents(false);
 528	}
 529
 530	/**
 531	 * @brief retrieves all known users from the mappings table
 532	 * @returns array with the results
 533	 *
 534	 * retrieves all known users from the mappings table
 535	 */
 536	private function mappedUsers() {
 537		return $this->mappedComponents(true);
 538	}
 539
 540	private function mappedComponents($isUsers) {
 541		$table = $this->getMapTable($isUsers);
 542
 543		$query = \OCP\DB::prepare('
 544			SELECT `ldap_dn`, `owncloud_name`
 545			FROM `'. $table . '`'
 546		);
 547
 548		return $query->execute()->fetchAll();
 549	}
 550
 551	/**
 552	 * @brief inserts a new user or group into the mappings table
 553	 * @param $dn the record in question
 554	 * @param $ocname the name to use in ownCloud
 555	 * @param $isUser is it a user or a group?
 556	 * @returns true on success, false otherwise
 557	 *
 558	 * inserts a new user or group into the mappings table
 559	 */
 560	private function mapComponent($dn, $ocname, $isUser = true) {
 561		$table = $this->getMapTable($isUser);
 562
 563		$sqlAdjustment = '';
 564		$dbtype = \OCP\Config::getSystemValue('dbtype');
 565		if($dbtype === 'mysql') {
 566			$sqlAdjustment = 'FROM DUAL';
 567		}
 568
 569		$insert = \OCP\DB::prepare('
 570			INSERT INTO `'.$table.'` (`ldap_dn`, `owncloud_name`, `directory_uuid`)
 571				SELECT ?,?,?
 572				'.$sqlAdjustment.'
 573				WHERE NOT EXISTS (
 574					SELECT 1
 575					FROM `'.$table.'`
 576					WHERE `ldap_dn` = ?
 577						OR `owncloud_name` = ?)
 578		');
 579
 580		//feed the DB
 581		$insRows = $insert->execute(array($dn, $ocname, $this->getUUID($dn), $dn, $ocname));
 582
 583		if(\OCP\DB::isError($insRows)) {
 584			return false;
 585		}
 586
 587		if($insRows === 0) {
 588			return false;
 589		}
 590
 591		return true;
 592	}
 593
 594	public function fetchListOfUsers($filter, $attr, $limit = null, $offset = null) {
 595		return $this->fetchList($this->searchUsers($filter, $attr, $limit, $offset), (count($attr) > 1));
 596	}
 597
 598	public function fetchListOfGroups($filter, $attr, $limit = null, $offset = null) {
 599		return $this->fetchList($this->searchGroups($filter, $attr, $limit, $offset), (count($attr) > 1));
 600	}
 601
 602	private function fetchList($list, $manyAttributes) {
 603		if(is_array($list)) {
 604			if($manyAttributes) {
 605				return $list;
 606			} else {
 607				return array_unique($list, SORT_LOCALE_STRING);
 608			}
 609		}
 610
 611		//error cause actually, maybe throw an exception in future.
 612		return array();
 613	}
 614
 615	/**
 616	 * @brief executes an LDAP search, optimized for Users
 617	 * @param $filter the LDAP filter for the search
 618	 * @param $attr optional, when a certain attribute shall be filtered out
 619	 * @returns array with the search result
 620	 *
 621	 * Executes an LDAP search
 622	 */
 623	public function searchUsers($filter, $attr = null, $limit = null, $offset = null) {
 624		return $this->search($filter, $this->connection->ldapBaseUsers, $attr, $limit, $offset);
 625	}
 626
 627	/**
 628	 * @brief executes an LDAP search, optimized for Groups
 629	 * @param $filter the LDAP filter for the search
 630	 * @param $attr optional, when a certain attribute shall be filtered out
 631	 * @returns array with the search result
 632	 *
 633	 * Executes an LDAP search
 634	 */
 635	public function searchGroups($filter, $attr = null, $limit = null, $offset = null) {
 636		return $this->search($filter, $this->connection->ldapBaseGroups, $attr, $limit, $offset);
 637	}
 638
 639	/**
 640	 * @brief executes an LDAP search
 641	 * @param $filter the LDAP filter for the search
 642	 * @param $base an array containing the LDAP subtree(s) that shall be searched
 643	 * @param $attr optional, array, one or more attributes that shall be
 644	 * retrieved. Results will according to the order in the array.
 645	 * @returns array with the search result
 646	 *
 647	 * Executes an LDAP search
 648	 */
 649	private function search($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
 650		if(!is_null($attr) && !is_array($attr)) {
 651			$attr = array(mb_strtolower($attr, 'UTF-8'));
 652		}
 653
 654		// See if we have a resource, in case not cancel with message
 655		$link_resource = $this->connection->getConnectionResource();
 656		if(!is_resource($link_resource)) {
 657			// Seems like we didn't find any resource.
 658			// Return an empty array just like before.
 659			\OCP\Util::writeLog('user_ldap', 'Could not search, because resource is missing.', \OCP\Util::DEBUG);
 660			return array();
 661		}
 662
 663		//check wether paged search should be attempted
 664		$pagedSearchOK = $this->initPagedSearch($filter, $base, $attr, $limit, $offset);
 665
 666		$linkResources = array_pad(array(), count($base), $link_resource);
 667		$sr = ldap_search($linkResources, $base, $filter, $attr);
 668		$error = ldap_errno($link_resource);
 669		if(!is_array($sr) || $error !== 0) {
 670			\OCP\Util::writeLog('user_ldap',
 671				'Error when searching: '.ldap_error($link_resource).' code '.ldap_errno($link_resource),
 672				\OCP\Util::ERROR);
 673			\OCP\Util::writeLog('user_ldap', 'Attempt for Paging?  '.print_r($pagedSearchOK, true), \OCP\Util::ERROR);
 674			return array();
 675		}
 676
 677		// Do the server-side sorting
 678		foreach(array_reverse($attr) as $sortAttr){
 679			foreach($sr as $searchResource) {
 680				ldap_sort($link_resource, $searchResource, $sortAttr);
 681			}
 682		}
 683
 684		$findings = array();
 685		foreach($sr as $key => $res) {
 686		    $findings = array_merge($findings, ldap_get_entries($link_resource, $res ));
 687		}
 688		if($pagedSearchOK) {
 689			\OCP\Util::writeLog('user_ldap', 'Paged search successful', \OCP\Util::INFO);
 690			foreach($sr as $key => $res) {
 691				$cookie = null;
 692				if(ldap_control_paged_result_response($link_resource, $res, $cookie)) {
 693					\OCP\Util::writeLog('user_ldap', 'Set paged search cookie', \OCP\Util::INFO);
 694					$this->setPagedResultCookie($base[$key], $filter, $limit, $offset, $cookie);
 695				}
 696			}
 697
 698			//browsing through prior pages to get the cookie for the new one
 699			if($skipHandling) {
 700				return;
 701			}
 702			// if count is bigger, then the server does not support
 703			// paged search. Instead, he did a normal search. We set a
 704			// flag here, so the callee knows how to deal with it.
 705			if($findings['count'] <= $limit) {
 706				$this->pagedSearchedSuccessful = true;
 707			}
 708		} else {
 709			if(!is_null($limit)) {
 710				\OCP\Util::writeLog('user_ldap', 'Paged search failed :(', \OCP\Util::INFO);
 711			}
 712		}
 713
 714		// if we're here, probably no connection resource is returned.
 715		// to make ownCloud behave nicely, we simply give back an empty array.
 716		if(is_null($findings)) {
 717			return array();
 718		}
 719
 720		if(!is_null($attr)) {
 721			$selection = array();
 722			$multiarray = false;
 723			if(count($attr) > 1) {
 724				$multiarray = true;
 725				$i = 0;
 726			}
 727			foreach($findings as $item) {
 728				if(!is_array($item)) {
 729					continue;
 730				}
 731				$item = \OCP\Util::mb_array_change_key_case($item, MB_CASE_LOWER, 'UTF-8');
 732
 733				if($multiarray) {
 734					foreach($attr as $key) {
 735						$key = mb_strtolower($key, 'UTF-8');
 736						if(isset($item[$key])) {
 737							if($key !== 'dn') {
 738								$selection[$i][$key] = $this->resemblesDN($key) ?
 739									$this->sanitizeDN($item[$key][0])
 740									: $item[$key][0];
 741							} else {
 742								$selection[$i][$key] = $this->sanitizeDN($item[$key]);
 743							}
 744						}
 745
 746					}
 747					$i++;
 748				} else {
 749					//tribute to case insensitivity
 750					$key = mb_strtolower($attr[0], 'UTF-8');
 751
 752					if(isset($item[$key])) {
 753						if($this->resemblesDN($key)) {
 754							$selection[] = $this->sanitizeDN($item[$key]);
 755						} else {
 756							$selection[] = $item[$key];
 757						}
 758					}
 759				}
 760			}
 761			$findings = $selection;
 762		}
 763		//we slice the findings, when
 764		//a) paged search insuccessful, though attempted
 765		//b) no paged search, but limit set
 766		if((!$this->pagedSearchedSuccessful
 767			&& $pagedSearchOK)
 768			|| (
 769				!$pagedSearchOK
 770				&& !is_null($limit)
 771			)
 772		) {
 773			$findings = array_slice($findings, intval($offset), $limit);
 774		}
 775		return $findings;
 776	}
 777
 778	public function sanitizeUsername($name) {
 779		if($this->connection->ldapIgnoreNamingRules) {
 780			return $name;
 781		}
 782
 783		// Translitaration
 784		//latin characters to ASCII
 785		$name = iconv('UTF-8', 'ASCII//TRANSLIT', $name);
 786
 787		//REPLACEMENTS
 788		$name = \OCP\Util::mb_str_replace(' ', '_', $name, 'UTF-8');
 789
 790		//every remaining unallowed characters will be removed
 791		$name = preg_replace('/[^a-zA-Z0-9_.@-]/u', '', $name);
 792
 793		return $name;
 794	}
 795
 796	/**
 797	 * @brief combines the input filters with AND
 798	 * @param $filters array, the filters to connect
 799	 * @returns the combined filter
 800	 *
 801	 * Combines Filter arguments with AND
 802	 */
 803	public function combineFilterWithAnd($filters) {
 804		return $this->combineFilter($filters, '&');
 805	}
 806
 807	/**
 808	 * @brief combines the input filters with AND
 809	 * @param $filters array, the filters to connect
 810	 * @returns the combined filter
 811	 *
 812	 * Combines Filter arguments with AND
 813	 */
 814	public function combineFilterWithOr($filters) {
 815		return $this->combineFilter($filters, '|');
 816	}
 817
 818	/**
 819	 * @brief combines the input filters with given operator
 820	 * @param $filters array, the filters to connect
 821	 * @param $operator either & or |
 822	 * @returns the combined filter
 823	 *
 824	 * Combines Filter arguments with AND
 825	 */
 826	private function combineFilter($filters, $operator) {
 827		$combinedFilter = '('.$operator;
 828		foreach($filters as $filter) {
 829		    if($filter[0] !== '(') {
 830				$filter = '('.$filter.')';
 831		    }
 832		    $combinedFilter.=$filter;
 833		}
 834		$combinedFilter.=')';
 835		return $combinedFilter;
 836	}
 837
 838	/**
 839	 * @brief creates a filter part for to perfrom search for users
 840	 * @param string $search the search term
 841	 * @return string the final filter part to use in LDAP searches
 842	 */
 843	public function getFilterPartForUserSearch($search) {
 844		return $this->getFilterPartForSearch($search,
 845			$this->connection->ldapAttributesForUserSearch,
 846			$this->connection->ldapUserDisplayName);
 847	}
 848
 849	/**
 850	 * @brief creates a filter part for to perfrom search for groups
 851	 * @param string $search the search term
 852	 * @return string the final filter part to use in LDAP searches
 853	 */
 854	public function getFilterPartForGroupSearch($search) {
 855		return $this->getFilterPartForSearch($search,
 856			$this->connection->ldapAttributesForGroupSearch,
 857			$this->connection->ldapGroupDisplayName);
 858	}
 859
 860	/**
 861	 * @brief creates a filter part for searches
 862	 * @param string $search the search term
 863	 * @param string $fallbackAttribute a fallback attribute in case the user
 864	 * did not define search attributes. Typically the display name attribute.
 865	 * @returns string the final filter part to use in LDAP searches
 866	 */
 867	private function getFilterPartForSearch($search, $searchAttributes, $fallbackAttribute) {
 868		$filter = array();
 869		$search = empty($search) ? '*' : '*'.$search.'*';
 870		if(!is_array($searchAttributes) || count($searchAttributes) === 0) {
 871			if(empty($fallbackAttribute)) {
 872				return '';
 873			}
 874			$filter[] = $fallbackAttribute . '=' . $search;
 875		} else {
 876			foreach($searchAttributes as $attribute) {
 877				$filter[] = $attribute . '=' . $search;
 878			}
 879		}
 880		if(count($filter) === 1) {
 881			return '('.$filter[0].')';
 882		}
 883		return $this->combineFilterWithOr($filter);
 884	}
 885
 886	public function areCredentialsValid($name, $password) {
 887		$name = $this->DNasBaseParameter($name);
 888		$testConnection = clone $this->connection;
 889		$credentials = array(
 890			'ldapAgentName' => $name,
 891			'ldapAgentPassword' => $password
 892		);
 893		if(!$testConnection->setConfiguration($credentials)) {
 894			return false;
 895		}
 896		return $testConnection->bind();
 897	}
 898
 899	/**
 900	 * @brief auto-detects the directory's UUID attribute
 901	 * @param $dn a known DN used to check against
 902	 * @param $force the detection should be run, even if it is not set to auto
 903	 * @returns true on success, false otherwise
 904	 */
 905	private function detectUuidAttribute($dn, $force = false) {
 906		if(($this->connection->ldapUuidAttribute !== 'auto') && !$force) {
 907			return true;
 908		}
 909
 910		$fixedAttribute = $this->connection->ldapExpertUUIDAttr;
 911		if(!empty($fixedAttribute)) {
 912			$this->connection->ldapUuidAttribute = $fixedAttribute;
 913			return true;
 914		}
 915
 916		//for now, supported (known) attributes are entryUUID, nsuniqueid, objectGUID
 917		$testAttributes = array('entryuuid', 'nsuniqueid', 'objectguid', 'guid');
 918
 919		foreach($testAttributes as $attribute) {
 920			\OCP\Util::writeLog('user_ldap', 'Testing '.$attribute.' as UUID attr', \OCP\Util::DEBUG);
 921
 922			$value = $this->readAttribute($dn, $attribute);
 923			if(is_array($value) && isset($value[0]) && !empty($value[0])) {
 924				\OCP\Util::writeLog('user_ldap', 'Setting '.$attribute.' as UUID attr', \OCP\Util::DEBUG);
 925				$this->connection->ldapUuidAttribute = $attribute;
 926				return true;
 927			}
 928			\OCP\Util::writeLog('user_ldap',
 929				'The looked for uuid attr is not '.$attribute.', result was '.print_r($value, true),
 930				\OCP\Util::DEBUG);
 931		}
 932
 933		return false;
 934	}
 935
 936	public function getUUID($dn) {
 937		if($this->detectUuidAttribute($dn)) {
 938			\OCP\Util::writeLog('user_ldap',
 939				'UUID Checking \ UUID for '.$dn.' using '. $this->connection->ldapUuidAttribute,
 940				\OCP\Util::DEBUG);
 941			$uuid = $this->readAttribute($dn, $this->connection->ldapUuidAttribute);
 942			if(!is_array($uuid) && $this->connection->ldapOverrideUuidAttribute) {
 943				$this->detectUuidAttribute($dn, true);
 944				$uuid = $this->readAttribute($dn, $this->connection->ldapUuidAttribute);
 945			}
 946			if(is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) {
 947				$uuid = $uuid[0];
 948			} else {
 949				$uuid = false;
 950			}
 951		} else {
 952			$uuid = false;
 953		}
 954		return $uuid;
 955	}
 956
 957	/**
 958	 * @brief converts a binary ObjectGUID into a string representation
 959	 * @param $oguid the ObjectGUID in it's binary form as retrieved from AD
 960	 * @returns String
 961	 *
 962	 * converts a binary ObjectGUID into a string representation
 963	 * http://www.php.net/manual/en/function.ldap-get-values-len.php#73198
 964	 */
 965	private function convertObjectGUID2Str($oguid) {
 966		$hex_guid = bin2hex($oguid);
 967		$hex_guid_to_guid_str = '';
 968		for($k = 1; $k <= 4; ++$k) {
 969			$hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2);
 970		}
 971		$hex_guid_to_guid_str .= '-';
 972		for($k = 1; $k <= 2; ++$k) {
 973			$hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2);
 974		}
 975		$hex_guid_to_guid_str .= '-';
 976		for($k = 1; $k <= 2; ++$k) {
 977			$hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2);
 978		}
 979		$hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4);
 980		$hex_guid_to_guid_str .= '-' . substr($hex_guid, 20);
 981
 982		return strtoupper($hex_guid_to_guid_str);
 983	}
 984
 985	/**
 986	 * @brief converts a stored DN so it can be used as base parameter for LDAP queries
 987	 * @param $dn the DN
 988	 * @returns String
 989	 *
 990	 * converts a stored DN so it can be used as base parameter for LDAP queries
 991	 * internally we store them for usage in LDAP filters
 992	 */
 993	private function DNasBaseParameter($dn) {
 994		return str_replace('\\5c', '\\', $dn);
 995	}
 996
 997	/**
 998	 * @brief checks if the given DN is part of the given base DN(s)
 999	 * @param $dn the DN
1000	 * @param $bases array containing the allowed base DN or DNs
1001	 * @returns Boolean
1002	 */
1003	private function isDNPartOfBase($dn, $bases) {
1004		$bases = $this->sanitizeDN($bases);
1005		foreach($bases as $base) {
1006			$belongsToBase = true;
1007			if(mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8')-mb_strlen($base))) {
1008				$belongsToBase = false;
1009			}
1010			if($belongsToBase) {
1011				break;
1012			}
1013		}
1014		return $belongsToBase;
1015	}
1016
1017	/**
1018	 * @brief get a cookie for the next LDAP paged search
1019	 * @param $base a string with the base DN for the search
1020	 * @param $filter the search filter to identify the correct search
1021	 * @param $limit the limit (or 'pageSize'), to identify the correct search well
1022	 * @param $offset the offset for the new search to identify the correct search really good
1023	 * @returns string containing the key or empty if none is cached
1024	 */
1025	private function getPagedResultCookie($base, $filter, $limit, $offset) {
1026		if($offset === 0) {
1027			return '';
1028		}
1029		$offset -= $limit;
1030		//we work with cache here
1031		$cachekey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . $limit . '-' . $offset;
1032		$cookie = $this->connection->getFromCache($cachekey);
1033		if(is_null($cookie)) {
1034			$cookie = '';
1035		}
1036		return $cookie;
1037	}
1038
1039	/**
1040	 * @brief set a cookie for LDAP paged search run
1041	 * @param $base a string with the base DN for the search
1042	 * @param $filter the search filter to identify the correct search
1043	 * @param $limit the limit (or 'pageSize'), to identify the correct search well
1044	 * @param $offset the offset for the run search to identify the correct search really good
1045	 * @param $cookie string containing the cookie returned by ldap_control_paged_result_response
1046	 * @return void
1047	 */
1048	private function setPagedResultCookie($base, $filter, $limit, $offset, $cookie) {
1049		if(!empty($cookie)) {
1050			$cachekey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' .$limit . '-' . $offset;
1051			$cookie = $this->connection->writeToCache($cachekey, $cookie);
1052		}
1053	}
1054
1055	/**
1056	 * @brief check wether the most recent paged search was successful. It flushed the state var. Use it always after a possible paged search.
1057	 * @return true on success, null or false otherwise
1058	 */
1059	public function getPagedSearchResultState() {
1060		$result = $this->pagedSearchedSuccessful;
1061		$this->pagedSearchedSuccessful = null;
1062		return $result;
1063	}
1064
1065
1066	/**
1067	 * @brief prepares a paged search, if possible
1068	 * @param $filter the LDAP filter for the search
1069	 * @param $bases an array containing the LDAP subtree(s) that shall be searched
1070	 * @param $attr optional, when a certain attribute shall be filtered outside
1071	 * @param $limit
1072	 * @param $offset
1073	 *
1074	 */
1075	private function initPagedSearch($filter, $bases, $attr, $limit, $offset) {
1076		$pagedSearchOK = false;
1077		if($this->connection->hasPagedResultSupport && !is_null($limit)) {
1078			$offset = intval($offset); //can be null
1079			\OCP\Util::writeLog('user_ldap',
1080				'initializing paged search for  Filter'.$filter.' base '.print_r($bases, true)
1081				.' attr '.print_r($attr, true). ' limit ' .$limit.' offset '.$offset,
1082				\OCP\Util::INFO);
1083			//get the cookie from the search for the previous search, required by LDAP
1084			foreach($bases as $base) {
1085
1086				$cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
1087				if(empty($cookie) && ($offset > 0)) {
1088					// no cookie known, although the offset is not 0. Maybe cache run out. We need
1089					// to start all over *sigh* (btw, Dear Reader, did you need LDAP paged
1090					// searching was designed by MSFT?)
1091					$reOffset = ($offset - $limit) < 0 ? 0 : $offset - $limit;
1092					//a bit recursive, $offset of 0 is the exit
1093					\OCP\Util::writeLog('user_ldap', 'Looking for cookie L/O '.$limit.'/'.$reOffset, \OCP\Util::INFO);
1094					$this->search($filter, array($base), $attr, $limit, $reOffset, true);
1095					$cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
1096					//still no cookie? obviously, the server does not like us. Let's skip paging efforts.
1097					//TODO: remember this, probably does not change in the next request...
1098					if(empty($cookie)) {
1099						$cookie = null;
1100					}
1101				}
1102				if(!is_null($cookie)) {
1103					if($offset > 0) {
1104						\OCP\Util::writeLog('user_ldap', 'Cookie '.$cookie, \OCP\Util::INFO);
1105					}
1106					$pagedSearchOK = ldap_control_paged_result($this->connection->getConnectionResource(),
1107						$limit, false, $cookie);
1108					if(!$pagedSearchOK) {
1109						return false;
1110					}
1111					\OCP\Util::writeLog('user_ldap', 'Ready for a paged search', \OCP\Util::INFO);
1112				} else {
1113					\OCP\Util::writeLog('user_ldap',
1114						'No paged search for us, Cpt., Limit '.$limit.' Offset '.$offset,
1115						\OCP\Util::INFO);
1116				}
1117
1118			}
1119		}
1120
1121		return $pagedSearchOK;
1122	}
1123
1124}