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