Passed
Push — master ( 62403d...0c3e2f )
by Joas
14:50 queued 14s
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 = [];
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, [$dn], [$attribute], $maxResults, 0);
272
-		$dn = $this->helper->DNasBaseParameter($dn);
273
-		$rr = @$this->invokeLDAPMethod('read', $cr, $dn, $filter, [$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 = [
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 = [];
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(['ldapCacheTTL' => 0]);
869
-		if($isUser) {
870
-			$altName = $this->_createAltInternalOwnCloudNameForUsers($name);
871
-		} else {
872
-			$altName = $this->_createAltInternalOwnCloudNameForGroups($name);
873
-		}
874
-		$this->connection->setConfiguration(['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 = ['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
-				}, []);
1000
-				return array_unique($list, SORT_LOCALE_STRING);
1001
-			}
1002
-		}
1003
-
1004
-		//error cause actually, maybe throw an exception in future.
1005
-		return [];
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 = ['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 = ['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([$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 = [];
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, [$dn], [$attribute], $maxResults, 0);
272
+        $dn = $this->helper->DNasBaseParameter($dn);
273
+        $rr = @$this->invokeLDAPMethod('read', $cr, $dn, $filter, [$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 = [
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 = [];
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(['ldapCacheTTL' => 0]);
869
+        if($isUser) {
870
+            $altName = $this->_createAltInternalOwnCloudNameForUsers($name);
871
+        } else {
872
+            $altName = $this->_createAltInternalOwnCloudNameForGroups($name);
873
+        }
874
+        $this->connection->setConfiguration(['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 = ['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
+                }, []);
1000
+                return array_unique($list, SORT_LOCALE_STRING);
1001
+            }
1002
+        }
1003
+
1004
+        //error cause actually, maybe throw an exception in future.
1005
+        return [];
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 = ['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 = ['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([$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 = [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([], 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 [$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 = [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([], 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 [$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 [];
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 [];
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  = ['*', '\\', '(', ')'];
1467
-		$replace = ['\\*', '\\\\', '\\(', '\\)'];
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 = [];
1545
-		foreach($searchWords as $word) {
1546
-			$word = $this->prepareSearchTerm($word);
1547
-			//every word needs to appear at least once
1548
-			$wordMatchOneAttrFilters = [];
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 = [];
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([
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 = [
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 [];
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 [];
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  = ['*', '\\', '(', ')'];
1467
+        $replace = ['\\*', '\\\\', '\\(', '\\)'];
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 = [];
1545
+        foreach($searchWords as $word) {
1546
+            $word = $this->prepareSearchTerm($word);
1547
+            //every word needs to appear at least once
1548
+            $wordMatchOneAttrFilters = [];
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 = [];
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([
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 = [
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 = [];
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, [$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 = [];
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, [$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.
apps/user_ldap/lib/UserPluginManager.php 1 patch
Indentation   +179 added lines, -179 removed lines patch added patch discarded remove patch
@@ -28,183 +28,183 @@
 block discarded – undo
28 28
 
29 29
 class UserPluginManager {
30 30
 
31
-	public $test = false;
32
-
33
-	private $respondToActions = 0;
34
-
35
-	private $which = [
36
-		Backend::CREATE_USER => null,
37
-		Backend::SET_PASSWORD => null,
38
-		Backend::GET_HOME => null,
39
-		Backend::GET_DISPLAYNAME => null,
40
-		Backend::SET_DISPLAYNAME => null,
41
-		Backend::PROVIDE_AVATAR => null,
42
-		Backend::COUNT_USERS => null,
43
-		'deleteUser' => null
44
-	];
45
-
46
-	/**
47
-	 * @return int All implemented actions, except for 'deleteUser'
48
-	 */
49
-	public function getImplementedActions() {
50
-		return $this->respondToActions;
51
-	}
52
-
53
-	/**
54
-	 * Registers a user plugin that may implement some actions, overriding User_LDAP's user actions.
55
-	 *
56
-	 * @param ILDAPUserPlugin $plugin
57
-	 */
58
-	public function register(ILDAPUserPlugin $plugin) {
59
-		$respondToActions = $plugin->respondToActions();
60
-		$this->respondToActions |= $respondToActions;
61
-
62
-		foreach($this->which as $action => $v) {
63
-			if (is_int($action) && (bool)($respondToActions & $action)) {
64
-				$this->which[$action] = $plugin;
65
-				\OC::$server->getLogger()->debug("Registered action ".$action." to plugin ".get_class($plugin), ['app' => 'user_ldap']);
66
-			}
67
-		}
68
-		if (method_exists($plugin,'deleteUser')) {
69
-			$this->which['deleteUser'] = $plugin;
70
-			\OC::$server->getLogger()->debug("Registered action deleteUser to plugin ".get_class($plugin), ['app' => 'user_ldap']);
71
-		}
72
-	}
73
-
74
-	/**
75
-	 * Signal if there is a registered plugin that implements some given actions
76
-	 * @param int $actions Actions defined in \OC\User\Backend, like Backend::CREATE_USER
77
-	 * @return bool
78
-	 */
79
-	public function implementsActions($actions) {
80
-		return ($actions & $this->respondToActions) == $actions;
81
-	}
82
-
83
-	/**
84
-	 * Create a new user in LDAP Backend
85
-	 *
86
-	 * @param string $username The username of the user to create
87
-	 * @param string $password The password of the new user
88
-	 * @return string | false The user DN if user creation was successful.
89
-	 * @throws \Exception
90
-	 */
91
-	public function createUser($username, $password) {
92
-		$plugin = $this->which[Backend::CREATE_USER];
93
-
94
-		if ($plugin) {
95
-			return $plugin->createUser($username,$password);
96
-		}
97
-		throw new \Exception('No plugin implements createUser in this LDAP Backend.');
98
-	}
99
-
100
-	/**
101
-	 * Change the password of a user*
102
-	 * @param string $uid The username
103
-	 * @param string $password The new password
104
-	 * @return bool
105
-	 * @throws \Exception
106
-	 */
107
-	public function setPassword($uid, $password) {
108
-		$plugin = $this->which[Backend::SET_PASSWORD];
109
-
110
-		if ($plugin) {
111
-			return $plugin->setPassword($uid,$password);
112
-		}
113
-		throw new \Exception('No plugin implements setPassword in this LDAP Backend.');
114
-	}
115
-
116
-	/**
117
-	 * checks whether the user is allowed to change his avatar in Nextcloud
118
-	 * @param string $uid the Nextcloud user name
119
-	 * @return boolean either the user can or cannot
120
-	 * @throws \Exception
121
-	 */
122
-	public function canChangeAvatar($uid) {
123
-		$plugin = $this->which[Backend::PROVIDE_AVATAR];
124
-
125
-		if ($plugin) {
126
-			return $plugin->canChangeAvatar($uid);
127
-		}
128
-		throw new \Exception('No plugin implements canChangeAvatar in this LDAP Backend.');
129
-	}
130
-
131
-	/**
132
-	 * Get the user's home directory
133
-	 * @param string $uid the username
134
-	 * @return boolean
135
-	 * @throws \Exception
136
-	 */
137
-	public function getHome($uid) {
138
-		$plugin = $this->which[Backend::GET_HOME];
139
-
140
-		if ($plugin) {
141
-			return $plugin->getHome($uid);
142
-		}
143
-		throw new \Exception('No plugin implements getHome in this LDAP Backend.');
144
-	}
145
-
146
-	/**
147
-	 * Get display name of the user
148
-	 * @param string $uid user ID of the user
149
-	 * @return string display name
150
-	 * @throws \Exception
151
-	 */
152
-	public function getDisplayName($uid) {
153
-		$plugin = $this->which[Backend::GET_DISPLAYNAME];
154
-
155
-		if ($plugin) {
156
-			return $plugin->getDisplayName($uid);
157
-		}
158
-		throw new \Exception('No plugin implements getDisplayName in this LDAP Backend.');
159
-	}
160
-
161
-	/**
162
-	 * Set display name of the user
163
-	 * @param string $uid user ID of the user
164
-	 * @param string $displayName new user's display name
165
-	 * @return string display name
166
-	 * @throws \Exception
167
-	 */
168
-	public function setDisplayName($uid, $displayName) {
169
-		$plugin = $this->which[Backend::SET_DISPLAYNAME];
170
-
171
-		if ($plugin) {
172
-			return $plugin->setDisplayName($uid, $displayName);
173
-		}
174
-		throw new \Exception('No plugin implements setDisplayName in this LDAP Backend.');
175
-	}
176
-
177
-	/**
178
-	 * Count the number of users
179
-	 * @return int|bool
180
-	 * @throws \Exception
181
-	 */
182
-	public function countUsers() {
183
-		$plugin = $this->which[Backend::COUNT_USERS];
184
-
185
-		if ($plugin) {
186
-			return $plugin->countUsers();
187
-		}
188
-		throw new \Exception('No plugin implements countUsers in this LDAP Backend.');
189
-	}
190
-
191
-	/**
192
-	 * @return bool
193
-	 */
194
-	public function canDeleteUser() {
195
-		return $this->which['deleteUser'] !== null;
196
-	}
197
-
198
-	/**
199
-	 * @param $uid
200
-	 * @return bool
201
-	 * @throws \Exception
202
-	 */
203
-	public function deleteUser($uid) {
204
-		$plugin = $this->which['deleteUser'];
205
-		if ($plugin) {
206
-			return $plugin->deleteUser($uid);
207
-		}
208
-		throw new \Exception('No plugin implements deleteUser in this LDAP Backend.');
209
-	}
31
+    public $test = false;
32
+
33
+    private $respondToActions = 0;
34
+
35
+    private $which = [
36
+        Backend::CREATE_USER => null,
37
+        Backend::SET_PASSWORD => null,
38
+        Backend::GET_HOME => null,
39
+        Backend::GET_DISPLAYNAME => null,
40
+        Backend::SET_DISPLAYNAME => null,
41
+        Backend::PROVIDE_AVATAR => null,
42
+        Backend::COUNT_USERS => null,
43
+        'deleteUser' => null
44
+    ];
45
+
46
+    /**
47
+     * @return int All implemented actions, except for 'deleteUser'
48
+     */
49
+    public function getImplementedActions() {
50
+        return $this->respondToActions;
51
+    }
52
+
53
+    /**
54
+     * Registers a user plugin that may implement some actions, overriding User_LDAP's user actions.
55
+     *
56
+     * @param ILDAPUserPlugin $plugin
57
+     */
58
+    public function register(ILDAPUserPlugin $plugin) {
59
+        $respondToActions = $plugin->respondToActions();
60
+        $this->respondToActions |= $respondToActions;
61
+
62
+        foreach($this->which as $action => $v) {
63
+            if (is_int($action) && (bool)($respondToActions & $action)) {
64
+                $this->which[$action] = $plugin;
65
+                \OC::$server->getLogger()->debug("Registered action ".$action." to plugin ".get_class($plugin), ['app' => 'user_ldap']);
66
+            }
67
+        }
68
+        if (method_exists($plugin,'deleteUser')) {
69
+            $this->which['deleteUser'] = $plugin;
70
+            \OC::$server->getLogger()->debug("Registered action deleteUser to plugin ".get_class($plugin), ['app' => 'user_ldap']);
71
+        }
72
+    }
73
+
74
+    /**
75
+     * Signal if there is a registered plugin that implements some given actions
76
+     * @param int $actions Actions defined in \OC\User\Backend, like Backend::CREATE_USER
77
+     * @return bool
78
+     */
79
+    public function implementsActions($actions) {
80
+        return ($actions & $this->respondToActions) == $actions;
81
+    }
82
+
83
+    /**
84
+     * Create a new user in LDAP Backend
85
+     *
86
+     * @param string $username The username of the user to create
87
+     * @param string $password The password of the new user
88
+     * @return string | false The user DN if user creation was successful.
89
+     * @throws \Exception
90
+     */
91
+    public function createUser($username, $password) {
92
+        $plugin = $this->which[Backend::CREATE_USER];
93
+
94
+        if ($plugin) {
95
+            return $plugin->createUser($username,$password);
96
+        }
97
+        throw new \Exception('No plugin implements createUser in this LDAP Backend.');
98
+    }
99
+
100
+    /**
101
+     * Change the password of a user*
102
+     * @param string $uid The username
103
+     * @param string $password The new password
104
+     * @return bool
105
+     * @throws \Exception
106
+     */
107
+    public function setPassword($uid, $password) {
108
+        $plugin = $this->which[Backend::SET_PASSWORD];
109
+
110
+        if ($plugin) {
111
+            return $plugin->setPassword($uid,$password);
112
+        }
113
+        throw new \Exception('No plugin implements setPassword in this LDAP Backend.');
114
+    }
115
+
116
+    /**
117
+     * checks whether the user is allowed to change his avatar in Nextcloud
118
+     * @param string $uid the Nextcloud user name
119
+     * @return boolean either the user can or cannot
120
+     * @throws \Exception
121
+     */
122
+    public function canChangeAvatar($uid) {
123
+        $plugin = $this->which[Backend::PROVIDE_AVATAR];
124
+
125
+        if ($plugin) {
126
+            return $plugin->canChangeAvatar($uid);
127
+        }
128
+        throw new \Exception('No plugin implements canChangeAvatar in this LDAP Backend.');
129
+    }
130
+
131
+    /**
132
+     * Get the user's home directory
133
+     * @param string $uid the username
134
+     * @return boolean
135
+     * @throws \Exception
136
+     */
137
+    public function getHome($uid) {
138
+        $plugin = $this->which[Backend::GET_HOME];
139
+
140
+        if ($plugin) {
141
+            return $plugin->getHome($uid);
142
+        }
143
+        throw new \Exception('No plugin implements getHome in this LDAP Backend.');
144
+    }
145
+
146
+    /**
147
+     * Get display name of the user
148
+     * @param string $uid user ID of the user
149
+     * @return string display name
150
+     * @throws \Exception
151
+     */
152
+    public function getDisplayName($uid) {
153
+        $plugin = $this->which[Backend::GET_DISPLAYNAME];
154
+
155
+        if ($plugin) {
156
+            return $plugin->getDisplayName($uid);
157
+        }
158
+        throw new \Exception('No plugin implements getDisplayName in this LDAP Backend.');
159
+    }
160
+
161
+    /**
162
+     * Set display name of the user
163
+     * @param string $uid user ID of the user
164
+     * @param string $displayName new user's display name
165
+     * @return string display name
166
+     * @throws \Exception
167
+     */
168
+    public function setDisplayName($uid, $displayName) {
169
+        $plugin = $this->which[Backend::SET_DISPLAYNAME];
170
+
171
+        if ($plugin) {
172
+            return $plugin->setDisplayName($uid, $displayName);
173
+        }
174
+        throw new \Exception('No plugin implements setDisplayName in this LDAP Backend.');
175
+    }
176
+
177
+    /**
178
+     * Count the number of users
179
+     * @return int|bool
180
+     * @throws \Exception
181
+     */
182
+    public function countUsers() {
183
+        $plugin = $this->which[Backend::COUNT_USERS];
184
+
185
+        if ($plugin) {
186
+            return $plugin->countUsers();
187
+        }
188
+        throw new \Exception('No plugin implements countUsers in this LDAP Backend.');
189
+    }
190
+
191
+    /**
192
+     * @return bool
193
+     */
194
+    public function canDeleteUser() {
195
+        return $this->which['deleteUser'] !== null;
196
+    }
197
+
198
+    /**
199
+     * @param $uid
200
+     * @return bool
201
+     * @throws \Exception
202
+     */
203
+    public function deleteUser($uid) {
204
+        $plugin = $this->which['deleteUser'];
205
+        if ($plugin) {
206
+            return $plugin->deleteUser($uid);
207
+        }
208
+        throw new \Exception('No plugin implements deleteUser in this LDAP Backend.');
209
+    }
210 210
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/WizardResult.php 1 patch
Indentation   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -29,50 +29,50 @@
 block discarded – undo
29 29
 namespace OCA\User_LDAP;
30 30
 
31 31
 class WizardResult {
32
-	protected $changes = [];
33
-	protected $options = [];
34
-	protected $markedChange = false;
32
+    protected $changes = [];
33
+    protected $options = [];
34
+    protected $markedChange = false;
35 35
 
36
-	/**
37
-	 * @param string $key
38
-	 * @param mixed $value
39
-	 */
40
-	public function addChange($key, $value) {
41
-		$this->changes[$key] = $value;
42
-	}
36
+    /**
37
+     * @param string $key
38
+     * @param mixed $value
39
+     */
40
+    public function addChange($key, $value) {
41
+        $this->changes[$key] = $value;
42
+    }
43 43
 
44 44
 	
45
-	public function markChange() {
46
-		$this->markedChange = true;
47
-	}
45
+    public function markChange() {
46
+        $this->markedChange = true;
47
+    }
48 48
 
49
-	/**
50
-	 * @param string $key
51
-	 * @param array|string $values
52
-	 */
53
-	public function addOptions($key, $values) {
54
-		if(!is_array($values)) {
55
-			$values = [$values];
56
-		}
57
-		$this->options[$key] = $values;
58
-	}
49
+    /**
50
+     * @param string $key
51
+     * @param array|string $values
52
+     */
53
+    public function addOptions($key, $values) {
54
+        if(!is_array($values)) {
55
+            $values = [$values];
56
+        }
57
+        $this->options[$key] = $values;
58
+    }
59 59
 
60
-	/**
61
-	 * @return bool
62
-	 */
63
-	public function hasChanges() {
64
-		return (count($this->changes) > 0 || $this->markedChange);
65
-	}
60
+    /**
61
+     * @return bool
62
+     */
63
+    public function hasChanges() {
64
+        return (count($this->changes) > 0 || $this->markedChange);
65
+    }
66 66
 
67
-	/**
68
-	 * @return array
69
-	 */
70
-	public function getResultArray() {
71
-		$result = [];
72
-		$result['changes'] = $this->changes;
73
-		if(count($this->options) > 0) {
74
-			$result['options'] = $this->options;
75
-		}
76
-		return $result;
77
-	}
67
+    /**
68
+     * @return array
69
+     */
70
+    public function getResultArray() {
71
+        $result = [];
72
+        $result['changes'] = $this->changes;
73
+        if(count($this->options) > 0) {
74
+            $result['options'] = $this->options;
75
+        }
76
+        return $result;
77
+    }
78 78
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/Configuration.php 1 patch
Indentation   +510 added lines, -510 removed lines patch added patch discarded remove patch
@@ -40,543 +40,543 @@
 block discarded – undo
40 40
  * @property string ldapUserAvatarRule
41 41
  */
42 42
 class Configuration {
43
-	const AVATAR_PREFIX_DEFAULT = 'default';
44
-	const AVATAR_PREFIX_NONE = 'none';
45
-	const AVATAR_PREFIX_DATA_ATTRIBUTE = 'data:';
43
+    const AVATAR_PREFIX_DEFAULT = 'default';
44
+    const AVATAR_PREFIX_NONE = 'none';
45
+    const AVATAR_PREFIX_DATA_ATTRIBUTE = 'data:';
46 46
 
47
-	protected $configPrefix = null;
48
-	protected $configRead = false;
49
-	/**
50
-	 * @var string[] pre-filled with one reference key so that at least one entry is written on save request and
51
-	 *               the config ID is registered
52
-	 */
53
-	protected $unsavedChanges = ['ldapConfigurationActive' => 'ldapConfigurationActive'];
47
+    protected $configPrefix = null;
48
+    protected $configRead = false;
49
+    /**
50
+     * @var string[] pre-filled with one reference key so that at least one entry is written on save request and
51
+     *               the config ID is registered
52
+     */
53
+    protected $unsavedChanges = ['ldapConfigurationActive' => 'ldapConfigurationActive'];
54 54
 
55
-	//settings
56
-	protected $config = [
57
-		'ldapHost' => null,
58
-		'ldapPort' => null,
59
-		'ldapBackupHost' => null,
60
-		'ldapBackupPort' => null,
61
-		'ldapBase' => null,
62
-		'ldapBaseUsers' => null,
63
-		'ldapBaseGroups' => null,
64
-		'ldapAgentName' => null,
65
-		'ldapAgentPassword' => null,
66
-		'ldapTLS' => null,
67
-		'turnOffCertCheck' => null,
68
-		'ldapIgnoreNamingRules' => null,
69
-		'ldapUserDisplayName' => null,
70
-		'ldapUserDisplayName2' => null,
71
-		'ldapUserAvatarRule' => null,
72
-		'ldapGidNumber' => null,
73
-		'ldapUserFilterObjectclass' => null,
74
-		'ldapUserFilterGroups' => null,
75
-		'ldapUserFilter' => null,
76
-		'ldapUserFilterMode' => null,
77
-		'ldapGroupFilter' => null,
78
-		'ldapGroupFilterMode' => null,
79
-		'ldapGroupFilterObjectclass' => null,
80
-		'ldapGroupFilterGroups' => null,
81
-		'ldapGroupDisplayName' => null,
82
-		'ldapGroupMemberAssocAttr' => null,
83
-		'ldapLoginFilter' => null,
84
-		'ldapLoginFilterMode' => null,
85
-		'ldapLoginFilterEmail' => null,
86
-		'ldapLoginFilterUsername' => null,
87
-		'ldapLoginFilterAttributes' => null,
88
-		'ldapQuotaAttribute' => null,
89
-		'ldapQuotaDefault' => null,
90
-		'ldapEmailAttribute' => null,
91
-		'ldapCacheTTL' => null,
92
-		'ldapUuidUserAttribute' => 'auto',
93
-		'ldapUuidGroupAttribute' => 'auto',
94
-		'ldapOverrideMainServer' => false,
95
-		'ldapConfigurationActive' => false,
96
-		'ldapAttributesForUserSearch' => null,
97
-		'ldapAttributesForGroupSearch' => null,
98
-		'ldapExperiencedAdmin' => false,
99
-		'homeFolderNamingRule' => null,
100
-		'hasMemberOfFilterSupport' => false,
101
-		'useMemberOfToDetectMembership' => true,
102
-		'ldapExpertUsernameAttr' => null,
103
-		'ldapExpertUUIDUserAttr' => null,
104
-		'ldapExpertUUIDGroupAttr' => null,
105
-		'lastJpegPhotoLookup' => null,
106
-		'ldapNestedGroups' => false,
107
-		'ldapPagingSize' => null,
108
-		'turnOnPasswordChange' => false,
109
-		'ldapDynamicGroupMemberURL' => null,
110
-		'ldapDefaultPPolicyDN' => null,
111
-		'ldapExtStorageHomeAttribute' => null,
112
-	];
55
+    //settings
56
+    protected $config = [
57
+        'ldapHost' => null,
58
+        'ldapPort' => null,
59
+        'ldapBackupHost' => null,
60
+        'ldapBackupPort' => null,
61
+        'ldapBase' => null,
62
+        'ldapBaseUsers' => null,
63
+        'ldapBaseGroups' => null,
64
+        'ldapAgentName' => null,
65
+        'ldapAgentPassword' => null,
66
+        'ldapTLS' => null,
67
+        'turnOffCertCheck' => null,
68
+        'ldapIgnoreNamingRules' => null,
69
+        'ldapUserDisplayName' => null,
70
+        'ldapUserDisplayName2' => null,
71
+        'ldapUserAvatarRule' => null,
72
+        'ldapGidNumber' => null,
73
+        'ldapUserFilterObjectclass' => null,
74
+        'ldapUserFilterGroups' => null,
75
+        'ldapUserFilter' => null,
76
+        'ldapUserFilterMode' => null,
77
+        'ldapGroupFilter' => null,
78
+        'ldapGroupFilterMode' => null,
79
+        'ldapGroupFilterObjectclass' => null,
80
+        'ldapGroupFilterGroups' => null,
81
+        'ldapGroupDisplayName' => null,
82
+        'ldapGroupMemberAssocAttr' => null,
83
+        'ldapLoginFilter' => null,
84
+        'ldapLoginFilterMode' => null,
85
+        'ldapLoginFilterEmail' => null,
86
+        'ldapLoginFilterUsername' => null,
87
+        'ldapLoginFilterAttributes' => null,
88
+        'ldapQuotaAttribute' => null,
89
+        'ldapQuotaDefault' => null,
90
+        'ldapEmailAttribute' => null,
91
+        'ldapCacheTTL' => null,
92
+        'ldapUuidUserAttribute' => 'auto',
93
+        'ldapUuidGroupAttribute' => 'auto',
94
+        'ldapOverrideMainServer' => false,
95
+        'ldapConfigurationActive' => false,
96
+        'ldapAttributesForUserSearch' => null,
97
+        'ldapAttributesForGroupSearch' => null,
98
+        'ldapExperiencedAdmin' => false,
99
+        'homeFolderNamingRule' => null,
100
+        'hasMemberOfFilterSupport' => false,
101
+        'useMemberOfToDetectMembership' => true,
102
+        'ldapExpertUsernameAttr' => null,
103
+        'ldapExpertUUIDUserAttr' => null,
104
+        'ldapExpertUUIDGroupAttr' => null,
105
+        'lastJpegPhotoLookup' => null,
106
+        'ldapNestedGroups' => false,
107
+        'ldapPagingSize' => null,
108
+        'turnOnPasswordChange' => false,
109
+        'ldapDynamicGroupMemberURL' => null,
110
+        'ldapDefaultPPolicyDN' => null,
111
+        'ldapExtStorageHomeAttribute' => null,
112
+    ];
113 113
 
114
-	/**
115
-	 * @param string $configPrefix
116
-	 * @param bool $autoRead
117
-	 */
118
-	public function __construct($configPrefix, $autoRead = true) {
119
-		$this->configPrefix = $configPrefix;
120
-		if($autoRead) {
121
-			$this->readConfiguration();
122
-		}
123
-	}
114
+    /**
115
+     * @param string $configPrefix
116
+     * @param bool $autoRead
117
+     */
118
+    public function __construct($configPrefix, $autoRead = true) {
119
+        $this->configPrefix = $configPrefix;
120
+        if($autoRead) {
121
+            $this->readConfiguration();
122
+        }
123
+    }
124 124
 
125
-	/**
126
-	 * @param string $name
127
-	 * @return mixed|null
128
-	 */
129
-	public function __get($name) {
130
-		if(isset($this->config[$name])) {
131
-			return $this->config[$name];
132
-		}
133
-		return null;
134
-	}
125
+    /**
126
+     * @param string $name
127
+     * @return mixed|null
128
+     */
129
+    public function __get($name) {
130
+        if(isset($this->config[$name])) {
131
+            return $this->config[$name];
132
+        }
133
+        return null;
134
+    }
135 135
 
136
-	/**
137
-	 * @param string $name
138
-	 * @param mixed $value
139
-	 */
140
-	public function __set($name, $value) {
141
-		$this->setConfiguration([$name => $value]);
142
-	}
136
+    /**
137
+     * @param string $name
138
+     * @param mixed $value
139
+     */
140
+    public function __set($name, $value) {
141
+        $this->setConfiguration([$name => $value]);
142
+    }
143 143
 
144
-	/**
145
-	 * @return array
146
-	 */
147
-	public function getConfiguration() {
148
-		return $this->config;
149
-	}
144
+    /**
145
+     * @return array
146
+     */
147
+    public function getConfiguration() {
148
+        return $this->config;
149
+    }
150 150
 
151
-	/**
152
-	 * set LDAP configuration with values delivered by an array, not read
153
-	 * from configuration. It does not save the configuration! To do so, you
154
-	 * must call saveConfiguration afterwards.
155
-	 * @param array $config array that holds the config parameters in an associated
156
-	 * array
157
-	 * @param array &$applied optional; array where the set fields will be given to
158
-	 * @return false|null
159
-	 */
160
-	public function setConfiguration($config, &$applied = null) {
161
-		if(!is_array($config)) {
162
-			return false;
163
-		}
151
+    /**
152
+     * set LDAP configuration with values delivered by an array, not read
153
+     * from configuration. It does not save the configuration! To do so, you
154
+     * must call saveConfiguration afterwards.
155
+     * @param array $config array that holds the config parameters in an associated
156
+     * array
157
+     * @param array &$applied optional; array where the set fields will be given to
158
+     * @return false|null
159
+     */
160
+    public function setConfiguration($config, &$applied = null) {
161
+        if(!is_array($config)) {
162
+            return false;
163
+        }
164 164
 
165
-		$cta = $this->getConfigTranslationArray();
166
-		foreach($config as $inputKey => $val) {
167
-			if(strpos($inputKey, '_') !== false && array_key_exists($inputKey, $cta)) {
168
-				$key = $cta[$inputKey];
169
-			} elseif(array_key_exists($inputKey, $this->config)) {
170
-				$key = $inputKey;
171
-			} else {
172
-				continue;
173
-			}
165
+        $cta = $this->getConfigTranslationArray();
166
+        foreach($config as $inputKey => $val) {
167
+            if(strpos($inputKey, '_') !== false && array_key_exists($inputKey, $cta)) {
168
+                $key = $cta[$inputKey];
169
+            } elseif(array_key_exists($inputKey, $this->config)) {
170
+                $key = $inputKey;
171
+            } else {
172
+                continue;
173
+            }
174 174
 
175
-			$setMethod = 'setValue';
176
-			switch($key) {
177
-				case 'ldapAgentPassword':
178
-					$setMethod = 'setRawValue';
179
-					break;
180
-				case 'homeFolderNamingRule':
181
-					$trimmedVal = trim($val);
182
-					if ($trimmedVal !== '' && strpos($val, 'attr:') === false) {
183
-						$val = 'attr:'.$trimmedVal;
184
-					}
185
-					break;
186
-				case 'ldapBase':
187
-				case 'ldapBaseUsers':
188
-				case 'ldapBaseGroups':
189
-				case 'ldapAttributesForUserSearch':
190
-				case 'ldapAttributesForGroupSearch':
191
-				case 'ldapUserFilterObjectclass':
192
-				case 'ldapUserFilterGroups':
193
-				case 'ldapGroupFilterObjectclass':
194
-				case 'ldapGroupFilterGroups':
195
-				case 'ldapLoginFilterAttributes':
196
-					$setMethod = 'setMultiLine';
197
-					break;
198
-			}
199
-			$this->$setMethod($key, $val);
200
-			if(is_array($applied)) {
201
-				$applied[] = $inputKey;
202
-				// storing key as index avoids duplication, and as value for simplicity
203
-			}
204
-			$this->unsavedChanges[$key] = $key;
205
-		}
206
-		return null;
207
-	}
175
+            $setMethod = 'setValue';
176
+            switch($key) {
177
+                case 'ldapAgentPassword':
178
+                    $setMethod = 'setRawValue';
179
+                    break;
180
+                case 'homeFolderNamingRule':
181
+                    $trimmedVal = trim($val);
182
+                    if ($trimmedVal !== '' && strpos($val, 'attr:') === false) {
183
+                        $val = 'attr:'.$trimmedVal;
184
+                    }
185
+                    break;
186
+                case 'ldapBase':
187
+                case 'ldapBaseUsers':
188
+                case 'ldapBaseGroups':
189
+                case 'ldapAttributesForUserSearch':
190
+                case 'ldapAttributesForGroupSearch':
191
+                case 'ldapUserFilterObjectclass':
192
+                case 'ldapUserFilterGroups':
193
+                case 'ldapGroupFilterObjectclass':
194
+                case 'ldapGroupFilterGroups':
195
+                case 'ldapLoginFilterAttributes':
196
+                    $setMethod = 'setMultiLine';
197
+                    break;
198
+            }
199
+            $this->$setMethod($key, $val);
200
+            if(is_array($applied)) {
201
+                $applied[] = $inputKey;
202
+                // storing key as index avoids duplication, and as value for simplicity
203
+            }
204
+            $this->unsavedChanges[$key] = $key;
205
+        }
206
+        return null;
207
+    }
208 208
 
209
-	public function readConfiguration() {
210
-		if(!$this->configRead && !is_null($this->configPrefix)) {
211
-			$cta = array_flip($this->getConfigTranslationArray());
212
-			foreach($this->config as $key => $val) {
213
-				if(!isset($cta[$key])) {
214
-					//some are determined
215
-					continue;
216
-				}
217
-				$dbKey = $cta[$key];
218
-				switch($key) {
219
-					case 'ldapBase':
220
-					case 'ldapBaseUsers':
221
-					case 'ldapBaseGroups':
222
-					case 'ldapAttributesForUserSearch':
223
-					case 'ldapAttributesForGroupSearch':
224
-					case 'ldapUserFilterObjectclass':
225
-					case 'ldapUserFilterGroups':
226
-					case 'ldapGroupFilterObjectclass':
227
-					case 'ldapGroupFilterGroups':
228
-					case 'ldapLoginFilterAttributes':
229
-						$readMethod = 'getMultiLine';
230
-						break;
231
-					case 'ldapIgnoreNamingRules':
232
-						$readMethod = 'getSystemValue';
233
-						$dbKey = $key;
234
-						break;
235
-					case 'ldapAgentPassword':
236
-						$readMethod = 'getPwd';
237
-						break;
238
-					case 'ldapUserDisplayName2':
239
-					case 'ldapGroupDisplayName':
240
-						$readMethod = 'getLcValue';
241
-						break;
242
-					case 'ldapUserDisplayName':
243
-					default:
244
-						// user display name does not lower case because
245
-						// we rely on an upper case N as indicator whether to
246
-						// auto-detect it or not. FIXME
247
-						$readMethod = 'getValue';
248
-						break;
249
-				}
250
-				$this->config[$key] = $this->$readMethod($dbKey);
251
-			}
252
-			$this->configRead = true;
253
-		}
254
-	}
209
+    public function readConfiguration() {
210
+        if(!$this->configRead && !is_null($this->configPrefix)) {
211
+            $cta = array_flip($this->getConfigTranslationArray());
212
+            foreach($this->config as $key => $val) {
213
+                if(!isset($cta[$key])) {
214
+                    //some are determined
215
+                    continue;
216
+                }
217
+                $dbKey = $cta[$key];
218
+                switch($key) {
219
+                    case 'ldapBase':
220
+                    case 'ldapBaseUsers':
221
+                    case 'ldapBaseGroups':
222
+                    case 'ldapAttributesForUserSearch':
223
+                    case 'ldapAttributesForGroupSearch':
224
+                    case 'ldapUserFilterObjectclass':
225
+                    case 'ldapUserFilterGroups':
226
+                    case 'ldapGroupFilterObjectclass':
227
+                    case 'ldapGroupFilterGroups':
228
+                    case 'ldapLoginFilterAttributes':
229
+                        $readMethod = 'getMultiLine';
230
+                        break;
231
+                    case 'ldapIgnoreNamingRules':
232
+                        $readMethod = 'getSystemValue';
233
+                        $dbKey = $key;
234
+                        break;
235
+                    case 'ldapAgentPassword':
236
+                        $readMethod = 'getPwd';
237
+                        break;
238
+                    case 'ldapUserDisplayName2':
239
+                    case 'ldapGroupDisplayName':
240
+                        $readMethod = 'getLcValue';
241
+                        break;
242
+                    case 'ldapUserDisplayName':
243
+                    default:
244
+                        // user display name does not lower case because
245
+                        // we rely on an upper case N as indicator whether to
246
+                        // auto-detect it or not. FIXME
247
+                        $readMethod = 'getValue';
248
+                        break;
249
+                }
250
+                $this->config[$key] = $this->$readMethod($dbKey);
251
+            }
252
+            $this->configRead = true;
253
+        }
254
+    }
255 255
 
256
-	/**
257
-	 * saves the current config changes in the database
258
-	 */
259
-	public function saveConfiguration() {
260
-		$cta = array_flip($this->getConfigTranslationArray());
261
-		foreach($this->unsavedChanges as $key) {
262
-			$value = $this->config[$key];
263
-			switch ($key) {
264
-				case 'ldapAgentPassword':
265
-					$value = base64_encode($value);
266
-					break;
267
-				case 'ldapBase':
268
-				case 'ldapBaseUsers':
269
-				case 'ldapBaseGroups':
270
-				case 'ldapAttributesForUserSearch':
271
-				case 'ldapAttributesForGroupSearch':
272
-				case 'ldapUserFilterObjectclass':
273
-				case 'ldapUserFilterGroups':
274
-				case 'ldapGroupFilterObjectclass':
275
-				case 'ldapGroupFilterGroups':
276
-				case 'ldapLoginFilterAttributes':
277
-					if(is_array($value)) {
278
-						$value = implode("\n", $value);
279
-					}
280
-					break;
281
-				//following options are not stored but detected, skip them
282
-				case 'ldapIgnoreNamingRules':
283
-				case 'ldapUuidUserAttribute':
284
-				case 'ldapUuidGroupAttribute':
285
-					continue 2;
286
-			}
287
-			if(is_null($value)) {
288
-				$value = '';
289
-			}
290
-			$this->saveValue($cta[$key], $value);
291
-		}
292
-		$this->saveValue('_lastChange', time());
293
-		$this->unsavedChanges = [];
294
-	}
256
+    /**
257
+     * saves the current config changes in the database
258
+     */
259
+    public function saveConfiguration() {
260
+        $cta = array_flip($this->getConfigTranslationArray());
261
+        foreach($this->unsavedChanges as $key) {
262
+            $value = $this->config[$key];
263
+            switch ($key) {
264
+                case 'ldapAgentPassword':
265
+                    $value = base64_encode($value);
266
+                    break;
267
+                case 'ldapBase':
268
+                case 'ldapBaseUsers':
269
+                case 'ldapBaseGroups':
270
+                case 'ldapAttributesForUserSearch':
271
+                case 'ldapAttributesForGroupSearch':
272
+                case 'ldapUserFilterObjectclass':
273
+                case 'ldapUserFilterGroups':
274
+                case 'ldapGroupFilterObjectclass':
275
+                case 'ldapGroupFilterGroups':
276
+                case 'ldapLoginFilterAttributes':
277
+                    if(is_array($value)) {
278
+                        $value = implode("\n", $value);
279
+                    }
280
+                    break;
281
+                //following options are not stored but detected, skip them
282
+                case 'ldapIgnoreNamingRules':
283
+                case 'ldapUuidUserAttribute':
284
+                case 'ldapUuidGroupAttribute':
285
+                    continue 2;
286
+            }
287
+            if(is_null($value)) {
288
+                $value = '';
289
+            }
290
+            $this->saveValue($cta[$key], $value);
291
+        }
292
+        $this->saveValue('_lastChange', time());
293
+        $this->unsavedChanges = [];
294
+    }
295 295
 
296
-	/**
297
-	 * @param string $varName
298
-	 * @return array|string
299
-	 */
300
-	protected function getMultiLine($varName) {
301
-		$value = $this->getValue($varName);
302
-		if(empty($value)) {
303
-			$value = '';
304
-		} else {
305
-			$value = preg_split('/\r\n|\r|\n/', $value);
306
-		}
296
+    /**
297
+     * @param string $varName
298
+     * @return array|string
299
+     */
300
+    protected function getMultiLine($varName) {
301
+        $value = $this->getValue($varName);
302
+        if(empty($value)) {
303
+            $value = '';
304
+        } else {
305
+            $value = preg_split('/\r\n|\r|\n/', $value);
306
+        }
307 307
 
308
-		return $value;
309
-	}
308
+        return $value;
309
+    }
310 310
 
311
-	/**
312
-	 * Sets multi-line values as arrays
313
-	 * 
314
-	 * @param string $varName name of config-key
315
-	 * @param array|string $value to set
316
-	 */
317
-	protected function setMultiLine($varName, $value) {
318
-		if(empty($value)) {
319
-			$value = '';
320
-		} else if (!is_array($value)) {
321
-			$value = preg_split('/\r\n|\r|\n|;/', $value);
322
-			if($value === false) {
323
-				$value = '';
324
-			}
325
-		}
311
+    /**
312
+     * Sets multi-line values as arrays
313
+     * 
314
+     * @param string $varName name of config-key
315
+     * @param array|string $value to set
316
+     */
317
+    protected function setMultiLine($varName, $value) {
318
+        if(empty($value)) {
319
+            $value = '';
320
+        } else if (!is_array($value)) {
321
+            $value = preg_split('/\r\n|\r|\n|;/', $value);
322
+            if($value === false) {
323
+                $value = '';
324
+            }
325
+        }
326 326
 
327
-		if(!is_array($value)) {
328
-			$finalValue = trim($value);
329
-		} else {
330
-			$finalValue = [];
331
-			foreach($value as $key => $val) {
332
-				if(is_string($val)) {
333
-					$val = trim($val);
334
-					if ($val !== '') {
335
-						//accidental line breaks are not wanted and can cause
336
-						// odd behaviour. Thus, away with them.
337
-						$finalValue[] = $val;
338
-					}
339
-				} else {
340
-					$finalValue[] = $val;
341
-				}
342
-			}
343
-		}
327
+        if(!is_array($value)) {
328
+            $finalValue = trim($value);
329
+        } else {
330
+            $finalValue = [];
331
+            foreach($value as $key => $val) {
332
+                if(is_string($val)) {
333
+                    $val = trim($val);
334
+                    if ($val !== '') {
335
+                        //accidental line breaks are not wanted and can cause
336
+                        // odd behaviour. Thus, away with them.
337
+                        $finalValue[] = $val;
338
+                    }
339
+                } else {
340
+                    $finalValue[] = $val;
341
+                }
342
+            }
343
+        }
344 344
 
345
-		$this->setRawValue($varName, $finalValue);
346
-	}
345
+        $this->setRawValue($varName, $finalValue);
346
+    }
347 347
 
348
-	/**
349
-	 * @param string $varName
350
-	 * @return string
351
-	 */
352
-	protected function getPwd($varName) {
353
-		return base64_decode($this->getValue($varName));
354
-	}
348
+    /**
349
+     * @param string $varName
350
+     * @return string
351
+     */
352
+    protected function getPwd($varName) {
353
+        return base64_decode($this->getValue($varName));
354
+    }
355 355
 
356
-	/**
357
-	 * @param string $varName
358
-	 * @return string
359
-	 */
360
-	protected function getLcValue($varName) {
361
-		return mb_strtolower($this->getValue($varName), 'UTF-8');
362
-	}
356
+    /**
357
+     * @param string $varName
358
+     * @return string
359
+     */
360
+    protected function getLcValue($varName) {
361
+        return mb_strtolower($this->getValue($varName), 'UTF-8');
362
+    }
363 363
 
364
-	/**
365
-	 * @param string $varName
366
-	 * @return string
367
-	 */
368
-	protected function getSystemValue($varName) {
369
-		//FIXME: if another system value is added, softcode the default value
370
-		return \OC::$server->getConfig()->getSystemValue($varName, false);
371
-	}
364
+    /**
365
+     * @param string $varName
366
+     * @return string
367
+     */
368
+    protected function getSystemValue($varName) {
369
+        //FIXME: if another system value is added, softcode the default value
370
+        return \OC::$server->getConfig()->getSystemValue($varName, false);
371
+    }
372 372
 
373
-	/**
374
-	 * @param string $varName
375
-	 * @return string
376
-	 */
377
-	protected function getValue($varName) {
378
-		static $defaults;
379
-		if(is_null($defaults)) {
380
-			$defaults = $this->getDefaults();
381
-		}
382
-		return \OC::$server->getConfig()->getAppValue('user_ldap',
383
-										$this->configPrefix.$varName,
384
-										$defaults[$varName]);
385
-	}
373
+    /**
374
+     * @param string $varName
375
+     * @return string
376
+     */
377
+    protected function getValue($varName) {
378
+        static $defaults;
379
+        if(is_null($defaults)) {
380
+            $defaults = $this->getDefaults();
381
+        }
382
+        return \OC::$server->getConfig()->getAppValue('user_ldap',
383
+                                        $this->configPrefix.$varName,
384
+                                        $defaults[$varName]);
385
+    }
386 386
 
387
-	/**
388
-	 * Sets a scalar value.
389
-	 * 
390
-	 * @param string $varName name of config key
391
-	 * @param mixed $value to set
392
-	 */
393
-	protected function setValue($varName, $value) {
394
-		if(is_string($value)) {
395
-			$value = trim($value);
396
-		}
397
-		$this->config[$varName] = $value;
398
-	}
387
+    /**
388
+     * Sets a scalar value.
389
+     * 
390
+     * @param string $varName name of config key
391
+     * @param mixed $value to set
392
+     */
393
+    protected function setValue($varName, $value) {
394
+        if(is_string($value)) {
395
+            $value = trim($value);
396
+        }
397
+        $this->config[$varName] = $value;
398
+    }
399 399
 
400
-	/**
401
-	 * Sets a scalar value without trimming.
402
-	 *
403
-	 * @param string $varName name of config key
404
-	 * @param mixed $value to set
405
-	 */
406
-	protected function setRawValue($varName, $value) {
407
-		$this->config[$varName] = $value;
408
-	}
400
+    /**
401
+     * Sets a scalar value without trimming.
402
+     *
403
+     * @param string $varName name of config key
404
+     * @param mixed $value to set
405
+     */
406
+    protected function setRawValue($varName, $value) {
407
+        $this->config[$varName] = $value;
408
+    }
409 409
 
410
-	/**
411
-	 * @param string $varName
412
-	 * @param string $value
413
-	 * @return bool
414
-	 */
415
-	protected function saveValue($varName, $value) {
416
-		\OC::$server->getConfig()->setAppValue(
417
-			'user_ldap',
418
-			$this->configPrefix.$varName,
419
-			$value
420
-		);
421
-		return true;
422
-	}
410
+    /**
411
+     * @param string $varName
412
+     * @param string $value
413
+     * @return bool
414
+     */
415
+    protected function saveValue($varName, $value) {
416
+        \OC::$server->getConfig()->setAppValue(
417
+            'user_ldap',
418
+            $this->configPrefix.$varName,
419
+            $value
420
+        );
421
+        return true;
422
+    }
423 423
 
424
-	/**
425
-	 * @return array an associative array with the default values. Keys are correspond
426
-	 * to config-value entries in the database table
427
-	 */
428
-	public function getDefaults() {
429
-		return [
430
-			'ldap_host'                         => '',
431
-			'ldap_port'                         => '',
432
-			'ldap_backup_host'                  => '',
433
-			'ldap_backup_port'                  => '',
434
-			'ldap_override_main_server'         => '',
435
-			'ldap_dn'                           => '',
436
-			'ldap_agent_password'               => '',
437
-			'ldap_base'                         => '',
438
-			'ldap_base_users'                   => '',
439
-			'ldap_base_groups'                  => '',
440
-			'ldap_userlist_filter'              => '',
441
-			'ldap_user_filter_mode'             => 0,
442
-			'ldap_userfilter_objectclass'       => '',
443
-			'ldap_userfilter_groups'            => '',
444
-			'ldap_login_filter'                 => '',
445
-			'ldap_login_filter_mode'            => 0,
446
-			'ldap_loginfilter_email'            => 0,
447
-			'ldap_loginfilter_username'         => 1,
448
-			'ldap_loginfilter_attributes'       => '',
449
-			'ldap_group_filter'                 => '',
450
-			'ldap_group_filter_mode'            => 0,
451
-			'ldap_groupfilter_objectclass'      => '',
452
-			'ldap_groupfilter_groups'           => '',
453
-			'ldap_gid_number'                   => 'gidNumber',
454
-			'ldap_display_name'                 => 'displayName',
455
-			'ldap_user_display_name_2'			=> '',
456
-			'ldap_group_display_name'           => 'cn',
457
-			'ldap_tls'                          => 0,
458
-			'ldap_quota_def'                    => '',
459
-			'ldap_quota_attr'                   => '',
460
-			'ldap_email_attr'                   => '',
461
-			'ldap_group_member_assoc_attribute' => '',
462
-			'ldap_cache_ttl'                    => 600,
463
-			'ldap_uuid_user_attribute'          => 'auto',
464
-			'ldap_uuid_group_attribute'         => 'auto',
465
-			'home_folder_naming_rule'           => '',
466
-			'ldap_turn_off_cert_check'          => 0,
467
-			'ldap_configuration_active'         => 0,
468
-			'ldap_attributes_for_user_search'   => '',
469
-			'ldap_attributes_for_group_search'  => '',
470
-			'ldap_expert_username_attr'         => '',
471
-			'ldap_expert_uuid_user_attr'        => '',
472
-			'ldap_expert_uuid_group_attr'       => '',
473
-			'has_memberof_filter_support'       => 0,
474
-			'use_memberof_to_detect_membership' => 1,
475
-			'last_jpegPhoto_lookup'             => 0,
476
-			'ldap_nested_groups'                => 0,
477
-			'ldap_paging_size'                  => 500,
478
-			'ldap_turn_on_pwd_change'           => 0,
479
-			'ldap_experienced_admin'            => 0,
480
-			'ldap_dynamic_group_member_url'     => '',
481
-			'ldap_default_ppolicy_dn'           => '',
482
-			'ldap_user_avatar_rule'             => 'default',
483
-			'ldap_ext_storage_home_attribute'   => '',
484
-		];
485
-	}
424
+    /**
425
+     * @return array an associative array with the default values. Keys are correspond
426
+     * to config-value entries in the database table
427
+     */
428
+    public function getDefaults() {
429
+        return [
430
+            'ldap_host'                         => '',
431
+            'ldap_port'                         => '',
432
+            'ldap_backup_host'                  => '',
433
+            'ldap_backup_port'                  => '',
434
+            'ldap_override_main_server'         => '',
435
+            'ldap_dn'                           => '',
436
+            'ldap_agent_password'               => '',
437
+            'ldap_base'                         => '',
438
+            'ldap_base_users'                   => '',
439
+            'ldap_base_groups'                  => '',
440
+            'ldap_userlist_filter'              => '',
441
+            'ldap_user_filter_mode'             => 0,
442
+            'ldap_userfilter_objectclass'       => '',
443
+            'ldap_userfilter_groups'            => '',
444
+            'ldap_login_filter'                 => '',
445
+            'ldap_login_filter_mode'            => 0,
446
+            'ldap_loginfilter_email'            => 0,
447
+            'ldap_loginfilter_username'         => 1,
448
+            'ldap_loginfilter_attributes'       => '',
449
+            'ldap_group_filter'                 => '',
450
+            'ldap_group_filter_mode'            => 0,
451
+            'ldap_groupfilter_objectclass'      => '',
452
+            'ldap_groupfilter_groups'           => '',
453
+            'ldap_gid_number'                   => 'gidNumber',
454
+            'ldap_display_name'                 => 'displayName',
455
+            'ldap_user_display_name_2'			=> '',
456
+            'ldap_group_display_name'           => 'cn',
457
+            'ldap_tls'                          => 0,
458
+            'ldap_quota_def'                    => '',
459
+            'ldap_quota_attr'                   => '',
460
+            'ldap_email_attr'                   => '',
461
+            'ldap_group_member_assoc_attribute' => '',
462
+            'ldap_cache_ttl'                    => 600,
463
+            'ldap_uuid_user_attribute'          => 'auto',
464
+            'ldap_uuid_group_attribute'         => 'auto',
465
+            'home_folder_naming_rule'           => '',
466
+            'ldap_turn_off_cert_check'          => 0,
467
+            'ldap_configuration_active'         => 0,
468
+            'ldap_attributes_for_user_search'   => '',
469
+            'ldap_attributes_for_group_search'  => '',
470
+            'ldap_expert_username_attr'         => '',
471
+            'ldap_expert_uuid_user_attr'        => '',
472
+            'ldap_expert_uuid_group_attr'       => '',
473
+            'has_memberof_filter_support'       => 0,
474
+            'use_memberof_to_detect_membership' => 1,
475
+            'last_jpegPhoto_lookup'             => 0,
476
+            'ldap_nested_groups'                => 0,
477
+            'ldap_paging_size'                  => 500,
478
+            'ldap_turn_on_pwd_change'           => 0,
479
+            'ldap_experienced_admin'            => 0,
480
+            'ldap_dynamic_group_member_url'     => '',
481
+            'ldap_default_ppolicy_dn'           => '',
482
+            'ldap_user_avatar_rule'             => 'default',
483
+            'ldap_ext_storage_home_attribute'   => '',
484
+        ];
485
+    }
486 486
 
487
-	/**
488
-	 * @return array that maps internal variable names to database fields
489
-	 */
490
-	public function getConfigTranslationArray() {
491
-		//TODO: merge them into one representation
492
-		static $array = [
493
-			'ldap_host'                         => 'ldapHost',
494
-			'ldap_port'                         => 'ldapPort',
495
-			'ldap_backup_host'                  => 'ldapBackupHost',
496
-			'ldap_backup_port'                  => 'ldapBackupPort',
497
-			'ldap_override_main_server'         => 'ldapOverrideMainServer',
498
-			'ldap_dn'                           => 'ldapAgentName',
499
-			'ldap_agent_password'               => 'ldapAgentPassword',
500
-			'ldap_base'                         => 'ldapBase',
501
-			'ldap_base_users'                   => 'ldapBaseUsers',
502
-			'ldap_base_groups'                  => 'ldapBaseGroups',
503
-			'ldap_userfilter_objectclass'       => 'ldapUserFilterObjectclass',
504
-			'ldap_userfilter_groups'            => 'ldapUserFilterGroups',
505
-			'ldap_userlist_filter'              => 'ldapUserFilter',
506
-			'ldap_user_filter_mode'             => 'ldapUserFilterMode',
507
-			'ldap_user_avatar_rule'             => 'ldapUserAvatarRule',
508
-			'ldap_login_filter'                 => 'ldapLoginFilter',
509
-			'ldap_login_filter_mode'            => 'ldapLoginFilterMode',
510
-			'ldap_loginfilter_email'            => 'ldapLoginFilterEmail',
511
-			'ldap_loginfilter_username'         => 'ldapLoginFilterUsername',
512
-			'ldap_loginfilter_attributes'       => 'ldapLoginFilterAttributes',
513
-			'ldap_group_filter'                 => 'ldapGroupFilter',
514
-			'ldap_group_filter_mode'            => 'ldapGroupFilterMode',
515
-			'ldap_groupfilter_objectclass'      => 'ldapGroupFilterObjectclass',
516
-			'ldap_groupfilter_groups'           => 'ldapGroupFilterGroups',
517
-			'ldap_gid_number'                   => 'ldapGidNumber',
518
-			'ldap_display_name'                 => 'ldapUserDisplayName',
519
-			'ldap_user_display_name_2'			=> 'ldapUserDisplayName2',
520
-			'ldap_group_display_name'           => 'ldapGroupDisplayName',
521
-			'ldap_tls'                          => 'ldapTLS',
522
-			'ldap_quota_def'                    => 'ldapQuotaDefault',
523
-			'ldap_quota_attr'                   => 'ldapQuotaAttribute',
524
-			'ldap_email_attr'                   => 'ldapEmailAttribute',
525
-			'ldap_group_member_assoc_attribute' => 'ldapGroupMemberAssocAttr',
526
-			'ldap_cache_ttl'                    => 'ldapCacheTTL',
527
-			'home_folder_naming_rule'           => 'homeFolderNamingRule',
528
-			'ldap_turn_off_cert_check'          => 'turnOffCertCheck',
529
-			'ldap_configuration_active'         => 'ldapConfigurationActive',
530
-			'ldap_attributes_for_user_search'   => 'ldapAttributesForUserSearch',
531
-			'ldap_attributes_for_group_search'  => 'ldapAttributesForGroupSearch',
532
-			'ldap_expert_username_attr'         => 'ldapExpertUsernameAttr',
533
-			'ldap_expert_uuid_user_attr'        => 'ldapExpertUUIDUserAttr',
534
-			'ldap_expert_uuid_group_attr'       => 'ldapExpertUUIDGroupAttr',
535
-			'has_memberof_filter_support'       => 'hasMemberOfFilterSupport',
536
-			'use_memberof_to_detect_membership' => 'useMemberOfToDetectMembership',
537
-			'last_jpegPhoto_lookup'             => 'lastJpegPhotoLookup',
538
-			'ldap_nested_groups'                => 'ldapNestedGroups',
539
-			'ldap_paging_size'                  => 'ldapPagingSize',
540
-			'ldap_turn_on_pwd_change'           => 'turnOnPasswordChange',
541
-			'ldap_experienced_admin'            => 'ldapExperiencedAdmin',
542
-			'ldap_dynamic_group_member_url'     => 'ldapDynamicGroupMemberURL',
543
-			'ldap_default_ppolicy_dn'           => 'ldapDefaultPPolicyDN',
544
-			'ldap_ext_storage_home_attribute'   => 'ldapExtStorageHomeAttribute',
545
-			'ldapIgnoreNamingRules'             => 'ldapIgnoreNamingRules',	// sysconfig
546
-		];
547
-		return $array;
548
-	}
487
+    /**
488
+     * @return array that maps internal variable names to database fields
489
+     */
490
+    public function getConfigTranslationArray() {
491
+        //TODO: merge them into one representation
492
+        static $array = [
493
+            'ldap_host'                         => 'ldapHost',
494
+            'ldap_port'                         => 'ldapPort',
495
+            'ldap_backup_host'                  => 'ldapBackupHost',
496
+            'ldap_backup_port'                  => 'ldapBackupPort',
497
+            'ldap_override_main_server'         => 'ldapOverrideMainServer',
498
+            'ldap_dn'                           => 'ldapAgentName',
499
+            'ldap_agent_password'               => 'ldapAgentPassword',
500
+            'ldap_base'                         => 'ldapBase',
501
+            'ldap_base_users'                   => 'ldapBaseUsers',
502
+            'ldap_base_groups'                  => 'ldapBaseGroups',
503
+            'ldap_userfilter_objectclass'       => 'ldapUserFilterObjectclass',
504
+            'ldap_userfilter_groups'            => 'ldapUserFilterGroups',
505
+            'ldap_userlist_filter'              => 'ldapUserFilter',
506
+            'ldap_user_filter_mode'             => 'ldapUserFilterMode',
507
+            'ldap_user_avatar_rule'             => 'ldapUserAvatarRule',
508
+            'ldap_login_filter'                 => 'ldapLoginFilter',
509
+            'ldap_login_filter_mode'            => 'ldapLoginFilterMode',
510
+            'ldap_loginfilter_email'            => 'ldapLoginFilterEmail',
511
+            'ldap_loginfilter_username'         => 'ldapLoginFilterUsername',
512
+            'ldap_loginfilter_attributes'       => 'ldapLoginFilterAttributes',
513
+            'ldap_group_filter'                 => 'ldapGroupFilter',
514
+            'ldap_group_filter_mode'            => 'ldapGroupFilterMode',
515
+            'ldap_groupfilter_objectclass'      => 'ldapGroupFilterObjectclass',
516
+            'ldap_groupfilter_groups'           => 'ldapGroupFilterGroups',
517
+            'ldap_gid_number'                   => 'ldapGidNumber',
518
+            'ldap_display_name'                 => 'ldapUserDisplayName',
519
+            'ldap_user_display_name_2'			=> 'ldapUserDisplayName2',
520
+            'ldap_group_display_name'           => 'ldapGroupDisplayName',
521
+            'ldap_tls'                          => 'ldapTLS',
522
+            'ldap_quota_def'                    => 'ldapQuotaDefault',
523
+            'ldap_quota_attr'                   => 'ldapQuotaAttribute',
524
+            'ldap_email_attr'                   => 'ldapEmailAttribute',
525
+            'ldap_group_member_assoc_attribute' => 'ldapGroupMemberAssocAttr',
526
+            'ldap_cache_ttl'                    => 'ldapCacheTTL',
527
+            'home_folder_naming_rule'           => 'homeFolderNamingRule',
528
+            'ldap_turn_off_cert_check'          => 'turnOffCertCheck',
529
+            'ldap_configuration_active'         => 'ldapConfigurationActive',
530
+            'ldap_attributes_for_user_search'   => 'ldapAttributesForUserSearch',
531
+            'ldap_attributes_for_group_search'  => 'ldapAttributesForGroupSearch',
532
+            'ldap_expert_username_attr'         => 'ldapExpertUsernameAttr',
533
+            'ldap_expert_uuid_user_attr'        => 'ldapExpertUUIDUserAttr',
534
+            'ldap_expert_uuid_group_attr'       => 'ldapExpertUUIDGroupAttr',
535
+            'has_memberof_filter_support'       => 'hasMemberOfFilterSupport',
536
+            'use_memberof_to_detect_membership' => 'useMemberOfToDetectMembership',
537
+            'last_jpegPhoto_lookup'             => 'lastJpegPhotoLookup',
538
+            'ldap_nested_groups'                => 'ldapNestedGroups',
539
+            'ldap_paging_size'                  => 'ldapPagingSize',
540
+            'ldap_turn_on_pwd_change'           => 'turnOnPasswordChange',
541
+            'ldap_experienced_admin'            => 'ldapExperiencedAdmin',
542
+            'ldap_dynamic_group_member_url'     => 'ldapDynamicGroupMemberURL',
543
+            'ldap_default_ppolicy_dn'           => 'ldapDefaultPPolicyDN',
544
+            'ldap_ext_storage_home_attribute'   => 'ldapExtStorageHomeAttribute',
545
+            'ldapIgnoreNamingRules'             => 'ldapIgnoreNamingRules',	// sysconfig
546
+        ];
547
+        return $array;
548
+    }
549 549
 
550
-	/**
551
-	 * @param string $rule
552
-	 * @return array
553
-	 * @throws \RuntimeException
554
-	 */
555
-	public function resolveRule($rule) {
556
-		if($rule === 'avatar') {
557
-			return $this->getAvatarAttributes();
558
-		}
559
-		throw new \RuntimeException('Invalid rule');
560
-	}
550
+    /**
551
+     * @param string $rule
552
+     * @return array
553
+     * @throws \RuntimeException
554
+     */
555
+    public function resolveRule($rule) {
556
+        if($rule === 'avatar') {
557
+            return $this->getAvatarAttributes();
558
+        }
559
+        throw new \RuntimeException('Invalid rule');
560
+    }
561 561
 
562
-	public function getAvatarAttributes() {
563
-		$value = $this->ldapUserAvatarRule ?: self::AVATAR_PREFIX_DEFAULT;
564
-		$defaultAttributes = ['jpegphoto', 'thumbnailphoto'];
562
+    public function getAvatarAttributes() {
563
+        $value = $this->ldapUserAvatarRule ?: self::AVATAR_PREFIX_DEFAULT;
564
+        $defaultAttributes = ['jpegphoto', 'thumbnailphoto'];
565 565
 
566
-		if($value === self::AVATAR_PREFIX_NONE) {
567
-			return [];
568
-		}
569
-		if(strpos($value, self::AVATAR_PREFIX_DATA_ATTRIBUTE) === 0) {
570
-			$attribute = trim(substr($value, strlen(self::AVATAR_PREFIX_DATA_ATTRIBUTE)));
571
-			if($attribute === '') {
572
-				return $defaultAttributes;
573
-			}
574
-			return [strtolower($attribute)];
575
-		}
576
-		if($value !== self::AVATAR_PREFIX_DEFAULT) {
577
-			\OC::$server->getLogger()->warning('Invalid config value to ldapUserAvatarRule; falling back to default.');
578
-		}
579
-		return $defaultAttributes;
580
-	}
566
+        if($value === self::AVATAR_PREFIX_NONE) {
567
+            return [];
568
+        }
569
+        if(strpos($value, self::AVATAR_PREFIX_DATA_ATTRIBUTE) === 0) {
570
+            $attribute = trim(substr($value, strlen(self::AVATAR_PREFIX_DATA_ATTRIBUTE)));
571
+            if($attribute === '') {
572
+                return $defaultAttributes;
573
+            }
574
+            return [strtolower($attribute)];
575
+        }
576
+        if($value !== self::AVATAR_PREFIX_DEFAULT) {
577
+            \OC::$server->getLogger()->warning('Invalid config value to ldapUserAvatarRule; falling back to default.');
578
+        }
579
+        return $defaultAttributes;
580
+    }
581 581
 
582 582
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/Proxy.php 1 patch
Indentation   +166 added lines, -166 removed lines patch added patch discarded remove patch
@@ -37,170 +37,170 @@
 block discarded – undo
37 37
 use OCA\User_LDAP\User\Manager;
38 38
 
39 39
 abstract class Proxy {
40
-	static private $accesses = [];
41
-	private $ldap = null;
42
-
43
-	/** @var \OCP\ICache|null */
44
-	private $cache;
45
-
46
-	/**
47
-	 * @param ILDAPWrapper $ldap
48
-	 */
49
-	public function __construct(ILDAPWrapper $ldap) {
50
-		$this->ldap = $ldap;
51
-		$memcache = \OC::$server->getMemCacheFactory();
52
-		if($memcache->isAvailable()) {
53
-			$this->cache = $memcache->createDistributed();
54
-		}
55
-	}
56
-
57
-	/**
58
-	 * @param string $configPrefix
59
-	 */
60
-	private function addAccess($configPrefix) {
61
-		static $ocConfig;
62
-		static $fs;
63
-		static $log;
64
-		static $avatarM;
65
-		static $userMap;
66
-		static $groupMap;
67
-		static $db;
68
-		static $coreUserManager;
69
-		static $coreNotificationManager;
70
-		if($fs === null) {
71
-			$ocConfig = \OC::$server->getConfig();
72
-			$fs       = new FilesystemHelper();
73
-			$log      = new LogWrapper();
74
-			$avatarM  = \OC::$server->getAvatarManager();
75
-			$db       = \OC::$server->getDatabaseConnection();
76
-			$userMap  = new UserMapping($db);
77
-			$groupMap = new GroupMapping($db);
78
-			$coreUserManager = \OC::$server->getUserManager();
79
-			$coreNotificationManager = \OC::$server->getNotificationManager();
80
-		}
81
-		$userManager =
82
-			new Manager($ocConfig, $fs, $log, $avatarM, new \OCP\Image(), $db,
83
-				$coreUserManager, $coreNotificationManager);
84
-		$connector = new Connection($this->ldap, $configPrefix);
85
-		$access = new Access($connector, $this->ldap, $userManager, new Helper($ocConfig), $ocConfig, $coreUserManager);
86
-		$access->setUserMapper($userMap);
87
-		$access->setGroupMapper($groupMap);
88
-		self::$accesses[$configPrefix] = $access;
89
-	}
90
-
91
-	/**
92
-	 * @param string $configPrefix
93
-	 * @return mixed
94
-	 */
95
-	protected function getAccess($configPrefix) {
96
-		if(!isset(self::$accesses[$configPrefix])) {
97
-			$this->addAccess($configPrefix);
98
-		}
99
-		return self::$accesses[$configPrefix];
100
-	}
101
-
102
-	/**
103
-	 * @param string $uid
104
-	 * @return string
105
-	 */
106
-	protected function getUserCacheKey($uid) {
107
-		return 'user-'.$uid.'-lastSeenOn';
108
-	}
109
-
110
-	/**
111
-	 * @param string $gid
112
-	 * @return string
113
-	 */
114
-	protected function getGroupCacheKey($gid) {
115
-		return 'group-'.$gid.'-lastSeenOn';
116
-	}
117
-
118
-	/**
119
-	 * @param string $id
120
-	 * @param string $method
121
-	 * @param array $parameters
122
-	 * @param bool $passOnWhen
123
-	 * @return mixed
124
-	 */
125
-	abstract protected function callOnLastSeenOn($id, $method, $parameters, $passOnWhen);
126
-
127
-	/**
128
-	 * @param string $id
129
-	 * @param string $method
130
-	 * @param array $parameters
131
-	 * @return mixed
132
-	 */
133
-	abstract protected function walkBackends($id, $method, $parameters);
134
-
135
-	/**
136
-	 * @param string $id
137
-	 * @return Access
138
-	 */
139
-	abstract public function getLDAPAccess($id);
140
-
141
-	/**
142
-	 * Takes care of the request to the User backend
143
-	 * @param string $id
144
-	 * @param string $method string, the method of the user backend that shall be called
145
-	 * @param array $parameters an array of parameters to be passed
146
-	 * @param bool $passOnWhen
147
-	 * @return mixed, the result of the specified method
148
-	 */
149
-	protected function handleRequest($id, $method, $parameters, $passOnWhen = false) {
150
-		$result = $this->callOnLastSeenOn($id,  $method, $parameters, $passOnWhen);
151
-		if($result === $passOnWhen) {
152
-			$result = $this->walkBackends($id, $method, $parameters);
153
-		}
154
-		return $result;
155
-	}
156
-
157
-	/**
158
-	 * @param string|null $key
159
-	 * @return string
160
-	 */
161
-	private function getCacheKey($key) {
162
-		$prefix = 'LDAP-Proxy-';
163
-		if($key === null) {
164
-			return $prefix;
165
-		}
166
-		return $prefix.hash('sha256', $key);
167
-	}
168
-
169
-	/**
170
-	 * @param string $key
171
-	 * @return mixed|null
172
-	 */
173
-	public function getFromCache($key) {
174
-		if($this->cache === null) {
175
-			return null;
176
-		}
177
-
178
-		$key = $this->getCacheKey($key);
179
-		$value = $this->cache->get($key);
180
-		if ($value === null) {
181
-			return null;
182
-		}
183
-
184
-		return json_decode(base64_decode($value));
185
-	}
186
-
187
-	/**
188
-	 * @param string $key
189
-	 * @param mixed $value
190
-	 */
191
-	public function writeToCache($key, $value) {
192
-		if($this->cache === null) {
193
-			return;
194
-		}
195
-		$key   = $this->getCacheKey($key);
196
-		$value = base64_encode(json_encode($value));
197
-		$this->cache->set($key, $value, 2592000);
198
-	}
199
-
200
-	public function clearCache() {
201
-		if($this->cache === null) {
202
-			return;
203
-		}
204
-		$this->cache->clear($this->getCacheKey(null));
205
-	}
40
+    static private $accesses = [];
41
+    private $ldap = null;
42
+
43
+    /** @var \OCP\ICache|null */
44
+    private $cache;
45
+
46
+    /**
47
+     * @param ILDAPWrapper $ldap
48
+     */
49
+    public function __construct(ILDAPWrapper $ldap) {
50
+        $this->ldap = $ldap;
51
+        $memcache = \OC::$server->getMemCacheFactory();
52
+        if($memcache->isAvailable()) {
53
+            $this->cache = $memcache->createDistributed();
54
+        }
55
+    }
56
+
57
+    /**
58
+     * @param string $configPrefix
59
+     */
60
+    private function addAccess($configPrefix) {
61
+        static $ocConfig;
62
+        static $fs;
63
+        static $log;
64
+        static $avatarM;
65
+        static $userMap;
66
+        static $groupMap;
67
+        static $db;
68
+        static $coreUserManager;
69
+        static $coreNotificationManager;
70
+        if($fs === null) {
71
+            $ocConfig = \OC::$server->getConfig();
72
+            $fs       = new FilesystemHelper();
73
+            $log      = new LogWrapper();
74
+            $avatarM  = \OC::$server->getAvatarManager();
75
+            $db       = \OC::$server->getDatabaseConnection();
76
+            $userMap  = new UserMapping($db);
77
+            $groupMap = new GroupMapping($db);
78
+            $coreUserManager = \OC::$server->getUserManager();
79
+            $coreNotificationManager = \OC::$server->getNotificationManager();
80
+        }
81
+        $userManager =
82
+            new Manager($ocConfig, $fs, $log, $avatarM, new \OCP\Image(), $db,
83
+                $coreUserManager, $coreNotificationManager);
84
+        $connector = new Connection($this->ldap, $configPrefix);
85
+        $access = new Access($connector, $this->ldap, $userManager, new Helper($ocConfig), $ocConfig, $coreUserManager);
86
+        $access->setUserMapper($userMap);
87
+        $access->setGroupMapper($groupMap);
88
+        self::$accesses[$configPrefix] = $access;
89
+    }
90
+
91
+    /**
92
+     * @param string $configPrefix
93
+     * @return mixed
94
+     */
95
+    protected function getAccess($configPrefix) {
96
+        if(!isset(self::$accesses[$configPrefix])) {
97
+            $this->addAccess($configPrefix);
98
+        }
99
+        return self::$accesses[$configPrefix];
100
+    }
101
+
102
+    /**
103
+     * @param string $uid
104
+     * @return string
105
+     */
106
+    protected function getUserCacheKey($uid) {
107
+        return 'user-'.$uid.'-lastSeenOn';
108
+    }
109
+
110
+    /**
111
+     * @param string $gid
112
+     * @return string
113
+     */
114
+    protected function getGroupCacheKey($gid) {
115
+        return 'group-'.$gid.'-lastSeenOn';
116
+    }
117
+
118
+    /**
119
+     * @param string $id
120
+     * @param string $method
121
+     * @param array $parameters
122
+     * @param bool $passOnWhen
123
+     * @return mixed
124
+     */
125
+    abstract protected function callOnLastSeenOn($id, $method, $parameters, $passOnWhen);
126
+
127
+    /**
128
+     * @param string $id
129
+     * @param string $method
130
+     * @param array $parameters
131
+     * @return mixed
132
+     */
133
+    abstract protected function walkBackends($id, $method, $parameters);
134
+
135
+    /**
136
+     * @param string $id
137
+     * @return Access
138
+     */
139
+    abstract public function getLDAPAccess($id);
140
+
141
+    /**
142
+     * Takes care of the request to the User backend
143
+     * @param string $id
144
+     * @param string $method string, the method of the user backend that shall be called
145
+     * @param array $parameters an array of parameters to be passed
146
+     * @param bool $passOnWhen
147
+     * @return mixed, the result of the specified method
148
+     */
149
+    protected function handleRequest($id, $method, $parameters, $passOnWhen = false) {
150
+        $result = $this->callOnLastSeenOn($id,  $method, $parameters, $passOnWhen);
151
+        if($result === $passOnWhen) {
152
+            $result = $this->walkBackends($id, $method, $parameters);
153
+        }
154
+        return $result;
155
+    }
156
+
157
+    /**
158
+     * @param string|null $key
159
+     * @return string
160
+     */
161
+    private function getCacheKey($key) {
162
+        $prefix = 'LDAP-Proxy-';
163
+        if($key === null) {
164
+            return $prefix;
165
+        }
166
+        return $prefix.hash('sha256', $key);
167
+    }
168
+
169
+    /**
170
+     * @param string $key
171
+     * @return mixed|null
172
+     */
173
+    public function getFromCache($key) {
174
+        if($this->cache === null) {
175
+            return null;
176
+        }
177
+
178
+        $key = $this->getCacheKey($key);
179
+        $value = $this->cache->get($key);
180
+        if ($value === null) {
181
+            return null;
182
+        }
183
+
184
+        return json_decode(base64_decode($value));
185
+    }
186
+
187
+    /**
188
+     * @param string $key
189
+     * @param mixed $value
190
+     */
191
+    public function writeToCache($key, $value) {
192
+        if($this->cache === null) {
193
+            return;
194
+        }
195
+        $key   = $this->getCacheKey($key);
196
+        $value = base64_encode(json_encode($value));
197
+        $this->cache->set($key, $value, 2592000);
198
+    }
199
+
200
+    public function clearCache() {
201
+        if($this->cache === null) {
202
+            return;
203
+        }
204
+        $this->cache->clear($this->getCacheKey(null));
205
+    }
206 206
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/Jobs/Sync.php 1 patch
Indentation   +338 added lines, -338 removed lines patch added patch discarded remove patch
@@ -42,343 +42,343 @@
 block discarded – undo
42 42
 use OCP\Notification\IManager;
43 43
 
44 44
 class Sync extends TimedJob {
45
-	const MAX_INTERVAL = 12 * 60 * 60; // 12h
46
-	const MIN_INTERVAL = 30 * 60; // 30min
47
-	/** @var  Helper */
48
-	protected $ldapHelper;
49
-	/** @var  LDAP */
50
-	protected $ldap;
51
-	/** @var  Manager */
52
-	protected $userManager;
53
-	/** @var UserMapping */
54
-	protected $mapper;
55
-	/** @var  IConfig */
56
-	protected $config;
57
-	/** @var  IAvatarManager */
58
-	protected $avatarManager;
59
-	/** @var  IDBConnection */
60
-	protected $dbc;
61
-	/** @var  IUserManager */
62
-	protected $ncUserManager;
63
-	/** @var  IManager */
64
-	protected $notificationManager;
65
-	/** @var ConnectionFactory */
66
-	protected $connectionFactory;
67
-	/** @var AccessFactory */
68
-	protected $accessFactory;
69
-
70
-	public function __construct() {
71
-		$this->setInterval(
72
-			\OC::$server->getConfig()->getAppValue(
73
-				'user_ldap',
74
-				'background_sync_interval',
75
-				self::MIN_INTERVAL
76
-			)
77
-		);
78
-	}
79
-
80
-	/**
81
-	 * updates the interval
82
-	 *
83
-	 * the idea is to adjust the interval depending on the amount of known users
84
-	 * and the attempt to update each user one day. At most it would run every
85
-	 * 30 minutes, and at least every 12 hours.
86
-	 */
87
-	public function updateInterval() {
88
-		$minPagingSize = $this->getMinPagingSize();
89
-		$mappedUsers = $this->mapper->count();
90
-
91
-		$runsPerDay = ($minPagingSize === 0 || $mappedUsers === 0) ? self::MAX_INTERVAL
92
-			: $mappedUsers / $minPagingSize;
93
-		$interval = floor(24 * 60 * 60 / $runsPerDay);
94
-		$interval = min(max($interval, self::MIN_INTERVAL), self::MAX_INTERVAL);
95
-
96
-		$this->config->setAppValue('user_ldap', 'background_sync_interval', $interval);
97
-	}
98
-
99
-	/**
100
-	 * returns the smallest configured paging size
101
-	 * @return int
102
-	 */
103
-	protected function getMinPagingSize() {
104
-		$configKeys = $this->config->getAppKeys('user_ldap');
105
-		$configKeys = array_filter($configKeys, function($key) {
106
-			return strpos($key, 'ldap_paging_size') !== false;
107
-		});
108
-		$minPagingSize = null;
109
-		foreach ($configKeys as $configKey) {
110
-			$pagingSize = $this->config->getAppValue('user_ldap', $configKey, $minPagingSize);
111
-			$minPagingSize = $minPagingSize === null ? $pagingSize : min($minPagingSize, $pagingSize);
112
-		}
113
-		return (int)$minPagingSize;
114
-	}
115
-
116
-	/**
117
-	 * @param array $argument
118
-	 */
119
-	public function run($argument) {
120
-		$this->setArgument($argument);
121
-
122
-		$isBackgroundJobModeAjax = $this->config
123
-				->getAppValue('core', 'backgroundjobs_mode', 'ajax') === 'ajax';
124
-		if($isBackgroundJobModeAjax) {
125
-			return;
126
-		}
127
-
128
-		$cycleData = $this->getCycle();
129
-		if($cycleData === null) {
130
-			$cycleData = $this->determineNextCycle();
131
-			if($cycleData === null) {
132
-				$this->updateInterval();
133
-				return;
134
-			}
135
-		}
136
-
137
-		if(!$this->qualifiesToRun($cycleData)) {
138
-			$this->updateInterval();
139
-			return;
140
-		}
141
-
142
-		try {
143
-			$expectMoreResults = $this->runCycle($cycleData);
144
-			if ($expectMoreResults) {
145
-				$this->increaseOffset($cycleData);
146
-			} else {
147
-				$this->determineNextCycle($cycleData);
148
-			}
149
-			$this->updateInterval();
150
-		} catch (ServerNotAvailableException $e) {
151
-			$this->determineNextCycle($cycleData);
152
-		}
153
-	}
154
-
155
-	/**
156
-	 * @param array $cycleData
157
-	 * @return bool whether more results are expected from the same configuration
158
-	 */
159
-	public function runCycle($cycleData) {
160
-		$connection = $this->connectionFactory->get($cycleData['prefix']);
161
-		$access = $this->accessFactory->get($connection);
162
-		$access->setUserMapper($this->mapper);
163
-
164
-		$filter = $access->combineFilterWithAnd([
165
-			$access->connection->ldapUserFilter,
166
-			$access->connection->ldapUserDisplayName . '=*',
167
-			$access->getFilterPartForUserSearch('')
168
-		]);
169
-		$results = $access->fetchListOfUsers(
170
-			$filter,
171
-			$access->userManager->getAttributes(),
172
-			$connection->ldapPagingSize,
173
-			$cycleData['offset'],
174
-			true
175
-		);
176
-
177
-		if((int)$connection->ldapPagingSize === 0) {
178
-			return false;
179
-		}
180
-		return count($results) >= (int)$connection->ldapPagingSize;
181
-	}
182
-
183
-	/**
184
-	 * returns the info about the current cycle that should be run, if any,
185
-	 * otherwise null
186
-	 *
187
-	 * @return array|null
188
-	 */
189
-	public function getCycle() {
190
-		$prefixes = $this->ldapHelper->getServerConfigurationPrefixes(true);
191
-		if(count($prefixes) === 0) {
192
-			return null;
193
-		}
194
-
195
-		$cycleData = [
196
-			'prefix' => $this->config->getAppValue('user_ldap', 'background_sync_prefix', null),
197
-			'offset' => (int)$this->config->getAppValue('user_ldap', 'background_sync_offset', 0),
198
-		];
199
-
200
-		if(
201
-			$cycleData['prefix'] !== null
202
-			&& in_array($cycleData['prefix'], $prefixes)
203
-		) {
204
-			return $cycleData;
205
-		}
206
-
207
-		return null;
208
-	}
209
-
210
-	/**
211
-	 * Save the provided cycle information in the DB
212
-	 *
213
-	 * @param array $cycleData
214
-	 */
215
-	public function setCycle(array $cycleData) {
216
-		$this->config->setAppValue('user_ldap', 'background_sync_prefix', $cycleData['prefix']);
217
-		$this->config->setAppValue('user_ldap', 'background_sync_offset', $cycleData['offset']);
218
-	}
219
-
220
-	/**
221
-	 * returns data about the next cycle that should run, if any, otherwise
222
-	 * null. It also always goes for the next LDAP configuration!
223
-	 *
224
-	 * @param array|null $cycleData the old cycle
225
-	 * @return array|null
226
-	 */
227
-	public function determineNextCycle(array $cycleData = null) {
228
-		$prefixes = $this->ldapHelper->getServerConfigurationPrefixes(true);
229
-		if(count($prefixes) === 0) {
230
-			return null;
231
-		}
232
-
233
-		// get the next prefix in line and remember it
234
-		$oldPrefix = $cycleData === null ? null : $cycleData['prefix'];
235
-		$prefix = $this->getNextPrefix($oldPrefix);
236
-		if($prefix === null) {
237
-			return null;
238
-		}
239
-		$cycleData['prefix'] = $prefix;
240
-		$cycleData['offset'] = 0;
241
-		$this->setCycle(['prefix' => $prefix, 'offset' => 0]);
242
-
243
-		return $cycleData;
244
-	}
245
-
246
-	/**
247
-	 * Checks whether the provided cycle should be run. Currently only the
248
-	 * last configuration change goes into account (at least one hour).
249
-	 *
250
-	 * @param $cycleData
251
-	 * @return bool
252
-	 */
253
-	public function qualifiesToRun($cycleData) {
254
-		$lastChange = $this->config->getAppValue('user_ldap', $cycleData['prefix'] . '_lastChange', 0);
255
-		if((time() - $lastChange) > 60 * 30) {
256
-			return true;
257
-		}
258
-		return false;
259
-	}
260
-
261
-	/**
262
-	 * increases the offset of the current cycle for the next run
263
-	 *
264
-	 * @param $cycleData
265
-	 */
266
-	protected function increaseOffset($cycleData) {
267
-		$ldapConfig = new Configuration($cycleData['prefix']);
268
-		$cycleData['offset'] += (int)$ldapConfig->ldapPagingSize;
269
-		$this->setCycle($cycleData);
270
-	}
271
-
272
-	/**
273
-	 * determines the next configuration prefix based on the last one (if any)
274
-	 *
275
-	 * @param string|null $lastPrefix
276
-	 * @return string|null
277
-	 */
278
-	protected function getNextPrefix($lastPrefix) {
279
-		$prefixes = $this->ldapHelper->getServerConfigurationPrefixes(true);
280
-		$noOfPrefixes = count($prefixes);
281
-		if($noOfPrefixes === 0) {
282
-			return null;
283
-		}
284
-		$i = $lastPrefix === null ? false : array_search($lastPrefix, $prefixes, true);
285
-		if($i === false) {
286
-			$i = -1;
287
-		} else {
288
-			$i++;
289
-		}
290
-
291
-		if(!isset($prefixes[$i])) {
292
-			$i = 0;
293
-		}
294
-		return $prefixes[$i];
295
-	}
296
-
297
-	/**
298
-	 * "fixes" DI
299
-	 *
300
-	 * @param array $argument
301
-	 */
302
-	public function setArgument($argument) {
303
-		if(isset($argument['config'])) {
304
-			$this->config = $argument['config'];
305
-		} else {
306
-			$this->config = \OC::$server->getConfig();
307
-		}
308
-
309
-		if(isset($argument['helper'])) {
310
-			$this->ldapHelper = $argument['helper'];
311
-		} else {
312
-			$this->ldapHelper = new Helper($this->config);
313
-		}
314
-
315
-		if(isset($argument['ldapWrapper'])) {
316
-			$this->ldap = $argument['ldapWrapper'];
317
-		} else {
318
-			$this->ldap = new LDAP();
319
-		}
320
-
321
-		if(isset($argument['avatarManager'])) {
322
-			$this->avatarManager = $argument['avatarManager'];
323
-		} else {
324
-			$this->avatarManager = \OC::$server->getAvatarManager();
325
-		}
326
-
327
-		if(isset($argument['dbc'])) {
328
-			$this->dbc = $argument['dbc'];
329
-		} else {
330
-			$this->dbc = \OC::$server->getDatabaseConnection();
331
-		}
332
-
333
-		if(isset($argument['ncUserManager'])) {
334
-			$this->ncUserManager = $argument['ncUserManager'];
335
-		} else {
336
-			$this->ncUserManager = \OC::$server->getUserManager();
337
-		}
338
-
339
-		if(isset($argument['notificationManager'])) {
340
-			$this->notificationManager = $argument['notificationManager'];
341
-		} else {
342
-			$this->notificationManager = \OC::$server->getNotificationManager();
343
-		}
344
-
345
-		if(isset($argument['userManager'])) {
346
-			$this->userManager = $argument['userManager'];
347
-		} else {
348
-			$this->userManager = new Manager(
349
-				$this->config,
350
-				new FilesystemHelper(),
351
-				new LogWrapper(),
352
-				$this->avatarManager,
353
-				new Image(),
354
-				$this->dbc,
355
-				$this->ncUserManager,
356
-				$this->notificationManager
357
-			);
358
-		}
359
-
360
-		if(isset($argument['mapper'])) {
361
-			$this->mapper = $argument['mapper'];
362
-		} else {
363
-			$this->mapper = new UserMapping($this->dbc);
364
-		}
45
+    const MAX_INTERVAL = 12 * 60 * 60; // 12h
46
+    const MIN_INTERVAL = 30 * 60; // 30min
47
+    /** @var  Helper */
48
+    protected $ldapHelper;
49
+    /** @var  LDAP */
50
+    protected $ldap;
51
+    /** @var  Manager */
52
+    protected $userManager;
53
+    /** @var UserMapping */
54
+    protected $mapper;
55
+    /** @var  IConfig */
56
+    protected $config;
57
+    /** @var  IAvatarManager */
58
+    protected $avatarManager;
59
+    /** @var  IDBConnection */
60
+    protected $dbc;
61
+    /** @var  IUserManager */
62
+    protected $ncUserManager;
63
+    /** @var  IManager */
64
+    protected $notificationManager;
65
+    /** @var ConnectionFactory */
66
+    protected $connectionFactory;
67
+    /** @var AccessFactory */
68
+    protected $accessFactory;
69
+
70
+    public function __construct() {
71
+        $this->setInterval(
72
+            \OC::$server->getConfig()->getAppValue(
73
+                'user_ldap',
74
+                'background_sync_interval',
75
+                self::MIN_INTERVAL
76
+            )
77
+        );
78
+    }
79
+
80
+    /**
81
+     * updates the interval
82
+     *
83
+     * the idea is to adjust the interval depending on the amount of known users
84
+     * and the attempt to update each user one day. At most it would run every
85
+     * 30 minutes, and at least every 12 hours.
86
+     */
87
+    public function updateInterval() {
88
+        $minPagingSize = $this->getMinPagingSize();
89
+        $mappedUsers = $this->mapper->count();
90
+
91
+        $runsPerDay = ($minPagingSize === 0 || $mappedUsers === 0) ? self::MAX_INTERVAL
92
+            : $mappedUsers / $minPagingSize;
93
+        $interval = floor(24 * 60 * 60 / $runsPerDay);
94
+        $interval = min(max($interval, self::MIN_INTERVAL), self::MAX_INTERVAL);
95
+
96
+        $this->config->setAppValue('user_ldap', 'background_sync_interval', $interval);
97
+    }
98
+
99
+    /**
100
+     * returns the smallest configured paging size
101
+     * @return int
102
+     */
103
+    protected function getMinPagingSize() {
104
+        $configKeys = $this->config->getAppKeys('user_ldap');
105
+        $configKeys = array_filter($configKeys, function($key) {
106
+            return strpos($key, 'ldap_paging_size') !== false;
107
+        });
108
+        $minPagingSize = null;
109
+        foreach ($configKeys as $configKey) {
110
+            $pagingSize = $this->config->getAppValue('user_ldap', $configKey, $minPagingSize);
111
+            $minPagingSize = $minPagingSize === null ? $pagingSize : min($minPagingSize, $pagingSize);
112
+        }
113
+        return (int)$minPagingSize;
114
+    }
115
+
116
+    /**
117
+     * @param array $argument
118
+     */
119
+    public function run($argument) {
120
+        $this->setArgument($argument);
121
+
122
+        $isBackgroundJobModeAjax = $this->config
123
+                ->getAppValue('core', 'backgroundjobs_mode', 'ajax') === 'ajax';
124
+        if($isBackgroundJobModeAjax) {
125
+            return;
126
+        }
127
+
128
+        $cycleData = $this->getCycle();
129
+        if($cycleData === null) {
130
+            $cycleData = $this->determineNextCycle();
131
+            if($cycleData === null) {
132
+                $this->updateInterval();
133
+                return;
134
+            }
135
+        }
136
+
137
+        if(!$this->qualifiesToRun($cycleData)) {
138
+            $this->updateInterval();
139
+            return;
140
+        }
141
+
142
+        try {
143
+            $expectMoreResults = $this->runCycle($cycleData);
144
+            if ($expectMoreResults) {
145
+                $this->increaseOffset($cycleData);
146
+            } else {
147
+                $this->determineNextCycle($cycleData);
148
+            }
149
+            $this->updateInterval();
150
+        } catch (ServerNotAvailableException $e) {
151
+            $this->determineNextCycle($cycleData);
152
+        }
153
+    }
154
+
155
+    /**
156
+     * @param array $cycleData
157
+     * @return bool whether more results are expected from the same configuration
158
+     */
159
+    public function runCycle($cycleData) {
160
+        $connection = $this->connectionFactory->get($cycleData['prefix']);
161
+        $access = $this->accessFactory->get($connection);
162
+        $access->setUserMapper($this->mapper);
163
+
164
+        $filter = $access->combineFilterWithAnd([
165
+            $access->connection->ldapUserFilter,
166
+            $access->connection->ldapUserDisplayName . '=*',
167
+            $access->getFilterPartForUserSearch('')
168
+        ]);
169
+        $results = $access->fetchListOfUsers(
170
+            $filter,
171
+            $access->userManager->getAttributes(),
172
+            $connection->ldapPagingSize,
173
+            $cycleData['offset'],
174
+            true
175
+        );
176
+
177
+        if((int)$connection->ldapPagingSize === 0) {
178
+            return false;
179
+        }
180
+        return count($results) >= (int)$connection->ldapPagingSize;
181
+    }
182
+
183
+    /**
184
+     * returns the info about the current cycle that should be run, if any,
185
+     * otherwise null
186
+     *
187
+     * @return array|null
188
+     */
189
+    public function getCycle() {
190
+        $prefixes = $this->ldapHelper->getServerConfigurationPrefixes(true);
191
+        if(count($prefixes) === 0) {
192
+            return null;
193
+        }
194
+
195
+        $cycleData = [
196
+            'prefix' => $this->config->getAppValue('user_ldap', 'background_sync_prefix', null),
197
+            'offset' => (int)$this->config->getAppValue('user_ldap', 'background_sync_offset', 0),
198
+        ];
199
+
200
+        if(
201
+            $cycleData['prefix'] !== null
202
+            && in_array($cycleData['prefix'], $prefixes)
203
+        ) {
204
+            return $cycleData;
205
+        }
206
+
207
+        return null;
208
+    }
209
+
210
+    /**
211
+     * Save the provided cycle information in the DB
212
+     *
213
+     * @param array $cycleData
214
+     */
215
+    public function setCycle(array $cycleData) {
216
+        $this->config->setAppValue('user_ldap', 'background_sync_prefix', $cycleData['prefix']);
217
+        $this->config->setAppValue('user_ldap', 'background_sync_offset', $cycleData['offset']);
218
+    }
219
+
220
+    /**
221
+     * returns data about the next cycle that should run, if any, otherwise
222
+     * null. It also always goes for the next LDAP configuration!
223
+     *
224
+     * @param array|null $cycleData the old cycle
225
+     * @return array|null
226
+     */
227
+    public function determineNextCycle(array $cycleData = null) {
228
+        $prefixes = $this->ldapHelper->getServerConfigurationPrefixes(true);
229
+        if(count($prefixes) === 0) {
230
+            return null;
231
+        }
232
+
233
+        // get the next prefix in line and remember it
234
+        $oldPrefix = $cycleData === null ? null : $cycleData['prefix'];
235
+        $prefix = $this->getNextPrefix($oldPrefix);
236
+        if($prefix === null) {
237
+            return null;
238
+        }
239
+        $cycleData['prefix'] = $prefix;
240
+        $cycleData['offset'] = 0;
241
+        $this->setCycle(['prefix' => $prefix, 'offset' => 0]);
242
+
243
+        return $cycleData;
244
+    }
245
+
246
+    /**
247
+     * Checks whether the provided cycle should be run. Currently only the
248
+     * last configuration change goes into account (at least one hour).
249
+     *
250
+     * @param $cycleData
251
+     * @return bool
252
+     */
253
+    public function qualifiesToRun($cycleData) {
254
+        $lastChange = $this->config->getAppValue('user_ldap', $cycleData['prefix'] . '_lastChange', 0);
255
+        if((time() - $lastChange) > 60 * 30) {
256
+            return true;
257
+        }
258
+        return false;
259
+    }
260
+
261
+    /**
262
+     * increases the offset of the current cycle for the next run
263
+     *
264
+     * @param $cycleData
265
+     */
266
+    protected function increaseOffset($cycleData) {
267
+        $ldapConfig = new Configuration($cycleData['prefix']);
268
+        $cycleData['offset'] += (int)$ldapConfig->ldapPagingSize;
269
+        $this->setCycle($cycleData);
270
+    }
271
+
272
+    /**
273
+     * determines the next configuration prefix based on the last one (if any)
274
+     *
275
+     * @param string|null $lastPrefix
276
+     * @return string|null
277
+     */
278
+    protected function getNextPrefix($lastPrefix) {
279
+        $prefixes = $this->ldapHelper->getServerConfigurationPrefixes(true);
280
+        $noOfPrefixes = count($prefixes);
281
+        if($noOfPrefixes === 0) {
282
+            return null;
283
+        }
284
+        $i = $lastPrefix === null ? false : array_search($lastPrefix, $prefixes, true);
285
+        if($i === false) {
286
+            $i = -1;
287
+        } else {
288
+            $i++;
289
+        }
290
+
291
+        if(!isset($prefixes[$i])) {
292
+            $i = 0;
293
+        }
294
+        return $prefixes[$i];
295
+    }
296
+
297
+    /**
298
+     * "fixes" DI
299
+     *
300
+     * @param array $argument
301
+     */
302
+    public function setArgument($argument) {
303
+        if(isset($argument['config'])) {
304
+            $this->config = $argument['config'];
305
+        } else {
306
+            $this->config = \OC::$server->getConfig();
307
+        }
308
+
309
+        if(isset($argument['helper'])) {
310
+            $this->ldapHelper = $argument['helper'];
311
+        } else {
312
+            $this->ldapHelper = new Helper($this->config);
313
+        }
314
+
315
+        if(isset($argument['ldapWrapper'])) {
316
+            $this->ldap = $argument['ldapWrapper'];
317
+        } else {
318
+            $this->ldap = new LDAP();
319
+        }
320
+
321
+        if(isset($argument['avatarManager'])) {
322
+            $this->avatarManager = $argument['avatarManager'];
323
+        } else {
324
+            $this->avatarManager = \OC::$server->getAvatarManager();
325
+        }
326
+
327
+        if(isset($argument['dbc'])) {
328
+            $this->dbc = $argument['dbc'];
329
+        } else {
330
+            $this->dbc = \OC::$server->getDatabaseConnection();
331
+        }
332
+
333
+        if(isset($argument['ncUserManager'])) {
334
+            $this->ncUserManager = $argument['ncUserManager'];
335
+        } else {
336
+            $this->ncUserManager = \OC::$server->getUserManager();
337
+        }
338
+
339
+        if(isset($argument['notificationManager'])) {
340
+            $this->notificationManager = $argument['notificationManager'];
341
+        } else {
342
+            $this->notificationManager = \OC::$server->getNotificationManager();
343
+        }
344
+
345
+        if(isset($argument['userManager'])) {
346
+            $this->userManager = $argument['userManager'];
347
+        } else {
348
+            $this->userManager = new Manager(
349
+                $this->config,
350
+                new FilesystemHelper(),
351
+                new LogWrapper(),
352
+                $this->avatarManager,
353
+                new Image(),
354
+                $this->dbc,
355
+                $this->ncUserManager,
356
+                $this->notificationManager
357
+            );
358
+        }
359
+
360
+        if(isset($argument['mapper'])) {
361
+            $this->mapper = $argument['mapper'];
362
+        } else {
363
+            $this->mapper = new UserMapping($this->dbc);
364
+        }
365 365
 		
366
-		if(isset($argument['connectionFactory'])) {
367
-			$this->connectionFactory = $argument['connectionFactory'];
368
-		} else {
369
-			$this->connectionFactory = new ConnectionFactory($this->ldap);
370
-		}
371
-
372
-		if(isset($argument['accessFactory'])) {
373
-			$this->accessFactory = $argument['accessFactory'];
374
-		} else {
375
-			$this->accessFactory = new AccessFactory(
376
-				$this->ldap,
377
-				$this->userManager,
378
-				$this->ldapHelper,
379
-				$this->config,
380
-				$this->ncUserManager
381
-			);
382
-		}
383
-	}
366
+        if(isset($argument['connectionFactory'])) {
367
+            $this->connectionFactory = $argument['connectionFactory'];
368
+        } else {
369
+            $this->connectionFactory = new ConnectionFactory($this->ldap);
370
+        }
371
+
372
+        if(isset($argument['accessFactory'])) {
373
+            $this->accessFactory = $argument['accessFactory'];
374
+        } else {
375
+            $this->accessFactory = new AccessFactory(
376
+                $this->ldap,
377
+                $this->userManager,
378
+                $this->ldapHelper,
379
+                $this->config,
380
+                $this->ncUserManager
381
+            );
382
+        }
383
+    }
384 384
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/Jobs/UpdateGroups.php 1 patch
Indentation   +164 added lines, -164 removed lines patch added patch discarded remove patch
@@ -45,183 +45,183 @@
 block discarded – undo
45 45
 use OCP\ILogger;
46 46
 
47 47
 class UpdateGroups extends \OC\BackgroundJob\TimedJob {
48
-	static private $groupsFromDB;
49
-
50
-	static private $groupBE;
51
-
52
-	public function __construct(){
53
-		$this->interval = self::getRefreshInterval();
54
-	}
55
-
56
-	/**
57
-	 * @param mixed $argument
58
-	 */
59
-	public function run($argument){
60
-		self::updateGroups();
61
-	}
62
-
63
-	static public function updateGroups() {
64
-		\OCP\Util::writeLog('user_ldap', 'Run background job "updateGroups"', ILogger::DEBUG);
65
-
66
-		$knownGroups = array_keys(self::getKnownGroups());
67
-		$actualGroups = self::getGroupBE()->getGroups();
68
-
69
-		if(empty($actualGroups) && empty($knownGroups)) {
70
-			\OCP\Util::writeLog('user_ldap',
71
-				'bgJ "updateGroups" – groups do not seem to be configured properly, aborting.',
72
-				ILogger::INFO);
73
-			return;
74
-		}
75
-
76
-		self::handleKnownGroups(array_intersect($actualGroups, $knownGroups));
77
-		self::handleCreatedGroups(array_diff($actualGroups, $knownGroups));
78
-		self::handleRemovedGroups(array_diff($knownGroups, $actualGroups));
79
-
80
-		\OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Finished.', ILogger::DEBUG);
81
-	}
82
-
83
-	/**
84
-	 * @return int
85
-	 */
86
-	static private function getRefreshInterval() {
87
-		//defaults to every hour
88
-		return \OC::$server->getConfig()->getAppValue('user_ldap', 'bgjRefreshInterval', 3600);
89
-	}
90
-
91
-	/**
92
-	 * @param string[] $groups
93
-	 */
94
-	static private function handleKnownGroups($groups) {
95
-		\OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Dealing with known Groups.', ILogger::DEBUG);
96
-		$query = \OC_DB::prepare('
48
+    static private $groupsFromDB;
49
+
50
+    static private $groupBE;
51
+
52
+    public function __construct(){
53
+        $this->interval = self::getRefreshInterval();
54
+    }
55
+
56
+    /**
57
+     * @param mixed $argument
58
+     */
59
+    public function run($argument){
60
+        self::updateGroups();
61
+    }
62
+
63
+    static public function updateGroups() {
64
+        \OCP\Util::writeLog('user_ldap', 'Run background job "updateGroups"', ILogger::DEBUG);
65
+
66
+        $knownGroups = array_keys(self::getKnownGroups());
67
+        $actualGroups = self::getGroupBE()->getGroups();
68
+
69
+        if(empty($actualGroups) && empty($knownGroups)) {
70
+            \OCP\Util::writeLog('user_ldap',
71
+                'bgJ "updateGroups" – groups do not seem to be configured properly, aborting.',
72
+                ILogger::INFO);
73
+            return;
74
+        }
75
+
76
+        self::handleKnownGroups(array_intersect($actualGroups, $knownGroups));
77
+        self::handleCreatedGroups(array_diff($actualGroups, $knownGroups));
78
+        self::handleRemovedGroups(array_diff($knownGroups, $actualGroups));
79
+
80
+        \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Finished.', ILogger::DEBUG);
81
+    }
82
+
83
+    /**
84
+     * @return int
85
+     */
86
+    static private function getRefreshInterval() {
87
+        //defaults to every hour
88
+        return \OC::$server->getConfig()->getAppValue('user_ldap', 'bgjRefreshInterval', 3600);
89
+    }
90
+
91
+    /**
92
+     * @param string[] $groups
93
+     */
94
+    static private function handleKnownGroups($groups) {
95
+        \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Dealing with known Groups.', ILogger::DEBUG);
96
+        $query = \OC_DB::prepare('
97 97
 			UPDATE `*PREFIX*ldap_group_members`
98 98
 			SET `owncloudusers` = ?
99 99
 			WHERE `owncloudname` = ?
100 100
 		');
101
-		foreach($groups as $group) {
102
-			//we assume, that self::$groupsFromDB has been retrieved already
103
-			$knownUsers = unserialize(self::$groupsFromDB[$group]['owncloudusers']);
104
-			$actualUsers = self::getGroupBE()->usersInGroup($group);
105
-			$hasChanged = false;
106
-			foreach(array_diff($knownUsers, $actualUsers) as $removedUser) {
107
-				\OCP\Util::emitHook('OC_User', 'post_removeFromGroup', ['uid' => $removedUser, 'gid' => $group]);
108
-				\OCP\Util::writeLog('user_ldap',
109
-				'bgJ "updateGroups" – "'.$removedUser.'" removed from "'.$group.'".',
110
-					ILogger::INFO);
111
-				$hasChanged = true;
112
-			}
113
-			foreach(array_diff($actualUsers, $knownUsers) as $addedUser) {
114
-				\OCP\Util::emitHook('OC_User', 'post_addToGroup', ['uid' => $addedUser, 'gid' => $group]);
115
-				\OCP\Util::writeLog('user_ldap',
116
-				'bgJ "updateGroups" – "'.$addedUser.'" added to "'.$group.'".',
117
-					ILogger::INFO);
118
-				$hasChanged = true;
119
-			}
120
-			if($hasChanged) {
121
-				$query->execute([serialize($actualUsers), $group]);
122
-			}
123
-		}
124
-		\OCP\Util::writeLog('user_ldap',
125
-			'bgJ "updateGroups" – FINISHED dealing with known Groups.',
126
-			ILogger::DEBUG);
127
-	}
128
-
129
-	/**
130
-	 * @param string[] $createdGroups
131
-	 */
132
-	static private function handleCreatedGroups($createdGroups) {
133
-		\OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with created Groups.', ILogger::DEBUG);
134
-		$query = \OC_DB::prepare('
101
+        foreach($groups as $group) {
102
+            //we assume, that self::$groupsFromDB has been retrieved already
103
+            $knownUsers = unserialize(self::$groupsFromDB[$group]['owncloudusers']);
104
+            $actualUsers = self::getGroupBE()->usersInGroup($group);
105
+            $hasChanged = false;
106
+            foreach(array_diff($knownUsers, $actualUsers) as $removedUser) {
107
+                \OCP\Util::emitHook('OC_User', 'post_removeFromGroup', ['uid' => $removedUser, 'gid' => $group]);
108
+                \OCP\Util::writeLog('user_ldap',
109
+                'bgJ "updateGroups" – "'.$removedUser.'" removed from "'.$group.'".',
110
+                    ILogger::INFO);
111
+                $hasChanged = true;
112
+            }
113
+            foreach(array_diff($actualUsers, $knownUsers) as $addedUser) {
114
+                \OCP\Util::emitHook('OC_User', 'post_addToGroup', ['uid' => $addedUser, 'gid' => $group]);
115
+                \OCP\Util::writeLog('user_ldap',
116
+                'bgJ "updateGroups" – "'.$addedUser.'" added to "'.$group.'".',
117
+                    ILogger::INFO);
118
+                $hasChanged = true;
119
+            }
120
+            if($hasChanged) {
121
+                $query->execute([serialize($actualUsers), $group]);
122
+            }
123
+        }
124
+        \OCP\Util::writeLog('user_ldap',
125
+            'bgJ "updateGroups" – FINISHED dealing with known Groups.',
126
+            ILogger::DEBUG);
127
+    }
128
+
129
+    /**
130
+     * @param string[] $createdGroups
131
+     */
132
+    static private function handleCreatedGroups($createdGroups) {
133
+        \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with created Groups.', ILogger::DEBUG);
134
+        $query = \OC_DB::prepare('
135 135
 			INSERT
136 136
 			INTO `*PREFIX*ldap_group_members` (`owncloudname`, `owncloudusers`)
137 137
 			VALUES (?, ?)
138 138
 		');
139
-		foreach($createdGroups as $createdGroup) {
140
-			\OCP\Util::writeLog('user_ldap',
141
-				'bgJ "updateGroups" – new group "'.$createdGroup.'" found.',
142
-				ILogger::INFO);
143
-			$users = serialize(self::getGroupBE()->usersInGroup($createdGroup));
144
-			$query->execute([$createdGroup, $users]);
145
-		}
146
-		\OCP\Util::writeLog('user_ldap',
147
-			'bgJ "updateGroups" – FINISHED dealing with created Groups.',
148
-			ILogger::DEBUG);
149
-	}
150
-
151
-	/**
152
-	 * @param string[] $removedGroups
153
-	 */
154
-	static private function handleRemovedGroups($removedGroups) {
155
-		\OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with removed groups.', ILogger::DEBUG);
156
-		$query = \OC_DB::prepare('
139
+        foreach($createdGroups as $createdGroup) {
140
+            \OCP\Util::writeLog('user_ldap',
141
+                'bgJ "updateGroups" – new group "'.$createdGroup.'" found.',
142
+                ILogger::INFO);
143
+            $users = serialize(self::getGroupBE()->usersInGroup($createdGroup));
144
+            $query->execute([$createdGroup, $users]);
145
+        }
146
+        \OCP\Util::writeLog('user_ldap',
147
+            'bgJ "updateGroups" – FINISHED dealing with created Groups.',
148
+            ILogger::DEBUG);
149
+    }
150
+
151
+    /**
152
+     * @param string[] $removedGroups
153
+     */
154
+    static private function handleRemovedGroups($removedGroups) {
155
+        \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with removed groups.', ILogger::DEBUG);
156
+        $query = \OC_DB::prepare('
157 157
 			DELETE
158 158
 			FROM `*PREFIX*ldap_group_members`
159 159
 			WHERE `owncloudname` = ?
160 160
 		');
161
-		foreach($removedGroups as $removedGroup) {
162
-			\OCP\Util::writeLog('user_ldap',
163
-				'bgJ "updateGroups" – group "'.$removedGroup.'" was removed.',
164
-				ILogger::INFO);
165
-			$query->execute([$removedGroup]);
166
-		}
167
-		\OCP\Util::writeLog('user_ldap',
168
-			'bgJ "updateGroups" – FINISHED dealing with removed groups.',
169
-			ILogger::DEBUG);
170
-	}
171
-
172
-	/**
173
-	 * @return \OCA\User_LDAP\Group_LDAP|\OCA\User_LDAP\Group_Proxy
174
-	 */
175
-	static private function getGroupBE() {
176
-		if(!is_null(self::$groupBE)) {
177
-			return self::$groupBE;
178
-		}
179
-		$helper = new Helper(\OC::$server->getConfig());
180
-		$configPrefixes = $helper->getServerConfigurationPrefixes(true);
181
-		$ldapWrapper = new LDAP();
182
-		if(count($configPrefixes) === 1) {
183
-			//avoid the proxy when there is only one LDAP server configured
184
-			$dbc = \OC::$server->getDatabaseConnection();
185
-			$userManager = new Manager(
186
-				\OC::$server->getConfig(),
187
-				new FilesystemHelper(),
188
-				new LogWrapper(),
189
-				\OC::$server->getAvatarManager(),
190
-				new \OCP\Image(),
191
-				$dbc,
192
-				\OC::$server->getUserManager(),
193
-				\OC::$server->getNotificationManager());
194
-			$connector = new Connection($ldapWrapper, $configPrefixes[0]);
195
-			$ldapAccess = new Access($connector, $ldapWrapper, $userManager, $helper, \OC::$server->getConfig(), \OC::$server->getUserManager());
196
-			$groupMapper = new GroupMapping($dbc);
197
-			$userMapper  = new UserMapping($dbc);
198
-			$ldapAccess->setGroupMapper($groupMapper);
199
-			$ldapAccess->setUserMapper($userMapper);
200
-			self::$groupBE = new \OCA\User_LDAP\Group_LDAP($ldapAccess, \OC::$server->query('LDAPGroupPluginManager'));
201
-		} else {
202
-			self::$groupBE = new \OCA\User_LDAP\Group_Proxy($configPrefixes, $ldapWrapper, \OC::$server->query('LDAPGroupPluginManager'));
203
-		}
204
-
205
-		return self::$groupBE;
206
-	}
207
-
208
-	/**
209
-	 * @return array
210
-	 */
211
-	static private function getKnownGroups() {
212
-		if(is_array(self::$groupsFromDB)) {
213
-			return self::$groupsFromDB;
214
-		}
215
-		$query = \OC_DB::prepare('
161
+        foreach($removedGroups as $removedGroup) {
162
+            \OCP\Util::writeLog('user_ldap',
163
+                'bgJ "updateGroups" – group "'.$removedGroup.'" was removed.',
164
+                ILogger::INFO);
165
+            $query->execute([$removedGroup]);
166
+        }
167
+        \OCP\Util::writeLog('user_ldap',
168
+            'bgJ "updateGroups" – FINISHED dealing with removed groups.',
169
+            ILogger::DEBUG);
170
+    }
171
+
172
+    /**
173
+     * @return \OCA\User_LDAP\Group_LDAP|\OCA\User_LDAP\Group_Proxy
174
+     */
175
+    static private function getGroupBE() {
176
+        if(!is_null(self::$groupBE)) {
177
+            return self::$groupBE;
178
+        }
179
+        $helper = new Helper(\OC::$server->getConfig());
180
+        $configPrefixes = $helper->getServerConfigurationPrefixes(true);
181
+        $ldapWrapper = new LDAP();
182
+        if(count($configPrefixes) === 1) {
183
+            //avoid the proxy when there is only one LDAP server configured
184
+            $dbc = \OC::$server->getDatabaseConnection();
185
+            $userManager = new Manager(
186
+                \OC::$server->getConfig(),
187
+                new FilesystemHelper(),
188
+                new LogWrapper(),
189
+                \OC::$server->getAvatarManager(),
190
+                new \OCP\Image(),
191
+                $dbc,
192
+                \OC::$server->getUserManager(),
193
+                \OC::$server->getNotificationManager());
194
+            $connector = new Connection($ldapWrapper, $configPrefixes[0]);
195
+            $ldapAccess = new Access($connector, $ldapWrapper, $userManager, $helper, \OC::$server->getConfig(), \OC::$server->getUserManager());
196
+            $groupMapper = new GroupMapping($dbc);
197
+            $userMapper  = new UserMapping($dbc);
198
+            $ldapAccess->setGroupMapper($groupMapper);
199
+            $ldapAccess->setUserMapper($userMapper);
200
+            self::$groupBE = new \OCA\User_LDAP\Group_LDAP($ldapAccess, \OC::$server->query('LDAPGroupPluginManager'));
201
+        } else {
202
+            self::$groupBE = new \OCA\User_LDAP\Group_Proxy($configPrefixes, $ldapWrapper, \OC::$server->query('LDAPGroupPluginManager'));
203
+        }
204
+
205
+        return self::$groupBE;
206
+    }
207
+
208
+    /**
209
+     * @return array
210
+     */
211
+    static private function getKnownGroups() {
212
+        if(is_array(self::$groupsFromDB)) {
213
+            return self::$groupsFromDB;
214
+        }
215
+        $query = \OC_DB::prepare('
216 216
 			SELECT `owncloudname`, `owncloudusers`
217 217
 			FROM `*PREFIX*ldap_group_members`
218 218
 		');
219
-		$result = $query->execute()->fetchAll();
220
-		self::$groupsFromDB = [];
221
-		foreach($result as $dataset) {
222
-			self::$groupsFromDB[$dataset['owncloudname']] = $dataset;
223
-		}
224
-
225
-		return self::$groupsFromDB;
226
-	}
219
+        $result = $query->execute()->fetchAll();
220
+        self::$groupsFromDB = [];
221
+        foreach($result as $dataset) {
222
+            self::$groupsFromDB[$dataset['owncloudname']] = $dataset;
223
+        }
224
+
225
+        return self::$groupsFromDB;
226
+    }
227 227
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/User_LDAP.php 1 patch
Indentation   +579 added lines, -579 removed lines patch added patch discarded remove patch
@@ -52,587 +52,587 @@
 block discarded – undo
52 52
 use OCP\Util;
53 53
 
54 54
 class User_LDAP extends BackendUtility implements \OCP\IUserBackend, \OCP\UserInterface, IUserLDAP {
55
-	/** @var \OCP\IConfig */
56
-	protected $ocConfig;
57
-
58
-	/** @var INotificationManager */
59
-	protected $notificationManager;
60
-
61
-	/** @var UserPluginManager */
62
-	protected $userPluginManager;
63
-
64
-	/**
65
-	 * @param Access $access
66
-	 * @param \OCP\IConfig $ocConfig
67
-	 * @param \OCP\Notification\IManager $notificationManager
68
-	 * @param IUserSession $userSession
69
-	 */
70
-	public function __construct(Access $access, IConfig $ocConfig, INotificationManager $notificationManager, IUserSession $userSession, UserPluginManager $userPluginManager) {
71
-		parent::__construct($access);
72
-		$this->ocConfig = $ocConfig;
73
-		$this->notificationManager = $notificationManager;
74
-		$this->userPluginManager = $userPluginManager;
75
-	}
76
-
77
-	/**
78
-	 * checks whether the user is allowed to change his avatar in Nextcloud
79
-	 *
80
-	 * @param string $uid the Nextcloud user name
81
-	 * @return boolean either the user can or cannot
82
-	 * @throws \Exception
83
-	 */
84
-	public function canChangeAvatar($uid) {
85
-		if ($this->userPluginManager->implementsActions(Backend::PROVIDE_AVATAR)) {
86
-			return $this->userPluginManager->canChangeAvatar($uid);
87
-		}
88
-
89
-		if(!$this->implementsActions(Backend::PROVIDE_AVATAR)) {
90
-			return true;
91
-		}
92
-
93
-		$user = $this->access->userManager->get($uid);
94
-		if(!$user instanceof User) {
95
-			return false;
96
-		}
97
-		$imageData = $user->getAvatarImage();
98
-		if($imageData === false) {
99
-			return true;
100
-		}
101
-		return !$user->updateAvatar(true);
102
-	}
103
-
104
-	/**
105
-	 * Return the username for the given login name, if available
106
-	 *
107
-	 * @param string $loginName
108
-	 * @return string|false
109
-	 * @throws \Exception
110
-	 */
111
-	public function loginName2UserName($loginName) {
112
-		$cacheKey = 'loginName2UserName-' . $loginName;
113
-		$username = $this->access->connection->getFromCache($cacheKey);
114
-
115
-		if ($username !== null) {
116
-			return $username;
117
-		}
118
-
119
-		try {
120
-			$ldapRecord = $this->getLDAPUserByLoginName($loginName);
121
-			$user = $this->access->userManager->get($ldapRecord['dn'][0]);
122
-			if ($user === null || $user instanceof OfflineUser) {
123
-				// this path is not really possible, however get() is documented
124
-				// to return User, OfflineUser or null so we are very defensive here.
125
-				$this->access->connection->writeToCache($cacheKey, false);
126
-				return false;
127
-			}
128
-			$username = $user->getUsername();
129
-			$this->access->connection->writeToCache($cacheKey, $username);
130
-			return $username;
131
-		} catch (NotOnLDAP $e) {
132
-			$this->access->connection->writeToCache($cacheKey, false);
133
-			return false;
134
-		}
135
-	}
55
+    /** @var \OCP\IConfig */
56
+    protected $ocConfig;
57
+
58
+    /** @var INotificationManager */
59
+    protected $notificationManager;
60
+
61
+    /** @var UserPluginManager */
62
+    protected $userPluginManager;
63
+
64
+    /**
65
+     * @param Access $access
66
+     * @param \OCP\IConfig $ocConfig
67
+     * @param \OCP\Notification\IManager $notificationManager
68
+     * @param IUserSession $userSession
69
+     */
70
+    public function __construct(Access $access, IConfig $ocConfig, INotificationManager $notificationManager, IUserSession $userSession, UserPluginManager $userPluginManager) {
71
+        parent::__construct($access);
72
+        $this->ocConfig = $ocConfig;
73
+        $this->notificationManager = $notificationManager;
74
+        $this->userPluginManager = $userPluginManager;
75
+    }
76
+
77
+    /**
78
+     * checks whether the user is allowed to change his avatar in Nextcloud
79
+     *
80
+     * @param string $uid the Nextcloud user name
81
+     * @return boolean either the user can or cannot
82
+     * @throws \Exception
83
+     */
84
+    public function canChangeAvatar($uid) {
85
+        if ($this->userPluginManager->implementsActions(Backend::PROVIDE_AVATAR)) {
86
+            return $this->userPluginManager->canChangeAvatar($uid);
87
+        }
88
+
89
+        if(!$this->implementsActions(Backend::PROVIDE_AVATAR)) {
90
+            return true;
91
+        }
92
+
93
+        $user = $this->access->userManager->get($uid);
94
+        if(!$user instanceof User) {
95
+            return false;
96
+        }
97
+        $imageData = $user->getAvatarImage();
98
+        if($imageData === false) {
99
+            return true;
100
+        }
101
+        return !$user->updateAvatar(true);
102
+    }
103
+
104
+    /**
105
+     * Return the username for the given login name, if available
106
+     *
107
+     * @param string $loginName
108
+     * @return string|false
109
+     * @throws \Exception
110
+     */
111
+    public function loginName2UserName($loginName) {
112
+        $cacheKey = 'loginName2UserName-' . $loginName;
113
+        $username = $this->access->connection->getFromCache($cacheKey);
114
+
115
+        if ($username !== null) {
116
+            return $username;
117
+        }
118
+
119
+        try {
120
+            $ldapRecord = $this->getLDAPUserByLoginName($loginName);
121
+            $user = $this->access->userManager->get($ldapRecord['dn'][0]);
122
+            if ($user === null || $user instanceof OfflineUser) {
123
+                // this path is not really possible, however get() is documented
124
+                // to return User, OfflineUser or null so we are very defensive here.
125
+                $this->access->connection->writeToCache($cacheKey, false);
126
+                return false;
127
+            }
128
+            $username = $user->getUsername();
129
+            $this->access->connection->writeToCache($cacheKey, $username);
130
+            return $username;
131
+        } catch (NotOnLDAP $e) {
132
+            $this->access->connection->writeToCache($cacheKey, false);
133
+            return false;
134
+        }
135
+    }
136 136
 	
137
-	/**
138
-	 * returns the username for the given LDAP DN, if available
139
-	 *
140
-	 * @param string $dn
141
-	 * @return string|false with the username
142
-	 */
143
-	public function dn2UserName($dn) {
144
-		return $this->access->dn2username($dn);
145
-	}
146
-
147
-	/**
148
-	 * returns an LDAP record based on a given login name
149
-	 *
150
-	 * @param string $loginName
151
-	 * @return array
152
-	 * @throws NotOnLDAP
153
-	 */
154
-	public function getLDAPUserByLoginName($loginName) {
155
-		//find out dn of the user name
156
-		$attrs = $this->access->userManager->getAttributes();
157
-		$users = $this->access->fetchUsersByLoginName($loginName, $attrs);
158
-		if(count($users) < 1) {
159
-			throw new NotOnLDAP('No user available for the given login name on ' .
160
-				$this->access->connection->ldapHost . ':' . $this->access->connection->ldapPort);
161
-		}
162
-		return $users[0];
163
-	}
164
-
165
-	/**
166
-	 * Check if the password is correct without logging in the user
167
-	 *
168
-	 * @param string $uid The username
169
-	 * @param string $password The password
170
-	 * @return false|string
171
-	 */
172
-	public function checkPassword($uid, $password) {
173
-		try {
174
-			$ldapRecord = $this->getLDAPUserByLoginName($uid);
175
-		} catch(NotOnLDAP $e) {
176
-			\OC::$server->getLogger()->logException($e, ['app' => 'user_ldap', 'level' => ILogger::DEBUG]);
177
-			return false;
178
-		}
179
-		$dn = $ldapRecord['dn'][0];
180
-		$user = $this->access->userManager->get($dn);
181
-
182
-		if(!$user instanceof User) {
183
-			Util::writeLog('user_ldap',
184
-				'LDAP Login: Could not get user object for DN ' . $dn .
185
-				'. Maybe the LDAP entry has no set display name attribute?',
186
-				ILogger::WARN);
187
-			return false;
188
-		}
189
-		if($user->getUsername() !== false) {
190
-			//are the credentials OK?
191
-			if(!$this->access->areCredentialsValid($dn, $password)) {
192
-				return false;
193
-			}
194
-
195
-			$this->access->cacheUserExists($user->getUsername());
196
-			$user->processAttributes($ldapRecord);
197
-			$user->markLogin();
198
-
199
-			return $user->getUsername();
200
-		}
201
-
202
-		return false;
203
-	}
204
-
205
-	/**
206
-	 * Set password
207
-	 * @param string $uid The username
208
-	 * @param string $password The new password
209
-	 * @return bool
210
-	 */
211
-	public function setPassword($uid, $password) {
212
-		if ($this->userPluginManager->implementsActions(Backend::SET_PASSWORD)) {
213
-			return $this->userPluginManager->setPassword($uid, $password);
214
-		}
215
-
216
-		$user = $this->access->userManager->get($uid);
217
-
218
-		if(!$user instanceof User) {
219
-			throw new \Exception('LDAP setPassword: Could not get user object for uid ' . $uid .
220
-				'. Maybe the LDAP entry has no set display name attribute?');
221
-		}
222
-		if($user->getUsername() !== false && $this->access->setPassword($user->getDN(), $password)) {
223
-			$ldapDefaultPPolicyDN = $this->access->connection->ldapDefaultPPolicyDN;
224
-			$turnOnPasswordChange = $this->access->connection->turnOnPasswordChange;
225
-			if (!empty($ldapDefaultPPolicyDN) && ((int)$turnOnPasswordChange === 1)) {
226
-				//remove last password expiry warning if any
227
-				$notification = $this->notificationManager->createNotification();
228
-				$notification->setApp('user_ldap')
229
-					->setUser($uid)
230
-					->setObject('pwd_exp_warn', $uid)
231
-				;
232
-				$this->notificationManager->markProcessed($notification);
233
-			}
234
-			return true;
235
-		}
236
-
237
-		return false;
238
-	}
239
-
240
-	/**
241
-	 * Get a list of all users
242
-	 *
243
-	 * @param string $search
244
-	 * @param integer $limit
245
-	 * @param integer $offset
246
-	 * @return string[] an array of all uids
247
-	 */
248
-	public function getUsers($search = '', $limit = 10, $offset = 0) {
249
-		$search = $this->access->escapeFilterPart($search, true);
250
-		$cachekey = 'getUsers-'.$search.'-'.$limit.'-'.$offset;
251
-
252
-		//check if users are cached, if so return
253
-		$ldap_users = $this->access->connection->getFromCache($cachekey);
254
-		if(!is_null($ldap_users)) {
255
-			return $ldap_users;
256
-		}
257
-
258
-		// if we'd pass -1 to LDAP search, we'd end up in a Protocol
259
-		// error. With a limit of 0, we get 0 results. So we pass null.
260
-		if($limit <= 0) {
261
-			$limit = null;
262
-		}
263
-		$filter = $this->access->combineFilterWithAnd([
264
-			$this->access->connection->ldapUserFilter,
265
-			$this->access->connection->ldapUserDisplayName . '=*',
266
-			$this->access->getFilterPartForUserSearch($search)
267
-		]);
268
-
269
-		Util::writeLog('user_ldap',
270
-			'getUsers: Options: search '.$search.' limit '.$limit.' offset '.$offset.' Filter: '.$filter,
271
-			ILogger::DEBUG);
272
-		//do the search and translate results to Nextcloud names
273
-		$ldap_users = $this->access->fetchListOfUsers(
274
-			$filter,
275
-			$this->access->userManager->getAttributes(true),
276
-			$limit, $offset);
277
-		$ldap_users = $this->access->nextcloudUserNames($ldap_users);
278
-		Util::writeLog('user_ldap', 'getUsers: '.count($ldap_users). ' Users found', ILogger::DEBUG);
279
-
280
-		$this->access->connection->writeToCache($cachekey, $ldap_users);
281
-		return $ldap_users;
282
-	}
283
-
284
-	/**
285
-	 * checks whether a user is still available on LDAP
286
-	 *
287
-	 * @param string|\OCA\User_LDAP\User\User $user either the Nextcloud user
288
-	 * name or an instance of that user
289
-	 * @return bool
290
-	 * @throws \Exception
291
-	 * @throws \OC\ServerNotAvailableException
292
-	 */
293
-	public function userExistsOnLDAP($user) {
294
-		if(is_string($user)) {
295
-			$user = $this->access->userManager->get($user);
296
-		}
297
-		if(is_null($user)) {
298
-			return false;
299
-		}
300
-		$uid = $user instanceof User ? $user->getUsername() : $user->getOCName();
301
-		$cacheKey = 'userExistsOnLDAP' . $uid;
302
-		$userExists = $this->access->connection->getFromCache($cacheKey);
303
-		if(!is_null($userExists)) {
304
-			return (bool)$userExists;
305
-		}
306
-
307
-		$dn = $user->getDN();
308
-		//check if user really still exists by reading its entry
309
-		if(!is_array($this->access->readAttribute($dn, '', $this->access->connection->ldapUserFilter))) {
310
-			try {
311
-				$uuid = $this->access->getUserMapper()->getUUIDByDN($dn);
312
-				if (!$uuid) {
313
-					$this->access->connection->writeToCache($cacheKey, false);
314
-					return false;
315
-				}
316
-				$newDn = $this->access->getUserDnByUuid($uuid);
317
-				//check if renamed user is still valid by reapplying the ldap filter
318
-				if ($newDn === $dn || !is_array($this->access->readAttribute($newDn, '', $this->access->connection->ldapUserFilter))) {
319
-					$this->access->connection->writeToCache($cacheKey, false);
320
-					return false;
321
-				}
322
-				$this->access->getUserMapper()->setDNbyUUID($newDn, $uuid);
323
-				$this->access->connection->writeToCache($cacheKey, true);
324
-				return true;
325
-			} catch (ServerNotAvailableException $e) {
326
-				throw $e;
327
-			} catch (\Exception $e) {
328
-				$this->access->connection->writeToCache($cacheKey, false);
329
-				return false;
330
-			}
331
-		}
332
-
333
-		if($user instanceof OfflineUser) {
334
-			$user->unmark();
335
-		}
336
-
337
-		$this->access->connection->writeToCache($cacheKey, true);
338
-		return true;
339
-	}
340
-
341
-	/**
342
-	 * check if a user exists
343
-	 * @param string $uid the username
344
-	 * @return boolean
345
-	 * @throws \Exception when connection could not be established
346
-	 */
347
-	public function userExists($uid) {
348
-		$userExists = $this->access->connection->getFromCache('userExists'.$uid);
349
-		if(!is_null($userExists)) {
350
-			return (bool)$userExists;
351
-		}
352
-		//getting dn, if false the user does not exist. If dn, he may be mapped only, requires more checking.
353
-		$user = $this->access->userManager->get($uid);
354
-
355
-		if(is_null($user)) {
356
-			Util::writeLog('user_ldap', 'No DN found for '.$uid.' on '.
357
-				$this->access->connection->ldapHost, ILogger::DEBUG);
358
-			$this->access->connection->writeToCache('userExists'.$uid, false);
359
-			return false;
360
-		}
361
-
362
-		$this->access->connection->writeToCache('userExists'.$uid, true);
363
-		return true;
364
-	}
365
-
366
-	/**
367
-	* returns whether a user was deleted in LDAP
368
-	*
369
-	* @param string $uid The username of the user to delete
370
-	* @return bool
371
-	*/
372
-	public function deleteUser($uid) {
373
-		if ($this->userPluginManager->canDeleteUser()) {
374
-			$status = $this->userPluginManager->deleteUser($uid);
375
-			if($status === false) {
376
-				return false;
377
-			}
378
-		}
379
-
380
-		$marked = $this->ocConfig->getUserValue($uid, 'user_ldap', 'isDeleted', 0);
381
-		if((int)$marked === 0) {
382
-			\OC::$server->getLogger()->notice(
383
-				'User '.$uid . ' is not marked as deleted, not cleaning up.',
384
-				['app' => 'user_ldap']);
385
-			return false;
386
-		}
387
-		\OC::$server->getLogger()->info('Cleaning up after user ' . $uid,
388
-			['app' => 'user_ldap']);
389
-
390
-		$this->access->getUserMapper()->unmap($uid); // we don't emit unassign signals here, since it is implicit to delete signals fired from core
391
-		$this->access->userManager->invalidate($uid);
392
-		return true;
393
-	}
394
-
395
-	/**
396
-	 * get the user's home directory
397
-	 *
398
-	 * @param string $uid the username
399
-	 * @return bool|string
400
-	 * @throws NoUserException
401
-	 * @throws \Exception
402
-	 */
403
-	public function getHome($uid) {
404
-		// user Exists check required as it is not done in user proxy!
405
-		if(!$this->userExists($uid)) {
406
-			return false;
407
-		}
408
-
409
-		if ($this->userPluginManager->implementsActions(Backend::GET_HOME)) {
410
-			return $this->userPluginManager->getHome($uid);
411
-		}
412
-
413
-		$cacheKey = 'getHome'.$uid;
414
-		$path = $this->access->connection->getFromCache($cacheKey);
415
-		if(!is_null($path)) {
416
-			return $path;
417
-		}
418
-
419
-		// early return path if it is a deleted user
420
-		$user = $this->access->userManager->get($uid);
421
-		if($user instanceof User || $user instanceof OfflineUser) {
422
-			$path = $user->getHomePath() ?: false;
423
-		} else {
424
-			throw new NoUserException($uid . ' is not a valid user anymore');
425
-		}
426
-
427
-		$this->access->cacheUserHome($uid, $path);
428
-		return $path;
429
-	}
430
-
431
-	/**
432
-	 * get display name of the user
433
-	 * @param string $uid user ID of the user
434
-	 * @return string|false display name
435
-	 */
436
-	public function getDisplayName($uid) {
437
-		if ($this->userPluginManager->implementsActions(Backend::GET_DISPLAYNAME)) {
438
-			return $this->userPluginManager->getDisplayName($uid);
439
-		}
440
-
441
-		if(!$this->userExists($uid)) {
442
-			return false;
443
-		}
444
-
445
-		$cacheKey = 'getDisplayName'.$uid;
446
-		if(!is_null($displayName = $this->access->connection->getFromCache($cacheKey))) {
447
-			return $displayName;
448
-		}
449
-
450
-		//Check whether the display name is configured to have a 2nd feature
451
-		$additionalAttribute = $this->access->connection->ldapUserDisplayName2;
452
-		$displayName2 = '';
453
-		if ($additionalAttribute !== '') {
454
-			$displayName2 = $this->access->readAttribute(
455
-				$this->access->username2dn($uid),
456
-				$additionalAttribute);
457
-		}
458
-
459
-		$displayName = $this->access->readAttribute(
460
-			$this->access->username2dn($uid),
461
-			$this->access->connection->ldapUserDisplayName);
462
-
463
-		if($displayName && (count($displayName) > 0)) {
464
-			$displayName = $displayName[0];
465
-
466
-			if (is_array($displayName2)){
467
-				$displayName2 = count($displayName2) > 0 ? $displayName2[0] : '';
468
-			}
469
-
470
-			$user = $this->access->userManager->get($uid);
471
-			if ($user instanceof User) {
472
-				$displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
473
-				$this->access->connection->writeToCache($cacheKey, $displayName);
474
-			}
475
-			if ($user instanceof OfflineUser) {
476
-				/** @var OfflineUser $user*/
477
-				$displayName = $user->getDisplayName();
478
-			}
479
-			return $displayName;
480
-		}
481
-
482
-		return null;
483
-	}
484
-
485
-	/**
486
-	 * set display name of the user
487
-	 * @param string $uid user ID of the user
488
-	 * @param string $displayName new display name of the user
489
-	 * @return string|false display name
490
-	 */
491
-	public function setDisplayName($uid, $displayName) {
492
-		if ($this->userPluginManager->implementsActions(Backend::SET_DISPLAYNAME)) {
493
-			$this->userPluginManager->setDisplayName($uid, $displayName);
494
-			$this->access->cacheUserDisplayName($uid, $displayName);
495
-			return $displayName;
496
-		}
497
-		return false;
498
-	}
499
-
500
-	/**
501
-	 * Get a list of all display names
502
-	 *
503
-	 * @param string $search
504
-	 * @param string|null $limit
505
-	 * @param string|null $offset
506
-	 * @return array an array of all displayNames (value) and the corresponding uids (key)
507
-	 */
508
-	public function getDisplayNames($search = '', $limit = null, $offset = null) {
509
-		$cacheKey = 'getDisplayNames-'.$search.'-'.$limit.'-'.$offset;
510
-		if(!is_null($displayNames = $this->access->connection->getFromCache($cacheKey))) {
511
-			return $displayNames;
512
-		}
513
-
514
-		$displayNames = [];
515
-		$users = $this->getUsers($search, $limit, $offset);
516
-		foreach ($users as $user) {
517
-			$displayNames[$user] = $this->getDisplayName($user);
518
-		}
519
-		$this->access->connection->writeToCache($cacheKey, $displayNames);
520
-		return $displayNames;
521
-	}
522
-
523
-	/**
524
-	* Check if backend implements actions
525
-	* @param int $actions bitwise-or'ed actions
526
-	* @return boolean
527
-	*
528
-	* Returns the supported actions as int to be
529
-	* compared with \OC\User\Backend::CREATE_USER etc.
530
-	*/
531
-	public function implementsActions($actions) {
532
-		return (bool)((Backend::CHECK_PASSWORD
533
-			| Backend::GET_HOME
534
-			| Backend::GET_DISPLAYNAME
535
-			| (($this->access->connection->ldapUserAvatarRule !== 'none') ? Backend::PROVIDE_AVATAR : 0)
536
-			| Backend::COUNT_USERS
537
-			| (((int)$this->access->connection->turnOnPasswordChange === 1)? Backend::SET_PASSWORD :0)
538
-			| $this->userPluginManager->getImplementedActions())
539
-			& $actions);
540
-	}
541
-
542
-	/**
543
-	 * @return bool
544
-	 */
545
-	public function hasUserListings() {
546
-		return true;
547
-	}
548
-
549
-	/**
550
-	 * counts the users in LDAP
551
-	 *
552
-	 * @return int|bool
553
-	 */
554
-	public function countUsers() {
555
-		if ($this->userPluginManager->implementsActions(Backend::COUNT_USERS)) {
556
-			return $this->userPluginManager->countUsers();
557
-		}
558
-
559
-		$filter = $this->access->getFilterForUserCount();
560
-		$cacheKey = 'countUsers-'.$filter;
561
-		if(!is_null($entries = $this->access->connection->getFromCache($cacheKey))) {
562
-			return $entries;
563
-		}
564
-		$entries = $this->access->countUsers($filter);
565
-		$this->access->connection->writeToCache($cacheKey, $entries);
566
-		return $entries;
567
-	}
568
-
569
-	/**
570
-	 * Backend name to be shown in user management
571
-	 * @return string the name of the backend to be shown
572
-	 */
573
-	public function getBackendName(){
574
-		return 'LDAP';
575
-	}
137
+    /**
138
+     * returns the username for the given LDAP DN, if available
139
+     *
140
+     * @param string $dn
141
+     * @return string|false with the username
142
+     */
143
+    public function dn2UserName($dn) {
144
+        return $this->access->dn2username($dn);
145
+    }
146
+
147
+    /**
148
+     * returns an LDAP record based on a given login name
149
+     *
150
+     * @param string $loginName
151
+     * @return array
152
+     * @throws NotOnLDAP
153
+     */
154
+    public function getLDAPUserByLoginName($loginName) {
155
+        //find out dn of the user name
156
+        $attrs = $this->access->userManager->getAttributes();
157
+        $users = $this->access->fetchUsersByLoginName($loginName, $attrs);
158
+        if(count($users) < 1) {
159
+            throw new NotOnLDAP('No user available for the given login name on ' .
160
+                $this->access->connection->ldapHost . ':' . $this->access->connection->ldapPort);
161
+        }
162
+        return $users[0];
163
+    }
164
+
165
+    /**
166
+     * Check if the password is correct without logging in the user
167
+     *
168
+     * @param string $uid The username
169
+     * @param string $password The password
170
+     * @return false|string
171
+     */
172
+    public function checkPassword($uid, $password) {
173
+        try {
174
+            $ldapRecord = $this->getLDAPUserByLoginName($uid);
175
+        } catch(NotOnLDAP $e) {
176
+            \OC::$server->getLogger()->logException($e, ['app' => 'user_ldap', 'level' => ILogger::DEBUG]);
177
+            return false;
178
+        }
179
+        $dn = $ldapRecord['dn'][0];
180
+        $user = $this->access->userManager->get($dn);
181
+
182
+        if(!$user instanceof User) {
183
+            Util::writeLog('user_ldap',
184
+                'LDAP Login: Could not get user object for DN ' . $dn .
185
+                '. Maybe the LDAP entry has no set display name attribute?',
186
+                ILogger::WARN);
187
+            return false;
188
+        }
189
+        if($user->getUsername() !== false) {
190
+            //are the credentials OK?
191
+            if(!$this->access->areCredentialsValid($dn, $password)) {
192
+                return false;
193
+            }
194
+
195
+            $this->access->cacheUserExists($user->getUsername());
196
+            $user->processAttributes($ldapRecord);
197
+            $user->markLogin();
198
+
199
+            return $user->getUsername();
200
+        }
201
+
202
+        return false;
203
+    }
204
+
205
+    /**
206
+     * Set password
207
+     * @param string $uid The username
208
+     * @param string $password The new password
209
+     * @return bool
210
+     */
211
+    public function setPassword($uid, $password) {
212
+        if ($this->userPluginManager->implementsActions(Backend::SET_PASSWORD)) {
213
+            return $this->userPluginManager->setPassword($uid, $password);
214
+        }
215
+
216
+        $user = $this->access->userManager->get($uid);
217
+
218
+        if(!$user instanceof User) {
219
+            throw new \Exception('LDAP setPassword: Could not get user object for uid ' . $uid .
220
+                '. Maybe the LDAP entry has no set display name attribute?');
221
+        }
222
+        if($user->getUsername() !== false && $this->access->setPassword($user->getDN(), $password)) {
223
+            $ldapDefaultPPolicyDN = $this->access->connection->ldapDefaultPPolicyDN;
224
+            $turnOnPasswordChange = $this->access->connection->turnOnPasswordChange;
225
+            if (!empty($ldapDefaultPPolicyDN) && ((int)$turnOnPasswordChange === 1)) {
226
+                //remove last password expiry warning if any
227
+                $notification = $this->notificationManager->createNotification();
228
+                $notification->setApp('user_ldap')
229
+                    ->setUser($uid)
230
+                    ->setObject('pwd_exp_warn', $uid)
231
+                ;
232
+                $this->notificationManager->markProcessed($notification);
233
+            }
234
+            return true;
235
+        }
236
+
237
+        return false;
238
+    }
239
+
240
+    /**
241
+     * Get a list of all users
242
+     *
243
+     * @param string $search
244
+     * @param integer $limit
245
+     * @param integer $offset
246
+     * @return string[] an array of all uids
247
+     */
248
+    public function getUsers($search = '', $limit = 10, $offset = 0) {
249
+        $search = $this->access->escapeFilterPart($search, true);
250
+        $cachekey = 'getUsers-'.$search.'-'.$limit.'-'.$offset;
251
+
252
+        //check if users are cached, if so return
253
+        $ldap_users = $this->access->connection->getFromCache($cachekey);
254
+        if(!is_null($ldap_users)) {
255
+            return $ldap_users;
256
+        }
257
+
258
+        // if we'd pass -1 to LDAP search, we'd end up in a Protocol
259
+        // error. With a limit of 0, we get 0 results. So we pass null.
260
+        if($limit <= 0) {
261
+            $limit = null;
262
+        }
263
+        $filter = $this->access->combineFilterWithAnd([
264
+            $this->access->connection->ldapUserFilter,
265
+            $this->access->connection->ldapUserDisplayName . '=*',
266
+            $this->access->getFilterPartForUserSearch($search)
267
+        ]);
268
+
269
+        Util::writeLog('user_ldap',
270
+            'getUsers: Options: search '.$search.' limit '.$limit.' offset '.$offset.' Filter: '.$filter,
271
+            ILogger::DEBUG);
272
+        //do the search and translate results to Nextcloud names
273
+        $ldap_users = $this->access->fetchListOfUsers(
274
+            $filter,
275
+            $this->access->userManager->getAttributes(true),
276
+            $limit, $offset);
277
+        $ldap_users = $this->access->nextcloudUserNames($ldap_users);
278
+        Util::writeLog('user_ldap', 'getUsers: '.count($ldap_users). ' Users found', ILogger::DEBUG);
279
+
280
+        $this->access->connection->writeToCache($cachekey, $ldap_users);
281
+        return $ldap_users;
282
+    }
283
+
284
+    /**
285
+     * checks whether a user is still available on LDAP
286
+     *
287
+     * @param string|\OCA\User_LDAP\User\User $user either the Nextcloud user
288
+     * name or an instance of that user
289
+     * @return bool
290
+     * @throws \Exception
291
+     * @throws \OC\ServerNotAvailableException
292
+     */
293
+    public function userExistsOnLDAP($user) {
294
+        if(is_string($user)) {
295
+            $user = $this->access->userManager->get($user);
296
+        }
297
+        if(is_null($user)) {
298
+            return false;
299
+        }
300
+        $uid = $user instanceof User ? $user->getUsername() : $user->getOCName();
301
+        $cacheKey = 'userExistsOnLDAP' . $uid;
302
+        $userExists = $this->access->connection->getFromCache($cacheKey);
303
+        if(!is_null($userExists)) {
304
+            return (bool)$userExists;
305
+        }
306
+
307
+        $dn = $user->getDN();
308
+        //check if user really still exists by reading its entry
309
+        if(!is_array($this->access->readAttribute($dn, '', $this->access->connection->ldapUserFilter))) {
310
+            try {
311
+                $uuid = $this->access->getUserMapper()->getUUIDByDN($dn);
312
+                if (!$uuid) {
313
+                    $this->access->connection->writeToCache($cacheKey, false);
314
+                    return false;
315
+                }
316
+                $newDn = $this->access->getUserDnByUuid($uuid);
317
+                //check if renamed user is still valid by reapplying the ldap filter
318
+                if ($newDn === $dn || !is_array($this->access->readAttribute($newDn, '', $this->access->connection->ldapUserFilter))) {
319
+                    $this->access->connection->writeToCache($cacheKey, false);
320
+                    return false;
321
+                }
322
+                $this->access->getUserMapper()->setDNbyUUID($newDn, $uuid);
323
+                $this->access->connection->writeToCache($cacheKey, true);
324
+                return true;
325
+            } catch (ServerNotAvailableException $e) {
326
+                throw $e;
327
+            } catch (\Exception $e) {
328
+                $this->access->connection->writeToCache($cacheKey, false);
329
+                return false;
330
+            }
331
+        }
332
+
333
+        if($user instanceof OfflineUser) {
334
+            $user->unmark();
335
+        }
336
+
337
+        $this->access->connection->writeToCache($cacheKey, true);
338
+        return true;
339
+    }
340
+
341
+    /**
342
+     * check if a user exists
343
+     * @param string $uid the username
344
+     * @return boolean
345
+     * @throws \Exception when connection could not be established
346
+     */
347
+    public function userExists($uid) {
348
+        $userExists = $this->access->connection->getFromCache('userExists'.$uid);
349
+        if(!is_null($userExists)) {
350
+            return (bool)$userExists;
351
+        }
352
+        //getting dn, if false the user does not exist. If dn, he may be mapped only, requires more checking.
353
+        $user = $this->access->userManager->get($uid);
354
+
355
+        if(is_null($user)) {
356
+            Util::writeLog('user_ldap', 'No DN found for '.$uid.' on '.
357
+                $this->access->connection->ldapHost, ILogger::DEBUG);
358
+            $this->access->connection->writeToCache('userExists'.$uid, false);
359
+            return false;
360
+        }
361
+
362
+        $this->access->connection->writeToCache('userExists'.$uid, true);
363
+        return true;
364
+    }
365
+
366
+    /**
367
+     * returns whether a user was deleted in LDAP
368
+     *
369
+     * @param string $uid The username of the user to delete
370
+     * @return bool
371
+     */
372
+    public function deleteUser($uid) {
373
+        if ($this->userPluginManager->canDeleteUser()) {
374
+            $status = $this->userPluginManager->deleteUser($uid);
375
+            if($status === false) {
376
+                return false;
377
+            }
378
+        }
379
+
380
+        $marked = $this->ocConfig->getUserValue($uid, 'user_ldap', 'isDeleted', 0);
381
+        if((int)$marked === 0) {
382
+            \OC::$server->getLogger()->notice(
383
+                'User '.$uid . ' is not marked as deleted, not cleaning up.',
384
+                ['app' => 'user_ldap']);
385
+            return false;
386
+        }
387
+        \OC::$server->getLogger()->info('Cleaning up after user ' . $uid,
388
+            ['app' => 'user_ldap']);
389
+
390
+        $this->access->getUserMapper()->unmap($uid); // we don't emit unassign signals here, since it is implicit to delete signals fired from core
391
+        $this->access->userManager->invalidate($uid);
392
+        return true;
393
+    }
394
+
395
+    /**
396
+     * get the user's home directory
397
+     *
398
+     * @param string $uid the username
399
+     * @return bool|string
400
+     * @throws NoUserException
401
+     * @throws \Exception
402
+     */
403
+    public function getHome($uid) {
404
+        // user Exists check required as it is not done in user proxy!
405
+        if(!$this->userExists($uid)) {
406
+            return false;
407
+        }
408
+
409
+        if ($this->userPluginManager->implementsActions(Backend::GET_HOME)) {
410
+            return $this->userPluginManager->getHome($uid);
411
+        }
412
+
413
+        $cacheKey = 'getHome'.$uid;
414
+        $path = $this->access->connection->getFromCache($cacheKey);
415
+        if(!is_null($path)) {
416
+            return $path;
417
+        }
418
+
419
+        // early return path if it is a deleted user
420
+        $user = $this->access->userManager->get($uid);
421
+        if($user instanceof User || $user instanceof OfflineUser) {
422
+            $path = $user->getHomePath() ?: false;
423
+        } else {
424
+            throw new NoUserException($uid . ' is not a valid user anymore');
425
+        }
426
+
427
+        $this->access->cacheUserHome($uid, $path);
428
+        return $path;
429
+    }
430
+
431
+    /**
432
+     * get display name of the user
433
+     * @param string $uid user ID of the user
434
+     * @return string|false display name
435
+     */
436
+    public function getDisplayName($uid) {
437
+        if ($this->userPluginManager->implementsActions(Backend::GET_DISPLAYNAME)) {
438
+            return $this->userPluginManager->getDisplayName($uid);
439
+        }
440
+
441
+        if(!$this->userExists($uid)) {
442
+            return false;
443
+        }
444
+
445
+        $cacheKey = 'getDisplayName'.$uid;
446
+        if(!is_null($displayName = $this->access->connection->getFromCache($cacheKey))) {
447
+            return $displayName;
448
+        }
449
+
450
+        //Check whether the display name is configured to have a 2nd feature
451
+        $additionalAttribute = $this->access->connection->ldapUserDisplayName2;
452
+        $displayName2 = '';
453
+        if ($additionalAttribute !== '') {
454
+            $displayName2 = $this->access->readAttribute(
455
+                $this->access->username2dn($uid),
456
+                $additionalAttribute);
457
+        }
458
+
459
+        $displayName = $this->access->readAttribute(
460
+            $this->access->username2dn($uid),
461
+            $this->access->connection->ldapUserDisplayName);
462
+
463
+        if($displayName && (count($displayName) > 0)) {
464
+            $displayName = $displayName[0];
465
+
466
+            if (is_array($displayName2)){
467
+                $displayName2 = count($displayName2) > 0 ? $displayName2[0] : '';
468
+            }
469
+
470
+            $user = $this->access->userManager->get($uid);
471
+            if ($user instanceof User) {
472
+                $displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
473
+                $this->access->connection->writeToCache($cacheKey, $displayName);
474
+            }
475
+            if ($user instanceof OfflineUser) {
476
+                /** @var OfflineUser $user*/
477
+                $displayName = $user->getDisplayName();
478
+            }
479
+            return $displayName;
480
+        }
481
+
482
+        return null;
483
+    }
484
+
485
+    /**
486
+     * set display name of the user
487
+     * @param string $uid user ID of the user
488
+     * @param string $displayName new display name of the user
489
+     * @return string|false display name
490
+     */
491
+    public function setDisplayName($uid, $displayName) {
492
+        if ($this->userPluginManager->implementsActions(Backend::SET_DISPLAYNAME)) {
493
+            $this->userPluginManager->setDisplayName($uid, $displayName);
494
+            $this->access->cacheUserDisplayName($uid, $displayName);
495
+            return $displayName;
496
+        }
497
+        return false;
498
+    }
499
+
500
+    /**
501
+     * Get a list of all display names
502
+     *
503
+     * @param string $search
504
+     * @param string|null $limit
505
+     * @param string|null $offset
506
+     * @return array an array of all displayNames (value) and the corresponding uids (key)
507
+     */
508
+    public function getDisplayNames($search = '', $limit = null, $offset = null) {
509
+        $cacheKey = 'getDisplayNames-'.$search.'-'.$limit.'-'.$offset;
510
+        if(!is_null($displayNames = $this->access->connection->getFromCache($cacheKey))) {
511
+            return $displayNames;
512
+        }
513
+
514
+        $displayNames = [];
515
+        $users = $this->getUsers($search, $limit, $offset);
516
+        foreach ($users as $user) {
517
+            $displayNames[$user] = $this->getDisplayName($user);
518
+        }
519
+        $this->access->connection->writeToCache($cacheKey, $displayNames);
520
+        return $displayNames;
521
+    }
522
+
523
+    /**
524
+     * Check if backend implements actions
525
+     * @param int $actions bitwise-or'ed actions
526
+     * @return boolean
527
+     *
528
+     * Returns the supported actions as int to be
529
+     * compared with \OC\User\Backend::CREATE_USER etc.
530
+     */
531
+    public function implementsActions($actions) {
532
+        return (bool)((Backend::CHECK_PASSWORD
533
+            | Backend::GET_HOME
534
+            | Backend::GET_DISPLAYNAME
535
+            | (($this->access->connection->ldapUserAvatarRule !== 'none') ? Backend::PROVIDE_AVATAR : 0)
536
+            | Backend::COUNT_USERS
537
+            | (((int)$this->access->connection->turnOnPasswordChange === 1)? Backend::SET_PASSWORD :0)
538
+            | $this->userPluginManager->getImplementedActions())
539
+            & $actions);
540
+    }
541
+
542
+    /**
543
+     * @return bool
544
+     */
545
+    public function hasUserListings() {
546
+        return true;
547
+    }
548
+
549
+    /**
550
+     * counts the users in LDAP
551
+     *
552
+     * @return int|bool
553
+     */
554
+    public function countUsers() {
555
+        if ($this->userPluginManager->implementsActions(Backend::COUNT_USERS)) {
556
+            return $this->userPluginManager->countUsers();
557
+        }
558
+
559
+        $filter = $this->access->getFilterForUserCount();
560
+        $cacheKey = 'countUsers-'.$filter;
561
+        if(!is_null($entries = $this->access->connection->getFromCache($cacheKey))) {
562
+            return $entries;
563
+        }
564
+        $entries = $this->access->countUsers($filter);
565
+        $this->access->connection->writeToCache($cacheKey, $entries);
566
+        return $entries;
567
+    }
568
+
569
+    /**
570
+     * Backend name to be shown in user management
571
+     * @return string the name of the backend to be shown
572
+     */
573
+    public function getBackendName(){
574
+        return 'LDAP';
575
+    }
576 576
 	
577
-	/**
578
-	 * Return access for LDAP interaction.
579
-	 * @param string $uid
580
-	 * @return Access instance of Access for LDAP interaction
581
-	 */
582
-	public function getLDAPAccess($uid) {
583
-		return $this->access;
584
-	}
577
+    /**
578
+     * Return access for LDAP interaction.
579
+     * @param string $uid
580
+     * @return Access instance of Access for LDAP interaction
581
+     */
582
+    public function getLDAPAccess($uid) {
583
+        return $this->access;
584
+    }
585 585
 	
586
-	/**
587
-	 * Return LDAP connection resource from a cloned connection.
588
-	 * The cloned connection needs to be closed manually.
589
-	 * of the current access.
590
-	 * @param string $uid
591
-	 * @return resource of the LDAP connection
592
-	 */
593
-	public function getNewLDAPConnection($uid) {
594
-		$connection = clone $this->access->getConnection();
595
-		return $connection->getConnectionResource();
596
-	}
597
-
598
-	/**
599
-	 * create new user
600
-	 * @param string $username username of the new user
601
-	 * @param string $password password of the new user
602
-	 * @throws \UnexpectedValueException
603
-	 * @return bool
604
-	 */
605
-	public function createUser($username, $password) {
606
-		if ($this->userPluginManager->implementsActions(Backend::CREATE_USER)) {
607
-			if ($dn = $this->userPluginManager->createUser($username, $password)) {
608
-				if (is_string($dn)) {
609
-					// the NC user creation work flow requires a know user id up front
610
-					$uuid = $this->access->getUUID($dn, true);
611
-					if(is_string($uuid)) {
612
-						$this->access->mapAndAnnounceIfApplicable(
613
-							$this->access->getUserMapper(),
614
-							$dn,
615
-							$username,
616
-							$uuid,
617
-							true
618
-						);
619
-						$this->access->cacheUserExists($username);
620
-					} else {
621
-						\OC::$server->getLogger()->warning(
622
-							'Failed to map created LDAP user with userid {userid}, because UUID could not be determined',
623
-							[
624
-								'app' => 'user_ldap',
625
-								'userid' => $username,
626
-							]
627
-						);
628
-					}
629
-				} else {
630
-					throw new \UnexpectedValueException("LDAP Plugin: Method createUser changed to return the user DN instead of boolean.");
631
-				}
632
-			}
633
-			return (bool) $dn;
634
-		}
635
-		return false;
636
-	}
586
+    /**
587
+     * Return LDAP connection resource from a cloned connection.
588
+     * The cloned connection needs to be closed manually.
589
+     * of the current access.
590
+     * @param string $uid
591
+     * @return resource of the LDAP connection
592
+     */
593
+    public function getNewLDAPConnection($uid) {
594
+        $connection = clone $this->access->getConnection();
595
+        return $connection->getConnectionResource();
596
+    }
597
+
598
+    /**
599
+     * create new user
600
+     * @param string $username username of the new user
601
+     * @param string $password password of the new user
602
+     * @throws \UnexpectedValueException
603
+     * @return bool
604
+     */
605
+    public function createUser($username, $password) {
606
+        if ($this->userPluginManager->implementsActions(Backend::CREATE_USER)) {
607
+            if ($dn = $this->userPluginManager->createUser($username, $password)) {
608
+                if (is_string($dn)) {
609
+                    // the NC user creation work flow requires a know user id up front
610
+                    $uuid = $this->access->getUUID($dn, true);
611
+                    if(is_string($uuid)) {
612
+                        $this->access->mapAndAnnounceIfApplicable(
613
+                            $this->access->getUserMapper(),
614
+                            $dn,
615
+                            $username,
616
+                            $uuid,
617
+                            true
618
+                        );
619
+                        $this->access->cacheUserExists($username);
620
+                    } else {
621
+                        \OC::$server->getLogger()->warning(
622
+                            'Failed to map created LDAP user with userid {userid}, because UUID could not be determined',
623
+                            [
624
+                                'app' => 'user_ldap',
625
+                                'userid' => $username,
626
+                            ]
627
+                        );
628
+                    }
629
+                } else {
630
+                    throw new \UnexpectedValueException("LDAP Plugin: Method createUser changed to return the user DN instead of boolean.");
631
+                }
632
+            }
633
+            return (bool) $dn;
634
+        }
635
+        return false;
636
+    }
637 637
 
638 638
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/User_Proxy.php 1 patch
Indentation   +307 added lines, -307 removed lines patch added patch discarded remove patch
@@ -37,335 +37,335 @@
 block discarded – undo
37 37
 use OCP\Notification\IManager as INotificationManager;
38 38
 
39 39
 class User_Proxy extends Proxy implements \OCP\IUserBackend, \OCP\UserInterface, IUserLDAP {
40
-	private $backends = [];
41
-	/** @var User_LDAP */
42
-	private $refBackend = null;
40
+    private $backends = [];
41
+    /** @var User_LDAP */
42
+    private $refBackend = null;
43 43
 
44
-	/**
45
-	 * Constructor
46
-	 *
47
-	 * @param array $serverConfigPrefixes array containing the config Prefixes
48
-	 * @param ILDAPWrapper $ldap
49
-	 * @param IConfig $ocConfig
50
-	 * @param INotificationManager $notificationManager
51
-	 * @param IUserSession $userSession
52
-	 */
53
-	public function __construct(
54
-		array $serverConfigPrefixes,
55
-		ILDAPWrapper $ldap,
56
-		IConfig $ocConfig,
57
-		INotificationManager $notificationManager,
58
-		IUserSession $userSession,
59
-		UserPluginManager $userPluginManager
60
-	) {
61
-		parent::__construct($ldap);
62
-		foreach($serverConfigPrefixes as $configPrefix) {
63
-			$this->backends[$configPrefix] =
64
-				new User_LDAP($this->getAccess($configPrefix), $ocConfig, $notificationManager, $userSession, $userPluginManager);
44
+    /**
45
+     * Constructor
46
+     *
47
+     * @param array $serverConfigPrefixes array containing the config Prefixes
48
+     * @param ILDAPWrapper $ldap
49
+     * @param IConfig $ocConfig
50
+     * @param INotificationManager $notificationManager
51
+     * @param IUserSession $userSession
52
+     */
53
+    public function __construct(
54
+        array $serverConfigPrefixes,
55
+        ILDAPWrapper $ldap,
56
+        IConfig $ocConfig,
57
+        INotificationManager $notificationManager,
58
+        IUserSession $userSession,
59
+        UserPluginManager $userPluginManager
60
+    ) {
61
+        parent::__construct($ldap);
62
+        foreach($serverConfigPrefixes as $configPrefix) {
63
+            $this->backends[$configPrefix] =
64
+                new User_LDAP($this->getAccess($configPrefix), $ocConfig, $notificationManager, $userSession, $userPluginManager);
65 65
 
66
-			if(is_null($this->refBackend)) {
67
-				$this->refBackend = &$this->backends[$configPrefix];
68
-			}
69
-		}
70
-	}
66
+            if(is_null($this->refBackend)) {
67
+                $this->refBackend = &$this->backends[$configPrefix];
68
+            }
69
+        }
70
+    }
71 71
 
72
-	/**
73
-	 * Tries the backends one after the other until a positive result is returned from the specified method
74
-	 * @param string $uid the uid connected to the request
75
-	 * @param string $method the method of the user backend that shall be called
76
-	 * @param array $parameters an array of parameters to be passed
77
-	 * @return mixed the result of the method or false
78
-	 */
79
-	protected function walkBackends($uid, $method, $parameters) {
80
-		$cacheKey = $this->getUserCacheKey($uid);
81
-		foreach($this->backends as $configPrefix => $backend) {
82
-			$instance = $backend;
83
-			if(!method_exists($instance, $method)
84
-				&& method_exists($this->getAccess($configPrefix), $method)) {
85
-				$instance = $this->getAccess($configPrefix);
86
-			}
87
-			if($result = call_user_func_array([$instance, $method], $parameters)) {
88
-				$this->writeToCache($cacheKey, $configPrefix);
89
-				return $result;
90
-			}
91
-		}
92
-		return false;
93
-	}
72
+    /**
73
+     * Tries the backends one after the other until a positive result is returned from the specified method
74
+     * @param string $uid the uid connected to the request
75
+     * @param string $method the method of the user backend that shall be called
76
+     * @param array $parameters an array of parameters to be passed
77
+     * @return mixed the result of the method or false
78
+     */
79
+    protected function walkBackends($uid, $method, $parameters) {
80
+        $cacheKey = $this->getUserCacheKey($uid);
81
+        foreach($this->backends as $configPrefix => $backend) {
82
+            $instance = $backend;
83
+            if(!method_exists($instance, $method)
84
+                && method_exists($this->getAccess($configPrefix), $method)) {
85
+                $instance = $this->getAccess($configPrefix);
86
+            }
87
+            if($result = call_user_func_array([$instance, $method], $parameters)) {
88
+                $this->writeToCache($cacheKey, $configPrefix);
89
+                return $result;
90
+            }
91
+        }
92
+        return false;
93
+    }
94 94
 
95
-	/**
96
-	 * Asks the backend connected to the server that supposely takes care of the uid from the request.
97
-	 * @param string $uid the uid connected to the request
98
-	 * @param string $method the method of the user backend that shall be called
99
-	 * @param array $parameters an array of parameters to be passed
100
-	 * @param mixed $passOnWhen the result matches this variable
101
-	 * @return mixed the result of the method or false
102
-	 */
103
-	protected function callOnLastSeenOn($uid, $method, $parameters, $passOnWhen) {
104
-		$cacheKey = $this->getUserCacheKey($uid);
105
-		$prefix = $this->getFromCache($cacheKey);
106
-		//in case the uid has been found in the past, try this stored connection first
107
-		if(!is_null($prefix)) {
108
-			if(isset($this->backends[$prefix])) {
109
-				$instance = $this->backends[$prefix];
110
-				if(!method_exists($instance, $method)
111
-					&& method_exists($this->getAccess($prefix), $method)) {
112
-					$instance = $this->getAccess($prefix);
113
-				}
114
-				$result = call_user_func_array([$instance, $method], $parameters);
115
-				if($result === $passOnWhen) {
116
-					//not found here, reset cache to null if user vanished
117
-					//because sometimes methods return false with a reason
118
-					$userExists = call_user_func_array(
119
-						[$this->backends[$prefix], 'userExistsOnLDAP'],
120
-						[$uid]
121
-					);
122
-					if(!$userExists) {
123
-						$this->writeToCache($cacheKey, null);
124
-					}
125
-				}
126
-				return $result;
127
-			}
128
-		}
129
-		return false;
130
-	}
95
+    /**
96
+     * Asks the backend connected to the server that supposely takes care of the uid from the request.
97
+     * @param string $uid the uid connected to the request
98
+     * @param string $method the method of the user backend that shall be called
99
+     * @param array $parameters an array of parameters to be passed
100
+     * @param mixed $passOnWhen the result matches this variable
101
+     * @return mixed the result of the method or false
102
+     */
103
+    protected function callOnLastSeenOn($uid, $method, $parameters, $passOnWhen) {
104
+        $cacheKey = $this->getUserCacheKey($uid);
105
+        $prefix = $this->getFromCache($cacheKey);
106
+        //in case the uid has been found in the past, try this stored connection first
107
+        if(!is_null($prefix)) {
108
+            if(isset($this->backends[$prefix])) {
109
+                $instance = $this->backends[$prefix];
110
+                if(!method_exists($instance, $method)
111
+                    && method_exists($this->getAccess($prefix), $method)) {
112
+                    $instance = $this->getAccess($prefix);
113
+                }
114
+                $result = call_user_func_array([$instance, $method], $parameters);
115
+                if($result === $passOnWhen) {
116
+                    //not found here, reset cache to null if user vanished
117
+                    //because sometimes methods return false with a reason
118
+                    $userExists = call_user_func_array(
119
+                        [$this->backends[$prefix], 'userExistsOnLDAP'],
120
+                        [$uid]
121
+                    );
122
+                    if(!$userExists) {
123
+                        $this->writeToCache($cacheKey, null);
124
+                    }
125
+                }
126
+                return $result;
127
+            }
128
+        }
129
+        return false;
130
+    }
131 131
 
132
-	/**
133
-	 * Check if backend implements actions
134
-	 * @param int $actions bitwise-or'ed actions
135
-	 * @return boolean
136
-	 *
137
-	 * Returns the supported actions as int to be
138
-	 * compared with \OC\User\Backend::CREATE_USER etc.
139
-	 */
140
-	public function implementsActions($actions) {
141
-		//it's the same across all our user backends obviously
142
-		return $this->refBackend->implementsActions($actions);
143
-	}
132
+    /**
133
+     * Check if backend implements actions
134
+     * @param int $actions bitwise-or'ed actions
135
+     * @return boolean
136
+     *
137
+     * Returns the supported actions as int to be
138
+     * compared with \OC\User\Backend::CREATE_USER etc.
139
+     */
140
+    public function implementsActions($actions) {
141
+        //it's the same across all our user backends obviously
142
+        return $this->refBackend->implementsActions($actions);
143
+    }
144 144
 
145
-	/**
146
-	 * Backend name to be shown in user management
147
-	 * @return string the name of the backend to be shown
148
-	 */
149
-	public function getBackendName() {
150
-		return $this->refBackend->getBackendName();
151
-	}
145
+    /**
146
+     * Backend name to be shown in user management
147
+     * @return string the name of the backend to be shown
148
+     */
149
+    public function getBackendName() {
150
+        return $this->refBackend->getBackendName();
151
+    }
152 152
 
153
-	/**
154
-	 * Get a list of all users
155
-	 *
156
-	 * @param string $search
157
-	 * @param null|int $limit
158
-	 * @param null|int $offset
159
-	 * @return string[] an array of all uids
160
-	 */
161
-	public function getUsers($search = '', $limit = 10, $offset = 0) {
162
-		//we do it just as the /OC_User implementation: do not play around with limit and offset but ask all backends
163
-		$users = [];
164
-		foreach($this->backends as $backend) {
165
-			$backendUsers = $backend->getUsers($search, $limit, $offset);
166
-			if (is_array($backendUsers)) {
167
-				$users = array_merge($users, $backendUsers);
168
-			}
169
-		}
170
-		return $users;
171
-	}
153
+    /**
154
+     * Get a list of all users
155
+     *
156
+     * @param string $search
157
+     * @param null|int $limit
158
+     * @param null|int $offset
159
+     * @return string[] an array of all uids
160
+     */
161
+    public function getUsers($search = '', $limit = 10, $offset = 0) {
162
+        //we do it just as the /OC_User implementation: do not play around with limit and offset but ask all backends
163
+        $users = [];
164
+        foreach($this->backends as $backend) {
165
+            $backendUsers = $backend->getUsers($search, $limit, $offset);
166
+            if (is_array($backendUsers)) {
167
+                $users = array_merge($users, $backendUsers);
168
+            }
169
+        }
170
+        return $users;
171
+    }
172 172
 
173
-	/**
174
-	 * check if a user exists
175
-	 * @param string $uid the username
176
-	 * @return boolean
177
-	 */
178
-	public function userExists($uid) {
179
-		$existsOnLDAP = false;
180
-		$existsLocally = $this->handleRequest($uid, 'userExists', [$uid]);
181
-		if($existsLocally) {
182
-			$existsOnLDAP = $this->userExistsOnLDAP($uid);
183
-		}
184
-		if($existsLocally && !$existsOnLDAP) {
185
-			try {
186
-				$user = $this->getLDAPAccess($uid)->userManager->get($uid);
187
-				if($user instanceof User) {
188
-					$user->markUser();
189
-				}
190
-			} catch (\Exception $e) {
191
-				// ignore
192
-			}
193
-		}
194
-		return $existsLocally;
195
-	}
173
+    /**
174
+     * check if a user exists
175
+     * @param string $uid the username
176
+     * @return boolean
177
+     */
178
+    public function userExists($uid) {
179
+        $existsOnLDAP = false;
180
+        $existsLocally = $this->handleRequest($uid, 'userExists', [$uid]);
181
+        if($existsLocally) {
182
+            $existsOnLDAP = $this->userExistsOnLDAP($uid);
183
+        }
184
+        if($existsLocally && !$existsOnLDAP) {
185
+            try {
186
+                $user = $this->getLDAPAccess($uid)->userManager->get($uid);
187
+                if($user instanceof User) {
188
+                    $user->markUser();
189
+                }
190
+            } catch (\Exception $e) {
191
+                // ignore
192
+            }
193
+        }
194
+        return $existsLocally;
195
+    }
196 196
 
197
-	/**
198
-	 * check if a user exists on LDAP
199
-	 * @param string|\OCA\User_LDAP\User\User $user either the Nextcloud user
200
-	 * name or an instance of that user
201
-	 * @return boolean
202
-	 */
203
-	public function userExistsOnLDAP($user) {
204
-		$id = ($user instanceof User) ? $user->getUsername() : $user;
205
-		return $this->handleRequest($id, 'userExistsOnLDAP', [$user]);
206
-	}
197
+    /**
198
+     * check if a user exists on LDAP
199
+     * @param string|\OCA\User_LDAP\User\User $user either the Nextcloud user
200
+     * name or an instance of that user
201
+     * @return boolean
202
+     */
203
+    public function userExistsOnLDAP($user) {
204
+        $id = ($user instanceof User) ? $user->getUsername() : $user;
205
+        return $this->handleRequest($id, 'userExistsOnLDAP', [$user]);
206
+    }
207 207
 
208
-	/**
209
-	 * Check if the password is correct
210
-	 * @param string $uid The username
211
-	 * @param string $password The password
212
-	 * @return bool
213
-	 *
214
-	 * Check if the password is correct without logging in the user
215
-	 */
216
-	public function checkPassword($uid, $password) {
217
-		return $this->handleRequest($uid, 'checkPassword', [$uid, $password]);
218
-	}
208
+    /**
209
+     * Check if the password is correct
210
+     * @param string $uid The username
211
+     * @param string $password The password
212
+     * @return bool
213
+     *
214
+     * Check if the password is correct without logging in the user
215
+     */
216
+    public function checkPassword($uid, $password) {
217
+        return $this->handleRequest($uid, 'checkPassword', [$uid, $password]);
218
+    }
219 219
 
220
-	/**
221
-	 * returns the username for the given login name, if available
222
-	 *
223
-	 * @param string $loginName
224
-	 * @return string|false
225
-	 */
226
-	public function loginName2UserName($loginName) {
227
-		$id = 'LOGINNAME,' . $loginName;
228
-		return $this->handleRequest($id, 'loginName2UserName', [$loginName]);
229
-	}
220
+    /**
221
+     * returns the username for the given login name, if available
222
+     *
223
+     * @param string $loginName
224
+     * @return string|false
225
+     */
226
+    public function loginName2UserName($loginName) {
227
+        $id = 'LOGINNAME,' . $loginName;
228
+        return $this->handleRequest($id, 'loginName2UserName', [$loginName]);
229
+    }
230 230
 	
231
-	/**
232
-	 * returns the username for the given LDAP DN, if available
233
-	 *
234
-	 * @param string $dn
235
-	 * @return string|false with the username
236
-	 */
237
-	public function dn2UserName($dn) {
238
-		$id = 'DN,' . $dn;
239
-		return $this->handleRequest($id, 'dn2UserName', [$dn]);
240
-	}
231
+    /**
232
+     * returns the username for the given LDAP DN, if available
233
+     *
234
+     * @param string $dn
235
+     * @return string|false with the username
236
+     */
237
+    public function dn2UserName($dn) {
238
+        $id = 'DN,' . $dn;
239
+        return $this->handleRequest($id, 'dn2UserName', [$dn]);
240
+    }
241 241
 
242
-	/**
243
-	 * get the user's home directory
244
-	 * @param string $uid the username
245
-	 * @return boolean
246
-	 */
247
-	public function getHome($uid) {
248
-		return $this->handleRequest($uid, 'getHome', [$uid]);
249
-	}
242
+    /**
243
+     * get the user's home directory
244
+     * @param string $uid the username
245
+     * @return boolean
246
+     */
247
+    public function getHome($uid) {
248
+        return $this->handleRequest($uid, 'getHome', [$uid]);
249
+    }
250 250
 
251
-	/**
252
-	 * get display name of the user
253
-	 * @param string $uid user ID of the user
254
-	 * @return string display name
255
-	 */
256
-	public function getDisplayName($uid) {
257
-		return $this->handleRequest($uid, 'getDisplayName', [$uid]);
258
-	}
251
+    /**
252
+     * get display name of the user
253
+     * @param string $uid user ID of the user
254
+     * @return string display name
255
+     */
256
+    public function getDisplayName($uid) {
257
+        return $this->handleRequest($uid, 'getDisplayName', [$uid]);
258
+    }
259 259
 
260
-	/**
261
-	 * set display name of the user
262
-	 *
263
-	 * @param string $uid user ID of the user
264
-	 * @param string $displayName new display name
265
-	 * @return string display name
266
-	 */
267
-	public function setDisplayName($uid, $displayName) {
268
-		return $this->handleRequest($uid, 'setDisplayName', [$uid, $displayName]);
269
-	}
260
+    /**
261
+     * set display name of the user
262
+     *
263
+     * @param string $uid user ID of the user
264
+     * @param string $displayName new display name
265
+     * @return string display name
266
+     */
267
+    public function setDisplayName($uid, $displayName) {
268
+        return $this->handleRequest($uid, 'setDisplayName', [$uid, $displayName]);
269
+    }
270 270
 
271
-	/**
272
-	 * checks whether the user is allowed to change his avatar in Nextcloud
273
-	 * @param string $uid the Nextcloud user name
274
-	 * @return boolean either the user can or cannot
275
-	 */
276
-	public function canChangeAvatar($uid) {
277
-		return $this->handleRequest($uid, 'canChangeAvatar', [$uid], true);
278
-	}
271
+    /**
272
+     * checks whether the user is allowed to change his avatar in Nextcloud
273
+     * @param string $uid the Nextcloud user name
274
+     * @return boolean either the user can or cannot
275
+     */
276
+    public function canChangeAvatar($uid) {
277
+        return $this->handleRequest($uid, 'canChangeAvatar', [$uid], true);
278
+    }
279 279
 
280
-	/**
281
-	 * Get a list of all display names and user ids.
282
-	 * @param string $search
283
-	 * @param string|null $limit
284
-	 * @param string|null $offset
285
-	 * @return array an array of all displayNames (value) and the corresponding uids (key)
286
-	 */
287
-	public function getDisplayNames($search = '', $limit = null, $offset = null) {
288
-		//we do it just as the /OC_User implementation: do not play around with limit and offset but ask all backends
289
-		$users = [];
290
-		foreach($this->backends as $backend) {
291
-			$backendUsers = $backend->getDisplayNames($search, $limit, $offset);
292
-			if (is_array($backendUsers)) {
293
-				$users = $users + $backendUsers;
294
-			}
295
-		}
296
-		return $users;
297
-	}
280
+    /**
281
+     * Get a list of all display names and user ids.
282
+     * @param string $search
283
+     * @param string|null $limit
284
+     * @param string|null $offset
285
+     * @return array an array of all displayNames (value) and the corresponding uids (key)
286
+     */
287
+    public function getDisplayNames($search = '', $limit = null, $offset = null) {
288
+        //we do it just as the /OC_User implementation: do not play around with limit and offset but ask all backends
289
+        $users = [];
290
+        foreach($this->backends as $backend) {
291
+            $backendUsers = $backend->getDisplayNames($search, $limit, $offset);
292
+            if (is_array($backendUsers)) {
293
+                $users = $users + $backendUsers;
294
+            }
295
+        }
296
+        return $users;
297
+    }
298 298
 
299
-	/**
300
-	 * delete a user
301
-	 * @param string $uid The username of the user to delete
302
-	 * @return bool
303
-	 *
304
-	 * Deletes a user
305
-	 */
306
-	public function deleteUser($uid) {
307
-		return $this->handleRequest($uid, 'deleteUser', [$uid]);
308
-	}
299
+    /**
300
+     * delete a user
301
+     * @param string $uid The username of the user to delete
302
+     * @return bool
303
+     *
304
+     * Deletes a user
305
+     */
306
+    public function deleteUser($uid) {
307
+        return $this->handleRequest($uid, 'deleteUser', [$uid]);
308
+    }
309 309
 	
310
-	/**
311
-	 * Set password
312
-	 * @param string $uid The username
313
-	 * @param string $password The new password
314
-	 * @return bool
315
-	 *
316
-	 */
317
-	public function setPassword($uid, $password) {
318
-		return $this->handleRequest($uid, 'setPassword', [$uid, $password]);
319
-	}
310
+    /**
311
+     * Set password
312
+     * @param string $uid The username
313
+     * @param string $password The new password
314
+     * @return bool
315
+     *
316
+     */
317
+    public function setPassword($uid, $password) {
318
+        return $this->handleRequest($uid, 'setPassword', [$uid, $password]);
319
+    }
320 320
 
321
-	/**
322
-	 * @return bool
323
-	 */
324
-	public function hasUserListings() {
325
-		return $this->refBackend->hasUserListings();
326
-	}
321
+    /**
322
+     * @return bool
323
+     */
324
+    public function hasUserListings() {
325
+        return $this->refBackend->hasUserListings();
326
+    }
327 327
 
328
-	/**
329
-	 * Count the number of users
330
-	 * @return int|bool
331
-	 */
332
-	public function countUsers() {
333
-		$users = false;
334
-		foreach($this->backends as $backend) {
335
-			$backendUsers = $backend->countUsers();
336
-			if ($backendUsers !== false) {
337
-				$users += $backendUsers;
338
-			}
339
-		}
340
-		return $users;
341
-	}
328
+    /**
329
+     * Count the number of users
330
+     * @return int|bool
331
+     */
332
+    public function countUsers() {
333
+        $users = false;
334
+        foreach($this->backends as $backend) {
335
+            $backendUsers = $backend->countUsers();
336
+            if ($backendUsers !== false) {
337
+                $users += $backendUsers;
338
+            }
339
+        }
340
+        return $users;
341
+    }
342 342
 
343
-	/**
344
-	 * Return access for LDAP interaction.
345
-	 * @param string $uid
346
-	 * @return Access instance of Access for LDAP interaction
347
-	 */
348
-	public function getLDAPAccess($uid) {
349
-		return $this->handleRequest($uid, 'getLDAPAccess', [$uid]);
350
-	}
343
+    /**
344
+     * Return access for LDAP interaction.
345
+     * @param string $uid
346
+     * @return Access instance of Access for LDAP interaction
347
+     */
348
+    public function getLDAPAccess($uid) {
349
+        return $this->handleRequest($uid, 'getLDAPAccess', [$uid]);
350
+    }
351 351
 	
352
-	/**
353
-	 * Return a new LDAP connection for the specified user.
354
-	 * The connection needs to be closed manually.
355
-	 * @param string $uid
356
-	 * @return resource of the LDAP connection
357
-	 */
358
-	public function getNewLDAPConnection($uid) {
359
-		return $this->handleRequest($uid, 'getNewLDAPConnection', [$uid]);
360
-	}
352
+    /**
353
+     * Return a new LDAP connection for the specified user.
354
+     * The connection needs to be closed manually.
355
+     * @param string $uid
356
+     * @return resource of the LDAP connection
357
+     */
358
+    public function getNewLDAPConnection($uid) {
359
+        return $this->handleRequest($uid, 'getNewLDAPConnection', [$uid]);
360
+    }
361 361
 
362
-	/**
363
-	 * Creates a new user in LDAP
364
-	 * @param $username
365
-	 * @param $password
366
-	 * @return bool
367
-	 */
368
-	public function createUser($username, $password) {
369
-		return $this->handleRequest($username, 'createUser', [$username,$password]);
370
-	}
362
+    /**
363
+     * Creates a new user in LDAP
364
+     * @param $username
365
+     * @param $password
366
+     * @return bool
367
+     */
368
+    public function createUser($username, $password) {
369
+        return $this->handleRequest($username, 'createUser', [$username,$password]);
370
+    }
371 371
 }
Please login to merge, or discard this patch.