Completed
Push — master ( 63676d...3faef6 )
by Lukas
28:10 queued 12:28
created
lib/private/legacy/user.php 2 patches
Indentation   +444 added lines, -444 removed lines patch added patch discarded remove patch
@@ -57,448 +57,448 @@
 block discarded – undo
57 57
  */
58 58
 class OC_User {
59 59
 
60
-	/**
61
-	 * @return \OC\User\Session
62
-	 */
63
-	public static function getUserSession() {
64
-		return OC::$server->getUserSession();
65
-	}
66
-
67
-	private static $_usedBackends = array();
68
-
69
-	private static $_setupedBackends = array();
70
-
71
-	// bool, stores if a user want to access a resource anonymously, e.g if they open a public link
72
-	private static $incognitoMode = false;
73
-
74
-	/**
75
-	 * Adds the backend to the list of used backends
76
-	 *
77
-	 * @param string|\OCP\UserInterface $backend default: database The backend to use for user management
78
-	 * @return bool
79
-	 *
80
-	 * Set the User Authentication Module
81
-	 */
82
-	public static function useBackend($backend = 'database') {
83
-		if ($backend instanceof \OCP\UserInterface) {
84
-			self::$_usedBackends[get_class($backend)] = $backend;
85
-			\OC::$server->getUserManager()->registerBackend($backend);
86
-		} else {
87
-			// You'll never know what happens
88
-			if (null === $backend OR !is_string($backend)) {
89
-				$backend = 'database';
90
-			}
91
-
92
-			// Load backend
93
-			switch ($backend) {
94
-				case 'database':
95
-				case 'mysql':
96
-				case 'sqlite':
97
-					\OCP\Util::writeLog('core', 'Adding user backend ' . $backend . '.', \OCP\Util::DEBUG);
98
-					self::$_usedBackends[$backend] = new \OC\User\Database();
99
-					\OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
100
-					break;
101
-				case 'dummy':
102
-					self::$_usedBackends[$backend] = new \Test\Util\User\Dummy();
103
-					\OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
104
-					break;
105
-				default:
106
-					\OCP\Util::writeLog('core', 'Adding default user backend ' . $backend . '.', \OCP\Util::DEBUG);
107
-					$className = 'OC_USER_' . strtoupper($backend);
108
-					self::$_usedBackends[$backend] = new $className();
109
-					\OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
110
-					break;
111
-			}
112
-		}
113
-		return true;
114
-	}
115
-
116
-	/**
117
-	 * remove all used backends
118
-	 */
119
-	public static function clearBackends() {
120
-		self::$_usedBackends = array();
121
-		\OC::$server->getUserManager()->clearBackends();
122
-	}
123
-
124
-	/**
125
-	 * setup the configured backends in config.php
126
-	 */
127
-	public static function setupBackends() {
128
-		OC_App::loadApps(['prelogin']);
129
-		$backends = \OC::$server->getSystemConfig()->getValue('user_backends', []);
130
-		if (isset($backends['default']) && !$backends['default']) {
131
-			// clear default backends
132
-			self::clearBackends();
133
-		}
134
-		foreach ($backends as $i => $config) {
135
-			if (!is_array($config)) {
136
-				continue;
137
-			}
138
-			$class = $config['class'];
139
-			$arguments = $config['arguments'];
140
-			if (class_exists($class)) {
141
-				if (array_search($i, self::$_setupedBackends) === false) {
142
-					// make a reflection object
143
-					$reflectionObj = new ReflectionClass($class);
144
-
145
-					// use Reflection to create a new instance, using the $args
146
-					$backend = $reflectionObj->newInstanceArgs($arguments);
147
-					self::useBackend($backend);
148
-					self::$_setupedBackends[] = $i;
149
-				} else {
150
-					\OCP\Util::writeLog('core', 'User backend ' . $class . ' already initialized.', \OCP\Util::DEBUG);
151
-				}
152
-			} else {
153
-				\OCP\Util::writeLog('core', 'User backend ' . $class . ' not found.', \OCP\Util::ERROR);
154
-			}
155
-		}
156
-	}
157
-
158
-	/**
159
-	 * Try to login a user, assuming authentication
160
-	 * has already happened (e.g. via Single Sign On).
161
-	 *
162
-	 * Log in a user and regenerate a new session.
163
-	 *
164
-	 * @param \OCP\Authentication\IApacheBackend $backend
165
-	 * @return bool
166
-	 */
167
-	public static function loginWithApache(\OCP\Authentication\IApacheBackend $backend) {
168
-
169
-		$uid = $backend->getCurrentUserId();
170
-		$run = true;
171
-		OC_Hook::emit("OC_User", "pre_login", array("run" => &$run, "uid" => $uid));
172
-
173
-		if ($uid) {
174
-			if (self::getUser() !== $uid) {
175
-				self::setUserId($uid);
176
-				$setUidAsDisplayName = true;
177
-				if($backend instanceof \OCP\UserInterface
178
-					&& $backend->implementsActions(\OC\User\Backend::GET_DISPLAYNAME)) {
179
-
180
-					$backendDisplayName = $backend->getDisplayName($uid);
181
-					if(is_string($backendDisplayName) && trim($backendDisplayName) !== '') {
182
-						$setUidAsDisplayName = false;
183
-					}
184
-				}
185
-				if($setUidAsDisplayName) {
186
-					self::setDisplayName($uid);
187
-				}
188
-				$userSession = self::getUserSession();
189
-				$userSession->setLoginName($uid);
190
-				$request = OC::$server->getRequest();
191
-				$userSession->createSessionToken($request, $uid, $uid);
192
-				// setup the filesystem
193
-				OC_Util::setupFS($uid);
194
-				// first call the post_login hooks, the login-process needs to be
195
-				// completed before we can safely create the users folder.
196
-				// For example encryption needs to initialize the users keys first
197
-				// before we can create the user folder with the skeleton files
198
-				OC_Hook::emit("OC_User", "post_login", array("uid" => $uid, 'password' => ''));
199
-				//trigger creation of user home and /files folder
200
-				\OC::$server->getUserFolder($uid);
201
-			}
202
-			return true;
203
-		}
204
-		return false;
205
-	}
206
-
207
-	/**
208
-	 * Verify with Apache whether user is authenticated.
209
-	 *
210
-	 * @return boolean|null
211
-	 *          true: authenticated
212
-	 *          false: not authenticated
213
-	 *          null: not handled / no backend available
214
-	 */
215
-	public static function handleApacheAuth() {
216
-		$backend = self::findFirstActiveUsedBackend();
217
-		if ($backend) {
218
-			OC_App::loadApps();
219
-
220
-			//setup extra user backends
221
-			self::setupBackends();
222
-			self::getUserSession()->unsetMagicInCookie();
223
-
224
-			return self::loginWithApache($backend);
225
-		}
226
-
227
-		return null;
228
-	}
229
-
230
-
231
-	/**
232
-	 * Sets user id for session and triggers emit
233
-	 *
234
-	 * @param string $uid
235
-	 */
236
-	public static function setUserId($uid) {
237
-		$userSession = \OC::$server->getUserSession();
238
-		$userManager = \OC::$server->getUserManager();
239
-		if ($user = $userManager->get($uid)) {
240
-			$userSession->setUser($user);
241
-		} else {
242
-			\OC::$server->getSession()->set('user_id', $uid);
243
-		}
244
-	}
245
-
246
-	/**
247
-	 * Sets user display name for session
248
-	 *
249
-	 * @param string $uid
250
-	 * @param string $displayName
251
-	 * @return bool Whether the display name could get set
252
-	 */
253
-	public static function setDisplayName($uid, $displayName = null) {
254
-		if (is_null($displayName)) {
255
-			$displayName = $uid;
256
-		}
257
-		$user = \OC::$server->getUserManager()->get($uid);
258
-		if ($user) {
259
-			return $user->setDisplayName($displayName);
260
-		} else {
261
-			return false;
262
-		}
263
-	}
264
-
265
-	/**
266
-	 * Check if the user is logged in, considers also the HTTP basic credentials
267
-	 *
268
-	 * @deprecated use \OC::$server->getUserSession()->isLoggedIn()
269
-	 * @return bool
270
-	 */
271
-	public static function isLoggedIn() {
272
-		return \OC::$server->getUserSession()->isLoggedIn();
273
-	}
274
-
275
-	/**
276
-	 * set incognito mode, e.g. if a user wants to open a public link
277
-	 *
278
-	 * @param bool $status
279
-	 */
280
-	public static function setIncognitoMode($status) {
281
-		self::$incognitoMode = $status;
282
-	}
283
-
284
-	/**
285
-	 * get incognito mode status
286
-	 *
287
-	 * @return bool
288
-	 */
289
-	public static function isIncognitoMode() {
290
-		return self::$incognitoMode;
291
-	}
292
-
293
-	/**
294
-	 * Supplies an attribute to the logout hyperlink. The default behaviour
295
-	 * is to return an href with '?logout=true' appended. However, it can
296
-	 * supply any attribute(s) which are valid for <a>.
297
-	 *
298
-	 * @return string with one or more HTML attributes.
299
-	 */
300
-	public static function getLogoutAttribute() {
301
-		$backend = self::findFirstActiveUsedBackend();
302
-		if ($backend) {
303
-			return $backend->getLogoutAttribute();
304
-		}
305
-
306
-		$logoutUrl = \OC::$server->getURLGenerator()->linkToRouteAbsolute(
307
-			'core.login.logout',
308
-			[
309
-				'requesttoken' => \OCP\Util::callRegister(),
310
-			]
311
-		);
312
-
313
-		return 'href="'.$logoutUrl.'"';
314
-	}
315
-
316
-	/**
317
-	 * Check if the user is an admin user
318
-	 *
319
-	 * @param string $uid uid of the admin
320
-	 * @return bool
321
-	 */
322
-	public static function isAdminUser($uid) {
323
-		$group = \OC::$server->getGroupManager()->get('admin');
324
-		$user = \OC::$server->getUserManager()->get($uid);
325
-		if ($group && $user && $group->inGroup($user) && self::$incognitoMode === false) {
326
-			return true;
327
-		}
328
-		return false;
329
-	}
330
-
331
-
332
-	/**
333
-	 * get the user id of the user currently logged in.
334
-	 *
335
-	 * @return string|bool uid or false
336
-	 */
337
-	public static function getUser() {
338
-		$uid = \OC::$server->getSession() ? \OC::$server->getSession()->get('user_id') : null;
339
-		if (!is_null($uid) && self::$incognitoMode === false) {
340
-			return $uid;
341
-		} else {
342
-			return false;
343
-		}
344
-	}
345
-
346
-	/**
347
-	 * get the display name of the user currently logged in.
348
-	 *
349
-	 * @param string $uid
350
-	 * @return string uid or false
351
-	 */
352
-	public static function getDisplayName($uid = null) {
353
-		if ($uid) {
354
-			$user = \OC::$server->getUserManager()->get($uid);
355
-			if ($user) {
356
-				return $user->getDisplayName();
357
-			} else {
358
-				return $uid;
359
-			}
360
-		} else {
361
-			$user = self::getUserSession()->getUser();
362
-			if ($user) {
363
-				return $user->getDisplayName();
364
-			} else {
365
-				return false;
366
-			}
367
-		}
368
-	}
369
-
370
-	/**
371
-	 * Set password
372
-	 *
373
-	 * @param string $uid The username
374
-	 * @param string $password The new password
375
-	 * @param string $recoveryPassword for the encryption app to reset encryption keys
376
-	 * @return bool
377
-	 *
378
-	 * Change the password of a user
379
-	 */
380
-	public static function setPassword($uid, $password, $recoveryPassword = null) {
381
-		$user = \OC::$server->getUserManager()->get($uid);
382
-		if ($user) {
383
-			return $user->setPassword($password, $recoveryPassword);
384
-		} else {
385
-			return false;
386
-		}
387
-	}
388
-
389
-	/**
390
-	 * Check if the password is correct
391
-	 *
392
-	 * @param string $uid The username
393
-	 * @param string $password The password
394
-	 * @return string|false user id a string on success, false otherwise
395
-	 *
396
-	 * Check if the password is correct without logging in the user
397
-	 * returns the user id or false
398
-	 */
399
-	public static function checkPassword($uid, $password) {
400
-		$manager = \OC::$server->getUserManager();
401
-		$username = $manager->checkPassword($uid, $password);
402
-		if ($username !== false) {
403
-			return $username->getUID();
404
-		}
405
-		return false;
406
-	}
407
-
408
-	/**
409
-	 * @param string $uid The username
410
-	 * @return string
411
-	 *
412
-	 * returns the path to the users home directory
413
-	 * @deprecated Use \OC::$server->getUserManager->getHome()
414
-	 */
415
-	public static function getHome($uid) {
416
-		$user = \OC::$server->getUserManager()->get($uid);
417
-		if ($user) {
418
-			return $user->getHome();
419
-		} else {
420
-			return \OC::$server->getSystemConfig()->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $uid;
421
-		}
422
-	}
423
-
424
-	/**
425
-	 * Get a list of all users
426
-	 *
427
-	 * @return array an array of all uids
428
-	 *
429
-	 * Get a list of all users.
430
-	 * @param string $search
431
-	 * @param integer $limit
432
-	 * @param integer $offset
433
-	 */
434
-	public static function getUsers($search = '', $limit = null, $offset = null) {
435
-		$users = \OC::$server->getUserManager()->search($search, $limit, $offset);
436
-		$uids = array();
437
-		foreach ($users as $user) {
438
-			$uids[] = $user->getUID();
439
-		}
440
-		return $uids;
441
-	}
442
-
443
-	/**
444
-	 * Get a list of all users display name
445
-	 *
446
-	 * @param string $search
447
-	 * @param int $limit
448
-	 * @param int $offset
449
-	 * @return array associative array with all display names (value) and corresponding uids (key)
450
-	 *
451
-	 * Get a list of all display names and user ids.
452
-	 * @deprecated Use \OC::$server->getUserManager->searchDisplayName($search, $limit, $offset) instead.
453
-	 */
454
-	public static function getDisplayNames($search = '', $limit = null, $offset = null) {
455
-		$displayNames = array();
456
-		$users = \OC::$server->getUserManager()->searchDisplayName($search, $limit, $offset);
457
-		foreach ($users as $user) {
458
-			$displayNames[$user->getUID()] = $user->getDisplayName();
459
-		}
460
-		return $displayNames;
461
-	}
462
-
463
-	/**
464
-	 * check if a user exists
465
-	 *
466
-	 * @param string $uid the username
467
-	 * @return boolean
468
-	 */
469
-	public static function userExists($uid) {
470
-		return \OC::$server->getUserManager()->userExists($uid);
471
-	}
472
-
473
-	/**
474
-	 * checks if a user is enabled
475
-	 *
476
-	 * @param string $uid
477
-	 * @return bool
478
-	 */
479
-	public static function isEnabled($uid) {
480
-		$user = \OC::$server->getUserManager()->get($uid);
481
-		if ($user) {
482
-			return $user->isEnabled();
483
-		} else {
484
-			return false;
485
-		}
486
-	}
487
-
488
-	/**
489
-	 * Returns the first active backend from self::$_usedBackends.
490
-	 *
491
-	 * @return OCP\Authentication\IApacheBackend|null if no backend active, otherwise OCP\Authentication\IApacheBackend
492
-	 */
493
-	private static function findFirstActiveUsedBackend() {
494
-		foreach (self::$_usedBackends as $backend) {
495
-			if ($backend instanceof OCP\Authentication\IApacheBackend) {
496
-				if ($backend->isSessionActive()) {
497
-					return $backend;
498
-				}
499
-			}
500
-		}
501
-
502
-		return null;
503
-	}
60
+    /**
61
+     * @return \OC\User\Session
62
+     */
63
+    public static function getUserSession() {
64
+        return OC::$server->getUserSession();
65
+    }
66
+
67
+    private static $_usedBackends = array();
68
+
69
+    private static $_setupedBackends = array();
70
+
71
+    // bool, stores if a user want to access a resource anonymously, e.g if they open a public link
72
+    private static $incognitoMode = false;
73
+
74
+    /**
75
+     * Adds the backend to the list of used backends
76
+     *
77
+     * @param string|\OCP\UserInterface $backend default: database The backend to use for user management
78
+     * @return bool
79
+     *
80
+     * Set the User Authentication Module
81
+     */
82
+    public static function useBackend($backend = 'database') {
83
+        if ($backend instanceof \OCP\UserInterface) {
84
+            self::$_usedBackends[get_class($backend)] = $backend;
85
+            \OC::$server->getUserManager()->registerBackend($backend);
86
+        } else {
87
+            // You'll never know what happens
88
+            if (null === $backend OR !is_string($backend)) {
89
+                $backend = 'database';
90
+            }
91
+
92
+            // Load backend
93
+            switch ($backend) {
94
+                case 'database':
95
+                case 'mysql':
96
+                case 'sqlite':
97
+                    \OCP\Util::writeLog('core', 'Adding user backend ' . $backend . '.', \OCP\Util::DEBUG);
98
+                    self::$_usedBackends[$backend] = new \OC\User\Database();
99
+                    \OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
100
+                    break;
101
+                case 'dummy':
102
+                    self::$_usedBackends[$backend] = new \Test\Util\User\Dummy();
103
+                    \OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
104
+                    break;
105
+                default:
106
+                    \OCP\Util::writeLog('core', 'Adding default user backend ' . $backend . '.', \OCP\Util::DEBUG);
107
+                    $className = 'OC_USER_' . strtoupper($backend);
108
+                    self::$_usedBackends[$backend] = new $className();
109
+                    \OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
110
+                    break;
111
+            }
112
+        }
113
+        return true;
114
+    }
115
+
116
+    /**
117
+     * remove all used backends
118
+     */
119
+    public static function clearBackends() {
120
+        self::$_usedBackends = array();
121
+        \OC::$server->getUserManager()->clearBackends();
122
+    }
123
+
124
+    /**
125
+     * setup the configured backends in config.php
126
+     */
127
+    public static function setupBackends() {
128
+        OC_App::loadApps(['prelogin']);
129
+        $backends = \OC::$server->getSystemConfig()->getValue('user_backends', []);
130
+        if (isset($backends['default']) && !$backends['default']) {
131
+            // clear default backends
132
+            self::clearBackends();
133
+        }
134
+        foreach ($backends as $i => $config) {
135
+            if (!is_array($config)) {
136
+                continue;
137
+            }
138
+            $class = $config['class'];
139
+            $arguments = $config['arguments'];
140
+            if (class_exists($class)) {
141
+                if (array_search($i, self::$_setupedBackends) === false) {
142
+                    // make a reflection object
143
+                    $reflectionObj = new ReflectionClass($class);
144
+
145
+                    // use Reflection to create a new instance, using the $args
146
+                    $backend = $reflectionObj->newInstanceArgs($arguments);
147
+                    self::useBackend($backend);
148
+                    self::$_setupedBackends[] = $i;
149
+                } else {
150
+                    \OCP\Util::writeLog('core', 'User backend ' . $class . ' already initialized.', \OCP\Util::DEBUG);
151
+                }
152
+            } else {
153
+                \OCP\Util::writeLog('core', 'User backend ' . $class . ' not found.', \OCP\Util::ERROR);
154
+            }
155
+        }
156
+    }
157
+
158
+    /**
159
+     * Try to login a user, assuming authentication
160
+     * has already happened (e.g. via Single Sign On).
161
+     *
162
+     * Log in a user and regenerate a new session.
163
+     *
164
+     * @param \OCP\Authentication\IApacheBackend $backend
165
+     * @return bool
166
+     */
167
+    public static function loginWithApache(\OCP\Authentication\IApacheBackend $backend) {
168
+
169
+        $uid = $backend->getCurrentUserId();
170
+        $run = true;
171
+        OC_Hook::emit("OC_User", "pre_login", array("run" => &$run, "uid" => $uid));
172
+
173
+        if ($uid) {
174
+            if (self::getUser() !== $uid) {
175
+                self::setUserId($uid);
176
+                $setUidAsDisplayName = true;
177
+                if($backend instanceof \OCP\UserInterface
178
+                    && $backend->implementsActions(\OC\User\Backend::GET_DISPLAYNAME)) {
179
+
180
+                    $backendDisplayName = $backend->getDisplayName($uid);
181
+                    if(is_string($backendDisplayName) && trim($backendDisplayName) !== '') {
182
+                        $setUidAsDisplayName = false;
183
+                    }
184
+                }
185
+                if($setUidAsDisplayName) {
186
+                    self::setDisplayName($uid);
187
+                }
188
+                $userSession = self::getUserSession();
189
+                $userSession->setLoginName($uid);
190
+                $request = OC::$server->getRequest();
191
+                $userSession->createSessionToken($request, $uid, $uid);
192
+                // setup the filesystem
193
+                OC_Util::setupFS($uid);
194
+                // first call the post_login hooks, the login-process needs to be
195
+                // completed before we can safely create the users folder.
196
+                // For example encryption needs to initialize the users keys first
197
+                // before we can create the user folder with the skeleton files
198
+                OC_Hook::emit("OC_User", "post_login", array("uid" => $uid, 'password' => ''));
199
+                //trigger creation of user home and /files folder
200
+                \OC::$server->getUserFolder($uid);
201
+            }
202
+            return true;
203
+        }
204
+        return false;
205
+    }
206
+
207
+    /**
208
+     * Verify with Apache whether user is authenticated.
209
+     *
210
+     * @return boolean|null
211
+     *          true: authenticated
212
+     *          false: not authenticated
213
+     *          null: not handled / no backend available
214
+     */
215
+    public static function handleApacheAuth() {
216
+        $backend = self::findFirstActiveUsedBackend();
217
+        if ($backend) {
218
+            OC_App::loadApps();
219
+
220
+            //setup extra user backends
221
+            self::setupBackends();
222
+            self::getUserSession()->unsetMagicInCookie();
223
+
224
+            return self::loginWithApache($backend);
225
+        }
226
+
227
+        return null;
228
+    }
229
+
230
+
231
+    /**
232
+     * Sets user id for session and triggers emit
233
+     *
234
+     * @param string $uid
235
+     */
236
+    public static function setUserId($uid) {
237
+        $userSession = \OC::$server->getUserSession();
238
+        $userManager = \OC::$server->getUserManager();
239
+        if ($user = $userManager->get($uid)) {
240
+            $userSession->setUser($user);
241
+        } else {
242
+            \OC::$server->getSession()->set('user_id', $uid);
243
+        }
244
+    }
245
+
246
+    /**
247
+     * Sets user display name for session
248
+     *
249
+     * @param string $uid
250
+     * @param string $displayName
251
+     * @return bool Whether the display name could get set
252
+     */
253
+    public static function setDisplayName($uid, $displayName = null) {
254
+        if (is_null($displayName)) {
255
+            $displayName = $uid;
256
+        }
257
+        $user = \OC::$server->getUserManager()->get($uid);
258
+        if ($user) {
259
+            return $user->setDisplayName($displayName);
260
+        } else {
261
+            return false;
262
+        }
263
+    }
264
+
265
+    /**
266
+     * Check if the user is logged in, considers also the HTTP basic credentials
267
+     *
268
+     * @deprecated use \OC::$server->getUserSession()->isLoggedIn()
269
+     * @return bool
270
+     */
271
+    public static function isLoggedIn() {
272
+        return \OC::$server->getUserSession()->isLoggedIn();
273
+    }
274
+
275
+    /**
276
+     * set incognito mode, e.g. if a user wants to open a public link
277
+     *
278
+     * @param bool $status
279
+     */
280
+    public static function setIncognitoMode($status) {
281
+        self::$incognitoMode = $status;
282
+    }
283
+
284
+    /**
285
+     * get incognito mode status
286
+     *
287
+     * @return bool
288
+     */
289
+    public static function isIncognitoMode() {
290
+        return self::$incognitoMode;
291
+    }
292
+
293
+    /**
294
+     * Supplies an attribute to the logout hyperlink. The default behaviour
295
+     * is to return an href with '?logout=true' appended. However, it can
296
+     * supply any attribute(s) which are valid for <a>.
297
+     *
298
+     * @return string with one or more HTML attributes.
299
+     */
300
+    public static function getLogoutAttribute() {
301
+        $backend = self::findFirstActiveUsedBackend();
302
+        if ($backend) {
303
+            return $backend->getLogoutAttribute();
304
+        }
305
+
306
+        $logoutUrl = \OC::$server->getURLGenerator()->linkToRouteAbsolute(
307
+            'core.login.logout',
308
+            [
309
+                'requesttoken' => \OCP\Util::callRegister(),
310
+            ]
311
+        );
312
+
313
+        return 'href="'.$logoutUrl.'"';
314
+    }
315
+
316
+    /**
317
+     * Check if the user is an admin user
318
+     *
319
+     * @param string $uid uid of the admin
320
+     * @return bool
321
+     */
322
+    public static function isAdminUser($uid) {
323
+        $group = \OC::$server->getGroupManager()->get('admin');
324
+        $user = \OC::$server->getUserManager()->get($uid);
325
+        if ($group && $user && $group->inGroup($user) && self::$incognitoMode === false) {
326
+            return true;
327
+        }
328
+        return false;
329
+    }
330
+
331
+
332
+    /**
333
+     * get the user id of the user currently logged in.
334
+     *
335
+     * @return string|bool uid or false
336
+     */
337
+    public static function getUser() {
338
+        $uid = \OC::$server->getSession() ? \OC::$server->getSession()->get('user_id') : null;
339
+        if (!is_null($uid) && self::$incognitoMode === false) {
340
+            return $uid;
341
+        } else {
342
+            return false;
343
+        }
344
+    }
345
+
346
+    /**
347
+     * get the display name of the user currently logged in.
348
+     *
349
+     * @param string $uid
350
+     * @return string uid or false
351
+     */
352
+    public static function getDisplayName($uid = null) {
353
+        if ($uid) {
354
+            $user = \OC::$server->getUserManager()->get($uid);
355
+            if ($user) {
356
+                return $user->getDisplayName();
357
+            } else {
358
+                return $uid;
359
+            }
360
+        } else {
361
+            $user = self::getUserSession()->getUser();
362
+            if ($user) {
363
+                return $user->getDisplayName();
364
+            } else {
365
+                return false;
366
+            }
367
+        }
368
+    }
369
+
370
+    /**
371
+     * Set password
372
+     *
373
+     * @param string $uid The username
374
+     * @param string $password The new password
375
+     * @param string $recoveryPassword for the encryption app to reset encryption keys
376
+     * @return bool
377
+     *
378
+     * Change the password of a user
379
+     */
380
+    public static function setPassword($uid, $password, $recoveryPassword = null) {
381
+        $user = \OC::$server->getUserManager()->get($uid);
382
+        if ($user) {
383
+            return $user->setPassword($password, $recoveryPassword);
384
+        } else {
385
+            return false;
386
+        }
387
+    }
388
+
389
+    /**
390
+     * Check if the password is correct
391
+     *
392
+     * @param string $uid The username
393
+     * @param string $password The password
394
+     * @return string|false user id a string on success, false otherwise
395
+     *
396
+     * Check if the password is correct without logging in the user
397
+     * returns the user id or false
398
+     */
399
+    public static function checkPassword($uid, $password) {
400
+        $manager = \OC::$server->getUserManager();
401
+        $username = $manager->checkPassword($uid, $password);
402
+        if ($username !== false) {
403
+            return $username->getUID();
404
+        }
405
+        return false;
406
+    }
407
+
408
+    /**
409
+     * @param string $uid The username
410
+     * @return string
411
+     *
412
+     * returns the path to the users home directory
413
+     * @deprecated Use \OC::$server->getUserManager->getHome()
414
+     */
415
+    public static function getHome($uid) {
416
+        $user = \OC::$server->getUserManager()->get($uid);
417
+        if ($user) {
418
+            return $user->getHome();
419
+        } else {
420
+            return \OC::$server->getSystemConfig()->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $uid;
421
+        }
422
+    }
423
+
424
+    /**
425
+     * Get a list of all users
426
+     *
427
+     * @return array an array of all uids
428
+     *
429
+     * Get a list of all users.
430
+     * @param string $search
431
+     * @param integer $limit
432
+     * @param integer $offset
433
+     */
434
+    public static function getUsers($search = '', $limit = null, $offset = null) {
435
+        $users = \OC::$server->getUserManager()->search($search, $limit, $offset);
436
+        $uids = array();
437
+        foreach ($users as $user) {
438
+            $uids[] = $user->getUID();
439
+        }
440
+        return $uids;
441
+    }
442
+
443
+    /**
444
+     * Get a list of all users display name
445
+     *
446
+     * @param string $search
447
+     * @param int $limit
448
+     * @param int $offset
449
+     * @return array associative array with all display names (value) and corresponding uids (key)
450
+     *
451
+     * Get a list of all display names and user ids.
452
+     * @deprecated Use \OC::$server->getUserManager->searchDisplayName($search, $limit, $offset) instead.
453
+     */
454
+    public static function getDisplayNames($search = '', $limit = null, $offset = null) {
455
+        $displayNames = array();
456
+        $users = \OC::$server->getUserManager()->searchDisplayName($search, $limit, $offset);
457
+        foreach ($users as $user) {
458
+            $displayNames[$user->getUID()] = $user->getDisplayName();
459
+        }
460
+        return $displayNames;
461
+    }
462
+
463
+    /**
464
+     * check if a user exists
465
+     *
466
+     * @param string $uid the username
467
+     * @return boolean
468
+     */
469
+    public static function userExists($uid) {
470
+        return \OC::$server->getUserManager()->userExists($uid);
471
+    }
472
+
473
+    /**
474
+     * checks if a user is enabled
475
+     *
476
+     * @param string $uid
477
+     * @return bool
478
+     */
479
+    public static function isEnabled($uid) {
480
+        $user = \OC::$server->getUserManager()->get($uid);
481
+        if ($user) {
482
+            return $user->isEnabled();
483
+        } else {
484
+            return false;
485
+        }
486
+    }
487
+
488
+    /**
489
+     * Returns the first active backend from self::$_usedBackends.
490
+     *
491
+     * @return OCP\Authentication\IApacheBackend|null if no backend active, otherwise OCP\Authentication\IApacheBackend
492
+     */
493
+    private static function findFirstActiveUsedBackend() {
494
+        foreach (self::$_usedBackends as $backend) {
495
+            if ($backend instanceof OCP\Authentication\IApacheBackend) {
496
+                if ($backend->isSessionActive()) {
497
+                    return $backend;
498
+                }
499
+            }
500
+        }
501
+
502
+        return null;
503
+    }
504 504
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -94,7 +94,7 @@  discard block
 block discarded – undo
94 94
 				case 'database':
95 95
 				case 'mysql':
96 96
 				case 'sqlite':
97
-					\OCP\Util::writeLog('core', 'Adding user backend ' . $backend . '.', \OCP\Util::DEBUG);
97
+					\OCP\Util::writeLog('core', 'Adding user backend '.$backend.'.', \OCP\Util::DEBUG);
98 98
 					self::$_usedBackends[$backend] = new \OC\User\Database();
99 99
 					\OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
100 100
 					break;
@@ -103,8 +103,8 @@  discard block
 block discarded – undo
103 103
 					\OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
104 104
 					break;
105 105
 				default:
106
-					\OCP\Util::writeLog('core', 'Adding default user backend ' . $backend . '.', \OCP\Util::DEBUG);
107
-					$className = 'OC_USER_' . strtoupper($backend);
106
+					\OCP\Util::writeLog('core', 'Adding default user backend '.$backend.'.', \OCP\Util::DEBUG);
107
+					$className = 'OC_USER_'.strtoupper($backend);
108 108
 					self::$_usedBackends[$backend] = new $className();
109 109
 					\OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
110 110
 					break;
@@ -147,10 +147,10 @@  discard block
 block discarded – undo
147 147
 					self::useBackend($backend);
148 148
 					self::$_setupedBackends[] = $i;
149 149
 				} else {
150
-					\OCP\Util::writeLog('core', 'User backend ' . $class . ' already initialized.', \OCP\Util::DEBUG);
150
+					\OCP\Util::writeLog('core', 'User backend '.$class.' already initialized.', \OCP\Util::DEBUG);
151 151
 				}
