Passed
Push — master ( 57ed51...959a0b )
by Roeland
23:00 queued 11:38
created
apps/user_ldap/lib/User_LDAP.php 1 patch
Indentation   +580 added lines, -580 removed lines patch added patch discarded remove patch
@@ -52,587 +52,587 @@
 block discarded – undo
52 52
 use OCP\Util;
53 53
 
54 54
 class User_LDAP extends BackendUtility implements \OCP\IUserBackend, \OCP\UserInterface, IUserLDAP {
55
-	/** @var \OCP\IConfig */
56
-	protected $ocConfig;
57
-
58
-	/** @var INotificationManager */
59
-	protected $notificationManager;
60
-
61
-	/** @var UserPluginManager */
62
-	protected $userPluginManager;
63
-
64
-	/**
65
-	 * @param Access $access
66
-	 * @param \OCP\IConfig $ocConfig
67
-	 * @param \OCP\Notification\IManager $notificationManager
68
-	 * @param IUserSession $userSession
69
-	 */
70
-	public function __construct(Access $access, IConfig $ocConfig, INotificationManager $notificationManager, IUserSession $userSession, UserPluginManager $userPluginManager) {
71
-		parent::__construct($access);
72
-		$this->ocConfig = $ocConfig;
73
-		$this->notificationManager = $notificationManager;
74
-		$this->userPluginManager = $userPluginManager;
75
-	}
76
-
77
-	/**
78
-	 * checks whether the user is allowed to change his avatar in Nextcloud
79
-	 *
80
-	 * @param string $uid the Nextcloud user name
81
-	 * @return boolean either the user can or cannot
82
-	 * @throws \Exception
83
-	 */
84
-	public function canChangeAvatar($uid) {
85
-		if ($this->userPluginManager->implementsActions(Backend::PROVIDE_AVATAR)) {
86
-			return $this->userPluginManager->canChangeAvatar($uid);
87
-		}
88
-
89
-		if (!$this->implementsActions(Backend::PROVIDE_AVATAR)) {
90
-			return true;
91
-		}
92
-
93
-		$user = $this->access->userManager->get($uid);
94
-		if (!$user instanceof User) {
95
-			return false;
96
-		}
97
-		$imageData = $user->getAvatarImage();
98
-		if ($imageData === false) {
99
-			return true;
100
-		}
101
-		return !$user->updateAvatar(true);
102
-	}
103
-
104
-	/**
105
-	 * Return the username for the given login name, if available
106
-	 *
107
-	 * @param string $loginName
108
-	 * @return string|false
109
-	 * @throws \Exception
110
-	 */
111
-	public function loginName2UserName($loginName) {
112
-		$cacheKey = 'loginName2UserName-' . $loginName;
113
-		$username = $this->access->connection->getFromCache($cacheKey);
114
-
115
-		if ($username !== null) {
116
-			return $username;
117
-		}
118
-
119
-		try {
120
-			$ldapRecord = $this->getLDAPUserByLoginName($loginName);
121
-			$user = $this->access->userManager->get($ldapRecord['dn'][0]);
122
-			if ($user === null || $user instanceof OfflineUser) {
123
-				// this path is not really possible, however get() is documented
124
-				// to return User, OfflineUser or null so we are very defensive here.
125
-				$this->access->connection->writeToCache($cacheKey, false);
126
-				return false;
127
-			}
128
-			$username = $user->getUsername();
129
-			$this->access->connection->writeToCache($cacheKey, $username);
130
-			return $username;
131
-		} catch (NotOnLDAP $e) {
132
-			$this->access->connection->writeToCache($cacheKey, false);
133
-			return false;
134
-		}
135
-	}
55
+    /** @var \OCP\IConfig */
56
+    protected $ocConfig;
57
+
58
+    /** @var INotificationManager */
59
+    protected $notificationManager;
60
+
61
+    /** @var UserPluginManager */
62
+    protected $userPluginManager;
63
+
64
+    /**
65
+     * @param Access $access
66
+     * @param \OCP\IConfig $ocConfig
67
+     * @param \OCP\Notification\IManager $notificationManager
68
+     * @param IUserSession $userSession
69
+     */
70
+    public function __construct(Access $access, IConfig $ocConfig, INotificationManager $notificationManager, IUserSession $userSession, UserPluginManager $userPluginManager) {
71
+        parent::__construct($access);
72
+        $this->ocConfig = $ocConfig;
73
+        $this->notificationManager = $notificationManager;
74
+        $this->userPluginManager = $userPluginManager;
75
+    }
76
+
77
+    /**
78
+     * checks whether the user is allowed to change his avatar in Nextcloud
79
+     *
80
+     * @param string $uid the Nextcloud user name
81
+     * @return boolean either the user can or cannot
82
+     * @throws \Exception
83
+     */
84
+    public function canChangeAvatar($uid) {
85
+        if ($this->userPluginManager->implementsActions(Backend::PROVIDE_AVATAR)) {
86
+            return $this->userPluginManager->canChangeAvatar($uid);
87
+        }
88
+
89
+        if (!$this->implementsActions(Backend::PROVIDE_AVATAR)) {
90
+            return true;
91
+        }
92
+
93
+        $user = $this->access->userManager->get($uid);
94
+        if (!$user instanceof User) {
95
+            return false;
96
+        }
97
+        $imageData = $user->getAvatarImage();
98
+        if ($imageData === false) {
99
+            return true;
100
+        }
101
+        return !$user->updateAvatar(true);
102
+    }
103
+
104
+    /**
105
+     * Return the username for the given login name, if available
106
+     *
107
+     * @param string $loginName
108
+     * @return string|false
109
+     * @throws \Exception
110
+     */
111
+    public function loginName2UserName($loginName) {
112
+        $cacheKey = 'loginName2UserName-' . $loginName;
113
+        $username = $this->access->connection->getFromCache($cacheKey);
114
+
115
+        if ($username !== null) {
116
+            return $username;
117
+        }
118
+
119
+        try {
120
+            $ldapRecord = $this->getLDAPUserByLoginName($loginName);
121
+            $user = $this->access->userManager->get($ldapRecord['dn'][0]);
122
+            if ($user === null || $user instanceof OfflineUser) {
123
+                // this path is not really possible, however get() is documented
124
+                // to return User, OfflineUser or null so we are very defensive here.
125
+                $this->access->connection->writeToCache($cacheKey, false);
126
+                return false;
127
+            }
128
+            $username = $user->getUsername();
129
+            $this->access->connection->writeToCache($cacheKey, $username);
130
+            return $username;
131
+        } catch (NotOnLDAP $e) {
132
+            $this->access->connection->writeToCache($cacheKey, false);
133
+            return false;
134
+        }
135
+    }
136 136
 	
137
-	/**
138
-	 * returns the username for the given LDAP DN, if available
139
-	 *
140
-	 * @param string $dn
141
-	 * @return string|false with the username
142
-	 */
143
-	public function dn2UserName($dn) {
144
-		return $this->access->dn2username($dn);
145
-	}
146
-
147
-	/**
148
-	 * returns an LDAP record based on a given login name
149
-	 *
150
-	 * @param string $loginName
151
-	 * @return array
152
-	 * @throws NotOnLDAP
153
-	 */
154
-	public function getLDAPUserByLoginName($loginName) {
155
-		//find out dn of the user name
156
-		$attrs = $this->access->userManager->getAttributes();
157
-		$users = $this->access->fetchUsersByLoginName($loginName, $attrs);
158
-		if (count($users) < 1) {
159
-			throw new NotOnLDAP('No user available for the given login name on ' .
160
-				$this->access->connection->ldapHost . ':' . $this->access->connection->ldapPort);
161
-		}
162
-		return $users[0];
163
-	}
164
-
165
-	/**
166
-	 * Check if the password is correct without logging in the user
167
-	 *
168
-	 * @param string $uid The username
169
-	 * @param string $password The password
170
-	 * @return false|string
171
-	 */
172
-	public function checkPassword($uid, $password) {
173
-		try {
174
-			$ldapRecord = $this->getLDAPUserByLoginName($uid);
175
-		} catch (NotOnLDAP $e) {
176
-			\OC::$server->getLogger()->logException($e, ['app' => 'user_ldap', 'level' => ILogger::DEBUG]);
177
-			return false;
178
-		}
179
-		$dn = $ldapRecord['dn'][0];
180
-		$user = $this->access->userManager->get($dn);
181
-
182
-		if (!$user instanceof User) {
183
-			Util::writeLog('user_ldap',
184
-				'LDAP Login: Could not get user object for DN ' . $dn .
185
-				'. Maybe the LDAP entry has no set display name attribute?',
186
-				ILogger::WARN);
187
-			return false;
188
-		}
189
-		if ($user->getUsername() !== false) {
190
-			//are the credentials OK?
191
-			if (!$this->access->areCredentialsValid($dn, $password)) {
192
-				return false;
193
-			}
194
-
195
-			$this->access->cacheUserExists($user->getUsername());
196
-			$user->processAttributes($ldapRecord);
197
-			$user->markLogin();
198
-
199
-			return $user->getUsername();
200
-		}
201
-
202
-		return false;
203
-	}
204
-
205
-	/**
206
-	 * Set password
207
-	 * @param string $uid The username
208
-	 * @param string $password The new password
209
-	 * @return bool
210
-	 */
211
-	public function setPassword($uid, $password) {
212
-		if ($this->userPluginManager->implementsActions(Backend::SET_PASSWORD)) {
213
-			return $this->userPluginManager->setPassword($uid, $password);
214
-		}
215
-
216
-		$user = $this->access->userManager->get($uid);
217
-
218
-		if (!$user instanceof User) {
219
-			throw new \Exception('LDAP setPassword: Could not get user object for uid ' . $uid .
220
-				'. Maybe the LDAP entry has no set display name attribute?');
221
-		}
222
-		if ($user->getUsername() !== false && $this->access->setPassword($user->getDN(), $password)) {
223
-			$ldapDefaultPPolicyDN = $this->access->connection->ldapDefaultPPolicyDN;
224
-			$turnOnPasswordChange = $this->access->connection->turnOnPasswordChange;
225
-			if (!empty($ldapDefaultPPolicyDN) && ((int)$turnOnPasswordChange === 1)) {
226
-				//remove last password expiry warning if any
227
-				$notification = $this->notificationManager->createNotification();
228
-				$notification->setApp('user_ldap')
229
-					->setUser($uid)
230
-					->setObject('pwd_exp_warn', $uid)
231
-				;
232
-				$this->notificationManager->markProcessed($notification);
233
-			}
234
-			return true;
235
-		}
236
-
237
-		return false;
238
-	}
239
-
240
-	/**
241
-	 * Get a list of all users
242
-	 *
243
-	 * @param string $search
244
-	 * @param integer $limit
245
-	 * @param integer $offset
246
-	 * @return string[] an array of all uids
247
-	 */
248
-	public function getUsers($search = '', $limit = 10, $offset = 0) {
249
-		$search = $this->access->escapeFilterPart($search, true);
250
-		$cachekey = 'getUsers-'.$search.'-'.$limit.'-'.$offset;
251
-
252
-		//check if users are cached, if so return
253
-		$ldap_users = $this->access->connection->getFromCache($cachekey);
254
-		if (!is_null($ldap_users)) {
255
-			return $ldap_users;
256
-		}
257
-
258
-		// if we'd pass -1 to LDAP search, we'd end up in a Protocol
259
-		// error. With a limit of 0, we get 0 results. So we pass null.
260
-		if ($limit <= 0) {
261
-			$limit = null;
262
-		}
263
-		$filter = $this->access->combineFilterWithAnd([
264
-			$this->access->connection->ldapUserFilter,
265
-			$this->access->connection->ldapUserDisplayName . '=*',
266
-			$this->access->getFilterPartForUserSearch($search)
267
-		]);
268
-
269
-		Util::writeLog('user_ldap',
270
-			'getUsers: Options: search '.$search.' limit '.$limit.' offset '.$offset.' Filter: '.$filter,
271
-			ILogger::DEBUG);
272
-		//do the search and translate results to Nextcloud names
273
-		$ldap_users = $this->access->fetchListOfUsers(
274
-			$filter,
275
-			$this->access->userManager->getAttributes(true),
276
-			$limit, $offset);
277
-		$ldap_users = $this->access->nextcloudUserNames($ldap_users);
278
-		Util::writeLog('user_ldap', 'getUsers: '.count($ldap_users). ' Users found', ILogger::DEBUG);
279
-
280
-		$this->access->connection->writeToCache($cachekey, $ldap_users);
281
-		return $ldap_users;
282
-	}
283
-
284
-	/**
285
-	 * checks whether a user is still available on LDAP
286
-	 *
287
-	 * @param string|\OCA\User_LDAP\User\User $user either the Nextcloud user
288
-	 * name or an instance of that user
289
-	 * @return bool
290
-	 * @throws \Exception
291
-	 * @throws \OC\ServerNotAvailableException
292
-	 */
293
-	public function userExistsOnLDAP($user) {
294
-		if (is_string($user)) {
295
-			$user = $this->access->userManager->get($user);
296
-		}
297
-		if (is_null($user)) {
298
-			return false;
299
-		}
300
-		$uid = $user instanceof User ? $user->getUsername() : $user->getOCName();
301
-		$cacheKey = 'userExistsOnLDAP' . $uid;
302
-		$userExists = $this->access->connection->getFromCache($cacheKey);
303
-		if (!is_null($userExists)) {
304
-			return (bool)$userExists;
305
-		}
306
-
307
-		$dn = $user->getDN();
308
-		//check if user really still exists by reading its entry
309
-		if (!is_array($this->access->readAttribute($dn, '', $this->access->connection->ldapUserFilter))) {
310
-			try {
311
-				$uuid = $this->access->getUserMapper()->getUUIDByDN($dn);
312
-				if (!$uuid) {
313
-					$this->access->connection->writeToCache($cacheKey, false);
314
-					return false;
315
-				}
316
-				$newDn = $this->access->getUserDnByUuid($uuid);
317
-				//check if renamed user is still valid by reapplying the ldap filter
318
-				if ($newDn === $dn || !is_array($this->access->readAttribute($newDn, '', $this->access->connection->ldapUserFilter))) {
319
-					$this->access->connection->writeToCache($cacheKey, false);
320
-					return false;
321
-				}
322
-				$this->access->getUserMapper()->setDNbyUUID($newDn, $uuid);
323
-				$this->access->connection->writeToCache($cacheKey, true);
324
-				return true;
325
-			} catch (ServerNotAvailableException $e) {
326
-				throw $e;
327
-			} catch (\Exception $e) {
328
-				$this->access->connection->writeToCache($cacheKey, false);
329
-				return false;
330
-			}
331
-		}
332
-
333
-		if ($user instanceof OfflineUser) {
334
-			$user->unmark();
335
-		}
336
-
337
-		$this->access->connection->writeToCache($cacheKey, true);
338
-		return true;
339
-	}
340
-
341
-	/**
342
-	 * check if a user exists
343
-	 * @param string $uid the username
344
-	 * @return boolean
345
-	 * @throws \Exception when connection could not be established
346
-	 */
347
-	public function userExists($uid) {
348
-		$userExists = $this->access->connection->getFromCache('userExists'.$uid);
349
-		if (!is_null($userExists)) {
350
-			return (bool)$userExists;
351
-		}
352
-		//getting dn, if false the user does not exist. If dn, he may be mapped only, requires more checking.
353
-		$user = $this->access->userManager->get($uid);
354
-
355
-		if (is_null($user)) {
356
-			Util::writeLog('user_ldap', 'No DN found for '.$uid.' on '.
357
-				$this->access->connection->ldapHost, ILogger::DEBUG);
358
-			$this->access->connection->writeToCache('userExists'.$uid, false);
359
-			return false;
360
-		}
361
-
362
-		$this->access->connection->writeToCache('userExists'.$uid, true);
363
-		return true;
364
-	}
365
-
366
-	/**
367
-	 * returns whether a user was deleted in LDAP
368
-	 *
369
-	 * @param string $uid The username of the user to delete
370
-	 * @return bool
371
-	 */
372
-	public function deleteUser($uid) {
373
-		if ($this->userPluginManager->canDeleteUser()) {
374
-			$status = $this->userPluginManager->deleteUser($uid);
375
-			if ($status === false) {
376
-				return false;
377
-			}
378
-		}
379
-
380
-		$marked = $this->ocConfig->getUserValue($uid, 'user_ldap', 'isDeleted', 0);
381
-		if ((int)$marked === 0) {
382
-			\OC::$server->getLogger()->notice(
383
-				'User '.$uid . ' is not marked as deleted, not cleaning up.',
384
-				['app' => 'user_ldap']);
385
-			return false;
386
-		}
387
-		\OC::$server->getLogger()->info('Cleaning up after user ' . $uid,
388
-			['app' => 'user_ldap']);
389
-
390
-		$this->access->getUserMapper()->unmap($uid); // we don't emit unassign signals here, since it is implicit to delete signals fired from core
391
-		$this->access->userManager->invalidate($uid);
392
-		$this->access->connection->clearCache();
393
-		return true;
394
-	}
395
-
396
-	/**
397
-	 * get the user's home directory
398
-	 *
399
-	 * @param string $uid the username
400
-	 * @return bool|string
401
-	 * @throws NoUserException
402
-	 * @throws \Exception
403
-	 */
404
-	public function getHome($uid) {
405
-		// user Exists check required as it is not done in user proxy!
406
-		if (!$this->userExists($uid)) {
407
-			return false;
408
-		}
409
-
410
-		if ($this->userPluginManager->implementsActions(Backend::GET_HOME)) {
411
-			return $this->userPluginManager->getHome($uid);
412
-		}
413
-
414
-		$cacheKey = 'getHome'.$uid;
415
-		$path = $this->access->connection->getFromCache($cacheKey);
416
-		if (!is_null($path)) {
417
-			return $path;
418
-		}
419
-
420
-		// early return path if it is a deleted user
421
-		$user = $this->access->userManager->get($uid);
422
-		if ($user instanceof User || $user instanceof OfflineUser) {
423
-			$path = $user->getHomePath() ?: false;
424
-		} else {
425
-			throw new NoUserException($uid . ' is not a valid user anymore');
426
-		}
427
-
428
-		$this->access->cacheUserHome($uid, $path);
429
-		return $path;
430
-	}
431
-
432
-	/**
433
-	 * get display name of the user
434
-	 * @param string $uid user ID of the user
435
-	 * @return string|false display name
436
-	 */
437
-	public function getDisplayName($uid) {
438
-		if ($this->userPluginManager->implementsActions(Backend::GET_DISPLAYNAME)) {
439
-			return $this->userPluginManager->getDisplayName($uid);
440
-		}
441
-
442
-		if (!$this->userExists($uid)) {
443
-			return false;
444
-		}
445
-
446
-		$cacheKey = 'getDisplayName'.$uid;
447
-		if (!is_null($displayName = $this->access->connection->getFromCache($cacheKey))) {
448
-			return $displayName;
449
-		}
450
-
451
-		//Check whether the display name is configured to have a 2nd feature
452
-		$additionalAttribute = $this->access->connection->ldapUserDisplayName2;
453
-		$displayName2 = '';
454
-		if ($additionalAttribute !== '') {
455
-			$displayName2 = $this->access->readAttribute(
456
-				$this->access->username2dn($uid),
457
-				$additionalAttribute);
458
-		}
459
-
460
-		$displayName = $this->access->readAttribute(
461
-			$this->access->username2dn($uid),
462
-			$this->access->connection->ldapUserDisplayName);
463
-
464
-		if ($displayName && (count($displayName) > 0)) {
465
-			$displayName = $displayName[0];
466
-
467
-			if (is_array($displayName2)) {
468
-				$displayName2 = count($displayName2) > 0 ? $displayName2[0] : '';
469
-			}
470
-
471
-			$user = $this->access->userManager->get($uid);
472
-			if ($user instanceof User) {
473
-				$displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
474
-				$this->access->connection->writeToCache($cacheKey, $displayName);
475
-			}
476
-			if ($user instanceof OfflineUser) {
477
-				/** @var OfflineUser $user*/
478
-				$displayName = $user->getDisplayName();
479
-			}
480
-			return $displayName;
481
-		}
482
-
483
-		return null;
484
-	}
485
-
486
-	/**
487
-	 * set display name of the user
488
-	 * @param string $uid user ID of the user
489
-	 * @param string $displayName new display name of the user
490
-	 * @return string|false display name
491
-	 */
492
-	public function setDisplayName($uid, $displayName) {
493
-		if ($this->userPluginManager->implementsActions(Backend::SET_DISPLAYNAME)) {
494
-			$this->userPluginManager->setDisplayName($uid, $displayName);
495
-			$this->access->cacheUserDisplayName($uid, $displayName);
496
-			return $displayName;
497
-		}
498
-		return false;
499
-	}
500
-
501
-	/**
502
-	 * Get a list of all display names
503
-	 *
504
-	 * @param string $search
505
-	 * @param string|null $limit
506
-	 * @param string|null $offset
507
-	 * @return array an array of all displayNames (value) and the corresponding uids (key)
508
-	 */
509
-	public function getDisplayNames($search = '', $limit = null, $offset = null) {
510
-		$cacheKey = 'getDisplayNames-'.$search.'-'.$limit.'-'.$offset;
511
-		if (!is_null($displayNames = $this->access->connection->getFromCache($cacheKey))) {
512
-			return $displayNames;
513
-		}
514
-
515
-		$displayNames = [];
516
-		$users = $this->getUsers($search, $limit, $offset);
517
-		foreach ($users as $user) {
518
-			$displayNames[$user] = $this->getDisplayName($user);
519
-		}
520
-		$this->access->connection->writeToCache($cacheKey, $displayNames);
521
-		return $displayNames;
522
-	}
523
-
524
-	/**
525
-	 * Check if backend implements actions
526
-	 * @param int $actions bitwise-or'ed actions
527
-	 * @return boolean
528
-	 *
529
-	 * Returns the supported actions as int to be
530
-	 * compared with \OC\User\Backend::CREATE_USER etc.
531
-	 */
532
-	public function implementsActions($actions) {
533
-		return (bool)((Backend::CHECK_PASSWORD
534
-			| Backend::GET_HOME
535
-			| Backend::GET_DISPLAYNAME
536
-			| (($this->access->connection->ldapUserAvatarRule !== 'none') ? Backend::PROVIDE_AVATAR : 0)
537
-			| Backend::COUNT_USERS
538
-			| (((int)$this->access->connection->turnOnPasswordChange === 1)? Backend::SET_PASSWORD :0)
539
-			| $this->userPluginManager->getImplementedActions())
540
-			& $actions);
541
-	}
542
-
543
-	/**
544
-	 * @return bool
545
-	 */
546
-	public function hasUserListings() {
547
-		return true;
548
-	}
549
-
550
-	/**
551
-	 * counts the users in LDAP
552
-	 *
553
-	 * @return int|bool
554
-	 */
555
-	public function countUsers() {
556
-		if ($this->userPluginManager->implementsActions(Backend::COUNT_USERS)) {
557
-			return $this->userPluginManager->countUsers();
558
-		}
559
-
560
-		$filter = $this->access->getFilterForUserCount();
561
-		$cacheKey = 'countUsers-'.$filter;
562
-		if (!is_null($entries = $this->access->connection->getFromCache($cacheKey))) {
563
-			return $entries;
564
-		}
565
-		$entries = $this->access->countUsers($filter);
566
-		$this->access->connection->writeToCache($cacheKey, $entries);
567
-		return $entries;
568
-	}
569
-
570
-	/**
571
-	 * Backend name to be shown in user management
572
-	 * @return string the name of the backend to be shown
573
-	 */
574
-	public function getBackendName() {
575
-		return 'LDAP';
576
-	}
137
+    /**
138
+     * returns the username for the given LDAP DN, if available
139
+     *
140
+     * @param string $dn
141
+     * @return string|false with the username
142
+     */
143
+    public function dn2UserName($dn) {
144
+        return $this->access->dn2username($dn);
145
+    }
146
+
147
+    /**
148
+     * returns an LDAP record based on a given login name
149
+     *
150
+     * @param string $loginName
151
+     * @return array
152
+     * @throws NotOnLDAP
153
+     */
154
+    public function getLDAPUserByLoginName($loginName) {
155
+        //find out dn of the user name
156
+        $attrs = $this->access->userManager->getAttributes();
157
+        $users = $this->access->fetchUsersByLoginName($loginName, $attrs);
158
+        if (count($users) < 1) {
159
+            throw new NotOnLDAP('No user available for the given login name on ' .
160
+                $this->access->connection->ldapHost . ':' . $this->access->connection->ldapPort);
161
+        }
162
+        return $users[0];
163
+    }
164
+
165
+    /**
166
+     * Check if the password is correct without logging in the user
167
+     *
168
+     * @param string $uid The username
169
+     * @param string $password The password
170
+     * @return false|string
171
+     */
172
+    public function checkPassword($uid, $password) {
173
+        try {
174
+            $ldapRecord = $this->getLDAPUserByLoginName($uid);
175
+        } catch (NotOnLDAP $e) {
176
+            \OC::$server->getLogger()->logException($e, ['app' => 'user_ldap', 'level' => ILogger::DEBUG]);
177
+            return false;
178
+        }
179
+        $dn = $ldapRecord['dn'][0];
180
+        $user = $this->access->userManager->get($dn);
181
+
182
+        if (!$user instanceof User) {
183
+            Util::writeLog('user_ldap',
184
+                'LDAP Login: Could not get user object for DN ' . $dn .
185
+                '. Maybe the LDAP entry has no set display name attribute?',
186
+                ILogger::WARN);
187
+            return false;
188
+        }
189
+        if ($user->getUsername() !== false) {
190
+            //are the credentials OK?
191
+            if (!$this->access->areCredentialsValid($dn, $password)) {
192
+                return false;
193
+            }
194
+
195
+            $this->access->cacheUserExists($user->getUsername());
196
+            $user->processAttributes($ldapRecord);
197
+            $user->markLogin();
198
+
199
+            return $user->getUsername();
200
+        }
201
+
202
+        return false;
203
+    }
204
+
205
+    /**
206
+     * Set password
207
+     * @param string $uid The username
208
+     * @param string $password The new password
209
+     * @return bool
210
+     */
211
+    public function setPassword($uid, $password) {
212
+        if ($this->userPluginManager->implementsActions(Backend::SET_PASSWORD)) {
213
+            return $this->userPluginManager->setPassword($uid, $password);
214
+        }
215
+
216
+        $user = $this->access->userManager->get($uid);
217
+
218
+        if (!$user instanceof User) {
219
+            throw new \Exception('LDAP setPassword: Could not get user object for uid ' . $uid .
220
+                '. Maybe the LDAP entry has no set display name attribute?');
221
+        }
222
+        if ($user->getUsername() !== false && $this->access->setPassword($user->getDN(), $password)) {
223
+            $ldapDefaultPPolicyDN = $this->access->connection->ldapDefaultPPolicyDN;
224
+            $turnOnPasswordChange = $this->access->connection->turnOnPasswordChange;
225
+            if (!empty($ldapDefaultPPolicyDN) && ((int)$turnOnPasswordChange === 1)) {
226
+                //remove last password expiry warning if any
227
+                $notification = $this->notificationManager->createNotification();
228
+                $notification->setApp('user_ldap')
229
+                    ->setUser($uid)
230
+                    ->setObject('pwd_exp_warn', $uid)
231
+                ;
232
+                $this->notificationManager->markProcessed($notification);
233
+            }
234
+            return true;
235
+        }
236
+
237
+        return false;
238
+    }
239
+
240
+    /**
241
+     * Get a list of all users
242
+     *
243
+     * @param string $search
244
+     * @param integer $limit
245
+     * @param integer $offset
246
+     * @return string[] an array of all uids
247
+     */
248
+    public function getUsers($search = '', $limit = 10, $offset = 0) {
249
+        $search = $this->access->escapeFilterPart($search, true);
250
+        $cachekey = 'getUsers-'.$search.'-'.$limit.'-'.$offset;
251
+
252
+        //check if users are cached, if so return
253
+        $ldap_users = $this->access->connection->getFromCache($cachekey);
254
+        if (!is_null($ldap_users)) {
255
+            return $ldap_users;
256
+        }
257
+
258
+        // if we'd pass -1 to LDAP search, we'd end up in a Protocol
259
+        // error. With a limit of 0, we get 0 results. So we pass null.
260
+        if ($limit <= 0) {
261
+            $limit = null;
262
+        }
263
+        $filter = $this->access->combineFilterWithAnd([
264
+            $this->access->connection->ldapUserFilter,
265
+            $this->access->connection->ldapUserDisplayName . '=*',
266
+            $this->access->getFilterPartForUserSearch($search)
267
+        ]);
268
+
269
+        Util::writeLog('user_ldap',
270
+            'getUsers: Options: search '.$search.' limit '.$limit.' offset '.$offset.' Filter: '.$filter,
271
+            ILogger::DEBUG);
272
+        //do the search and translate results to Nextcloud names
273
+        $ldap_users = $this->access->fetchListOfUsers(
274
+            $filter,
275
+            $this->access->userManager->getAttributes(true),
276
+            $limit, $offset);
277
+        $ldap_users = $this->access->nextcloudUserNames($ldap_users);
278
+        Util::writeLog('user_ldap', 'getUsers: '.count($ldap_users). ' Users found', ILogger::DEBUG);
279
+
280
+        $this->access->connection->writeToCache($cachekey, $ldap_users);
281
+        return $ldap_users;
282
+    }
283
+
284
+    /**
285
+     * checks whether a user is still available on LDAP
286
+     *
287
+     * @param string|\OCA\User_LDAP\User\User $user either the Nextcloud user
288
+     * name or an instance of that user
289
+     * @return bool
290
+     * @throws \Exception
291
+     * @throws \OC\ServerNotAvailableException
292
+     */
293
+    public function userExistsOnLDAP($user) {
294
+        if (is_string($user)) {
295
+            $user = $this->access->userManager->get($user);
296
+        }
297
+        if (is_null($user)) {
298
+            return false;
299
+        }
300
+        $uid = $user instanceof User ? $user->getUsername() : $user->getOCName();
301
+        $cacheKey = 'userExistsOnLDAP' . $uid;
302
+        $userExists = $this->access->connection->getFromCache($cacheKey);
303
+        if (!is_null($userExists)) {
304
+            return (bool)$userExists;
305
+        }
306
+
307
+        $dn = $user->getDN();
308
+        //check if user really still exists by reading its entry
309
+        if (!is_array($this->access->readAttribute($dn, '', $this->access->connection->ldapUserFilter))) {
310
+            try {
311
+                $uuid = $this->access->getUserMapper()->getUUIDByDN($dn);
312
+                if (!$uuid) {
313
+                    $this->access->connection->writeToCache($cacheKey, false);
314
+                    return false;
315
+                }
316
+                $newDn = $this->access->getUserDnByUuid($uuid);
317
+                //check if renamed user is still valid by reapplying the ldap filter
318
+                if ($newDn === $dn || !is_array($this->access->readAttribute($newDn, '', $this->access->connection->ldapUserFilter))) {
319
+                    $this->access->connection->writeToCache($cacheKey, false);
320
+                    return false;
321
+                }
322
+                $this->access->getUserMapper()->setDNbyUUID($newDn, $uuid);
323
+                $this->access->connection->writeToCache($cacheKey, true);
324
+                return true;
325
+            } catch (ServerNotAvailableException $e) {
326
+                throw $e;
327
+            } catch (\Exception $e) {
328
+                $this->access->connection->writeToCache($cacheKey, false);
329
+                return false;
330
+            }
331
+        }
332
+
333
+        if ($user instanceof OfflineUser) {
334
+            $user->unmark();
335
+        }
336
+
337
+        $this->access->connection->writeToCache($cacheKey, true);
338
+        return true;
339
+    }
340
+
341
+    /**
342
+     * check if a user exists
343
+     * @param string $uid the username
344
+     * @return boolean
345
+     * @throws \Exception when connection could not be established
346
+     */
347
+    public function userExists($uid) {
348
+        $userExists = $this->access->connection->getFromCache('userExists'.$uid);
349
+        if (!is_null($userExists)) {
350
+            return (bool)$userExists;
351
+        }
352
+        //getting dn, if false the user does not exist. If dn, he may be mapped only, requires more checking.
353
+        $user = $this->access->userManager->get($uid);
354
+
355
+        if (is_null($user)) {
356
+            Util::writeLog('user_ldap', 'No DN found for '.$uid.' on '.
357
+                $this->access->connection->ldapHost, ILogger::DEBUG);
358
+            $this->access->connection->writeToCache('userExists'.$uid, false);
359
+            return false;
360
+        }
361
+
362
+        $this->access->connection->writeToCache('userExists'.$uid, true);
363
+        return true;
364
+    }
365
+
366
+    /**
367
+     * returns whether a user was deleted in LDAP
368
+     *
369
+     * @param string $uid The username of the user to delete
370
+     * @return bool
371
+     */
372
+    public function deleteUser($uid) {
373
+        if ($this->userPluginManager->canDeleteUser()) {
374
+            $status = $this->userPluginManager->deleteUser($uid);
375
+            if ($status === false) {
376
+                return false;
377
+            }
378
+        }
379
+
380
+        $marked = $this->ocConfig->getUserValue($uid, 'user_ldap', 'isDeleted', 0);
381
+        if ((int)$marked === 0) {
382
+            \OC::$server->getLogger()->notice(
383
+                'User '.$uid . ' is not marked as deleted, not cleaning up.',
384
+                ['app' => 'user_ldap']);
385
+            return false;
386
+        }
387
+        \OC::$server->getLogger()->info('Cleaning up after user ' . $uid,
388
+            ['app' => 'user_ldap']);
389
+
390
+        $this->access->getUserMapper()->unmap($uid); // we don't emit unassign signals here, since it is implicit to delete signals fired from core
391
+        $this->access->userManager->invalidate($uid);
392
+        $this->access->connection->clearCache();
393
+        return true;
394
+    }
395
+
396
+    /**
397
+     * get the user's home directory
398
+     *
399
+     * @param string $uid the username
400
+     * @return bool|string
401
+     * @throws NoUserException
402
+     * @throws \Exception
403
+     */
404
+    public function getHome($uid) {
405
+        // user Exists check required as it is not done in user proxy!
406
+        if (!$this->userExists($uid)) {
407
+            return false;
408
+        }
409
+
410
+        if ($this->userPluginManager->implementsActions(Backend::GET_HOME)) {
411
+            return $this->userPluginManager->getHome($uid);
412
+        }
413
+
414
+        $cacheKey = 'getHome'.$uid;
415
+        $path = $this->access->connection->getFromCache($cacheKey);
416
+        if (!is_null($path)) {
417
+            return $path;
418
+        }
419
+
420
+        // early return path if it is a deleted user
421
+        $user = $this->access->userManager->get($uid);
422
+        if ($user instanceof User || $user instanceof OfflineUser) {
423
+            $path = $user->getHomePath() ?: false;
424
+        } else {
425
+            throw new NoUserException($uid . ' is not a valid user anymore');
426
+        }
427
+
428
+        $this->access->cacheUserHome($uid, $path);
429
+        return $path;
430
+    }
431
+
432
+    /**
433
+     * get display name of the user
434
+     * @param string $uid user ID of the user
435
+     * @return string|false display name
436
+     */
437
+    public function getDisplayName($uid) {
438
+        if ($this->userPluginManager->implementsActions(Backend::GET_DISPLAYNAME)) {
439
+            return $this->userPluginManager->getDisplayName($uid);
440
+        }
441
+
442
+        if (!$this->userExists($uid)) {
443
+            return false;
444
+        }
445
+
446
+        $cacheKey = 'getDisplayName'.$uid;
447
+        if (!is_null($displayName = $this->access->connection->getFromCache($cacheKey))) {
448
+            return $displayName;
449
+        }
450
+
451
+        //Check whether the display name is configured to have a 2nd feature
452
+        $additionalAttribute = $this->access->connection->ldapUserDisplayName2;
453
+        $displayName2 = '';
454
+        if ($additionalAttribute !== '') {
455
+            $displayName2 = $this->access->readAttribute(
456
+                $this->access->username2dn($uid),
457
+                $additionalAttribute);
458
+        }
459
+
460
+        $displayName = $this->access->readAttribute(
461
+            $this->access->username2dn($uid),
462
+            $this->access->connection->ldapUserDisplayName);
463
+
464
+        if ($displayName && (count($displayName) > 0)) {
465
+            $displayName = $displayName[0];
466
+
467
+            if (is_array($displayName2)) {
468
+                $displayName2 = count($displayName2) > 0 ? $displayName2[0] : '';
469
+            }
470
+
471
+            $user = $this->access->userManager->get($uid);
472
+            if ($user instanceof User) {
473
+                $displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
474
+                $this->access->connection->writeToCache($cacheKey, $displayName);
475
+            }
476
+            if ($user instanceof OfflineUser) {
477
+                /** @var OfflineUser $user*/
478
+                $displayName = $user->getDisplayName();
479
+            }
480
+            return $displayName;
481
+        }
482
+
483
+        return null;
484
+    }
485
+
486
+    /**
487
+     * set display name of the user
488
+     * @param string $uid user ID of the user
489
+     * @param string $displayName new display name of the user
490
+     * @return string|false display name
491
+     */
492
+    public function setDisplayName($uid, $displayName) {
493
+        if ($this->userPluginManager->implementsActions(Backend::SET_DISPLAYNAME)) {
494
+            $this->userPluginManager->setDisplayName($uid, $displayName);
495
+            $this->access->cacheUserDisplayName($uid, $displayName);
496
+            return $displayName;
497
+        }
498
+        return false;
499
+    }
500
+
501
+    /**
502
+     * Get a list of all display names
503
+     *
504
+     * @param string $search
505
+     * @param string|null $limit
506
+     * @param string|null $offset
507
+     * @return array an array of all displayNames (value) and the corresponding uids (key)
508
+     */
509
+    public function getDisplayNames($search = '', $limit = null, $offset = null) {
510
+        $cacheKey = 'getDisplayNames-'.$search.'-'.$limit.'-'.$offset;
511
+        if (!is_null($displayNames = $this->access->connection->getFromCache($cacheKey))) {
512
+            return $displayNames;
513
+        }
514
+
515
+        $displayNames = [];
516
+        $users = $this->getUsers($search, $limit, $offset);
517
+        foreach ($users as $user) {
518
+            $displayNames[$user] = $this->getDisplayName($user);
519
+        }
520
+        $this->access->connection->writeToCache($cacheKey, $displayNames);
521
+        return $displayNames;
522
+    }
523
+
524
+    /**
525
+     * Check if backend implements actions
526
+     * @param int $actions bitwise-or'ed actions
527
+     * @return boolean
528
+     *
529
+     * Returns the supported actions as int to be
530
+     * compared with \OC\User\Backend::CREATE_USER etc.
531
+     */
532
+    public function implementsActions($actions) {
533
+        return (bool)((Backend::CHECK_PASSWORD
534
+            | Backend::GET_HOME
535
+            | Backend::GET_DISPLAYNAME
536
+            | (($this->access->connection->ldapUserAvatarRule !== 'none') ? Backend::PROVIDE_AVATAR : 0)
537
+            | Backend::COUNT_USERS
538
+            | (((int)$this->access->connection->turnOnPasswordChange === 1)? Backend::SET_PASSWORD :0)
539
+            | $this->userPluginManager->getImplementedActions())
540
+            & $actions);
541
+    }
542
+
543
+    /**
544
+     * @return bool
545
+     */
546
+    public function hasUserListings() {
547
+        return true;
548
+    }
549
+
550
+    /**
551
+     * counts the users in LDAP
552
+     *
553
+     * @return int|bool
554
+     */
555
+    public function countUsers() {
556
+        if ($this->userPluginManager->implementsActions(Backend::COUNT_USERS)) {
557
+            return $this->userPluginManager->countUsers();
558
+        }
559
+
560
+        $filter = $this->access->getFilterForUserCount();
561
+        $cacheKey = 'countUsers-'.$filter;
562
+        if (!is_null($entries = $this->access->connection->getFromCache($cacheKey))) {
563
+            return $entries;
564
+        }
565
+        $entries = $this->access->countUsers($filter);
566
+        $this->access->connection->writeToCache($cacheKey, $entries);
567
+        return $entries;
568
+    }
569
+
570
+    /**
571
+     * Backend name to be shown in user management
572
+     * @return string the name of the backend to be shown
573
+     */
574
+    public function getBackendName() {
575
+        return 'LDAP';
576
+    }
577 577
 	
578
-	/**
579
-	 * Return access for LDAP interaction.
580
-	 * @param string $uid
581
-	 * @return Access instance of Access for LDAP interaction
582
-	 */
583
-	public function getLDAPAccess($uid) {
584
-		return $this->access;
585
-	}
578
+    /**
579
+     * Return access for LDAP interaction.
580
+     * @param string $uid
581
+     * @return Access instance of Access for LDAP interaction
582
+     */
583
+    public function getLDAPAccess($uid) {
584
+        return $this->access;
585
+    }
586 586
 	
587
-	/**
588
-	 * Return LDAP connection resource from a cloned connection.
589
-	 * The cloned connection needs to be closed manually.
590
-	 * of the current access.
591
-	 * @param string $uid
592
-	 * @return resource of the LDAP connection
593
-	 */
594
-	public function getNewLDAPConnection($uid) {
595
-		$connection = clone $this->access->getConnection();
596
-		return $connection->getConnectionResource();
597
-	}
598
-
599
-	/**
600
-	 * create new user
601
-	 * @param string $username username of the new user
602
-	 * @param string $password password of the new user
603
-	 * @throws \UnexpectedValueException
604
-	 * @return bool
605
-	 */
606
-	public function createUser($username, $password) {
607
-		if ($this->userPluginManager->implementsActions(Backend::CREATE_USER)) {
608
-			if ($dn = $this->userPluginManager->createUser($username, $password)) {
609
-				if (is_string($dn)) {
610
-					// the NC user creation work flow requires a know user id up front
611
-					$uuid = $this->access->getUUID($dn, true);
612
-					if (is_string($uuid)) {
613
-						$this->access->mapAndAnnounceIfApplicable(
614
-							$this->access->getUserMapper(),
615
-							$dn,
616
-							$username,
617
-							$uuid,
618
-							true
619
-						);
620
-						$this->access->cacheUserExists($username);
621
-					} else {
622
-						\OC::$server->getLogger()->warning(
623
-							'Failed to map created LDAP user with userid {userid}, because UUID could not be determined',
624
-							[
625
-								'app' => 'user_ldap',
626
-								'userid' => $username,
627
-							]
628
-						);
629
-					}
630
-				} else {
631
-					throw new \UnexpectedValueException("LDAP Plugin: Method createUser changed to return the user DN instead of boolean.");
632
-				}
633
-			}
634
-			return (bool) $dn;
635
-		}
636
-		return false;
637
-	}
587
+    /**
588
+     * Return LDAP connection resource from a cloned connection.
589
+     * The cloned connection needs to be closed manually.
590
+     * of the current access.
591
+     * @param string $uid
592
+     * @return resource of the LDAP connection
593
+     */
594
+    public function getNewLDAPConnection($uid) {
595
+        $connection = clone $this->access->getConnection();
596
+        return $connection->getConnectionResource();
597
+    }
598
+
599
+    /**
600
+     * create new user
601
+     * @param string $username username of the new user
602
+     * @param string $password password of the new user
603
+     * @throws \UnexpectedValueException
604
+     * @return bool
605
+     */
606
+    public function createUser($username, $password) {
607
+        if ($this->userPluginManager->implementsActions(Backend::CREATE_USER)) {
608
+            if ($dn = $this->userPluginManager->createUser($username, $password)) {
609
+                if (is_string($dn)) {
610
+                    // the NC user creation work flow requires a know user id up front
611
+                    $uuid = $this->access->getUUID($dn, true);
612
+                    if (is_string($uuid)) {
613
+                        $this->access->mapAndAnnounceIfApplicable(
614
+                            $this->access->getUserMapper(),
615
+                            $dn,
616
+                            $username,
617
+                            $uuid,
618
+                            true
619
+                        );
620
+                        $this->access->cacheUserExists($username);
621
+                    } else {
622
+                        \OC::$server->getLogger()->warning(
623
+                            'Failed to map created LDAP user with userid {userid}, because UUID could not be determined',
624
+                            [
625
+                                'app' => 'user_ldap',
626
+                                'userid' => $username,
627
+                            ]
628
+                        );
629
+                    }
630
+                } else {
631
+                    throw new \UnexpectedValueException("LDAP Plugin: Method createUser changed to return the user DN instead of boolean.");
632
+                }
633
+            }
634
+            return (bool) $dn;
635
+        }
636
+        return false;
637
+    }
638 638
 }
Please login to merge, or discard this patch.