Passed
Push — master ( fda71a...69e2aa )
by Roeland
13:54 queued 13s
created
apps/user_ldap/lib/Access.php 1 patch
Indentation   +2004 added lines, -2004 removed lines patch added patch discarded remove patch
@@ -63,1790 +63,1790 @@  discard block
 block discarded – undo
63 63
  * @package OCA\User_LDAP
64 64
  */
65 65
 class Access extends LDAPUtility {
66
-	public const UUID_ATTRIBUTES = ['entryuuid', 'nsuniqueid', 'objectguid', 'guid', 'ipauniqueid'];
67
-
68
-	/** @var \OCA\User_LDAP\Connection */
69
-	public $connection;
70
-	/** @var Manager */
71
-	public $userManager;
72
-	//never ever check this var directly, always use getPagedSearchResultState
73
-	protected $pagedSearchedSuccessful;
74
-
75
-	/**
76
-	 * protected $cookies = [];
77
-	 *
78
-	 * @var AbstractMapping $userMapper
79
-	 */
80
-	protected $userMapper;
81
-
82
-	/**
83
-	 * @var AbstractMapping $userMapper
84
-	 */
85
-	protected $groupMapper;
86
-
87
-	/**
88
-	 * @var \OCA\User_LDAP\Helper
89
-	 */
90
-	private $helper;
91
-	/** @var IConfig */
92
-	private $config;
93
-	/** @var IUserManager */
94
-	private $ncUserManager;
95
-	/** @var string */
96
-	private $lastCookie = '';
97
-
98
-	public function __construct(
99
-		Connection $connection,
100
-		ILDAPWrapper $ldap,
101
-		Manager $userManager,
102
-		Helper $helper,
103
-		IConfig $config,
104
-		IUserManager $ncUserManager
105
-	) {
106
-		parent::__construct($ldap);
107
-		$this->connection = $connection;
108
-		$this->userManager = $userManager;
109
-		$this->userManager->setLdapAccess($this);
110
-		$this->helper = $helper;
111
-		$this->config = $config;
112
-		$this->ncUserManager = $ncUserManager;
113
-	}
114
-
115
-	/**
116
-	 * sets the User Mapper
117
-	 *
118
-	 * @param AbstractMapping $mapper
119
-	 */
120
-	public function setUserMapper(AbstractMapping $mapper) {
121
-		$this->userMapper = $mapper;
122
-	}
123
-
124
-	/**
125
-	 * returns the User Mapper
126
-	 *
127
-	 * @return AbstractMapping
128
-	 * @throws \Exception
129
-	 */
130
-	public function getUserMapper() {
131
-		if (is_null($this->userMapper)) {
132
-			throw new \Exception('UserMapper was not assigned to this Access instance.');
133
-		}
134
-		return $this->userMapper;
135
-	}
136
-
137
-	/**
138
-	 * sets the Group Mapper
139
-	 *
140
-	 * @param AbstractMapping $mapper
141
-	 */
142
-	public function setGroupMapper(AbstractMapping $mapper) {
143
-		$this->groupMapper = $mapper;
144
-	}
145
-
146
-	/**
147
-	 * returns the Group Mapper
148
-	 *
149
-	 * @return AbstractMapping
150
-	 * @throws \Exception
151
-	 */
152
-	public function getGroupMapper() {
153
-		if (is_null($this->groupMapper)) {
154
-			throw new \Exception('GroupMapper was not assigned to this Access instance.');
155
-		}
156
-		return $this->groupMapper;
157
-	}
158
-
159
-	/**
160
-	 * @return bool
161
-	 */
162
-	private function checkConnection() {
163
-		return ($this->connection instanceof Connection);
164
-	}
165
-
166
-	/**
167
-	 * returns the Connection instance
168
-	 *
169
-	 * @return \OCA\User_LDAP\Connection
170
-	 */
171
-	public function getConnection() {
172
-		return $this->connection;
173
-	}
174
-
175
-	/**
176
-	 * reads a given attribute for an LDAP record identified by a DN
177
-	 *
178
-	 * @param string $dn the record in question
179
-	 * @param string $attr the attribute that shall be retrieved
180
-	 *        if empty, just check the record's existence
181
-	 * @param string $filter
182
-	 * @return array|false an array of values on success or an empty
183
-	 *          array if $attr is empty, false otherwise
184
-	 * @throws ServerNotAvailableException
185
-	 */
186
-	public function readAttribute($dn, $attr, $filter = 'objectClass=*') {
187
-		if (!$this->checkConnection()) {
188
-			\OCP\Util::writeLog('user_ldap',
189
-				'No LDAP Connector assigned, access impossible for readAttribute.',
190
-				ILogger::WARN);
191
-			return false;
192
-		}
193
-		$cr = $this->connection->getConnectionResource();
194
-		if (!$this->ldap->isResource($cr)) {
195
-			//LDAP not available
196
-			\OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', ILogger::DEBUG);
197
-			return false;
198
-		}
199
-		//Cancel possibly running Paged Results operation, otherwise we run in
200
-		//LDAP protocol errors
201
-		$this->abandonPagedSearch();
202
-		// openLDAP requires that we init a new Paged Search. Not needed by AD,
203
-		// but does not hurt either.
204
-		$pagingSize = (int)$this->connection->ldapPagingSize;
205
-		// 0 won't result in replies, small numbers may leave out groups
206
-		// (cf. #12306), 500 is default for paging and should work everywhere.
207
-		$maxResults = $pagingSize > 20 ? $pagingSize : 500;
208
-		$attr = mb_strtolower($attr, 'UTF-8');
209
-		// the actual read attribute later may contain parameters on a ranged
210
-		// request, e.g. member;range=99-199. Depends on server reply.
211
-		$attrToRead = $attr;
212
-
213
-		$values = [];
214
-		$isRangeRequest = false;
215
-		do {
216
-			$result = $this->executeRead($cr, $dn, $attrToRead, $filter, $maxResults);
217
-			if (is_bool($result)) {
218
-				// when an exists request was run and it was successful, an empty
219
-				// array must be returned
220
-				return $result ? [] : false;
221
-			}
222
-
223
-			if (!$isRangeRequest) {
224
-				$values = $this->extractAttributeValuesFromResult($result, $attr);
225
-				if (!empty($values)) {
226
-					return $values;
227
-				}
228
-			}
229
-
230
-			$isRangeRequest = false;
231
-			$result = $this->extractRangeData($result, $attr);
232
-			if (!empty($result)) {
233
-				$normalizedResult = $this->extractAttributeValuesFromResult(
234
-					[$attr => $result['values']],
235
-					$attr
236
-				);
237
-				$values = array_merge($values, $normalizedResult);
238
-
239
-				if ($result['rangeHigh'] === '*') {
240
-					// when server replies with * as high range value, there are
241
-					// no more results left
242
-					return $values;
243
-				} else {
244
-					$low = $result['rangeHigh'] + 1;
245
-					$attrToRead = $result['attributeName'] . ';range=' . $low . '-*';
246
-					$isRangeRequest = true;
247
-				}
248
-			}
249
-		} while ($isRangeRequest);
250
-
251
-		\OCP\Util::writeLog('user_ldap', 'Requested attribute ' . $attr . ' not found for ' . $dn, ILogger::DEBUG);
252
-		return false;
253
-	}
254
-
255
-	/**
256
-	 * Runs an read operation against LDAP
257
-	 *
258
-	 * @param resource $cr the LDAP connection
259
-	 * @param string $dn
260
-	 * @param string $attribute
261
-	 * @param string $filter
262
-	 * @param int $maxResults
263
-	 * @return array|bool false if there was any error, true if an exists check
264
-	 *                    was performed and the requested DN found, array with the
265
-	 *                    returned data on a successful usual operation
266
-	 * @throws ServerNotAvailableException
267
-	 */
268
-	public function executeRead($cr, $dn, $attribute, $filter, $maxResults) {
269
-		$this->initPagedSearch($filter, $dn, [$attribute], $maxResults, 0);
270
-		$dn = $this->helper->DNasBaseParameter($dn);
271
-		$rr = @$this->invokeLDAPMethod('read', $cr, $dn, $filter, [$attribute]);
272
-		if (!$this->ldap->isResource($rr)) {
273
-			if ($attribute !== '') {
274
-				//do not throw this message on userExists check, irritates
275
-				\OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN ' . $dn, ILogger::DEBUG);
276
-			}
277
-			//in case an error occurs , e.g. object does not exist
278
-			return false;
279
-		}
280
-		if ($attribute === '' && ($filter === 'objectclass=*' || $this->invokeLDAPMethod('countEntries', $cr, $rr) === 1)) {
281
-			\OCP\Util::writeLog('user_ldap', 'readAttribute: ' . $dn . ' found', ILogger::DEBUG);
282
-			return true;
283
-		}
284
-		$er = $this->invokeLDAPMethod('firstEntry', $cr, $rr);
285
-		if (!$this->ldap->isResource($er)) {
286
-			//did not match the filter, return false
287
-			return false;
288
-		}
289
-		//LDAP attributes are not case sensitive
290
-		$result = \OCP\Util::mb_array_change_key_case(
291
-			$this->invokeLDAPMethod('getAttributes', $cr, $er), MB_CASE_LOWER, 'UTF-8');
292
-
293
-		return $result;
294
-	}
295
-
296
-	/**
297
-	 * Normalizes a result grom getAttributes(), i.e. handles DNs and binary
298
-	 * data if present.
299
-	 *
300
-	 * @param array $result from ILDAPWrapper::getAttributes()
301
-	 * @param string $attribute the attribute name that was read
302
-	 * @return string[]
303
-	 */
304
-	public function extractAttributeValuesFromResult($result, $attribute) {
305
-		$values = [];
306
-		if (isset($result[$attribute]) && $result[$attribute]['count'] > 0) {
307
-			$lowercaseAttribute = strtolower($attribute);
308
-			for ($i = 0; $i < $result[$attribute]['count']; $i++) {
309
-				if ($this->resemblesDN($attribute)) {
310
-					$values[] = $this->helper->sanitizeDN($result[$attribute][$i]);
311
-				} elseif ($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') {
312
-					$values[] = $this->convertObjectGUID2Str($result[$attribute][$i]);
313
-				} else {
314
-					$values[] = $result[$attribute][$i];
315
-				}
316
-			}
317
-		}
318
-		return $values;
319
-	}
320
-
321
-	/**
322
-	 * Attempts to find ranged data in a getAttribute results and extracts the
323
-	 * returned values as well as information on the range and full attribute
324
-	 * name for further processing.
325
-	 *
326
-	 * @param array $result from ILDAPWrapper::getAttributes()
327
-	 * @param string $attribute the attribute name that was read. Without ";range=…"
328
-	 * @return array If a range was detected with keys 'values', 'attributeName',
329
-	 *               'attributeFull' and 'rangeHigh', otherwise empty.
330
-	 */
331
-	public function extractRangeData($result, $attribute) {
332
-		$keys = array_keys($result);
333
-		foreach ($keys as $key) {
334
-			if ($key !== $attribute && strpos($key, $attribute) === 0) {
335
-				$queryData = explode(';', $key);
336
-				if (strpos($queryData[1], 'range=') === 0) {
337
-					$high = substr($queryData[1], 1 + strpos($queryData[1], '-'));
338
-					$data = [
339
-						'values' => $result[$key],
340
-						'attributeName' => $queryData[0],
341
-						'attributeFull' => $key,
342
-						'rangeHigh' => $high,
343
-					];
344
-					return $data;
345
-				}
346
-			}
347
-		}
348
-		return [];
349
-	}
350
-
351
-	/**
352
-	 * Set password for an LDAP user identified by a DN
353
-	 *
354
-	 * @param string $userDN the user in question
355
-	 * @param string $password the new password
356
-	 * @return bool
357
-	 * @throws HintException
358
-	 * @throws \Exception
359
-	 */
360
-	public function setPassword($userDN, $password) {
361
-		if ((int)$this->connection->turnOnPasswordChange !== 1) {
362
-			throw new \Exception('LDAP password changes are disabled.');
363
-		}
364
-		$cr = $this->connection->getConnectionResource();
365
-		if (!$this->ldap->isResource($cr)) {
366
-			//LDAP not available
367
-			\OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', ILogger::DEBUG);
368
-			return false;
369
-		}
370
-		try {
371
-			// try PASSWD extended operation first
372
-			return @$this->invokeLDAPMethod('exopPasswd', $cr, $userDN, '', $password) ||
373
-				@$this->invokeLDAPMethod('modReplace', $cr, $userDN, $password);
374
-		} catch (ConstraintViolationException $e) {
375
-			throw new HintException('Password change rejected.', \OC::$server->getL10N('user_ldap')->t('Password change rejected. Hint: ') . $e->getMessage(), $e->getCode());
376
-		}
377
-	}
378
-
379
-	/**
380
-	 * checks whether the given attributes value is probably a DN
381
-	 *
382
-	 * @param string $attr the attribute in question
383
-	 * @return boolean if so true, otherwise false
384
-	 */
385
-	private function resemblesDN($attr) {
386
-		$resemblingAttributes = [
387
-			'dn',
388
-			'uniquemember',
389
-			'member',
390
-			// memberOf is an "operational" attribute, without a definition in any RFC
391
-			'memberof'
392
-		];
393
-		return in_array($attr, $resemblingAttributes);
394
-	}
395
-
396
-	/**
397
-	 * checks whether the given string is probably a DN
398
-	 *
399
-	 * @param string $string
400
-	 * @return boolean
401
-	 */
402
-	public function stringResemblesDN($string) {
403
-		$r = $this->ldap->explodeDN($string, 0);
404
-		// if exploding a DN succeeds and does not end up in
405
-		// an empty array except for $r[count] being 0.
406
-		return (is_array($r) && count($r) > 1);
407
-	}
408
-
409
-	/**
410
-	 * returns a DN-string that is cleaned from not domain parts, e.g.
411
-	 * cn=foo,cn=bar,dc=foobar,dc=server,dc=org
412
-	 * becomes dc=foobar,dc=server,dc=org
413
-	 *
414
-	 * @param string $dn
415
-	 * @return string
416
-	 */
417
-	public function getDomainDNFromDN($dn) {
418
-		$allParts = $this->ldap->explodeDN($dn, 0);
419
-		if ($allParts === false) {
420
-			//not a valid DN
421
-			return '';
422
-		}
423
-		$domainParts = [];
424
-		$dcFound = false;
425
-		foreach ($allParts as $part) {
426
-			if (!$dcFound && strpos($part, 'dc=') === 0) {
427
-				$dcFound = true;
428
-			}
429
-			if ($dcFound) {
430
-				$domainParts[] = $part;
431
-			}
432
-		}
433
-		return implode(',', $domainParts);
434
-	}
435
-
436
-	/**
437
-	 * returns the LDAP DN for the given internal Nextcloud name of the group
438
-	 *
439
-	 * @param string $name the Nextcloud name in question
440
-	 * @return string|false LDAP DN on success, otherwise false
441
-	 */
442
-	public function groupname2dn($name) {
443
-		return $this->groupMapper->getDNByName($name);
444
-	}
445
-
446
-	/**
447
-	 * returns the LDAP DN for the given internal Nextcloud name of the user
448
-	 *
449
-	 * @param string $name the Nextcloud name in question
450
-	 * @return string|false with the LDAP DN on success, otherwise false
451
-	 */
452
-	public function username2dn($name) {
453
-		$fdn = $this->userMapper->getDNByName($name);
454
-
455
-		//Check whether the DN belongs to the Base, to avoid issues on multi-
456
-		//server setups
457
-		if (is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
458
-			return $fdn;
459
-		}
460
-
461
-		return false;
462
-	}
463
-
464
-	/**
465
-	 * returns the internal Nextcloud name for the given LDAP DN of the group, false on DN outside of search DN or failure
466
-	 *
467
-	 * @param string $fdn the dn of the group object
468
-	 * @param string $ldapName optional, the display name of the object
469
-	 * @return string|false with the name to use in Nextcloud, false on DN outside of search DN
470
-	 * @throws \Exception
471
-	 */
472
-	public function dn2groupname($fdn, $ldapName = null) {
473
-		//To avoid bypassing the base DN settings under certain circumstances
474
-		//with the group support, check whether the provided DN matches one of
475
-		//the given Bases
476
-		if (!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) {
477
-			return false;
478
-		}
479
-
480
-		return $this->dn2ocname($fdn, $ldapName, false);
481
-	}
482
-
483
-	/**
484
-	 * returns the internal Nextcloud name for the given LDAP DN of the user, false on DN outside of search DN or failure
485
-	 *
486
-	 * @param string $dn the dn of the user object
487
-	 * @param string $ldapName optional, the display name of the object
488
-	 * @return string|false with with the name to use in Nextcloud
489
-	 * @throws \Exception
490
-	 */
491
-	public function dn2username($fdn, $ldapName = null) {
492
-		//To avoid bypassing the base DN settings under certain circumstances
493
-		//with the group support, check whether the provided DN matches one of
494
-		//the given Bases
495
-		if (!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
496
-			return false;
497
-		}
498
-
499
-		return $this->dn2ocname($fdn, $ldapName, true);
500
-	}
501
-
502
-	/**
503
-	 * returns an internal Nextcloud name for the given LDAP DN, false on DN outside of search DN
504
-	 *
505
-	 * @param string $fdn the dn of the user object
506
-	 * @param string|null $ldapName optional, the display name of the object
507
-	 * @param bool $isUser optional, whether it is a user object (otherwise group assumed)
508
-	 * @param bool|null $newlyMapped
509
-	 * @param array|null $record
510
-	 * @return false|string with with the name to use in Nextcloud
511
-	 * @throws \Exception
512
-	 */
513
-	public function dn2ocname($fdn, $ldapName = null, $isUser = true, &$newlyMapped = null, array $record = null) {
514
-		$newlyMapped = false;
515
-		if ($isUser) {
516
-			$mapper = $this->getUserMapper();
517
-			$nameAttribute = $this->connection->ldapUserDisplayName;
518
-			$filter = $this->connection->ldapUserFilter;
519
-		} else {
520
-			$mapper = $this->getGroupMapper();
521
-			$nameAttribute = $this->connection->ldapGroupDisplayName;
522
-			$filter = $this->connection->ldapGroupFilter;
523
-		}
524
-
525
-		//let's try to retrieve the Nextcloud name from the mappings table
526
-		$ncName = $mapper->getNameByDN($fdn);
527
-		if (is_string($ncName)) {
528
-			return $ncName;
529
-		}
530
-
531
-		//second try: get the UUID and check if it is known. Then, update the DN and return the name.
532
-		$uuid = $this->getUUID($fdn, $isUser, $record);
533
-		if (is_string($uuid)) {
534
-			$ncName = $mapper->getNameByUUID($uuid);
535
-			if (is_string($ncName)) {
536
-				$mapper->setDNbyUUID($fdn, $uuid);
537
-				return $ncName;
538
-			}
539
-		} else {
540
-			//If the UUID can't be detected something is foul.
541
-			\OCP\Util::writeLog('user_ldap', 'Cannot determine UUID for ' . $fdn . '. Skipping.', ILogger::INFO);
542
-			return false;
543
-		}
544
-
545
-		if (is_null($ldapName)) {
546
-			$ldapName = $this->readAttribute($fdn, $nameAttribute, $filter);
547
-			if (!isset($ldapName[0]) && empty($ldapName[0])) {
548
-				\OCP\Util::writeLog('user_ldap', 'No or empty name for ' . $fdn . ' with filter ' . $filter . '.', ILogger::INFO);
549
-				return false;
550
-			}
551
-			$ldapName = $ldapName[0];
552
-		}
553
-
554
-		if ($isUser) {
555
-			$usernameAttribute = (string)$this->connection->ldapExpertUsernameAttr;
556
-			if ($usernameAttribute !== '') {
557
-				$username = $this->readAttribute($fdn, $usernameAttribute);
558
-				$username = $username[0];
559
-			} else {
560
-				$username = $uuid;
561
-			}
562
-			try {
563
-				$intName = $this->sanitizeUsername($username);
564
-			} catch (\InvalidArgumentException $e) {
565
-				\OC::$server->getLogger()->logException($e, [
566
-					'app' => 'user_ldap',
567
-					'level' => ILogger::WARN,
568
-				]);
569
-				// we don't attempt to set a username here. We can go for
570
-				// for an alternative 4 digit random number as we would append
571
-				// otherwise, however it's likely not enough space in bigger
572
-				// setups, and most importantly: this is not intended.
573
-				return false;
574
-			}
575
-		} else {
576
-			$intName = $ldapName;
577
-		}
578
-
579
-		//a new user/group! Add it only if it doesn't conflict with other backend's users or existing groups
580
-		//disabling Cache is required to avoid that the new user is cached as not-existing in fooExists check
581
-		//NOTE: mind, disabling cache affects only this instance! Using it
582
-		// outside of core user management will still cache the user as non-existing.
583
-		$originalTTL = $this->connection->ldapCacheTTL;
584
-		$this->connection->setConfiguration(['ldapCacheTTL' => 0]);
585
-		if ($intName !== ''
586
-			&& (($isUser && !$this->ncUserManager->userExists($intName))
587
-				|| (!$isUser && !\OC::$server->getGroupManager()->groupExists($intName))
588
-			)
589
-		) {
590
-			$this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]);
591
-			$newlyMapped = $this->mapAndAnnounceIfApplicable($mapper, $fdn, $intName, $uuid, $isUser);
592
-			if ($newlyMapped) {
593
-				return $intName;
594
-			}
595
-		}
596
-
597
-		$this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]);
598
-		$altName = $this->createAltInternalOwnCloudName($intName, $isUser);
599
-		if (is_string($altName)) {
600
-			if ($this->mapAndAnnounceIfApplicable($mapper, $fdn, $altName, $uuid, $isUser)) {
601
-				$newlyMapped = true;
602
-				return $altName;
603
-			}
604
-		}
605
-
606
-		//if everything else did not help..
607
-		\OCP\Util::writeLog('user_ldap', 'Could not create unique name for ' . $fdn . '.', ILogger::INFO);
608
-		return false;
609
-	}
610
-
611
-	public function mapAndAnnounceIfApplicable(
612
-		AbstractMapping $mapper,
613
-		string $fdn,
614
-		string $name,
615
-		string $uuid,
616
-		bool $isUser
617
-	): bool {
618
-		if ($mapper->map($fdn, $name, $uuid)) {
619
-			if ($this->ncUserManager instanceof PublicEmitter && $isUser) {
620
-				$this->cacheUserExists($name);
621
-				$this->ncUserManager->emit('\OC\User', 'assignedUserId', [$name]);
622
-			} elseif (!$isUser) {
623
-				$this->cacheGroupExists($name);
624
-			}
625
-			return true;
626
-		}
627
-		return false;
628
-	}
629
-
630
-	/**
631
-	 * gives back the user names as they are used ownClod internally
632
-	 *
633
-	 * @param array $ldapUsers as returned by fetchList()
634
-	 * @return array an array with the user names to use in Nextcloud
635
-	 *
636
-	 * gives back the user names as they are used ownClod internally
637
-	 * @throws \Exception
638
-	 */
639
-	public function nextcloudUserNames($ldapUsers) {
640
-		return $this->ldap2NextcloudNames($ldapUsers, true);
641
-	}
642
-
643
-	/**
644
-	 * gives back the group names as they are used ownClod internally
645
-	 *
646
-	 * @param array $ldapGroups as returned by fetchList()
647
-	 * @return array an array with the group names to use in Nextcloud
648
-	 *
649
-	 * gives back the group names as they are used ownClod internally
650
-	 * @throws \Exception
651
-	 */
652
-	public function nextcloudGroupNames($ldapGroups) {
653
-		return $this->ldap2NextcloudNames($ldapGroups, false);
654
-	}
655
-
656
-	/**
657
-	 * @param array $ldapObjects as returned by fetchList()
658
-	 * @param bool $isUsers
659
-	 * @return array
660
-	 * @throws \Exception
661
-	 */
662
-	private function ldap2NextcloudNames($ldapObjects, $isUsers) {
663
-		if ($isUsers) {
664
-			$nameAttribute = $this->connection->ldapUserDisplayName;
665
-			$sndAttribute = $this->connection->ldapUserDisplayName2;
666
-		} else {
667
-			$nameAttribute = $this->connection->ldapGroupDisplayName;
668
-		}
669
-		$nextcloudNames = [];
670
-
671
-		foreach ($ldapObjects as $ldapObject) {
672
-			$nameByLDAP = null;
673
-			if (isset($ldapObject[$nameAttribute])
674
-				&& is_array($ldapObject[$nameAttribute])
675
-				&& isset($ldapObject[$nameAttribute][0])
676
-			) {
677
-				// might be set, but not necessarily. if so, we use it.
678
-				$nameByLDAP = $ldapObject[$nameAttribute][0];
679
-			}
680
-
681
-			$ncName = $this->dn2ocname($ldapObject['dn'][0], $nameByLDAP, $isUsers);
682
-			if ($ncName) {
683
-				$nextcloudNames[] = $ncName;
684
-				if ($isUsers) {
685
-					$this->updateUserState($ncName);
686
-					//cache the user names so it does not need to be retrieved
687
-					//again later (e.g. sharing dialogue).
688
-					if (is_null($nameByLDAP)) {
689
-						continue;
690
-					}
691
-					$sndName = isset($ldapObject[$sndAttribute][0])
692
-						? $ldapObject[$sndAttribute][0] : '';
693
-					$this->cacheUserDisplayName($ncName, $nameByLDAP, $sndName);
694
-				} elseif ($nameByLDAP !== null) {
695
-					$this->cacheGroupDisplayName($ncName, $nameByLDAP);
696
-				}
697
-			}
698
-		}
699
-		return $nextcloudNames;
700
-	}
701
-
702
-	/**
703
-	 * removes the deleted-flag of a user if it was set
704
-	 *
705
-	 * @param string $ncname
706
-	 * @throws \Exception
707
-	 */
708
-	public function updateUserState($ncname) {
709
-		$user = $this->userManager->get($ncname);
710
-		if ($user instanceof OfflineUser) {
711
-			$user->unmark();
712
-		}
713
-	}
714
-
715
-	/**
716
-	 * caches the user display name
717
-	 *
718
-	 * @param string $ocName the internal Nextcloud username
719
-	 * @param string|false $home the home directory path
720
-	 */
721
-	public function cacheUserHome($ocName, $home) {
722
-		$cacheKey = 'getHome' . $ocName;
723
-		$this->connection->writeToCache($cacheKey, $home);
724
-	}
725
-
726
-	/**
727
-	 * caches a user as existing
728
-	 *
729
-	 * @param string $ocName the internal Nextcloud username
730
-	 */
731
-	public function cacheUserExists($ocName) {
732
-		$this->connection->writeToCache('userExists' . $ocName, true);
733
-	}
734
-
735
-	/**
736
-	 * caches a group as existing
737
-	 */
738
-	public function cacheGroupExists(string $gid): void {
739
-		$this->connection->writeToCache('groupExists' . $gid, true);
740
-	}
741
-
742
-	/**
743
-	 * caches the user display name
744
-	 *
745
-	 * @param string $ocName the internal Nextcloud username
746
-	 * @param string $displayName the display name
747
-	 * @param string $displayName2 the second display name
748
-	 * @throws \Exception
749
-	 */
750
-	public function cacheUserDisplayName($ocName, $displayName, $displayName2 = '') {
751
-		$user = $this->userManager->get($ocName);
752
-		if ($user === null) {
753
-			return;
754
-		}
755
-		$displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
756
-		$cacheKeyTrunk = 'getDisplayName';
757
-		$this->connection->writeToCache($cacheKeyTrunk . $ocName, $displayName);
758
-	}
759
-
760
-	public function cacheGroupDisplayName(string $ncName, string $displayName): void {
761
-		$cacheKey = 'group_getDisplayName' . $ncName;
762
-		$this->connection->writeToCache($cacheKey, $displayName);
763
-	}
764
-
765
-	/**
766
-	 * creates a unique name for internal Nextcloud use for users. Don't call it directly.
767
-	 *
768
-	 * @param string $name the display name of the object
769
-	 * @return string|false with with the name to use in Nextcloud or false if unsuccessful
770
-	 *
771
-	 * Instead of using this method directly, call
772
-	 * createAltInternalOwnCloudName($name, true)
773
-	 */
774
-	private function _createAltInternalOwnCloudNameForUsers($name) {
775
-		$attempts = 0;
776
-		//while loop is just a precaution. If a name is not generated within
777
-		//20 attempts, something else is very wrong. Avoids infinite loop.
778
-		while ($attempts < 20) {
779
-			$altName = $name . '_' . rand(1000, 9999);
780
-			if (!$this->ncUserManager->userExists($altName)) {
781
-				return $altName;
782
-			}
783
-			$attempts++;
784
-		}
785
-		return false;
786
-	}
787
-
788
-	/**
789
-	 * creates a unique name for internal Nextcloud use for groups. Don't call it directly.
790
-	 *
791
-	 * @param string $name the display name of the object
792
-	 * @return string|false with with the name to use in Nextcloud or false if unsuccessful.
793
-	 *
794
-	 * Instead of using this method directly, call
795
-	 * createAltInternalOwnCloudName($name, false)
796
-	 *
797
-	 * Group names are also used as display names, so we do a sequential
798
-	 * numbering, e.g. Developers_42 when there are 41 other groups called
799
-	 * "Developers"
800
-	 */
801
-	private function _createAltInternalOwnCloudNameForGroups($name) {
802
-		$usedNames = $this->groupMapper->getNamesBySearch($name, "", '_%');
803
-		if (!$usedNames || count($usedNames) === 0) {
804
-			$lastNo = 1; //will become name_2
805
-		} else {
806
-			natsort($usedNames);
807
-			$lastName = array_pop($usedNames);
808
-			$lastNo = (int)substr($lastName, strrpos($lastName, '_') + 1);
809
-		}
810
-		$altName = $name . '_' . (string)($lastNo + 1);
811
-		unset($usedNames);
812
-
813
-		$attempts = 1;
814
-		while ($attempts < 21) {
815
-			// Check to be really sure it is unique
816
-			// while loop is just a precaution. If a name is not generated within
817
-			// 20 attempts, something else is very wrong. Avoids infinite loop.
818
-			if (!\OC::$server->getGroupManager()->groupExists($altName)) {
819
-				return $altName;
820
-			}
821
-			$altName = $name . '_' . ($lastNo + $attempts);
822
-			$attempts++;
823
-		}
824
-		return false;
825
-	}
826
-
827
-	/**
828
-	 * creates a unique name for internal Nextcloud use.
829
-	 *
830
-	 * @param string $name the display name of the object
831
-	 * @param boolean $isUser whether name should be created for a user (true) or a group (false)
832
-	 * @return string|false with with the name to use in Nextcloud or false if unsuccessful
833
-	 */
834
-	private function createAltInternalOwnCloudName($name, $isUser) {
835
-		$originalTTL = $this->connection->ldapCacheTTL;
836
-		$this->connection->setConfiguration(['ldapCacheTTL' => 0]);
837
-		if ($isUser) {
838
-			$altName = $this->_createAltInternalOwnCloudNameForUsers($name);
839
-		} else {
840
-			$altName = $this->_createAltInternalOwnCloudNameForGroups($name);
841
-		}
842
-		$this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]);
843
-
844
-		return $altName;
845
-	}
846
-
847
-	/**
848
-	 * fetches a list of users according to a provided loginName and utilizing
849
-	 * the login filter.
850
-	 *
851
-	 * @param string $loginName
852
-	 * @param array $attributes optional, list of attributes to read
853
-	 * @return array
854
-	 */
855
-	public function fetchUsersByLoginName($loginName, $attributes = ['dn']) {
856
-		$loginName = $this->escapeFilterPart($loginName);
857
-		$filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
858
-		return $this->fetchListOfUsers($filter, $attributes);
859
-	}
860
-
861
-	/**
862
-	 * counts the number of users according to a provided loginName and
863
-	 * utilizing the login filter.
864
-	 *
865
-	 * @param string $loginName
866
-	 * @return int
867
-	 */
868
-	public function countUsersByLoginName($loginName) {
869
-		$loginName = $this->escapeFilterPart($loginName);
870
-		$filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
871
-		return $this->countUsers($filter);
872
-	}
873
-
874
-	/**
875
-	 * @param string $filter
876
-	 * @param string|string[] $attr
877
-	 * @param int $limit
878
-	 * @param int $offset
879
-	 * @param bool $forceApplyAttributes
880
-	 * @return array
881
-	 * @throws \Exception
882
-	 */
883
-	public function fetchListOfUsers($filter, $attr, $limit = null, $offset = null, $forceApplyAttributes = false) {
884
-		$ldapRecords = $this->searchUsers($filter, $attr, $limit, $offset);
885
-		$recordsToUpdate = $ldapRecords;
886
-		if (!$forceApplyAttributes) {
887
-			$isBackgroundJobModeAjax = $this->config
888
-					->getAppValue('core', 'backgroundjobs_mode', 'ajax') === 'ajax';
889
-			$listOfDNs = array_reduce($ldapRecords, function ($listOfDNs, $entry) {
890
-				$listOfDNs[] = $entry['dn'][0];
891
-				return $listOfDNs;
892
-			}, []);
893
-			$idsByDn = $this->userMapper->getListOfIdsByDn($listOfDNs);
894
-			$recordsToUpdate = array_filter($ldapRecords, function ($record) use ($isBackgroundJobModeAjax, $idsByDn) {
895
-				$newlyMapped = false;
896
-				$uid = $idsByDn[$record['dn'][0]] ?? null;
897
-				if ($uid === null) {
898
-					$uid = $this->dn2ocname($record['dn'][0], null, true, $newlyMapped, $record);
899
-				}
900
-				if (is_string($uid)) {
901
-					$this->cacheUserExists($uid);
902
-				}
903
-				return ($uid !== false) && ($newlyMapped || $isBackgroundJobModeAjax);
904
-			});
905
-		}
906
-		$this->batchApplyUserAttributes($recordsToUpdate);
907
-		return $this->fetchList($ldapRecords, $this->manyAttributes($attr));
908
-	}
909
-
910
-	/**
911
-	 * provided with an array of LDAP user records the method will fetch the
912
-	 * user object and requests it to process the freshly fetched attributes and
913
-	 * and their values
914
-	 *
915
-	 * @param array $ldapRecords
916
-	 * @throws \Exception
917
-	 */
918
-	public function batchApplyUserAttributes(array $ldapRecords) {
919
-		$displayNameAttribute = strtolower($this->connection->ldapUserDisplayName);
920
-		foreach ($ldapRecords as $userRecord) {
921
-			if (!isset($userRecord[$displayNameAttribute])) {
922
-				// displayName is obligatory
923
-				continue;
924
-			}
925
-			$ocName = $this->dn2ocname($userRecord['dn'][0], null, true);
926
-			if ($ocName === false) {
927
-				continue;
928
-			}
929
-			$this->updateUserState($ocName);
930
-			$user = $this->userManager->get($ocName);
931
-			if ($user !== null) {
932
-				$user->processAttributes($userRecord);
933
-			} else {
934
-				\OC::$server->getLogger()->debug(
935
-					"The ldap user manager returned null for $ocName",
936
-					['app' => 'user_ldap']
937
-				);
938
-			}
939
-		}
940
-	}
941
-
942
-	/**
943
-	 * @param string $filter
944
-	 * @param string|string[] $attr
945
-	 * @param int $limit
946
-	 * @param int $offset
947
-	 * @return array
948
-	 */
949
-	public function fetchListOfGroups($filter, $attr, $limit = null, $offset = null) {
950
-		$groupRecords = $this->searchGroups($filter, $attr, $limit, $offset);
951
-
952
-		$listOfDNs = array_reduce($groupRecords, function ($listOfDNs, $entry) {
953
-			$listOfDNs[] = $entry['dn'][0];
954
-			return $listOfDNs;
955
-		}, []);
956
-		$idsByDn = $this->groupMapper->getListOfIdsByDn($listOfDNs);
957
-
958
-		array_walk($groupRecords, function ($record) use ($idsByDn) {
959
-			$newlyMapped = false;
960
-			$gid = $uidsByDn[$record['dn'][0]] ?? null;
961
-			if ($gid === null) {
962
-				$gid = $this->dn2ocname($record['dn'][0], null, false, $newlyMapped, $record);
963
-			}
964
-			if (!$newlyMapped && is_string($gid)) {
965
-				$this->cacheGroupExists($gid);
966
-			}
967
-		});
968
-		return $this->fetchList($groupRecords, $this->manyAttributes($attr));
969
-	}
970
-
971
-	/**
972
-	 * @param array $list
973
-	 * @param bool $manyAttributes
974
-	 * @return array
975
-	 */
976
-	private function fetchList($list, $manyAttributes) {
977
-		if (is_array($list)) {
978
-			if ($manyAttributes) {
979
-				return $list;
980
-			} else {
981
-				$list = array_reduce($list, function ($carry, $item) {
982
-					$attribute = array_keys($item)[0];
983
-					$carry[] = $item[$attribute][0];
984
-					return $carry;
985
-				}, []);
986
-				return array_unique($list, SORT_LOCALE_STRING);
987
-			}
988
-		}
989
-
990
-		//error cause actually, maybe throw an exception in future.
991
-		return [];
992
-	}
993
-
994
-	/**
995
-	 * executes an LDAP search, optimized for Users
996
-	 *
997
-	 * @param string $filter the LDAP filter for the search
998
-	 * @param string|string[] $attr optional, when a certain attribute shall be filtered out
999
-	 * @param integer $limit
1000
-	 * @param integer $offset
1001
-	 * @return array with the search result
1002
-	 *
1003
-	 * Executes an LDAP search
1004
-	 * @throws ServerNotAvailableException
1005
-	 */
1006
-	public function searchUsers($filter, $attr = null, $limit = null, $offset = null) {
1007
-		$result = [];
1008
-		foreach ($this->connection->ldapBaseUsers as $base) {
1009
-			$result = array_merge($result, $this->search($filter, $base, $attr, $limit, $offset));
1010
-		}
1011
-		return $result;
1012
-	}
1013
-
1014
-	/**
1015
-	 * @param string $filter
1016
-	 * @param string|string[] $attr
1017
-	 * @param int $limit
1018
-	 * @param int $offset
1019
-	 * @return false|int
1020
-	 * @throws ServerNotAvailableException
1021
-	 */
1022
-	public function countUsers($filter, $attr = ['dn'], $limit = null, $offset = null) {
1023
-		$result = false;
1024
-		foreach ($this->connection->ldapBaseUsers as $base) {
1025
-			$count = $this->count($filter, [$base], $attr, $limit, $offset);
1026
-			$result = is_int($count) ? (int)$result + $count : $result;
1027
-		}
1028
-		return $result;
1029
-	}
1030
-
1031
-	/**
1032
-	 * executes an LDAP search, optimized for Groups
1033
-	 *
1034
-	 * @param string $filter the LDAP filter for the search
1035
-	 * @param string|string[] $attr optional, when a certain attribute shall be filtered out
1036
-	 * @param integer $limit
1037
-	 * @param integer $offset
1038
-	 * @return array with the search result
1039
-	 *
1040
-	 * Executes an LDAP search
1041
-	 * @throws ServerNotAvailableException
1042
-	 */
1043
-	public function searchGroups($filter, $attr = null, $limit = null, $offset = null) {
1044
-		$result = [];
1045
-		foreach ($this->connection->ldapBaseGroups as $base) {
1046
-			$result = array_merge($result, $this->search($filter, $base, $attr, $limit, $offset));
1047
-		}
1048
-		return $result;
1049
-	}
1050
-
1051
-	/**
1052
-	 * returns the number of available groups
1053
-	 *
1054
-	 * @param string $filter the LDAP search filter
1055
-	 * @param string[] $attr optional
1056
-	 * @param int|null $limit
1057
-	 * @param int|null $offset
1058
-	 * @return int|bool
1059
-	 * @throws ServerNotAvailableException
1060
-	 */
1061
-	public function countGroups($filter, $attr = ['dn'], $limit = null, $offset = null) {
1062
-		$result = false;
1063
-		foreach ($this->connection->ldapBaseGroups as $base) {
1064
-			$count = $this->count($filter, [$base], $attr, $limit, $offset);
1065
-			$result = is_int($count) ? (int)$result + $count : $result;
1066
-		}
1067
-		return $result;
1068
-	}
1069
-
1070
-	/**
1071
-	 * returns the number of available objects on the base DN
1072
-	 *
1073
-	 * @param int|null $limit
1074
-	 * @param int|null $offset
1075
-	 * @return int|bool
1076
-	 * @throws ServerNotAvailableException
1077
-	 */
1078
-	public function countObjects($limit = null, $offset = null) {
1079
-		$result = false;
1080
-		foreach ($this->connection->ldapBase as $base) {
1081
-			$count = $this->count('objectclass=*', [$base], ['dn'], $limit, $offset);
1082
-			$result = is_int($count) ? (int)$result + $count : $result;
1083
-		}
1084
-		return $result;
1085
-	}
1086
-
1087
-	/**
1088
-	 * Returns the LDAP handler
1089
-	 *
1090
-	 * @throws \OC\ServerNotAvailableException
1091
-	 */
1092
-
1093
-	/**
1094
-	 * @return mixed
1095
-	 * @throws \OC\ServerNotAvailableException
1096
-	 */
1097
-	private function invokeLDAPMethod() {
1098
-		$arguments = func_get_args();
1099
-		$command = array_shift($arguments);
1100
-		$cr = array_shift($arguments);
1101
-		if (!method_exists($this->ldap, $command)) {
1102
-			return null;
1103
-		}
1104
-		array_unshift($arguments, $cr);
1105
-		// php no longer supports call-time pass-by-reference
1106
-		// thus cannot support controlPagedResultResponse as the third argument
1107
-		// is a reference
1108
-		$doMethod = function () use ($command, &$arguments) {
1109
-			if ($command == 'controlPagedResultResponse') {
1110
-				throw new \InvalidArgumentException('Invoker does not support controlPagedResultResponse, call LDAP Wrapper directly instead.');
1111
-			} else {
1112
-				return call_user_func_array([$this->ldap, $command], $arguments);
1113
-			}
1114
-		};
1115
-		try {
1116
-			$ret = $doMethod();
1117
-		} catch (ServerNotAvailableException $e) {
1118
-			/* Server connection lost, attempt to reestablish it
66
+    public const UUID_ATTRIBUTES = ['entryuuid', 'nsuniqueid', 'objectguid', 'guid', 'ipauniqueid'];
67
+
68
+    /** @var \OCA\User_LDAP\Connection */
69
+    public $connection;
70
+    /** @var Manager */
71
+    public $userManager;
72
+    //never ever check this var directly, always use getPagedSearchResultState
73
+    protected $pagedSearchedSuccessful;
74
+
75
+    /**
76
+     * protected $cookies = [];
77
+     *
78
+     * @var AbstractMapping $userMapper
79
+     */
80
+    protected $userMapper;
81
+
82
+    /**
83
+     * @var AbstractMapping $userMapper
84
+     */
85
+    protected $groupMapper;
86
+
87
+    /**
88
+     * @var \OCA\User_LDAP\Helper
89
+     */
90
+    private $helper;
91
+    /** @var IConfig */
92
+    private $config;
93
+    /** @var IUserManager */
94
+    private $ncUserManager;
95
+    /** @var string */
96
+    private $lastCookie = '';
97
+
98
+    public function __construct(
99
+        Connection $connection,
100
+        ILDAPWrapper $ldap,
101
+        Manager $userManager,
102
+        Helper $helper,
103
+        IConfig $config,
104
+        IUserManager $ncUserManager
105
+    ) {
106
+        parent::__construct($ldap);
107
+        $this->connection = $connection;
108
+        $this->userManager = $userManager;
109
+        $this->userManager->setLdapAccess($this);
110
+        $this->helper = $helper;
111
+        $this->config = $config;
112
+        $this->ncUserManager = $ncUserManager;
113
+    }
114
+
115
+    /**
116
+     * sets the User Mapper
117
+     *
118
+     * @param AbstractMapping $mapper
119
+     */
120
+    public function setUserMapper(AbstractMapping $mapper) {
121
+        $this->userMapper = $mapper;
122
+    }
123
+
124
+    /**
125
+     * returns the User Mapper
126
+     *
127
+     * @return AbstractMapping
128
+     * @throws \Exception
129
+     */
130
+    public function getUserMapper() {
131
+        if (is_null($this->userMapper)) {
132
+            throw new \Exception('UserMapper was not assigned to this Access instance.');
133
+        }
134
+        return $this->userMapper;
135
+    }
136
+
137
+    /**
138
+     * sets the Group Mapper
139
+     *
140
+     * @param AbstractMapping $mapper
141
+     */
142
+    public function setGroupMapper(AbstractMapping $mapper) {
143
+        $this->groupMapper = $mapper;
144
+    }
145
+
146
+    /**
147
+     * returns the Group Mapper
148
+     *
149
+     * @return AbstractMapping
150
+     * @throws \Exception
151
+     */
152
+    public function getGroupMapper() {
153
+        if (is_null($this->groupMapper)) {
154
+            throw new \Exception('GroupMapper was not assigned to this Access instance.');
155
+        }
156
+        return $this->groupMapper;
157
+    }
158
+
159
+    /**
160
+     * @return bool
161
+     */
162
+    private function checkConnection() {
163
+        return ($this->connection instanceof Connection);
164
+    }
165
+
166
+    /**
167
+     * returns the Connection instance
168
+     *
169
+     * @return \OCA\User_LDAP\Connection
170
+     */
171
+    public function getConnection() {
172
+        return $this->connection;
173
+    }
174
+
175
+    /**
176
+     * reads a given attribute for an LDAP record identified by a DN
177
+     *
178
+     * @param string $dn the record in question
179
+     * @param string $attr the attribute that shall be retrieved
180
+     *        if empty, just check the record's existence
181
+     * @param string $filter
182
+     * @return array|false an array of values on success or an empty
183
+     *          array if $attr is empty, false otherwise
184
+     * @throws ServerNotAvailableException
185
+     */
186
+    public function readAttribute($dn, $attr, $filter = 'objectClass=*') {
187
+        if (!$this->checkConnection()) {
188
+            \OCP\Util::writeLog('user_ldap',
189
+                'No LDAP Connector assigned, access impossible for readAttribute.',
190
+                ILogger::WARN);
191
+            return false;
192
+        }
193
+        $cr = $this->connection->getConnectionResource();
194
+        if (!$this->ldap->isResource($cr)) {
195
+            //LDAP not available
196
+            \OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', ILogger::DEBUG);
197
+            return false;
198
+        }
199
+        //Cancel possibly running Paged Results operation, otherwise we run in
200
+        //LDAP protocol errors
201
+        $this->abandonPagedSearch();
202
+        // openLDAP requires that we init a new Paged Search. Not needed by AD,
203
+        // but does not hurt either.
204
+        $pagingSize = (int)$this->connection->ldapPagingSize;
205
+        // 0 won't result in replies, small numbers may leave out groups
206
+        // (cf. #12306), 500 is default for paging and should work everywhere.
207
+        $maxResults = $pagingSize > 20 ? $pagingSize : 500;
208
+        $attr = mb_strtolower($attr, 'UTF-8');
209
+        // the actual read attribute later may contain parameters on a ranged
210
+        // request, e.g. member;range=99-199. Depends on server reply.
211
+        $attrToRead = $attr;
212
+
213
+        $values = [];
214
+        $isRangeRequest = false;
215
+        do {
216
+            $result = $this->executeRead($cr, $dn, $attrToRead, $filter, $maxResults);
217
+            if (is_bool($result)) {
218
+                // when an exists request was run and it was successful, an empty
219
+                // array must be returned
220
+                return $result ? [] : false;
221
+            }
222
+
223
+            if (!$isRangeRequest) {
224
+                $values = $this->extractAttributeValuesFromResult($result, $attr);
225
+                if (!empty($values)) {
226
+                    return $values;
227
+                }
228
+            }
229
+
230
+            $isRangeRequest = false;
231
+            $result = $this->extractRangeData($result, $attr);
232
+            if (!empty($result)) {
233
+                $normalizedResult = $this->extractAttributeValuesFromResult(
234
+                    [$attr => $result['values']],
235
+                    $attr
236
+                );
237
+                $values = array_merge($values, $normalizedResult);
238
+
239
+                if ($result['rangeHigh'] === '*') {
240
+                    // when server replies with * as high range value, there are
241
+                    // no more results left
242
+                    return $values;
243
+                } else {
244
+                    $low = $result['rangeHigh'] + 1;
245
+                    $attrToRead = $result['attributeName'] . ';range=' . $low . '-*';
246
+                    $isRangeRequest = true;
247
+                }
248
+            }
249
+        } while ($isRangeRequest);
250
+
251
+        \OCP\Util::writeLog('user_ldap', 'Requested attribute ' . $attr . ' not found for ' . $dn, ILogger::DEBUG);
252
+        return false;
253
+    }
254
+
255
+    /**
256
+     * Runs an read operation against LDAP
257
+     *
258
+     * @param resource $cr the LDAP connection
259
+     * @param string $dn
260
+     * @param string $attribute
261
+     * @param string $filter
262
+     * @param int $maxResults
263
+     * @return array|bool false if there was any error, true if an exists check
264
+     *                    was performed and the requested DN found, array with the
265
+     *                    returned data on a successful usual operation
266
+     * @throws ServerNotAvailableException
267
+     */
268
+    public function executeRead($cr, $dn, $attribute, $filter, $maxResults) {
269
+        $this->initPagedSearch($filter, $dn, [$attribute], $maxResults, 0);
270
+        $dn = $this->helper->DNasBaseParameter($dn);
271
+        $rr = @$this->invokeLDAPMethod('read', $cr, $dn, $filter, [$attribute]);
272
+        if (!$this->ldap->isResource($rr)) {
273
+            if ($attribute !== '') {
274
+                //do not throw this message on userExists check, irritates
275
+                \OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN ' . $dn, ILogger::DEBUG);
276
+            }
277
+            //in case an error occurs , e.g. object does not exist
278
+            return false;
279
+        }
280
+        if ($attribute === '' && ($filter === 'objectclass=*' || $this->invokeLDAPMethod('countEntries', $cr, $rr) === 1)) {
281
+            \OCP\Util::writeLog('user_ldap', 'readAttribute: ' . $dn . ' found', ILogger::DEBUG);
282
+            return true;
283
+        }
284
+        $er = $this->invokeLDAPMethod('firstEntry', $cr, $rr);
285
+        if (!$this->ldap->isResource($er)) {
286
+            //did not match the filter, return false
287
+            return false;
288
+        }
289
+        //LDAP attributes are not case sensitive
290
+        $result = \OCP\Util::mb_array_change_key_case(
291
+            $this->invokeLDAPMethod('getAttributes', $cr, $er), MB_CASE_LOWER, 'UTF-8');
292
+
293
+        return $result;
294
+    }
295
+
296
+    /**
297
+     * Normalizes a result grom getAttributes(), i.e. handles DNs and binary
298
+     * data if present.
299
+     *
300
+     * @param array $result from ILDAPWrapper::getAttributes()
301
+     * @param string $attribute the attribute name that was read
302
+     * @return string[]
303
+     */
304
+    public function extractAttributeValuesFromResult($result, $attribute) {
305
+        $values = [];
306
+        if (isset($result[$attribute]) && $result[$attribute]['count'] > 0) {
307
+            $lowercaseAttribute = strtolower($attribute);
308
+            for ($i = 0; $i < $result[$attribute]['count']; $i++) {
309
+                if ($this->resemblesDN($attribute)) {
310
+                    $values[] = $this->helper->sanitizeDN($result[$attribute][$i]);
311
+                } elseif ($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') {
312
+                    $values[] = $this->convertObjectGUID2Str($result[$attribute][$i]);
313
+                } else {
314
+                    $values[] = $result[$attribute][$i];
315
+                }
316
+            }
317
+        }
318
+        return $values;
319
+    }
320
+
321
+    /**
322
+     * Attempts to find ranged data in a getAttribute results and extracts the
323
+     * returned values as well as information on the range and full attribute
324
+     * name for further processing.
325
+     *
326
+     * @param array $result from ILDAPWrapper::getAttributes()
327
+     * @param string $attribute the attribute name that was read. Without ";range=…"
328
+     * @return array If a range was detected with keys 'values', 'attributeName',
329
+     *               'attributeFull' and 'rangeHigh', otherwise empty.
330
+     */
331
+    public function extractRangeData($result, $attribute) {
332
+        $keys = array_keys($result);
333
+        foreach ($keys as $key) {
334
+            if ($key !== $attribute && strpos($key, $attribute) === 0) {
335
+                $queryData = explode(';', $key);
336
+                if (strpos($queryData[1], 'range=') === 0) {
337
+                    $high = substr($queryData[1], 1 + strpos($queryData[1], '-'));
338
+                    $data = [
339
+                        'values' => $result[$key],
340
+                        'attributeName' => $queryData[0],
341
+                        'attributeFull' => $key,
342
+                        'rangeHigh' => $high,
343
+                    ];
344
+                    return $data;
345
+                }
346
+            }
347
+        }
348
+        return [];
349
+    }
350
+
351
+    /**
352
+     * Set password for an LDAP user identified by a DN
353
+     *
354
+     * @param string $userDN the user in question
355
+     * @param string $password the new password
356
+     * @return bool
357
+     * @throws HintException
358
+     * @throws \Exception
359
+     */
360
+    public function setPassword($userDN, $password) {
361
+        if ((int)$this->connection->turnOnPasswordChange !== 1) {
362
+            throw new \Exception('LDAP password changes are disabled.');
363
+        }
364
+        $cr = $this->connection->getConnectionResource();
365
+        if (!$this->ldap->isResource($cr)) {
366
+            //LDAP not available
367
+            \OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', ILogger::DEBUG);
368
+            return false;
369
+        }
370
+        try {
371
+            // try PASSWD extended operation first
372
+            return @$this->invokeLDAPMethod('exopPasswd', $cr, $userDN, '', $password) ||
373
+                @$this->invokeLDAPMethod('modReplace', $cr, $userDN, $password);
374
+        } catch (ConstraintViolationException $e) {
375
+            throw new HintException('Password change rejected.', \OC::$server->getL10N('user_ldap')->t('Password change rejected. Hint: ') . $e->getMessage(), $e->getCode());
376
+        }
377
+    }
378
+
379
+    /**
380
+     * checks whether the given attributes value is probably a DN
381
+     *
382
+     * @param string $attr the attribute in question
383
+     * @return boolean if so true, otherwise false
384
+     */
385
+    private function resemblesDN($attr) {
386
+        $resemblingAttributes = [
387
+            'dn',
388
+            'uniquemember',
389
+            'member',
390
+            // memberOf is an "operational" attribute, without a definition in any RFC
391
+            'memberof'
392
+        ];
393
+        return in_array($attr, $resemblingAttributes);
394
+    }
395
+
396
+    /**
397
+     * checks whether the given string is probably a DN
398
+     *
399
+     * @param string $string
400
+     * @return boolean
401
+     */
402
+    public function stringResemblesDN($string) {
403
+        $r = $this->ldap->explodeDN($string, 0);
404
+        // if exploding a DN succeeds and does not end up in
405
+        // an empty array except for $r[count] being 0.
406
+        return (is_array($r) && count($r) > 1);
407
+    }
408
+
409
+    /**
410
+     * returns a DN-string that is cleaned from not domain parts, e.g.
411
+     * cn=foo,cn=bar,dc=foobar,dc=server,dc=org
412
+     * becomes dc=foobar,dc=server,dc=org
413
+     *
414
+     * @param string $dn
415
+     * @return string
416
+     */
417
+    public function getDomainDNFromDN($dn) {
418
+        $allParts = $this->ldap->explodeDN($dn, 0);
419
+        if ($allParts === false) {
420
+            //not a valid DN
421
+            return '';
422
+        }
423
+        $domainParts = [];
424
+        $dcFound = false;
425
+        foreach ($allParts as $part) {
426
+            if (!$dcFound && strpos($part, 'dc=') === 0) {
427
+                $dcFound = true;
428
+            }
429
+            if ($dcFound) {
430
+                $domainParts[] = $part;
431
+            }
432
+        }
433
+        return implode(',', $domainParts);
434
+    }
435
+
436
+    /**
437
+     * returns the LDAP DN for the given internal Nextcloud name of the group
438
+     *
439
+     * @param string $name the Nextcloud name in question
440
+     * @return string|false LDAP DN on success, otherwise false
441
+     */
442
+    public function groupname2dn($name) {
443
+        return $this->groupMapper->getDNByName($name);
444
+    }
445
+
446
+    /**
447
+     * returns the LDAP DN for the given internal Nextcloud name of the user
448
+     *
449
+     * @param string $name the Nextcloud name in question
450
+     * @return string|false with the LDAP DN on success, otherwise false
451
+     */
452
+    public function username2dn($name) {
453
+        $fdn = $this->userMapper->getDNByName($name);
454
+
455
+        //Check whether the DN belongs to the Base, to avoid issues on multi-
456
+        //server setups
457
+        if (is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
458
+            return $fdn;
459
+        }
460
+
461
+        return false;
462
+    }
463
+
464
+    /**
465
+     * returns the internal Nextcloud name for the given LDAP DN of the group, false on DN outside of search DN or failure
466
+     *
467
+     * @param string $fdn the dn of the group object
468
+     * @param string $ldapName optional, the display name of the object
469
+     * @return string|false with the name to use in Nextcloud, false on DN outside of search DN
470
+     * @throws \Exception
471
+     */
472
+    public function dn2groupname($fdn, $ldapName = null) {
473
+        //To avoid bypassing the base DN settings under certain circumstances
474
+        //with the group support, check whether the provided DN matches one of
475
+        //the given Bases
476
+        if (!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) {
477
+            return false;
478
+        }
479
+
480
+        return $this->dn2ocname($fdn, $ldapName, false);
481
+    }
482
+
483
+    /**
484
+     * returns the internal Nextcloud name for the given LDAP DN of the user, false on DN outside of search DN or failure
485
+     *
486
+     * @param string $dn the dn of the user object
487
+     * @param string $ldapName optional, the display name of the object
488
+     * @return string|false with with the name to use in Nextcloud
489
+     * @throws \Exception
490
+     */
491
+    public function dn2username($fdn, $ldapName = null) {
492
+        //To avoid bypassing the base DN settings under certain circumstances
493
+        //with the group support, check whether the provided DN matches one of
494
+        //the given Bases
495
+        if (!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
496
+            return false;
497
+        }
498
+
499
+        return $this->dn2ocname($fdn, $ldapName, true);
500
+    }
501
+
502
+    /**
503
+     * returns an internal Nextcloud name for the given LDAP DN, false on DN outside of search DN
504
+     *
505
+     * @param string $fdn the dn of the user object
506
+     * @param string|null $ldapName optional, the display name of the object
507
+     * @param bool $isUser optional, whether it is a user object (otherwise group assumed)
508
+     * @param bool|null $newlyMapped
509
+     * @param array|null $record
510
+     * @return false|string with with the name to use in Nextcloud
511
+     * @throws \Exception
512
+     */
513
+    public function dn2ocname($fdn, $ldapName = null, $isUser = true, &$newlyMapped = null, array $record = null) {
514
+        $newlyMapped = false;
515
+        if ($isUser) {
516
+            $mapper = $this->getUserMapper();
517
+            $nameAttribute = $this->connection->ldapUserDisplayName;
518
+            $filter = $this->connection->ldapUserFilter;
519
+        } else {
520
+            $mapper = $this->getGroupMapper();
521
+            $nameAttribute = $this->connection->ldapGroupDisplayName;
522
+            $filter = $this->connection->ldapGroupFilter;
523
+        }
524
+
525
+        //let's try to retrieve the Nextcloud name from the mappings table
526
+        $ncName = $mapper->getNameByDN($fdn);
527
+        if (is_string($ncName)) {
528
+            return $ncName;
529
+        }
530
+
531
+        //second try: get the UUID and check if it is known. Then, update the DN and return the name.
532
+        $uuid = $this->getUUID($fdn, $isUser, $record);
533
+        if (is_string($uuid)) {
534
+            $ncName = $mapper->getNameByUUID($uuid);
535
+            if (is_string($ncName)) {
536
+                $mapper->setDNbyUUID($fdn, $uuid);
537
+                return $ncName;
538
+            }
539
+        } else {
540
+            //If the UUID can't be detected something is foul.
541
+            \OCP\Util::writeLog('user_ldap', 'Cannot determine UUID for ' . $fdn . '. Skipping.', ILogger::INFO);
542
+            return false;
543
+        }
544
+
545
+        if (is_null($ldapName)) {
546
+            $ldapName = $this->readAttribute($fdn, $nameAttribute, $filter);
547
+            if (!isset($ldapName[0]) && empty($ldapName[0])) {
548
+                \OCP\Util::writeLog('user_ldap', 'No or empty name for ' . $fdn . ' with filter ' . $filter . '.', ILogger::INFO);
549
+                return false;
550
+            }
551
+            $ldapName = $ldapName[0];
552
+        }
553
+
554
+        if ($isUser) {
555
+            $usernameAttribute = (string)$this->connection->ldapExpertUsernameAttr;
556
+            if ($usernameAttribute !== '') {
557
+                $username = $this->readAttribute($fdn, $usernameAttribute);
558
+                $username = $username[0];
559
+            } else {
560
+                $username = $uuid;
561
+            }
562
+            try {
563
+                $intName = $this->sanitizeUsername($username);
564
+            } catch (\InvalidArgumentException $e) {
565
+                \OC::$server->getLogger()->logException($e, [
566
+                    'app' => 'user_ldap',
567
+                    'level' => ILogger::WARN,
568
+                ]);
569
+                // we don't attempt to set a username here. We can go for
570
+                // for an alternative 4 digit random number as we would append
571
+                // otherwise, however it's likely not enough space in bigger
572
+                // setups, and most importantly: this is not intended.
573
+                return false;
574
+            }
575
+        } else {
576
+            $intName = $ldapName;
577
+        }
578
+
579
+        //a new user/group! Add it only if it doesn't conflict with other backend's users or existing groups
580
+        //disabling Cache is required to avoid that the new user is cached as not-existing in fooExists check
581
+        //NOTE: mind, disabling cache affects only this instance! Using it
582
+        // outside of core user management will still cache the user as non-existing.
583
+        $originalTTL = $this->connection->ldapCacheTTL;
584
+        $this->connection->setConfiguration(['ldapCacheTTL' => 0]);
585
+        if ($intName !== ''
586
+            && (($isUser && !$this->ncUserManager->userExists($intName))
587
+                || (!$isUser && !\OC::$server->getGroupManager()->groupExists($intName))
588
+            )
589
+        ) {
590
+            $this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]);
591
+            $newlyMapped = $this->mapAndAnnounceIfApplicable($mapper, $fdn, $intName, $uuid, $isUser);
592
+            if ($newlyMapped) {
593
+                return $intName;
594
+            }
595
+        }
596
+
597
+        $this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]);
598
+        $altName = $this->createAltInternalOwnCloudName($intName, $isUser);
599
+        if (is_string($altName)) {
600
+            if ($this->mapAndAnnounceIfApplicable($mapper, $fdn, $altName, $uuid, $isUser)) {
601
+                $newlyMapped = true;
602
+                return $altName;
603
+            }
604
+        }
605
+
606
+        //if everything else did not help..
607
+        \OCP\Util::writeLog('user_ldap', 'Could not create unique name for ' . $fdn . '.', ILogger::INFO);
608
+        return false;
609
+    }
610
+
611
+    public function mapAndAnnounceIfApplicable(
612
+        AbstractMapping $mapper,
613
+        string $fdn,
614
+        string $name,
615
+        string $uuid,
616
+        bool $isUser
617
+    ): bool {
618
+        if ($mapper->map($fdn, $name, $uuid)) {
619
+            if ($this->ncUserManager instanceof PublicEmitter && $isUser) {
620
+                $this->cacheUserExists($name);
621
+                $this->ncUserManager->emit('\OC\User', 'assignedUserId', [$name]);
622
+            } elseif (!$isUser) {
623
+                $this->cacheGroupExists($name);
624
+            }
625
+            return true;
626
+        }
627
+        return false;
628
+    }
629
+
630
+    /**
631
+     * gives back the user names as they are used ownClod internally
632
+     *
633
+     * @param array $ldapUsers as returned by fetchList()
634
+     * @return array an array with the user names to use in Nextcloud
635
+     *
636
+     * gives back the user names as they are used ownClod internally
637
+     * @throws \Exception
638
+     */
639
+    public function nextcloudUserNames($ldapUsers) {
640
+        return $this->ldap2NextcloudNames($ldapUsers, true);
641
+    }
642
+
643
+    /**
644
+     * gives back the group names as they are used ownClod internally
645
+     *
646
+     * @param array $ldapGroups as returned by fetchList()
647
+     * @return array an array with the group names to use in Nextcloud
648
+     *
649
+     * gives back the group names as they are used ownClod internally
650
+     * @throws \Exception
651
+     */
652
+    public function nextcloudGroupNames($ldapGroups) {
653
+        return $this->ldap2NextcloudNames($ldapGroups, false);
654
+    }
655
+
656
+    /**
657
+     * @param array $ldapObjects as returned by fetchList()
658
+     * @param bool $isUsers
659
+     * @return array
660
+     * @throws \Exception
661
+     */
662
+    private function ldap2NextcloudNames($ldapObjects, $isUsers) {
663
+        if ($isUsers) {
664
+            $nameAttribute = $this->connection->ldapUserDisplayName;
665
+            $sndAttribute = $this->connection->ldapUserDisplayName2;
666
+        } else {
667
+            $nameAttribute = $this->connection->ldapGroupDisplayName;
668
+        }
669
+        $nextcloudNames = [];
670
+
671
+        foreach ($ldapObjects as $ldapObject) {
672
+            $nameByLDAP = null;
673
+            if (isset($ldapObject[$nameAttribute])
674
+                && is_array($ldapObject[$nameAttribute])
675
+                && isset($ldapObject[$nameAttribute][0])
676
+            ) {
677
+                // might be set, but not necessarily. if so, we use it.
678
+                $nameByLDAP = $ldapObject[$nameAttribute][0];
679
+            }
680
+
681
+            $ncName = $this->dn2ocname($ldapObject['dn'][0], $nameByLDAP, $isUsers);
682
+            if ($ncName) {
683
+                $nextcloudNames[] = $ncName;
684
+                if ($isUsers) {
685
+                    $this->updateUserState($ncName);
686
+                    //cache the user names so it does not need to be retrieved
687
+                    //again later (e.g. sharing dialogue).
688
+                    if (is_null($nameByLDAP)) {
689
+                        continue;
690
+                    }
691
+                    $sndName = isset($ldapObject[$sndAttribute][0])
692
+                        ? $ldapObject[$sndAttribute][0] : '';
693
+                    $this->cacheUserDisplayName($ncName, $nameByLDAP, $sndName);
694
+                } elseif ($nameByLDAP !== null) {
695
+                    $this->cacheGroupDisplayName($ncName, $nameByLDAP);
696
+                }
697
+            }
698
+        }
699
+        return $nextcloudNames;
700
+    }
701
+
702
+    /**
703
+     * removes the deleted-flag of a user if it was set
704
+     *
705
+     * @param string $ncname
706
+     * @throws \Exception
707
+     */
708
+    public function updateUserState($ncname) {
709
+        $user = $this->userManager->get($ncname);
710
+        if ($user instanceof OfflineUser) {
711
+            $user->unmark();
712
+        }
713
+    }
714
+
715
+    /**
716
+     * caches the user display name
717
+     *
718
+     * @param string $ocName the internal Nextcloud username
719
+     * @param string|false $home the home directory path
720
+     */
721
+    public function cacheUserHome($ocName, $home) {
722
+        $cacheKey = 'getHome' . $ocName;
723
+        $this->connection->writeToCache($cacheKey, $home);
724
+    }
725
+
726
+    /**
727
+     * caches a user as existing
728
+     *
729
+     * @param string $ocName the internal Nextcloud username
730
+     */
731
+    public function cacheUserExists($ocName) {
732
+        $this->connection->writeToCache('userExists' . $ocName, true);
733
+    }
734
+
735
+    /**
736
+     * caches a group as existing
737
+     */
738
+    public function cacheGroupExists(string $gid): void {
739
+        $this->connection->writeToCache('groupExists' . $gid, true);
740
+    }
741
+
742
+    /**
743
+     * caches the user display name
744
+     *
745
+     * @param string $ocName the internal Nextcloud username
746
+     * @param string $displayName the display name
747
+     * @param string $displayName2 the second display name
748
+     * @throws \Exception
749
+     */
750
+    public function cacheUserDisplayName($ocName, $displayName, $displayName2 = '') {
751
+        $user = $this->userManager->get($ocName);
752
+        if ($user === null) {
753
+            return;
754
+        }
755
+        $displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
756
+        $cacheKeyTrunk = 'getDisplayName';
757
+        $this->connection->writeToCache($cacheKeyTrunk . $ocName, $displayName);
758
+    }
759
+
760
+    public function cacheGroupDisplayName(string $ncName, string $displayName): void {
761
+        $cacheKey = 'group_getDisplayName' . $ncName;
762
+        $this->connection->writeToCache($cacheKey, $displayName);
763
+    }
764
+
765
+    /**
766
+     * creates a unique name for internal Nextcloud use for users. Don't call it directly.
767
+     *
768
+     * @param string $name the display name of the object
769
+     * @return string|false with with the name to use in Nextcloud or false if unsuccessful
770
+     *
771
+     * Instead of using this method directly, call
772
+     * createAltInternalOwnCloudName($name, true)
773
+     */
774
+    private function _createAltInternalOwnCloudNameForUsers($name) {
775
+        $attempts = 0;
776
+        //while loop is just a precaution. If a name is not generated within
777
+        //20 attempts, something else is very wrong. Avoids infinite loop.
778
+        while ($attempts < 20) {
779
+            $altName = $name . '_' . rand(1000, 9999);
780
+            if (!$this->ncUserManager->userExists($altName)) {
781
+                return $altName;
782
+            }
783
+            $attempts++;
784
+        }
785
+        return false;
786
+    }
787
+
788
+    /**
789
+     * creates a unique name for internal Nextcloud use for groups. Don't call it directly.
790
+     *
791
+     * @param string $name the display name of the object
792
+     * @return string|false with with the name to use in Nextcloud or false if unsuccessful.
793
+     *
794
+     * Instead of using this method directly, call
795
+     * createAltInternalOwnCloudName($name, false)
796
+     *
797
+     * Group names are also used as display names, so we do a sequential
798
+     * numbering, e.g. Developers_42 when there are 41 other groups called
799
+     * "Developers"
800
+     */
801
+    private function _createAltInternalOwnCloudNameForGroups($name) {
802
+        $usedNames = $this->groupMapper->getNamesBySearch($name, "", '_%');
803
+        if (!$usedNames || count($usedNames) === 0) {
804
+            $lastNo = 1; //will become name_2
805
+        } else {
806
+            natsort($usedNames);
807
+            $lastName = array_pop($usedNames);
808
+            $lastNo = (int)substr($lastName, strrpos($lastName, '_') + 1);
809
+        }
810
+        $altName = $name . '_' . (string)($lastNo + 1);
811
+        unset($usedNames);
812
+
813
+        $attempts = 1;
814
+        while ($attempts < 21) {
815
+            // Check to be really sure it is unique
816
+            // while loop is just a precaution. If a name is not generated within
817
+            // 20 attempts, something else is very wrong. Avoids infinite loop.
818
+            if (!\OC::$server->getGroupManager()->groupExists($altName)) {
819
+                return $altName;
820
+            }
821
+            $altName = $name . '_' . ($lastNo + $attempts);
822
+            $attempts++;
823
+        }
824
+        return false;
825
+    }
826
+
827
+    /**
828
+     * creates a unique name for internal Nextcloud use.
829
+     *
830
+     * @param string $name the display name of the object
831
+     * @param boolean $isUser whether name should be created for a user (true) or a group (false)
832
+     * @return string|false with with the name to use in Nextcloud or false if unsuccessful
833
+     */
834
+    private function createAltInternalOwnCloudName($name, $isUser) {
835
+        $originalTTL = $this->connection->ldapCacheTTL;
836
+        $this->connection->setConfiguration(['ldapCacheTTL' => 0]);
837
+        if ($isUser) {
838
+            $altName = $this->_createAltInternalOwnCloudNameForUsers($name);
839
+        } else {
840
+            $altName = $this->_createAltInternalOwnCloudNameForGroups($name);
841
+        }
842
+        $this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]);
843
+
844
+        return $altName;
845
+    }
846
+
847
+    /**
848
+     * fetches a list of users according to a provided loginName and utilizing
849
+     * the login filter.
850
+     *
851
+     * @param string $loginName
852
+     * @param array $attributes optional, list of attributes to read
853
+     * @return array
854
+     */
855
+    public function fetchUsersByLoginName($loginName, $attributes = ['dn']) {
856
+        $loginName = $this->escapeFilterPart($loginName);
857
+        $filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
858
+        return $this->fetchListOfUsers($filter, $attributes);
859
+    }
860
+
861
+    /**
862
+     * counts the number of users according to a provided loginName and
863
+     * utilizing the login filter.
864
+     *
865
+     * @param string $loginName
866
+     * @return int
867
+     */
868
+    public function countUsersByLoginName($loginName) {
869
+        $loginName = $this->escapeFilterPart($loginName);
870
+        $filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
871
+        return $this->countUsers($filter);
872
+    }
873
+
874
+    /**
875
+     * @param string $filter
876
+     * @param string|string[] $attr
877
+     * @param int $limit
878
+     * @param int $offset
879
+     * @param bool $forceApplyAttributes
880
+     * @return array
881
+     * @throws \Exception
882
+     */
883
+    public function fetchListOfUsers($filter, $attr, $limit = null, $offset = null, $forceApplyAttributes = false) {
884
+        $ldapRecords = $this->searchUsers($filter, $attr, $limit, $offset);
885
+        $recordsToUpdate = $ldapRecords;
886
+        if (!$forceApplyAttributes) {
887
+            $isBackgroundJobModeAjax = $this->config
888
+                    ->getAppValue('core', 'backgroundjobs_mode', 'ajax') === 'ajax';
889
+            $listOfDNs = array_reduce($ldapRecords, function ($listOfDNs, $entry) {
890
+                $listOfDNs[] = $entry['dn'][0];
891
+                return $listOfDNs;
892
+            }, []);
893
+            $idsByDn = $this->userMapper->getListOfIdsByDn($listOfDNs);
894
+            $recordsToUpdate = array_filter($ldapRecords, function ($record) use ($isBackgroundJobModeAjax, $idsByDn) {
895
+                $newlyMapped = false;
896
+                $uid = $idsByDn[$record['dn'][0]] ?? null;
897
+                if ($uid === null) {
898
+                    $uid = $this->dn2ocname($record['dn'][0], null, true, $newlyMapped, $record);
899
+                }
900
+                if (is_string($uid)) {
901
+                    $this->cacheUserExists($uid);
902
+                }
903
+                return ($uid !== false) && ($newlyMapped || $isBackgroundJobModeAjax);
904
+            });
905
+        }
906
+        $this->batchApplyUserAttributes($recordsToUpdate);
907
+        return $this->fetchList($ldapRecords, $this->manyAttributes($attr));
908
+    }
909
+
910
+    /**
911
+     * provided with an array of LDAP user records the method will fetch the
912
+     * user object and requests it to process the freshly fetched attributes and
913
+     * and their values
914
+     *
915
+     * @param array $ldapRecords
916
+     * @throws \Exception
917
+     */
918
+    public function batchApplyUserAttributes(array $ldapRecords) {
919
+        $displayNameAttribute = strtolower($this->connection->ldapUserDisplayName);
920
+        foreach ($ldapRecords as $userRecord) {
921
+            if (!isset($userRecord[$displayNameAttribute])) {
922
+                // displayName is obligatory
923
+                continue;
924
+            }
925
+            $ocName = $this->dn2ocname($userRecord['dn'][0], null, true);
926
+            if ($ocName === false) {
927
+                continue;
928
+            }
929
+            $this->updateUserState($ocName);
930
+            $user = $this->userManager->get($ocName);
931
+            if ($user !== null) {
932
+                $user->processAttributes($userRecord);
933
+            } else {
934
+                \OC::$server->getLogger()->debug(
935
+                    "The ldap user manager returned null for $ocName",
936
+                    ['app' => 'user_ldap']
937
+                );
938
+            }
939
+        }
940
+    }
941
+
942
+    /**
943
+     * @param string $filter
944
+     * @param string|string[] $attr
945
+     * @param int $limit
946
+     * @param int $offset
947
+     * @return array
948
+     */
949
+    public function fetchListOfGroups($filter, $attr, $limit = null, $offset = null) {
950
+        $groupRecords = $this->searchGroups($filter, $attr, $limit, $offset);
951
+
952
+        $listOfDNs = array_reduce($groupRecords, function ($listOfDNs, $entry) {
953
+            $listOfDNs[] = $entry['dn'][0];
954
+            return $listOfDNs;
955
+        }, []);
956
+        $idsByDn = $this->groupMapper->getListOfIdsByDn($listOfDNs);
957
+
958
+        array_walk($groupRecords, function ($record) use ($idsByDn) {
959
+            $newlyMapped = false;
960
+            $gid = $uidsByDn[$record['dn'][0]] ?? null;
961
+            if ($gid === null) {
962
+                $gid = $this->dn2ocname($record['dn'][0], null, false, $newlyMapped, $record);
963
+            }
964
+            if (!$newlyMapped && is_string($gid)) {
965
+                $this->cacheGroupExists($gid);
966
+            }
967
+        });
968
+        return $this->fetchList($groupRecords, $this->manyAttributes($attr));
969
+    }
970
+
971
+    /**
972
+     * @param array $list
973
+     * @param bool $manyAttributes
974
+     * @return array
975
+     */
976
+    private function fetchList($list, $manyAttributes) {
977
+        if (is_array($list)) {
978
+            if ($manyAttributes) {
979
+                return $list;
980
+            } else {
981
+                $list = array_reduce($list, function ($carry, $item) {
982
+                    $attribute = array_keys($item)[0];
983
+                    $carry[] = $item[$attribute][0];
984
+                    return $carry;
985
+                }, []);
986
+                return array_unique($list, SORT_LOCALE_STRING);
987
+            }
988
+        }
989
+
990
+        //error cause actually, maybe throw an exception in future.
991
+        return [];
992
+    }
993
+
994
+    /**
995
+     * executes an LDAP search, optimized for Users
996
+     *
997
+     * @param string $filter the LDAP filter for the search
998
+     * @param string|string[] $attr optional, when a certain attribute shall be filtered out
999
+     * @param integer $limit
1000
+     * @param integer $offset
1001
+     * @return array with the search result
1002
+     *
1003
+     * Executes an LDAP search
1004
+     * @throws ServerNotAvailableException
1005
+     */
1006
+    public function searchUsers($filter, $attr = null, $limit = null, $offset = null) {
1007
+        $result = [];
1008
+        foreach ($this->connection->ldapBaseUsers as $base) {
1009
+            $result = array_merge($result, $this->search($filter, $base, $attr, $limit, $offset));
1010
+        }
1011
+        return $result;
1012
+    }
1013
+
1014
+    /**
1015
+     * @param string $filter
1016
+     * @param string|string[] $attr
1017
+     * @param int $limit
1018
+     * @param int $offset
1019
+     * @return false|int
1020
+     * @throws ServerNotAvailableException
1021
+     */
1022
+    public function countUsers($filter, $attr = ['dn'], $limit = null, $offset = null) {
1023
+        $result = false;
1024
+        foreach ($this->connection->ldapBaseUsers as $base) {
1025
+            $count = $this->count($filter, [$base], $attr, $limit, $offset);
1026
+            $result = is_int($count) ? (int)$result + $count : $result;
1027
+        }
1028
+        return $result;
1029
+    }
1030
+
1031
+    /**
1032
+     * executes an LDAP search, optimized for Groups
1033
+     *
1034
+     * @param string $filter the LDAP filter for the search
1035
+     * @param string|string[] $attr optional, when a certain attribute shall be filtered out
1036
+     * @param integer $limit
1037
+     * @param integer $offset
1038
+     * @return array with the search result
1039
+     *
1040
+     * Executes an LDAP search
1041
+     * @throws ServerNotAvailableException
1042
+     */
1043
+    public function searchGroups($filter, $attr = null, $limit = null, $offset = null) {
1044
+        $result = [];
1045
+        foreach ($this->connection->ldapBaseGroups as $base) {
1046
+            $result = array_merge($result, $this->search($filter, $base, $attr, $limit, $offset));
1047
+        }
1048
+        return $result;
1049
+    }
1050
+
1051
+    /**
1052
+     * returns the number of available groups
1053
+     *
1054
+     * @param string $filter the LDAP search filter
1055
+     * @param string[] $attr optional
1056
+     * @param int|null $limit
1057
+     * @param int|null $offset
1058
+     * @return int|bool
1059
+     * @throws ServerNotAvailableException
1060
+     */
1061
+    public function countGroups($filter, $attr = ['dn'], $limit = null, $offset = null) {
1062
+        $result = false;
1063
+        foreach ($this->connection->ldapBaseGroups as $base) {
1064
+            $count = $this->count($filter, [$base], $attr, $limit, $offset);
1065
+            $result = is_int($count) ? (int)$result + $count : $result;
1066
+        }
1067
+        return $result;
1068
+    }
1069
+
1070
+    /**
1071
+     * returns the number of available objects on the base DN
1072
+     *
1073
+     * @param int|null $limit
1074
+     * @param int|null $offset
1075
+     * @return int|bool
1076
+     * @throws ServerNotAvailableException
1077
+     */
1078
+    public function countObjects($limit = null, $offset = null) {
1079
+        $result = false;
1080
+        foreach ($this->connection->ldapBase as $base) {
1081
+            $count = $this->count('objectclass=*', [$base], ['dn'], $limit, $offset);
1082
+            $result = is_int($count) ? (int)$result + $count : $result;
1083
+        }
1084
+        return $result;
1085
+    }
1086
+
1087
+    /**
1088
+     * Returns the LDAP handler
1089
+     *
1090
+     * @throws \OC\ServerNotAvailableException
1091
+     */
1092
+
1093
+    /**
1094
+     * @return mixed
1095
+     * @throws \OC\ServerNotAvailableException
1096
+     */
1097
+    private function invokeLDAPMethod() {
1098
+        $arguments = func_get_args();
1099
+        $command = array_shift($arguments);
1100
+        $cr = array_shift($arguments);
1101
+        if (!method_exists($this->ldap, $command)) {
1102
+            return null;
1103
+        }
1104
+        array_unshift($arguments, $cr);
1105
+        // php no longer supports call-time pass-by-reference
1106
+        // thus cannot support controlPagedResultResponse as the third argument
1107
+        // is a reference
1108
+        $doMethod = function () use ($command, &$arguments) {
1109
+            if ($command == 'controlPagedResultResponse') {
1110
+                throw new \InvalidArgumentException('Invoker does not support controlPagedResultResponse, call LDAP Wrapper directly instead.');
1111
+            } else {
1112
+                return call_user_func_array([$this->ldap, $command], $arguments);
1113
+            }
1114
+        };
1115
+        try {
1116
+            $ret = $doMethod();
1117
+        } catch (ServerNotAvailableException $e) {
1118
+            /* Server connection lost, attempt to reestablish it
1119 1119
 			 * Maybe implement exponential backoff?
1120 1120
 			 * This was enough to get solr indexer working which has large delays between LDAP fetches.
1121 1121
 			 */
1122
-			\OCP\Util::writeLog('user_ldap', "Connection lost on $command, attempting to reestablish.", ILogger::DEBUG);
1123
-			$this->connection->resetConnectionResource();
1124
-			$cr = $this->connection->getConnectionResource();
1125
-
1126
-			if (!$this->ldap->isResource($cr)) {
1127
-				// Seems like we didn't find any resource.
1128
-				\OCP\Util::writeLog('user_ldap', "Could not $command, because resource is missing.", ILogger::DEBUG);
1129
-				throw $e;
1130
-			}
1131
-
1132
-			$arguments[0] = $cr;
1133
-			$ret = $doMethod();
1134
-		}
1135
-		return $ret;
1136
-	}
1137
-
1138
-	/**
1139
-	 * retrieved. Results will according to the order in the array.
1140
-	 *
1141
-	 * @param string $filter
1142
-	 * @param string $base
1143
-	 * @param string[] $attr
1144
-	 * @param int|null $limit optional, maximum results to be counted
1145
-	 * @param int|null $offset optional, a starting point
1146
-	 * @return array|false array with the search result as first value and pagedSearchOK as
1147
-	 * second | false if not successful
1148
-	 * @throws ServerNotAvailableException
1149
-	 */
1150
-	private function executeSearch(
1151
-		string $filter,
1152
-		string $base,
1153
-		?array &$attr,
1154
-		?int $limit,
1155
-		?int $offset
1156
-	) {
1157
-		// See if we have a resource, in case not cancel with message
1158
-		$cr = $this->connection->getConnectionResource();
1159
-		if (!$this->ldap->isResource($cr)) {
1160
-			// Seems like we didn't find any resource.
1161
-			// Return an empty array just like before.
1162
-			\OCP\Util::writeLog('user_ldap', 'Could not search, because resource is missing.', ILogger::DEBUG);
1163
-			return false;
1164
-		}
1165
-
1166
-		//check whether paged search should be attempted
1167
-		$pagedSearchOK = $this->initPagedSearch($filter, $base, $attr, (int)$limit, (int)$offset);
1168
-
1169
-		$sr = $this->invokeLDAPMethod('search', $cr, $base, $filter, $attr);
1170
-		// cannot use $cr anymore, might have changed in the previous call!
1171
-		$error = $this->ldap->errno($this->connection->getConnectionResource());
1172
-		if (!$this->ldap->isResource($sr) || $error !== 0) {
1173
-			\OCP\Util::writeLog('user_ldap', 'Attempt for Paging?  ' . print_r($pagedSearchOK, true), ILogger::ERROR);
1174
-			return false;
1175
-		}
1176
-
1177
-		return [$sr, $pagedSearchOK];
1178
-	}
1179
-
1180
-	/**
1181
-	 * processes an LDAP paged search operation
1182
-	 *
1183
-	 * @param resource $sr the array containing the LDAP search resources
1184
-	 * @param int $foundItems number of results in the single search operation
1185
-	 * @param int $limit maximum results to be counted
1186
-	 * @param bool $pagedSearchOK whether a paged search has been executed
1187
-	 * @param bool $skipHandling required for paged search when cookies to
1188
-	 * prior results need to be gained
1189
-	 * @return bool cookie validity, true if we have more pages, false otherwise.
1190
-	 * @throws ServerNotAvailableException
1191
-	 */
1192
-	private function processPagedSearchStatus(
1193
-		$sr,
1194
-		int $foundItems,
1195
-		int $limit,
1196
-		bool $pagedSearchOK,
1197
-		bool $skipHandling
1198
-	): bool {
1199
-		$cookie = null;
1200
-		if ($pagedSearchOK) {
1201
-			$cr = $this->connection->getConnectionResource();
1202
-			if ($this->ldap->controlPagedResultResponse($cr, $sr, $cookie)) {
1203
-				$this->lastCookie = $cookie;
1204
-			}
1205
-
1206
-			//browsing through prior pages to get the cookie for the new one
1207
-			if ($skipHandling) {
1208
-				return false;
1209
-			}
1210
-			// if count is bigger, then the server does not support
1211
-			// paged search. Instead, he did a normal search. We set a
1212
-			// flag here, so the callee knows how to deal with it.
1213
-			if ($foundItems <= $limit) {
1214
-				$this->pagedSearchedSuccessful = true;
1215
-			}
1216
-		} else {
1217
-			if (!is_null($limit) && (int)$this->connection->ldapPagingSize !== 0) {
1218
-				\OC::$server->getLogger()->debug(
1219
-					'Paged search was not available',
1220
-					['app' => 'user_ldap']
1221
-				);
1222
-			}
1223
-		}
1224
-		/* ++ Fixing RHDS searches with pages with zero results ++
1122
+            \OCP\Util::writeLog('user_ldap', "Connection lost on $command, attempting to reestablish.", ILogger::DEBUG);
1123
+            $this->connection->resetConnectionResource();
1124
+            $cr = $this->connection->getConnectionResource();
1125
+
1126
+            if (!$this->ldap->isResource($cr)) {
1127
+                // Seems like we didn't find any resource.
1128
+                \OCP\Util::writeLog('user_ldap', "Could not $command, because resource is missing.", ILogger::DEBUG);
1129
+                throw $e;
1130
+            }
1131
+
1132
+            $arguments[0] = $cr;
1133
+            $ret = $doMethod();
1134
+        }
1135
+        return $ret;
1136
+    }
1137
+
1138
+    /**
1139
+     * retrieved. Results will according to the order in the array.
1140
+     *
1141
+     * @param string $filter
1142
+     * @param string $base
1143
+     * @param string[] $attr
1144
+     * @param int|null $limit optional, maximum results to be counted
1145
+     * @param int|null $offset optional, a starting point
1146
+     * @return array|false array with the search result as first value and pagedSearchOK as
1147
+     * second | false if not successful
1148
+     * @throws ServerNotAvailableException
1149
+     */
1150
+    private function executeSearch(
1151
+        string $filter,
1152
+        string $base,
1153
+        ?array &$attr,
1154
+        ?int $limit,
1155
+        ?int $offset
1156
+    ) {
1157
+        // See if we have a resource, in case not cancel with message
1158
+        $cr = $this->connection->getConnectionResource();
1159
+        if (!$this->ldap->isResource($cr)) {
1160
+            // Seems like we didn't find any resource.
1161
+            // Return an empty array just like before.
1162
+            \OCP\Util::writeLog('user_ldap', 'Could not search, because resource is missing.', ILogger::DEBUG);
1163
+            return false;
1164
+        }
1165
+
1166
+        //check whether paged search should be attempted
1167
+        $pagedSearchOK = $this->initPagedSearch($filter, $base, $attr, (int)$limit, (int)$offset);
1168
+
1169
+        $sr = $this->invokeLDAPMethod('search', $cr, $base, $filter, $attr);
1170
+        // cannot use $cr anymore, might have changed in the previous call!
1171
+        $error = $this->ldap->errno($this->connection->getConnectionResource());
1172
+        if (!$this->ldap->isResource($sr) || $error !== 0) {
1173
+            \OCP\Util::writeLog('user_ldap', 'Attempt for Paging?  ' . print_r($pagedSearchOK, true), ILogger::ERROR);
1174
+            return false;
1175
+        }
1176
+
1177
+        return [$sr, $pagedSearchOK];
1178
+    }
1179
+
1180
+    /**
1181
+     * processes an LDAP paged search operation
1182
+     *
1183
+     * @param resource $sr the array containing the LDAP search resources
1184
+     * @param int $foundItems number of results in the single search operation
1185
+     * @param int $limit maximum results to be counted
1186
+     * @param bool $pagedSearchOK whether a paged search has been executed
1187
+     * @param bool $skipHandling required for paged search when cookies to
1188
+     * prior results need to be gained
1189
+     * @return bool cookie validity, true if we have more pages, false otherwise.
1190
+     * @throws ServerNotAvailableException
1191
+     */
1192
+    private function processPagedSearchStatus(
1193
+        $sr,
1194
+        int $foundItems,
1195
+        int $limit,
1196
+        bool $pagedSearchOK,
1197
+        bool $skipHandling
1198
+    ): bool {
1199
+        $cookie = null;
1200
+        if ($pagedSearchOK) {
1201
+            $cr = $this->connection->getConnectionResource();
1202
+            if ($this->ldap->controlPagedResultResponse($cr, $sr, $cookie)) {
1203
+                $this->lastCookie = $cookie;
1204
+            }
1205
+
1206
+            //browsing through prior pages to get the cookie for the new one
1207
+            if ($skipHandling) {
1208
+                return false;
1209
+            }
1210
+            // if count is bigger, then the server does not support
1211
+            // paged search. Instead, he did a normal search. We set a
1212
+            // flag here, so the callee knows how to deal with it.
1213
+            if ($foundItems <= $limit) {
1214
+                $this->pagedSearchedSuccessful = true;
1215
+            }
1216
+        } else {
1217
+            if (!is_null($limit) && (int)$this->connection->ldapPagingSize !== 0) {
1218
+                \OC::$server->getLogger()->debug(
1219
+                    'Paged search was not available',
1220
+                    ['app' => 'user_ldap']
1221
+                );
1222
+            }
1223
+        }
1224
+        /* ++ Fixing RHDS searches with pages with zero results ++
1225 1225
 		 * Return cookie status. If we don't have more pages, with RHDS
1226 1226
 		 * cookie is null, with openldap cookie is an empty string and
1227 1227
 		 * to 386ds '0' is a valid cookie. Even if $iFoundItems == 0
1228 1228
 		 */
1229
-		return !empty($cookie) || $cookie === '0';
1230
-	}
1231
-
1232
-	/**
1233
-	 * executes an LDAP search, but counts the results only
1234
-	 *
1235
-	 * @param string $filter the LDAP filter for the search
1236
-	 * @param array $bases an array containing the LDAP subtree(s) that shall be searched
1237
-	 * @param string|string[] $attr optional, array, one or more attributes that shall be
1238
-	 * retrieved. Results will according to the order in the array.
1239
-	 * @param int $limit optional, maximum results to be counted
1240
-	 * @param int $offset optional, a starting point
1241
-	 * @param bool $skipHandling indicates whether the pages search operation is
1242
-	 * completed
1243
-	 * @return int|false Integer or false if the search could not be initialized
1244
-	 * @throws ServerNotAvailableException
1245
-	 */
1246
-	private function count(
1247
-		string $filter,
1248
-		array $bases,
1249
-		$attr = null,
1250
-		?int $limit = null,
1251
-		?int $offset = null,
1252
-		bool $skipHandling = false
1253
-	) {
1254
-		\OC::$server->getLogger()->debug('Count filter: {filter}', [
1255
-			'app' => 'user_ldap',
1256
-			'filter' => $filter
1257
-		]);
1258
-
1259
-		if (!is_null($attr) && !is_array($attr)) {
1260
-			$attr = [mb_strtolower($attr, 'UTF-8')];
1261
-		}
1262
-
1263
-		$limitPerPage = (int)$this->connection->ldapPagingSize;
1264
-		if (!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1265
-			$limitPerPage = $limit;
1266
-		}
1267
-
1268
-		$counter = 0;
1269
-		$count = null;
1270
-		$this->connection->getConnectionResource();
1271
-
1272
-		foreach ($bases as $base) {
1273
-			do {
1274
-				$search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
1275
-				if ($search === false) {
1276
-					return $counter > 0 ? $counter : false;
1277
-				}
1278
-				list($sr, $pagedSearchOK) = $search;
1279
-
1280
-				/* ++ Fixing RHDS searches with pages with zero results ++
1229
+        return !empty($cookie) || $cookie === '0';
1230
+    }
1231
+
1232
+    /**
1233
+     * executes an LDAP search, but counts the results only
1234
+     *
1235
+     * @param string $filter the LDAP filter for the search
1236
+     * @param array $bases an array containing the LDAP subtree(s) that shall be searched
1237
+     * @param string|string[] $attr optional, array, one or more attributes that shall be
1238
+     * retrieved. Results will according to the order in the array.
1239
+     * @param int $limit optional, maximum results to be counted
1240
+     * @param int $offset optional, a starting point
1241
+     * @param bool $skipHandling indicates whether the pages search operation is
1242
+     * completed
1243
+     * @return int|false Integer or false if the search could not be initialized
1244
+     * @throws ServerNotAvailableException
1245
+     */
1246
+    private function count(
1247
+        string $filter,
1248
+        array $bases,
1249
+        $attr = null,
1250
+        ?int $limit = null,
1251
+        ?int $offset = null,
1252
+        bool $skipHandling = false
1253
+    ) {
1254
+        \OC::$server->getLogger()->debug('Count filter: {filter}', [
1255
+            'app' => 'user_ldap',
1256
+            'filter' => $filter
1257
+        ]);
1258
+
1259
+        if (!is_null($attr) && !is_array($attr)) {
1260
+            $attr = [mb_strtolower($attr, 'UTF-8')];
1261
+        }
1262
+
1263
+        $limitPerPage = (int)$this->connection->ldapPagingSize;
1264
+        if (!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1265
+            $limitPerPage = $limit;
1266
+        }
1267
+
1268
+        $counter = 0;
1269
+        $count = null;
1270
+        $this->connection->getConnectionResource();
1271
+
1272
+        foreach ($bases as $base) {
1273
+            do {
1274
+                $search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
1275
+                if ($search === false) {
1276
+                    return $counter > 0 ? $counter : false;
1277
+                }
1278
+                list($sr, $pagedSearchOK) = $search;
1279
+
1280
+                /* ++ Fixing RHDS searches with pages with zero results ++
1281 1281
 				 * countEntriesInSearchResults() method signature changed
1282 1282
 				 * by removing $limit and &$hasHitLimit parameters
1283 1283
 				 */
1284
-				$count = $this->countEntriesInSearchResults($sr);
1285
-				$counter += $count;
1284
+                $count = $this->countEntriesInSearchResults($sr);
1285
+                $counter += $count;
1286 1286
 
1287
-				$hasMorePages = $this->processPagedSearchStatus($sr, $count, $limitPerPage, $pagedSearchOK, $skipHandling);
1288
-				$offset += $limitPerPage;
1289
-				/* ++ Fixing RHDS searches with pages with zero results ++
1287
+                $hasMorePages = $this->processPagedSearchStatus($sr, $count, $limitPerPage, $pagedSearchOK, $skipHandling);
1288
+                $offset += $limitPerPage;
1289
+                /* ++ Fixing RHDS searches with pages with zero results ++
1290 1290
 				 * Continue now depends on $hasMorePages value
1291 1291
 				 */
1292
-				$continue = $pagedSearchOK && $hasMorePages;
1293
-			} while ($continue && (is_null($limit) || $limit <= 0 || $limit > $counter));
1294
-		}
1295
-
1296
-		return $counter;
1297
-	}
1298
-
1299
-	/**
1300
-	 * @param resource $sr
1301
-	 * @return int
1302
-	 * @throws ServerNotAvailableException
1303
-	 */
1304
-	private function countEntriesInSearchResults($sr): int {
1305
-		return (int)$this->invokeLDAPMethod('countEntries', $this->connection->getConnectionResource(), $sr);
1306
-	}
1307
-
1308
-	/**
1309
-	 * Executes an LDAP search
1310
-	 *
1311
-	 * @throws ServerNotAvailableException
1312
-	 */
1313
-	public function search(
1314
-		string $filter,
1315
-		string $base,
1316
-		?array $attr = null,
1317
-		?int $limit = null,
1318
-		?int $offset = null,
1319
-		bool $skipHandling = false
1320
-	): array {
1321
-		$limitPerPage = (int)$this->connection->ldapPagingSize;
1322
-		if (!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1323
-			$limitPerPage = $limit;
1324
-		}
1325
-
1326
-		if (!is_null($attr) && !is_array($attr)) {
1327
-			$attr = [mb_strtolower($attr, 'UTF-8')];
1328
-		}
1329
-
1330
-		/* ++ Fixing RHDS searches with pages with zero results ++
1292
+                $continue = $pagedSearchOK && $hasMorePages;
1293
+            } while ($continue && (is_null($limit) || $limit <= 0 || $limit > $counter));
1294
+        }
1295
+
1296
+        return $counter;
1297
+    }
1298
+
1299
+    /**
1300
+     * @param resource $sr
1301
+     * @return int
1302
+     * @throws ServerNotAvailableException
1303
+     */
1304
+    private function countEntriesInSearchResults($sr): int {
1305
+        return (int)$this->invokeLDAPMethod('countEntries', $this->connection->getConnectionResource(), $sr);
1306
+    }
1307
+
1308
+    /**
1309
+     * Executes an LDAP search
1310
+     *
1311
+     * @throws ServerNotAvailableException
1312
+     */
1313
+    public function search(
1314
+        string $filter,
1315
+        string $base,
1316
+        ?array $attr = null,
1317
+        ?int $limit = null,
1318
+        ?int $offset = null,
1319
+        bool $skipHandling = false
1320
+    ): array {
1321
+        $limitPerPage = (int)$this->connection->ldapPagingSize;
1322
+        if (!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1323
+            $limitPerPage = $limit;
1324
+        }
1325
+
1326
+        if (!is_null($attr) && !is_array($attr)) {
1327
+            $attr = [mb_strtolower($attr, 'UTF-8')];
1328
+        }
1329
+
1330
+        /* ++ Fixing RHDS searches with pages with zero results ++
1331 1331
 		 * As we can have pages with zero results and/or pages with less
1332 1332
 		 * than $limit results but with a still valid server 'cookie',
1333 1333
 		 * loops through until we get $continue equals true and
1334 1334
 		 * $findings['count'] < $limit
1335 1335
 		 */
1336
-		$findings = [];
1337
-		$savedoffset = $offset;
1338
-		$iFoundItems = 0;
1339
-
1340
-		do {
1341
-			$search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
1342
-			if ($search === false) {
1343
-				return [];
1344
-			}
1345
-			list($sr, $pagedSearchOK) = $search;
1346
-			$cr = $this->connection->getConnectionResource();
1347
-
1348
-			if ($skipHandling) {
1349
-				//i.e. result do not need to be fetched, we just need the cookie
1350
-				//thus pass 1 or any other value as $iFoundItems because it is not
1351
-				//used
1352
-				$this->processPagedSearchStatus($sr, 1, $limitPerPage, $pagedSearchOK, $skipHandling);
1353
-				return [];
1354
-			}
1355
-
1356
-			$findings = array_merge($findings, $this->invokeLDAPMethod('getEntries', $cr, $sr));
1357
-			$iFoundItems = max($iFoundItems, $findings['count']);
1358
-			unset($findings['count']);
1359
-
1360
-			$continue = $this->processPagedSearchStatus($sr, $iFoundItems, $limitPerPage, $pagedSearchOK, $skipHandling);
1361
-			$offset += $limitPerPage;
1362
-		} while ($continue && $pagedSearchOK && ($limit === null || count($findings) < $limit));
1363
-
1364
-		// resetting offset
1365
-		$offset = $savedoffset;
1366
-
1367
-		// if we're here, probably no connection resource is returned.
1368
-		// to make Nextcloud behave nicely, we simply give back an empty array.
1369
-		if (is_null($findings)) {
1370
-			return [];
1371
-		}
1372
-
1373
-		if (!is_null($attr)) {
1374
-			$selection = [];
1375
-			$i = 0;
1376
-			foreach ($findings as $item) {
1377
-				if (!is_array($item)) {
1378
-					continue;
1379
-				}
1380
-				$item = \OCP\Util::mb_array_change_key_case($item, MB_CASE_LOWER, 'UTF-8');
1381
-				foreach ($attr as $key) {
1382
-					if (isset($item[$key])) {
1383
-						if (is_array($item[$key]) && isset($item[$key]['count'])) {
1384
-							unset($item[$key]['count']);
1385
-						}
1386
-						if ($key !== 'dn') {
1387
-							if ($this->resemblesDN($key)) {
1388
-								$selection[$i][$key] = $this->helper->sanitizeDN($item[$key]);
1389
-							} elseif ($key === 'objectguid' || $key === 'guid') {
1390
-								$selection[$i][$key] = [$this->convertObjectGUID2Str($item[$key][0])];
1391
-							} else {
1392
-								$selection[$i][$key] = $item[$key];
1393
-							}
1394
-						} else {
1395
-							$selection[$i][$key] = [$this->helper->sanitizeDN($item[$key])];
1396
-						}
1397
-					}
1398
-				}
1399
-				$i++;
1400
-			}
1401
-			$findings = $selection;
1402
-		}
1403
-		//we slice the findings, when
1404
-		//a) paged search unsuccessful, though attempted
1405
-		//b) no paged search, but limit set
1406
-		if ((!$this->getPagedSearchResultState()
1407
-				&& $pagedSearchOK)
1408
-			|| (
1409
-				!$pagedSearchOK
1410
-				&& !is_null($limit)
1411
-			)
1412
-		) {
1413
-			$findings = array_slice($findings, (int)$offset, $limit);
1414
-		}
1415
-		return $findings;
1416
-	}
1417
-
1418
-	/**
1419
-	 * @param string $name
1420
-	 * @return string
1421
-	 * @throws \InvalidArgumentException
1422
-	 */
1423
-	public function sanitizeUsername($name) {
1424
-		$name = trim($name);
1425
-
1426
-		if ($this->connection->ldapIgnoreNamingRules) {
1427
-			return $name;
1428
-		}
1429
-
1430
-		// Transliteration to ASCII
1431
-		$transliterated = @iconv('UTF-8', 'ASCII//TRANSLIT', $name);
1432
-		if ($transliterated !== false) {
1433
-			// depending on system config iconv can work or not
1434
-			$name = $transliterated;
1435
-		}
1436
-
1437
-		// Replacements
1438
-		$name = str_replace(' ', '_', $name);
1439
-
1440
-		// Every remaining disallowed characters will be removed
1441
-		$name = preg_replace('/[^a-zA-Z0-9_.@-]/u', '', $name);
1442
-
1443
-		if ($name === '') {
1444
-			throw new \InvalidArgumentException('provided name template for username does not contain any allowed characters');
1445
-		}
1446
-
1447
-		return $name;
1448
-	}
1449
-
1450
-	/**
1451
-	 * escapes (user provided) parts for LDAP filter
1452
-	 *
1453
-	 * @param string $input , the provided value
1454
-	 * @param bool $allowAsterisk whether in * at the beginning should be preserved
1455
-	 * @return string the escaped string
1456
-	 */
1457
-	public function escapeFilterPart($input, $allowAsterisk = false) {
1458
-		$asterisk = '';
1459
-		if ($allowAsterisk && strlen($input) > 0 && $input[0] === '*') {
1460
-			$asterisk = '*';
1461
-			$input = mb_substr($input, 1, null, 'UTF-8');
1462
-		}
1463
-		$search = ['*', '\\', '(', ')'];
1464
-		$replace = ['\\*', '\\\\', '\\(', '\\)'];
1465
-		return $asterisk . str_replace($search, $replace, $input);
1466
-	}
1467
-
1468
-	/**
1469
-	 * combines the input filters with AND
1470
-	 *
1471
-	 * @param string[] $filters the filters to connect
1472
-	 * @return string the combined filter
1473
-	 */
1474
-	public function combineFilterWithAnd($filters) {
1475
-		return $this->combineFilter($filters, '&');
1476
-	}
1477
-
1478
-	/**
1479
-	 * combines the input filters with OR
1480
-	 *
1481
-	 * @param string[] $filters the filters to connect
1482
-	 * @return string the combined filter
1483
-	 * Combines Filter arguments with OR
1484
-	 */
1485
-	public function combineFilterWithOr($filters) {
1486
-		return $this->combineFilter($filters, '|');
1487
-	}
1488
-
1489
-	/**
1490
-	 * combines the input filters with given operator
1491
-	 *
1492
-	 * @param string[] $filters the filters to connect
1493
-	 * @param string $operator either & or |
1494
-	 * @return string the combined filter
1495
-	 */
1496
-	private function combineFilter($filters, $operator) {
1497
-		$combinedFilter = '(' . $operator;
1498
-		foreach ($filters as $filter) {
1499
-			if ($filter !== '' && $filter[0] !== '(') {
1500
-				$filter = '(' . $filter . ')';
1501
-			}
1502
-			$combinedFilter .= $filter;
1503
-		}
1504
-		$combinedFilter .= ')';
1505
-		return $combinedFilter;
1506
-	}
1507
-
1508
-	/**
1509
-	 * creates a filter part for to perform search for users
1510
-	 *
1511
-	 * @param string $search the search term
1512
-	 * @return string the final filter part to use in LDAP searches
1513
-	 */
1514
-	public function getFilterPartForUserSearch($search) {
1515
-		return $this->getFilterPartForSearch($search,
1516
-			$this->connection->ldapAttributesForUserSearch,
1517
-			$this->connection->ldapUserDisplayName);
1518
-	}
1519
-
1520
-	/**
1521
-	 * creates a filter part for to perform search for groups
1522
-	 *
1523
-	 * @param string $search the search term
1524
-	 * @return string the final filter part to use in LDAP searches
1525
-	 */
1526
-	public function getFilterPartForGroupSearch($search) {
1527
-		return $this->getFilterPartForSearch($search,
1528
-			$this->connection->ldapAttributesForGroupSearch,
1529
-			$this->connection->ldapGroupDisplayName);
1530
-	}
1531
-
1532
-	/**
1533
-	 * creates a filter part for searches by splitting up the given search
1534
-	 * string into single words
1535
-	 *
1536
-	 * @param string $search the search term
1537
-	 * @param string[] $searchAttributes needs to have at least two attributes,
1538
-	 * otherwise it does not make sense :)
1539
-	 * @return string the final filter part to use in LDAP searches
1540
-	 * @throws \Exception
1541
-	 */
1542
-	private function getAdvancedFilterPartForSearch($search, $searchAttributes) {
1543
-		if (!is_array($searchAttributes) || count($searchAttributes) < 2) {
1544
-			throw new \Exception('searchAttributes must be an array with at least two string');
1545
-		}
1546
-		$searchWords = explode(' ', trim($search));
1547
-		$wordFilters = [];
1548
-		foreach ($searchWords as $word) {
1549
-			$word = $this->prepareSearchTerm($word);
1550
-			//every word needs to appear at least once
1551
-			$wordMatchOneAttrFilters = [];
1552
-			foreach ($searchAttributes as $attr) {
1553
-				$wordMatchOneAttrFilters[] = $attr . '=' . $word;
1554
-			}
1555
-			$wordFilters[] = $this->combineFilterWithOr($wordMatchOneAttrFilters);
1556
-		}
1557
-		return $this->combineFilterWithAnd($wordFilters);
1558
-	}
1559
-
1560
-	/**
1561
-	 * creates a filter part for searches
1562
-	 *
1563
-	 * @param string $search the search term
1564
-	 * @param string[]|null $searchAttributes
1565
-	 * @param string $fallbackAttribute a fallback attribute in case the user
1566
-	 * did not define search attributes. Typically the display name attribute.
1567
-	 * @return string the final filter part to use in LDAP searches
1568
-	 */
1569
-	private function getFilterPartForSearch($search, $searchAttributes, $fallbackAttribute) {
1570
-		$filter = [];
1571
-		$haveMultiSearchAttributes = (is_array($searchAttributes) && count($searchAttributes) > 0);
1572
-		if ($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) {
1573
-			try {
1574
-				return $this->getAdvancedFilterPartForSearch($search, $searchAttributes);
1575
-			} catch (\Exception $e) {
1576
-				\OCP\Util::writeLog(
1577
-					'user_ldap',
1578
-					'Creating advanced filter for search failed, falling back to simple method.',
1579
-					ILogger::INFO
1580
-				);
1581
-			}
1582
-		}
1583
-
1584
-		$search = $this->prepareSearchTerm($search);
1585
-		if (!is_array($searchAttributes) || count($searchAttributes) === 0) {
1586
-			if ($fallbackAttribute === '') {
1587
-				return '';
1588
-			}
1589
-			$filter[] = $fallbackAttribute . '=' . $search;
1590
-		} else {
1591
-			foreach ($searchAttributes as $attribute) {
1592
-				$filter[] = $attribute . '=' . $search;
1593
-			}
1594
-		}
1595
-		if (count($filter) === 1) {
1596
-			return '(' . $filter[0] . ')';
1597
-		}
1598
-		return $this->combineFilterWithOr($filter);
1599
-	}
1600
-
1601
-	/**
1602
-	 * returns the search term depending on whether we are allowed
1603
-	 * list users found by ldap with the current input appended by
1604
-	 * a *
1605
-	 *
1606
-	 * @return string
1607
-	 */
1608
-	private function prepareSearchTerm($term) {
1609
-		$config = \OC::$server->getConfig();
1610
-
1611
-		$allowEnum = $config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes');
1612
-
1613
-		$result = $term;
1614
-		if ($term === '') {
1615
-			$result = '*';
1616
-		} elseif ($allowEnum !== 'no') {
1617
-			$result = $term . '*';
1618
-		}
1619
-		return $result;
1620
-	}
1621
-
1622
-	/**
1623
-	 * returns the filter used for counting users
1624
-	 *
1625
-	 * @return string
1626
-	 */
1627
-	public function getFilterForUserCount() {
1628
-		$filter = $this->combineFilterWithAnd([
1629
-			$this->connection->ldapUserFilter,
1630
-			$this->connection->ldapUserDisplayName . '=*'
1631
-		]);
1632
-
1633
-		return $filter;
1634
-	}
1635
-
1636
-	/**
1637
-	 * @param string $name
1638
-	 * @param string $password
1639
-	 * @return bool
1640
-	 */
1641
-	public function areCredentialsValid($name, $password) {
1642
-		$name = $this->helper->DNasBaseParameter($name);
1643
-		$testConnection = clone $this->connection;
1644
-		$credentials = [
1645
-			'ldapAgentName' => $name,
1646
-			'ldapAgentPassword' => $password
1647
-		];
1648
-		if (!$testConnection->setConfiguration($credentials)) {
1649
-			return false;
1650
-		}
1651
-		return $testConnection->bind();
1652
-	}
1653
-
1654
-	/**
1655
-	 * reverse lookup of a DN given a known UUID
1656
-	 *
1657
-	 * @param string $uuid
1658
-	 * @return string
1659
-	 * @throws \Exception
1660
-	 */
1661
-	public function getUserDnByUuid($uuid) {
1662
-		$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1663
-		$filter = $this->connection->ldapUserFilter;
1664
-		$bases = $this->connection->ldapBaseUsers;
1665
-
1666
-		if ($this->connection->ldapUuidUserAttribute === 'auto' && $uuidOverride === '') {
1667
-			// Sacrebleu! The UUID attribute is unknown :( We need first an
1668
-			// existing DN to be able to reliably detect it.
1669
-			foreach ($bases as $base) {
1670
-				$result = $this->search($filter, $base, ['dn'], 1);
1671
-				if (!isset($result[0]) || !isset($result[0]['dn'])) {
1672
-					continue;
1673
-				}
1674
-				$dn = $result[0]['dn'][0];
1675
-				if ($hasFound = $this->detectUuidAttribute($dn, true)) {
1676
-					break;
1677
-				}
1678
-			}
1679
-			if (!isset($hasFound) || !$hasFound) {
1680
-				throw new \Exception('Cannot determine UUID attribute');
1681
-			}
1682
-		} else {
1683
-			// The UUID attribute is either known or an override is given.
1684
-			// By calling this method we ensure that $this->connection->$uuidAttr
1685
-			// is definitely set
1686
-			if (!$this->detectUuidAttribute('', true)) {
1687
-				throw new \Exception('Cannot determine UUID attribute');
1688
-			}
1689
-		}
1690
-
1691
-		$uuidAttr = $this->connection->ldapUuidUserAttribute;
1692
-		if ($uuidAttr === 'guid' || $uuidAttr === 'objectguid') {
1693
-			$uuid = $this->formatGuid2ForFilterUser($uuid);
1694
-		}
1695
-
1696
-		$filter = $uuidAttr . '=' . $uuid;
1697
-		$result = $this->searchUsers($filter, ['dn'], 2);
1698
-		if (is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) {
1699
-			// we put the count into account to make sure that this is
1700
-			// really unique
1701
-			return $result[0]['dn'][0];
1702
-		}
1703
-
1704
-		throw new \Exception('Cannot determine UUID attribute');
1705
-	}
1706
-
1707
-	/**
1708
-	 * auto-detects the directory's UUID attribute
1709
-	 *
1710
-	 * @param string $dn a known DN used to check against
1711
-	 * @param bool $isUser
1712
-	 * @param bool $force the detection should be run, even if it is not set to auto
1713
-	 * @param array|null $ldapRecord
1714
-	 * @return bool true on success, false otherwise
1715
-	 * @throws ServerNotAvailableException
1716
-	 */
1717
-	private function detectUuidAttribute($dn, $isUser = true, $force = false, array $ldapRecord = null) {
1718
-		if ($isUser) {
1719
-			$uuidAttr = 'ldapUuidUserAttribute';
1720
-			$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1721
-		} else {
1722
-			$uuidAttr = 'ldapUuidGroupAttribute';
1723
-			$uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1724
-		}
1725
-
1726
-		if (!$force) {
1727
-			if ($this->connection->$uuidAttr !== 'auto') {
1728
-				return true;
1729
-			} elseif (is_string($uuidOverride) && trim($uuidOverride) !== '') {
1730
-				$this->connection->$uuidAttr = $uuidOverride;
1731
-				return true;
1732
-			}
1733
-
1734
-			$attribute = $this->connection->getFromCache($uuidAttr);
1735
-			if (!$attribute === null) {
1736
-				$this->connection->$uuidAttr = $attribute;
1737
-				return true;
1738
-			}
1739
-		}
1740
-
1741
-		foreach (self::UUID_ATTRIBUTES as $attribute) {
1742
-			if ($ldapRecord !== null) {
1743
-				// we have the info from LDAP already, we don't need to talk to the server again
1744
-				if (isset($ldapRecord[$attribute])) {
1745
-					$this->connection->$uuidAttr = $attribute;
1746
-					return true;
1747
-				}
1748
-			}
1749
-
1750
-			$value = $this->readAttribute($dn, $attribute);
1751
-			if (is_array($value) && isset($value[0]) && !empty($value[0])) {
1752
-				\OC::$server->getLogger()->debug(
1753
-					'Setting {attribute} as {subject}',
1754
-					[
1755
-						'app' => 'user_ldap',
1756
-						'attribute' => $attribute,
1757
-						'subject' => $uuidAttr
1758
-					]
1759
-				);
1760
-				$this->connection->$uuidAttr = $attribute;
1761
-				$this->connection->writeToCache($uuidAttr, $attribute);
1762
-				return true;
1763
-			}
1764
-		}
1765
-		\OC::$server->getLogger()->debug('Could not autodetect the UUID attribute', ['app' => 'user_ldap']);
1766
-
1767
-		return false;
1768
-	}
1769
-
1770
-	/**
1771
-	 * @param string $dn
1772
-	 * @param bool $isUser
1773
-	 * @param null $ldapRecord
1774
-	 * @return bool|string
1775
-	 * @throws ServerNotAvailableException
1776
-	 */
1777
-	public function getUUID($dn, $isUser = true, $ldapRecord = null) {
1778
-		if ($isUser) {
1779
-			$uuidAttr = 'ldapUuidUserAttribute';
1780
-			$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1781
-		} else {
1782
-			$uuidAttr = 'ldapUuidGroupAttribute';
1783
-			$uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1784
-		}
1785
-
1786
-		$uuid = false;
1787
-		if ($this->detectUuidAttribute($dn, $isUser, false, $ldapRecord)) {
1788
-			$attr = $this->connection->$uuidAttr;
1789
-			$uuid = isset($ldapRecord[$attr]) ? $ldapRecord[$attr] : $this->readAttribute($dn, $attr);
1790
-			if (!is_array($uuid)
1791
-				&& $uuidOverride !== ''
1792
-				&& $this->detectUuidAttribute($dn, $isUser, true, $ldapRecord)) {
1793
-				$uuid = isset($ldapRecord[$this->connection->$uuidAttr])
1794
-					? $ldapRecord[$this->connection->$uuidAttr]
1795
-					: $this->readAttribute($dn, $this->connection->$uuidAttr);
1796
-			}
1797
-			if (is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) {
1798
-				$uuid = $uuid[0];
1799
-			}
1800
-		}
1801
-
1802
-		return $uuid;
1803
-	}
1804
-
1805
-	/**
1806
-	 * converts a binary ObjectGUID into a string representation
1807
-	 *
1808
-	 * @param string $oguid the ObjectGUID in it's binary form as retrieved from AD
1809
-	 * @return string
1810
-	 * @link http://www.php.net/manual/en/function.ldap-get-values-len.php#73198
1811
-	 */
1812
-	private function convertObjectGUID2Str($oguid) {
1813
-		$hex_guid = bin2hex($oguid);
1814
-		$hex_guid_to_guid_str = '';
1815
-		for ($k = 1; $k <= 4; ++$k) {
1816
-			$hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2);
1817
-		}
1818
-		$hex_guid_to_guid_str .= '-';
1819
-		for ($k = 1; $k <= 2; ++$k) {
1820
-			$hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2);
1821
-		}
1822
-		$hex_guid_to_guid_str .= '-';
1823
-		for ($k = 1; $k <= 2; ++$k) {
1824
-			$hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2);
1825
-		}
1826
-		$hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4);
1827
-		$hex_guid_to_guid_str .= '-' . substr($hex_guid, 20);
1828
-
1829
-		return strtoupper($hex_guid_to_guid_str);
1830
-	}
1831
-
1832
-	/**
1833
-	 * the first three blocks of the string-converted GUID happen to be in
1834
-	 * reverse order. In order to use it in a filter, this needs to be
1835
-	 * corrected. Furthermore the dashes need to be replaced and \\ preprended
1836
-	 * to every two hax figures.
1837
-	 *
1838
-	 * If an invalid string is passed, it will be returned without change.
1839
-	 *
1840
-	 * @param string $guid
1841
-	 * @return string
1842
-	 */
1843
-	public function formatGuid2ForFilterUser($guid) {
1844
-		if (!is_string($guid)) {
1845
-			throw new \InvalidArgumentException('String expected');
1846
-		}
1847
-		$blocks = explode('-', $guid);
1848
-		if (count($blocks) !== 5) {
1849
-			/*
1336
+        $findings = [];
1337
+        $savedoffset = $offset;
1338
+        $iFoundItems = 0;
1339
+
1340
+        do {
1341
+            $search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
1342
+            if ($search === false) {
1343
+                return [];
1344
+            }
1345
+            list($sr, $pagedSearchOK) = $search;
1346
+            $cr = $this->connection->getConnectionResource();
1347
+
1348
+            if ($skipHandling) {
1349
+                //i.e. result do not need to be fetched, we just need the cookie
1350
+                //thus pass 1 or any other value as $iFoundItems because it is not
1351
+                //used
1352
+                $this->processPagedSearchStatus($sr, 1, $limitPerPage, $pagedSearchOK, $skipHandling);
1353
+                return [];
1354
+            }
1355
+
1356
+            $findings = array_merge($findings, $this->invokeLDAPMethod('getEntries', $cr, $sr));
1357
+            $iFoundItems = max($iFoundItems, $findings['count']);
1358
+            unset($findings['count']);
1359
+
1360
+            $continue = $this->processPagedSearchStatus($sr, $iFoundItems, $limitPerPage, $pagedSearchOK, $skipHandling);
1361
+            $offset += $limitPerPage;
1362
+        } while ($continue && $pagedSearchOK && ($limit === null || count($findings) < $limit));
1363
+
1364
+        // resetting offset
1365
+        $offset = $savedoffset;
1366
+
1367
+        // if we're here, probably no connection resource is returned.
1368
+        // to make Nextcloud behave nicely, we simply give back an empty array.
1369
+        if (is_null($findings)) {
1370
+            return [];
1371
+        }
1372
+
1373
+        if (!is_null($attr)) {
1374
+            $selection = [];
1375
+            $i = 0;
1376
+            foreach ($findings as $item) {
1377
+                if (!is_array($item)) {
1378
+                    continue;
1379
+                }
1380
+                $item = \OCP\Util::mb_array_change_key_case($item, MB_CASE_LOWER, 'UTF-8');
1381
+                foreach ($attr as $key) {
1382
+                    if (isset($item[$key])) {
1383
+                        if (is_array($item[$key]) && isset($item[$key]['count'])) {
1384
+                            unset($item[$key]['count']);
1385
+                        }
1386
+                        if ($key !== 'dn') {
1387
+                            if ($this->resemblesDN($key)) {
1388
+                                $selection[$i][$key] = $this->helper->sanitizeDN($item[$key]);
1389
+                            } elseif ($key === 'objectguid' || $key === 'guid') {
1390
+                                $selection[$i][$key] = [$this->convertObjectGUID2Str($item[$key][0])];
1391
+                            } else {
1392
+                                $selection[$i][$key] = $item[$key];
1393
+                            }
1394
+                        } else {
1395
+                            $selection[$i][$key] = [$this->helper->sanitizeDN($item[$key])];
1396
+                        }
1397
+                    }
1398
+                }
1399
+                $i++;
1400
+            }
1401
+            $findings = $selection;
1402
+        }
1403
+        //we slice the findings, when
1404
+        //a) paged search unsuccessful, though attempted
1405
+        //b) no paged search, but limit set
1406
+        if ((!$this->getPagedSearchResultState()
1407
+                && $pagedSearchOK)
1408
+            || (
1409
+                !$pagedSearchOK
1410
+                && !is_null($limit)
1411
+            )
1412
+        ) {
1413
+            $findings = array_slice($findings, (int)$offset, $limit);
1414
+        }
1415
+        return $findings;
1416
+    }
1417
+
1418
+    /**
1419
+     * @param string $name
1420
+     * @return string
1421
+     * @throws \InvalidArgumentException
1422
+     */
1423
+    public function sanitizeUsername($name) {
1424
+        $name = trim($name);
1425
+
1426
+        if ($this->connection->ldapIgnoreNamingRules) {
1427
+            return $name;
1428
+        }
1429
+
1430
+        // Transliteration to ASCII
1431
+        $transliterated = @iconv('UTF-8', 'ASCII//TRANSLIT', $name);
1432
+        if ($transliterated !== false) {
1433
+            // depending on system config iconv can work or not
1434
+            $name = $transliterated;
1435
+        }
1436
+
1437
+        // Replacements
1438
+        $name = str_replace(' ', '_', $name);
1439
+
1440
+        // Every remaining disallowed characters will be removed
1441
+        $name = preg_replace('/[^a-zA-Z0-9_.@-]/u', '', $name);
1442
+
1443
+        if ($name === '') {
1444
+            throw new \InvalidArgumentException('provided name template for username does not contain any allowed characters');
1445
+        }
1446
+
1447
+        return $name;
1448
+    }
1449
+
1450
+    /**
1451
+     * escapes (user provided) parts for LDAP filter
1452
+     *
1453
+     * @param string $input , the provided value
1454
+     * @param bool $allowAsterisk whether in * at the beginning should be preserved
1455
+     * @return string the escaped string
1456
+     */
1457
+    public function escapeFilterPart($input, $allowAsterisk = false) {
1458
+        $asterisk = '';
1459
+        if ($allowAsterisk && strlen($input) > 0 && $input[0] === '*') {
1460
+            $asterisk = '*';
1461
+            $input = mb_substr($input, 1, null, 'UTF-8');
1462
+        }
1463
+        $search = ['*', '\\', '(', ')'];
1464
+        $replace = ['\\*', '\\\\', '\\(', '\\)'];
1465
+        return $asterisk . str_replace($search, $replace, $input);
1466
+    }
1467
+
1468
+    /**
1469
+     * combines the input filters with AND
1470
+     *
1471
+     * @param string[] $filters the filters to connect
1472
+     * @return string the combined filter
1473
+     */
1474
+    public function combineFilterWithAnd($filters) {
1475
+        return $this->combineFilter($filters, '&');
1476
+    }
1477
+
1478
+    /**
1479
+     * combines the input filters with OR
1480
+     *
1481
+     * @param string[] $filters the filters to connect
1482
+     * @return string the combined filter
1483
+     * Combines Filter arguments with OR
1484
+     */
1485
+    public function combineFilterWithOr($filters) {
1486
+        return $this->combineFilter($filters, '|');
1487
+    }
1488
+
1489
+    /**
1490
+     * combines the input filters with given operator
1491
+     *
1492
+     * @param string[] $filters the filters to connect
1493
+     * @param string $operator either & or |
1494
+     * @return string the combined filter
1495
+     */
1496
+    private function combineFilter($filters, $operator) {
1497
+        $combinedFilter = '(' . $operator;
1498
+        foreach ($filters as $filter) {
1499
+            if ($filter !== '' && $filter[0] !== '(') {
1500
+                $filter = '(' . $filter . ')';
1501
+            }
1502
+            $combinedFilter .= $filter;
1503
+        }
1504
+        $combinedFilter .= ')';
1505
+        return $combinedFilter;
1506
+    }
1507
+
1508
+    /**
1509
+     * creates a filter part for to perform search for users
1510
+     *
1511
+     * @param string $search the search term
1512
+     * @return string the final filter part to use in LDAP searches
1513
+     */
1514
+    public function getFilterPartForUserSearch($search) {
1515
+        return $this->getFilterPartForSearch($search,
1516
+            $this->connection->ldapAttributesForUserSearch,
1517
+            $this->connection->ldapUserDisplayName);
1518
+    }
1519
+
1520
+    /**
1521
+     * creates a filter part for to perform search for groups
1522
+     *
1523
+     * @param string $search the search term
1524
+     * @return string the final filter part to use in LDAP searches
1525
+     */
1526
+    public function getFilterPartForGroupSearch($search) {
1527
+        return $this->getFilterPartForSearch($search,
1528
+            $this->connection->ldapAttributesForGroupSearch,
1529
+            $this->connection->ldapGroupDisplayName);
1530
+    }
1531
+
1532
+    /**
1533
+     * creates a filter part for searches by splitting up the given search
1534
+     * string into single words
1535
+     *
1536
+     * @param string $search the search term
1537
+     * @param string[] $searchAttributes needs to have at least two attributes,
1538
+     * otherwise it does not make sense :)
1539
+     * @return string the final filter part to use in LDAP searches
1540
+     * @throws \Exception
1541
+     */
1542
+    private function getAdvancedFilterPartForSearch($search, $searchAttributes) {
1543
+        if (!is_array($searchAttributes) || count($searchAttributes) < 2) {
1544
+            throw new \Exception('searchAttributes must be an array with at least two string');
1545
+        }
1546
+        $searchWords = explode(' ', trim($search));
1547
+        $wordFilters = [];
1548
+        foreach ($searchWords as $word) {
1549
+            $word = $this->prepareSearchTerm($word);
1550
+            //every word needs to appear at least once
1551
+            $wordMatchOneAttrFilters = [];
1552
+            foreach ($searchAttributes as $attr) {
1553
+                $wordMatchOneAttrFilters[] = $attr . '=' . $word;
1554
+            }
1555
+            $wordFilters[] = $this->combineFilterWithOr($wordMatchOneAttrFilters);
1556
+        }
1557
+        return $this->combineFilterWithAnd($wordFilters);
1558
+    }
1559
+
1560
+    /**
1561
+     * creates a filter part for searches
1562
+     *
1563
+     * @param string $search the search term
1564
+     * @param string[]|null $searchAttributes
1565
+     * @param string $fallbackAttribute a fallback attribute in case the user
1566
+     * did not define search attributes. Typically the display name attribute.
1567
+     * @return string the final filter part to use in LDAP searches
1568
+     */
1569
+    private function getFilterPartForSearch($search, $searchAttributes, $fallbackAttribute) {
1570
+        $filter = [];
1571
+        $haveMultiSearchAttributes = (is_array($searchAttributes) && count($searchAttributes) > 0);
1572
+        if ($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) {
1573
+            try {
1574
+                return $this->getAdvancedFilterPartForSearch($search, $searchAttributes);
1575
+            } catch (\Exception $e) {
1576
+                \OCP\Util::writeLog(
1577
+                    'user_ldap',
1578
+                    'Creating advanced filter for search failed, falling back to simple method.',
1579
+                    ILogger::INFO
1580
+                );
1581
+            }
1582
+        }
1583
+
1584
+        $search = $this->prepareSearchTerm($search);
1585
+        if (!is_array($searchAttributes) || count($searchAttributes) === 0) {
1586
+            if ($fallbackAttribute === '') {
1587
+                return '';
1588
+            }
1589
+            $filter[] = $fallbackAttribute . '=' . $search;
1590
+        } else {
1591
+            foreach ($searchAttributes as $attribute) {
1592
+                $filter[] = $attribute . '=' . $search;
1593
+            }
1594
+        }
1595
+        if (count($filter) === 1) {
1596
+            return '(' . $filter[0] . ')';
1597
+        }
1598
+        return $this->combineFilterWithOr($filter);
1599
+    }
1600
+
1601
+    /**
1602
+     * returns the search term depending on whether we are allowed
1603
+     * list users found by ldap with the current input appended by
1604
+     * a *
1605
+     *
1606
+     * @return string
1607
+     */
1608
+    private function prepareSearchTerm($term) {
1609
+        $config = \OC::$server->getConfig();
1610
+
1611
+        $allowEnum = $config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes');
1612
+
1613
+        $result = $term;
1614
+        if ($term === '') {
1615
+            $result = '*';
1616
+        } elseif ($allowEnum !== 'no') {
1617
+            $result = $term . '*';
1618
+        }
1619
+        return $result;
1620
+    }
1621
+
1622
+    /**
1623
+     * returns the filter used for counting users
1624
+     *
1625
+     * @return string
1626
+     */
1627
+    public function getFilterForUserCount() {
1628
+        $filter = $this->combineFilterWithAnd([
1629
+            $this->connection->ldapUserFilter,
1630
+            $this->connection->ldapUserDisplayName . '=*'
1631
+        ]);
1632
+
1633
+        return $filter;
1634
+    }
1635
+
1636
+    /**
1637
+     * @param string $name
1638
+     * @param string $password
1639
+     * @return bool
1640
+     */
1641
+    public function areCredentialsValid($name, $password) {
1642
+        $name = $this->helper->DNasBaseParameter($name);
1643
+        $testConnection = clone $this->connection;
1644
+        $credentials = [
1645
+            'ldapAgentName' => $name,
1646
+            'ldapAgentPassword' => $password
1647
+        ];
1648
+        if (!$testConnection->setConfiguration($credentials)) {
1649
+            return false;
1650
+        }
1651
+        return $testConnection->bind();
1652
+    }
1653
+
1654
+    /**
1655
+     * reverse lookup of a DN given a known UUID
1656
+     *
1657
+     * @param string $uuid
1658
+     * @return string
1659
+     * @throws \Exception
1660
+     */
1661
+    public function getUserDnByUuid($uuid) {
1662
+        $uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1663
+        $filter = $this->connection->ldapUserFilter;
1664
+        $bases = $this->connection->ldapBaseUsers;
1665
+
1666
+        if ($this->connection->ldapUuidUserAttribute === 'auto' && $uuidOverride === '') {
1667
+            // Sacrebleu! The UUID attribute is unknown :( We need first an
1668
+            // existing DN to be able to reliably detect it.
1669
+            foreach ($bases as $base) {
1670
+                $result = $this->search($filter, $base, ['dn'], 1);
1671
+                if (!isset($result[0]) || !isset($result[0]['dn'])) {
1672
+                    continue;
1673
+                }
1674
+                $dn = $result[0]['dn'][0];
1675
+                if ($hasFound = $this->detectUuidAttribute($dn, true)) {
1676
+                    break;
1677
+                }
1678
+            }
1679
+            if (!isset($hasFound) || !$hasFound) {
1680
+                throw new \Exception('Cannot determine UUID attribute');
1681
+            }
1682
+        } else {
1683
+            // The UUID attribute is either known or an override is given.
1684
+            // By calling this method we ensure that $this->connection->$uuidAttr
1685
+            // is definitely set
1686
+            if (!$this->detectUuidAttribute('', true)) {
1687
+                throw new \Exception('Cannot determine UUID attribute');
1688
+            }
1689
+        }
1690
+
1691
+        $uuidAttr = $this->connection->ldapUuidUserAttribute;
1692
+        if ($uuidAttr === 'guid' || $uuidAttr === 'objectguid') {
1693
+            $uuid = $this->formatGuid2ForFilterUser($uuid);
1694
+        }
1695
+
1696
+        $filter = $uuidAttr . '=' . $uuid;
1697
+        $result = $this->searchUsers($filter, ['dn'], 2);
1698
+        if (is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) {
1699
+            // we put the count into account to make sure that this is
1700
+            // really unique
1701
+            return $result[0]['dn'][0];
1702
+        }
1703
+
1704
+        throw new \Exception('Cannot determine UUID attribute');
1705
+    }
1706
+
1707
+    /**
1708
+     * auto-detects the directory's UUID attribute
1709
+     *
1710
+     * @param string $dn a known DN used to check against
1711
+     * @param bool $isUser
1712
+     * @param bool $force the detection should be run, even if it is not set to auto
1713
+     * @param array|null $ldapRecord
1714
+     * @return bool true on success, false otherwise
1715
+     * @throws ServerNotAvailableException
1716
+     */
1717
+    private function detectUuidAttribute($dn, $isUser = true, $force = false, array $ldapRecord = null) {
1718
+        if ($isUser) {
1719
+            $uuidAttr = 'ldapUuidUserAttribute';
1720
+            $uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1721
+        } else {
1722
+            $uuidAttr = 'ldapUuidGroupAttribute';
1723
+            $uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1724
+        }
1725
+
1726
+        if (!$force) {
1727
+            if ($this->connection->$uuidAttr !== 'auto') {
1728
+                return true;
1729
+            } elseif (is_string($uuidOverride) && trim($uuidOverride) !== '') {
1730
+                $this->connection->$uuidAttr = $uuidOverride;
1731
+                return true;
1732
+            }
1733
+
1734
+            $attribute = $this->connection->getFromCache($uuidAttr);
1735
+            if (!$attribute === null) {
1736
+                $this->connection->$uuidAttr = $attribute;
1737
+                return true;
1738
+            }
1739
+        }
1740
+
1741
+        foreach (self::UUID_ATTRIBUTES as $attribute) {
1742
+            if ($ldapRecord !== null) {
1743
+                // we have the info from LDAP already, we don't need to talk to the server again
1744
+                if (isset($ldapRecord[$attribute])) {
1745
+                    $this->connection->$uuidAttr = $attribute;
1746
+                    return true;
1747
+                }
1748
+            }
1749
+
1750
+            $value = $this->readAttribute($dn, $attribute);
1751
+            if (is_array($value) && isset($value[0]) && !empty($value[0])) {
1752
+                \OC::$server->getLogger()->debug(
1753
+                    'Setting {attribute} as {subject}',
1754
+                    [
1755
+                        'app' => 'user_ldap',
1756
+                        'attribute' => $attribute,
1757
+                        'subject' => $uuidAttr
1758
+                    ]
1759
+                );
1760
+                $this->connection->$uuidAttr = $attribute;
1761
+                $this->connection->writeToCache($uuidAttr, $attribute);
1762
+                return true;
1763
+            }
1764
+        }
1765
+        \OC::$server->getLogger()->debug('Could not autodetect the UUID attribute', ['app' => 'user_ldap']);
1766
+
1767
+        return false;
1768
+    }
1769
+
1770
+    /**
1771
+     * @param string $dn
1772
+     * @param bool $isUser
1773
+     * @param null $ldapRecord
1774
+     * @return bool|string
1775
+     * @throws ServerNotAvailableException
1776
+     */
1777
+    public function getUUID($dn, $isUser = true, $ldapRecord = null) {
1778
+        if ($isUser) {
1779
+            $uuidAttr = 'ldapUuidUserAttribute';
1780
+            $uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1781
+        } else {
1782
+            $uuidAttr = 'ldapUuidGroupAttribute';
1783
+            $uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1784
+        }
1785
+
1786
+        $uuid = false;
1787
+        if ($this->detectUuidAttribute($dn, $isUser, false, $ldapRecord)) {
1788
+            $attr = $this->connection->$uuidAttr;
1789
+            $uuid = isset($ldapRecord[$attr]) ? $ldapRecord[$attr] : $this->readAttribute($dn, $attr);
1790
+            if (!is_array($uuid)
1791
+                && $uuidOverride !== ''
1792
+                && $this->detectUuidAttribute($dn, $isUser, true, $ldapRecord)) {
1793
+                $uuid = isset($ldapRecord[$this->connection->$uuidAttr])
1794
+                    ? $ldapRecord[$this->connection->$uuidAttr]
1795
+                    : $this->readAttribute($dn, $this->connection->$uuidAttr);
1796
+            }
1797
+            if (is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) {
1798
+                $uuid = $uuid[0];
1799
+            }
1800
+        }
1801
+
1802
+        return $uuid;
1803
+    }
1804
+
1805
+    /**
1806
+     * converts a binary ObjectGUID into a string representation
1807
+     *
1808
+     * @param string $oguid the ObjectGUID in it's binary form as retrieved from AD
1809
+     * @return string
1810
+     * @link http://www.php.net/manual/en/function.ldap-get-values-len.php#73198
1811
+     */
1812
+    private function convertObjectGUID2Str($oguid) {
1813
+        $hex_guid = bin2hex($oguid);
1814
+        $hex_guid_to_guid_str = '';
1815
+        for ($k = 1; $k <= 4; ++$k) {
1816
+            $hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2);
1817
+        }
1818
+        $hex_guid_to_guid_str .= '-';
1819
+        for ($k = 1; $k <= 2; ++$k) {
1820
+            $hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2);
1821
+        }
1822
+        $hex_guid_to_guid_str .= '-';
1823
+        for ($k = 1; $k <= 2; ++$k) {
1824
+            $hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2);
1825
+        }
1826
+        $hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4);
1827
+        $hex_guid_to_guid_str .= '-' . substr($hex_guid, 20);
1828
+
1829
+        return strtoupper($hex_guid_to_guid_str);
1830
+    }
1831
+
1832
+    /**
1833
+     * the first three blocks of the string-converted GUID happen to be in
1834
+     * reverse order. In order to use it in a filter, this needs to be
1835
+     * corrected. Furthermore the dashes need to be replaced and \\ preprended
1836
+     * to every two hax figures.
1837
+     *
1838
+     * If an invalid string is passed, it will be returned without change.
1839
+     *
1840
+     * @param string $guid
1841
+     * @return string
1842
+     */
1843
+    public function formatGuid2ForFilterUser($guid) {
1844
+        if (!is_string($guid)) {
1845
+            throw new \InvalidArgumentException('String expected');
1846
+        }
1847
+        $blocks = explode('-', $guid);
1848
+        if (count($blocks) !== 5) {
1849
+            /*
1850 1850
 			 * Why not throw an Exception instead? This method is a utility
1851 1851
 			 * called only when trying to figure out whether a "missing" known
1852 1852
 			 * LDAP user was or was not renamed on the LDAP server. And this
@@ -1857,247 +1857,247 @@  discard block
 block discarded – undo
1857 1857
 			 * an exception here would kill the experience for a valid, acting
1858 1858
 			 * user. Instead we write a log message.
1859 1859
 			 */
1860
-			\OC::$server->getLogger()->info(
1861
-				'Passed string does not resemble a valid GUID. Known UUID ' .
1862
-				'({uuid}) probably does not match UUID configuration.',
1863
-				['app' => 'user_ldap', 'uuid' => $guid]
1864
-			);
1865
-			return $guid;
1866
-		}
1867
-		for ($i = 0; $i < 3; $i++) {
1868
-			$pairs = str_split($blocks[$i], 2);
1869
-			$pairs = array_reverse($pairs);
1870
-			$blocks[$i] = implode('', $pairs);
1871
-		}
1872
-		for ($i = 0; $i < 5; $i++) {
1873
-			$pairs = str_split($blocks[$i], 2);
1874
-			$blocks[$i] = '\\' . implode('\\', $pairs);
1875
-		}
1876
-		return implode('', $blocks);
1877
-	}
1878
-
1879
-	/**
1880
-	 * gets a SID of the domain of the given dn
1881
-	 *
1882
-	 * @param string $dn
1883
-	 * @return string|bool
1884
-	 * @throws ServerNotAvailableException
1885
-	 */
1886
-	public function getSID($dn) {
1887
-		$domainDN = $this->getDomainDNFromDN($dn);
1888
-		$cacheKey = 'getSID-' . $domainDN;
1889
-		$sid = $this->connection->getFromCache($cacheKey);
1890
-		if (!is_null($sid)) {
1891
-			return $sid;
1892
-		}
1893
-
1894
-		$objectSid = $this->readAttribute($domainDN, 'objectsid');
1895
-		if (!is_array($objectSid) || empty($objectSid)) {
1896
-			$this->connection->writeToCache($cacheKey, false);
1897
-			return false;
1898
-		}
1899
-		$domainObjectSid = $this->convertSID2Str($objectSid[0]);
1900
-		$this->connection->writeToCache($cacheKey, $domainObjectSid);
1901
-
1902
-		return $domainObjectSid;
1903
-	}
1904
-
1905
-	/**
1906
-	 * converts a binary SID into a string representation
1907
-	 *
1908
-	 * @param string $sid
1909
-	 * @return string
1910
-	 */
1911
-	public function convertSID2Str($sid) {
1912
-		// The format of a SID binary string is as follows:
1913
-		// 1 byte for the revision level
1914
-		// 1 byte for the number n of variable sub-ids
1915
-		// 6 bytes for identifier authority value
1916
-		// n*4 bytes for n sub-ids
1917
-		//
1918
-		// Example: 010400000000000515000000a681e50e4d6c6c2bca32055f
1919
-		//  Legend: RRNNAAAAAAAAAAAA11111111222222223333333344444444
1920
-		$revision = ord($sid[0]);
1921
-		$numberSubID = ord($sid[1]);
1922
-
1923
-		$subIdStart = 8; // 1 + 1 + 6
1924
-		$subIdLength = 4;
1925
-		if (strlen($sid) !== $subIdStart + $subIdLength * $numberSubID) {
1926
-			// Incorrect number of bytes present.
1927
-			return '';
1928
-		}
1929
-
1930
-		// 6 bytes = 48 bits can be represented using floats without loss of
1931
-		// precision (see https://gist.github.com/bantu/886ac680b0aef5812f71)
1932
-		$iav = number_format(hexdec(bin2hex(substr($sid, 2, 6))), 0, '', '');
1933
-
1934
-		$subIDs = [];
1935
-		for ($i = 0; $i < $numberSubID; $i++) {
1936
-			$subID = unpack('V', substr($sid, $subIdStart + $subIdLength * $i, $subIdLength));
1937
-			$subIDs[] = sprintf('%u', $subID[1]);
1938
-		}
1939
-
1940
-		// Result for example above: S-1-5-21-249921958-728525901-1594176202
1941
-		return sprintf('S-%d-%s-%s', $revision, $iav, implode('-', $subIDs));
1942
-	}
1943
-
1944
-	/**
1945
-	 * checks if the given DN is part of the given base DN(s)
1946
-	 *
1947
-	 * @param string $dn the DN
1948
-	 * @param string[] $bases array containing the allowed base DN or DNs
1949
-	 * @return bool
1950
-	 */
1951
-	public function isDNPartOfBase($dn, $bases) {
1952
-		$belongsToBase = false;
1953
-		$bases = $this->helper->sanitizeDN($bases);
1954
-
1955
-		foreach ($bases as $base) {
1956
-			$belongsToBase = true;
1957
-			if (mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8') - mb_strlen($base, 'UTF-8'))) {
1958
-				$belongsToBase = false;
1959
-			}
1960
-			if ($belongsToBase) {
1961
-				break;
1962
-			}
1963
-		}
1964
-		return $belongsToBase;
1965
-	}
1966
-
1967
-	/**
1968
-	 * resets a running Paged Search operation
1969
-	 *
1970
-	 * @throws ServerNotAvailableException
1971
-	 */
1972
-	private function abandonPagedSearch() {
1973
-		if ($this->lastCookie === '') {
1974
-			return;
1975
-		}
1976
-		$cr = $this->connection->getConnectionResource();
1977
-		$this->invokeLDAPMethod('controlPagedResult', $cr, 0, false);
1978
-		$this->getPagedSearchResultState();
1979
-		$this->lastCookie = '';
1980
-	}
1981
-
1982
-	/**
1983
-	 * checks whether an LDAP paged search operation has more pages that can be
1984
-	 * retrieved, typically when offset and limit are provided.
1985
-	 *
1986
-	 * Be very careful to use it: the last cookie value, which is inspected, can
1987
-	 * be reset by other operations. Best, call it immediately after a search(),
1988
-	 * searchUsers() or searchGroups() call. count-methods are probably safe as
1989
-	 * well. Don't rely on it with any fetchList-method.
1990
-	 *
1991
-	 * @return bool
1992
-	 */
1993
-	public function hasMoreResults() {
1994
-		if (empty($this->lastCookie) && $this->lastCookie !== '0') {
1995
-			// as in RFC 2696, when all results are returned, the cookie will
1996
-			// be empty.
1997
-			return false;
1998
-		}
1999
-
2000
-		return true;
2001
-	}
2002
-
2003
-	/**
2004
-	 * Check whether the most recent paged search was successful. It flushed the state var. Use it always after a possible paged search.
2005
-	 *
2006
-	 * @return boolean|null true on success, null or false otherwise
2007
-	 */
2008
-	public function getPagedSearchResultState() {
2009
-		$result = $this->pagedSearchedSuccessful;
2010
-		$this->pagedSearchedSuccessful = null;
2011
-		return $result;
2012
-	}
2013
-
2014
-	/**
2015
-	 * Prepares a paged search, if possible
2016
-	 *
2017
-	 * @param string $filter the LDAP filter for the search
2018
-	 * @param string[] $bases an array containing the LDAP subtree(s) that shall be searched
2019
-	 * @param string[] $attr optional, when a certain attribute shall be filtered outside
2020
-	 * @param int $limit
2021
-	 * @param int $offset
2022
-	 * @return bool|true
2023
-	 * @throws ServerNotAvailableException
2024
-	 */
2025
-	private function initPagedSearch(
2026
-		string $filter,
2027
-		string $base,
2028
-		?array $attr,
2029
-		int $limit,
2030
-		int $offset
2031
-	): bool {
2032
-		$pagedSearchOK = false;
2033
-		if ($limit !== 0) {
2034
-			\OC::$server->getLogger()->debug(
2035
-				'initializing paged search for filter {filter}, base {base}, attr {attr}, limit {limit}, offset {offset}',
2036
-				[
2037
-					'app' => 'user_ldap',
2038
-					'filter' => $filter,
2039
-					'base' => $base,
2040
-					'attr' => $attr,
2041
-					'limit' => $limit,
2042
-					'offset' => $offset
2043
-				]
2044
-			);
2045
-			//get the cookie from the search for the previous search, required by LDAP
2046
-			if (empty($this->lastCookie) && $this->lastCookie !== "0" && ($offset > 0)) {
2047
-				// no cookie known from a potential previous search. We need
2048
-				// to start from 0 to come to the desired page. cookie value
2049
-				// of '0' is valid, because 389ds
2050
-				$reOffset = ($offset - $limit) < 0 ? 0 : $offset - $limit;
2051
-				$this->search($filter, $base, $attr, $limit, $reOffset, true);
2052
-				if (!$this->hasMoreResults()) {
2053
-					// when the cookie is reset with != 0 offset, there are no further
2054
-					// results, so stop. This if block is not necessary with new API
2055
-					// and can be removed with dropping PHP 7.2
2056
-					return false;
2057
-				}
2058
-			}
2059
-			if ($this->lastCookie !== '' && $offset === 0) {
2060
-				//since offset = 0, this is a new search. We abandon other searches that might be ongoing.
2061
-				$this->abandonPagedSearch();
2062
-			}
2063
-			$pagedSearchOK = true === $this->invokeLDAPMethod(
2064
-					'controlPagedResult', $this->connection->getConnectionResource(), $limit, false
2065
-				);
2066
-			if ($pagedSearchOK) {
2067
-				\OC::$server->getLogger()->debug('Ready for a paged search', ['app' => 'user_ldap']);
2068
-			}
2069
-			/* ++ Fixing RHDS searches with pages with zero results ++
1860
+            \OC::$server->getLogger()->info(
1861
+                'Passed string does not resemble a valid GUID. Known UUID ' .
1862
+                '({uuid}) probably does not match UUID configuration.',
1863
+                ['app' => 'user_ldap', 'uuid' => $guid]
1864
+            );
1865
+            return $guid;
1866
+        }
1867
+        for ($i = 0; $i < 3; $i++) {
1868
+            $pairs = str_split($blocks[$i], 2);
1869
+            $pairs = array_reverse($pairs);
1870
+            $blocks[$i] = implode('', $pairs);
1871
+        }
1872
+        for ($i = 0; $i < 5; $i++) {
1873
+            $pairs = str_split($blocks[$i], 2);
1874
+            $blocks[$i] = '\\' . implode('\\', $pairs);
1875
+        }
1876
+        return implode('', $blocks);
1877
+    }
1878
+
1879
+    /**
1880
+     * gets a SID of the domain of the given dn
1881
+     *
1882
+     * @param string $dn
1883
+     * @return string|bool
1884
+     * @throws ServerNotAvailableException
1885
+     */
1886
+    public function getSID($dn) {
1887
+        $domainDN = $this->getDomainDNFromDN($dn);
1888
+        $cacheKey = 'getSID-' . $domainDN;
1889
+        $sid = $this->connection->getFromCache($cacheKey);
1890
+        if (!is_null($sid)) {
1891
+            return $sid;
1892
+        }
1893
+
1894
+        $objectSid = $this->readAttribute($domainDN, 'objectsid');
1895
+        if (!is_array($objectSid) || empty($objectSid)) {
1896
+            $this->connection->writeToCache($cacheKey, false);
1897
+            return false;
1898
+        }
1899
+        $domainObjectSid = $this->convertSID2Str($objectSid[0]);
1900
+        $this->connection->writeToCache($cacheKey, $domainObjectSid);
1901
+
1902
+        return $domainObjectSid;
1903
+    }
1904
+
1905
+    /**
1906
+     * converts a binary SID into a string representation
1907
+     *
1908
+     * @param string $sid
1909
+     * @return string
1910
+     */
1911
+    public function convertSID2Str($sid) {
1912
+        // The format of a SID binary string is as follows:
1913
+        // 1 byte for the revision level
1914
+        // 1 byte for the number n of variable sub-ids
1915
+        // 6 bytes for identifier authority value
1916
+        // n*4 bytes for n sub-ids
1917
+        //
1918
+        // Example: 010400000000000515000000a681e50e4d6c6c2bca32055f
1919
+        //  Legend: RRNNAAAAAAAAAAAA11111111222222223333333344444444
1920
+        $revision = ord($sid[0]);
1921
+        $numberSubID = ord($sid[1]);
1922
+
1923
+        $subIdStart = 8; // 1 + 1 + 6
1924
+        $subIdLength = 4;
1925
+        if (strlen($sid) !== $subIdStart + $subIdLength * $numberSubID) {
1926
+            // Incorrect number of bytes present.
1927
+            return '';
1928
+        }
1929
+
1930
+        // 6 bytes = 48 bits can be represented using floats without loss of
1931
+        // precision (see https://gist.github.com/bantu/886ac680b0aef5812f71)
1932
+        $iav = number_format(hexdec(bin2hex(substr($sid, 2, 6))), 0, '', '');
1933
+
1934
+        $subIDs = [];
1935
+        for ($i = 0; $i < $numberSubID; $i++) {
1936
+            $subID = unpack('V', substr($sid, $subIdStart + $subIdLength * $i, $subIdLength));
1937
+            $subIDs[] = sprintf('%u', $subID[1]);
1938
+        }
1939
+
1940
+        // Result for example above: S-1-5-21-249921958-728525901-1594176202
1941
+        return sprintf('S-%d-%s-%s', $revision, $iav, implode('-', $subIDs));
1942
+    }
1943
+
1944
+    /**
1945
+     * checks if the given DN is part of the given base DN(s)
1946
+     *
1947
+     * @param string $dn the DN
1948
+     * @param string[] $bases array containing the allowed base DN or DNs
1949
+     * @return bool
1950
+     */
1951
+    public function isDNPartOfBase($dn, $bases) {
1952
+        $belongsToBase = false;
1953
+        $bases = $this->helper->sanitizeDN($bases);
1954
+
1955
+        foreach ($bases as $base) {
1956
+            $belongsToBase = true;
1957
+            if (mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8') - mb_strlen($base, 'UTF-8'))) {
1958
+                $belongsToBase = false;
1959
+            }
1960
+            if ($belongsToBase) {
1961
+                break;
1962
+            }
1963
+        }
1964
+        return $belongsToBase;
1965
+    }
1966
+
1967
+    /**
1968
+     * resets a running Paged Search operation
1969
+     *
1970
+     * @throws ServerNotAvailableException
1971
+     */
1972
+    private function abandonPagedSearch() {
1973
+        if ($this->lastCookie === '') {
1974
+            return;
1975
+        }
1976
+        $cr = $this->connection->getConnectionResource();
1977
+        $this->invokeLDAPMethod('controlPagedResult', $cr, 0, false);
1978
+        $this->getPagedSearchResultState();
1979
+        $this->lastCookie = '';
1980
+    }
1981
+
1982
+    /**
1983
+     * checks whether an LDAP paged search operation has more pages that can be
1984
+     * retrieved, typically when offset and limit are provided.
1985
+     *
1986
+     * Be very careful to use it: the last cookie value, which is inspected, can
1987
+     * be reset by other operations. Best, call it immediately after a search(),
1988
+     * searchUsers() or searchGroups() call. count-methods are probably safe as
1989
+     * well. Don't rely on it with any fetchList-method.
1990
+     *
1991
+     * @return bool
1992
+     */
1993
+    public function hasMoreResults() {
1994
+        if (empty($this->lastCookie) && $this->lastCookie !== '0') {
1995
+            // as in RFC 2696, when all results are returned, the cookie will
1996
+            // be empty.
1997
+            return false;
1998
+        }
1999
+
2000
+        return true;
2001
+    }
2002
+
2003
+    /**
2004
+     * Check whether the most recent paged search was successful. It flushed the state var. Use it always after a possible paged search.
2005
+     *
2006
+     * @return boolean|null true on success, null or false otherwise
2007
+     */
2008
+    public function getPagedSearchResultState() {
2009
+        $result = $this->pagedSearchedSuccessful;
2010
+        $this->pagedSearchedSuccessful = null;
2011
+        return $result;
2012
+    }
2013
+
2014
+    /**
2015
+     * Prepares a paged search, if possible
2016
+     *
2017
+     * @param string $filter the LDAP filter for the search
2018
+     * @param string[] $bases an array containing the LDAP subtree(s) that shall be searched
2019
+     * @param string[] $attr optional, when a certain attribute shall be filtered outside
2020
+     * @param int $limit
2021
+     * @param int $offset
2022
+     * @return bool|true
2023
+     * @throws ServerNotAvailableException
2024
+     */
2025
+    private function initPagedSearch(
2026
+        string $filter,
2027
+        string $base,
2028
+        ?array $attr,
2029
+        int $limit,
2030
+        int $offset
2031
+    ): bool {
2032
+        $pagedSearchOK = false;
2033
+        if ($limit !== 0) {
2034
+            \OC::$server->getLogger()->debug(
2035
+                'initializing paged search for filter {filter}, base {base}, attr {attr}, limit {limit}, offset {offset}',
2036
+                [
2037
+                    'app' => 'user_ldap',
2038
+                    'filter' => $filter,
2039
+                    'base' => $base,
2040
+                    'attr' => $attr,
2041
+                    'limit' => $limit,
2042
+                    'offset' => $offset
2043
+                ]
2044
+            );
2045
+            //get the cookie from the search for the previous search, required by LDAP
2046
+            if (empty($this->lastCookie) && $this->lastCookie !== "0" && ($offset > 0)) {
2047
+                // no cookie known from a potential previous search. We need
2048
+                // to start from 0 to come to the desired page. cookie value
2049
+                // of '0' is valid, because 389ds
2050
+                $reOffset = ($offset - $limit) < 0 ? 0 : $offset - $limit;
2051
+                $this->search($filter, $base, $attr, $limit, $reOffset, true);
2052
+                if (!$this->hasMoreResults()) {
2053
+                    // when the cookie is reset with != 0 offset, there are no further
2054
+                    // results, so stop. This if block is not necessary with new API
2055
+                    // and can be removed with dropping PHP 7.2
2056
+                    return false;
2057
+                }
2058
+            }
2059
+            if ($this->lastCookie !== '' && $offset === 0) {
2060
+                //since offset = 0, this is a new search. We abandon other searches that might be ongoing.
2061
+                $this->abandonPagedSearch();
2062
+            }
2063
+            $pagedSearchOK = true === $this->invokeLDAPMethod(
2064
+                    'controlPagedResult', $this->connection->getConnectionResource(), $limit, false
2065
+                );
2066
+            if ($pagedSearchOK) {
2067
+                \OC::$server->getLogger()->debug('Ready for a paged search', ['app' => 'user_ldap']);
2068
+            }
2069
+            /* ++ Fixing RHDS searches with pages with zero results ++
2070 2070
 			 * We coudn't get paged searches working with our RHDS for login ($limit = 0),
2071 2071
 			 * due to pages with zero results.
2072 2072
 			 * So we added "&& !empty($this->lastCookie)" to this test to ignore pagination
2073 2073
 			 * if we don't have a previous paged search.
2074 2074
 			 */
2075
-		} elseif ($limit === 0 && !empty($this->lastCookie)) {
2076
-			// a search without limit was requested. However, if we do use
2077
-			// Paged Search once, we always must do it. This requires us to
2078
-			// initialize it with the configured page size.
2079
-			$this->abandonPagedSearch();
2080
-			// in case someone set it to 0 … use 500, otherwise no results will
2081
-			// be returned.
2082
-			$pageSize = (int)$this->connection->ldapPagingSize > 0 ? (int)$this->connection->ldapPagingSize : 500;
2083
-			$pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
2084
-				$this->connection->getConnectionResource(),
2085
-				$pageSize, false);
2086
-		}
2087
-
2088
-		return $pagedSearchOK;
2089
-	}
2090
-
2091
-	/**
2092
-	 * Is more than one $attr used for search?
2093
-	 *
2094
-	 * @param string|string[]|null $attr
2095
-	 * @return bool
2096
-	 */
2097
-	private function manyAttributes($attr): bool {
2098
-		if (\is_array($attr)) {
2099
-			return \count($attr) > 1;
2100
-		}
2101
-		return false;
2102
-	}
2075
+        } elseif ($limit === 0 && !empty($this->lastCookie)) {
2076
+            // a search without limit was requested. However, if we do use
2077
+            // Paged Search once, we always must do it. This requires us to
2078
+            // initialize it with the configured page size.
2079
+            $this->abandonPagedSearch();
2080
+            // in case someone set it to 0 … use 500, otherwise no results will
2081
+            // be returned.
2082
+            $pageSize = (int)$this->connection->ldapPagingSize > 0 ? (int)$this->connection->ldapPagingSize : 500;
2083
+            $pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
2084
+                $this->connection->getConnectionResource(),
2085
+                $pageSize, false);
2086
+        }
2087
+
2088
+        return $pagedSearchOK;
2089
+    }
2090
+
2091
+    /**
2092
+     * Is more than one $attr used for search?
2093
+     *
2094
+     * @param string|string[]|null $attr
2095
+     * @return bool
2096
+     */
2097
+    private function manyAttributes($attr): bool {
2098
+        if (\is_array($attr)) {
2099
+            return \count($attr) > 1;
2100
+        }
2101
+        return false;
2102
+    }
2103 2103
 }
Please login to merge, or discard this patch.