152 152
 			} else {
153
-				\OCP\Util::writeLog('core', 'User backend ' . $class . ' not found.', \OCP\Util::ERROR);
153
+				\OCP\Util::writeLog('core', 'User backend '.$class.' not found.', \OCP\Util::ERROR);
154 154
 			}
155 155
 		}
156 156
 	}
@@ -174,15 +174,15 @@  discard block
 block discarded – undo
174 174
 			if (self::getUser() !== $uid) {
175 175
 				self::setUserId($uid);
176 176
 				$setUidAsDisplayName = true;
177
-				if($backend instanceof \OCP\UserInterface
177
+				if ($backend instanceof \OCP\UserInterface
178 178
 					&& $backend->implementsActions(\OC\User\Backend::GET_DISPLAYNAME)) {
179 179
 
180 180
 					$backendDisplayName = $backend->getDisplayName($uid);
181
-					if(is_string($backendDisplayName) && trim($backendDisplayName) !== '') {
181
+					if (is_string($backendDisplayName) && trim($backendDisplayName) !== '') {
182 182
 						$setUidAsDisplayName = false;
183 183
 					}
184 184
 				}
185
-				if($setUidAsDisplayName) {
185
+				if ($setUidAsDisplayName) {
186 186
 					self::setDisplayName($uid);
187 187
 				}
188 188
 				$userSession = self::getUserSession();
@@ -417,7 +417,7 @@  discard block
 block discarded – undo
417 417
 		if ($user) {
418 418
 			return $user->getHome();
419 419
 		} else {
420
-			return \OC::$server->getSystemConfig()->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $uid;
420
+			return \OC::$server->getSystemConfig()->getValue('datadirectory', OC::$SERVERROOT.'/data').'/'.$uid;
421 421
 		}
422 422
 	}
423 423
 
Please login to merge, or discard this patch.
apps/user_ldap/lib/User_LDAP.php 2 patches
Indentation   +501 added lines, -501 removed lines patch added patch discarded remove patch
@@ -45,508 +45,508 @@
 block discarded – undo
45 45
 use OCP\Util;
46 46
 
47 47
 class User_LDAP extends BackendUtility implements \OCP\IUserBackend, \OCP\UserInterface, IUserLDAP {
48
-	/** @var string[] $homesToKill */
49
-	protected $homesToKill = array();
50
-
51
-	/** @var \OCP\IConfig */
52
-	protected $ocConfig;
53
-
54
-	/** @var INotificationManager */
55
-	protected $notificationManager;
56
-
57
-	/**
58
-	 * @param Access $access
59
-	 * @param \OCP\IConfig $ocConfig
60
-	 * @param \OCP\Notification\IManager $notificationManager
61
-	 */
62
-	public function __construct(Access $access, IConfig $ocConfig, INotificationManager $notificationManager) {
63
-		parent::__construct($access);
64
-		$this->ocConfig = $ocConfig;
65
-		$this->notificationManager = $notificationManager;
66
-	}
67
-
68
-	/**
69
-	 * checks whether the user is allowed to change his avatar in Nextcloud
70
-	 * @param string $uid the Nextcloud user name
71
-	 * @return boolean either the user can or cannot
72
-	 */
73
-	public function canChangeAvatar($uid) {
74
-		$user = $this->access->userManager->get($uid);
75
-		if(!$user instanceof User) {
76
-			return false;
77
-		}
78
-		if($user->getAvatarImage() === false) {
79
-			return true;
80
-		}
81
-
82
-		return false;
83
-	}
84
-
85
-	/**
86
-	 * returns the username for the given login name, if available
87
-	 *
88
-	 * @param string $loginName
89
-	 * @return string|false
90
-	 */
91
-	public function loginName2UserName($loginName) {
92
-		$cacheKey = 'loginName2UserName-'.$loginName;
93
-		$username = $this->access->connection->getFromCache($cacheKey);
94
-		if(!is_null($username)) {
95
-			return $username;
96
-		}
97
-
98
-		try {
99
-			$ldapRecord = $this->getLDAPUserByLoginName($loginName);
100
-			$user = $this->access->userManager->get($ldapRecord['dn'][0]);
101
-			if($user instanceof OfflineUser) {
102
-				// this path is not really possible, however get() is documented
103
-				// to return User or OfflineUser so we are very defensive here.
104
-				$this->access->connection->writeToCache($cacheKey, false);
105
-				return false;
106
-			}
107
-			$username = $user->getUsername();
108
-			$this->access->connection->writeToCache($cacheKey, $username);
109
-			return $username;
110
-		} catch (NotOnLDAP $e) {
111
-			$this->access->connection->writeToCache($cacheKey, false);
112
-			return false;
113
-		}
114
-	}
48
+    /** @var string[] $homesToKill */
49
+    protected $homesToKill = array();
50
+
51
+    /** @var \OCP\IConfig */
52
+    protected $ocConfig;
53
+
54
+    /** @var INotificationManager */
55
+    protected $notificationManager;
56
+
57
+    /**
58
+     * @param Access $access
59
+     * @param \OCP\IConfig $ocConfig
60
+     * @param \OCP\Notification\IManager $notificationManager
61
+     */
62
+    public function __construct(Access $access, IConfig $ocConfig, INotificationManager $notificationManager) {
63
+        parent::__construct($access);
64
+        $this->ocConfig = $ocConfig;
65
+        $this->notificationManager = $notificationManager;
66
+    }
67
+
68
+    /**
69
+     * checks whether the user is allowed to change his avatar in Nextcloud
70
+     * @param string $uid the Nextcloud user name
71
+     * @return boolean either the user can or cannot
72
+     */
73
+    public function canChangeAvatar($uid) {
74
+        $user = $this->access->userManager->get($uid);
75
+        if(!$user instanceof User) {
76
+            return false;
77
+        }
78
+        if($user->getAvatarImage() === false) {
79
+            return true;
80
+        }
81
+
82
+        return false;
83
+    }
84
+
85
+    /**
86
+     * returns the username for the given login name, if available
87
+     *
88
+     * @param string $loginName
89
+     * @return string|false
90
+     */
91
+    public function loginName2UserName($loginName) {
92
+        $cacheKey = 'loginName2UserName-'.$loginName;
93
+        $username = $this->access->connection->getFromCache($cacheKey);
94
+        if(!is_null($username)) {
95
+            return $username;
96
+        }
97
+
98
+        try {
99
+            $ldapRecord = $this->getLDAPUserByLoginName($loginName);
100
+            $user = $this->access->userManager->get($ldapRecord['dn'][0]);
101
+            if($user instanceof OfflineUser) {
102
+                // this path is not really possible, however get() is documented
103
+                // to return User or OfflineUser so we are very defensive here.
104
+                $this->access->connection->writeToCache($cacheKey, false);
105
+                return false;
106
+            }
107
+            $username = $user->getUsername();
108
+            $this->access->connection->writeToCache($cacheKey, $username);
109
+            return $username;
110
+        } catch (NotOnLDAP $e) {
111
+            $this->access->connection->writeToCache($cacheKey, false);
112
+            return false;
113
+        }
114
+    }
115 115
 	
116
-	/**
117
-	 * returns the username for the given LDAP DN, if available
118
-	 *
119
-	 * @param string $dn
120
-	 * @return string|false with the username
121
-	 */
122
-	public function dn2UserName($dn) {
123
-		return $this->access->dn2username($dn);
124
-	}
125
-
126
-	/**
127
-	 * returns an LDAP record based on a given login name
128
-	 *
129
-	 * @param string $loginName
130
-	 * @return array
131
-	 * @throws NotOnLDAP
132
-	 */
133
-	public function getLDAPUserByLoginName($loginName) {
134
-		//find out dn of the user name
135
-		$attrs = $this->access->userManager->getAttributes();
136
-		$users = $this->access->fetchUsersByLoginName($loginName, $attrs);
137
-		if(count($users) < 1) {
138
-			throw new NotOnLDAP('No user available for the given login name on ' .
139
-				$this->access->connection->ldapHost . ':' . $this->access->connection->ldapPort);
140
-		}
141
-		return $users[0];
142
-	}
143
-
144
-	/**
145
-	 * Check if the password is correct without logging in the user
146
-	 *
147
-	 * @param string $uid The username
148
-	 * @param string $password The password
149
-	 * @return false|string
150
-	 */
151
-	public function checkPassword($uid, $password) {
152
-		try {
153
-			$ldapRecord = $this->getLDAPUserByLoginName($uid);
154
-		} catch(NotOnLDAP $e) {
155
-			if($this->ocConfig->getSystemValue('loglevel', Util::WARN) === Util::DEBUG) {
156
-				\OC::$server->getLogger()->logException($e, ['app' => 'user_ldap']);
157
-			}
158
-			return false;
159
-		}
160
-		$dn = $ldapRecord['dn'][0];
161
-		$user = $this->access->userManager->get($dn);
162
-
163
-		if(!$user instanceof User) {
164
-			Util::writeLog('user_ldap',
165
-				'LDAP Login: Could not get user object for DN ' . $dn .
166
-				'. Maybe the LDAP entry has no set display name attribute?',
167
-				Util::WARN);
168
-			return false;
169
-		}
170
-		if($user->getUsername() !== false) {
171
-			//are the credentials OK?
172
-			if(!$this->access->areCredentialsValid($dn, $password)) {
173
-				return false;
174
-			}
175
-
176
-			$this->access->cacheUserExists($user->getUsername());
177
-			$user->processAttributes($ldapRecord);
178
-			$user->markLogin();
179
-
180
-			return $user->getUsername();
181
-		}
182
-
183
-		return false;
184
-	}
185
-
186
-	/**
187
-	 * Set password
188
-	 * @param string $uid The username
189
-	 * @param string $password The new password
190
-	 * @return bool
191
-	 */
192
-	public function setPassword($uid, $password) {
193
-		$user = $this->access->userManager->get($uid);
194
-
195
-		if(!$user instanceof User) {
196
-			throw new \Exception('LDAP setPassword: Could not get user object for uid ' . $uid .
197
-				'. Maybe the LDAP entry has no set display name attribute?');
198
-		}
199
-		if($user->getUsername() !== false && $this->access->setPassword($user->getDN(), $password)) {
200
-			$ldapDefaultPPolicyDN = $this->access->connection->ldapDefaultPPolicyDN;
201
-			$turnOnPasswordChange = $this->access->connection->turnOnPasswordChange;
202
-			if (!empty($ldapDefaultPPolicyDN) && (intval($turnOnPasswordChange) === 1)) {
203
-				//remove last password expiry warning if any
204
-				$notification = $this->notificationManager->createNotification();
205
-				$notification->setApp('user_ldap')
206
-					->setUser($uid)
207
-					->setObject('pwd_exp_warn', $uid)
208
-				;
209
-				$this->notificationManager->markProcessed($notification);
210
-			}
211
-			return true;
212
-		}
213
-
214
-		return false;
215
-	}
216
-
217
-	/**
218
-	 * Get a list of all users
219
-	 *
220
-	 * @param string $search
221
-	 * @param integer $limit
222
-	 * @param integer $offset
223
-	 * @return string[] an array of all uids
224
-	 */
225
-	public function getUsers($search = '', $limit = 10, $offset = 0) {
226
-		$search = $this->access->escapeFilterPart($search, true);
227
-		$cachekey = 'getUsers-'.$search.'-'.$limit.'-'.$offset;
228
-
229
-		//check if users are cached, if so return
230
-		$ldap_users = $this->access->connection->getFromCache($cachekey);
231
-		if(!is_null($ldap_users)) {
232
-			return $ldap_users;
233
-		}
234
-
235
-		// if we'd pass -1 to LDAP search, we'd end up in a Protocol
236
-		// error. With a limit of 0, we get 0 results. So we pass null.
237
-		if($limit <= 0) {
238
-			$limit = null;
239
-		}
240
-		$filter = $this->access->combineFilterWithAnd(array(
241
-			$this->access->connection->ldapUserFilter,
242
-			$this->access->connection->ldapUserDisplayName . '=*',
243
-			$this->access->getFilterPartForUserSearch($search)
244
-		));
245
-
246
-		Util::writeLog('user_ldap',
247
-			'getUsers: Options: search '.$search.' limit '.$limit.' offset '.$offset.' Filter: '.$filter,
248
-			Util::DEBUG);
249
-		//do the search and translate results to owncloud names
250
-		$ldap_users = $this->access->fetchListOfUsers(
251
-			$filter,
252
-			$this->access->userManager->getAttributes(true),
253
-			$limit, $offset);
254
-		$ldap_users = $this->access->nextcloudUserNames($ldap_users);
255
-		Util::writeLog('user_ldap', 'getUsers: '.count($ldap_users). ' Users found', Util::DEBUG);
256
-
257
-		$this->access->connection->writeToCache($cachekey, $ldap_users);
258
-		return $ldap_users;
259
-	}
260
-
261
-	/**
262
-	 * checks whether a user is still available on LDAP
263
-	 *
264
-	 * @param string|\OCA\User_LDAP\User\User $user either the Nextcloud user
265
-	 * name or an instance of that user
266
-	 * @return bool
267
-	 * @throws \Exception
268
-	 * @throws \OC\ServerNotAvailableException
269
-	 */
270
-	public function userExistsOnLDAP($user) {
271
-		if(is_string($user)) {
272
-			$user = $this->access->userManager->get($user);
273
-		}
274
-		if(is_null($user)) {
275
-			return false;
276
-		}
277
-
278
-		$dn = $user->getDN();
279
-		//check if user really still exists by reading its entry
280
-		if(!is_array($this->access->readAttribute($dn, '', $this->access->connection->ldapUserFilter))) {
281
-			$lcr = $this->access->connection->getConnectionResource();
282
-			if(is_null($lcr)) {
283
-				throw new \Exception('No LDAP Connection to server ' . $this->access->connection->ldapHost);
284
-			}
285
-
286
-			try {
287
-				$uuid = $this->access->getUserMapper()->getUUIDByDN($dn);
288
-				if(!$uuid) {
289
-					return false;
290
-				}
291
-				$newDn = $this->access->getUserDnByUuid($uuid);
292
-				//check if renamed user is still valid by reapplying the ldap filter
293
-				if(!is_array($this->access->readAttribute($newDn, '', $this->access->connection->ldapUserFilter))) {
294
-					return false;
295
-				}
296
-				$this->access->getUserMapper()->setDNbyUUID($newDn, $uuid);
297
-				return true;
298
-			} catch (\Exception $e) {
299
-				return false;
300
-			}
301
-		}
302
-
303
-		if($user instanceof OfflineUser) {
304
-			$user->unmark();
305
-		}
306
-
307
-		return true;
308
-	}
309
-
310
-	/**
311
-	 * check if a user exists
312
-	 * @param string $uid the username
313
-	 * @return boolean
314
-	 * @throws \Exception when connection could not be established
315
-	 */
316
-	public function userExists($uid) {
317
-		$userExists = $this->access->connection->getFromCache('userExists'.$uid);
318
-		if(!is_null($userExists)) {
319
-			return (bool)$userExists;
320
-		}
321
-		//getting dn, if false the user does not exist. If dn, he may be mapped only, requires more checking.
322
-		$user = $this->access->userManager->get($uid);
323
-
324
-		if(is_null($user)) {
325
-			Util::writeLog('user_ldap', 'No DN found for '.$uid.' on '.
326
-				$this->access->connection->ldapHost, Util::DEBUG);
327
-			$this->access->connection->writeToCache('userExists'.$uid, false);
328
-			return false;
329
-		} else if($user instanceof OfflineUser) {
330
-			//express check for users marked as deleted. Returning true is
331
-			//necessary for cleanup
332
-			return true;
333
-		}
334
-
335
-		$result = $this->userExistsOnLDAP($user);
336
-		$this->access->connection->writeToCache('userExists'.$uid, $result);
337
-		if($result === true) {
338
-			$user->update();
339
-		}
340
-		return $result;
341
-	}
342
-
343
-	/**
344
-	* returns whether a user was deleted in LDAP
345
-	*
346
-	* @param string $uid The username of the user to delete
347
-	* @return bool
348
-	*/
349
-	public function deleteUser($uid) {
350
-		$marked = $this->ocConfig->getUserValue($uid, 'user_ldap', 'isDeleted', 0);
351
-		if(intval($marked) === 0) {
352
-			\OC::$server->getLogger()->notice(
353
-				'User '.$uid . ' is not marked as deleted, not cleaning up.',
354
-				array('app' => 'user_ldap'));
355
-			return false;
356
-		}
357
-		\OC::$server->getLogger()->info('Cleaning up after user ' . $uid,
358
-			array('app' => 'user_ldap'));
359
-
360
-		//Get Home Directory out of user preferences so we can return it later,
361
-		//necessary for removing directories as done by OC_User.
362
-		$home = $this->ocConfig->getUserValue($uid, 'user_ldap', 'homePath', '');
363
-		$this->homesToKill[$uid] = $home;
364
-		$this->access->getUserMapper()->unmap($uid);
365
-
366
-		return true;
367
-	}
368
-
369
-	/**
370
-	 * get the user's home directory
371
-	 *
372
-	 * @param string $uid the username
373
-	 * @return bool|string
374
-	 * @throws NoUserException
375
-	 * @throws \Exception
376
-	 */
377
-	public function getHome($uid) {
378
-		if(isset($this->homesToKill[$uid]) && !empty($this->homesToKill[$uid])) {
379
-			//a deleted user who needs some clean up
380
-			return $this->homesToKill[$uid];
381
-		}
382
-
383
-		// user Exists check required as it is not done in user proxy!
384
-		if(!$this->userExists($uid)) {
385
-			return false;
386
-		}
387
-
388
-		$cacheKey = 'getHome'.$uid;
389
-		$path = $this->access->connection->getFromCache($cacheKey);
390
-		if(!is_null($path)) {
391
-			return $path;
392
-		}
393
-
394
-		$user = $this->access->userManager->get($uid);
395
-		if(is_null($user) || ($user instanceof OfflineUser && !$this->userExistsOnLDAP($user->getOCName()))) {
396
-			throw new NoUserException($uid . ' is not a valid user anymore');
397
-		}
398
-		if($user instanceof OfflineUser) {
399
-			// apparently this user survived the userExistsOnLDAP check,
400
-			// we request the user instance again in order to retrieve a User
401
-			// instance instead
402
-			$user = $this->access->userManager->get($uid);
403
-		}
404
-		$path = $user->getHomePath();
405
-		$this->access->cacheUserHome($uid, $path);
406
-
407
-		return $path;
408
-	}
409
-
410
-	/**
411
-	 * get display name of the user
412
-	 * @param string $uid user ID of the user
413
-	 * @return string|false display name
414
-	 */
415
-	public function getDisplayName($uid) {
416
-		if(!$this->userExists($uid)) {
417
-			return false;
418
-		}
419
-
420
-		$cacheKey = 'getDisplayName'.$uid;
421
-		if(!is_null($displayName = $this->access->connection->getFromCache($cacheKey))) {
422
-			return $displayName;
423
-		}
424
-
425
-		//Check whether the display name is configured to have a 2nd feature
426
-		$additionalAttribute = $this->access->connection->ldapUserDisplayName2;
427
-		$displayName2 = '';
428
-		if ($additionalAttribute !== '') {
429
-			$displayName2 = $this->access->readAttribute(
430
-				$this->access->username2dn($uid),
431
-				$additionalAttribute);
432
-		}
433
-
434
-		$displayName = $this->access->readAttribute(
435
-			$this->access->username2dn($uid),
436
-			$this->access->connection->ldapUserDisplayName);
437
-
438
-		if($displayName && (count($displayName) > 0)) {
439
-			$displayName = $displayName[0];
440
-
441
-			if (is_array($displayName2)){
442
-				$displayName2 = count($displayName2) > 0 ? $displayName2[0] : '';
443
-			}
444
-
445
-			$user = $this->access->userManager->get($uid);
446
-			if ($user instanceof User) {
447
-				$displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
448
-				$this->access->connection->writeToCache($cacheKey, $displayName);
449
-			}
450
-			if ($user instanceof OfflineUser) {
451
-				/** @var OfflineUser $user*/
452
-				$displayName = $user->getDisplayName();
453
-			}
454
-			return $displayName;
455
-		}
456
-
457
-		return null;
458
-	}
459
-
460
-	/**
461
-	 * Get a list of all display names
462
-	 *
463
-	 * @param string $search
464
-	 * @param string|null $limit
465
-	 * @param string|null $offset
466
-	 * @return array an array of all displayNames (value) and the corresponding uids (key)
467
-	 */
468
-	public function getDisplayNames($search = '', $limit = null, $offset = null) {
469
-		$cacheKey = 'getDisplayNames-'.$search.'-'.$limit.'-'.$offset;
470
-		if(!is_null($displayNames = $this->access->connection->getFromCache($cacheKey))) {
471
-			return $displayNames;
472
-		}
473
-
474
-		$displayNames = array();
475
-		$users = $this->getUsers($search, $limit, $offset);
476
-		foreach ($users as $user) {
477
-			$displayNames[$user] = $this->getDisplayName($user);
478
-		}
479
-		$this->access->connection->writeToCache($cacheKey, $displayNames);
480
-		return $displayNames;
481
-	}
482
-
483
-	/**
484
-	* Check if backend implements actions
485
-	* @param int $actions bitwise-or'ed actions
486
-	* @return boolean
487
-	*
488
-	* Returns the supported actions as int to be
489
-	* compared with \OC\User\Backend::CREATE_USER etc.
490
-	*/
491
-	public function implementsActions($actions) {
492
-		return (bool)((Backend::CHECK_PASSWORD
493
-			| Backend::GET_HOME
494
-			| Backend::GET_DISPLAYNAME
495
-			| Backend::PROVIDE_AVATAR
496
-			| Backend::COUNT_USERS
497
-			| ((intval($this->access->connection->turnOnPasswordChange) === 1)?(Backend::SET_PASSWORD):0))
498
-			& $actions);
499
-	}
500
-
501
-	/**
502
-	 * @return bool
503
-	 */
504
-	public function hasUserListings() {
505
-		return true;
506
-	}
507
-
508
-	/**
509
-	 * counts the users in LDAP
510
-	 *
511
-	 * @return int|bool
512
-	 */
513
-	public function countUsers() {
514
-		$filter = $this->access->getFilterForUserCount();
515
-		$cacheKey = 'countUsers-'.$filter;
516
-		if(!is_null($entries = $this->access->connection->getFromCache($cacheKey))) {
517
-			return $entries;
518
-		}
519
-		$entries = $this->access->countUsers($filter);
520
-		$this->access->connection->writeToCache($cacheKey, $entries);
521
-		return $entries;
522
-	}
523
-
524
-	/**
525
-	 * Backend name to be shown in user management
526
-	 * @return string the name of the backend to be shown
527
-	 */
528
-	public function getBackendName(){
529
-		return 'LDAP';
530
-	}
116
+    /**
117
+     * returns the username for the given LDAP DN, if available
118
+     *
119
+     * @param string $dn
120
+     * @return string|false with the username
121
+     */
122
+    public function dn2UserName($dn) {
123
+        return $this->access->dn2username($dn);
124
+    }
125
+
126
+    /**
127
+     * returns an LDAP record based on a given login name
128
+     *
129
+     * @param string $loginName
130
+     * @return array
131
+     * @throws NotOnLDAP
132
+     */
133
+    public function getLDAPUserByLoginName($loginName) {
134
+        //find out dn of the user name
135
+        $attrs = $this->access->userManager->getAttributes();
136
+        $users = $this->access->fetchUsersByLoginName($loginName, $attrs);
137
+        if(count($users) < 1) {
138
+            throw new NotOnLDAP('No user available for the given login name on ' .
139
+                $this->access->connection->ldapHost . ':' . $this->access->connection->ldapPort);
140
+        }
141
+        return $users[0];
142
+    }
143
+
144
+    /**
145
+     * Check if the password is correct without logging in the user
146
+     *
147
+     * @param string $uid The username
148
+     * @param string $password The password
149
+     * @return false|string
150
+     */
151
+    public function checkPassword($uid, $password) {
152
+        try {
153
+            $ldapRecord = $this->getLDAPUserByLoginName($uid);
154
+        } catch(NotOnLDAP $e) {
155
+            if($this->ocConfig->getSystemValue('loglevel', Util::WARN) === Util::DEBUG) {
156
+                \OC::$server->getLogger()->logException($e, ['app' => 'user_ldap']);
157
+            }
158
+            return false;
159
+        }
160
+        $dn = $ldapRecord['dn'][0];
161
+        $user = $this->access->userManager->get($dn);
162
+
163
+        if(!$user instanceof User) {
164
+            Util::writeLog('user_ldap',
165
+                'LDAP Login: Could not get user object for DN ' . $dn .
166
+                '. Maybe the LDAP entry has no set display name attribute?',
167
+                Util::WARN);
168
+            return false;
169
+        }
170
+        if($user->getUsername() !== false) {
171
+            //are the credentials OK?
172
+            if(!$this->access->areCredentialsValid($dn, $password)) {
173
+                return false;
174
+            }
175
+
176
+            $this->access->cacheUserExists($user->getUsername());
177
+            $user->processAttributes($ldapRecord);
178
+            $user->markLogin();
179
+
180
+            return $user->getUsername();
181
+        }
182
+
183
+        return false;
184
+    }
185
+
186
+    /**
187
+     * Set password
188
+     * @param string $uid The username
189
+     * @param string $password The new password
190
+     * @return bool
191
+     */
192
+    public function setPassword($uid, $password) {
193
+        $user = $this->access->userManager->get($uid);
194
+
195
+        if(!$user instanceof User) {
196
+            throw new \Exception('LDAP setPassword: Could not get user object for uid ' . $uid .
197
+                '. Maybe the LDAP entry has no set display name attribute?');
198
+        }
199
+        if($user->getUsername() !== false && $this->access->setPassword($user->getDN(), $password)) {
200
+            $ldapDefaultPPolicyDN = $this->access->connection->ldapDefaultPPolicyDN;
201
+            $turnOnPasswordChange = $this->access->connection->turnOnPasswordChange;
202
+            if (!empty($ldapDefaultPPolicyDN) && (intval($turnOnPasswordChange) === 1)) {
203
+                //remove last password expiry warning if any
204
+                $notification = $this->notificationManager->createNotification();
205
+                $notification->setApp('user_ldap')
206
+                    ->setUser($uid)
207
+                    ->setObject('pwd_exp_warn', $uid)
208
+                ;
209
+                $this->notificationManager->markProcessed($notification);
210
+            }
211
+            return true;
212
+        }
213
+
214
+        return false;
215
+    }
216
+
217
+    /**
218
+     * Get a list of all users
219
+     *
220
+     * @param string $search
221
+     * @param integer $limit
222
+     * @param integer $offset
223
+     * @return string[] an array of all uids
224
+     */
225
+    public function getUsers($search = '', $limit = 10, $offset = 0) {
226
+        $search = $this->access->escapeFilterPart($search, true);
227
+        $cachekey = 'getUsers-'.$search.'-'.$limit.'-'.$offset;
228
+
229
+        //check if users are cached, if so return
230
+        $ldap_users = $this->access->connection->getFromCache($cachekey);
231
+        if(!is_null($ldap_users)) {
232
+            return $ldap_users;
233
+        }
234
+
235
+        // if we'd pass -1 to LDAP search, we'd end up in a Protocol
236
+        // error. With a limit of 0, we get 0 results. So we pass null.
237
+        if($limit <= 0) {
238
+            $limit = null;
239
+        }
240
+        $filter = $this->access->combineFilterWithAnd(array(
241
+            $this->access->connection->ldapUserFilter,
242
+            $this->access->connection->ldapUserDisplayName . '=*',
243
+            $this->access->getFilterPartForUserSearch($search)
244
+        ));
245
+
246
+        Util::writeLog('user_ldap',
247
+            'getUsers: Options: search '.$search.' limit '.$limit.' offset '.$offset.' Filter: '.$filter,
248
+            Util::DEBUG);
249
+        //do the search and translate results to owncloud names
250
+        $ldap_users = $this->access->fetchListOfUsers(
251
+            $filter,
252
+            $this->access->userManager->getAttributes(true),
253
+            $limit, $offset);
254
+        $ldap_users = $this->access->nextcloudUserNames($ldap_users);
255
+        Util::writeLog('user_ldap', 'getUsers: '.count($ldap_users). ' Users found', Util::DEBUG);
256
+
257
+        $this->access->connection->writeToCache($cachekey, $ldap_users);
258
+        return $ldap_users;
259
+    }
260
+
261
+    /**
262
+     * checks whether a user is still available on LDAP
263
+     *
264
+     * @param string|\OCA\User_LDAP\User\User $user either the Nextcloud user
265
+     * name or an instance of that user
266
+     * @return bool
267
+     * @throws \Exception
268
+     * @throws \OC\ServerNotAvailableException
269
+     */
270
+    public function userExistsOnLDAP($user) {
271
+        if(is_string($user)) {
272
+            $user = $this->access->userManager->get($user);
273
+        }
274
+        if(is_null($user)) {
275
+            return false;
276
+        }
277
+
278
+        $dn = $user->getDN();
279
+        //check if user really still exists by reading its entry
280
+        if(!is_array($this->access->readAttribute($dn, '', $this->access->connection->ldapUserFilter))) {
281
+            $lcr = $this->access->connection->getConnectionResource();
282
+            if(is_null($lcr)) {
283
+                throw new \Exception('No LDAP Connection to server ' . $this->access->connection->ldapHost);
284
+            }
285
+
286
+            try {
287
+                $uuid = $this->access->getUserMapper()->getUUIDByDN($dn);
288
+                if(!$uuid) {
289
+                    return false;
290
+                }
291
+                $newDn = $this->access->getUserDnByUuid($uuid);
292
+                //check if renamed user is still valid by reapplying the ldap filter
293
+                if(!is_array($this->access->readAttribute($newDn, '', $this->access->connection->ldapUserFilter))) {
294
+                    return false;
295
+                }
296
+                $this->access->getUserMapper()->setDNbyUUID($newDn, $uuid);
297
+                return true;
298
+            } catch (\Exception $e) {
299
+                return false;
300
+            }
301
+        }
302
+
303
+        if($user instanceof OfflineUser) {
304
+            $user->unmark();
305
+        }
306
+
307
+        return true;
308
+    }
309
+
310
+    /**
311
+     * check if a user exists
312
+     * @param string $uid the username
313
+     * @return boolean
314
+     * @throws \Exception when connection could not be established
315
+     */
316
+    public function userExists($uid) {
317
+        $userExists = $this->access->connection->getFromCache('userExists'.$uid);
318
+        if(!is_null($userExists)) {
319
+            return (bool)$userExists;
320
+        }
321
+        //getting dn, if false the user does not exist. If dn, he may be mapped only, requires more checking.
322
+        $user = $this->access->userManager->get($uid);
323
+
324
+        if(is_null($user)) {
325
+            Util::writeLog('user_ldap', 'No DN found for '.$uid.' on '.
326
+                $this->access->connection->ldapHost, Util::DEBUG);
327
+            $this->access->connection->writeToCache('userExists'.$uid, false);
328
+            return false;
329
+        } else if($user instanceof OfflineUser) {
330
+            //express check for users marked as deleted. Returning true is
331
+            //necessary for cleanup
332
+            return true;
333
+        }
334
+
335
+        $result = $this->userExistsOnLDAP($user);
336
+        $this->access->connection->writeToCache('userExists'.$uid, $result);
337
+        if($result === true) {
338
+            $user->update();
339
+        }
340
+        return $result;
341
+    }
342
+
343
+    /**
344
+     * returns whether a user was deleted in LDAP
345
+     *
346
+     * @param string $uid The username of the user to delete
347
+     * @return bool
348
+     */
349
+    public function deleteUser($uid) {
350
+        $marked = $this->ocConfig->getUserValue($uid, 'user_ldap', 'isDeleted', 0);
351
+        if(intval($marked) === 0) {
352
+            \OC::$server->getLogger()->notice(
353
+                'User '.$uid . ' is not marked as deleted, not cleaning up.',
354
+                array('app' => 'user_ldap'));
355
+            return false;
356
+        }
357
+        \OC::$server->getLogger()->info('Cleaning up after user ' . $uid,
358
+            array('app' => 'user_ldap'));
359
+
360
+        //Get Home Directory out of user preferences so we can return it later,
361
+        //necessary for removing directories as done by OC_User.
362
+        $home = $this->ocConfig->getUserValue($uid, 'user_ldap', 'homePath', '');
363
+        $this->homesToKill[$uid] = $home;
364
+        $this->access->getUserMapper()->unmap($uid);
365
+
366
+        return true;
367
+    }
368
+
369
+    /**
370
+     * get the user's home directory
371
+     *
372
+     * @param string $uid the username
373
+     * @return bool|string
374
+     * @throws NoUserException
375
+     * @throws \Exception
376
+     */
377
+    public function getHome($uid) {
378
+        if(isset($this->homesToKill[$uid]) && !empty($this->homesToKill[$uid])) {
379
+            //a deleted user who needs some clean up
380
+            return $this->homesToKill[$uid];
381
+        }
382
+
383
+        // user Exists check required as it is not done in user proxy!
384
+        if(!$this->userExists($uid)) {
385
+            return false;
386
+        }
387
+
388
+        $cacheKey = 'getHome'.$uid;
389
+        $path = $this->access->connection->getFromCache($cacheKey);
390
+        if(!is_null($path)) {
391
+            return $path;
392
+        }
393
+
394
+        $user = $this->access->userManager->get($uid);
395
+        if(is_null($user) || ($user instanceof OfflineUser && !$this->userExistsOnLDAP($user->getOCName()))) {
396
+            throw new NoUserException($uid . ' is not a valid user anymore');
397
+        }
398
+        if($user instanceof OfflineUser) {
399
+            // apparently this user survived the userExistsOnLDAP check,
400
+            // we request the user instance again in order to retrieve a User
401
+            // instance instead
402
+            $user = $this->access->userManager->get($uid);
403
+        }
404
+        $path = $user->getHomePath();
405
+        $this->access->cacheUserHome($uid, $path);
406
+
407
+        return $path;
408
+    }
409
+
410
+    /**
411
+     * get display name of the user
412
+     * @param string $uid user ID of the user
413
+     * @return string|false display name
414
+     */
415
+    public function getDisplayName($uid) {
416
+        if(!$this->userExists($uid)) {
417
+            return false;
418
+        }
419
+
420
+        $cacheKey = 'getDisplayName'.$uid;
421
+        if(!is_null($displayName = $this->access->connection->getFromCache($cacheKey))) {
422
+            return $displayName;
423
+        }
424
+
425
+        //Check whether the display name is configured to have a 2nd feature
426
+        $additionalAttribute = $this->access->connection->ldapUserDisplayName2;
427
+        $displayName2 = '';
428
+        if ($additionalAttribute !== '') {
429
+            $displayName2 = $this->access->readAttribute(
430
+                $this->access->username2dn($uid),
431
+                $additionalAttribute);
432
+        }
433
+
434
+        $displayName = $this->access->readAttribute(
435
+            $this->access->username2dn($uid),
436
+            $this->access->connection->ldapUserDisplayName);
437
+
438
+        if($displayName && (count($displayName) > 0)) {
439
+            $displayName = $displayName[0];
440
+
441
+            if (is_array($displayName2)){
442
+                $displayName2 = count($displayName2) > 0 ? $displayName2[0] : '';
443
+            }
444
+
445
+            $user = $this->access->userManager->get($uid);
446
+            if ($user instanceof User) {
447
+                $displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
448
+                $this->access->connection->writeToCache($cacheKey, $displayName);
449
+            }
450
+            if ($user instanceof OfflineUser) {
451
+                /** @var OfflineUser $user*/
452
+                $displayName = $user->getDisplayName();
453
+            }
454
+            return $displayName;
455
+        }
456
+
457
+        return null;
458
+    }
459
+
460
+    /**
461
+     * Get a list of all display names
462
+     *
463
+     * @param string $search
464
+     * @param string|null $limit
465
+     * @param string|null $offset
466
+     * @return array an array of all displayNames (value) and the corresponding uids (key)
467
+     */
468
+    public function getDisplayNames($search = '', $limit = null, $offset = null) {
469
+        $cacheKey = 'getDisplayNames-'.$search.'-'.$limit.'-'.$offset;
470
+        if(!is_null($displayNames = $this->access->connection->getFromCache($cacheKey))) {
471
+            return $displayNames;
472
+        }
473
+
474
+        $displayNames = array();
475
+        $users = $this->getUsers($search, $limit, $offset);
476
+        foreach ($users as $user) {
477
+            $displayNames[$user] = $this->getDisplayName($user);
478
+        }
479
+        $this->access->connection->writeToCache($cacheKey, $displayNames);
480
+        return $displayNames;
481
+    }
482
+
483
+    /**
484
+     * Check if backend implements actions
485
+     * @param int $actions bitwise-or'ed actions
486
+     * @return boolean
487
+     *
488
+     * Returns the supported actions as int to be
489
+     * compared with \OC\User\Backend::CREATE_USER etc.
490
+     */
491
+    public function implementsActions($actions) {
492
+        return (bool)((Backend::CHECK_PASSWORD
493
+            | Backend::GET_HOME
494
+            | Backend::GET_DISPLAYNAME
495
+            | Backend::PROVIDE_AVATAR
496
+            | Backend::COUNT_USERS
497
+            | ((intval($this->access->connection->turnOnPasswordChange) === 1)?(Backend::SET_PASSWORD):0))
498
+            & $actions);
499
+    }
500
+
501
+    /**
502
+     * @return bool
503
+     */
504
+    public function hasUserListings() {
505
+        return true;
506
+    }
507
+
508
+    /**
509
+     * counts the users in LDAP
510
+     *
511
+     * @return int|bool
512
+     */
513
+    public function countUsers() {
514
+        $filter = $this->access->getFilterForUserCount();
515
+        $cacheKey = 'countUsers-'.$filter;
516
+        if(!is_null($entries = $this->access->connection->getFromCache($cacheKey))) {
517
+            return $entries;
518
+        }
519
+        $entries = $this->access->countUsers($filter);
520
+        $this->access->connection->writeToCache($cacheKey, $entries);
521
+        return $entries;
522
+    }
523
+
524
+    /**
525
+     * Backend name to be shown in user management
526
+     * @return string the name of the backend to be shown
527
+     */
528
+    public function getBackendName(){
529
+        return 'LDAP';
530
+    }
531 531
 	
532
-	/**
533
-	 * Return access for LDAP interaction.
534
-	 * @param string $uid
535
-	 * @return Access instance of Access for LDAP interaction
536
-	 */
537
-	public function getLDAPAccess($uid) {
538
-		return $this->access;
539
-	}
532
+    /**
533
+     * Return access for LDAP interaction.
534
+     * @param string $uid
535
+     * @return Access instance of Access for LDAP interaction
536
+     */
537
+    public function getLDAPAccess($uid) {
538
+        return $this->access;
539
+    }
540 540
 	
541
-	/**
542
-	 * Return LDAP connection resource from a cloned connection.
543
-	 * The cloned connection needs to be closed manually.
544
-	 * of the current access.
545
-	 * @param string $uid
546
-	 * @return resource of the LDAP connection
547
-	 */
548
-	public function getNewLDAPConnection($uid) {
549
-		$connection = clone $this->access->getConnection();
550
-		return $connection->getConnectionResource();
551
-	}
541
+    /**
542
+     * Return LDAP connection resource from a cloned connection.
543
+     * The cloned connection needs to be closed manually.
544
+     * of the current access.
545
+     * @param string $uid
546
+     * @return resource of the LDAP connection
547
+     */
548
+    public function getNewLDAPConnection($uid) {
549
+        $connection = clone $this->access->getConnection();
550
+        return $connection->getConnectionResource();
551
+    }
552 552
 }
Please login to merge, or discard this patch.
Spacing   +51 added lines, -51 removed lines patch added patch discarded remove patch
@@ -72,10 +72,10 @@  discard block
 block discarded – undo
72 72
 	 */
73 73
 	public function canChangeAvatar($uid) {
74 74
 		$user = $this->access->userManager->get($uid);
75
-		if(!$user instanceof User) {
75
+		if (!$user instanceof User) {
76 76
 			return false;
77 77
 		}
78
-		if($user->getAvatarImage() === false) {
78
+		if ($user->getAvatarImage() === false) {
79 79
 			return true;
80 80
 		}
81 81
 
@@ -91,14 +91,14 @@  discard block
 block discarded – undo
91 91
 	public function loginName2UserName($loginName) {
92 92
 		$cacheKey = 'loginName2UserName-'.$loginName;
93 93
 		$username = $this->access->connection->getFromCache($cacheKey);
94
-		if(!is_null($username)) {
94
+		if (!is_null($username)) {
95 95
 			return $username;
96 96
 		}
97 97
 
98 98
 		try {
99 99
 			$ldapRecord = $this->getLDAPUserByLoginName($loginName);
100 100
 			$user = $this->access->userManager->get($ldapRecord['dn'][0]);
101
-			if($user instanceof OfflineUser) {
101
+			if ($user instanceof OfflineUser) {
102 102
 				// this path is not really possible, however get() is documented
103 103
 				// to return User or OfflineUser so we are very defensive here.
104 104
 				$this->access->connection->writeToCache($cacheKey, false);
@@ -134,9 +134,9 @@  discard block
 block discarded – undo
134 134
 		//find out dn of the user name
135 135
 		$attrs = $this->access->userManager->getAttributes();
136 136
 		$users = $this->access->fetchUsersByLoginName($loginName, $attrs);
137
-		if(count($users) < 1) {
138
-			throw new NotOnLDAP('No user available for the given login name on ' .
139
-				$this->access->connection->ldapHost . ':' . $this->access->connection->ldapPort);
137
+		if (count($users) < 1) {
138
+			throw new NotOnLDAP('No user available for the given login name on '.
139
+				$this->access->connection->ldapHost.':'.$this->access->connection->ldapPort);
140 140
 		}
141 141
 		return $users[0];
142 142
 	}
@@ -151,8 +151,8 @@  discard block
 block discarded – undo
151 151
 	public function checkPassword($uid, $password) {
152 152
 		try {
153 153
 			$ldapRecord = $this->getLDAPUserByLoginName($uid);
154
-		} catch(NotOnLDAP $e) {
155
-			if($this->ocConfig->getSystemValue('loglevel', Util::WARN) === Util::DEBUG) {
154
+		} catch (NotOnLDAP $e) {
155
+			if ($this->ocConfig->getSystemValue('loglevel', Util::WARN) === Util::DEBUG) {
156 156
 				\OC::$server->getLogger()->logException($e, ['app' => 'user_ldap']);
157 157
 			}
158 158
 			return false;
@@ -160,16 +160,16 @@  discard block
 block discarded – undo
160 160
 		$dn = $ldapRecord['dn'][0];
161 161
 		$user = $this->access->userManager->get($dn);
162 162
 
163
-		if(!$user instanceof User) {
163
+		if (!$user instanceof User) {
164 164
 			Util::writeLog('user_ldap',
165
-				'LDAP Login: Could not get user object for DN ' . $dn .
165
+				'LDAP Login: Could not get user object for DN '.$dn.
166 166
 				'. Maybe the LDAP entry has no set display name attribute?',
167 167
 				Util::WARN);
168 168
 			return false;
169 169
 		}
170
-		if($user->getUsername() !== false) {
170
+		if ($user->getUsername() !== false) {
171 171
 			//are the credentials OK?
172
-			if(!$this->access->areCredentialsValid($dn, $password)) {
172
+			if (!$this->access->areCredentialsValid($dn, $password)) {
173 173
 				return false;
174 174
 			}
175 175
 
@@ -192,11 +192,11 @@  discard block
 block discarded – undo
192 192
 	public function setPassword($uid, $password) {
193 193
 		$user = $this->access->userManager->get($uid);
194 194
 
195
-		if(!$user instanceof User) {
196
-			throw new \Exception('LDAP setPassword: Could not get user object for uid ' . $uid .
195
+		if (!$user instanceof User) {
196
+			throw new \Exception('LDAP setPassword: Could not get user object for uid '.$uid.
197 197
 				'. Maybe the LDAP entry has no set display name attribute?');
198 198
 		}
199
-		if($user->getUsername() !== false && $this->access->setPassword($user->getDN(), $password)) {
199
+		if ($user->getUsername() !== false && $this->access->setPassword($user->getDN(), $password)) {
200 200
 			$ldapDefaultPPolicyDN = $this->access->connection->ldapDefaultPPolicyDN;
201 201
 			$turnOnPasswordChange = $this->access->connection->turnOnPasswordChange;
202 202
 			if (!empty($ldapDefaultPPolicyDN) && (intval($turnOnPasswordChange) === 1)) {
@@ -228,18 +228,18 @@  discard block
 block discarded – undo
228 228
 
229 229
 		//check if users are cached, if so return
230 230
 		$ldap_users = $this->access->connection->getFromCache($cachekey);
231
-		if(!is_null($ldap_users)) {
231
+		if (!is_null($ldap_users)) {
232 232
 			return $ldap_users;
233 233
 		}
234 234
 
235 235
 		// if we'd pass -1 to LDAP search, we'd end up in a Protocol
236 236
 		// error. With a limit of 0, we get 0 results. So we pass null.
237
-		if($limit <= 0) {
237
+		if ($limit <= 0) {
238 238
 			$limit = null;
239 239
 		}
240 240
 		$filter = $this->access->combineFilterWithAnd(array(
241 241
 			$this->access->connection->ldapUserFilter,
242
-			$this->access->connection->ldapUserDisplayName . '=*',
242
+			$this->access->connection->ldapUserDisplayName.'=*',
243 243
 			$this->access->getFilterPartForUserSearch($search)
244 244
 		));
245 245
 
@@ -252,7 +252,7 @@  discard block
 block discarded – undo
252 252
 			$this->access->userManager->getAttributes(true),
253 253
 			$limit, $offset);
254 254
 		$ldap_users = $this->access->nextcloudUserNames($ldap_users);
255
-		Util::writeLog('user_ldap', 'getUsers: '.count($ldap_users). ' Users found', Util::DEBUG);
255
+		Util::writeLog('user_ldap', 'getUsers: '.count($ldap_users).' Users found', Util::DEBUG);
256 256
 
257 257
 		$this->access->connection->writeToCache($cachekey, $ldap_users);
258 258
 		return $ldap_users;
@@ -268,29 +268,29 @@  discard block
 block discarded – undo
268 268
 	 * @throws \OC\ServerNotAvailableException
269 269
 	 */
270 270
 	public function userExistsOnLDAP($user) {
271
-		if(is_string($user)) {
271
+		if (is_string($user)) {
272 272
 			$user = $this->access->userManager->get($user);
273 273
 		}
274
-		if(is_null($user)) {
274
+		if (is_null($user)) {
275 275
 			return false;
276 276
 		}
277 277
 
278 278
 		$dn = $user->getDN();
279 279
 		//check if user really still exists by reading its entry
280
-		if(!is_array($this->access->readAttribute($dn, '', $this->access->connection->ldapUserFilter))) {
280
+		if (!is_array($this->access->readAttribute($dn, '', $this->access->connection->ldapUserFilter))) {
281 281
 			$lcr = $this->access->connection->getConnectionResource();
282
-			if(is_null($lcr)) {
283
-				throw new \Exception('No LDAP Connection to server ' . $this->access->connection->ldapHost);
282
+			if (is_null($lcr)) {
283
+				throw new \Exception('No LDAP Connection to server '.$this->access->connection->ldapHost);
284 284
 			}
285 285
 
286 286
 			try {
287 287
 				$uuid = $this->access->getUserMapper()->getUUIDByDN($dn);
288
-				if(!$uuid) {
288
+				if (!$uuid) {
289 289
 					return false;
290 290
 				}
291 291
 				$newDn = $this->access->getUserDnByUuid($uuid);
292 292
 				//check if renamed user is still valid by reapplying the ldap filter
293
-				if(!is_array($this->access->readAttribute($newDn, '', $this->access->connection->ldapUserFilter))) {
293
+				if (!is_array($this->access->readAttribute($newDn, '', $this->access->connection->ldapUserFilter))) {
294 294
 					return false;
295 295
 				}
296 296
 				$this->access->getUserMapper()->setDNbyUUID($newDn, $uuid);
@@ -300,7 +300,7 @@  discard block
 block discarded – undo
300 300
 			}
301 301
 		}
302 302
 
303
-		if($user instanceof OfflineUser) {
303
+		if ($user instanceof OfflineUser) {
304 304
 			$user->unmark();
305 305
 		}
306 306
 
@@ -315,18 +315,18 @@  discard block
 block discarded – undo
315 315
 	 */
316 316
 	public function userExists($uid) {
317 317
 		$userExists = $this->access->connection->getFromCache('userExists'.$uid);
318
-		if(!is_null($userExists)) {
319
-			return (bool)$userExists;
318
+		if (!is_null($userExists)) {
319
+			return (bool) $userExists;
320 320
 		}
321 321
 		//getting dn, if false the user does not exist. If dn, he may be mapped only, requires more checking.
322 322
 		$user = $this->access->userManager->get($uid);
323 323
 
324
-		if(is_null($user)) {
324
+		if (is_null($user)) {
325 325
 			Util::writeLog('user_ldap', 'No DN found for '.$uid.' on '.
326 326
 				$this->access->connection->ldapHost, Util::DEBUG);
327 327
 			$this->access->connection->writeToCache('userExists'.$uid, false);
328 328
 			return false;
329
-		} else if($user instanceof OfflineUser) {
329
+		} else if ($user instanceof OfflineUser) {
330 330
 			//express check for users marked as deleted. Returning true is
331 331
 			//necessary for cleanup
332 332
 			return true;
@@ -334,7 +334,7 @@  discard block
 block discarded – undo
334 334
 
335 335
 		$result = $this->userExistsOnLDAP($user);
336 336
 		$this->access->connection->writeToCache('userExists'.$uid, $result);
337
-		if($result === true) {
337
+		if ($result === true) {
338 338
 			$user->update();
339 339
 		}
340 340
 		return $result;
@@ -348,13 +348,13 @@  discard block
 block discarded – undo
348 348
 	*/
349 349
 	public function deleteUser($uid) {
350 350
 		$marked = $this->ocConfig->getUserValue($uid, 'user_ldap', 'isDeleted', 0);
351
-		if(intval($marked) === 0) {
351
+		if (intval($marked) === 0) {
352 352
 			\OC::$server->getLogger()->notice(
353
-				'User '.$uid . ' is not marked as deleted, not cleaning up.',
353
+				'User '.$uid.' is not marked as deleted, not cleaning up.',
354 354
 				array('app' => 'user_ldap'));
355 355
 			return false;
356 356
 		}
357
-		\OC::$server->getLogger()->info('Cleaning up after user ' . $uid,
357
+		\OC::$server->getLogger()->info('Cleaning up after user '.$uid,
358 358
 			array('app' => 'user_ldap'));
359 359
 
360 360
 		//Get Home Directory out of user preferences so we can return it later,
@@ -375,27 +375,27 @@  discard block
 block discarded – undo
375 375
 	 * @throws \Exception
376 376
 	 */
377 377
 	public function getHome($uid) {
378
-		if(isset($this->homesToKill[$uid]) && !empty($this->homesToKill[$uid])) {
378
+		if (isset($this->homesToKill[$uid]) && !empty($this->homesToKill[$uid])) {
379 379
 			//a deleted user who needs some clean up
380 380
 			return $this->homesToKill[$uid];
381 381
 		}
382 382
 
383 383
 		// user Exists check required as it is not done in user proxy!
384
-		if(!$this->userExists($uid)) {
384
+		if (!$this->userExists($uid)) {
385 385
 			return false;
386 386
 		}
387 387
 
388 388
 		$cacheKey = 'getHome'.$uid;
389 389
 		$path = $this->access->connection->getFromCache($cacheKey);
390
-		if(!is_null($path)) {
390
+		if (!is_null($path)) {
391 391
 			return $path;
392 392
 		}
393 393
 
394 394
 		$user = $this->access->userManager->get($uid);
395
-		if(is_null($user) || ($user instanceof OfflineUser && !$this->userExistsOnLDAP($user->getOCName()))) {
396
-			throw new NoUserException($uid . ' is not a valid user anymore');
395
+		if (is_null($user) || ($user instanceof OfflineUser && !$this->userExistsOnLDAP($user->getOCName()))) {
396
+			throw new NoUserException($uid.' is not a valid user anymore');
397 397
 		}
398
-		if($user instanceof OfflineUser) {
398
+		if ($user instanceof OfflineUser) {
399 399
 			// apparently this user survived the userExistsOnLDAP check,
400 400
 			// we request the user instance again in order to retrieve a User
401 401
 			// instance instead
@@ -413,12 +413,12 @@  discard block
 block discarded – undo
413 413
 	 * @return string|false display name
414 414
 	 */
415 415
 	public function getDisplayName($uid) {
416
-		if(!$this->userExists($uid)) {
416
+		if (!$this->userExists($uid)) {
417 417
 			return false;
418 418
 		}
419 419
 
420 420
 		$cacheKey = 'getDisplayName'.$uid;
421
-		if(!is_null($displayName = $this->access->connection->getFromCache($cacheKey))) {
421
+		if (!is_null($displayName = $this->access->connection->getFromCache($cacheKey))) {
422 422
 			return $displayName;
423 423
 		}
424 424
 
@@ -435,10 +435,10 @@  discard block
 block discarded – undo
435 435
 			$this->access->username2dn($uid),
436 436
 			$this->access->connection->ldapUserDisplayName);
437 437
 
438
-		if($displayName && (count($displayName) > 0)) {
438
+		if ($displayName && (count($displayName) > 0)) {
439 439
 			$displayName = $displayName[0];
440 440
 
441
-			if (is_array($displayName2)){
441
+			if (is_array($displayName2)) {
442 442
 				$displayName2 = count($displayName2) > 0 ? $displayName2[0] : '';
443 443
 			}
444 444
 
@@ -467,7 +467,7 @@  discard block
 block discarded – undo
467 467
 	 */
468 468
 	public function getDisplayNames($search = '', $limit = null, $offset = null) {
469 469
 		$cacheKey = 'getDisplayNames-'.$search.'-'.$limit.'-'.$offset;
470
-		if(!is_null($displayNames = $this->access->connection->getFromCache($cacheKey))) {
470
+		if (!is_null($displayNames = $this->access->connection->getFromCache($cacheKey))) {
471 471
 			return $displayNames;
472 472
 		}
473 473
 
@@ -489,12 +489,12 @@  discard block
 block discarded – undo
489 489
 	* compared with \OC\User\Backend::CREATE_USER etc.
490 490
 	*/
491 491
 	public function implementsActions($actions) {
492
-		return (bool)((Backend::CHECK_PASSWORD
492
+		return (bool) ((Backend::CHECK_PASSWORD
493 493
 			| Backend::GET_HOME
494 494
 			| Backend::GET_DISPLAYNAME
495 495
 			| Backend::PROVIDE_AVATAR
496 496
 			| Backend::COUNT_USERS
497
-			| ((intval($this->access->connection->turnOnPasswordChange) === 1)?(Backend::SET_PASSWORD):0))
497
+			| ((intval($this->access->connection->turnOnPasswordChange) === 1) ? (Backend::SET_PASSWORD) : 0))
498 498
 			& $actions);
499 499
 	}
500 500
 
@@ -513,7 +513,7 @@  discard block
 block discarded – undo
513 513
 	public function countUsers() {
514 514
 		$filter = $this->access->getFilterForUserCount();
515 515
 		$cacheKey = 'countUsers-'.$filter;
516
-		if(!is_null($entries = $this->access->connection->getFromCache($cacheKey))) {
516
+		if (!is_null($entries = $this->access->connection->getFromCache($cacheKey))) {
517 517
 			return $entries;
518 518
 		}
519 519
 		$entries = $this->access->countUsers($filter);
@@ -525,7 +525,7 @@  discard block
 block discarded – undo
525 525
 	 * Backend name to be shown in user management
526 526
 	 * @return string the name of the backend to be shown
527 527
 	 */
528
-	public function getBackendName(){
528
+	public function getBackendName() {
529 529
 		return 'LDAP';
530 530
 	}
531 531
 	
Please login to merge, or discard this patch.
apps/user_ldap/lib/User_Proxy.php 1 patch
Indentation   +261 added lines, -261 removed lines patch added patch discarded remove patch
@@ -34,286 +34,286 @@
 block discarded – undo
34 34
 use OCP\Notification\IManager as INotificationManager;
35 35
 
36 36
 class User_Proxy extends Proxy implements \OCP\IUserBackend, \OCP\UserInterface, IUserLDAP {
37
-	private $backends = array();
38
-	private $refBackend = null;
37
+    private $backends = array();
38
+    private $refBackend = null;
39 39
 
40
-	/**
41
-	 * Constructor
42
-	 * @param array $serverConfigPrefixes array containing the config Prefixes
43
-	 */
44
-	public function __construct(array $serverConfigPrefixes, ILDAPWrapper $ldap, IConfig $ocConfig,
45
-		INotificationManager $notificationManager) {
46
-		parent::__construct($ldap);
47
-		foreach($serverConfigPrefixes as $configPrefix) {
48
-			$this->backends[$configPrefix] =
49
-				new User_LDAP($this->getAccess($configPrefix), $ocConfig, $notificationManager);
50
-			if(is_null($this->refBackend)) {
51
-				$this->refBackend = &$this->backends[$configPrefix];
52
-			}
53
-		}
54
-	}
40
+    /**
41
+     * Constructor
42
+     * @param array $serverConfigPrefixes array containing the config Prefixes
43
+     */
44
+    public function __construct(array $serverConfigPrefixes, ILDAPWrapper $ldap, IConfig $ocConfig,
45
+        INotificationManager $notificationManager) {
46
+        parent::__construct($ldap);
47
+        foreach($serverConfigPrefixes as $configPrefix) {
48
+            $this->backends[$configPrefix] =
49
+                new User_LDAP($this->getAccess($configPrefix), $ocConfig, $notificationManager);
50
+            if(is_null($this->refBackend)) {
51
+                $this->refBackend = &$this->backends[$configPrefix];
52
+            }
53
+        }
54
+    }
55 55
 
56
-	/**
57
-	 * Tries the backends one after the other until a positive result is returned from the specified method
58
-	 * @param string $uid the uid connected to the request
59
-	 * @param string $method the method of the user backend that shall be called
60
-	 * @param array $parameters an array of parameters to be passed
61
-	 * @return mixed the result of the method or false
62
-	 */
63
-	protected function walkBackends($uid, $method, $parameters) {
64
-		$cacheKey = $this->getUserCacheKey($uid);
65
-		foreach($this->backends as $configPrefix => $backend) {
66
-			$instance = $backend;
67
-			if(!method_exists($instance, $method)
68
-				&& method_exists($this->getAccess($configPrefix), $method)) {
69
-				$instance = $this->getAccess($configPrefix);
70
-			}
71
-			if($result = call_user_func_array(array($instance, $method), $parameters)) {
72
-				$this->writeToCache($cacheKey, $configPrefix);
73
-				return $result;
74
-			}
75
-		}
76
-		return false;
77
-	}
56
+    /**
57
+     * Tries the backends one after the other until a positive result is returned from the specified method
58
+     * @param string $uid the uid connected to the request
59
+     * @param string $method the method of the user backend that shall be called
60
+     * @param array $parameters an array of parameters to be passed
61
+     * @return mixed the result of the method or false
62
+     */
63
+    protected function walkBackends($uid, $method, $parameters) {
64
+        $cacheKey = $this->getUserCacheKey($uid);
65
+        foreach($this->backends as $configPrefix => $backend) {
66
+            $instance = $backend;
67
+            if(!method_exists($instance, $method)
68
+                && method_exists($this->getAccess($configPrefix), $method)) {
69
+                $instance = $this->getAccess($configPrefix);
70
+            }
71
+            if($result = call_user_func_array(array($instance, $method), $parameters)) {
72
+                $this->writeToCache($cacheKey, $configPrefix);
73
+                return $result;
74
+            }
75
+        }
76
+        return false;
77
+    }
78 78
 
79
-	/**
80
-	 * Asks the backend connected to the server that supposely takes care of the uid from the request.
81
-	 * @param string $uid the uid connected to the request
82
-	 * @param string $method the method of the user backend that shall be called
83
-	 * @param array $parameters an array of parameters to be passed
84
-	 * @param mixed $passOnWhen the result matches this variable
85
-	 * @return mixed the result of the method or false
86
-	 */
87
-	protected function callOnLastSeenOn($uid, $method, $parameters, $passOnWhen) {
88
-		$cacheKey = $this->getUserCacheKey($uid);
89
-		$prefix = $this->getFromCache($cacheKey);
90
-		//in case the uid has been found in the past, try this stored connection first
91
-		if(!is_null($prefix)) {
92
-			if(isset($this->backends[$prefix])) {
93
-				$instance = $this->backends[$prefix];
94
-				if(!method_exists($instance, $method)
95
-					&& method_exists($this->getAccess($prefix), $method)) {
96
-					$instance = $this->getAccess($prefix);
97
-				}
98
-				$result = call_user_func_array(array($instance, $method), $parameters);
99
-				if($result === $passOnWhen) {
100
-					//not found here, reset cache to null if user vanished
101
-					//because sometimes methods return false with a reason
102
-					$userExists = call_user_func_array(
103
-						array($this->backends[$prefix], 'userExists'),
104
-						array($uid)
105
-					);
106
-					if(!$userExists) {
107
-						$this->writeToCache($cacheKey, null);
108
-					}
109
-				}
110
-				return $result;
111
-			}
112
-		}
113
-		return false;
114
-	}
79
+    /**
80
+     * Asks the backend connected to the server that supposely takes care of the uid from the request.
81
+     * @param string $uid the uid connected to the request
82
+     * @param string $method the method of the user backend that shall be called
83
+     * @param array $parameters an array of parameters to be passed
84
+     * @param mixed $passOnWhen the result matches this variable
85
+     * @return mixed the result of the method or false
86
+     */
87
+    protected function callOnLastSeenOn($uid, $method, $parameters, $passOnWhen) {
88
+        $cacheKey = $this->getUserCacheKey($uid);
89
+        $prefix = $this->getFromCache($cacheKey);
90
+        //in case the uid has been found in the past, try this stored connection first
91
+        if(!is_null($prefix)) {
92
+            if(isset($this->backends[$prefix])) {
93
+                $instance = $this->backends[$prefix];
94
+                if(!method_exists($instance, $method)
95
+                    && method_exists($this->getAccess($prefix), $method)) {
96
+                    $instance = $this->getAccess($prefix);
97
+                }
98
+                $result = call_user_func_array(array($instance, $method), $parameters);
99
+                if($result === $passOnWhen) {
100
+                    //not found here, reset cache to null if user vanished
101
+                    //because sometimes methods return false with a reason
102
+                    $userExists = call_user_func_array(
103
+                        array($this->backends[$prefix], 'userExists'),
104
+                        array($uid)
105
+                    );
106
+                    if(!$userExists) {
107
+                        $this->writeToCache($cacheKey, null);
108
+                    }
109
+                }
110
+                return $result;
111
+            }
112
+        }
113
+        return false;
114
+    }
115 115
 
116
-	/**
117
-	 * Check if backend implements actions
118
-	 * @param int $actions bitwise-or'ed actions
119
-	 * @return boolean
120
-	 *
121
-	 * Returns the supported actions as int to be
122
-	 * compared with \OC\User\Backend::CREATE_USER etc.
123
-	 */
124
-	public function implementsActions($actions) {
125
-		//it's the same across all our user backends obviously
126
-		return $this->refBackend->implementsActions($actions);
127
-	}
116
+    /**
117
+     * Check if backend implements actions
118
+     * @param int $actions bitwise-or'ed actions
119
+     * @return boolean
120
+     *
121
+     * Returns the supported actions as int to be
122
+     * compared with \OC\User\Backend::CREATE_USER etc.
123
+     */
124
+    public function implementsActions($actions) {
125
+        //it's the same across all our user backends obviously
126
+        return $this->refBackend->implementsActions($actions);
127
+    }
128 128
 
129
-	/**
130
-	 * Backend name to be shown in user management
131
-	 * @return string the name of the backend to be shown
132
-	 */
133
-	public function getBackendName() {
134
-		return $this->refBackend->getBackendName();
135
-	}
129
+    /**
130
+     * Backend name to be shown in user management
131
+     * @return string the name of the backend to be shown
132
+     */
133
+    public function getBackendName() {
134
+        return $this->refBackend->getBackendName();
135
+    }
136 136
 
137
-	/**
138
-	 * Get a list of all users
139
-	 *
140
-	 * @param string $search
141
-	 * @param null|int $limit
142
-	 * @param null|int $offset
143
-	 * @return string[] an array of all uids
144
-	 */
145
-	public function getUsers($search = '', $limit = 10, $offset = 0) {
146
-		//we do it just as the /OC_User implementation: do not play around with limit and offset but ask all backends
147
-		$users = array();
148
-		foreach($this->backends as $backend) {
149
-			$backendUsers = $backend->getUsers($search, $limit, $offset);
150
-			if (is_array($backendUsers)) {
151
-				$users = array_merge($users, $backendUsers);
152
-			}
153
-		}
154
-		return $users;
155
-	}
137
+    /**
138
+     * Get a list of all users
139
+     *
140
+     * @param string $search
141
+     * @param null|int $limit
142
+     * @param null|int $offset
143
+     * @return string[] an array of all uids
144
+     */
145
+    public function getUsers($search = '', $limit = 10, $offset = 0) {
146
+        //we do it just as the /OC_User implementation: do not play around with limit and offset but ask all backends
147
+        $users = array();
148
+        foreach($this->backends as $backend) {
149
+            $backendUsers = $backend->getUsers($search, $limit, $offset);
150
+            if (is_array($backendUsers)) {
151
+                $users = array_merge($users, $backendUsers);
152
+            }
153
+        }
154
+        return $users;
155
+    }
156 156
 
157
-	/**
158
-	 * check if a user exists
159
-	 * @param string $uid the username
160
-	 * @return boolean
161
-	 */
162
-	public function userExists($uid) {
163
-		return $this->handleRequest($uid, 'userExists', array($uid));
164
-	}
157
+    /**
158
+     * check if a user exists
159
+     * @param string $uid the username
160
+     * @return boolean
161
+     */
162
+    public function userExists($uid) {
163
+        return $this->handleRequest($uid, 'userExists', array($uid));
164
+    }
165 165
 
166
-	/**
167
-	 * check if a user exists on LDAP
168
-	 * @param string|\OCA\User_LDAP\User\User $user either the Nextcloud user
169
-	 * name or an instance of that user
170
-	 * @return boolean
171
-	 */
172
-	public function userExistsOnLDAP($user) {
173
-		$id = ($user instanceof User) ? $user->getUsername() : $user;
174
-		return $this->handleRequest($id, 'userExistsOnLDAP', array($user));
175
-	}
166
+    /**
167
+     * check if a user exists on LDAP
168
+     * @param string|\OCA\User_LDAP\User\User $user either the Nextcloud user
169
+     * name or an instance of that user
170
+     * @return boolean
171
+     */
172
+    public function userExistsOnLDAP($user) {
173
+        $id = ($user instanceof User) ? $user->getUsername() : $user;
174
+        return $this->handleRequest($id, 'userExistsOnLDAP', array($user));
175
+    }
176 176
 
177
-	/**
178
-	 * Check if the password is correct
179
-	 * @param string $uid The username
180
-	 * @param string $password The password
181
-	 * @return bool
182
-	 *
183
-	 * Check if the password is correct without logging in the user
184
-	 */
185
-	public function checkPassword($uid, $password) {
186
-		return $this->handleRequest($uid, 'checkPassword', array($uid, $password));
187
-	}
177
+    /**
178
+     * Check if the password is correct
179
+     * @param string $uid The username
180
+     * @param string $password The password
181
+     * @return bool
182
+     *
183
+     * Check if the password is correct without logging in the user
184
+     */
185
+    public function checkPassword($uid, $password) {
186
+        return $this->handleRequest($uid, 'checkPassword', array($uid, $password));
187
+    }
188 188
 
189
-	/**
190
-	 * returns the username for the given login name, if available
191
-	 *
192
-	 * @param string $loginName
193
-	 * @return string|false
194
-	 */
195
-	public function loginName2UserName($loginName) {
196
-		$id = 'LOGINNAME,' . $loginName;
197
-		return $this->handleRequest($id, 'loginName2UserName', array($loginName));
198
-	}
189
+    /**
190
+     * returns the username for the given login name, if available
191
+     *
192
+     * @param string $loginName
193
+     * @return string|false
194
+     */
195
+    public function loginName2UserName($loginName) {
196
+        $id = 'LOGINNAME,' . $loginName;
197
+        return $this->handleRequest($id, 'loginName2UserName', array($loginName));
198
+    }
199 199
 	
200
-	/**
201
-	 * returns the username for the given LDAP DN, if available
202
-	 *
203
-	 * @param string $dn
204
-	 * @return string|false with the username
205
-	 */
206
-	public function dn2UserName($dn) {
207
-		$id = 'DN,' . $dn;
208
-		return $this->handleRequest($id, 'dn2UserName', array($dn));
209
-	}
200
+    /**
201
+     * returns the username for the given LDAP DN, if available
202
+     *
203
+     * @param string $dn
204
+     * @return string|false with the username
205
+     */
206
+    public function dn2UserName($dn) {
207
+        $id = 'DN,' . $dn;
208
+        return $this->handleRequest($id, 'dn2UserName', array($dn));
209
+    }
210 210
 
211
-	/**
212
-	 * get the user's home directory
213
-	 * @param string $uid the username
214
-	 * @return boolean
215
-	 */
216
-	public function getHome($uid) {
217
-		return $this->handleRequest($uid, 'getHome', array($uid));
218
-	}
211
+    /**
212
+     * get the user's home directory
213
+     * @param string $uid the username
214
+     * @return boolean
215
+     */
216
+    public function getHome($uid) {
217
+        return $this->handleRequest($uid, 'getHome', array($uid));
218
+    }
219 219
 
220
-	/**
221
-	 * get display name of the user
222
-	 * @param string $uid user ID of the user
223
-	 * @return string display name
224
-	 */
225
-	public function getDisplayName($uid) {
226
-		return $this->handleRequest($uid, 'getDisplayName', array($uid));
227
-	}
220
+    /**
221
+     * get display name of the user
222
+     * @param string $uid user ID of the user
223
+     * @return string display name
224
+     */
225
+    public function getDisplayName($uid) {
226
+        return $this->handleRequest($uid, 'getDisplayName', array($uid));
227
+    }
228 228
 
229
-	/**
230
-	 * checks whether the user is allowed to change his avatar in Nextcloud
231
-	 * @param string $uid the Nextcloud user name
232
-	 * @return boolean either the user can or cannot
233
-	 */
234
-	public function canChangeAvatar($uid) {
235
-		return $this->handleRequest($uid, 'canChangeAvatar', array($uid), true);
236
-	}
229
+    /**
230
+     * checks whether the user is allowed to change his avatar in Nextcloud
231
+     * @param string $uid the Nextcloud user name
232
+     * @return boolean either the user can or cannot
233
+     */
234
+    public function canChangeAvatar($uid) {
235
+        return $this->handleRequest($uid, 'canChangeAvatar', array($uid), true);
236
+    }
237 237
 
238
-	/**
239
-	 * Get a list of all display names and user ids.
240
-	 * @param string $search
241
-	 * @param string|null $limit
242
-	 * @param string|null $offset
243
-	 * @return array an array of all displayNames (value) and the corresponding uids (key)
244
-	 */
245
-	public function getDisplayNames($search = '', $limit = null, $offset = null) {
246
-		//we do it just as the /OC_User implementation: do not play around with limit and offset but ask all backends
247
-		$users = array();
248
-		foreach($this->backends as $backend) {
249
-			$backendUsers = $backend->getDisplayNames($search, $limit, $offset);
250
-			if (is_array($backendUsers)) {
251
-				$users = $users + $backendUsers;
252
-			}
253
-		}
254
-		return $users;
255
-	}
238
+    /**
239
+     * Get a list of all display names and user ids.
240
+     * @param string $search
241
+     * @param string|null $limit
242
+     * @param string|null $offset
243
+     * @return array an array of all displayNames (value) and the corresponding uids (key)
244
+     */
245
+    public function getDisplayNames($search = '', $limit = null, $offset = null) {
246
+        //we do it just as the /OC_User implementation: do not play around with limit and offset but ask all backends
247
+        $users = array();
248
+        foreach($this->backends as $backend) {
249
+            $backendUsers = $backend->getDisplayNames($search, $limit, $offset);
250
+            if (is_array($backendUsers)) {
251
+                $users = $users + $backendUsers;
252
+            }
253
+        }
254
+        return $users;
255
+    }
256 256
 
257
-	/**
258
-	 * delete a user
259
-	 * @param string $uid The username of the user to delete
260
-	 * @return bool
261
-	 *
262
-	 * Deletes a user
263
-	 */
264
-	public function deleteUser($uid) {
265
-		return $this->handleRequest($uid, 'deleteUser', array($uid));
266
-	}
257
+    /**
258
+     * delete a user
259
+     * @param string $uid The username of the user to delete
260
+     * @return bool
261
+     *
262
+     * Deletes a user
263
+     */
264
+    public function deleteUser($uid) {
265
+        return $this->handleRequest($uid, 'deleteUser', array($uid));
266
+    }
267 267
 	
268
-	/**
269
-	 * Set password
270
-	 * @param string $uid The username
271
-	 * @param string $password The new password
272
-	 * @return bool
273
-	 *
274
-	 */
275
-	public function setPassword($uid, $password) {
276
-		return $this->handleRequest($uid, 'setPassword', array($uid, $password));
277
-	}
268
+    /**
269
+     * Set password
270
+     * @param string $uid The username
271
+     * @param string $password The new password
272
+     * @return bool
273
+     *
274
+     */
275
+    public function setPassword($uid, $password) {
276
+        return $this->handleRequest($uid, 'setPassword', array($uid, $password));
277
+    }
278 278
 
279
-	/**
280
-	 * @return bool
281
-	 */
282
-	public function hasUserListings() {
283
-		return $this->refBackend->hasUserListings();
284
-	}
279
+    /**
280
+     * @return bool
281
+     */
282
+    public function hasUserListings() {
283
+        return $this->refBackend->hasUserListings();
284
+    }
285 285
 
286
-	/**
287
-	 * Count the number of users
288
-	 * @return int|bool
289
-	 */
290
-	public function countUsers() {
291
-		$users = false;
292
-		foreach($this->backends as $backend) {
293
-			$backendUsers = $backend->countUsers();
294
-			if ($backendUsers !== false) {
295
-				$users += $backendUsers;
296
-			}
297
-		}
298
-		return $users;
299
-	}
286
+    /**
287
+     * Count the number of users
288
+     * @return int|bool
289
+     */
290
+    public function countUsers() {
291
+        $users = false;
292
+        foreach($this->backends as $backend) {
293
+            $backendUsers = $backend->countUsers();
294
+            if ($backendUsers !== false) {
295
+                $users += $backendUsers;
296
+            }
297
+        }
298
+        return $users;
299
+    }
300 300
 
301
-	/**
302
-	 * Return access for LDAP interaction.
303
-	 * @param string $uid
304
-	 * @return Access instance of Access for LDAP interaction
305
-	 */
306
-	public function getLDAPAccess($uid) {
307
-		return $this->handleRequest($uid, 'getLDAPAccess', array($uid));
308
-	}
301
+    /**
302
+     * Return access for LDAP interaction.
303
+     * @param string $uid
304
+     * @return Access instance of Access for LDAP interaction
305
+     */
306
+    public function getLDAPAccess($uid) {
307
+        return $this->handleRequest($uid, 'getLDAPAccess', array($uid));
308
+    }
309 309
 	
310
-	/**
311
-	 * Return a new LDAP connection for the specified user.
312
-	 * The connection needs to be closed manually.
313
-	 * @param string $uid
314
-	 * @return resource of the LDAP connection
315
-	 */
316
-	public function getNewLDAPConnection($uid) {
317
-		return $this->handleRequest($uid, 'getNewLDAPConnection', array($uid));
318
-	}
310
+    /**
311
+     * Return a new LDAP connection for the specified user.
312
+     * The connection needs to be closed manually.
313
+     * @param string $uid
314
+     * @return resource of the LDAP connection
315
+     */
316
+    public function getNewLDAPConnection($uid) {
317
+        return $this->handleRequest($uid, 'getNewLDAPConnection', array($uid));
318
+    }
319 319
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/Group_Proxy.php 1 patch
Indentation   +178 added lines, -178 removed lines patch added patch discarded remove patch
@@ -27,182 +27,182 @@
 block discarded – undo
27 27
 namespace OCA\User_LDAP;
28 28
 
29 29
 class Group_Proxy extends Proxy implements \OCP\GroupInterface {
30
-	private $backends = array();
31
-	private $refBackend = null;
32
-
33
-	/**
34
-	 * Constructor
35
-	 * @param string[] $serverConfigPrefixes array containing the config Prefixes
36
-	 */
37
-	public function __construct($serverConfigPrefixes, ILDAPWrapper $ldap) {
38
-		parent::__construct($ldap);
39
-		foreach($serverConfigPrefixes as $configPrefix) {
40
-			$this->backends[$configPrefix] =
41
-				new \OCA\User_LDAP\Group_LDAP($this->getAccess($configPrefix));
42
-			if(is_null($this->refBackend)) {
43
-				$this->refBackend = &$this->backends[$configPrefix];
44
-			}
45
-		}
46
-	}
47
-
48
-	/**
49
-	 * Tries the backends one after the other until a positive result is returned from the specified method
50
-	 * @param string $gid the gid connected to the request
51
-	 * @param string $method the method of the group backend that shall be called
52
-	 * @param array $parameters an array of parameters to be passed
53
-	 * @return mixed, the result of the method or false
54
-	 */
55
-	protected function walkBackends($gid, $method, $parameters) {
56
-		$cacheKey = $this->getGroupCacheKey($gid);
57
-		foreach($this->backends as $configPrefix => $backend) {
58
-			if($result = call_user_func_array(array($backend, $method), $parameters)) {
59
-				$this->writeToCache($cacheKey, $configPrefix);
60
-				return $result;
61
-			}
62
-		}
63
-		return false;
64
-	}
65
-
66
-	/**
67
-	 * Asks the backend connected to the server that supposely takes care of the gid from the request.
68
-	 * @param string $gid the gid connected to the request
69
-	 * @param string $method the method of the group backend that shall be called
70
-	 * @param array $parameters an array of parameters to be passed
71
-	 * @param mixed $passOnWhen the result matches this variable
72
-	 * @return mixed, the result of the method or false
73
-	 */
74
-	protected function callOnLastSeenOn($gid, $method, $parameters, $passOnWhen) {
75
-		$cacheKey = $this->getGroupCacheKey($gid);;
76
-		$prefix = $this->getFromCache($cacheKey);
77
-		//in case the uid has been found in the past, try this stored connection first
78
-		if(!is_null($prefix)) {
79
-			if(isset($this->backends[$prefix])) {
80
-				$result = call_user_func_array(array($this->backends[$prefix], $method), $parameters);
81
-				if($result === $passOnWhen) {
82
-					//not found here, reset cache to null if group vanished
83
-					//because sometimes methods return false with a reason
84
-					$groupExists = call_user_func_array(
85
-						array($this->backends[$prefix], 'groupExists'),
86
-						array($gid)
87
-					);
88
-					if(!$groupExists) {
89
-						$this->writeToCache($cacheKey, null);
90
-					}
91
-				}
92
-				return $result;
93
-			}
94
-		}
95
-		return false;
96
-	}
97
-
98
-	/**
99
-	 * is user in group?
100
-	 * @param string $uid uid of the user
101
-	 * @param string $gid gid of the group
102
-	 * @return bool
103
-	 *
104
-	 * Checks whether the user is member of a group or not.
105
-	 */
106
-	public function inGroup($uid, $gid) {
107
-		return $this->handleRequest($gid, 'inGroup', array($uid, $gid));
108
-	}
109
-
110
-	/**
111
-	 * Get all groups a user belongs to
112
-	 * @param string $uid Name of the user
113
-	 * @return string[] with group names
114
-	 *
115
-	 * This function fetches all groups a user belongs to. It does not check
116
-	 * if the user exists at all.
117
-	 */
118
-	public function getUserGroups($uid) {
119
-		$groups = array();
120
-
121
-		foreach($this->backends as $backend) {
122
-			$backendGroups = $backend->getUserGroups($uid);
123
-			if (is_array($backendGroups)) {
124
-				$groups = array_merge($groups, $backendGroups);
125
-			}
126
-		}
127
-
128
-		return $groups;
129
-	}
130
-
131
-	/**
132
-	 * get a list of all users in a group
133
-	 * @return string[] with user ids
134
-	 */
135
-	public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) {
136
-		$users = array();
137
-
138
-		foreach($this->backends as $backend) {
139
-			$backendUsers = $backend->usersInGroup($gid, $search, $limit, $offset);
140
-			if (is_array($backendUsers)) {
141
-				$users = array_merge($users, $backendUsers);
142
-			}
143
-		}
144
-
145
-		return $users;
146
-	}
147
-
148
-	/**
149
-	 * returns the number of users in a group, who match the search term
150
-	 * @param string $gid the internal group name
151
-	 * @param string $search optional, a search string
152
-	 * @return int|bool
153
-	 */
154
-	public function countUsersInGroup($gid, $search = '') {
155
-		return $this->handleRequest(
156
-			$gid, 'countUsersInGroup', array($gid, $search));
157
-	}
158
-
159
-	/**
160
-	 * get a list of all groups
161
-	 * @return string[] with group names
162
-	 *
163
-	 * Returns a list with all groups
164
-	 */
165
-	public function getGroups($search = '', $limit = -1, $offset = 0) {
166
-		$groups = array();
167
-
168
-		foreach($this->backends as $backend) {
169
-			$backendGroups = $backend->getGroups($search, $limit, $offset);
170
-			if (is_array($backendGroups)) {
171
-				$groups = array_merge($groups, $backendGroups);
172
-			}
173
-		}
174
-
175
-		return $groups;
176
-	}
177
-
178
-	/**
179
-	 * check if a group exists
180
-	 * @param string $gid
181
-	 * @return bool
182
-	 */
183
-	public function groupExists($gid) {
184
-		return $this->handleRequest($gid, 'groupExists', array($gid));
185
-	}
186
-
187
-	/**
188
-	 * Check if backend implements actions
189
-	 * @param int $actions bitwise-or'ed actions
190
-	 * @return boolean
191
-	 *
192
-	 * Returns the supported actions as int to be
193
-	 * compared with \OC\User\Backend::CREATE_USER etc.
194
-	 */
195
-	public function implementsActions($actions) {
196
-		//it's the same across all our user backends obviously
197
-		return $this->refBackend->implementsActions($actions);
198
-	}
199
-
200
-	/**
201
-	 * Return access for LDAP interaction.
202
-	 * @param string $gid
203
-	 * @return Access instance of Access for LDAP interaction
204
-	 */
205
-	public function getLDAPAccess($gid) {
206
-		return $this->handleRequest($gid, 'getLDAPAccess', []);
207
-	}
30
+    private $backends = array();
31
+    private $refBackend = null;
32
+
33
+    /**
34
+     * Constructor
35
+     * @param string[] $serverConfigPrefixes array containing the config Prefixes
36
+     */
37
+    public function __construct($serverConfigPrefixes, ILDAPWrapper $ldap) {
38
+        parent::__construct($ldap);
39
+        foreach($serverConfigPrefixes as $configPrefix) {
40
+            $this->backends[$configPrefix] =
41
+                new \OCA\User_LDAP\Group_LDAP($this->getAccess($configPrefix));
42
+            if(is_null($this->refBackend)) {
43
+                $this->refBackend = &$this->backends[$configPrefix];
44
+            }
45
+        }
46
+    }
47
+
48
+    /**
49
+     * Tries the backends one after the other until a positive result is returned from the specified method
50
+     * @param string $gid the gid connected to the request
51
+     * @param string $method the method of the group backend that shall be called
52
+     * @param array $parameters an array of parameters to be passed
53
+     * @return mixed, the result of the method or false
54
+     */
55
+    protected function walkBackends($gid, $method, $parameters) {
56
+        $cacheKey = $this->getGroupCacheKey($gid);
57
+        foreach($this->backends as $configPrefix => $backend) {
58
+            if($result = call_user_func_array(array($backend, $method), $parameters)) {
59
+                $this->writeToCache($cacheKey, $configPrefix);
60
+                return $result;
61
+            }
62
+        }
63
+        return false;
64
+    }
65
+
66
+    /**
67
+     * Asks the backend connected to the server that supposely takes care of the gid from the request.
68
+     * @param string $gid the gid connected to the request
69
+     * @param string $method the method of the group backend that shall be called
70
+     * @param array $parameters an array of parameters to be passed
71
+     * @param mixed $passOnWhen the result matches this variable
72
+     * @return mixed, the result of the method or false
73
+     */
74
+    protected function callOnLastSeenOn($gid, $method, $parameters, $passOnWhen) {
75
+        $cacheKey = $this->getGroupCacheKey($gid);;
76
+        $prefix = $this->getFromCache($cacheKey);
77
+        //in case the uid has been found in the past, try this stored connection first
78
+        if(!is_null($prefix)) {
79
+            if(isset($this->backends[$prefix])) {
80
+                $result = call_user_func_array(array($this->backends[$prefix], $method), $parameters);
81
+                if($result === $passOnWhen) {
82
+                    //not found here, reset cache to null if group vanished
83
+                    //because sometimes methods return false with a reason
84
+                    $groupExists = call_user_func_array(
85
+                        array($this->backends[$prefix], 'groupExists'),
86
+                        array($gid)
87
+                    );
88
+                    if(!$groupExists) {
89
+                        $this->writeToCache($cacheKey, null);
90
+                    }
91
+                }
92
+                return $result;
93
+            }
94
+        }
95
+        return false;
96
+    }
97
+
98
+    /**
99
+     * is user in group?
100
+     * @param string $uid uid of the user
101
+     * @param string $gid gid of the group
102
+     * @return bool
103
+     *
104
+     * Checks whether the user is member of a group or not.
105
+     */
106
+    public function inGroup($uid, $gid) {
107
+        return $this->handleRequest($gid, 'inGroup', array($uid, $gid));
108
+    }
109
+
110
+    /**
111
+     * Get all groups a user belongs to
112
+     * @param string $uid Name of the user
113
+     * @return string[] with group names
114
+     *
115
+     * This function fetches all groups a user belongs to. It does not check
116
+     * if the user exists at all.
117
+     */
118
+    public function getUserGroups($uid) {
119
+        $groups = array();
120
+
121
+        foreach($this->backends as $backend) {
122
+            $backendGroups = $backend->getUserGroups($uid);
123
+            if (is_array($backendGroups)) {
124
+                $groups = array_merge($groups, $backendGroups);
125
+            }
126
+        }
127
+
128
+        return $groups;
129
+    }
130
+
131
+    /**
132
+     * get a list of all users in a group
133
+     * @return string[] with user ids
134
+     */
135
+    public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) {
136
+        $users = array();
137
+
138
+        foreach($this->backends as $backend) {
139
+            $backendUsers = $backend->usersInGroup($gid, $search, $limit, $offset);
140
+            if (is_array($backendUsers)) {
141
+                $users = array_merge($users, $backendUsers);
142
+            }
143
+        }
144
+
145
+        return $users;
146
+    }
147
+
148
+    /**
149
+     * returns the number of users in a group, who match the search term
150
+     * @param string $gid the internal group name
151
+     * @param string $search optional, a search string
152
+     * @return int|bool
153
+     */
154
+    public function countUsersInGroup($gid, $search = '') {
155
+        return $this->handleRequest(
156
+            $gid, 'countUsersInGroup', array($gid, $search));
157
+    }
158
+
159
+    /**
160
+     * get a list of all groups
161
+     * @return string[] with group names
162
+     *
163
+     * Returns a list with all groups
164
+     */
165
+    public function getGroups($search = '', $limit = -1, $offset = 0) {
166
+        $groups = array();
167
+
168
+        foreach($this->backends as $backend) {
169
+            $backendGroups = $backend->getGroups($search, $limit, $offset);
170
+            if (is_array($backendGroups)) {
171
+                $groups = array_merge($groups, $backendGroups);
172
+            }
173
+        }
174
+
175
+        return $groups;
176
+    }
177
+
178
+    /**
179
+     * check if a group exists
180
+     * @param string $gid
181
+     * @return bool
182
+     */
183
+    public function groupExists($gid) {
184
+        return $this->handleRequest($gid, 'groupExists', array($gid));
185
+    }
186
+
187
+    /**
188
+     * Check if backend implements actions
189
+     * @param int $actions bitwise-or'ed actions
190
+     * @return boolean
191
+     *
192
+     * Returns the supported actions as int to be
193
+     * compared with \OC\User\Backend::CREATE_USER etc.
194
+     */
195
+    public function implementsActions($actions) {
196
+        //it's the same across all our user backends obviously
197
+        return $this->refBackend->implementsActions($actions);
198
+    }
199
+
200
+    /**
201
+     * Return access for LDAP interaction.
202
+     * @param string $gid
203
+     * @return Access instance of Access for LDAP interaction
204
+     */
205
+    public function getLDAPAccess($gid) {
206
+        return $this->handleRequest($gid, 'getLDAPAccess', []);
207
+    }
208 208
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/Group_LDAP.php 2 patches
Indentation   +1039 added lines, -1039 removed lines patch added patch discarded remove patch
@@ -41,1043 +41,1043 @@
 block discarded – undo
41 41
 use OC\Cache\CappedMemoryCache;
42 42
 
43 43
 class Group_LDAP extends BackendUtility implements \OCP\GroupInterface {
44
-	protected $enabled = false;
45
-
46
-	/**
47
-	 * @var string[] $cachedGroupMembers array of users with gid as key
48
-	 */
49
-	protected $cachedGroupMembers;
50
-
51
-	/**
52
-	 * @var string[] $cachedGroupsByMember array of groups with uid as key
53
-	 */
54
-	protected $cachedGroupsByMember;
55
-
56
-	public function __construct(Access $access) {
57
-		parent::__construct($access);
58
-		$filter = $this->access->connection->ldapGroupFilter;
59
-		$gassoc = $this->access->connection->ldapGroupMemberAssocAttr;
60
-		if(!empty($filter) && !empty($gassoc)) {
61
-			$this->enabled = true;
62
-		}
63
-
64
-		$this->cachedGroupMembers = new CappedMemoryCache();
65
-		$this->cachedGroupsByMember = new CappedMemoryCache();
66
-	}
67
-
68
-	/**
69
-	 * is user in group?
70
-	 * @param string $uid uid of the user
71
-	 * @param string $gid gid of the group
72
-	 * @return bool
73
-	 *
74
-	 * Checks whether the user is member of a group or not.
75
-	 */
76
-	public function inGroup($uid, $gid) {
77
-		if(!$this->enabled) {
78
-			return false;
79
-		}
80
-		$cacheKey = 'inGroup'.$uid.':'.$gid;
81
-		$inGroup = $this->access->connection->getFromCache($cacheKey);
82
-		if(!is_null($inGroup)) {
83
-			return (bool)$inGroup;
84
-		}
85
-
86
-		$userDN = $this->access->username2dn($uid);
87
-
88
-		if(isset($this->cachedGroupMembers[$gid])) {
89
-			$isInGroup = in_array($userDN, $this->cachedGroupMembers[$gid]);
90
-			return $isInGroup;
91
-		}
92
-
93
-		$cacheKeyMembers = 'inGroup-members:'.$gid;
94
-		$members = $this->access->connection->getFromCache($cacheKeyMembers);
95
-		if(!is_null($members)) {
96
-			$this->cachedGroupMembers[$gid] = $members;
97
-			$isInGroup = in_array($userDN, $members);
98
-			$this->access->connection->writeToCache($cacheKey, $isInGroup);
99
-			return $isInGroup;
100
-		}
101
-
102
-		$groupDN = $this->access->groupname2dn($gid);
103
-		// just in case
104
-		if(!$groupDN || !$userDN) {
105
-			$this->access->connection->writeToCache($cacheKey, false);
106
-			return false;
107
-		}
108
-
109
-		//check primary group first
110
-		if($gid === $this->getUserPrimaryGroup($userDN)) {
111
-			$this->access->connection->writeToCache($cacheKey, true);
112
-			return true;
113
-		}
114
-
115
-		//usually, LDAP attributes are said to be case insensitive. But there are exceptions of course.
116
-		$members = $this->_groupMembers($groupDN);
117
-		$members = array_keys($members); // uids are returned as keys
118
-		if(!is_array($members) || count($members) === 0) {
119
-			$this->access->connection->writeToCache($cacheKey, false);
120
-			return false;
121
-		}
122
-
123
-		//extra work if we don't get back user DNs
124
-		if(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') {
125
-			$dns = array();
126
-			$filterParts = array();
127
-			$bytes = 0;
128
-			foreach($members as $mid) {
129
-				$filter = str_replace('%uid', $mid, $this->access->connection->ldapLoginFilter);
130
-				$filterParts[] = $filter;
131
-				$bytes += strlen($filter);
132
-				if($bytes >= 9000000) {
133
-					// AD has a default input buffer of 10 MB, we do not want
134
-					// to take even the chance to exceed it
135
-					$filter = $this->access->combineFilterWithOr($filterParts);
136
-					$bytes = 0;
137
-					$filterParts = array();
138
-					$users = $this->access->fetchListOfUsers($filter, 'dn', count($filterParts));
139
-					$dns = array_merge($dns, $users);
140
-				}
141
-			}
142
-			if(count($filterParts) > 0) {
143
-				$filter = $this->access->combineFilterWithOr($filterParts);
144
-				$users = $this->access->fetchListOfUsers($filter, 'dn', count($filterParts));
145
-				$dns = array_merge($dns, $users);
146
-			}
147
-			$members = $dns;
148
-		}
149
-
150
-		$isInGroup = in_array($userDN, $members);
151
-		$this->access->connection->writeToCache($cacheKey, $isInGroup);
152
-		$this->access->connection->writeToCache($cacheKeyMembers, $members);
153
-		$this->cachedGroupMembers[$gid] = $members;
154
-
155
-		return $isInGroup;
156
-	}
157
-
158
-	/**
159
-	 * @param string $dnGroup
160
-	 * @return array
161
-	 *
162
-	 * For a group that has user membership defined by an LDAP search url attribute returns the users
163
-	 * that match the search url otherwise returns an empty array.
164
-	 */
165
-	public function getDynamicGroupMembers($dnGroup) {
166
-		$dynamicGroupMemberURL = strtolower($this->access->connection->ldapDynamicGroupMemberURL);
167
-
168
-		if (empty($dynamicGroupMemberURL)) {
169
-			return array();
170
-		}
171
-
172
-		$dynamicMembers = array();
173
-		$memberURLs = $this->access->readAttribute(
174
-			$dnGroup,
175
-			$dynamicGroupMemberURL,
176
-			$this->access->connection->ldapGroupFilter
177
-		);
178
-		if ($memberURLs !== false) {
179
-			// this group has the 'memberURL' attribute so this is a dynamic group
180
-			// example 1: ldap:///cn=users,cn=accounts,dc=dcsubbase,dc=dcbase??one?(o=HeadOffice)
181
-			// example 2: ldap:///cn=users,cn=accounts,dc=dcsubbase,dc=dcbase??one?(&(o=HeadOffice)(uidNumber>=500))
182
-			$pos = strpos($memberURLs[0], '(');
183
-			if ($pos !== false) {
184
-				$memberUrlFilter = substr($memberURLs[0], $pos);
185
-				$foundMembers = $this->access->searchUsers($memberUrlFilter,'dn');
186
-				$dynamicMembers = array();
187
-				foreach($foundMembers as $value) {
188
-					$dynamicMembers[$value['dn'][0]] = 1;
189
-				}
190
-			} else {
191
-				\OCP\Util::writeLog('user_ldap', 'No search filter found on member url '.
192
-					'of group ' . $dnGroup, \OCP\Util::DEBUG);
193
-			}
194
-		}
195
-		return $dynamicMembers;
196
-	}
197
-
198
-	/**
199
-	 * @param string $dnGroup
200
-	 * @param array|null &$seen
201
-	 * @return array|mixed|null
202
-	 */
203
-	private function _groupMembers($dnGroup, &$seen = null) {
204
-		if ($seen === null) {
205
-			$seen = array();
206
-		}
207
-		$allMembers = array();
208
-		if (array_key_exists($dnGroup, $seen)) {
209
-			// avoid loops
210
-			return array();
211
-		}
212
-		// used extensively in cron job, caching makes sense for nested groups
213
-		$cacheKey = '_groupMembers'.$dnGroup;
214
-		$groupMembers = $this->access->connection->getFromCache($cacheKey);
215
-		if(!is_null($groupMembers)) {
216
-			return $groupMembers;
217
-		}
218
-		$seen[$dnGroup] = 1;
219
-		$members = $this->access->readAttribute($dnGroup, $this->access->connection->ldapGroupMemberAssocAttr,
220
-												$this->access->connection->ldapGroupFilter);
221
-		if (is_array($members)) {
222
-			foreach ($members as $memberDN) {
223
-				$allMembers[$memberDN] = 1;
224
-				$nestedGroups = $this->access->connection->ldapNestedGroups;
225
-				if (!empty($nestedGroups)) {
226
-					$subMembers = $this->_groupMembers($memberDN, $seen);
227
-					if ($subMembers) {
228
-						$allMembers = array_merge($allMembers, $subMembers);
229
-					}
230
-				}
231
-			}
232
-		}
233
-
234
-		$allMembers = array_merge($allMembers, $this->getDynamicGroupMembers($dnGroup));
235
-
236
-		$this->access->connection->writeToCache($cacheKey, $allMembers);
237
-		return $allMembers;
238
-	}
239
-
240
-	/**
241
-	 * @param string $DN
242
-	 * @param array|null &$seen
243
-	 * @return array
244
-	 */
245
-	private function _getGroupDNsFromMemberOf($DN, &$seen = null) {
246
-		if ($seen === null) {
247
-			$seen = array();
248
-		}
249
-		if (array_key_exists($DN, $seen)) {
250
-			// avoid loops
251
-			return array();
252
-		}
253
-		$seen[$DN] = 1;
254
-		$groups = $this->access->readAttribute($DN, 'memberOf');
255
-		if (!is_array($groups)) {
256
-			return array();
257
-		}
258
-		$groups = $this->access->groupsMatchFilter($groups);
259
-		$allGroups =  $groups;
260
-		$nestedGroups = $this->access->connection->ldapNestedGroups;
261
-		if (intval($nestedGroups) === 1) {
262
-			foreach ($groups as $group) {
263
-				$subGroups = $this->_getGroupDNsFromMemberOf($group, $seen);
264
-				$allGroups = array_merge($allGroups, $subGroups);
265
-			}
266
-		}
267
-		return $allGroups;
268
-	}
269
-
270
-	/**
271
-	 * translates a gidNumber into an ownCloud internal name
272
-	 * @param string $gid as given by gidNumber on POSIX LDAP
273
-	 * @param string $dn a DN that belongs to the same domain as the group
274
-	 * @return string|bool
275
-	 */
276
-	public function gidNumber2Name($gid, $dn) {
277
-		$cacheKey = 'gidNumberToName' . $gid;
278
-		$groupName = $this->access->connection->getFromCache($cacheKey);
279
-		if(!is_null($groupName) && isset($groupName)) {
280
-			return $groupName;
281
-		}
282
-
283
-		//we need to get the DN from LDAP
284
-		$filter = $this->access->combineFilterWithAnd([
285
-			$this->access->connection->ldapGroupFilter,
286
-			'objectClass=posixGroup',
287
-			$this->access->connection->ldapGidNumber . '=' . $gid
288
-		]);
289
-		$result = $this->access->searchGroups($filter, array('dn'), 1);
290
-		if(empty($result)) {
291
-			return false;
292
-		}
293
-		$dn = $result[0]['dn'][0];
294
-
295
-		//and now the group name
296
-		//NOTE once we have separate ownCloud group IDs and group names we can
297
-		//directly read the display name attribute instead of the DN
298
-		$name = $this->access->dn2groupname($dn);
299
-
300
-		$this->access->connection->writeToCache($cacheKey, $name);
301
-
302
-		return $name;
303
-	}
304
-
305
-	/**
306
-	 * returns the entry's gidNumber
307
-	 * @param string $dn
308
-	 * @param string $attribute
309
-	 * @return string|bool
310
-	 */
311
-	private function getEntryGidNumber($dn, $attribute) {
312
-		$value = $this->access->readAttribute($dn, $attribute);
313
-		if(is_array($value) && !empty($value)) {
314
-			return $value[0];
315
-		}
316
-		return false;
317
-	}
318
-
319
-	/**
320
-	 * returns the group's primary ID
321
-	 * @param string $dn
322
-	 * @return string|bool
323
-	 */
324
-	public function getGroupGidNumber($dn) {
325
-		return $this->getEntryGidNumber($dn, 'gidNumber');
326
-	}
327
-
328
-	/**
329
-	 * returns the user's gidNumber
330
-	 * @param string $dn
331
-	 * @return string|bool
332
-	 */
333
-	public function getUserGidNumber($dn) {
334
-		$gidNumber = false;
335
-		if($this->access->connection->hasGidNumber) {
336
-			$gidNumber = $this->getEntryGidNumber($dn, 'gidNumber');
337
-			if($gidNumber === false) {
338
-				$this->access->connection->hasGidNumber = false;
339
-			}
340
-		}
341
-		return $gidNumber;
342
-	}
343
-
344
-	/**
345
-	 * returns a filter for a "users has specific gid" search or count operation
346
-	 *
347
-	 * @param string $groupDN
348
-	 * @param string $search
349
-	 * @return string
350
-	 * @throws \Exception
351
-	 */
352
-	private function prepareFilterForUsersHasGidNumber($groupDN, $search = '') {
353
-		$groupID = $this->getGroupGidNumber($groupDN);
354
-		if($groupID === false) {
355
-			throw new \Exception('Not a valid group');
356
-		}
357
-
358
-		$filterParts = [];
359
-		$filterParts[] = $this->access->getFilterForUserCount();
360
-		if ($search !== '') {
361
-			$filterParts[] = $this->access->getFilterPartForUserSearch($search);
362
-		}
363
-		$filterParts[] = $this->access->connection->ldapGidNumber .'=' . $groupID;
364
-
365
-		$filter = $this->access->combineFilterWithAnd($filterParts);
366
-
367
-		return $filter;
368
-	}
369
-
370
-	/**
371
-	 * returns a list of users that have the given group as gid number
372
-	 *
373
-	 * @param string $groupDN
374
-	 * @param string $search
375
-	 * @param int $limit
376
-	 * @param int $offset
377
-	 * @return string[]
378
-	 */
379
-	public function getUsersInGidNumber($groupDN, $search = '', $limit = -1, $offset = 0) {
380
-		try {
381
-			$filter = $this->prepareFilterForUsersHasGidNumber($groupDN, $search);
382
-			$users = $this->access->fetchListOfUsers(
383
-				$filter,
384
-				[$this->access->connection->ldapUserDisplayName, 'dn'],
385
-				$limit,
386
-				$offset
387
-			);
388
-			return $this->access->nextcloudUserNames($users);
389
-		} catch (\Exception $e) {
390
-			return [];
391
-		}
392
-	}
393
-
394
-	/**
395
-	 * returns the number of users that have the given group as gid number
396
-	 *
397
-	 * @param string $groupDN
398
-	 * @param string $search
399
-	 * @param int $limit
400
-	 * @param int $offset
401
-	 * @return int
402
-	 */
403
-	public function countUsersInGidNumber($groupDN, $search = '', $limit = -1, $offset = 0) {
404
-		try {
405
-			$filter = $this->prepareFilterForUsersHasGidNumber($groupDN, $search);
406
-			$users = $this->access->countUsers($filter, ['dn'], $limit, $offset);
407
-			return (int)$users;
408
-		} catch (\Exception $e) {
409
-			return 0;
410
-		}
411
-	}
412
-
413
-	/**
414
-	 * gets the gidNumber of a user
415
-	 * @param string $dn
416
-	 * @return string
417
-	 */
418
-	public function getUserGroupByGid($dn) {
419
-		$groupID = $this->getUserGidNumber($dn);
420
-		if($groupID !== false) {
421
-			$groupName = $this->gidNumber2Name($groupID, $dn);
422
-			if($groupName !== false) {
423
-				return $groupName;
424
-			}
425
-		}
426
-
427
-		return false;
428
-	}
429
-
430
-	/**
431
-	 * translates a primary group ID into an Nextcloud internal name
432
-	 * @param string $gid as given by primaryGroupID on AD
433
-	 * @param string $dn a DN that belongs to the same domain as the group
434
-	 * @return string|bool
435
-	 */
436
-	public function primaryGroupID2Name($gid, $dn) {
437
-		$cacheKey = 'primaryGroupIDtoName';
438
-		$groupNames = $this->access->connection->getFromCache($cacheKey);
439
-		if(!is_null($groupNames) && isset($groupNames[$gid])) {
440
-			return $groupNames[$gid];
441
-		}
442
-
443
-		$domainObjectSid = $this->access->getSID($dn);
444
-		if($domainObjectSid === false) {
445
-			return false;
446
-		}
447
-
448
-		//we need to get the DN from LDAP
449
-		$filter = $this->access->combineFilterWithAnd(array(
450
-			$this->access->connection->ldapGroupFilter,
451
-			'objectsid=' . $domainObjectSid . '-' . $gid
452
-		));
453
-		$result = $this->access->searchGroups($filter, array('dn'), 1);
454
-		if(empty($result)) {
455
-			return false;
456
-		}
457
-		$dn = $result[0]['dn'][0];
458
-
459
-		//and now the group name
460
-		//NOTE once we have separate Nextcloud group IDs and group names we can
461
-		//directly read the display name attribute instead of the DN
462
-		$name = $this->access->dn2groupname($dn);
463
-
464
-		$this->access->connection->writeToCache($cacheKey, $name);
465
-
466
-		return $name;
467
-	}
468
-
469
-	/**
470
-	 * returns the entry's primary group ID
471
-	 * @param string $dn
472
-	 * @param string $attribute
473
-	 * @return string|bool
474
-	 */
475
-	private function getEntryGroupID($dn, $attribute) {
476
-		$value = $this->access->readAttribute($dn, $attribute);
477
-		if(is_array($value) && !empty($value)) {
478
-			return $value[0];
479
-		}
480
-		return false;
481
-	}
482
-
483
-	/**
484
-	 * returns the group's primary ID
485
-	 * @param string $dn
486
-	 * @return string|bool
487
-	 */
488
-	public function getGroupPrimaryGroupID($dn) {
489
-		return $this->getEntryGroupID($dn, 'primaryGroupToken');
490
-	}
491
-
492
-	/**
493
-	 * returns the user's primary group ID
494
-	 * @param string $dn
495
-	 * @return string|bool
496
-	 */
497
-	public function getUserPrimaryGroupIDs($dn) {
498
-		$primaryGroupID = false;
499
-		if($this->access->connection->hasPrimaryGroups) {
500
-			$primaryGroupID = $this->getEntryGroupID($dn, 'primaryGroupID');
501
-			if($primaryGroupID === false) {
502
-				$this->access->connection->hasPrimaryGroups = false;
503
-			}
504
-		}
505
-		return $primaryGroupID;
506
-	}
507
-
508
-	/**
509
-	 * returns a filter for a "users in primary group" search or count operation
510
-	 *
511
-	 * @param string $groupDN
512
-	 * @param string $search
513
-	 * @return string
514
-	 * @throws \Exception
515
-	 */
516
-	private function prepareFilterForUsersInPrimaryGroup($groupDN, $search = '') {
517
-		$groupID = $this->getGroupPrimaryGroupID($groupDN);
518
-		if($groupID === false) {
519
-			throw new \Exception('Not a valid group');
520
-		}
521
-
522
-		$filterParts = [];
523
-		$filterParts[] = $this->access->getFilterForUserCount();
524
-		if ($search !== '') {
525
-			$filterParts[] = $this->access->getFilterPartForUserSearch($search);
526
-		}
527
-		$filterParts[] = 'primaryGroupID=' . $groupID;
528
-
529
-		$filter = $this->access->combineFilterWithAnd($filterParts);
530
-
531
-		return $filter;
532
-	}
533
-
534
-	/**
535
-	 * returns a list of users that have the given group as primary group
536
-	 *
537
-	 * @param string $groupDN
538
-	 * @param string $search
539
-	 * @param int $limit
540
-	 * @param int $offset
541
-	 * @return string[]
542
-	 */
543
-	public function getUsersInPrimaryGroup($groupDN, $search = '', $limit = -1, $offset = 0) {
544
-		try {
545
-			$filter = $this->prepareFilterForUsersInPrimaryGroup($groupDN, $search);
546
-			$users = $this->access->fetchListOfUsers(
547
-				$filter,
548
-				array($this->access->connection->ldapUserDisplayName, 'dn'),
549
-				$limit,
550
-				$offset
551
-			);
552
-			return $this->access->nextcloudUserNames($users);
553
-		} catch (\Exception $e) {
554
-			return array();
555
-		}
556
-	}
557
-
558
-	/**
559
-	 * returns the number of users that have the given group as primary group
560
-	 *
561
-	 * @param string $groupDN
562
-	 * @param string $search
563
-	 * @param int $limit
564
-	 * @param int $offset
565
-	 * @return int
566
-	 */
567
-	public function countUsersInPrimaryGroup($groupDN, $search = '', $limit = -1, $offset = 0) {
568
-		try {
569
-			$filter = $this->prepareFilterForUsersInPrimaryGroup($groupDN, $search);
570
-			$users = $this->access->countUsers($filter, array('dn'), $limit, $offset);
571
-			return (int)$users;
572
-		} catch (\Exception $e) {
573
-			return 0;
574
-		}
575
-	}
576
-
577
-	/**
578
-	 * gets the primary group of a user
579
-	 * @param string $dn
580
-	 * @return string
581
-	 */
582
-	public function getUserPrimaryGroup($dn) {
583
-		$groupID = $this->getUserPrimaryGroupIDs($dn);
584
-		if($groupID !== false) {
585
-			$groupName = $this->primaryGroupID2Name($groupID, $dn);
586
-			if($groupName !== false) {
587
-				return $groupName;
588
-			}
589
-		}
590
-
591
-		return false;
592
-	}
593
-
594
-	/**
595
-	 * Get all groups a user belongs to
596
-	 * @param string $uid Name of the user
597
-	 * @return array with group names
598
-	 *
599
-	 * This function fetches all groups a user belongs to. It does not check
600
-	 * if the user exists at all.
601
-	 *
602
-	 * This function includes groups based on dynamic group membership.
603
-	 */
604
-	public function getUserGroups($uid) {
605
-		if(!$this->enabled) {
606
-			return array();
607
-		}
608
-		$cacheKey = 'getUserGroups'.$uid;
609
-		$userGroups = $this->access->connection->getFromCache($cacheKey);
610
-		if(!is_null($userGroups)) {
611
-			return $userGroups;
612
-		}
613
-		$userDN = $this->access->username2dn($uid);
614
-		if(!$userDN) {
615
-			$this->access->connection->writeToCache($cacheKey, array());
616
-			return array();
617
-		}
618
-
619
-		$groups = [];
620
-		$primaryGroup = $this->getUserPrimaryGroup($userDN);
621
-		$gidGroupName = $this->getUserGroupByGid($userDN);
622
-
623
-		$dynamicGroupMemberURL = strtolower($this->access->connection->ldapDynamicGroupMemberURL);
624
-
625
-		if (!empty($dynamicGroupMemberURL)) {
626
-			// look through dynamic groups to add them to the result array if needed
627
-			$groupsToMatch = $this->access->fetchListOfGroups(
628
-				$this->access->connection->ldapGroupFilter,array('dn',$dynamicGroupMemberURL));
629
-			foreach($groupsToMatch as $dynamicGroup) {
630
-				if (!array_key_exists($dynamicGroupMemberURL, $dynamicGroup)) {
631
-					continue;
632
-				}
633
-				$pos = strpos($dynamicGroup[$dynamicGroupMemberURL][0], '(');
634
-				if ($pos !== false) {
635
-					$memberUrlFilter = substr($dynamicGroup[$dynamicGroupMemberURL][0],$pos);
636
-					// apply filter via ldap search to see if this user is in this
637
-					// dynamic group
638
-					$userMatch = $this->access->readAttribute(
639
-						$userDN,
640
-						$this->access->connection->ldapUserDisplayName,
641
-						$memberUrlFilter
642
-					);
643
-					if ($userMatch !== false) {
644
-						// match found so this user is in this group
645
-						$groupName = $this->access->dn2groupname($dynamicGroup['dn'][0]);
646
-						if(is_string($groupName)) {
647
-							// be sure to never return false if the dn could not be
648
-							// resolved to a name, for whatever reason.
649
-							$groups[] = $groupName;
650
-						}
651
-					}
652
-				} else {
653
-					\OCP\Util::writeLog('user_ldap', 'No search filter found on member url '.
654
-						'of group ' . print_r($dynamicGroup, true), \OCP\Util::DEBUG);
655
-				}
656
-			}
657
-		}
658
-
659
-		// if possible, read out membership via memberOf. It's far faster than
660
-		// performing a search, which still is a fallback later.
661
-		// memberof doesn't support memberuid, so skip it here.
662
-		if(intval($this->access->connection->hasMemberOfFilterSupport) === 1
663
-			&& intval($this->access->connection->useMemberOfToDetectMembership) === 1
664
-		    && strtolower($this->access->connection->ldapGroupMemberAssocAttr) !== 'memberuid'
665
-		    ) {
666
-			$groupDNs = $this->_getGroupDNsFromMemberOf($userDN);
667
-			if (is_array($groupDNs)) {
668
-				foreach ($groupDNs as $dn) {
669
-					$groupName = $this->access->dn2groupname($dn);
670
-					if(is_string($groupName)) {
671
-						// be sure to never return false if the dn could not be
672
-						// resolved to a name, for whatever reason.
673
-						$groups[] = $groupName;
674
-					}
675
-				}
676
-			}
677
-
678
-			if($primaryGroup !== false) {
679
-				$groups[] = $primaryGroup;
680
-			}
681
-			if($gidGroupName !== false) {
682
-				$groups[] = $gidGroupName;
683
-			}
684
-			$this->access->connection->writeToCache($cacheKey, $groups);
685
-			return $groups;
686
-		}
687
-
688
-		//uniqueMember takes DN, memberuid the uid, so we need to distinguish
689
-		if((strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'uniquemember')
690
-			|| (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'member')
691
-		) {
692
-			$uid = $userDN;
693
-		} else if(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') {
694
-			$result = $this->access->readAttribute($userDN, 'uid');
695
-			if ($result === false) {
696
-				\OCP\Util::writeLog('user_ldap', 'No uid attribute found for DN ' . $userDN . ' on '.
697
-					$this->access->connection->ldapHost, \OCP\Util::DEBUG);
698
-			}
699
-			$uid = $result[0];
700
-		} else {
701
-			// just in case
702
-			$uid = $userDN;
703
-		}
704
-
705
-		if(isset($this->cachedGroupsByMember[$uid])) {
706
-			$groups = array_merge($groups, $this->cachedGroupsByMember[$uid]);
707
-		} else {
708
-			$groupsByMember = array_values($this->getGroupsByMember($uid));
709
-			$groupsByMember = $this->access->nextcloudGroupNames($groupsByMember);
710
-			$this->cachedGroupsByMember[$uid] = $groupsByMember;
711
-			$groups = array_merge($groups, $groupsByMember);
712
-		}
713
-
714
-		if($primaryGroup !== false) {
715
-			$groups[] = $primaryGroup;
716
-		}
717
-		if($gidGroupName !== false) {
718
-			$groups[] = $gidGroupName;
719
-		}
720
-
721
-		$groups = array_unique($groups, SORT_LOCALE_STRING);
722
-		$this->access->connection->writeToCache($cacheKey, $groups);
723
-
724
-		return $groups;
725
-	}
726
-
727
-	/**
728
-	 * @param string $dn
729
-	 * @param array|null &$seen
730
-	 * @return array
731
-	 */
732
-	private function getGroupsByMember($dn, &$seen = null) {
733
-		if ($seen === null) {
734
-			$seen = array();
735
-		}
736
-		$allGroups = array();
737
-		if (array_key_exists($dn, $seen)) {
738
-			// avoid loops
739
-			return array();
740
-		}
741
-		$seen[$dn] = true;
742
-		$filter = $this->access->combineFilterWithAnd(array(
743
-			$this->access->connection->ldapGroupFilter,
744
-			$this->access->connection->ldapGroupMemberAssocAttr.'='.$dn
745
-		));
746
-		$groups = $this->access->fetchListOfGroups($filter,
747
-			array($this->access->connection->ldapGroupDisplayName, 'dn'));
748
-		if (is_array($groups)) {
749
-			foreach ($groups as $groupobj) {
750
-				$groupDN = $groupobj['dn'][0];
751
-				$allGroups[$groupDN] = $groupobj;
752
-				$nestedGroups = $this->access->connection->ldapNestedGroups;
753
-				if (!empty($nestedGroups)) {
754
-					$supergroups = $this->getGroupsByMember($groupDN, $seen);
755
-					if (is_array($supergroups) && (count($supergroups)>0)) {
756
-						$allGroups = array_merge($allGroups, $supergroups);
757
-					}
758
-				}
759
-			}
760
-		}
761
-		return $allGroups;
762
-	}
763
-
764
-	/**
765
-	 * get a list of all users in a group
766
-	 *
767
-	 * @param string $gid
768
-	 * @param string $search
769
-	 * @param int $limit
770
-	 * @param int $offset
771
-	 * @return array with user ids
772
-	 */
773
-	public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) {
774
-		if(!$this->enabled) {
775
-			return array();
776
-		}
777
-		if(!$this->groupExists($gid)) {
778
-			return array();
779
-		}
780
-		$search = $this->access->escapeFilterPart($search, true);
781
-		$cacheKey = 'usersInGroup-'.$gid.'-'.$search.'-'.$limit.'-'.$offset;
782
-		// check for cache of the exact query
783
-		$groupUsers = $this->access->connection->getFromCache($cacheKey);
784
-		if(!is_null($groupUsers)) {
785
-			return $groupUsers;
786
-		}
787
-
788
-		// check for cache of the query without limit and offset
789
-		$groupUsers = $this->access->connection->getFromCache('usersInGroup-'.$gid.'-'.$search);
790
-		if(!is_null($groupUsers)) {
791
-			$groupUsers = array_slice($groupUsers, $offset, $limit);
792
-			$this->access->connection->writeToCache($cacheKey, $groupUsers);
793
-			return $groupUsers;
794
-		}
795
-
796
-		if($limit === -1) {
797
-			$limit = null;
798
-		}
799
-		$groupDN = $this->access->groupname2dn($gid);
800
-		if(!$groupDN) {
801
-			// group couldn't be found, return empty resultset
802
-			$this->access->connection->writeToCache($cacheKey, array());
803
-			return array();
804
-		}
805
-
806
-		$primaryUsers = $this->getUsersInPrimaryGroup($groupDN, $search, $limit, $offset);
807
-		$posixGroupUsers = $this->getUsersInGidNumber($groupDN, $search, $limit, $offset);
808
-		$members = array_keys($this->_groupMembers($groupDN));
809
-		if(!$members && empty($posixGroupUsers) && empty($primaryUsers)) {
810
-			//in case users could not be retrieved, return empty result set
811
-			$this->access->connection->writeToCache($cacheKey, []);
812
-			return [];
813
-		}
814
-
815
-		$groupUsers = array();
816
-		$isMemberUid = (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid');
817
-		$attrs = $this->access->userManager->getAttributes(true);
818
-		foreach($members as $member) {
819
-			if($isMemberUid) {
820
-				//we got uids, need to get their DNs to 'translate' them to user names
821
-				$filter = $this->access->combineFilterWithAnd(array(
822
-					str_replace('%uid', $member, $this->access->connection->ldapLoginFilter),
823
-					$this->access->getFilterPartForUserSearch($search)
824
-				));
825
-				$ldap_users = $this->access->fetchListOfUsers($filter, $attrs, 1);
826
-				if(count($ldap_users) < 1) {
827
-					continue;
828
-				}
829
-				$groupUsers[] = $this->access->dn2username($ldap_users[0]['dn'][0]);
830
-			} else {
831
-				//we got DNs, check if we need to filter by search or we can give back all of them
832
-				if ($search !== '') {
833
-					if(!$this->access->readAttribute($member,
834
-						$this->access->connection->ldapUserDisplayName,
835
-						$this->access->getFilterPartForUserSearch($search))) {
836
-						continue;
837
-					}
838
-				}
839
-				// dn2username will also check if the users belong to the allowed base
840
-				if($ocname = $this->access->dn2username($member)) {
841
-					$groupUsers[] = $ocname;
842
-				}
843
-			}
844
-		}
845
-
846
-		$groupUsers = array_unique(array_merge($groupUsers, $primaryUsers, $posixGroupUsers));
847
-		natsort($groupUsers);
848
-		$this->access->connection->writeToCache('usersInGroup-'.$gid.'-'.$search, $groupUsers);
849
-		$groupUsers = array_slice($groupUsers, $offset, $limit);
850
-
851
-		$this->access->connection->writeToCache($cacheKey, $groupUsers);
852
-
853
-		return $groupUsers;
854
-	}
855
-
856
-	/**
857
-	 * returns the number of users in a group, who match the search term
858
-	 * @param string $gid the internal group name
859
-	 * @param string $search optional, a search string
860
-	 * @return int|bool
861
-	 */
862
-	public function countUsersInGroup($gid, $search = '') {
863
-		$cacheKey = 'countUsersInGroup-'.$gid.'-'.$search;
864
-		if(!$this->enabled || !$this->groupExists($gid)) {
865
-			return false;
866
-		}
867
-		$groupUsers = $this->access->connection->getFromCache($cacheKey);
868
-		if(!is_null($groupUsers)) {
869
-			return $groupUsers;
870
-		}
871
-
872
-		$groupDN = $this->access->groupname2dn($gid);
873
-		if(!$groupDN) {
874
-			// group couldn't be found, return empty result set
875
-			$this->access->connection->writeToCache($cacheKey, false);
876
-			return false;
877
-		}
878
-
879
-		$members = array_keys($this->_groupMembers($groupDN));
880
-		$primaryUserCount = $this->countUsersInPrimaryGroup($groupDN, '');
881
-		if(!$members && $primaryUserCount === 0) {
882
-			//in case users could not be retrieved, return empty result set
883
-			$this->access->connection->writeToCache($cacheKey, false);
884
-			return false;
885
-		}
886
-
887
-		if ($search === '') {
888
-			$groupUsers = count($members) + $primaryUserCount;
889
-			$this->access->connection->writeToCache($cacheKey, $groupUsers);
890
-			return $groupUsers;
891
-		}
892
-		$search = $this->access->escapeFilterPart($search, true);
893
-		$isMemberUid =
894
-			(strtolower($this->access->connection->ldapGroupMemberAssocAttr)
895
-			=== 'memberuid');
896
-
897
-		//we need to apply the search filter
898
-		//alternatives that need to be checked:
899
-		//a) get all users by search filter and array_intersect them
900
-		//b) a, but only when less than 1k 10k ?k users like it is
901
-		//c) put all DNs|uids in a LDAP filter, combine with the search string
902
-		//   and let it count.
903
-		//For now this is not important, because the only use of this method
904
-		//does not supply a search string
905
-		$groupUsers = array();
906
-		foreach($members as $member) {
907
-			if($isMemberUid) {
908
-				//we got uids, need to get their DNs to 'translate' them to user names
909
-				$filter = $this->access->combineFilterWithAnd(array(
910
-					str_replace('%uid', $member, $this->access->connection->ldapLoginFilter),
911
-					$this->access->getFilterPartForUserSearch($search)
912
-				));
913
-				$ldap_users = $this->access->fetchListOfUsers($filter, 'dn', 1);
914
-				if(count($ldap_users) < 1) {
915
-					continue;
916
-				}
917
-				$groupUsers[] = $this->access->dn2username($ldap_users[0]);
918
-			} else {
919
-				//we need to apply the search filter now
920
-				if(!$this->access->readAttribute($member,
921
-					$this->access->connection->ldapUserDisplayName,
922
-					$this->access->getFilterPartForUserSearch($search))) {
923
-					continue;
924
-				}
925
-				// dn2username will also check if the users belong to the allowed base
926
-				if($ocname = $this->access->dn2username($member)) {
927
-					$groupUsers[] = $ocname;
928
-				}
929
-			}
930
-		}
931
-
932
-		//and get users that have the group as primary
933
-		$primaryUsers = $this->countUsersInPrimaryGroup($groupDN, $search);
934
-
935
-		return count($groupUsers) + $primaryUsers;
936
-	}
937
-
938
-	/**
939
-	 * get a list of all groups
940
-	 *
941
-	 * @param string $search
942
-	 * @param $limit
943
-	 * @param int $offset
944
-	 * @return array with group names
945
-	 *
946
-	 * Returns a list with all groups (used by getGroups)
947
-	 */
948
-	protected function getGroupsChunk($search = '', $limit = -1, $offset = 0) {
949
-		if(!$this->enabled) {
950
-			return array();
951
-		}
952
-		$cacheKey = 'getGroups-'.$search.'-'.$limit.'-'.$offset;
953
-
954
-		//Check cache before driving unnecessary searches
955
-		\OCP\Util::writeLog('user_ldap', 'getGroups '.$cacheKey, \OCP\Util::DEBUG);
956
-		$ldap_groups = $this->access->connection->getFromCache($cacheKey);
957
-		if(!is_null($ldap_groups)) {
958
-			return $ldap_groups;
959
-		}
960
-
961
-		// if we'd pass -1 to LDAP search, we'd end up in a Protocol
962
-		// error. With a limit of 0, we get 0 results. So we pass null.
963
-		if($limit <= 0) {
964
-			$limit = null;
965
-		}
966
-		$filter = $this->access->combineFilterWithAnd(array(
967
-			$this->access->connection->ldapGroupFilter,
968
-			$this->access->getFilterPartForGroupSearch($search)
969
-		));
970
-		\OCP\Util::writeLog('user_ldap', 'getGroups Filter '.$filter, \OCP\Util::DEBUG);
971
-		$ldap_groups = $this->access->fetchListOfGroups($filter,
972
-				array($this->access->connection->ldapGroupDisplayName, 'dn'),
973
-				$limit,
974
-				$offset);
975
-		$ldap_groups = $this->access->nextcloudGroupNames($ldap_groups);
976
-
977
-		$this->access->connection->writeToCache($cacheKey, $ldap_groups);
978
-		return $ldap_groups;
979
-	}
980
-
981
-	/**
982
-	 * get a list of all groups using a paged search
983
-	 *
984
-	 * @param string $search
985
-	 * @param int $limit
986
-	 * @param int $offset
987
-	 * @return array with group names
988
-	 *
989
-	 * Returns a list with all groups
990
-	 * Uses a paged search if available to override a
991
-	 * server side search limit.
992
-	 * (active directory has a limit of 1000 by default)
993
-	 */
994
-	public function getGroups($search = '', $limit = -1, $offset = 0) {
995
-		if(!$this->enabled) {
996
-			return array();
997
-		}
998
-		$search = $this->access->escapeFilterPart($search, true);
999
-		$pagingSize = intval($this->access->connection->ldapPagingSize);
1000
-		if (!$this->access->connection->hasPagedResultSupport || $pagingSize <= 0) {
1001
-			return $this->getGroupsChunk($search, $limit, $offset);
1002
-		}
1003
-		$maxGroups = 100000; // limit max results (just for safety reasons)
1004
-		if ($limit > -1) {
1005
-		   $overallLimit = min($limit + $offset, $maxGroups);
1006
-		} else {
1007
-		   $overallLimit = $maxGroups;
1008
-		}
1009
-		$chunkOffset = $offset;
1010
-		$allGroups = array();
1011
-		while ($chunkOffset < $overallLimit) {
1012
-			$chunkLimit = min($pagingSize, $overallLimit - $chunkOffset);
1013
-			$ldapGroups = $this->getGroupsChunk($search, $chunkLimit, $chunkOffset);
1014
-			$nread = count($ldapGroups);
1015
-			\OCP\Util::writeLog('user_ldap', 'getGroups('.$search.'): read '.$nread.' at offset '.$chunkOffset.' (limit: '.$chunkLimit.')', \OCP\Util::DEBUG);
1016
-			if ($nread) {
1017
-				$allGroups = array_merge($allGroups, $ldapGroups);
1018
-				$chunkOffset += $nread;
1019
-			}
1020
-			if ($nread < $chunkLimit) {
1021
-				break;
1022
-			}
1023
-		}
1024
-		return $allGroups;
1025
-	}
1026
-
1027
-	/**
1028
-	 * @param string $group
1029
-	 * @return bool
1030
-	 */
1031
-	public function groupMatchesFilter($group) {
1032
-		return (strripos($group, $this->groupSearch) !== false);
1033
-	}
1034
-
1035
-	/**
1036
-	 * check if a group exists
1037
-	 * @param string $gid
1038
-	 * @return bool
1039
-	 */
1040
-	public function groupExists($gid) {
1041
-		$groupExists = $this->access->connection->getFromCache('groupExists'.$gid);
1042
-		if(!is_null($groupExists)) {
1043
-			return (bool)$groupExists;
1044
-		}
1045
-
1046
-		//getting dn, if false the group does not exist. If dn, it may be mapped
1047
-		//only, requires more checking.
1048
-		$dn = $this->access->groupname2dn($gid);
1049
-		if(!$dn) {
1050
-			$this->access->connection->writeToCache('groupExists'.$gid, false);
1051
-			return false;
1052
-		}
1053
-
1054
-		//if group really still exists, we will be able to read its objectclass
1055
-		if(!is_array($this->access->readAttribute($dn, ''))) {
1056
-			$this->access->connection->writeToCache('groupExists'.$gid, false);
1057
-			return false;
1058
-		}
1059
-
1060
-		$this->access->connection->writeToCache('groupExists'.$gid, true);
1061
-		return true;
1062
-	}
1063
-
1064
-	/**
1065
-	* Check if backend implements actions
1066
-	* @param int $actions bitwise-or'ed actions
1067
-	* @return boolean
1068
-	*
1069
-	* Returns the supported actions as int to be
1070
-	* compared with \OC\User\Backend::CREATE_USER etc.
1071
-	*/
1072
-	public function implementsActions($actions) {
1073
-		return (bool)(\OC\Group\Backend::COUNT_USERS & $actions);
1074
-	}
1075
-
1076
-	/**
1077
-	 * Return access for LDAP interaction.
1078
-	 * @return Access instance of Access for LDAP interaction
1079
-	 */
1080
-	public function getLDAPAccess() {
1081
-		return $this->access;
1082
-	}
44
+    protected $enabled = false;
45
+
46
+    /**
47
+     * @var string[] $cachedGroupMembers array of users with gid as key
48
+     */
49
+    protected $cachedGroupMembers;
50
+
51
+    /**
52
+     * @var string[] $cachedGroupsByMember array of groups with uid as key
53
+     */
54
+    protected $cachedGroupsByMember;
55
+
56
+    public function __construct(Access $access) {
57
+        parent::__construct($access);
58
+        $filter = $this->access->connection->ldapGroupFilter;
59
+        $gassoc = $this->access->connection->ldapGroupMemberAssocAttr;
60
+        if(!empty($filter) && !empty($gassoc)) {
61
+            $this->enabled = true;
62
+        }
63
+
64
+        $this->cachedGroupMembers = new CappedMemoryCache();
65
+        $this->cachedGroupsByMember = new CappedMemoryCache();
66
+    }
67
+
68
+    /**
69
+     * is user in group?
70
+     * @param string $uid uid of the user
71
+     * @param string $gid gid of the group
72
+     * @return bool
73
+     *
74
+     * Checks whether the user is member of a group or not.
75
+     */
76
+    public function inGroup($uid, $gid) {
77
+        if(!$this->enabled) {
78
+            return false;
79
+        }
80
+        $cacheKey = 'inGroup'.$uid.':'.$gid;
81
+        $inGroup = $this->access->connection->getFromCache($cacheKey);
82
+        if(!is_null($inGroup)) {
83
+            return (bool)$inGroup;
84
+        }
85
+
86
+        $userDN = $this->access->username2dn($uid);
87
+
88
+        if(isset($this->cachedGroupMembers[$gid])) {
89
+            $isInGroup = in_array($userDN, $this->cachedGroupMembers[$gid]);
90
+            return $isInGroup;
91
+        }
92
+
93
+        $cacheKeyMembers = 'inGroup-members:'.$gid;
94
+        $members = $this->access->connection->getFromCache($cacheKeyMembers);
95
+        if(!is_null($members)) {
96
+            $this->cachedGroupMembers[$gid] = $members;
97
+            $isInGroup = in_array($userDN, $members);
98
+            $this->access->connection->writeToCache($cacheKey, $isInGroup);
99
+            return $isInGroup;
100
+        }
101
+
102
+        $groupDN = $this->access->groupname2dn($gid);
103
+        // just in case
104
+        if(!$groupDN || !$userDN) {
105
+            $this->access->connection->writeToCache($cacheKey, false);
106
+            return false;
107
+        }
108
+
109
+        //check primary group first
110
+        if($gid === $this->getUserPrimaryGroup($userDN)) {
111
+            $this->access->connection->writeToCache($cacheKey, true);
112
+            return true;
113
+        }
114
+
115
+        //usually, LDAP attributes are said to be case insensitive. But there are exceptions of course.
116
+        $members = $this->_groupMembers($groupDN);
117
+        $members = array_keys($members); // uids are returned as keys
118
+        if(!is_array($members) || count($members) === 0) {
119
+            $this->access->connection->writeToCache($cacheKey, false);
120
+            return false;
121
+        }
122
+
123
+        //extra work if we don't get back user DNs
124
+        if(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') {
125
+            $dns = array();
126
+            $filterParts = array();
127
+            $bytes = 0;
128
+            foreach($members as $mid) {
129
+                $filter = str_replace('%uid', $mid, $this->access->connection->ldapLoginFilter);
130
+                $filterParts[] = $filter;
131
+                $bytes += strlen($filter);
132
+                if($bytes >= 9000000) {
133
+                    // AD has a default input buffer of 10 MB, we do not want
134
+                    // to take even the chance to exceed it
135
+                    $filter = $this->access->combineFilterWithOr($filterParts);
136
+                    $bytes = 0;
137
+                    $filterParts = array();
138
+                    $users = $this->access->fetchListOfUsers($filter, 'dn', count($filterParts));
139
+                    $dns = array_merge($dns, $users);
140
+                }
141
+            }
142
+            if(count($filterParts) > 0) {
143
+                $filter = $this->access->combineFilterWithOr($filterParts);
144
+                $users = $this->access->fetchListOfUsers($filter, 'dn', count($filterParts));
145
+                $dns = array_merge($dns, $users);
146
+            }
147
+            $members = $dns;
148
+        }
149
+
150
+        $isInGroup = in_array($userDN, $members);
151
+        $this->access->connection->writeToCache($cacheKey, $isInGroup);
152
+        $this->access->connection->writeToCache($cacheKeyMembers, $members);
153
+        $this->cachedGroupMembers[$gid] = $members;
154
+
155
+        return $isInGroup;
156
+    }
157
+
158
+    /**
159
+     * @param string $dnGroup
160
+     * @return array
161
+     *
162
+     * For a group that has user membership defined by an LDAP search url attribute returns the users
163
+     * that match the search url otherwise returns an empty array.
164
+     */
165
+    public function getDynamicGroupMembers($dnGroup) {
166
+        $dynamicGroupMemberURL = strtolower($this->access->connection->ldapDynamicGroupMemberURL);
167
+
168
+        if (empty($dynamicGroupMemberURL)) {
169
+            return array();
170
+        }
171
+
172
+        $dynamicMembers = array();
173
+        $memberURLs = $this->access->readAttribute(
174
+            $dnGroup,
175
+            $dynamicGroupMemberURL,
176
+            $this->access->connection->ldapGroupFilter
177
+        );
178
+        if ($memberURLs !== false) {
179
+            // this group has the 'memberURL' attribute so this is a dynamic group
180
+            // example 1: ldap:///cn=users,cn=accounts,dc=dcsubbase,dc=dcbase??one?(o=HeadOffice)
181
+            // example 2: ldap:///cn=users,cn=accounts,dc=dcsubbase,dc=dcbase??one?(&(o=HeadOffice)(uidNumber>=500))
182
+            $pos = strpos($memberURLs[0], '(');
183
+            if ($pos !== false) {
184
+                $memberUrlFilter = substr($memberURLs[0], $pos);
185
+                $foundMembers = $this->access->searchUsers($memberUrlFilter,'dn');
186
+                $dynamicMembers = array();
187
+                foreach($foundMembers as $value) {
188
+                    $dynamicMembers[$value['dn'][0]] = 1;
189
+                }
190
+            } else {
191
+                \OCP\Util::writeLog('user_ldap', 'No search filter found on member url '.
192
+                    'of group ' . $dnGroup, \OCP\Util::DEBUG);
193
+            }
194
+        }
195
+        return $dynamicMembers;
196
+    }
197
+
198
+    /**
199
+     * @param string $dnGroup
200
+     * @param array|null &$seen
201
+     * @return array|mixed|null
202
+     */
203
+    private function _groupMembers($dnGroup, &$seen = null) {
204
+        if ($seen === null) {
205
+            $seen = array();
206
+        }
207
+        $allMembers = array();
208
+        if (array_key_exists($dnGroup, $seen)) {
209
+            // avoid loops
210
+            return array();
211
+        }
212
+        // used extensively in cron job, caching makes sense for nested groups
213
+        $cacheKey = '_groupMembers'.$dnGroup;
214
+        $groupMembers = $this->access->connection->getFromCache($cacheKey);
215
+        if(!is_null($groupMembers)) {
216
+            return $groupMembers;
217
+        }
218
+        $seen[$dnGroup] = 1;
219
+        $members = $this->access->readAttribute($dnGroup, $this->access->connection->ldapGroupMemberAssocAttr,
220
+                                                $this->access->connection->ldapGroupFilter);
221
+        if (is_array($members)) {
222
+            foreach ($members as $memberDN) {
223
+                $allMembers[$memberDN] = 1;
224
+                $nestedGroups = $this->access->connection->ldapNestedGroups;
225
+                if (!empty($nestedGroups)) {
226
+                    $subMembers = $this->_groupMembers($memberDN, $seen);
227
+                    if ($subMembers) {
228
+                        $allMembers = array_merge($allMembers, $subMembers);
229
+                    }
230
+                }
231
+            }
232
+        }
233
+
234
+        $allMembers = array_merge($allMembers, $this->getDynamicGroupMembers($dnGroup));
235
+
236
+        $this->access->connection->writeToCache($cacheKey, $allMembers);
237
+        return $allMembers;
238
+    }
239
+
240
+    /**
241
+     * @param string $DN
242
+     * @param array|null &$seen
243
+     * @return array
244
+     */
245
+    private function _getGroupDNsFromMemberOf($DN, &$seen = null) {
246
+        if ($seen === null) {
247
+            $seen = array();
248
+        }
249
+        if (array_key_exists($DN, $seen)) {
250
+            // avoid loops
251
+            return array();
252
+        }
253
+        $seen[$DN] = 1;
254
+        $groups = $this->access->readAttribute($DN, 'memberOf');
255
+        if (!is_array($groups)) {
256
+            return array();
257
+        }
258
+        $groups = $this->access->groupsMatchFilter($groups);
259
+        $allGroups =  $groups;
260
+        $nestedGroups = $this->access->connection->ldapNestedGroups;
261
+        if (intval($nestedGroups) === 1) {
262
+            foreach ($groups as $group) {
263
+                $subGroups = $this->_getGroupDNsFromMemberOf($group, $seen);
264
+                $allGroups = array_merge($allGroups, $subGroups);
265
+            }
266
+        }
267
+        return $allGroups;
268
+    }
269
+
270
+    /**
271
+     * translates a gidNumber into an ownCloud internal name
272
+     * @param string $gid as given by gidNumber on POSIX LDAP
273
+     * @param string $dn a DN that belongs to the same domain as the group
274
+     * @return string|bool
275
+     */
276
+    public function gidNumber2Name($gid, $dn) {
277
+        $cacheKey = 'gidNumberToName' . $gid;
278
+        $groupName = $this->access->connection->getFromCache($cacheKey);
279
+        if(!is_null($groupName) && isset($groupName)) {
280
+            return $groupName;
281
+        }
282
+
283
+        //we need to get the DN from LDAP
284
+        $filter = $this->access->combineFilterWithAnd([
285
+            $this->access->connection->ldapGroupFilter,
286
+            'objectClass=posixGroup',
287
+            $this->access->connection->ldapGidNumber . '=' . $gid
288
+        ]);
289
+        $result = $this->access->searchGroups($filter, array('dn'), 1);
290
+        if(empty($result)) {
291
+            return false;
292
+        }
293
+        $dn = $result[0]['dn'][0];
294
+
295
+        //and now the group name
296
+        //NOTE once we have separate ownCloud group IDs and group names we can
297
+        //directly read the display name attribute instead of the DN
298
+        $name = $this->access->dn2groupname($dn);
299
+
300
+        $this->access->connection->writeToCache($cacheKey, $name);
301
+
302
+        return $name;
303
+    }
304
+
305
+    /**
306
+     * returns the entry's gidNumber
307
+     * @param string $dn
308
+     * @param string $attribute
309
+     * @return string|bool
310
+     */
311
+    private function getEntryGidNumber($dn, $attribute) {
312
+        $value = $this->access->readAttribute($dn, $attribute);
313
+        if(is_array($value) && !empty($value)) {
314
+            return $value[0];
315
+        }
316
+        return false;
317
+    }
318
+
319
+    /**
320
+     * returns the group's primary ID
321
+     * @param string $dn
322
+     * @return string|bool
323
+     */
324
+    public function getGroupGidNumber($dn) {
325
+        return $this->getEntryGidNumber($dn, 'gidNumber');
326
+    }
327
+
328
+    /**
329
+     * returns the user's gidNumber
330
+     * @param string $dn
331
+     * @return string|bool
332
+     */
333
+    public function getUserGidNumber($dn) {
334
+        $gidNumber = false;
335
+        if($this->access->connection->hasGidNumber) {
336
+            $gidNumber = $this->getEntryGidNumber($dn, 'gidNumber');
337
+            if($gidNumber === false) {
338
+                $this->access->connection->hasGidNumber = false;
339
+            }
340
+        }
341
+        return $gidNumber;
342
+    }
343
+
344
+    /**
345
+     * returns a filter for a "users has specific gid" search or count operation
346
+     *
347
+     * @param string $groupDN
348
+     * @param string $search
349
+     * @return string
350
+     * @throws \Exception
351
+     */
352
+    private function prepareFilterForUsersHasGidNumber($groupDN, $search = '') {
353
+        $groupID = $this->getGroupGidNumber($groupDN);
354
+        if($groupID === false) {
355
+            throw new \Exception('Not a valid group');
356
+        }
357
+
358
+        $filterParts = [];
359
+        $filterParts[] = $this->access->getFilterForUserCount();
360
+        if ($search !== '') {
361
+            $filterParts[] = $this->access->getFilterPartForUserSearch($search);
362
+        }
363
+        $filterParts[] = $this->access->connection->ldapGidNumber .'=' . $groupID;
364
+
365
+        $filter = $this->access->combineFilterWithAnd($filterParts);
366
+
367
+        return $filter;
368
+    }
369
+
370
+    /**
371
+     * returns a list of users that have the given group as gid number
372
+     *
373
+     * @param string $groupDN
374
+     * @param string $search
375
+     * @param int $limit
376
+     * @param int $offset
377
+     * @return string[]
378
+     */
379
+    public function getUsersInGidNumber($groupDN, $search = '', $limit = -1, $offset = 0) {
380
+        try {
381
+            $filter = $this->prepareFilterForUsersHasGidNumber($groupDN, $search);
382
+            $users = $this->access->fetchListOfUsers(
383
+                $filter,
384
+                [$this->access->connection->ldapUserDisplayName, 'dn'],
385
+                $limit,
386
+                $offset
387
+            );
388
+            return $this->access->nextcloudUserNames($users);
389
+        } catch (\Exception $e) {
390
+            return [];
391
+        }
392
+    }
393
+
394
+    /**
395
+     * returns the number of users that have the given group as gid number
396
+     *
397
+     * @param string $groupDN
398
+     * @param string $search
399
+     * @param int $limit
400
+     * @param int $offset
401
+     * @return int
402
+     */
403
+    public function countUsersInGidNumber($groupDN, $search = '', $limit = -1, $offset = 0) {
404
+        try {
405
+            $filter = $this->prepareFilterForUsersHasGidNumber($groupDN, $search);
406
+            $users = $this->access->countUsers($filter, ['dn'], $limit, $offset);
407
+            return (int)$users;
408
+        } catch (\Exception $e) {
409
+            return 0;
410
+        }
411
+    }
412
+
413
+    /**
414
+     * gets the gidNumber of a user
415
+     * @param string $dn
416
+     * @return string
417
+     */
418
+    public function getUserGroupByGid($dn) {
419
+        $groupID = $this->getUserGidNumber($dn);
420
+        if($groupID !== false) {
421
+            $groupName = $this->gidNumber2Name($groupID, $dn);
422
+            if($groupName !== false) {
423
+                return $groupName;
424
+            }
425
+        }
426
+
427
+        return false;
428
+    }
429
+
430
+    /**
431
+     * translates a primary group ID into an Nextcloud internal name
432
+     * @param string $gid as given by primaryGroupID on AD
433
+     * @param string $dn a DN that belongs to the same domain as the group
434
+     * @return string|bool
435
+     */
436
+    public function primaryGroupID2Name($gid, $dn) {
437
+        $cacheKey = 'primaryGroupIDtoName';
438
+        $groupNames = $this->access->connection->getFromCache($cacheKey);
439
+        if(!is_null($groupNames) && isset($groupNames[$gid])) {
440
+            return $groupNames[$gid];
441
+        }
442
+
443
+        $domainObjectSid = $this->access->getSID($dn);
444
+        if($domainObjectSid === false) {
445
+            return false;
446
+        }
447
+
448
+        //we need to get the DN from LDAP
449
+        $filter = $this->access->combineFilterWithAnd(array(
450
+            $this->access->connection->ldapGroupFilter,
451
+            'objectsid=' . $domainObjectSid . '-' . $gid
452
+        ));
453
+        $result = $this->access->searchGroups($filter, array('dn'), 1);
454
+        if(empty($result)) {
455
+            return false;
456
+        }
457
+        $dn = $result[0]['dn'][0];
458
+
459
+        //and now the group name
460
+        //NOTE once we have separate Nextcloud group IDs and group names we can
461
+        //directly read the display name attribute instead of the DN
462
+        $name = $this->access->dn2groupname($dn);
463
+
464
+        $this->access->connection->writeToCache($cacheKey, $name);
465
+
466
+        return $name;
467
+    }
468
+
469
+    /**
470
+     * returns the entry's primary group ID
471
+     * @param string $dn
472
+     * @param string $attribute
473
+     * @return string|bool
474
+     */
475
+    private function getEntryGroupID($dn, $attribute) {
476
+        $value = $this->access->readAttribute($dn, $attribute);
477
+        if(is_array($value) && !empty($value)) {
478
+            return $value[0];
479
+        }
480
+        return false;
481
+    }
482
+
483
+    /**
484
+     * returns the group's primary ID
485
+     * @param string $dn
486
+     * @return string|bool
487
+     */
488
+    public function getGroupPrimaryGroupID($dn) {
489
+        return $this->getEntryGroupID($dn, 'primaryGroupToken');
490
+    }
491
+
492
+    /**
493
+     * returns the user's primary group ID
494
+     * @param string $dn
495
+     * @return string|bool
496
+     */
497
+    public function getUserPrimaryGroupIDs($dn) {
498
+        $primaryGroupID = false;
499
+        if($this->access->connection->hasPrimaryGroups) {
500
+            $primaryGroupID = $this->getEntryGroupID($dn, 'primaryGroupID');
501
+            if($primaryGroupID === false) {
502
+                $this->access->connection->hasPrimaryGroups = false;
503
+            }
504
+        }
505
+        return $primaryGroupID;
506
+    }
507
+
508
+    /**
509
+     * returns a filter for a "users in primary group" search or count operation
510
+     *
511
+     * @param string $groupDN
512
+     * @param string $search
513
+     * @return string
514
+     * @throws \Exception
515
+     */
516
+    private function prepareFilterForUsersInPrimaryGroup($groupDN, $search = '') {
517
+        $groupID = $this->getGroupPrimaryGroupID($groupDN);
518
+        if($groupID === false) {
519
+            throw new \Exception('Not a valid group');
520
+        }
521
+
522
+        $filterParts = [];
523
+        $filterParts[] = $this->access->getFilterForUserCount();
524
+        if ($search !== '') {
525
+            $filterParts[] = $this->access->getFilterPartForUserSearch($search);
526
+        }
527
+        $filterParts[] = 'primaryGroupID=' . $groupID;
528
+
529
+        $filter = $this->access->combineFilterWithAnd($filterParts);
530
+
531
+        return $filter;
532
+    }
533
+
534
+    /**
535
+     * returns a list of users that have the given group as primary group
536
+     *
537
+     * @param string $groupDN
538
+     * @param string $search
539
+     * @param int $limit
540
+     * @param int $offset
541
+     * @return string[]
542
+     */
543
+    public function getUsersInPrimaryGroup($groupDN, $search = '', $limit = -1, $offset = 0) {
544
+        try {
545
+            $filter = $this->prepareFilterForUsersInPrimaryGroup($groupDN, $search);
546
+            $users = $this->access->fetchListOfUsers(
547
+                $filter,
548
+                array($this->access->connection->ldapUserDisplayName, 'dn'),
549
+                $limit,
550
+                $offset
551
+            );
552
+            return $this->access->nextcloudUserNames($users);
553
+        } catch (\Exception $e) {
554
+            return array();
555
+        }
556
+    }
557
+
558
+    /**
559
+     * returns the number of users that have the given group as primary group
560
+     *
561
+     * @param string $groupDN
562
+     * @param string $search
563
+     * @param int $limit
564
+     * @param int $offset
565
+     * @return int
566
+     */
567
+    public function countUsersInPrimaryGroup($groupDN, $search = '', $limit = -1, $offset = 0) {
568
+        try {
569
+            $filter = $this->prepareFilterForUsersInPrimaryGroup($groupDN, $search);
570
+            $users = $this->access->countUsers($filter, array('dn'), $limit, $offset);
571
+            return (int)$users;
572
+        } catch (\Exception $e) {
573
+            return 0;
574
+        }
575
+    }
576
+
577
+    /**
578
+     * gets the primary group of a user
579
+     * @param string $dn
580
+     * @return string
581
+     */
582
+    public function getUserPrimaryGroup($dn) {
583
+        $groupID = $this->getUserPrimaryGroupIDs($dn);
584
+        if($groupID !== false) {
585
+            $groupName = $this->primaryGroupID2Name($groupID, $dn);
586
+            if($groupName !== false) {
587
+                return $groupName;
588
+            }
589
+        }
590
+
591
+        return false;
592
+    }
593
+
594
+    /**
595
+     * Get all groups a user belongs to
596
+     * @param string $uid Name of the user
597
+     * @return array with group names
598
+     *
599
+     * This function fetches all groups a user belongs to. It does not check
600
+     * if the user exists at all.
601
+     *
602
+     * This function includes groups based on dynamic group membership.
603
+     */
604
+    public function getUserGroups($uid) {
605
+        if(!$this->enabled) {
606
+            return array();
607
+        }
608
+        $cacheKey = 'getUserGroups'.$uid;
609
+        $userGroups = $this->access->connection->getFromCache($cacheKey);
610
+        if(!is_null($userGroups)) {
611
+            return $userGroups;
612
+        }
613
+        $userDN = $this->access->username2dn($uid);
614
+        if(!$userDN) {
615
+            $this->access->connection->writeToCache($cacheKey, array());
616
+            return array();
617
+        }
618
+
619
+        $groups = [];
620
+        $primaryGroup = $this->getUserPrimaryGroup($userDN);
621
+        $gidGroupName = $this->getUserGroupByGid($userDN);
622
+
623
+        $dynamicGroupMemberURL = strtolower($this->access->connection->ldapDynamicGroupMemberURL);
624
+
625
+        if (!empty($dynamicGroupMemberURL)) {
626
+            // look through dynamic groups to add them to the result array if needed
627
+            $groupsToMatch = $this->access->fetchListOfGroups(
628
+                $this->access->connection->ldapGroupFilter,array('dn',$dynamicGroupMemberURL));
629
+            foreach($groupsToMatch as $dynamicGroup) {
630
+                if (!array_key_exists($dynamicGroupMemberURL, $dynamicGroup)) {
631
+                    continue;
632
+                }
633
+                $pos = strpos($dynamicGroup[$dynamicGroupMemberURL][0], '(');
634
+                if ($pos !== false) {
635
+                    $memberUrlFilter = substr($dynamicGroup[$dynamicGroupMemberURL][0],$pos);
636
+                    // apply filter via ldap search to see if this user is in this
637
+                    // dynamic group
638
+                    $userMatch = $this->access->readAttribute(
639
+                        $userDN,
640
+                        $this->access->connection->ldapUserDisplayName,
641
+                        $memberUrlFilter
642
+                    );
643
+                    if ($userMatch !== false) {
644
+                        // match found so this user is in this group
645
+                        $groupName = $this->access->dn2groupname($dynamicGroup['dn'][0]);
646
+                        if(is_string($groupName)) {
647
+                            // be sure to never return false if the dn could not be
648
+                            // resolved to a name, for whatever reason.
649
+                            $groups[] = $groupName;
650
+                        }
651
+                    }
652
+                } else {
653
+                    \OCP\Util::writeLog('user_ldap', 'No search filter found on member url '.
654
+                        'of group ' . print_r($dynamicGroup, true), \OCP\Util::DEBUG);
655
+                }
656
+            }
657
+        }
658
+
659
+        // if possible, read out membership via memberOf. It's far faster than
660
+        // performing a search, which still is a fallback later.
661
+        // memberof doesn't support memberuid, so skip it here.
662
+        if(intval($this->access->connection->hasMemberOfFilterSupport) === 1
663
+            && intval($this->access->connection->useMemberOfToDetectMembership) === 1
664
+            && strtolower($this->access->connection->ldapGroupMemberAssocAttr) !== 'memberuid'
665
+            ) {
666
+            $groupDNs = $this->_getGroupDNsFromMemberOf($userDN);
667
+            if (is_array($groupDNs)) {
668
+                foreach ($groupDNs as $dn) {
669
+                    $groupName = $this->access->dn2groupname($dn);
670
+                    if(is_string($groupName)) {
671
+                        // be sure to never return false if the dn could not be
672
+                        // resolved to a name, for whatever reason.
673
+                        $groups[] = $groupName;
674
+                    }
675
+                }
676
+            }
677
+
678
+            if($primaryGroup !== false) {
679
+                $groups[] = $primaryGroup;
680
+            }
681
+            if($gidGroupName !== false) {
682
+                $groups[] = $gidGroupName;
683
+            }
684
+            $this->access->connection->writeToCache($cacheKey, $groups);
685
+            return $groups;
686
+        }
687
+
688
+        //uniqueMember takes DN, memberuid the uid, so we need to distinguish
689
+        if((strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'uniquemember')
690
+            || (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'member')
691
+        ) {
692
+            $uid = $userDN;
693
+        } else if(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') {
694
+            $result = $this->access->readAttribute($userDN, 'uid');
695
+            if ($result === false) {
696
+                \OCP\Util::writeLog('user_ldap', 'No uid attribute found for DN ' . $userDN . ' on '.
697
+                    $this->access->connection->ldapHost, \OCP\Util::DEBUG);
698
+            }
699
+            $uid = $result[0];
700
+        } else {
701
+            // just in case
702
+            $uid = $userDN;
703
+        }
704
+
705
+        if(isset($this->cachedGroupsByMember[$uid])) {
706
+            $groups = array_merge($groups, $this->cachedGroupsByMember[$uid]);
707
+        } else {
708
+            $groupsByMember = array_values($this->getGroupsByMember($uid));
709
+            $groupsByMember = $this->access->nextcloudGroupNames($groupsByMember);
710
+            $this->cachedGroupsByMember[$uid] = $groupsByMember;
711
+            $groups = array_merge($groups, $groupsByMember);
712
+        }
713
+
714
+        if($primaryGroup !== false) {
715
+            $groups[] = $primaryGroup;
716
+        }
717
+        if($gidGroupName !== false) {
718
+            $groups[] = $gidGroupName;
719
+        }
720
+
721
+        $groups = array_unique($groups, SORT_LOCALE_STRING);
722
+        $this->access->connection->writeToCache($cacheKey, $groups);
723
+
724
+        return $groups;
725
+    }
726
+
727
+    /**
728
+     * @param string $dn
729
+     * @param array|null &$seen
730
+     * @return array
731
+     */
732
+    private function getGroupsByMember($dn, &$seen = null) {
733
+        if ($seen === null) {
734
+            $seen = array();
735
+        }
736
+        $allGroups = array();
737
+        if (array_key_exists($dn, $seen)) {
738
+            // avoid loops
739
+            return array();
740
+        }
741
+        $seen[$dn] = true;
742
+        $filter = $this->access->combineFilterWithAnd(array(
743
+            $this->access->connection->ldapGroupFilter,
744
+            $this->access->connection->ldapGroupMemberAssocAttr.'='.$dn
745
+        ));
746
+        $groups = $this->access->fetchListOfGroups($filter,
747
+            array($this->access->connection->ldapGroupDisplayName, 'dn'));
748
+        if (is_array($groups)) {
749
+            foreach ($groups as $groupobj) {
750
+                $groupDN = $groupobj['dn'][0];
751
+                $allGroups[$groupDN] = $groupobj;
752
+                $nestedGroups = $this->access->connection->ldapNestedGroups;
753
+                if (!empty($nestedGroups)) {
754
+                    $supergroups = $this->getGroupsByMember($groupDN, $seen);
755
+                    if (is_array($supergroups) && (count($supergroups)>0)) {
756
+                        $allGroups = array_merge($allGroups, $supergroups);
757
+                    }
758
+                }
759
+            }
760
+        }
761
+        return $allGroups;
762
+    }
763
+
764
+    /**
765
+     * get a list of all users in a group
766
+     *
767
+     * @param string $gid
768
+     * @param string $search
769
+     * @param int $limit
770
+     * @param int $offset
771
+     * @return array with user ids
772
+     */
773
+    public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) {
774
+        if(!$this->enabled) {
775
+            return array();
776
+        }
777
+        if(!$this->groupExists($gid)) {
778
+            return array();
779
+        }
780
+        $search = $this->access->escapeFilterPart($search, true);
781
+        $cacheKey = 'usersInGroup-'.$gid.'-'.$search.'-'.$limit.'-'.$offset;
782
+        // check for cache of the exact query
783
+        $groupUsers = $this->access->connection->getFromCache($cacheKey);
784
+        if(!is_null($groupUsers)) {
785
+            return $groupUsers;
786
+        }
787
+
788
+        // check for cache of the query without limit and offset
789
+        $groupUsers = $this->access->connection->getFromCache('usersInGroup-'.$gid.'-'.$search);
790
+        if(!is_null($groupUsers)) {
791
+            $groupUsers = array_slice($groupUsers, $offset, $limit);
792
+            $this->access->connection->writeToCache($cacheKey, $groupUsers);
793
+            return $groupUsers;
794
+        }
795
+
796
+        if($limit === -1) {
797
+            $limit = null;
798
+        }
799
+        $groupDN = $this->access->groupname2dn($gid);
800
+        if(!$groupDN) {
801
+            // group couldn't be found, return empty resultset
802
+            $this->access->connection->writeToCache($cacheKey, array());
803
+            return array();
804
+        }
805
+
806
+        $primaryUsers = $this->getUsersInPrimaryGroup($groupDN, $search, $limit, $offset);
807
+        $posixGroupUsers = $this->getUsersInGidNumber($groupDN, $search, $limit, $offset);
808
+        $members = array_keys($this->_groupMembers($groupDN));
809
+        if(!$members && empty($posixGroupUsers) && empty($primaryUsers)) {
810
+            //in case users could not be retrieved, return empty result set
811
+            $this->access->connection->writeToCache($cacheKey, []);
812
+            return [];
813
+        }
814
+
815
+        $groupUsers = array();
816
+        $isMemberUid = (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid');
817
+        $attrs = $this->access->userManager->getAttributes(true);
818
+        foreach($members as $member) {
819
+            if($isMemberUid) {
820
+                //we got uids, need to get their DNs to 'translate' them to user names
821
+                $filter = $this->access->combineFilterWithAnd(array(
822
+                    str_replace('%uid', $member, $this->access->connection->ldapLoginFilter),
823
+                    $this->access->getFilterPartForUserSearch($search)
824
+                ));
825
+                $ldap_users = $this->access->fetchListOfUsers($filter, $attrs, 1);
826
+                if(count($ldap_users) < 1) {
827
+                    continue;
828
+                }
829
+                $groupUsers[] = $this->access->dn2username($ldap_users[0]['dn'][0]);
830
+            } else {
831
+                //we got DNs, check if we need to filter by search or we can give back all of them
832
+                if ($search !== '') {
833
+                    if(!$this->access->readAttribute($member,
834
+                        $this->access->connection->ldapUserDisplayName,
835
+                        $this->access->getFilterPartForUserSearch($search))) {
836
+                        continue;
837
+                    }
838
+                }
839
+                // dn2username will also check if the users belong to the allowed base
840
+                if($ocname = $this->access->dn2username($member)) {
841
+                    $groupUsers[] = $ocname;
842
+                }
843
+            }
844
+        }
845
+
846
+        $groupUsers = array_unique(array_merge($groupUsers, $primaryUsers, $posixGroupUsers));
847
+        natsort($groupUsers);
848
+        $this->access->connection->writeToCache('usersInGroup-'.$gid.'-'.$search, $groupUsers);
849
+        $groupUsers = array_slice($groupUsers, $offset, $limit);
850
+
851
+        $this->access->connection->writeToCache($cacheKey, $groupUsers);
852
+
853
+        return $groupUsers;
854
+    }
855
+
856
+    /**
857
+     * returns the number of users in a group, who match the search term
858
+     * @param string $gid the internal group name
859
+     * @param string $search optional, a search string
860
+     * @return int|bool
861
+     */
862
+    public function countUsersInGroup($gid, $search = '') {
863
+        $cacheKey = 'countUsersInGroup-'.$gid.'-'.$search;
864
+        if(!$this->enabled || !$this->groupExists($gid)) {
865
+            return false;
866
+        }
867
+        $groupUsers = $this->access->connection->getFromCache($cacheKey);
868
+        if(!is_null($groupUsers)) {
869
+            return $groupUsers;
870
+        }
871
+
872
+        $groupDN = $this->access->groupname2dn($gid);
873
+        if(!$groupDN) {
874
+            // group couldn't be found, return empty result set
875
+            $this->access->connection->writeToCache($cacheKey, false);
876
+            return false;
877
+        }
878
+
879
+        $members = array_keys($this->_groupMembers($groupDN));
880
+        $primaryUserCount = $this->countUsersInPrimaryGroup($groupDN, '');
881
+        if(!$members && $primaryUserCount === 0) {
882
+            //in case users could not be retrieved, return empty result set
883
+            $this->access->connection->writeToCache($cacheKey, false);
884
+            return false;
885
+        }
886
+
887
+        if ($search === '') {
888
+            $groupUsers = count($members) + $primaryUserCount;
889
+            $this->access->connection->writeToCache($cacheKey, $groupUsers);
890
+            return $groupUsers;
891
+        }
892
+        $search = $this->access->escapeFilterPart($search, true);
893
+        $isMemberUid =
894
+            (strtolower($this->access->connection->ldapGroupMemberAssocAttr)
895
+            === 'memberuid');
896
+
897
+        //we need to apply the search filter
898
+        //alternatives that need to be checked:
899
+        //a) get all users by search filter and array_intersect them
900
+        //b) a, but only when less than 1k 10k ?k users like it is
901
+        //c) put all DNs|uids in a LDAP filter, combine with the search string
902
+        //   and let it count.
903
+        //For now this is not important, because the only use of this method
904
+        //does not supply a search string
905
+        $groupUsers = array();
906
+        foreach($members as $member) {
907
+            if($isMemberUid) {
908
+                //we got uids, need to get their DNs to 'translate' them to user names
909
+                $filter = $this->access->combineFilterWithAnd(array(
910
+                    str_replace('%uid', $member, $this->access->connection->ldapLoginFilter),
911
+                    $this->access->getFilterPartForUserSearch($search)
912
+                ));
913
+                $ldap_users = $this->access->fetchListOfUsers($filter, 'dn', 1);
914
+                if(count($ldap_users) < 1) {
915
+                    continue;
916
+                }
917
+                $groupUsers[] = $this->access->dn2username($ldap_users[0]);
918
+            } else {
919
+                //we need to apply the search filter now
920
+                if(!$this->access->readAttribute($member,
921
+                    $this->access->connection->ldapUserDisplayName,
922
+                    $this->access->getFilterPartForUserSearch($search))) {
923
+                    continue;
924
+                }
925
+                // dn2username will also check if the users belong to the allowed base
926
+                if($ocname = $this->access->dn2username($member)) {
927
+                    $groupUsers[] = $ocname;
928
+                }
929
+            }
930
+        }
931
+
932
+        //and get users that have the group as primary
933
+        $primaryUsers = $this->countUsersInPrimaryGroup($groupDN, $search);
934
+
935
+        return count($groupUsers) + $primaryUsers;
936
+    }
937
+
938
+    /**
939
+     * get a list of all groups
940
+     *
941
+     * @param string $search
942
+     * @param $limit
943
+     * @param int $offset
944
+     * @return array with group names
945
+     *
946
+     * Returns a list with all groups (used by getGroups)
947
+     */
948
+    protected function getGroupsChunk($search = '', $limit = -1, $offset = 0) {
949
+        if(!$this->enabled) {
950
+            return array();
951
+        }
952
+        $cacheKey = 'getGroups-'.$search.'-'.$limit.'-'.$offset;
953
+
954
+        //Check cache before driving unnecessary searches
955
+        \OCP\Util::writeLog('user_ldap', 'getGroups '.$cacheKey, \OCP\Util::DEBUG);
956
+        $ldap_groups = $this->access->connection->getFromCache($cacheKey);
957
+        if(!is_null($ldap_groups)) {
958
+            return $ldap_groups;
959
+        }
960
+
961
+        // if we'd pass -1 to LDAP search, we'd end up in a Protocol
962
+        // error. With a limit of 0, we get 0 results. So we pass null.
963
+        if($limit <= 0) {
964
+            $limit = null;
965
+        }
966
+        $filter = $this->access->combineFilterWithAnd(array(
967
+            $this->access->connection->ldapGroupFilter,
968
+            $this->access->getFilterPartForGroupSearch($search)
969
+        ));
970
+        \OCP\Util::writeLog('user_ldap', 'getGroups Filter '.$filter, \OCP\Util::DEBUG);
971
+        $ldap_groups = $this->access->fetchListOfGroups($filter,
972
+                array($this->access->connection->ldapGroupDisplayName, 'dn'),
973
+                $limit,
974
+                $offset);
975
+        $ldap_groups = $this->access->nextcloudGroupNames($ldap_groups);
976
+
977
+        $this->access->connection->writeToCache($cacheKey, $ldap_groups);
978
+        return $ldap_groups;
979
+    }
980
+
981
+    /**
982
+     * get a list of all groups using a paged search
983
+     *
984
+     * @param string $search
985
+     * @param int $limit
986
+     * @param int $offset
987
+     * @return array with group names
988
+     *
989
+     * Returns a list with all groups
990
+     * Uses a paged search if available to override a
991
+     * server side search limit.
992
+     * (active directory has a limit of 1000 by default)
993
+     */
994
+    public function getGroups($search = '', $limit = -1, $offset = 0) {
995
+        if(!$this->enabled) {
996
+            return array();
997
+        }
998
+        $search = $this->access->escapeFilterPart($search, true);
999
+        $pagingSize = intval($this->access->connection->ldapPagingSize);
1000
+        if (!$this->access->connection->hasPagedResultSupport || $pagingSize <= 0) {
1001
+            return $this->getGroupsChunk($search, $limit, $offset);
1002
+        }
1003
+        $maxGroups = 100000; // limit max results (just for safety reasons)
1004
+        if ($limit > -1) {
1005
+            $overallLimit = min($limit + $offset, $maxGroups);
1006
+        } else {
1007
+            $overallLimit = $maxGroups;
1008
+        }
1009
+        $chunkOffset = $offset;
1010
+        $allGroups = array();
1011
+        while ($chunkOffset < $overallLimit) {
1012
+            $chunkLimit = min($pagingSize, $overallLimit - $chunkOffset);
1013
+            $ldapGroups = $this->getGroupsChunk($search, $chunkLimit, $chunkOffset);
1014
+            $nread = count($ldapGroups);
1015
+            \OCP\Util::writeLog('user_ldap', 'getGroups('.$search.'): read '.$nread.' at offset '.$chunkOffset.' (limit: '.$chunkLimit.')', \OCP\Util::DEBUG);
1016
+            if ($nread) {
1017
+                $allGroups = array_merge($allGroups, $ldapGroups);
1018
+                $chunkOffset += $nread;
1019
+            }
1020
+            if ($nread < $chunkLimit) {
1021
+                break;
1022
+            }
1023
+        }
1024
+        return $allGroups;
1025
+    }
1026
+
1027
+    /**
1028
+     * @param string $group
1029
+     * @return bool
1030
+     */
1031
+    public function groupMatchesFilter($group) {
1032
+        return (strripos($group, $this->groupSearch) !== false);
1033
+    }
1034
+
1035
+    /**
1036
+     * check if a group exists
1037
+     * @param string $gid
1038
+     * @return bool
1039
+     */
1040
+    public function groupExists($gid) {
1041
+        $groupExists = $this->access->connection->getFromCache('groupExists'.$gid);
1042
+        if(!is_null($groupExists)) {
1043
+            return (bool)$groupExists;
1044
+        }
1045
+
1046
+        //getting dn, if false the group does not exist. If dn, it may be mapped
1047
+        //only, requires more checking.
1048
+        $dn = $this->access->groupname2dn($gid);
1049
+        if(!$dn) {
1050
+            $this->access->connection->writeToCache('groupExists'.$gid, false);
1051
+            return false;
1052
+        }
1053
+
1054
+        //if group really still exists, we will be able to read its objectclass
1055
+        if(!is_array($this->access->readAttribute($dn, ''))) {
1056
+            $this->access->connection->writeToCache('groupExists'.$gid, false);
1057
+            return false;
1058
+        }
1059
+
1060
+        $this->access->connection->writeToCache('groupExists'.$gid, true);
1061
+        return true;
1062
+    }
1063
+
1064
+    /**
1065
+     * Check if backend implements actions
1066
+     * @param int $actions bitwise-or'ed actions
1067
+     * @return boolean
1068
+     *
1069
+     * Returns the supported actions as int to be
1070
+     * compared with \OC\User\Backend::CREATE_USER etc.
1071
+     */
1072
+    public function implementsActions($actions) {
1073
+        return (bool)(\OC\Group\Backend::COUNT_USERS & $actions);
1074
+    }
1075
+
1076
+    /**
1077
+     * Return access for LDAP interaction.
1078
+     * @return Access instance of Access for LDAP interaction
1079
+     */
1080
+    public function getLDAPAccess() {
1081
+        return $this->access;
1082
+    }
1083 1083
 }
Please login to merge, or discard this patch.
Spacing   +91 added lines, -91 removed lines patch added patch discarded remove patch
@@ -57,7 +57,7 @@  discard block
 block discarded – undo
57 57
 		parent::__construct($access);
58 58
 		$filter = $this->access->connection->ldapGroupFilter;
59 59
 		$gassoc = $this->access->connection->ldapGroupMemberAssocAttr;
60
-		if(!empty($filter) && !empty($gassoc)) {
60
+		if (!empty($filter) && !empty($gassoc)) {
61 61
 			$this->enabled = true;
62 62
 		}
63 63
 
@@ -74,25 +74,25 @@  discard block
 block discarded – undo
74 74
 	 * Checks whether the user is member of a group or not.
75 75
 	 */
76 76
 	public function inGroup($uid, $gid) {
77
-		if(!$this->enabled) {
77
+		if (!$this->enabled) {
78 78
 			return false;
79 79
 		}
80 80
 		$cacheKey = 'inGroup'.$uid.':'.$gid;
81 81
 		$inGroup = $this->access->connection->getFromCache($cacheKey);
82
-		if(!is_null($inGroup)) {
83
-			return (bool)$inGroup;
82
+		if (!is_null($inGroup)) {
83
+			return (bool) $inGroup;
84 84
 		}
85 85
 
86 86
 		$userDN = $this->access->username2dn($uid);
87 87
 
88
-		if(isset($this->cachedGroupMembers[$gid])) {
88
+		if (isset($this->cachedGroupMembers[$gid])) {
89 89
 			$isInGroup = in_array($userDN, $this->cachedGroupMembers[$gid]);
90 90
 			return $isInGroup;
91 91
 		}
92 92
 
93 93
 		$cacheKeyMembers = 'inGroup-members:'.$gid;
94 94
 		$members = $this->access->connection->getFromCache($cacheKeyMembers);
95
-		if(!is_null($members)) {
95
+		if (!is_null($members)) {
96 96
 			$this->cachedGroupMembers[$gid] = $members;
97 97
 			$isInGroup = in_array($userDN, $members);
98 98
 			$this->access->connection->writeToCache($cacheKey, $isInGroup);
@@ -101,13 +101,13 @@  discard block
 block discarded – undo
101 101
 
102 102
 		$groupDN = $this->access->groupname2dn($gid);
103 103
 		// just in case
104
-		if(!$groupDN || !$userDN) {
104
+		if (!$groupDN || !$userDN) {
105 105
 			$this->access->connection->writeToCache($cacheKey, false);
106 106
 			return false;
107 107
 		}
108 108
 
109 109
 		//check primary group first
110
-		if($gid === $this->getUserPrimaryGroup($userDN)) {
110
+		if ($gid === $this->getUserPrimaryGroup($userDN)) {
111 111
 			$this->access->connection->writeToCache($cacheKey, true);
112 112
 			return true;
113 113
 		}
@@ -115,21 +115,21 @@  discard block
 block discarded – undo
115 115
 		//usually, LDAP attributes are said to be case insensitive. But there are exceptions of course.
116 116
 		$members = $this->_groupMembers($groupDN);
117 117
 		$members = array_keys($members); // uids are returned as keys
118
-		if(!is_array($members) || count($members) === 0) {
118
+		if (!is_array($members) || count($members) === 0) {
119 119
 			$this->access->connection->writeToCache($cacheKey, false);
120 120
 			return false;
121 121
 		}
122 122
 
123 123
 		//extra work if we don't get back user DNs
124
-		if(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') {
124
+		if (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') {
125 125
 			$dns = array();
126 126
 			$filterParts = array();
127 127
 			$bytes = 0;
128
-			foreach($members as $mid) {
128
+			foreach ($members as $mid) {
129 129
 				$filter = str_replace('%uid', $mid, $this->access->connection->ldapLoginFilter);
130 130
 				$filterParts[] = $filter;
131 131
 				$bytes += strlen($filter);
132
-				if($bytes >= 9000000) {
132
+				if ($bytes >= 9000000) {
133 133
 					// AD has a default input buffer of 10 MB, we do not want
134 134
 					// to take even the chance to exceed it
135 135
 					$filter = $this->access->combineFilterWithOr($filterParts);
@@ -139,7 +139,7 @@  discard block
 block discarded – undo
139 139
 					$dns = array_merge($dns, $users);
140 140
 				}
141 141
 			}
142
-			if(count($filterParts) > 0) {
142
+			if (count($filterParts) > 0) {
143 143
 				$filter = $this->access->combineFilterWithOr($filterParts);
144 144
 				$users = $this->access->fetchListOfUsers($filter, 'dn', count($filterParts));
145 145
 				$dns = array_merge($dns, $users);
@@ -182,14 +182,14 @@  discard block
 block discarded – undo
182 182
 			$pos = strpos($memberURLs[0], '(');
183 183
 			if ($pos !== false) {
184 184
 				$memberUrlFilter = substr($memberURLs[0], $pos);
185
-				$foundMembers = $this->access->searchUsers($memberUrlFilter,'dn');
185
+				$foundMembers = $this->access->searchUsers($memberUrlFilter, 'dn');
186 186
 				$dynamicMembers = array();
187
-				foreach($foundMembers as $value) {
187
+				foreach ($foundMembers as $value) {
188 188
 					$dynamicMembers[$value['dn'][0]] = 1;
189 189
 				}
190 190
 			} else {
191 191
 				\OCP\Util::writeLog('user_ldap', 'No search filter found on member url '.
192
-					'of group ' . $dnGroup, \OCP\Util::DEBUG);
192
+					'of group '.$dnGroup, \OCP\Util::DEBUG);
193 193
 			}
194 194
 		}
195 195
 		return $dynamicMembers;
@@ -212,7 +212,7 @@  discard block
 block discarded – undo
212 212
 		// used extensively in cron job, caching makes sense for nested groups
213 213
 		$cacheKey = '_groupMembers'.$dnGroup;
214 214
 		$groupMembers = $this->access->connection->getFromCache($cacheKey);
215
-		if(!is_null($groupMembers)) {
215
+		if (!is_null($groupMembers)) {
216 216
 			return $groupMembers;
217 217
 		}
218 218
 		$seen[$dnGroup] = 1;
@@ -256,7 +256,7 @@  discard block
 block discarded – undo
256 256
 			return array();
257 257
 		}
258 258
 		$groups = $this->access->groupsMatchFilter($groups);
259
-		$allGroups =  $groups;
259
+		$allGroups = $groups;
260 260
 		$nestedGroups = $this->access->connection->ldapNestedGroups;
261 261
 		if (intval($nestedGroups) === 1) {
262 262
 			foreach ($groups as $group) {
@@ -274,9 +274,9 @@  discard block
 block discarded – undo
274 274
 	 * @return string|bool
275 275
 	 */
276 276
 	public function gidNumber2Name($gid, $dn) {
277
-		$cacheKey = 'gidNumberToName' . $gid;
277
+		$cacheKey = 'gidNumberToName'.$gid;
278 278
 		$groupName = $this->access->connection->getFromCache($cacheKey);
279
-		if(!is_null($groupName) && isset($groupName)) {
279
+		if (!is_null($groupName) && isset($groupName)) {
280 280
 			return $groupName;
281 281
 		}
282 282
 
@@ -284,10 +284,10 @@  discard block
 block discarded – undo
284 284
 		$filter = $this->access->combineFilterWithAnd([
285 285
 			$this->access->connection->ldapGroupFilter,
286 286
 			'objectClass=posixGroup',
287
-			$this->access->connection->ldapGidNumber . '=' . $gid
287
+			$this->access->connection->ldapGidNumber.'='.$gid
288 288
 		]);
289 289
 		$result = $this->access->searchGroups($filter, array('dn'), 1);
290
-		if(empty($result)) {
290
+		if (empty($result)) {
291 291
 			return false;
292 292
 		}
293 293
 		$dn = $result[0]['dn'][0];
@@ -310,7 +310,7 @@  discard block
 block discarded – undo
310 310
 	 */
311 311
 	private function getEntryGidNumber($dn, $attribute) {
312 312
 		$value = $this->access->readAttribute($dn, $attribute);
313
-		if(is_array($value) && !empty($value)) {
313
+		if (is_array($value) && !empty($value)) {
314 314
 			return $value[0];
315 315
 		}
316 316
 		return false;
@@ -332,9 +332,9 @@  discard block
 block discarded – undo
332 332
 	 */
333 333
 	public function getUserGidNumber($dn) {
334 334
 		$gidNumber = false;
335
-		if($this->access->connection->hasGidNumber) {
335
+		if ($this->access->connection->hasGidNumber) {
336 336
 			$gidNumber = $this->getEntryGidNumber($dn, 'gidNumber');
337
-			if($gidNumber === false) {
337
+			if ($gidNumber === false) {
338 338
 				$this->access->connection->hasGidNumber = false;
339 339
 			}
340 340
 		}
@@ -351,7 +351,7 @@  discard block
 block discarded – undo
351 351
 	 */
352 352
 	private function prepareFilterForUsersHasGidNumber($groupDN, $search = '') {
353 353
 		$groupID = $this->getGroupGidNumber($groupDN);
354
-		if($groupID === false) {
354
+		if ($groupID === false) {
355 355
 			throw new \Exception('Not a valid group');
356 356
 		}
357 357
 
@@ -360,7 +360,7 @@  discard block
 block discarded – undo
360 360
 		if ($search !== '') {
361 361
 			$filterParts[] = $this->access->getFilterPartForUserSearch($search);
362 362
 		}
363
-		$filterParts[] = $this->access->connection->ldapGidNumber .'=' . $groupID;
363
+		$filterParts[] = $this->access->connection->ldapGidNumber.'='.$groupID;
364 364
 
365 365
 		$filter = $this->access->combineFilterWithAnd($filterParts);
366 366
 
@@ -404,7 +404,7 @@  discard block
 block discarded – undo
404 404
 		try {
405 405
 			$filter = $this->prepareFilterForUsersHasGidNumber($groupDN, $search);
406 406
 			$users = $this->access->countUsers($filter, ['dn'], $limit, $offset);
407
-			return (int)$users;
407
+			return (int) $users;
408 408
 		} catch (\Exception $e) {
409 409
 			return 0;
410 410
 		}
@@ -417,9 +417,9 @@  discard block
 block discarded – undo
417 417
 	 */
418 418
 	public function getUserGroupByGid($dn) {
419 419
 		$groupID = $this->getUserGidNumber($dn);
420
-		if($groupID !== false) {
420
+		if ($groupID !== false) {
421 421
 			$groupName = $this->gidNumber2Name($groupID, $dn);
422
-			if($groupName !== false) {
422
+			if ($groupName !== false) {
423 423
 				return $groupName;
424 424
 			}
425 425
 		}
@@ -436,22 +436,22 @@  discard block
 block discarded – undo
436 436
 	public function primaryGroupID2Name($gid, $dn) {
437 437
 		$cacheKey = 'primaryGroupIDtoName';
438 438
 		$groupNames = $this->access->connection->getFromCache($cacheKey);
439
-		if(!is_null($groupNames) && isset($groupNames[$gid])) {
439
+		if (!is_null($groupNames) && isset($groupNames[$gid])) {
440 440
 			return $groupNames[$gid];
441 441
 		}
442 442
 
443 443
 		$domainObjectSid = $this->access->getSID($dn);
444
-		if($domainObjectSid === false) {
444
+		if ($domainObjectSid === false) {
445 445
 			return false;
446 446
 		}
447 447
 
448 448
 		//we need to get the DN from LDAP
449 449
 		$filter = $this->access->combineFilterWithAnd(array(
450 450
 			$this->access->connection->ldapGroupFilter,
451
-			'objectsid=' . $domainObjectSid . '-' . $gid
451
+			'objectsid='.$domainObjectSid.'-'.$gid
452 452
 		));
453 453
 		$result = $this->access->searchGroups($filter, array('dn'), 1);
454
-		if(empty($result)) {
454
+		if (empty($result)) {
455 455
 			return false;
456 456
 		}
457 457
 		$dn = $result[0]['dn'][0];
@@ -474,7 +474,7 @@  discard block
 block discarded – undo
474 474
 	 */
475 475
 	private function getEntryGroupID($dn, $attribute) {
476 476
 		$value = $this->access->readAttribute($dn, $attribute);
477
-		if(is_array($value) && !empty($value)) {
477
+		if (is_array($value) && !empty($value)) {
478 478
 			return $value[0];
479 479
 		}
480 480
 		return false;
@@ -496,9 +496,9 @@  discard block
 block discarded – undo
496 496
 	 */
497 497
 	public function getUserPrimaryGroupIDs($dn) {
498 498
 		$primaryGroupID = false;
499
-		if($this->access->connection->hasPrimaryGroups) {
499
+		if ($this->access->connection->hasPrimaryGroups) {
500 500
 			$primaryGroupID = $this->getEntryGroupID($dn, 'primaryGroupID');
501
-			if($primaryGroupID === false) {
501
+			if ($primaryGroupID === false) {
502 502
 				$this->access->connection->hasPrimaryGroups = false;
503 503
 			}
504 504
 		}
@@ -515,7 +515,7 @@  discard block
 block discarded – undo
515 515
 	 */
516 516
 	private function prepareFilterForUsersInPrimaryGroup($groupDN, $search = '') {
517 517
 		$groupID = $this->getGroupPrimaryGroupID($groupDN);
518
-		if($groupID === false) {
518
+		if ($groupID === false) {
519 519
 			throw new \Exception('Not a valid group');
520 520
 		}
521 521
 
@@ -524,7 +524,7 @@  discard block
 block discarded – undo
524 524
 		if ($search !== '') {
525 525
 			$filterParts[] = $this->access->getFilterPartForUserSearch($search);
526 526
 		}
527
-		$filterParts[] = 'primaryGroupID=' . $groupID;
527
+		$filterParts[] = 'primaryGroupID='.$groupID;
528 528
 
529 529
 		$filter = $this->access->combineFilterWithAnd($filterParts);
530 530
 
@@ -568,7 +568,7 @@  discard block
 block discarded – undo
568 568
 		try {
569 569
 			$filter = $this->prepareFilterForUsersInPrimaryGroup($groupDN, $search);
570 570
 			$users = $this->access->countUsers($filter, array('dn'), $limit, $offset);
571
-			return (int)$users;
571
+			return (int) $users;
572 572
 		} catch (\Exception $e) {
573 573
 			return 0;
574 574
 		}
@@ -581,9 +581,9 @@  discard block
 block discarded – undo
581 581
 	 */
582 582
 	public function getUserPrimaryGroup($dn) {
583 583
 		$groupID = $this->getUserPrimaryGroupIDs($dn);
584
-		if($groupID !== false) {
584
+		if ($groupID !== false) {
585 585
 			$groupName = $this->primaryGroupID2Name($groupID, $dn);
586
-			if($groupName !== false) {
586
+			if ($groupName !== false) {
587 587
 				return $groupName;
588 588
 			}
589 589
 		}
@@ -602,16 +602,16 @@  discard block
 block discarded – undo
602 602
 	 * This function includes groups based on dynamic group membership.
603 603
 	 */
604 604
 	public function getUserGroups($uid) {
605
-		if(!$this->enabled) {
605
+		if (!$this->enabled) {
606 606
 			return array();
607 607
 		}
608 608
 		$cacheKey = 'getUserGroups'.$uid;
609 609
 		$userGroups = $this->access->connection->getFromCache($cacheKey);
610
-		if(!is_null($userGroups)) {
610
+		if (!is_null($userGroups)) {
611 611
 			return $userGroups;
612 612
 		}
613 613
 		$userDN = $this->access->username2dn($uid);
614
-		if(!$userDN) {
614
+		if (!$userDN) {
615 615
 			$this->access->connection->writeToCache($cacheKey, array());
616 616
 			return array();
617 617
 		}
@@ -625,14 +625,14 @@  discard block
 block discarded – undo
625 625
 		if (!empty($dynamicGroupMemberURL)) {
626 626
 			// look through dynamic groups to add them to the result array if needed
627 627
 			$groupsToMatch = $this->access->fetchListOfGroups(
628
-				$this->access->connection->ldapGroupFilter,array('dn',$dynamicGroupMemberURL));
629
-			foreach($groupsToMatch as $dynamicGroup) {
628
+				$this->access->connection->ldapGroupFilter, array('dn', $dynamicGroupMemberURL));
629
+			foreach ($groupsToMatch as $dynamicGroup) {
630 630
 				if (!array_key_exists($dynamicGroupMemberURL, $dynamicGroup)) {
631 631
 					continue;
632 632
 				}
633 633
 				$pos = strpos($dynamicGroup[$dynamicGroupMemberURL][0], '(');
634 634
 				if ($pos !== false) {
635
-					$memberUrlFilter = substr($dynamicGroup[$dynamicGroupMemberURL][0],$pos);
635
+					$memberUrlFilter = substr($dynamicGroup[$dynamicGroupMemberURL][0], $pos);
636 636
 					// apply filter via ldap search to see if this user is in this
637 637
 					// dynamic group
638 638
 					$userMatch = $this->access->readAttribute(
@@ -643,7 +643,7 @@  discard block
 block discarded – undo
643 643
 					if ($userMatch !== false) {
644 644
 						// match found so this user is in this group
645 645
 						$groupName = $this->access->dn2groupname($dynamicGroup['dn'][0]);
646
-						if(is_string($groupName)) {
646
+						if (is_string($groupName)) {
647 647
 							// be sure to never return false if the dn could not be
648 648
 							// resolved to a name, for whatever reason.
649 649
 							$groups[] = $groupName;
@@ -651,7 +651,7 @@  discard block
 block discarded – undo
651 651
 					}
652 652
 				} else {
653 653
 					\OCP\Util::writeLog('user_ldap', 'No search filter found on member url '.
654
-						'of group ' . print_r($dynamicGroup, true), \OCP\Util::DEBUG);
654
+						'of group '.print_r($dynamicGroup, true), \OCP\Util::DEBUG);
655 655
 				}
656 656
 			}
657 657
 		}
@@ -659,7 +659,7 @@  discard block
 block discarded – undo
659 659
 		// if possible, read out membership via memberOf. It's far faster than
660 660
 		// performing a search, which still is a fallback later.
661 661
 		// memberof doesn't support memberuid, so skip it here.
662
-		if(intval($this->access->connection->hasMemberOfFilterSupport) === 1
662
+		if (intval($this->access->connection->hasMemberOfFilterSupport) === 1
663 663
 			&& intval($this->access->connection->useMemberOfToDetectMembership) === 1
664 664
 		    && strtolower($this->access->connection->ldapGroupMemberAssocAttr) !== 'memberuid'
665 665
 		    ) {
@@ -667,7 +667,7 @@  discard block
 block discarded – undo
667 667
 			if (is_array($groupDNs)) {
668 668
 				foreach ($groupDNs as $dn) {
669 669
 					$groupName = $this->access->dn2groupname($dn);
670
-					if(is_string($groupName)) {
670
+					if (is_string($groupName)) {
671 671
 						// be sure to never return false if the dn could not be
672 672
 						// resolved to a name, for whatever reason.
673 673
 						$groups[] = $groupName;
@@ -675,10 +675,10 @@  discard block
 block discarded – undo
675 675
 				}
676 676
 			}
677 677
 
678
-			if($primaryGroup !== false) {
678
+			if ($primaryGroup !== false) {
679 679
 				$groups[] = $primaryGroup;
680 680
 			}
681
-			if($gidGroupName !== false) {
681
+			if ($gidGroupName !== false) {
682 682
 				$groups[] = $gidGroupName;
683 683
 			}
684 684
 			$this->access->connection->writeToCache($cacheKey, $groups);
@@ -686,14 +686,14 @@  discard block
 block discarded – undo
686 686
 		}
687 687
 
688 688
 		//uniqueMember takes DN, memberuid the uid, so we need to distinguish
689
-		if((strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'uniquemember')
689
+		if ((strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'uniquemember')
690 690
 			|| (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'member')
691 691
 		) {
692 692
 			$uid = $userDN;
693
-		} else if(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') {
693
+		} else if (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') {
694 694
 			$result = $this->access->readAttribute($userDN, 'uid');
695 695
 			if ($result === false) {
696
-				\OCP\Util::writeLog('user_ldap', 'No uid attribute found for DN ' . $userDN . ' on '.
696
+				\OCP\Util::writeLog('user_ldap', 'No uid attribute found for DN '.$userDN.' on '.
697 697
 					$this->access->connection->ldapHost, \OCP\Util::DEBUG);
698 698
 			}
699 699
 			$uid = $result[0];
@@ -702,7 +702,7 @@  discard block
 block discarded – undo
702 702
 			$uid = $userDN;
703 703
 		}
704 704
 
705
-		if(isset($this->cachedGroupsByMember[$uid])) {
705
+		if (isset($this->cachedGroupsByMember[$uid])) {
706 706
 			$groups = array_merge($groups, $this->cachedGroupsByMember[$uid]);
707 707
 		} else {
708 708
 			$groupsByMember = array_values($this->getGroupsByMember($uid));
@@ -711,10 +711,10 @@  discard block
 block discarded – undo
711 711
 			$groups = array_merge($groups, $groupsByMember);
712 712
 		}
713 713
 
714
-		if($primaryGroup !== false) {
714
+		if ($primaryGroup !== false) {
715 715
 			$groups[] = $primaryGroup;
716 716
 		}
717
-		if($gidGroupName !== false) {
717
+		if ($gidGroupName !== false) {
718 718
 			$groups[] = $gidGroupName;
719 719
 		}
720 720
 
@@ -752,7 +752,7 @@  discard block
 block discarded – undo
752 752
 				$nestedGroups = $this->access->connection->ldapNestedGroups;
753 753
 				if (!empty($nestedGroups)) {
754 754
 					$supergroups = $this->getGroupsByMember($groupDN, $seen);
755
-					if (is_array($supergroups) && (count($supergroups)>0)) {
755
+					if (is_array($supergroups) && (count($supergroups) > 0)) {
756 756
 						$allGroups = array_merge($allGroups, $supergroups);
757 757
 					}
758 758
 				}
@@ -771,33 +771,33 @@  discard block
 block discarded – undo
771 771
 	 * @return array with user ids
772 772
 	 */
773 773
 	public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) {
774
-		if(!$this->enabled) {
774
+		if (!$this->enabled) {
775 775
 			return array();
776 776
 		}
777
-		if(!$this->groupExists($gid)) {
777
+		if (!$this->groupExists($gid)) {
778 778
 			return array();
779 779
 		}
780 780
 		$search = $this->access->escapeFilterPart($search, true);
781 781
 		$cacheKey = 'usersInGroup-'.$gid.'-'.$search.'-'.$limit.'-'.$offset;
782 782
 		// check for cache of the exact query
783 783
 		$groupUsers = $this->access->connection->getFromCache($cacheKey);
784
-		if(!is_null($groupUsers)) {
784
+		if (!is_null($groupUsers)) {
785 785
 			return $groupUsers;
786 786
 		}
787 787
 
788 788
 		// check for cache of the query without limit and offset
789 789
 		$groupUsers = $this->access->connection->getFromCache('usersInGroup-'.$gid.'-'.$search);
790
-		if(!is_null($groupUsers)) {
790
+		if (!is_null($groupUsers)) {
791 791
 			$groupUsers = array_slice($groupUsers, $offset, $limit);
792 792
 			$this->access->connection->writeToCache($cacheKey, $groupUsers);
793 793
 			return $groupUsers;
794 794
 		}
795 795
 
796
-		if($limit === -1) {
796
+		if ($limit === -1) {
797 797
 			$limit = null;
798 798
 		}
799 799
 		$groupDN = $this->access->groupname2dn($gid);
800
-		if(!$groupDN) {
800
+		if (!$groupDN) {
801 801
 			// group couldn't be found, return empty resultset
802 802
 			$this->access->connection->writeToCache($cacheKey, array());
803 803
 			return array();
@@ -806,7 +806,7 @@  discard block
 block discarded – undo
806 806
 		$primaryUsers = $this->getUsersInPrimaryGroup($groupDN, $search, $limit, $offset);
807 807
 		$posixGroupUsers = $this->getUsersInGidNumber($groupDN, $search, $limit, $offset);
808 808
 		$members = array_keys($this->_groupMembers($groupDN));
809
-		if(!$members && empty($posixGroupUsers) && empty($primaryUsers)) {
809
+		if (!$members && empty($posixGroupUsers) && empty($primaryUsers)) {
810 810
 			//in case users could not be retrieved, return empty result set
811 811
 			$this->access->connection->writeToCache($cacheKey, []);
812 812
 			return [];
@@ -815,29 +815,29 @@  discard block
 block discarded – undo
815 815
 		$groupUsers = array();
816 816
 		$isMemberUid = (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid');
817 817
 		$attrs = $this->access->userManager->getAttributes(true);
818
-		foreach($members as $member) {
819
-			if($isMemberUid) {
818
+		foreach ($members as $member) {
819
+			if ($isMemberUid) {
820 820
 				//we got uids, need to get their DNs to 'translate' them to user names
821 821
 				$filter = $this->access->combineFilterWithAnd(array(
822 822
 					str_replace('%uid', $member, $this->access->connection->ldapLoginFilter),
823 823
 					$this->access->getFilterPartForUserSearch($search)
824 824
 				));
825 825
 				$ldap_users = $this->access->fetchListOfUsers($filter, $attrs, 1);
826
-				if(count($ldap_users) < 1) {
826
+				if (count($ldap_users) < 1) {
827 827
 					continue;
828 828
 				}
829 829
 				$groupUsers[] = $this->access->dn2username($ldap_users[0]['dn'][0]);
830 830
 			} else {
831 831
 				//we got DNs, check if we need to filter by search or we can give back all of them
832 832
 				if ($search !== '') {
833
-					if(!$this->access->readAttribute($member,
833
+					if (!$this->access->readAttribute($member,
834 834
 						$this->access->connection->ldapUserDisplayName,
835 835
 						$this->access->getFilterPartForUserSearch($search))) {
836 836
 						continue;
837 837
 					}
838 838
 				}
839 839
 				// dn2username will also check if the users belong to the allowed base
840
-				if($ocname = $this->access->dn2username($member)) {
840
+				if ($ocname = $this->access->dn2username($member)) {
841 841
 					$groupUsers[] = $ocname;
842 842
 				}
843 843
 			}
@@ -861,16 +861,16 @@  discard block
 block discarded – undo
861 861
 	 */
862 862
 	public function countUsersInGroup($gid, $search = '') {
863 863
 		$cacheKey = 'countUsersInGroup-'.$gid.'-'.$search;
864
-		if(!$this->enabled || !$this->groupExists($gid)) {
864
+		if (!$this->enabled || !$this->groupExists($gid)) {
865 865
 			return false;
866 866
 		}
867 867
 		$groupUsers = $this->access->connection->getFromCache($cacheKey);
868
-		if(!is_null($groupUsers)) {
868
+		if (!is_null($groupUsers)) {
869 869
 			return $groupUsers;
870 870
 		}
871 871
 
872 872
 		$groupDN = $this->access->groupname2dn($gid);
873
-		if(!$groupDN) {
873
+		if (!$groupDN) {
874 874
 			// group couldn't be found, return empty result set
875 875
 			$this->access->connection->writeToCache($cacheKey, false);
876 876
 			return false;
@@ -878,7 +878,7 @@  discard block
 block discarded – undo
878 878
 
879 879
 		$members = array_keys($this->_groupMembers($groupDN));
880 880
 		$primaryUserCount = $this->countUsersInPrimaryGroup($groupDN, '');
881
-		if(!$members && $primaryUserCount === 0) {
881
+		if (!$members && $primaryUserCount === 0) {
882 882
 			//in case users could not be retrieved, return empty result set
883 883
 			$this->access->connection->writeToCache($cacheKey, false);
884 884
 			return false;
@@ -903,27 +903,27 @@  discard block
 block discarded – undo
903 903
 		//For now this is not important, because the only use of this method
904 904
 		//does not supply a search string
905 905
 		$groupUsers = array();
906
-		foreach($members as $member) {
907
-			if($isMemberUid) {
906
+		foreach ($members as $member) {
907
+			if ($isMemberUid) {
908 908
 				//we got uids, need to get their DNs to 'translate' them to user names
909 909
 				$filter = $this->access->combineFilterWithAnd(array(
910 910
 					str_replace('%uid', $member, $this->access->connection->ldapLoginFilter),
911 911
 					$this->access->getFilterPartForUserSearch($search)
912 912
 				));
913 913
 				$ldap_users = $this->access->fetchListOfUsers($filter, 'dn', 1);
914
-				if(count($ldap_users) < 1) {
914
+				if (count($ldap_users) < 1) {
915 915
 					continue;
916 916
 				}
917 917
 				$groupUsers[] = $this->access->dn2username($ldap_users[0]);
918 918
 			} else {
919 919
 				//we need to apply the search filter now
920
-				if(!$this->access->readAttribute($member,
920
+				if (!$this->access->readAttribute($member,
921 921
 					$this->access->connection->ldapUserDisplayName,
922 922
 					$this->access->getFilterPartForUserSearch($search))) {
923 923
 					continue;
924 924
 				}
925 925
 				// dn2username will also check if the users belong to the allowed base
926
-				if($ocname = $this->access->dn2username($member)) {
926
+				if ($ocname = $this->access->dn2username($member)) {
927 927
 					$groupUsers[] = $ocname;
928 928
 				}
929 929
 			}
@@ -946,7 +946,7 @@  discard block
 block discarded – undo
946 946
 	 * Returns a list with all groups (used by getGroups)
947 947
 	 */
948 948
 	protected function getGroupsChunk($search = '', $limit = -1, $offset = 0) {
949
-		if(!$this->enabled) {
949
+		if (!$this->enabled) {
950 950
 			return array();
951 951
 		}
952 952
 		$cacheKey = 'getGroups-'.$search.'-'.$limit.'-'.$offset;
@@ -954,13 +954,13 @@  discard block
 block discarded – undo
954 954
 		//Check cache before driving unnecessary searches
955 955
 		\OCP\Util::writeLog('user_ldap', 'getGroups '.$cacheKey, \OCP\Util::DEBUG);
956 956
 		$ldap_groups = $this->access->connection->getFromCache($cacheKey);
957
-		if(!is_null($ldap_groups)) {
957
+		if (!is_null($ldap_groups)) {
958 958
 			return $ldap_groups;
959 959
 		}
960 960
 
961 961
 		// if we'd pass -1 to LDAP search, we'd end up in a Protocol
962 962
 		// error. With a limit of 0, we get 0 results. So we pass null.
963
-		if($limit <= 0) {
963
+		if ($limit <= 0) {
964 964
 			$limit = null;
965 965
 		}
966 966
 		$filter = $this->access->combineFilterWithAnd(array(
@@ -992,7 +992,7 @@  discard block
 block discarded – undo
992 992
 	 * (active directory has a limit of 1000 by default)
993 993
 	 */
994 994
 	public function getGroups($search = '', $limit = -1, $offset = 0) {
995
-		if(!$this->enabled) {
995
+		if (!$this->enabled) {
996 996
 			return array();
997 997
 		}
998 998
 		$search = $this->access->escapeFilterPart($search, true);
@@ -1039,20 +1039,20 @@  discard block
 block discarded – undo
1039 1039
 	 */
1040 1040
 	public function groupExists($gid) {
1041 1041
 		$groupExists = $this->access->connection->getFromCache('groupExists'.$gid);
1042
-		if(!is_null($groupExists)) {
1043
-			return (bool)$groupExists;
1042
+		if (!is_null($groupExists)) {
1043
+			return (bool) $groupExists;
1044 1044
 		}
1045 1045
 
1046 1046
 		//getting dn, if false the group does not exist. If dn, it may be mapped
1047 1047
 		//only, requires more checking.
1048 1048
 		$dn = $this->access->groupname2dn($gid);
1049
-		if(!$dn) {
1049
+		if (!$dn) {
1050 1050
 			$this->access->connection->writeToCache('groupExists'.$gid, false);
1051 1051
 			return false;
1052 1052
 		}
1053 1053
 
1054 1054
 		//if group really still exists, we will be able to read its objectclass
1055
-		if(!is_array($this->access->readAttribute($dn, ''))) {
1055
+		if (!is_array($this->access->readAttribute($dn, ''))) {
1056 1056
 			$this->access->connection->writeToCache('groupExists'.$gid, false);
1057 1057
 			return false;
1058 1058
 		}
@@ -1070,7 +1070,7 @@  discard block
 block discarded – undo
1070 1070
 	* compared with \OC\User\Backend::CREATE_USER etc.
1071 1071
 	*/
1072 1072
 	public function implementsActions($actions) {
1073
-		return (bool)(\OC\Group\Backend::COUNT_USERS & $actions);
1073
+		return (bool) (\OC\Group\Backend::COUNT_USERS & $actions);
1074 1074
 	}
1075 1075
 
1076 1076
 	/**
Please login to merge, or discard this patch.
lib/public/UserInterface.php 1 patch
Indentation   +57 added lines, -57 removed lines patch added patch discarded remove patch
@@ -40,68 +40,68 @@
 block discarded – undo
40 40
  */
41 41
 interface UserInterface {
42 42
 
43
-	/**
44
-	 * Check if backend implements actions
45
-	 * @param int $actions bitwise-or'ed actions
46
-	 * @return boolean
47
-	 *
48
-	 * Returns the supported actions as int to be
49
-	 * compared with \OC\User\Backend::CREATE_USER etc.
50
-	 * @since 4.5.0
51
-	 */
52
-	public function implementsActions($actions);
43
+    /**
44
+     * Check if backend implements actions
45
+     * @param int $actions bitwise-or'ed actions
46
+     * @return boolean
47
+     *
48
+     * Returns the supported actions as int to be
49
+     * compared with \OC\User\Backend::CREATE_USER etc.
50
+     * @since 4.5.0
51
+     */
52
+    public function implementsActions($actions);
53 53
 
54
-	/**
55
-	 * delete a user
56
-	 * @param string $uid The username of the user to delete
57
-	 * @return bool
58
-	 * @since 4.5.0
59
-	 */
60
-	public function deleteUser($uid);
54
+    /**
55
+     * delete a user
56
+     * @param string $uid The username of the user to delete
57
+     * @return bool
58
+     * @since 4.5.0
59
+     */
60
+    public function deleteUser($uid);
61 61
 
62
-	/**
63
-	 * Get a list of all users
64
-	 *
65
-	 * @param string $search
66
-	 * @param null|int $limit
67
-	 * @param null|int $offset
68
-	 * @return string[] an array of all uids
69
-	 * @since 4.5.0
70
-	 */
71
-	public function getUsers($search = '', $limit = null, $offset = null);
62
+    /**
63
+     * Get a list of all users
64
+     *
65
+     * @param string $search
66
+     * @param null|int $limit
67
+     * @param null|int $offset
68
+     * @return string[] an array of all uids
69
+     * @since 4.5.0
70
+     */
71
+    public function getUsers($search = '', $limit = null, $offset = null);
72 72
 
73
-	/**
74
-	 * check if a user exists
75
-	 * @param string $uid the username
76
-	 * @return boolean
77
-	 * @since 4.5.0
78
-	 */
79
-	public function userExists($uid);
73
+    /**
74
+     * check if a user exists
75
+     * @param string $uid the username
76
+     * @return boolean
77
+     * @since 4.5.0
78
+     */
79
+    public function userExists($uid);
80 80
 
81
-	/**
82
-	 * get display name of the user
83
-	 * @param string $uid user ID of the user
84
-	 * @return string display name
85
-	 * @since 4.5.0
86
-	 */
87
-	public function getDisplayName($uid);
81
+    /**
82
+     * get display name of the user
83
+     * @param string $uid user ID of the user
84
+     * @return string display name
85
+     * @since 4.5.0
86
+     */
87
+    public function getDisplayName($uid);
88 88
 
89
-	/**
90
-	 * Get a list of all display names and user ids.
91
-	 *
92
-	 * @param string $search
93
-	 * @param string|null $limit
94
-	 * @param string|null $offset
95
-	 * @return array an array of all displayNames (value) and the corresponding uids (key)
96
-	 * @since 4.5.0
97
-	 */
98
-	public function getDisplayNames($search = '', $limit = null, $offset = null);
89
+    /**
90
+     * Get a list of all display names and user ids.
91
+     *
92
+     * @param string $search
93
+     * @param string|null $limit
94
+     * @param string|null $offset
95
+     * @return array an array of all displayNames (value) and the corresponding uids (key)
96
+     * @since 4.5.0
97
+     */
98
+    public function getDisplayNames($search = '', $limit = null, $offset = null);
99 99
 
100
-	/**
101
-	 * Check if a user list is available or not
102
-	 * @return boolean if users can be listed or not
103
-	 * @since 4.5.0
104
-	 */
105
-	public function hasUserListings();
100
+    /**
101
+     * Check if a user list is available or not
102
+     * @return boolean if users can be listed or not
103
+     * @since 4.5.0
104
+     */
105
+    public function hasUserListings();
106 106
 
107 107
 }
Please login to merge, or discard this patch.