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