Completed
Pull Request — master (#1234)
by Morris
11:20
created
settings/templates/users/part.grouplist.php 1 patch
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -28,33 +28,33 @@
 block discarded – undo
28 28
 	</li>
29 29
 
30 30
 	<!-- The Admin Group -->
31
-	<?php foreach($_["adminGroup"] as $adminGroup): ?>
32
-		<li data-gid="admin" data-usercount="<?php if($adminGroup['usercount'] > 0) { p($adminGroup['usercount']); } ?>" class="isgroup">
31
+	<?php foreach ($_["adminGroup"] as $adminGroup): ?>
32
+		<li data-gid="admin" data-usercount="<?php if ($adminGroup['usercount'] > 0) { p($adminGroup['usercount']); } ?>" class="isgroup">
33 33
 			<a href="#"><span class="groupname"><?php p($l->t('Admins')); ?></span></a>
34 34
 			<span class="utils">
35
-				<span class="usercount"><?php if($adminGroup['usercount'] > 0) { p($adminGroup['usercount']); } ?></span>
35
+				<span class="usercount"><?php if ($adminGroup['usercount'] > 0) { p($adminGroup['usercount']); } ?></span>
36 36
 			</span>
37 37
 		</li>
38 38
 	<?php endforeach; ?>
39 39
 
40 40
 	<!-- Disabled Users -->
41 41
 	<?php $disabledUsersGroup = $_["disabledUsersGroup"] ?>
42
-	<li data-gid="_disabledUsers" data-usercount="<?php if($disabledUsersGroup['usercount'] > 0) { p($disabledUsersGroup['usercount']); } ?>" class="isgroup">
42
+	<li data-gid="_disabledUsers" data-usercount="<?php if ($disabledUsersGroup['usercount'] > 0) { p($disabledUsersGroup['usercount']); } ?>" class="isgroup">
43 43
 		<a href="#"><span class="groupname"><?php p($l->t('Disabled')); ?></span></a>
44 44
 		<span class="utils">
45
-			<span class="usercount"><?php if($disabledUsersGroup['usercount'] > 0) { p($disabledUsersGroup['usercount']); } ?></span>
45
+			<span class="usercount"><?php if ($disabledUsersGroup['usercount'] > 0) { p($disabledUsersGroup['usercount']); } ?></span>
46 46
 		</span>
47 47
 	</li>
48 48
 
49 49
 	<!--List of Groups-->
50
-	<?php foreach($_["groups"] as $group): ?>
50
+	<?php foreach ($_["groups"] as $group): ?>
51 51
 		<li data-gid="<?php p($group['name']) ?>" data-usercount="<?php p($group['usercount']) ?>" class="isgroup">
52 52
 			<a href="#" class="dorename">
53 53
 				<span class="groupname"><?php p($group['name']); ?></span>
54 54
 			</a>
55 55
 			<span class="utils">
56
-				<span class="usercount"><?php if($group['usercount'] > 0) { p($group['usercount']); } ?></span>
57
-				<?php if($_['isAdmin']): ?>
56
+				<span class="usercount"><?php if ($group['usercount'] > 0) { p($group['usercount']); } ?></span>
57
+				<?php if ($_['isAdmin']): ?>
58 58
 				<a href="#" class="action delete" original-title="<?php p($l->t('Delete'))?>">
59 59
 					<img src="<?php print_unescaped(image_path('core', 'actions/delete.svg')) ?>" />
60 60
 				</a>
Please login to merge, or discard this patch.
lib/private/User/Manager.php 2 patches
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -75,7 +75,7 @@  discard block
 block discarded – undo
75 75
 	public function __construct(IConfig $config) {
76 76
 		$this->config = $config;
77 77
 		$cachedUsers = &$this->cachedUsers;
78
-		$this->listen('\OC\User', 'postDelete', function ($user) use (&$cachedUsers) {
78
+		$this->listen('\OC\User', 'postDelete', function($user) use (&$cachedUsers) {
79 79
 			/** @var \OC\User\User $user */
80 80
 			unset($cachedUsers[$user->getUID()]);
81 81
 		});
@@ -188,7 +188,7 @@  discard block
 block discarded – undo
188 188
 		$result = $this->checkPasswordNoLogging($loginName, $password);
189 189
 
190 190
 		if ($result === false) {
191
-			\OC::$server->getLogger()->warning('Login failed: \''. $loginName .'\' (Remote IP: \''. \OC::$server->getRequest()->getRemoteAddress(). '\')', ['app' => 'core']);
191
+			\OC::$server->getLogger()->warning('Login failed: \''.$loginName.'\' (Remote IP: \''.\OC::$server->getRequest()->getRemoteAddress().'\')', ['app' => 'core']);
192 192
 		}
193 193
 
194 194
 		return $result;
@@ -237,7 +237,7 @@  discard block
 block discarded – undo
237 237
 			}
238 238
 		}
239 239
 
240
-		uasort($users, function ($a, $b) {
240
+		uasort($users, function($a, $b) {
241 241
 			/**
242 242
 			 * @var \OC\User\User $a
243 243
 			 * @var \OC\User\User $b
@@ -266,7 +266,7 @@  discard block
 block discarded – undo
266 266
 			}
267 267
 		}
268 268
 
269
-		usort($users, function ($a, $b) {
269
+		usort($users, function($a, $b) {
270 270
 			/**
271 271
 			 * @var \OC\User\User $a
272 272
 			 * @var \OC\User\User $b
@@ -340,13 +340,13 @@  discard block
 block discarded – undo
340 340
 		foreach ($this->backends as $backend) {
341 341
 			if ($backend->implementsActions(Backend::COUNT_USERS)) {
342 342
 				$backendUsers = $backend->countUsers();
343
-				if($backendUsers !== false) {
344
-					if($backend instanceof IUserBackend) {
343
+				if ($backendUsers !== false) {
344
+					if ($backend instanceof IUserBackend) {
345 345
 						$name = $backend->getBackendName();
346 346
 					} else {
347 347
 						$name = get_class($backend);
348 348
 					}
349
-					if(isset($userCountStatistics[$name])) {
349
+					if (isset($userCountStatistics[$name])) {
350 350
 						$userCountStatistics[$name] += $backendUsers;
351 351
 					} else {
352 352
 						$userCountStatistics[$name] = $backendUsers;
@@ -408,7 +408,7 @@  discard block
 block discarded – undo
408 408
 
409 409
 		$query = $queryBuilder->execute();
410 410
 
411
-		$result = (int)$query->fetchColumn();
411
+		$result = (int) $query->fetchColumn();
412 412
 		$query->closeCursor();
413 413
 
414 414
 		return $result;
@@ -430,7 +430,7 @@  discard block
 block discarded – undo
430 430
 
431 431
 		$query = $queryBuilder->execute();
432 432
 
433
-		$result = (int)$query->fetchColumn();
433
+		$result = (int) $query->fetchColumn();
434 434
 		$query->closeCursor();
435 435
 
436 436
 		return $result;
Please login to merge, or discard this patch.
Indentation   +473 added lines, -473 removed lines patch added patch discarded remove patch
@@ -55,477 +55,477 @@
 block discarded – undo
55 55
  * @package OC\User
56 56
  */
57 57
 class Manager extends PublicEmitter implements IUserManager {
58
-	/**
59
-	 * @var \OCP\UserInterface[] $backends
60
-	 */
61
-	private $backends = array();
62
-
63
-	/**
64
-	 * @var \OC\User\User[] $cachedUsers
65
-	 */
66
-	private $cachedUsers = array();
67
-
68
-	/**
69
-	 * @var \OCP\IConfig $config
70
-	 */
71
-	private $config;
72
-
73
-	/**
74
-	 * @param \OCP\IConfig $config
75
-	 */
76
-	public function __construct(IConfig $config) {
77
-		$this->config = $config;
78
-		$cachedUsers = &$this->cachedUsers;
79
-		$this->listen('\OC\User', 'postDelete', function ($user) use (&$cachedUsers) {
80
-			/** @var \OC\User\User $user */
81
-			unset($cachedUsers[$user->getUID()]);
82
-		});
83
-	}
84
-
85
-	/**
86
-	 * Get the active backends
87
-	 * @return \OCP\UserInterface[]
88
-	 */
89
-	public function getBackends() {
90
-		return $this->backends;
91
-	}
92
-
93
-	/**
94
-	 * register a user backend
95
-	 *
96
-	 * @param \OCP\UserInterface $backend
97
-	 */
98
-	public function registerBackend($backend) {
99
-		$this->backends[] = $backend;
100
-	}
101
-
102
-	/**
103
-	 * remove a user backend
104
-	 *
105
-	 * @param \OCP\UserInterface $backend
106
-	 */
107
-	public function removeBackend($backend) {
108
-		$this->cachedUsers = array();
109
-		if (($i = array_search($backend, $this->backends)) !== false) {
110
-			unset($this->backends[$i]);
111
-		}
112
-	}
113
-
114
-	/**
115
-	 * remove all user backends
116
-	 */
117
-	public function clearBackends() {
118
-		$this->cachedUsers = array();
119
-		$this->backends = array();
120
-	}
121
-
122
-	/**
123
-	 * get a user by user id
124
-	 *
125
-	 * @param string $uid
126
-	 * @return \OC\User\User|null Either the user or null if the specified user does not exist
127
-	 */
128
-	public function get($uid) {
129
-		if (isset($this->cachedUsers[$uid])) { //check the cache first to prevent having to loop over the backends
130
-			return $this->cachedUsers[$uid];
131
-		}
132
-		foreach ($this->backends as $backend) {
133
-			if ($backend->userExists($uid)) {
134
-				return $this->getUserObject($uid, $backend);
135
-			}
136
-		}
137
-		return null;
138
-	}
139
-
140
-	/**
141
-	 * get or construct the user object
142
-	 *
143
-	 * @param string $uid
144
-	 * @param \OCP\UserInterface $backend
145
-	 * @param bool $cacheUser If false the newly created user object will not be cached
146
-	 * @return \OC\User\User
147
-	 */
148
-	protected function getUserObject($uid, $backend, $cacheUser = true) {
149
-		if (isset($this->cachedUsers[$uid])) {
150
-			return $this->cachedUsers[$uid];
151
-		}
152
-
153
-		if (method_exists($backend, 'loginName2UserName')) {
154
-			$loginName = $backend->loginName2UserName($uid);
155
-			if ($loginName !== false) {
156
-				$uid = $loginName;
157
-			}
158
-			if (isset($this->cachedUsers[$uid])) {
159
-				return $this->cachedUsers[$uid];
160
-			}
161
-		}
162
-
163
-		$user = new User($uid, $backend, $this, $this->config);
164
-		if ($cacheUser) {
165
-			$this->cachedUsers[$uid] = $user;
166
-		}
167
-		return $user;
168
-	}
169
-
170
-	/**
171
-	 * check if a user exists
172
-	 *
173
-	 * @param string $uid
174
-	 * @return bool
175
-	 */
176
-	public function userExists($uid) {
177
-		$user = $this->get($uid);
178
-		return ($user !== null);
179
-	}
180
-
181
-	/**
182
-	 * Check if the password is valid for the user
183
-	 *
184
-	 * @param string $loginName
185
-	 * @param string $password
186
-	 * @return mixed the User object on success, false otherwise
187
-	 */
188
-	public function checkPassword($loginName, $password) {
189
-		$result = $this->checkPasswordNoLogging($loginName, $password);
190
-
191
-		if ($result === false) {
192
-			\OC::$server->getLogger()->warning('Login failed: \''. $loginName .'\' (Remote IP: \''. \OC::$server->getRequest()->getRemoteAddress(). '\')', ['app' => 'core']);
193
-		}
194
-
195
-		return $result;
196
-	}
197
-
198
-	/**
199
-	 * Check if the password is valid for the user
200
-	 *
201
-	 * @internal
202
-	 * @param string $loginName
203
-	 * @param string $password
204
-	 * @return mixed the User object on success, false otherwise
205
-	 */
206
-	public function checkPasswordNoLogging($loginName, $password) {
207
-		$loginName = str_replace("\0", '', $loginName);
208
-		$password = str_replace("\0", '', $password);
209
-
210
-		foreach ($this->backends as $backend) {
211
-			if ($backend->implementsActions(Backend::CHECK_PASSWORD)) {
212
-				$uid = $backend->checkPassword($loginName, $password);
213
-				if ($uid !== false) {
214
-					return $this->getUserObject($uid, $backend);
215
-				}
216
-			}
217
-		}
218
-
219
-		return false;
220
-	}
221
-
222
-	/**
223
-	 * search by user id
224
-	 *
225
-	 * @param string $pattern
226
-	 * @param int $limit
227
-	 * @param int $offset
228
-	 * @return \OC\User\User[]
229
-	 */
230
-	public function search($pattern, $limit = null, $offset = null) {
231
-		$users = array();
232
-		foreach ($this->backends as $backend) {
233
-			$backendUsers = $backend->getUsers($pattern, $limit, $offset);
234
-			if (is_array($backendUsers)) {
235
-				foreach ($backendUsers as $uid) {
236
-					$users[$uid] = $this->getUserObject($uid, $backend);
237
-				}
238
-			}
239
-		}
240
-
241
-		uasort($users, function ($a, $b) {
242
-			/**
243
-			 * @var \OC\User\User $a
244
-			 * @var \OC\User\User $b
245
-			 */
246
-			return strcmp($a->getUID(), $b->getUID());
247
-		});
248
-		return $users;
249
-	}
250
-
251
-	/**
252
-	 * search by displayName
253
-	 *
254
-	 * @param string $pattern
255
-	 * @param int $limit
256
-	 * @param int $offset
257
-	 * @return \OC\User\User[]
258
-	 */
259
-	public function searchDisplayName($pattern, $limit = null, $offset = null) {
260
-		$users = array();
261
-		foreach ($this->backends as $backend) {
262
-			$backendUsers = $backend->getDisplayNames($pattern, $limit, $offset);
263
-			if (is_array($backendUsers)) {
264
-				foreach ($backendUsers as $uid => $displayName) {
265
-					$users[] = $this->getUserObject($uid, $backend);
266
-				}
267
-			}
268
-		}
269
-
270
-		usort($users, function ($a, $b) {
271
-			/**
272
-			 * @var \OC\User\User $a
273
-			 * @var \OC\User\User $b
274
-			 */
275
-			return strcmp(strtolower($a->getDisplayName()), strtolower($b->getDisplayName()));
276
-		});
277
-		return $users;
278
-	}
279
-
280
-	/**
281
-	 * @param string $uid
282
-	 * @param string $password
283
-	 * @throws \InvalidArgumentException
284
-	 * @return bool|IUser the created user or false
285
-	 */
286
-	public function createUser($uid, $password) {
287
-		foreach ($this->backends as $backend) {
288
-			if ($backend->implementsActions(Backend::CREATE_USER)) {
289
-				return $this->createUserFromBackend($uid, $password, $backend);
290
-			}
291
-		}
292
-
293
-		return false;
294
-	}
295
-
296
-	/**
297
-	 * @param string $uid
298
-	 * @param string $password
299
-	 * @param UserInterface $backend
300
-	 * @return IUser|null
301
-	 * @throws \InvalidArgumentException
302
-	 */
303
-	public function createUserFromBackend($uid, $password, UserInterface $backend) {
304
-		$l = \OC::$server->getL10N('lib');
305
-
306
-		// Check the name for bad characters
307
-		// Allowed are: "a-z", "A-Z", "0-9" and "_.@-'"
308
-		if (preg_match('/[^a-zA-Z0-9 _\.@\-\']/', $uid)) {
309
-			throw new \InvalidArgumentException($l->t('Only the following characters are allowed in a username:'
310
-				. ' "a-z", "A-Z", "0-9", and "_.@-\'"'));
311
-		}
312
-		// No empty username
313
-		if (trim($uid) === '') {
314
-			throw new \InvalidArgumentException($l->t('A valid username must be provided'));
315
-		}
316
-		// No whitespace at the beginning or at the end
317
-		if (trim($uid) !== $uid) {
318
-			throw new \InvalidArgumentException($l->t('Username contains whitespace at the beginning or at the end'));
319
-		}
320
-		// Username only consists of 1 or 2 dots (directory traversal)
321
-		if ($uid === '.' || $uid === '..') {
322
-			throw new \InvalidArgumentException($l->t('Username must not consist of dots only'));
323
-		}
324
-		// No empty password
325
-		if (trim($password) === '') {
326
-			throw new \InvalidArgumentException($l->t('A valid password must be provided'));
327
-		}
328
-
329
-		// Check if user already exists
330
-		if ($this->userExists($uid)) {
331
-			throw new \InvalidArgumentException($l->t('The username is already being used'));
332
-		}
333
-
334
-		$this->emit('\OC\User', 'preCreateUser', [$uid, $password]);
335
-		$backend->createUser($uid, $password);
336
-		$user = $this->getUserObject($uid, $backend);
337
-		if ($user instanceof IUser) {
338
-			$this->emit('\OC\User', 'postCreateUser', [$user, $password]);
339
-		}
340
-		return $user;
341
-	}
342
-
343
-	/**
344
-	 * returns how many users per backend exist (if supported by backend)
345
-	 *
346
-	 * @param boolean $hasLoggedIn when true only users that have a lastLogin
347
-	 *                entry in the preferences table will be affected
348
-	 * @return array|int an array of backend class as key and count number as value
349
-	 *                if $hasLoggedIn is true only an int is returned
350
-	 */
351
-	public function countUsers($hasLoggedIn = false) {
352
-		if ($hasLoggedIn) {
353
-			return $this->countSeenUsers();
354
-		}
355
-		$userCountStatistics = [];
356
-		foreach ($this->backends as $backend) {
357
-			if ($backend->implementsActions(Backend::COUNT_USERS)) {
358
-				$backendUsers = $backend->countUsers();
359
-				if($backendUsers !== false) {
360
-					if($backend instanceof IUserBackend) {
361
-						$name = $backend->getBackendName();
362
-					} else {
363
-						$name = get_class($backend);
364
-					}
365
-					if(isset($userCountStatistics[$name])) {
366
-						$userCountStatistics[$name] += $backendUsers;
367
-					} else {
368
-						$userCountStatistics[$name] = $backendUsers;
369
-					}
370
-				}
371
-			}
372
-		}
373
-		return $userCountStatistics;
374
-	}
375
-
376
-	/**
377
-	 * The callback is executed for each user on each backend.
378
-	 * If the callback returns false no further users will be retrieved.
379
-	 *
380
-	 * @param \Closure $callback
381
-	 * @param string $search
382
-	 * @param boolean $onlySeen when true only users that have a lastLogin entry
383
-	 *                in the preferences table will be affected
384
-	 * @since 9.0.0
385
-	 */
386
-	public function callForAllUsers(\Closure $callback, $search = '', $onlySeen = false) {
387
-		if ($onlySeen) {
388
-			$this->callForSeenUsers($callback);
389
-		} else {
390
-			foreach ($this->getBackends() as $backend) {
391
-				$limit = 500;
392
-				$offset = 0;
393
-				do {
394
-					$users = $backend->getUsers($search, $limit, $offset);
395
-					foreach ($users as $uid) {
396
-						if (!$backend->userExists($uid)) {
397
-							continue;
398
-						}
399
-						$user = $this->getUserObject($uid, $backend, false);
400
-						$return = $callback($user);
401
-						if ($return === false) {
402
-							break;
403
-						}
404
-					}
405
-					$offset += $limit;
406
-				} while (count($users) >= $limit);
407
-			}
408
-		}
409
-	}
410
-
411
-	/**
412
-	 * returns how many users have logged in once
413
-	 *
414
-	 * @return int
415
-	 * @since 12.0.0
416
-	 */
417
-	public function countDisabledUsers() {
418
-		$queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
419
-		$queryBuilder->select($queryBuilder->createFunction('COUNT(*)'))
420
-			->from('preferences')
421
-			->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('core')))
422
-			->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('enabled')))
423
-			->andWhere($queryBuilder->expr()->eq('configvalue', $queryBuilder->createNamedParameter('false')));
424
-
425
-		$query = $queryBuilder->execute();
426
-
427
-		$result = (int)$query->fetchColumn();
428
-		$query->closeCursor();
429
-
430
-		return $result;
431
-	}
432
-
433
-	/**
434
-	 * returns how many users have logged in once
435
-	 *
436
-	 * @return int
437
-	 * @since 11.0.0
438
-	 */
439
-	public function countSeenUsers() {
440
-		$queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
441
-		$queryBuilder->select($queryBuilder->createFunction('COUNT(*)'))
442
-			->from('preferences')
443
-			->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('login')))
444
-			->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('lastLogin')))
445
-			->andWhere($queryBuilder->expr()->isNotNull('configvalue'));
446
-
447
-		$query = $queryBuilder->execute();
448
-
449
-		$result = (int)$query->fetchColumn();
450
-		$query->closeCursor();
451
-
452
-		return $result;
453
-	}
454
-
455
-	/**
456
-	 * @param \Closure $callback
457
-	 * @since 11.0.0
458
-	 */
459
-	public function callForSeenUsers(\Closure $callback) {
460
-		$limit = 1000;
461
-		$offset = 0;
462
-		do {
463
-			$userIds = $this->getSeenUserIds($limit, $offset);
464
-			$offset += $limit;
465
-			foreach ($userIds as $userId) {
466
-				foreach ($this->backends as $backend) {
467
-					if ($backend->userExists($userId)) {
468
-						$user = $this->getUserObject($userId, $backend, false);
469
-						$return = $callback($user);
470
-						if ($return === false) {
471
-							return;
472
-						}
473
-					}
474
-				}
475
-			}
476
-		} while (count($userIds) >= $limit);
477
-	}
478
-
479
-	/**
480
-	 * Getting all userIds that have a listLogin value requires checking the
481
-	 * value in php because on oracle you cannot use a clob in a where clause,
482
-	 * preventing us from doing a not null or length(value) > 0 check.
483
-	 * 
484
-	 * @param int $limit
485
-	 * @param int $offset
486
-	 * @return string[] with user ids
487
-	 */
488
-	private function getSeenUserIds($limit = null, $offset = null) {
489
-		$queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
490
-		$queryBuilder->select(['userid'])
491
-			->from('preferences')
492
-			->where($queryBuilder->expr()->eq(
493
-				'appid', $queryBuilder->createNamedParameter('login'))
494
-			)
495
-			->andWhere($queryBuilder->expr()->eq(
496
-				'configkey', $queryBuilder->createNamedParameter('lastLogin'))
497
-			)
498
-			->andWhere($queryBuilder->expr()->isNotNull('configvalue')
499
-			);
500
-
501
-		if ($limit !== null) {
502
-			$queryBuilder->setMaxResults($limit);
503
-		}
504
-		if ($offset !== null) {
505
-			$queryBuilder->setFirstResult($offset);
506
-		}
507
-		$query = $queryBuilder->execute();
508
-		$result = [];
509
-
510
-		while ($row = $query->fetch()) {
511
-			$result[] = $row['userid'];
512
-		}
513
-
514
-		$query->closeCursor();
515
-
516
-		return $result;
517
-	}
518
-
519
-	/**
520
-	 * @param string $email
521
-	 * @return IUser[]
522
-	 * @since 9.1.0
523
-	 */
524
-	public function getByEmail($email) {
525
-		$userIds = $this->config->getUsersForUserValue('settings', 'email', $email);
526
-
527
-		return array_map(function($uid) {
528
-			return $this->get($uid);
529
-		}, $userIds);
530
-	}
58
+    /**
59
+     * @var \OCP\UserInterface[] $backends
60
+     */
61
+    private $backends = array();
62
+
63
+    /**
64
+     * @var \OC\User\User[] $cachedUsers
65
+     */
66
+    private $cachedUsers = array();
67
+
68
+    /**
69
+     * @var \OCP\IConfig $config
70
+     */
71
+    private $config;
72
+
73
+    /**
74
+     * @param \OCP\IConfig $config
75
+     */
76
+    public function __construct(IConfig $config) {
77
+        $this->config = $config;
78
+        $cachedUsers = &$this->cachedUsers;
79
+        $this->listen('\OC\User', 'postDelete', function ($user) use (&$cachedUsers) {
80
+            /** @var \OC\User\User $user */
81
+            unset($cachedUsers[$user->getUID()]);
82
+        });
83
+    }
84
+
85
+    /**
86
+     * Get the active backends
87
+     * @return \OCP\UserInterface[]
88
+     */
89
+    public function getBackends() {
90
+        return $this->backends;
91
+    }
92
+
93
+    /**
94
+     * register a user backend
95
+     *
96
+     * @param \OCP\UserInterface $backend
97
+     */
98
+    public function registerBackend($backend) {
99
+        $this->backends[] = $backend;
100
+    }
101
+
102
+    /**
103
+     * remove a user backend
104
+     *
105
+     * @param \OCP\UserInterface $backend
106
+     */
107
+    public function removeBackend($backend) {
108
+        $this->cachedUsers = array();
109
+        if (($i = array_search($backend, $this->backends)) !== false) {
110
+            unset($this->backends[$i]);
111
+        }
112
+    }
113
+
114
+    /**
115
+     * remove all user backends
116
+     */
117
+    public function clearBackends() {
118
+        $this->cachedUsers = array();
119
+        $this->backends = array();
120
+    }
121
+
122
+    /**
123
+     * get a user by user id
124
+     *
125
+     * @param string $uid
126
+     * @return \OC\User\User|null Either the user or null if the specified user does not exist
127
+     */
128
+    public function get($uid) {
129
+        if (isset($this->cachedUsers[$uid])) { //check the cache first to prevent having to loop over the backends
130
+            return $this->cachedUsers[$uid];
131
+        }
132
+        foreach ($this->backends as $backend) {
133
+            if ($backend->userExists($uid)) {
134
+                return $this->getUserObject($uid, $backend);
135
+            }
136
+        }
137
+        return null;
138
+    }
139
+
140
+    /**
141
+     * get or construct the user object
142
+     *
143
+     * @param string $uid
144
+     * @param \OCP\UserInterface $backend
145
+     * @param bool $cacheUser If false the newly created user object will not be cached
146
+     * @return \OC\User\User
147
+     */
148
+    protected function getUserObject($uid, $backend, $cacheUser = true) {
149
+        if (isset($this->cachedUsers[$uid])) {
150
+            return $this->cachedUsers[$uid];
151
+        }
152
+
153
+        if (method_exists($backend, 'loginName2UserName')) {
154
+            $loginName = $backend->loginName2UserName($uid);
155
+            if ($loginName !== false) {
156
+                $uid = $loginName;
157
+            }
158
+            if (isset($this->cachedUsers[$uid])) {
159
+                return $this->cachedUsers[$uid];
160
+            }
161
+        }
162
+
163
+        $user = new User($uid, $backend, $this, $this->config);
164
+        if ($cacheUser) {
165
+            $this->cachedUsers[$uid] = $user;
166
+        }
167
+        return $user;
168
+    }
169
+
170
+    /**
171
+     * check if a user exists
172
+     *
173
+     * @param string $uid
174
+     * @return bool
175
+     */
176
+    public function userExists($uid) {
177
+        $user = $this->get($uid);
178
+        return ($user !== null);
179
+    }
180
+
181
+    /**
182
+     * Check if the password is valid for the user
183
+     *
184
+     * @param string $loginName
185
+     * @param string $password
186
+     * @return mixed the User object on success, false otherwise
187
+     */
188
+    public function checkPassword($loginName, $password) {
189
+        $result = $this->checkPasswordNoLogging($loginName, $password);
190
+
191
+        if ($result === false) {
192
+            \OC::$server->getLogger()->warning('Login failed: \''. $loginName .'\' (Remote IP: \''. \OC::$server->getRequest()->getRemoteAddress(). '\')', ['app' => 'core']);
193
+        }
194
+
195
+        return $result;
196
+    }
197
+
198
+    /**
199
+     * Check if the password is valid for the user
200
+     *
201
+     * @internal
202
+     * @param string $loginName
203
+     * @param string $password
204
+     * @return mixed the User object on success, false otherwise
205
+     */
206
+    public function checkPasswordNoLogging($loginName, $password) {
207
+        $loginName = str_replace("\0", '', $loginName);
208
+        $password = str_replace("\0", '', $password);
209
+
210
+        foreach ($this->backends as $backend) {
211
+            if ($backend->implementsActions(Backend::CHECK_PASSWORD)) {
212
+                $uid = $backend->checkPassword($loginName, $password);
213
+                if ($uid !== false) {
214
+                    return $this->getUserObject($uid, $backend);
215
+                }
216
+            }
217
+        }
218
+
219
+        return false;
220
+    }
221
+
222
+    /**
223
+     * search by user id
224
+     *
225
+     * @param string $pattern
226
+     * @param int $limit
227
+     * @param int $offset
228
+     * @return \OC\User\User[]
229
+     */
230
+    public function search($pattern, $limit = null, $offset = null) {
231
+        $users = array();
232
+        foreach ($this->backends as $backend) {
233
+            $backendUsers = $backend->getUsers($pattern, $limit, $offset);
234
+            if (is_array($backendUsers)) {
235
+                foreach ($backendUsers as $uid) {
236
+                    $users[$uid] = $this->getUserObject($uid, $backend);
237
+                }
238
+            }
239
+        }
240
+
241
+        uasort($users, function ($a, $b) {
242
+            /**
243
+             * @var \OC\User\User $a
244
+             * @var \OC\User\User $b
245
+             */
246
+            return strcmp($a->getUID(), $b->getUID());
247
+        });
248
+        return $users;
249
+    }
250
+
251
+    /**
252
+     * search by displayName
253
+     *
254
+     * @param string $pattern
255
+     * @param int $limit
256
+     * @param int $offset
257
+     * @return \OC\User\User[]
258
+     */
259
+    public function searchDisplayName($pattern, $limit = null, $offset = null) {
260
+        $users = array();
261
+        foreach ($this->backends as $backend) {
262
+            $backendUsers = $backend->getDisplayNames($pattern, $limit, $offset);
263
+            if (is_array($backendUsers)) {
264
+                foreach ($backendUsers as $uid => $displayName) {
265
+                    $users[] = $this->getUserObject($uid, $backend);
266
+                }
267
+            }
268
+        }
269
+
270
+        usort($users, function ($a, $b) {
271
+            /**
272
+             * @var \OC\User\User $a
273
+             * @var \OC\User\User $b
274
+             */
275
+            return strcmp(strtolower($a->getDisplayName()), strtolower($b->getDisplayName()));
276
+        });
277
+        return $users;
278
+    }
279
+
280
+    /**
281
+     * @param string $uid
282
+     * @param string $password
283
+     * @throws \InvalidArgumentException
284
+     * @return bool|IUser the created user or false
285
+     */
286
+    public function createUser($uid, $password) {
287
+        foreach ($this->backends as $backend) {
288
+            if ($backend->implementsActions(Backend::CREATE_USER)) {
289
+                return $this->createUserFromBackend($uid, $password, $backend);
290
+            }
291
+        }
292
+
293
+        return false;
294
+    }
295
+
296
+    /**
297
+     * @param string $uid
298
+     * @param string $password
299
+     * @param UserInterface $backend
300
+     * @return IUser|null
301
+     * @throws \InvalidArgumentException
302
+     */
303
+    public function createUserFromBackend($uid, $password, UserInterface $backend) {
304
+        $l = \OC::$server->getL10N('lib');
305
+
306
+        // Check the name for bad characters
307
+        // Allowed are: "a-z", "A-Z", "0-9" and "_.@-'"
308
+        if (preg_match('/[^a-zA-Z0-9 _\.@\-\']/', $uid)) {
309
+            throw new \InvalidArgumentException($l->t('Only the following characters are allowed in a username:'
310
+                . ' "a-z", "A-Z", "0-9", and "_.@-\'"'));
311
+        }
312
+        // No empty username
313
+        if (trim($uid) === '') {
314
+            throw new \InvalidArgumentException($l->t('A valid username must be provided'));
315
+        }
316
+        // No whitespace at the beginning or at the end
317
+        if (trim($uid) !== $uid) {
318
+            throw new \InvalidArgumentException($l->t('Username contains whitespace at the beginning or at the end'));
319
+        }
320
+        // Username only consists of 1 or 2 dots (directory traversal)
321
+        if ($uid === '.' || $uid === '..') {
322
+            throw new \InvalidArgumentException($l->t('Username must not consist of dots only'));
323
+        }
324
+        // No empty password
325
+        if (trim($password) === '') {
326
+            throw new \InvalidArgumentException($l->t('A valid password must be provided'));
327
+        }
328
+
329
+        // Check if user already exists
330
+        if ($this->userExists($uid)) {
331
+            throw new \InvalidArgumentException($l->t('The username is already being used'));
332
+        }
333
+
334
+        $this->emit('\OC\User', 'preCreateUser', [$uid, $password]);
335
+        $backend->createUser($uid, $password);
336
+        $user = $this->getUserObject($uid, $backend);
337
+        if ($user instanceof IUser) {
338
+            $this->emit('\OC\User', 'postCreateUser', [$user, $password]);
339
+        }
340
+        return $user;
341
+    }
342
+
343
+    /**
344
+     * returns how many users per backend exist (if supported by backend)
345
+     *
346
+     * @param boolean $hasLoggedIn when true only users that have a lastLogin
347
+     *                entry in the preferences table will be affected
348
+     * @return array|int an array of backend class as key and count number as value
349
+     *                if $hasLoggedIn is true only an int is returned
350
+     */
351
+    public function countUsers($hasLoggedIn = false) {
352
+        if ($hasLoggedIn) {
353
+            return $this->countSeenUsers();
354
+        }
355
+        $userCountStatistics = [];
356
+        foreach ($this->backends as $backend) {
357
+            if ($backend->implementsActions(Backend::COUNT_USERS)) {
358
+                $backendUsers = $backend->countUsers();
359
+                if($backendUsers !== false) {
360
+                    if($backend instanceof IUserBackend) {
361
+                        $name = $backend->getBackendName();
362
+                    } else {
363
+                        $name = get_class($backend);
364
+                    }
365
+                    if(isset($userCountStatistics[$name])) {
366
+                        $userCountStatistics[$name] += $backendUsers;
367
+                    } else {
368
+                        $userCountStatistics[$name] = $backendUsers;
369
+                    }
370
+                }
371
+            }
372
+        }
373
+        return $userCountStatistics;
374
+    }
375
+
376
+    /**
377
+     * The callback is executed for each user on each backend.
378
+     * If the callback returns false no further users will be retrieved.
379
+     *
380
+     * @param \Closure $callback
381
+     * @param string $search
382
+     * @param boolean $onlySeen when true only users that have a lastLogin entry
383
+     *                in the preferences table will be affected
384
+     * @since 9.0.0
385
+     */
386
+    public function callForAllUsers(\Closure $callback, $search = '', $onlySeen = false) {
387
+        if ($onlySeen) {
388
+            $this->callForSeenUsers($callback);
389
+        } else {
390
+            foreach ($this->getBackends() as $backend) {
391
+                $limit = 500;
392
+                $offset = 0;
393
+                do {
394
+                    $users = $backend->getUsers($search, $limit, $offset);
395
+                    foreach ($users as $uid) {
396
+                        if (!$backend->userExists($uid)) {
397
+                            continue;
398
+                        }
399
+                        $user = $this->getUserObject($uid, $backend, false);
400
+                        $return = $callback($user);
401
+                        if ($return === false) {
402
+                            break;
403
+                        }
404
+                    }
405
+                    $offset += $limit;
406
+                } while (count($users) >= $limit);
407
+            }
408
+        }
409
+    }
410
+
411
+    /**
412
+     * returns how many users have logged in once
413
+     *
414
+     * @return int
415
+     * @since 12.0.0
416
+     */
417
+    public function countDisabledUsers() {
418
+        $queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
419
+        $queryBuilder->select($queryBuilder->createFunction('COUNT(*)'))
420
+            ->from('preferences')
421
+            ->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('core')))
422
+            ->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('enabled')))
423
+            ->andWhere($queryBuilder->expr()->eq('configvalue', $queryBuilder->createNamedParameter('false')));
424
+
425
+        $query = $queryBuilder->execute();
426
+
427
+        $result = (int)$query->fetchColumn();
428
+        $query->closeCursor();
429
+
430
+        return $result;
431
+    }
432
+
433
+    /**
434
+     * returns how many users have logged in once
435
+     *
436
+     * @return int
437
+     * @since 11.0.0
438
+     */
439
+    public function countSeenUsers() {
440
+        $queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
441
+        $queryBuilder->select($queryBuilder->createFunction('COUNT(*)'))
442
+            ->from('preferences')
443
+            ->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('login')))
444
+            ->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('lastLogin')))
445
+            ->andWhere($queryBuilder->expr()->isNotNull('configvalue'));
446
+
447
+        $query = $queryBuilder->execute();
448
+
449
+        $result = (int)$query->fetchColumn();
450
+        $query->closeCursor();
451
+
452
+        return $result;
453
+    }
454
+
455
+    /**
456
+     * @param \Closure $callback
457
+     * @since 11.0.0
458
+     */
459
+    public function callForSeenUsers(\Closure $callback) {
460
+        $limit = 1000;
461
+        $offset = 0;
462
+        do {
463
+            $userIds = $this->getSeenUserIds($limit, $offset);
464
+            $offset += $limit;
465
+            foreach ($userIds as $userId) {
466
+                foreach ($this->backends as $backend) {
467
+                    if ($backend->userExists($userId)) {
468
+                        $user = $this->getUserObject($userId, $backend, false);
469
+                        $return = $callback($user);
470
+                        if ($return === false) {
471
+                            return;
472
+                        }
473
+                    }
474
+                }
475
+            }
476
+        } while (count($userIds) >= $limit);
477
+    }
478
+
479
+    /**
480
+     * Getting all userIds that have a listLogin value requires checking the
481
+     * value in php because on oracle you cannot use a clob in a where clause,
482
+     * preventing us from doing a not null or length(value) > 0 check.
483
+     * 
484
+     * @param int $limit
485
+     * @param int $offset
486
+     * @return string[] with user ids
487
+     */
488
+    private function getSeenUserIds($limit = null, $offset = null) {
489
+        $queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
490
+        $queryBuilder->select(['userid'])
491
+            ->from('preferences')
492
+            ->where($queryBuilder->expr()->eq(
493
+                'appid', $queryBuilder->createNamedParameter('login'))
494
+            )
495
+            ->andWhere($queryBuilder->expr()->eq(
496
+                'configkey', $queryBuilder->createNamedParameter('lastLogin'))
497
+            )
498
+            ->andWhere($queryBuilder->expr()->isNotNull('configvalue')
499
+            );
500
+
501
+        if ($limit !== null) {
502
+            $queryBuilder->setMaxResults($limit);
503
+        }
504
+        if ($offset !== null) {
505
+            $queryBuilder->setFirstResult($offset);
506
+        }
507
+        $query = $queryBuilder->execute();
508
+        $result = [];
509
+
510
+        while ($row = $query->fetch()) {
511
+            $result[] = $row['userid'];
512
+        }
513
+
514
+        $query->closeCursor();
515
+
516
+        return $result;
517
+    }
518
+
519
+    /**
520
+     * @param string $email
521
+     * @return IUser[]
522
+     * @since 9.1.0
523
+     */
524
+    public function getByEmail($email) {
525
+        $userIds = $this->config->getUsersForUserValue('settings', 'email', $email);
526
+
527
+        return array_map(function($uid) {
528
+            return $this->get($uid);
529
+        }, $userIds);
530
+    }
531 531
 }
Please login to merge, or discard this patch.
settings/users.php 2 patches
Indentation   +35 added lines, -35 removed lines patch added patch discarded remove patch
@@ -47,13 +47,13 @@  discard block
 block discarded – undo
47 47
 
48 48
 $isLDAPUsed = false;
49 49
 if (\OC_App::isEnabled('user_ldap')) {
50
-	$isLDAPUsed =
51
-		   $groupManager->isBackendUsed('\OCA\User_LDAP\Group_LDAP')
52
-		|| $groupManager->isBackendUsed('\OCA\User_LDAP\Group_Proxy');
53
-	if ($isLDAPUsed) {
54
-		// LDAP user count can be slow, so we sort by group name here
55
-		$sortGroupsBy = \OC\Group\MetaData::SORT_GROUPNAME;
56
-	}
50
+    $isLDAPUsed =
51
+            $groupManager->isBackendUsed('\OCA\User_LDAP\Group_LDAP')
52
+        || $groupManager->isBackendUsed('\OCA\User_LDAP\Group_Proxy');
53
+    if ($isLDAPUsed) {
54
+        // LDAP user count can be slow, so we sort by group name here
55
+        $sortGroupsBy = \OC\Group\MetaData::SORT_GROUPNAME;
56
+    }
57 57
 }
58 58
 
59 59
 $config = \OC::$server->getConfig();
@@ -63,58 +63,58 @@  discard block
 block discarded – undo
63 63
 $isDisabled = !OC_User::isEnabled(OC_User::getUser());
64 64
 
65 65
 $groupsInfo = new \OC\Group\MetaData(
66
-	OC_User::getUser(),
67
-	$isAdmin,
68
-	$groupManager,
69
-	\OC::$server->getUserSession()
66
+    OC_User::getUser(),
67
+    $isAdmin,
68
+    $groupManager,
69
+    \OC::$server->getUserSession()
70 70
 );
71 71
 
72 72
 $groupsInfo->setSorting($sortGroupsBy);
73 73
 list($adminGroup, $groups) = $groupsInfo->get();
74 74
 
75 75
 $recoveryAdminEnabled = OC_App::isEnabled('encryption') &&
76
-					    $config->getAppValue( 'encryption', 'recoveryAdminEnabled', null );
76
+                        $config->getAppValue( 'encryption', 'recoveryAdminEnabled', null );
77 77
 
78 78
 if($isAdmin) {
79
-	$subAdmins = \OC::$server->getGroupManager()->getSubAdmin()->getAllSubAdmins();
80
-	// New class returns IUser[] so convert back
81
-	$result = [];
82
-	foreach ($subAdmins as $subAdmin) {
83
-		$result[] = [
84
-			'gid' => $subAdmin['group']->getGID(),
85
-			'uid' => $subAdmin['user']->getUID(),
86
-		];
87
-	}
88
-	$subAdmins = $result;
79
+    $subAdmins = \OC::$server->getGroupManager()->getSubAdmin()->getAllSubAdmins();
80
+    // New class returns IUser[] so convert back
81
+    $result = [];
82
+    foreach ($subAdmins as $subAdmin) {
83
+        $result[] = [
84
+            'gid' => $subAdmin['group']->getGID(),
85
+            'uid' => $subAdmin['user']->getUID(),
86
+        ];
87
+    }
88
+    $subAdmins = $result;
89 89
 }else{
90
-	/* Retrieve group IDs from $groups array, so we can pass that information into OC_Group::displayNamesInGroups() */
91
-	$gids = array();
92
-	foreach($groups as $group) {
93
-		if (isset($group['id'])) {
94
-			$gids[] = $group['id'];
95
-		}
96
-	}
97
-	$subAdmins = false;
90
+    /* Retrieve group IDs from $groups array, so we can pass that information into OC_Group::displayNamesInGroups() */
91
+    $gids = array();
92
+    foreach($groups as $group) {
93
+        if (isset($group['id'])) {
94
+            $gids[] = $group['id'];
95
+        }
96
+    }
97
+    $subAdmins = false;
98 98
 }
99 99
 
100 100
 $disabledUsers = $isLDAPUsed ? 0 : $userManager->countDisabledUsers();
101 101
 $disabledUsersGroup = [
102
-	'id' => '_disabledUsers',
103
-	'name' => '_disabledUsers',
104
-	'usercount' => $disabledUsers
102
+    'id' => '_disabledUsers',
103
+    'name' => '_disabledUsers',
104
+    'usercount' => $disabledUsers
105 105
 ];
106 106
 
107 107
 // load preset quotas
108 108
 $quotaPreset=$config->getAppValue('files', 'quota_preset', '1 GB, 5 GB, 10 GB');
109 109
 $quotaPreset=explode(',', $quotaPreset);
110 110
 foreach($quotaPreset as &$preset) {
111
-	$preset=trim($preset);
111
+    $preset=trim($preset);
112 112
 }
113 113
 $quotaPreset=array_diff($quotaPreset, array('default', 'none'));
114 114
 
115 115
 $defaultQuota=$config->getAppValue('files', 'default_quota', 'none');
116 116
 $defaultQuotaIsUserDefined=array_search($defaultQuota, $quotaPreset)===false
117
-	&& array_search($defaultQuota, array('none', 'default'))===false;
117
+    && array_search($defaultQuota, array('none', 'default'))===false;
118 118
 
119 119
 \OC::$server->getEventDispatcher()->dispatch('OC\Settings\Users::loadAdditionalScripts');
120 120
 
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -73,9 +73,9 @@  discard block
 block discarded – undo
73 73
 list($adminGroup, $groups) = $groupsInfo->get();
74 74
 
75 75
 $recoveryAdminEnabled = OC_App::isEnabled('encryption') &&
76
-					    $config->getAppValue( 'encryption', 'recoveryAdminEnabled', null );
76
+					    $config->getAppValue('encryption', 'recoveryAdminEnabled', null);
77 77
 
78
-if($isAdmin) {
78
+if ($isAdmin) {
79 79
 	$subAdmins = \OC::$server->getGroupManager()->getSubAdmin()->getAllSubAdmins();
80 80
 	// New class returns IUser[] so convert back
81 81
 	$result = [];
@@ -86,10 +86,10 @@  discard block
 block discarded – undo
86 86
 		];
87 87
 	}
88 88
 	$subAdmins = $result;
89
-}else{
89
+} else {
90 90
 	/* Retrieve group IDs from $groups array, so we can pass that information into OC_Group::displayNamesInGroups() */
91 91
 	$gids = array();
92
-	foreach($groups as $group) {
92
+	foreach ($groups as $group) {
93 93
 		if (isset($group['id'])) {
94 94
 			$gids[] = $group['id'];
95 95
 		}
@@ -105,16 +105,16 @@  discard block
 block discarded – undo
105 105
 ];
106 106
 
107 107
 // load preset quotas
108
-$quotaPreset=$config->getAppValue('files', 'quota_preset', '1 GB, 5 GB, 10 GB');
109
-$quotaPreset=explode(',', $quotaPreset);
110
-foreach($quotaPreset as &$preset) {
111
-	$preset=trim($preset);
108
+$quotaPreset = $config->getAppValue('files', 'quota_preset', '1 GB, 5 GB, 10 GB');
109
+$quotaPreset = explode(',', $quotaPreset);
110
+foreach ($quotaPreset as &$preset) {
111
+	$preset = trim($preset);
112 112
 }
113
-$quotaPreset=array_diff($quotaPreset, array('default', 'none'));
113
+$quotaPreset = array_diff($quotaPreset, array('default', 'none'));
114 114
 
115
-$defaultQuota=$config->getAppValue('files', 'default_quota', 'none');
116
-$defaultQuotaIsUserDefined=array_search($defaultQuota, $quotaPreset)===false
117
-	&& array_search($defaultQuota, array('none', 'default'))===false;
115
+$defaultQuota = $config->getAppValue('files', 'default_quota', 'none');
116
+$defaultQuotaIsUserDefined = array_search($defaultQuota, $quotaPreset) === false
117
+	&& array_search($defaultQuota, array('none', 'default')) === false;
118 118
 
119 119
 \OC::$server->getEventDispatcher()->dispatch('OC\Settings\Users::loadAdditionalScripts');
120 120
 
@@ -123,7 +123,7 @@  discard block
 block discarded – undo
123 123
 $tmpl->assign('sortGroups', $sortGroupsBy);
124 124
 $tmpl->assign('adminGroup', $adminGroup);
125 125
 $tmpl->assign('disabledUsersGroup', $disabledUsersGroup);
126
-$tmpl->assign('isAdmin', (int)$isAdmin);
126
+$tmpl->assign('isAdmin', (int) $isAdmin);
127 127
 $tmpl->assign('subadmins', $subAdmins);
128 128
 $tmpl->assign('numofgroups', count($groups) + count($adminGroup));
129 129
 $tmpl->assign('quota_preset', $quotaPreset);
Please login to merge, or discard this patch.
lib/public/IUserManager.php 1 patch
Indentation   +141 added lines, -141 removed lines patch added patch discarded remove patch
@@ -41,145 +41,145 @@
 block discarded – undo
41 41
  * @since 8.0.0
42 42
  */
43 43
 interface IUserManager {
44
-		/**
45
-	 * register a user backend
46
-	 *
47
-	 * @param \OCP\UserInterface $backend
48
-	 * @since 8.0.0
49
-	 */
50
-	public function registerBackend($backend);
51
-
52
-	/**
53
-	 * Get the active backends
54
-	 * @return \OCP\UserInterface[]
55
-	 * @since 8.0.0
56
-	 */
57
-	public function getBackends();
58
-
59
-	/**
60
-	 * remove a user backend
61
-	 *
62
-	 * @param \OCP\UserInterface $backend
63
-	 * @since 8.0.0
64
-	 */
65
-	public function removeBackend($backend);
66
-
67
-	/**
68
-	 * remove all user backends
69
-	 * @since 8.0.0
70
-	 */
71
-	public function clearBackends() ;
72
-
73
-	/**
74
-	 * get a user by user id
75
-	 *
76
-	 * @param string $uid
77
-	 * @return \OCP\IUser|null Either the user or null if the specified user does not exist
78
-	 * @since 8.0.0
79
-	 */
80
-	public function get($uid);
81
-
82
-	/**
83
-	 * check if a user exists
84
-	 *
85
-	 * @param string $uid
86
-	 * @return bool
87
-	 * @since 8.0.0
88
-	 */
89
-	public function userExists($uid);
90
-
91
-	/**
92
-	 * Check if the password is valid for the user
93
-	 *
94
-	 * @param string $loginName
95
-	 * @param string $password
96
-	 * @return mixed the User object on success, false otherwise
97
-	 * @since 8.0.0
98
-	 */
99
-	public function checkPassword($loginName, $password);
100
-
101
-	/**
102
-	 * search by user id
103
-	 *
104
-	 * @param string $pattern
105
-	 * @param int $limit
106
-	 * @param int $offset
107
-	 * @return \OCP\IUser[]
108
-	 * @since 8.0.0
109
-	 */
110
-	public function search($pattern, $limit = null, $offset = null);
111
-
112
-	/**
113
-	 * search by displayName
114
-	 *
115
-	 * @param string $pattern
116
-	 * @param int $limit
117
-	 * @param int $offset
118
-	 * @return \OCP\IUser[]
119
-	 * @since 8.0.0
120
-	 */
121
-	public function searchDisplayName($pattern, $limit = null, $offset = null);
122
-
123
-	/**
124
-	 * @param string $uid
125
-	 * @param string $password
126
-	 * @throws \InvalidArgumentException
127
-	 * @return bool|\OCP\IUser the created user of false
128
-	 * @since 8.0.0
129
-	 */
130
-	public function createUser($uid, $password);
131
-
132
-	/**
133
-	 * @param string $uid
134
-	 * @param string $password
135
-	 * @param UserInterface $backend
136
-	 * @return IUser|null
137
-	 * @throws \InvalidArgumentException
138
-	 * @since 12.0.0
139
-	 */
140
-	public function createUserFromBackend($uid, $password, UserInterface $backend);
141
-
142
-	/**
143
-	 * returns how many users per backend exist (if supported by backend)
144
-	 *
145
-	 * @return array an array of backend class as key and count number as value
146
-	 * @since 8.0.0
147
-	 */
148
-	public function countUsers();
149
-
150
-	/**
151
-	 * @param \Closure $callback
152
-	 * @param string $search
153
-	 * @since 9.0.0
154
-	 */
155
-	public function callForAllUsers(\Closure $callback, $search = '');
156
-
157
-	/**
158
-	 * returns how many users have logged in once
159
-	 *
160
-	 * @return int
161
-	 * @since 11.0.0
162
-	 */
163
-	public function countDisabledUsers();
164
-
165
-	/**
166
-	 * returns how many users have logged in once
167
-	 *
168
-	 * @return int
169
-	 * @since 11.0.0
170
-	 */
171
-	public function countSeenUsers();
172
-
173
-	/**
174
-	 * @param \Closure $callback
175
-	 * @since 11.0.0
176
-	 */
177
-	public function callForSeenUsers(\Closure $callback);
178
-
179
-	/**
180
-	 * @param string $email
181
-	 * @return IUser[]
182
-	 * @since 9.1.0
183
-	 */
184
-	public function getByEmail($email);
44
+        /**
45
+         * register a user backend
46
+         *
47
+         * @param \OCP\UserInterface $backend
48
+         * @since 8.0.0
49
+         */
50
+    public function registerBackend($backend);
51
+
52
+    /**
53
+     * Get the active backends
54
+     * @return \OCP\UserInterface[]
55
+     * @since 8.0.0
56
+     */
57
+    public function getBackends();
58
+
59
+    /**
60
+     * remove a user backend
61
+     *
62
+     * @param \OCP\UserInterface $backend
63
+     * @since 8.0.0
64
+     */
65
+    public function removeBackend($backend);
66
+
67
+    /**
68
+     * remove all user backends
69
+     * @since 8.0.0
70
+     */
71
+    public function clearBackends() ;
72
+
73
+    /**
74
+     * get a user by user id
75
+     *
76
+     * @param string $uid
77
+     * @return \OCP\IUser|null Either the user or null if the specified user does not exist
78
+     * @since 8.0.0
79
+     */
80
+    public function get($uid);
81
+
82
+    /**
83
+     * check if a user exists
84
+     *
85
+     * @param string $uid
86
+     * @return bool
87
+     * @since 8.0.0
88
+     */
89
+    public function userExists($uid);
90
+
91
+    /**
92
+     * Check if the password is valid for the user
93
+     *
94
+     * @param string $loginName
95
+     * @param string $password
96
+     * @return mixed the User object on success, false otherwise
97
+     * @since 8.0.0
98
+     */
99
+    public function checkPassword($loginName, $password);
100
+
101
+    /**
102
+     * search by user id
103
+     *
104
+     * @param string $pattern
105
+     * @param int $limit
106
+     * @param int $offset
107
+     * @return \OCP\IUser[]
108
+     * @since 8.0.0
109
+     */
110
+    public function search($pattern, $limit = null, $offset = null);
111
+
112
+    /**
113
+     * search by displayName
114
+     *
115
+     * @param string $pattern
116
+     * @param int $limit
117
+     * @param int $offset
118
+     * @return \OCP\IUser[]
119
+     * @since 8.0.0
120
+     */
121
+    public function searchDisplayName($pattern, $limit = null, $offset = null);
122
+
123
+    /**
124
+     * @param string $uid
125
+     * @param string $password
126
+     * @throws \InvalidArgumentException
127
+     * @return bool|\OCP\IUser the created user of false
128
+     * @since 8.0.0
129
+     */
130
+    public function createUser($uid, $password);
131
+
132
+    /**
133
+     * @param string $uid
134
+     * @param string $password
135
+     * @param UserInterface $backend
136
+     * @return IUser|null
137
+     * @throws \InvalidArgumentException
138
+     * @since 12.0.0
139
+     */
140
+    public function createUserFromBackend($uid, $password, UserInterface $backend);
141
+
142
+    /**
143
+     * returns how many users per backend exist (if supported by backend)
144
+     *
145
+     * @return array an array of backend class as key and count number as value
146
+     * @since 8.0.0
147
+     */
148
+    public function countUsers();
149
+
150
+    /**
151
+     * @param \Closure $callback
152
+     * @param string $search
153
+     * @since 9.0.0
154
+     */
155
+    public function callForAllUsers(\Closure $callback, $search = '');
156
+
157
+    /**
158
+     * returns how many users have logged in once
159
+     *
160
+     * @return int
161
+     * @since 11.0.0
162
+     */
163
+    public function countDisabledUsers();
164
+
165
+    /**
166
+     * returns how many users have logged in once
167
+     *
168
+     * @return int
169
+     * @since 11.0.0
170
+     */
171
+    public function countSeenUsers();
172
+
173
+    /**
174
+     * @param \Closure $callback
175
+     * @since 11.0.0
176
+     */
177
+    public function callForSeenUsers(\Closure $callback);
178
+
179
+    /**
180
+     * @param string $email
181
+     * @return IUser[]
182
+     * @since 9.1.0
183
+     */
184
+    public function getByEmail($email);
185 185
 }
Please login to merge, or discard this patch.
settings/routes.php 1 patch
Indentation   +53 added lines, -53 removed lines patch added patch discarded remove patch
@@ -36,78 +36,78 @@
 block discarded – undo
36 36
 
37 37
 $application = new Application();
38 38
 $application->registerRoutes($this, [
39
-	'resources' => [
40
-		'users' => ['url' => '/settings/users/users'],
41
-		'AuthSettings' => ['url' => '/settings/personal/authtokens'],
42
-	],
43
-	'routes' => [
44
-		['name' => 'MailSettings#setMailSettings', 'url' => '/settings/admin/mailsettings', 'verb' => 'POST'],
45
-		['name' => 'MailSettings#storeCredentials', 'url' => '/settings/admin/mailsettings/credentials', 'verb' => 'POST'],
46
-		['name' => 'MailSettings#sendTestMail', 'url' => '/settings/admin/mailtest', 'verb' => 'POST'],
47
-		['name' => 'Encryption#startMigration', 'url' => '/settings/admin/startmigration', 'verb' => 'POST'],
48
-		['name' => 'AppSettings#listCategories', 'url' => '/settings/apps/categories', 'verb' => 'GET'],
49
-		['name' => 'AppSettings#viewApps', 'url' => '/settings/apps', 'verb' => 'GET'],
50
-		['name' => 'AppSettings#listApps', 'url' => '/settings/apps/list', 'verb' => 'GET'],
51
-		['name' => 'SecuritySettings#trustedDomains', 'url' => '/settings/admin/security/trustedDomains', 'verb' => 'POST'],
52
-		['name' => 'Users#setDisplayName', 'url' => '/settings/users/{username}/displayName', 'verb' => 'POST'],
53
-		['name' => 'Users#setEMailAddress', 'url' => '/settings/users/{id}/mailAddress', 'verb' => 'PUT'],
54
-		['name' => 'Users#setUserSettings', 'url' => '/settings/users/{username}/settings', 'verb' => 'PUT'],
55
-		['name' => 'Users#getVerificationCode', 'url' => '/settings/users/{account}/verify', 'verb' => 'GET'],
56
-		['name' => 'Users#setEnabled', 'url' => '/settings/users/{id}/setEnabled', 'verb' => 'POST'],
57
-		['name' => 'Users#stats', 'url' => '/settings/users/stats', 'verb' => 'GET'],
58
-		['name' => 'LogSettings#setLogLevel', 'url' => '/settings/admin/log/level', 'verb' => 'POST'],
59
-		['name' => 'LogSettings#getEntries', 'url' => '/settings/admin/log/entries', 'verb' => 'GET'],
60
-		['name' => 'LogSettings#download', 'url' => '/settings/admin/log/download', 'verb' => 'GET'],
61
-		['name' => 'CheckSetup#check', 'url' => '/settings/ajax/checksetup', 'verb' => 'GET'],
62
-		['name' => 'CheckSetup#getFailedIntegrityCheckFiles', 'url' => '/settings/integrity/failed', 'verb' => 'GET'],
63
-		['name' => 'CheckSetup#rescanFailedIntegrityCheck', 'url' => '/settings/integrity/rescan', 'verb' => 'GET'],
64
-		['name' => 'Certificate#addPersonalRootCertificate', 'url' => '/settings/personal/certificate', 'verb' => 'POST'],
65
-		['name' => 'Certificate#removePersonalRootCertificate', 'url' => '/settings/personal/certificate/{certificateIdentifier}', 'verb' => 'DELETE'],
66
-		['name' => 'Certificate#addSystemRootCertificate', 'url' => '/settings/admin/certificate', 'verb' => 'POST'],
67
-		['name' => 'Certificate#removeSystemRootCertificate', 'url' => '/settings/admin/certificate/{certificateIdentifier}', 'verb' => 'DELETE'],
68
-		['name' => 'AdminSettings#index', 'url' => '/settings/admin/{section}', 'verb' => 'GET', 'defaults' => ['section' => 'server']],
69
-		['name' => 'AdminSettings#form', 'url' => '/settings/admin/{section}', 'verb' => 'GET'],
70
-		['name' => 'ChangePassword#changePersonalPassword', 'url' => '/settings/personal/changepassword', 'verb' => 'POST'],
71
-		['name' => 'ChangePassword#changeUserPassword', 'url' => '/settings/users/changepassword', 'verb' => 'POST'],
72
-		['name' => 'Personal#setLanguage', 'url' => '/settings/ajax/setlanguage.php', 'verb' => 'POST'],
73
-		['name' => 'Groups#index', 'url' => '/settings/users/groups', 'verb' => 'GET'],
74
-		['name' => 'Groups#show', 'url' => '/settings/users/groups/{id}', 'requirements' => ['id' => '[^?]*'], 'verb' => 'GET'],
75
-		['name' => 'Groups#create', 'url' => '/settings/users/groups', 'verb' => 'POST'],
76
-		['name' => 'Groups#update', 'url' => '/settings/users/groups/{id}', 'requirements' => ['id' => '[^?]*'], 'verb' => 'PUT'],
77
-		['name' => 'Groups#destroy', 'url' => '/settings/users/groups/{id}', 'requirements' => ['id' => '[^?]*'], 'verb' => 'DELETE'],
78
-	]
39
+    'resources' => [
40
+        'users' => ['url' => '/settings/users/users'],
41
+        'AuthSettings' => ['url' => '/settings/personal/authtokens'],
42
+    ],
43
+    'routes' => [
44
+        ['name' => 'MailSettings#setMailSettings', 'url' => '/settings/admin/mailsettings', 'verb' => 'POST'],
45
+        ['name' => 'MailSettings#storeCredentials', 'url' => '/settings/admin/mailsettings/credentials', 'verb' => 'POST'],
46
+        ['name' => 'MailSettings#sendTestMail', 'url' => '/settings/admin/mailtest', 'verb' => 'POST'],
47
+        ['name' => 'Encryption#startMigration', 'url' => '/settings/admin/startmigration', 'verb' => 'POST'],
48
+        ['name' => 'AppSettings#listCategories', 'url' => '/settings/apps/categories', 'verb' => 'GET'],
49
+        ['name' => 'AppSettings#viewApps', 'url' => '/settings/apps', 'verb' => 'GET'],
50
+        ['name' => 'AppSettings#listApps', 'url' => '/settings/apps/list', 'verb' => 'GET'],
51
+        ['name' => 'SecuritySettings#trustedDomains', 'url' => '/settings/admin/security/trustedDomains', 'verb' => 'POST'],
52
+        ['name' => 'Users#setDisplayName', 'url' => '/settings/users/{username}/displayName', 'verb' => 'POST'],
53
+        ['name' => 'Users#setEMailAddress', 'url' => '/settings/users/{id}/mailAddress', 'verb' => 'PUT'],
54
+        ['name' => 'Users#setUserSettings', 'url' => '/settings/users/{username}/settings', 'verb' => 'PUT'],
55
+        ['name' => 'Users#getVerificationCode', 'url' => '/settings/users/{account}/verify', 'verb' => 'GET'],
56
+        ['name' => 'Users#setEnabled', 'url' => '/settings/users/{id}/setEnabled', 'verb' => 'POST'],
57
+        ['name' => 'Users#stats', 'url' => '/settings/users/stats', 'verb' => 'GET'],
58
+        ['name' => 'LogSettings#setLogLevel', 'url' => '/settings/admin/log/level', 'verb' => 'POST'],
59
+        ['name' => 'LogSettings#getEntries', 'url' => '/settings/admin/log/entries', 'verb' => 'GET'],
60
+        ['name' => 'LogSettings#download', 'url' => '/settings/admin/log/download', 'verb' => 'GET'],
61
+        ['name' => 'CheckSetup#check', 'url' => '/settings/ajax/checksetup', 'verb' => 'GET'],
62
+        ['name' => 'CheckSetup#getFailedIntegrityCheckFiles', 'url' => '/settings/integrity/failed', 'verb' => 'GET'],
63
+        ['name' => 'CheckSetup#rescanFailedIntegrityCheck', 'url' => '/settings/integrity/rescan', 'verb' => 'GET'],
64
+        ['name' => 'Certificate#addPersonalRootCertificate', 'url' => '/settings/personal/certificate', 'verb' => 'POST'],
65
+        ['name' => 'Certificate#removePersonalRootCertificate', 'url' => '/settings/personal/certificate/{certificateIdentifier}', 'verb' => 'DELETE'],
66
+        ['name' => 'Certificate#addSystemRootCertificate', 'url' => '/settings/admin/certificate', 'verb' => 'POST'],
67
+        ['name' => 'Certificate#removeSystemRootCertificate', 'url' => '/settings/admin/certificate/{certificateIdentifier}', 'verb' => 'DELETE'],
68
+        ['name' => 'AdminSettings#index', 'url' => '/settings/admin/{section}', 'verb' => 'GET', 'defaults' => ['section' => 'server']],
69
+        ['name' => 'AdminSettings#form', 'url' => '/settings/admin/{section}', 'verb' => 'GET'],
70
+        ['name' => 'ChangePassword#changePersonalPassword', 'url' => '/settings/personal/changepassword', 'verb' => 'POST'],
71
+        ['name' => 'ChangePassword#changeUserPassword', 'url' => '/settings/users/changepassword', 'verb' => 'POST'],
72
+        ['name' => 'Personal#setLanguage', 'url' => '/settings/ajax/setlanguage.php', 'verb' => 'POST'],
73
+        ['name' => 'Groups#index', 'url' => '/settings/users/groups', 'verb' => 'GET'],
74
+        ['name' => 'Groups#show', 'url' => '/settings/users/groups/{id}', 'requirements' => ['id' => '[^?]*'], 'verb' => 'GET'],
75
+        ['name' => 'Groups#create', 'url' => '/settings/users/groups', 'verb' => 'POST'],
76
+        ['name' => 'Groups#update', 'url' => '/settings/users/groups/{id}', 'requirements' => ['id' => '[^?]*'], 'verb' => 'PUT'],
77
+        ['name' => 'Groups#destroy', 'url' => '/settings/users/groups/{id}', 'requirements' => ['id' => '[^?]*'], 'verb' => 'DELETE'],
78
+    ]
79 79
 ]);
80 80
 
81 81
 /** @var $this \OCP\Route\IRouter */
82 82
 
83 83
 // Settings pages
84 84
 $this->create('settings_help', '/settings/help')
85
-	->actionInclude('settings/help.php');
85
+    ->actionInclude('settings/help.php');
86 86
 $this->create('settings_personal', '/settings/personal')
87
-	->actionInclude('settings/personal.php');
87
+    ->actionInclude('settings/personal.php');
88 88
 $this->create('settings_users', '/settings/users')
89
-	->actionInclude('settings/users.php');
89
+    ->actionInclude('settings/users.php');
90 90
 // Settings ajax actions
91 91
 // users
92 92
 $this->create('settings_ajax_setquota', '/settings/ajax/setquota.php')
93
-	->actionInclude('settings/ajax/setquota.php');
93
+    ->actionInclude('settings/ajax/setquota.php');
94 94
 $this->create('settings_ajax_togglegroups', '/settings/ajax/togglegroups.php')
95
-	->actionInclude('settings/ajax/togglegroups.php');
95
+    ->actionInclude('settings/ajax/togglegroups.php');
96 96
 $this->create('settings_ajax_togglesubadmins', '/settings/ajax/togglesubadmins.php')
97
-	->actionInclude('settings/ajax/togglesubadmins.php');
97
+    ->actionInclude('settings/ajax/togglesubadmins.php');
98 98
 $this->create('settings_ajax_changegorupname', '/settings/ajax/changegroupname.php')
99
-	->actionInclude('settings/ajax/changegroupname.php');
99
+    ->actionInclude('settings/ajax/changegroupname.php');
100 100
 // apps
101 101
 $this->create('settings_ajax_enableapp', '/settings/ajax/enableapp.php')
102
-	->actionInclude('settings/ajax/enableapp.php');
102
+    ->actionInclude('settings/ajax/enableapp.php');
103 103
 $this->create('settings_ajax_disableapp', '/settings/ajax/disableapp.php')
104
-	->actionInclude('settings/ajax/disableapp.php');
104
+    ->actionInclude('settings/ajax/disableapp.php');
105 105
 $this->create('settings_ajax_updateapp', '/settings/ajax/updateapp.php')
106
-	->actionInclude('settings/ajax/updateapp.php');
106
+    ->actionInclude('settings/ajax/updateapp.php');
107 107
 $this->create('settings_ajax_uninstallapp', '/settings/ajax/uninstallapp.php')
108
-	->actionInclude('settings/ajax/uninstallapp.php');
108
+    ->actionInclude('settings/ajax/uninstallapp.php');
109 109
 $this->create('settings_ajax_navigationdetect', '/settings/ajax/navigationdetect.php')
110
-	->actionInclude('settings/ajax/navigationdetect.php');
110
+    ->actionInclude('settings/ajax/navigationdetect.php');
111 111
 // admin
112 112
 $this->create('settings_ajax_excludegroups', '/settings/ajax/excludegroups.php')
113
-	->actionInclude('settings/ajax/excludegroups.php');
113
+    ->actionInclude('settings/ajax/excludegroups.php');
Please login to merge, or discard this patch.
settings/Controller/UsersController.php 2 patches
Indentation   +928 added lines, -928 removed lines patch added patch discarded remove patch
@@ -58,933 +58,933 @@
 block discarded – undo
58 58
  * @package OC\Settings\Controller
59 59
  */
60 60
 class UsersController extends Controller {
61
-	/** @var IL10N */
62
-	private $l10n;
63
-	/** @var IUserSession */
64
-	private $userSession;
65
-	/** @var bool */
66
-	private $isAdmin;
67
-	/** @var IUserManager */
68
-	private $userManager;
69
-	/** @var IGroupManager */
70
-	private $groupManager;
71
-	/** @var IConfig */
72
-	private $config;
73
-	/** @var ILogger */
74
-	private $log;
75
-	/** @var IMailer */
76
-	private $mailer;
77
-	/** @var bool contains the state of the encryption app */
78
-	private $isEncryptionAppEnabled;
79
-	/** @var bool contains the state of the admin recovery setting */
80
-	private $isRestoreEnabled = false;
81
-	/** @var IAvatarManager */
82
-	private $avatarManager;
83
-	/** @var AccountManager */
84
-	private $accountManager;
85
-	/** @var ISecureRandom */
86
-	private $secureRandom;
87
-	/** @var NewUserMailHelper */
88
-	private $newUserMailHelper;
89
-	/** @var ITimeFactory */
90
-	private $timeFactory;
91
-	/** @var ICrypto */
92
-	private $crypto;
93
-	/** @var Manager */
94
-	private $keyManager;
95
-	/** @var IJobList */
96
-	private $jobList;
97
-
98
-	/**
99
-	 * @param string $appName
100
-	 * @param IRequest $request
101
-	 * @param IUserManager $userManager
102
-	 * @param IGroupManager $groupManager
103
-	 * @param IUserSession $userSession
104
-	 * @param IConfig $config
105
-	 * @param bool $isAdmin
106
-	 * @param IL10N $l10n
107
-	 * @param ILogger $log
108
-	 * @param IMailer $mailer
109
-	 * @param IURLGenerator $urlGenerator
110
-	 * @param IAppManager $appManager
111
-	 * @param IAvatarManager $avatarManager
112
-	 * @param AccountManager $accountManager
113
-	 * @param ISecureRandom $secureRandom
114
-	 * @param NewUserMailHelper $newUserMailHelper
115
-	 * @param ITimeFactory $timeFactory
116
-	 * @param ICrypto $crypto
117
-	 * @param Manager $keyManager
118
-	 * @param IJobList $jobList
119
-	 */
120
-	public function __construct($appName,
121
-								IRequest $request,
122
-								IUserManager $userManager,
123
-								IGroupManager $groupManager,
124
-								IUserSession $userSession,
125
-								IConfig $config,
126
-								$isAdmin,
127
-								IL10N $l10n,
128
-								ILogger $log,
129
-								IMailer $mailer,
130
-								IURLGenerator $urlGenerator,
131
-								IAppManager $appManager,
132
-								IAvatarManager $avatarManager,
133
-								AccountManager $accountManager,
134
-								ISecureRandom $secureRandom,
135
-								NewUserMailHelper $newUserMailHelper,
136
-								ITimeFactory $timeFactory,
137
-								ICrypto $crypto,
138
-								Manager $keyManager,
139
-								IJobList $jobList) {
140
-		parent::__construct($appName, $request);
141
-		$this->userManager = $userManager;
142
-		$this->groupManager = $groupManager;
143
-		$this->userSession = $userSession;
144
-		$this->config = $config;
145
-		$this->isAdmin = $isAdmin;
146
-		$this->l10n = $l10n;
147
-		$this->log = $log;
148
-		$this->mailer = $mailer;
149
-		$this->avatarManager = $avatarManager;
150
-		$this->accountManager = $accountManager;
151
-		$this->secureRandom = $secureRandom;
152
-		$this->newUserMailHelper = $newUserMailHelper;
153
-		$this->timeFactory = $timeFactory;
154
-		$this->crypto = $crypto;
155
-		$this->keyManager = $keyManager;
156
-		$this->jobList = $jobList;
157
-
158
-		// check for encryption state - TODO see formatUserForIndex
159
-		$this->isEncryptionAppEnabled = $appManager->isEnabledForUser('encryption');
160
-		if($this->isEncryptionAppEnabled) {
161
-			// putting this directly in empty is possible in PHP 5.5+
162
-			$result = $config->getAppValue('encryption', 'recoveryAdminEnabled', 0);
163
-			$this->isRestoreEnabled = !empty($result);
164
-		}
165
-	}
166
-
167
-	/**
168
-	 * @param IUser $user
169
-	 * @param array $userGroups
170
-	 * @return array
171
-	 */
172
-	private function formatUserForIndex(IUser $user, array $userGroups = null) {
173
-
174
-		// TODO: eliminate this encryption specific code below and somehow
175
-		// hook in additional user info from other apps
176
-
177
-		// recovery isn't possible if admin or user has it disabled and encryption
178
-		// is enabled - so we eliminate the else paths in the conditional tree
179
-		// below
180
-		$restorePossible = false;
181
-
182
-		if ($this->isEncryptionAppEnabled) {
183
-			if ($this->isRestoreEnabled) {
184
-				// check for the users recovery setting
185
-				$recoveryMode = $this->config->getUserValue($user->getUID(), 'encryption', 'recoveryEnabled', '0');
186
-				// method call inside empty is possible with PHP 5.5+
187
-				$recoveryModeEnabled = !empty($recoveryMode);
188
-				if ($recoveryModeEnabled) {
189
-					// user also has recovery mode enabled
190
-					$restorePossible = true;
191
-				}
192
-			}
193
-		} else {
194
-			// recovery is possible if encryption is disabled (plain files are
195
-			// available)
196
-			$restorePossible = true;
197
-		}
198
-
199
-		$subAdminGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($user);
200
-		foreach($subAdminGroups as $key => $subAdminGroup) {
201
-			$subAdminGroups[$key] = $subAdminGroup->getGID();
202
-		}
203
-
204
-		$displayName = $user->getEMailAddress();
205
-		if (is_null($displayName)) {
206
-			$displayName = '';
207
-		}
208
-
209
-		$avatarAvailable = false;
210
-		try {
211
-			$avatarAvailable = $this->avatarManager->getAvatar($user->getUID())->exists();
212
-		} catch (\Exception $e) {
213
-			//No avatar yet
214
-		}
215
-
216
-		return [
217
-			'name' => $user->getUID(),
218
-			'displayname' => $user->getDisplayName(),
219
-			'groups' => (empty($userGroups)) ? $this->groupManager->getUserGroupIds($user) : $userGroups,
220
-			'subadmin' => $subAdminGroups,
221
-			'quota' => $user->getQuota(),
222
-			'storageLocation' => $user->getHome(),
223
-			'lastLogin' => $user->getLastLogin() * 1000,
224
-			'backend' => $user->getBackendClassName(),
225
-			'email' => $displayName,
226
-			'isRestoreDisabled' => !$restorePossible,
227
-			'isAvatarAvailable' => $avatarAvailable,
228
-			'isEnabled' => $user->isEnabled(),
229
-		];
230
-	}
231
-
232
-	/**
233
-	 * @param array $userIDs Array with schema [$uid => $displayName]
234
-	 * @return IUser[]
235
-	 */
236
-	private function getUsersForUID(array $userIDs) {
237
-		$users = [];
238
-		foreach ($userIDs as $uid => $displayName) {
239
-			$users[$uid] = $this->userManager->get($uid);
240
-		}
241
-		return $users;
242
-	}
243
-
244
-	/**
245
-	 * @NoAdminRequired
246
-	 *
247
-	 * @param int $offset
248
-	 * @param int $limit
249
-	 * @param string $gid GID to filter for
250
-	 * @param string $pattern Pattern to search for in the username
251
-	 * @param string $backend Backend to filter for (class-name)
252
-	 * @return DataResponse
253
-	 *
254
-	 * TODO: Tidy up and write unit tests - code is mainly static method calls
255
-	 */
256
-	public function index($offset = 0, $limit = 10, $gid = '', $pattern = '', $backend = '') {
257
-		// Remove backends
258
-		if(!empty($backend)) {
259
-			$activeBackends = $this->userManager->getBackends();
260
-			$this->userManager->clearBackends();
261
-			foreach($activeBackends as $singleActiveBackend) {
262
-				if($backend === get_class($singleActiveBackend)) {
263
-					$this->userManager->registerBackend($singleActiveBackend);
264
-					break;
265
-				}
266
-			}
267
-		}
268
-
269
-		$users = [];
270
-		if ($this->isAdmin) {
271
-			if($gid !== '' && $gid !== '_disabledUsers') {
272
-				$batch = $this->getUsersForUID($this->groupManager->displayNamesInGroup($gid, $pattern, $limit, $offset));
273
-			} else {
274
-				$batch = $this->userManager->search($pattern, $limit, $offset);
275
-			}
276
-
277
-			foreach ($batch as $user) {
278
-				if( ($gid !== '_disabledUsers' && $user->isEnabled()) ||
279
-					($gid === '_disabledUsers' && !$user->isEnabled())
280
-				) {
281
-					$users[] = $this->formatUserForIndex($user);
282
-				}
283
-			}
284
-
285
-		} else {
286
-			$subAdminOfGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($this->userSession->getUser());
287
-			// New class returns IGroup[] so convert back
288
-			$gids = [];
289
-			foreach ($subAdminOfGroups as $group) {
290
-				$gids[] = $group->getGID();
291
-			}
292
-			$subAdminOfGroups = $gids;
293
-
294
-			// Set the $gid parameter to an empty value if the subadmin has no rights to access a specific group
295
-			if($gid !== '' && $gid !== '_disabledUsers' && !in_array($gid, $subAdminOfGroups)) {
296
-				$gid = '';
297
-			}
298
-
299
-			// Batch all groups the user is subadmin of when a group is specified
300
-			$batch = [];
301
-			if($gid === '') {
302
-				foreach($subAdminOfGroups as $group) {
303
-					$groupUsers = $this->groupManager->displayNamesInGroup($group, $pattern, $limit, $offset);
304
-
305
-					foreach($groupUsers as $uid => $displayName) {
306
-						$batch[$uid] = $displayName;
307
-					}
308
-				}
309
-			} else {
310
-				$batch = $this->groupManager->displayNamesInGroup($gid, $pattern, $limit, $offset);
311
-			}
312
-			$batch = $this->getUsersForUID($batch);
313
-
314
-			foreach ($batch as $user) {
315
-				// Only add the groups, this user is a subadmin of
316
-				$userGroups = array_values(array_intersect(
317
-					$this->groupManager->getUserGroupIds($user),
318
-					$subAdminOfGroups
319
-				));
320
-				if( ($gid !== '_disabledUsers' && $user->isEnabled()) ||
321
-					($gid === '_disabledUsers' && !$user->isEnabled())
322
-				) {
323
-					$users[] = $this->formatUserForIndex($user, $userGroups);
324
-				}
325
-			}
326
-		}
327
-
328
-		return new DataResponse($users);
329
-	}
330
-
331
-	/**
332
-	 * @NoAdminRequired
333
-	 * @PasswordConfirmationRequired
334
-	 *
335
-	 * @param string $username
336
-	 * @param string $password
337
-	 * @param array $groups
338
-	 * @param string $email
339
-	 * @return DataResponse
340
-	 */
341
-	public function create($username, $password, array $groups=[], $email='') {
342
-		if($email !== '' && !$this->mailer->validateMailAddress($email)) {
343
-			return new DataResponse(
344
-				[
345
-					'message' => (string)$this->l10n->t('Invalid mail address')
346
-				],
347
-				Http::STATUS_UNPROCESSABLE_ENTITY
348
-			);
349
-		}
350
-
351
-		$currentUser = $this->userSession->getUser();
352
-
353
-		if (!$this->isAdmin) {
354
-			if (!empty($groups)) {
355
-				foreach ($groups as $key => $group) {
356
-					$groupObject = $this->groupManager->get($group);
357
-					if($groupObject === null) {
358
-						unset($groups[$key]);
359
-						continue;
360
-					}
361
-
362
-					if (!$this->groupManager->getSubAdmin()->isSubAdminofGroup($currentUser, $groupObject)) {
363
-						unset($groups[$key]);
364
-					}
365
-				}
366
-			}
367
-
368
-			if (empty($groups)) {
369
-				return new DataResponse(
370
-					[
371
-						'message' => $this->l10n->t('No valid group selected'),
372
-					],
373
-					Http::STATUS_FORBIDDEN
374
-				);
375
-			}
376
-		}
377
-
378
-		if ($this->userManager->userExists($username)) {
379
-			return new DataResponse(
380
-				[
381
-					'message' => (string)$this->l10n->t('A user with that name already exists.')
382
-				],
383
-				Http::STATUS_CONFLICT
384
-			);
385
-		}
386
-
387
-		$generatePasswordResetToken = false;
388
-		if ($password === '') {
389
-			if ($email === '') {
390
-				return new DataResponse(
391
-					[
392
-						'message' => (string)$this->l10n->t('To send a password link to the user an email address is required.')
393
-					],
394
-					Http::STATUS_UNPROCESSABLE_ENTITY
395
-				);
396
-			}
397
-
398
-			$password = $this->secureRandom->generate(32);
399
-			$generatePasswordResetToken = true;
400
-		}
401
-
402
-		try {
403
-			$user = $this->userManager->createUser($username, $password);
404
-		} catch (\Exception $exception) {
405
-			$message = $exception->getMessage();
406
-			if (!$message) {
407
-				$message = $this->l10n->t('Unable to create user.');
408
-			}
409
-			return new DataResponse(
410
-				[
411
-					'message' => (string) $message,
412
-				],
413
-				Http::STATUS_FORBIDDEN
414
-			);
415
-		}
416
-
417
-		if($user instanceof IUser) {
418
-			if($groups !== null) {
419
-				foreach($groups as $groupName) {
420
-					$group = $this->groupManager->get($groupName);
421
-
422
-					if(empty($group)) {
423
-						$group = $this->groupManager->createGroup($groupName);
424
-					}
425
-					$group->addUser($user);
426
-				}
427
-			}
428
-			/**
429
-			 * Send new user mail only if a mail is set
430
-			 */
431
-			if($email !== '') {
432
-				$user->setEMailAddress($email);
433
-				try {
434
-					$emailTemplate = $this->newUserMailHelper->generateTemplate($user, $generatePasswordResetToken);
435
-					$this->newUserMailHelper->sendMail($user, $emailTemplate);
436
-				} catch(\Exception $e) {
437
-					$this->log->error("Can't send new user mail to $email: " . $e->getMessage(), ['app' => 'settings']);
438
-				}
439
-			}
440
-			// fetch users groups
441
-			$userGroups = $this->groupManager->getUserGroupIds($user);
442
-
443
-			return new DataResponse(
444
-				$this->formatUserForIndex($user, $userGroups),
445
-				Http::STATUS_CREATED
446
-			);
447
-		}
448
-
449
-		return new DataResponse(
450
-			[
451
-				'message' => (string) $this->l10n->t('Unable to create user.')
452
-			],
453
-			Http::STATUS_FORBIDDEN
454
-		);
455
-
456
-	}
457
-
458
-	/**
459
-	 * @NoAdminRequired
460
-	 * @PasswordConfirmationRequired
461
-	 *
462
-	 * @param string $id
463
-	 * @return DataResponse
464
-	 */
465
-	public function destroy($id) {
466
-		$userId = $this->userSession->getUser()->getUID();
467
-		$user = $this->userManager->get($id);
468
-
469
-		if($userId === $id) {
470
-			return new DataResponse(
471
-				[
472
-					'status' => 'error',
473
-					'data' => [
474
-						'message' => (string) $this->l10n->t('Unable to delete user.')
475
-					]
476
-				],
477
-				Http::STATUS_FORBIDDEN
478
-			);
479
-		}
480
-
481
-		if(!$this->isAdmin && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)) {
482
-			return new DataResponse(
483
-				[
484
-					'status' => 'error',
485
-					'data' => [
486
-						'message' => (string)$this->l10n->t('Authentication error')
487
-					]
488
-				],
489
-				Http::STATUS_FORBIDDEN
490
-			);
491
-		}
492
-
493
-		if($user) {
494
-			if($user->delete()) {
495
-				return new DataResponse(
496
-					[
497
-						'status' => 'success',
498
-						'data' => [
499
-							'username' => $id
500
-						]
501
-					],
502
-					Http::STATUS_NO_CONTENT
503
-				);
504
-			}
505
-		}
506
-
507
-		return new DataResponse(
508
-			[
509
-				'status' => 'error',
510
-				'data' => [
511
-					'message' => (string)$this->l10n->t('Unable to delete user.')
512
-				]
513
-			],
514
-			Http::STATUS_FORBIDDEN
515
-		);
516
-	}
517
-
518
-	/**
519
-	 * @NoAdminRequired
520
-	 *
521
-	 * @param string $id
522
-	 * @param int $enabled
523
-	 * @return DataResponse
524
-	 */
525
-	public function setEnabled($id, $enabled) {
526
-		$enabled = (bool)$enabled;
527
-		if($enabled) {
528
-			$errorMsgGeneral = (string) $this->l10n->t('Error while enabling user.');
529
-		} else {
530
-			$errorMsgGeneral = (string) $this->l10n->t('Error while disabling user.');
531
-		}
532
-
533
-		$userId = $this->userSession->getUser()->getUID();
534
-		$user = $this->userManager->get($id);
535
-
536
-		if ($userId === $id) {
537
-			return new DataResponse(
538
-				[
539
-					'status' => 'error',
540
-					'data' => [
541
-						'message' => $errorMsgGeneral
542
-					]
543
-				], Http::STATUS_FORBIDDEN
544
-			);
545
-		}
546
-
547
-		if($user) {
548
-			if (!$this->isAdmin && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)) {
549
-				return new DataResponse(
550
-					[
551
-						'status' => 'error',
552
-						'data' => [
553
-							'message' => (string) $this->l10n->t('Authentication error')
554
-						]
555
-					],
556
-					Http::STATUS_FORBIDDEN
557
-				);
558
-			}
559
-
560
-			$user->setEnabled($enabled);
561
-			return new DataResponse(
562
-				[
563
-					'status' => 'success',
564
-					'data' => [
565
-						'username' => $id,
566
-						'enabled' => $enabled
567
-					]
568
-				]
569
-			);
570
-		} else {
571
-			return new DataResponse(
572
-				[
573
-					'status' => 'error',
574
-					'data' => [
575
-						'message' => $errorMsgGeneral
576
-					]
577
-				],
578
-				Http::STATUS_FORBIDDEN
579
-			);
580
-		}
581
-
582
-	}
583
-
584
-	/**
585
-	 * Set the mail address of a user
586
-	 *
587
-	 * @NoAdminRequired
588
-	 * @NoSubadminRequired
589
-	 * @PasswordConfirmationRequired
590
-	 *
591
-	 * @param string $account
592
-	 * @param bool $onlyVerificationCode only return verification code without updating the data
593
-	 * @return DataResponse
594
-	 */
595
-	public function getVerificationCode($account, $onlyVerificationCode) {
596
-
597
-		$user = $this->userSession->getUser();
598
-
599
-		if ($user === null) {
600
-			return new DataResponse([], Http::STATUS_BAD_REQUEST);
601
-		}
602
-
603
-		$accountData = $this->accountManager->getUser($user);
604
-		$cloudId = $user->getCloudId();
605
-		$message = "Use my Federated Cloud ID to share with me: " . $cloudId;
606
-		$signature = $this->signMessage($user, $message);
607
-
608
-		$code = $message . ' ' . $signature;
609
-		$codeMd5 = $message . ' ' . md5($signature);
610
-
611
-		switch ($account) {
612
-			case 'verify-twitter':
613
-				$accountData[AccountManager::PROPERTY_TWITTER]['verified'] = AccountManager::VERIFICATION_IN_PROGRESS;
614
-				$msg = $this->l10n->t('In order to verify your Twitter account post following tweet on Twitter (please make sure to post it without any line breaks):');
615
-				$code = $codeMd5;
616
-				$type = AccountManager::PROPERTY_TWITTER;
617
-				$data = $accountData[AccountManager::PROPERTY_TWITTER]['value'];
618
-				$accountData[AccountManager::PROPERTY_TWITTER]['signature'] = $signature;
619
-				break;
620
-			case 'verify-website':
621
-				$accountData[AccountManager::PROPERTY_WEBSITE]['verified'] = AccountManager::VERIFICATION_IN_PROGRESS;
622
-				$msg = $this->l10n->t('In order to verify your Website store following content in your web-root at \'.well-known/CloudIdVerificationCode.txt\' (please make sure that the complete text is in one line):');
623
-				$type = AccountManager::PROPERTY_WEBSITE;
624
-				$data = $accountData[AccountManager::PROPERTY_WEBSITE]['value'];
625
-				$accountData[AccountManager::PROPERTY_WEBSITE]['signature'] = $signature;
626
-				break;
627
-			default:
628
-				return new DataResponse([], Http::STATUS_BAD_REQUEST);
629
-		}
630
-
631
-		if ($onlyVerificationCode === false) {
632
-			$this->accountManager->updateUser($user, $accountData);
633
-
634
-			$this->jobList->add('OC\Settings\BackgroundJobs\VerifyUserData',
635
-				[
636
-					'verificationCode' => $code,
637
-					'data' => $data,
638
-					'type' => $type,
639
-					'uid' => $user->getUID(),
640
-					'try' => 0,
641
-					'lastRun' => $this->getCurrentTime()
642
-				]
643
-			);
644
-		}
645
-
646
-		return new DataResponse(['msg' => $msg, 'code' => $code]);
647
-	}
648
-
649
-	/**
650
-	 * get current timestamp
651
-	 *
652
-	 * @return int
653
-	 */
654
-	protected function getCurrentTime() {
655
-		return time();
656
-	}
657
-
658
-	/**
659
-	 * sign message with users private key
660
-	 *
661
-	 * @param IUser $user
662
-	 * @param string $message
663
-	 *
664
-	 * @return string base64 encoded signature
665
-	 */
666
-	protected function signMessage(IUser $user, $message) {
667
-		$privateKey = $this->keyManager->getKey($user)->getPrivate();
668
-		openssl_sign(json_encode($message), $signature, $privateKey, OPENSSL_ALGO_SHA512);
669
-		$signatureBase64 = base64_encode($signature);
670
-
671
-		return $signatureBase64;
672
-	}
673
-
674
-	/**
675
-	 * @NoAdminRequired
676
-	 * @NoSubadminRequired
677
-	 * @PasswordConfirmationRequired
678
-	 *
679
-	 * @param string $avatarScope
680
-	 * @param string $displayname
681
-	 * @param string $displaynameScope
682
-	 * @param string $phone
683
-	 * @param string $phoneScope
684
-	 * @param string $email
685
-	 * @param string $emailScope
686
-	 * @param string $website
687
-	 * @param string $websiteScope
688
-	 * @param string $address
689
-	 * @param string $addressScope
690
-	 * @param string $twitter
691
-	 * @param string $twitterScope
692
-	 * @return DataResponse
693
-	 */
694
-	public function setUserSettings($avatarScope,
695
-									$displayname,
696
-									$displaynameScope,
697
-									$phone,
698
-									$phoneScope,
699
-									$email,
700
-									$emailScope,
701
-									$website,
702
-									$websiteScope,
703
-									$address,
704
-									$addressScope,
705
-									$twitter,
706
-									$twitterScope
707
-	) {
708
-
709
-		if (!empty($email) && !$this->mailer->validateMailAddress($email)) {
710
-			return new DataResponse(
711
-				[
712
-					'status' => 'error',
713
-					'data' => [
714
-						'message' => (string) $this->l10n->t('Invalid mail address')
715
-					]
716
-				],
717
-				Http::STATUS_UNPROCESSABLE_ENTITY
718
-			);
719
-		}
720
-
721
-		$data = [
722
-			AccountManager::PROPERTY_AVATAR =>  ['scope' => $avatarScope],
723
-			AccountManager::PROPERTY_DISPLAYNAME => ['value' => $displayname, 'scope' => $displaynameScope],
724
-			AccountManager::PROPERTY_EMAIL=> ['value' => $email, 'scope' => $emailScope],
725
-			AccountManager::PROPERTY_WEBSITE => ['value' => $website, 'scope' => $websiteScope],
726
-			AccountManager::PROPERTY_ADDRESS => ['value' => $address, 'scope' => $addressScope],
727
-			AccountManager::PROPERTY_PHONE => ['value' => $phone, 'scope' => $phoneScope],
728
-			AccountManager::PROPERTY_TWITTER => ['value' => $twitter, 'scope' => $twitterScope]
729
-		];
730
-
731
-		$user = $this->userSession->getUser();
732
-
733
-		try {
734
-			$this->saveUserSettings($user, $data);
735
-			return new DataResponse(
736
-				[
737
-					'status' => 'success',
738
-					'data' => [
739
-						'userId' => $user->getUID(),
740
-						'avatarScope' => $avatarScope,
741
-						'displayname' => $displayname,
742
-						'displaynameScope' => $displaynameScope,
743
-						'email' => $email,
744
-						'emailScope' => $emailScope,
745
-						'website' => $website,
746
-						'websiteScope' => $websiteScope,
747
-						'address' => $address,
748
-						'addressScope' => $addressScope,
749
-						'message' => (string) $this->l10n->t('Settings saved')
750
-					]
751
-				],
752
-				Http::STATUS_OK
753
-			);
754
-		} catch (ForbiddenException $e) {
755
-			return new DataResponse([
756
-				'status' => 'error',
757
-				'data' => [
758
-					'message' => $e->getMessage()
759
-				],
760
-			]);
761
-		}
762
-
763
-	}
764
-
765
-
766
-	/**
767
-	 * update account manager with new user data
768
-	 *
769
-	 * @param IUser $user
770
-	 * @param array $data
771
-	 * @throws ForbiddenException
772
-	 */
773
-	protected function saveUserSettings(IUser $user, $data) {
774
-
775
-		// keep the user back-end up-to-date with the latest display name and email
776
-		// address
777
-		$oldDisplayName = $user->getDisplayName();
778
-		$oldDisplayName = is_null($oldDisplayName) ? '' : $oldDisplayName;
779
-		if (isset($data[AccountManager::PROPERTY_DISPLAYNAME]['value'])
780
-			&& $oldDisplayName !== $data[AccountManager::PROPERTY_DISPLAYNAME]['value']
781
-		) {
782
-			$result = $user->setDisplayName($data[AccountManager::PROPERTY_DISPLAYNAME]['value']);
783
-			if ($result === false) {
784
-				throw new ForbiddenException($this->l10n->t('Unable to change full name'));
785
-			}
786
-		}
787
-
788
-		$oldEmailAddress = $user->getEMailAddress();
789
-		$oldEmailAddress = is_null($oldEmailAddress) ? '' : $oldEmailAddress;
790
-		if (isset($data[AccountManager::PROPERTY_EMAIL]['value'])
791
-			&& $oldEmailAddress !== $data[AccountManager::PROPERTY_EMAIL]['value']
792
-		) {
793
-			// this is the only permission a backend provides and is also used
794
-			// for the permission of setting a email address
795
-			if (!$user->canChangeDisplayName()) {
796
-				throw new ForbiddenException($this->l10n->t('Unable to change email address'));
797
-			}
798
-			$user->setEMailAddress($data[AccountManager::PROPERTY_EMAIL]['value']);
799
-		}
800
-
801
-		$this->accountManager->updateUser($user, $data);
802
-	}
803
-
804
-	/**
805
-	 * Count all unique users visible for the current admin/subadmin.
806
-	 *
807
-	 * @NoAdminRequired
808
-	 *
809
-	 * @return DataResponse
810
-	 */
811
-	public function stats() {
812
-		$userCount = 0;
813
-		if ($this->isAdmin) {
814
-			$countByBackend = $this->userManager->countUsers();
815
-
816
-			if (!empty($countByBackend)) {
817
-				foreach ($countByBackend as $count) {
818
-					$userCount += $count;
819
-				}
820
-			}
821
-		} else {
822
-			$groups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($this->userSession->getUser());
823
-
824
-			$uniqueUsers = [];
825
-			foreach ($groups as $group) {
826
-				foreach($group->getUsers() as $uid => $displayName) {
827
-					$uniqueUsers[$uid] = true;
828
-				}
829
-			}
830
-
831
-			$userCount = count($uniqueUsers);
832
-		}
833
-
834
-		return new DataResponse(
835
-			[
836
-				'totalUsers' => $userCount
837
-			]
838
-		);
839
-	}
840
-
841
-
842
-	/**
843
-	 * Set the displayName of a user
844
-	 *
845
-	 * @NoAdminRequired
846
-	 * @NoSubadminRequired
847
-	 * @PasswordConfirmationRequired
848
-	 * @todo merge into saveUserSettings
849
-	 *
850
-	 * @param string $username
851
-	 * @param string $displayName
852
-	 * @return DataResponse
853
-	 */
854
-	public function setDisplayName($username, $displayName) {
855
-		$currentUser = $this->userSession->getUser();
856
-		$user = $this->userManager->get($username);
857
-
858
-		if ($user === null ||
859
-			!$user->canChangeDisplayName() ||
860
-			(
861
-				!$this->groupManager->isAdmin($currentUser->getUID()) &&
862
-				!$this->groupManager->getSubAdmin()->isUserAccessible($currentUser, $user) &&
863
-				$currentUser->getUID() !== $username
864
-
865
-			)
866
-		) {
867
-			return new DataResponse([
868
-				'status' => 'error',
869
-				'data' => [
870
-					'message' => $this->l10n->t('Authentication error'),
871
-				],
872
-			]);
873
-		}
874
-
875
-		$userData = $this->accountManager->getUser($user);
876
-		$userData[AccountManager::PROPERTY_DISPLAYNAME]['value'] = $displayName;
877
-
878
-
879
-		try {
880
-			$this->saveUserSettings($user, $userData);
881
-			return new DataResponse([
882
-				'status' => 'success',
883
-				'data' => [
884
-					'message' => $this->l10n->t('Your full name has been changed.'),
885
-					'username' => $username,
886
-					'displayName' => $displayName,
887
-				],
888
-			]);
889
-		} catch (ForbiddenException $e) {
890
-			return new DataResponse([
891
-				'status' => 'error',
892
-				'data' => [
893
-					'message' => $e->getMessage(),
894
-					'displayName' => $user->getDisplayName(),
895
-				],
896
-			]);
897
-		}
898
-	}
899
-
900
-	/**
901
-	 * Set the mail address of a user
902
-	 *
903
-	 * @NoAdminRequired
904
-	 * @NoSubadminRequired
905
-	 * @PasswordConfirmationRequired
906
-	 *
907
-	 * @param string $id
908
-	 * @param string $mailAddress
909
-	 * @return DataResponse
910
-	 */
911
-	public function setEMailAddress($id, $mailAddress) {
912
-		$user = $this->userManager->get($id);
913
-		if (!$this->isAdmin
914
-			&& !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)
915
-		) {
916
-			return new DataResponse(
917
-				[
918
-					'status' => 'error',
919
-					'data' => [
920
-						'message' => (string) $this->l10n->t('Forbidden')
921
-					]
922
-				],
923
-				Http::STATUS_FORBIDDEN
924
-			);
925
-		}
926
-
927
-		if($mailAddress !== '' && !$this->mailer->validateMailAddress($mailAddress)) {
928
-			return new DataResponse(
929
-				[
930
-					'status' => 'error',
931
-					'data' => [
932
-						'message' => (string) $this->l10n->t('Invalid mail address')
933
-					]
934
-				],
935
-				Http::STATUS_UNPROCESSABLE_ENTITY
936
-			);
937
-		}
938
-
939
-		if (!$user) {
940
-			return new DataResponse(
941
-				[
942
-					'status' => 'error',
943
-					'data' => [
944
-						'message' => (string) $this->l10n->t('Invalid user')
945
-					]
946
-				],
947
-				Http::STATUS_UNPROCESSABLE_ENTITY
948
-			);
949
-		}
950
-		// this is the only permission a backend provides and is also used
951
-		// for the permission of setting a email address
952
-		if (!$user->canChangeDisplayName()) {
953
-			return new DataResponse(
954
-				[
955
-					'status' => 'error',
956
-					'data' => [
957
-						'message' => (string) $this->l10n->t('Unable to change mail address')
958
-					]
959
-				],
960
-				Http::STATUS_FORBIDDEN
961
-			);
962
-		}
963
-
964
-		$userData = $this->accountManager->getUser($user);
965
-		$userData[AccountManager::PROPERTY_EMAIL]['value'] = $mailAddress;
966
-
967
-		try {
968
-			$this->saveUserSettings($user, $userData);
969
-			return new DataResponse(
970
-				[
971
-					'status' => 'success',
972
-					'data' => [
973
-						'username' => $id,
974
-						'mailAddress' => $mailAddress,
975
-						'message' => (string) $this->l10n->t('Email saved')
976
-					]
977
-				],
978
-				Http::STATUS_OK
979
-			);
980
-		} catch (ForbiddenException $e) {
981
-			return new DataResponse([
982
-				'status' => 'error',
983
-				'data' => [
984
-					'message' => $e->getMessage()
985
-				],
986
-			]);
987
-		}
988
-	}
61
+    /** @var IL10N */
62
+    private $l10n;
63
+    /** @var IUserSession */
64
+    private $userSession;
65
+    /** @var bool */
66
+    private $isAdmin;
67
+    /** @var IUserManager */
68
+    private $userManager;
69
+    /** @var IGroupManager */
70
+    private $groupManager;
71
+    /** @var IConfig */
72
+    private $config;
73
+    /** @var ILogger */
74
+    private $log;
75
+    /** @var IMailer */
76
+    private $mailer;
77
+    /** @var bool contains the state of the encryption app */
78
+    private $isEncryptionAppEnabled;
79
+    /** @var bool contains the state of the admin recovery setting */
80
+    private $isRestoreEnabled = false;
81
+    /** @var IAvatarManager */
82
+    private $avatarManager;
83
+    /** @var AccountManager */
84
+    private $accountManager;
85
+    /** @var ISecureRandom */
86
+    private $secureRandom;
87
+    /** @var NewUserMailHelper */
88
+    private $newUserMailHelper;
89
+    /** @var ITimeFactory */
90
+    private $timeFactory;
91
+    /** @var ICrypto */
92
+    private $crypto;
93
+    /** @var Manager */
94
+    private $keyManager;
95
+    /** @var IJobList */
96
+    private $jobList;
97
+
98
+    /**
99
+     * @param string $appName
100
+     * @param IRequest $request
101
+     * @param IUserManager $userManager
102
+     * @param IGroupManager $groupManager
103
+     * @param IUserSession $userSession
104
+     * @param IConfig $config
105
+     * @param bool $isAdmin
106
+     * @param IL10N $l10n
107
+     * @param ILogger $log
108
+     * @param IMailer $mailer
109
+     * @param IURLGenerator $urlGenerator
110
+     * @param IAppManager $appManager
111
+     * @param IAvatarManager $avatarManager
112
+     * @param AccountManager $accountManager
113
+     * @param ISecureRandom $secureRandom
114
+     * @param NewUserMailHelper $newUserMailHelper
115
+     * @param ITimeFactory $timeFactory
116
+     * @param ICrypto $crypto
117
+     * @param Manager $keyManager
118
+     * @param IJobList $jobList
119
+     */
120
+    public function __construct($appName,
121
+                                IRequest $request,
122
+                                IUserManager $userManager,
123
+                                IGroupManager $groupManager,
124
+                                IUserSession $userSession,
125
+                                IConfig $config,
126
+                                $isAdmin,
127
+                                IL10N $l10n,
128
+                                ILogger $log,
129
+                                IMailer $mailer,
130
+                                IURLGenerator $urlGenerator,
131
+                                IAppManager $appManager,
132
+                                IAvatarManager $avatarManager,
133
+                                AccountManager $accountManager,
134
+                                ISecureRandom $secureRandom,
135
+                                NewUserMailHelper $newUserMailHelper,
136
+                                ITimeFactory $timeFactory,
137
+                                ICrypto $crypto,
138
+                                Manager $keyManager,
139
+                                IJobList $jobList) {
140
+        parent::__construct($appName, $request);
141
+        $this->userManager = $userManager;
142
+        $this->groupManager = $groupManager;
143
+        $this->userSession = $userSession;
144
+        $this->config = $config;
145
+        $this->isAdmin = $isAdmin;
146
+        $this->l10n = $l10n;
147
+        $this->log = $log;
148
+        $this->mailer = $mailer;
149
+        $this->avatarManager = $avatarManager;
150
+        $this->accountManager = $accountManager;
151
+        $this->secureRandom = $secureRandom;
152
+        $this->newUserMailHelper = $newUserMailHelper;
153
+        $this->timeFactory = $timeFactory;
154
+        $this->crypto = $crypto;
155
+        $this->keyManager = $keyManager;
156
+        $this->jobList = $jobList;
157
+
158
+        // check for encryption state - TODO see formatUserForIndex
159
+        $this->isEncryptionAppEnabled = $appManager->isEnabledForUser('encryption');
160
+        if($this->isEncryptionAppEnabled) {
161
+            // putting this directly in empty is possible in PHP 5.5+
162
+            $result = $config->getAppValue('encryption', 'recoveryAdminEnabled', 0);
163
+            $this->isRestoreEnabled = !empty($result);
164
+        }
165
+    }
166
+
167
+    /**
168
+     * @param IUser $user
169
+     * @param array $userGroups
170
+     * @return array
171
+     */
172
+    private function formatUserForIndex(IUser $user, array $userGroups = null) {
173
+
174
+        // TODO: eliminate this encryption specific code below and somehow
175
+        // hook in additional user info from other apps
176
+
177
+        // recovery isn't possible if admin or user has it disabled and encryption
178
+        // is enabled - so we eliminate the else paths in the conditional tree
179
+        // below
180
+        $restorePossible = false;
181
+
182
+        if ($this->isEncryptionAppEnabled) {
183
+            if ($this->isRestoreEnabled) {
184
+                // check for the users recovery setting
185
+                $recoveryMode = $this->config->getUserValue($user->getUID(), 'encryption', 'recoveryEnabled', '0');
186
+                // method call inside empty is possible with PHP 5.5+
187
+                $recoveryModeEnabled = !empty($recoveryMode);
188
+                if ($recoveryModeEnabled) {
189
+                    // user also has recovery mode enabled
190
+                    $restorePossible = true;
191
+                }
192
+            }
193
+        } else {
194
+            // recovery is possible if encryption is disabled (plain files are
195
+            // available)
196
+            $restorePossible = true;
197
+        }
198
+
199
+        $subAdminGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($user);
200
+        foreach($subAdminGroups as $key => $subAdminGroup) {
201
+            $subAdminGroups[$key] = $subAdminGroup->getGID();
202
+        }
203
+
204
+        $displayName = $user->getEMailAddress();
205
+        if (is_null($displayName)) {
206
+            $displayName = '';
207
+        }
208
+
209
+        $avatarAvailable = false;
210
+        try {
211
+            $avatarAvailable = $this->avatarManager->getAvatar($user->getUID())->exists();
212
+        } catch (\Exception $e) {
213
+            //No avatar yet
214
+        }
215
+
216
+        return [
217
+            'name' => $user->getUID(),
218
+            'displayname' => $user->getDisplayName(),
219
+            'groups' => (empty($userGroups)) ? $this->groupManager->getUserGroupIds($user) : $userGroups,
220
+            'subadmin' => $subAdminGroups,
221
+            'quota' => $user->getQuota(),
222
+            'storageLocation' => $user->getHome(),
223
+            'lastLogin' => $user->getLastLogin() * 1000,
224
+            'backend' => $user->getBackendClassName(),
225
+            'email' => $displayName,
226
+            'isRestoreDisabled' => !$restorePossible,
227
+            'isAvatarAvailable' => $avatarAvailable,
228
+            'isEnabled' => $user->isEnabled(),
229
+        ];
230
+    }
231
+
232
+    /**
233
+     * @param array $userIDs Array with schema [$uid => $displayName]
234
+     * @return IUser[]
235
+     */
236
+    private function getUsersForUID(array $userIDs) {
237
+        $users = [];
238
+        foreach ($userIDs as $uid => $displayName) {
239
+            $users[$uid] = $this->userManager->get($uid);
240
+        }
241
+        return $users;
242
+    }
243
+
244
+    /**
245
+     * @NoAdminRequired
246
+     *
247
+     * @param int $offset
248
+     * @param int $limit
249
+     * @param string $gid GID to filter for
250
+     * @param string $pattern Pattern to search for in the username
251
+     * @param string $backend Backend to filter for (class-name)
252
+     * @return DataResponse
253
+     *
254
+     * TODO: Tidy up and write unit tests - code is mainly static method calls
255
+     */
256
+    public function index($offset = 0, $limit = 10, $gid = '', $pattern = '', $backend = '') {
257
+        // Remove backends
258
+        if(!empty($backend)) {
259
+            $activeBackends = $this->userManager->getBackends();
260
+            $this->userManager->clearBackends();
261
+            foreach($activeBackends as $singleActiveBackend) {
262
+                if($backend === get_class($singleActiveBackend)) {
263
+                    $this->userManager->registerBackend($singleActiveBackend);
264
+                    break;
265
+                }
266
+            }
267
+        }
268
+
269
+        $users = [];
270
+        if ($this->isAdmin) {
271
+            if($gid !== '' && $gid !== '_disabledUsers') {
272
+                $batch = $this->getUsersForUID($this->groupManager->displayNamesInGroup($gid, $pattern, $limit, $offset));
273
+            } else {
274
+                $batch = $this->userManager->search($pattern, $limit, $offset);
275
+            }
276
+
277
+            foreach ($batch as $user) {
278
+                if( ($gid !== '_disabledUsers' && $user->isEnabled()) ||
279
+                    ($gid === '_disabledUsers' && !$user->isEnabled())
280
+                ) {
281
+                    $users[] = $this->formatUserForIndex($user);
282
+                }
283
+            }
284
+
285
+        } else {
286
+            $subAdminOfGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($this->userSession->getUser());
287
+            // New class returns IGroup[] so convert back
288
+            $gids = [];
289
+            foreach ($subAdminOfGroups as $group) {
290
+                $gids[] = $group->getGID();
291
+            }
292
+            $subAdminOfGroups = $gids;
293
+
294
+            // Set the $gid parameter to an empty value if the subadmin has no rights to access a specific group
295
+            if($gid !== '' && $gid !== '_disabledUsers' && !in_array($gid, $subAdminOfGroups)) {
296
+                $gid = '';
297
+            }
298
+
299
+            // Batch all groups the user is subadmin of when a group is specified
300
+            $batch = [];
301
+            if($gid === '') {
302
+                foreach($subAdminOfGroups as $group) {
303
+                    $groupUsers = $this->groupManager->displayNamesInGroup($group, $pattern, $limit, $offset);
304
+
305
+                    foreach($groupUsers as $uid => $displayName) {
306
+                        $batch[$uid] = $displayName;
307
+                    }
308
+                }
309
+            } else {
310
+                $batch = $this->groupManager->displayNamesInGroup($gid, $pattern, $limit, $offset);
311
+            }
312
+            $batch = $this->getUsersForUID($batch);
313
+
314
+            foreach ($batch as $user) {
315
+                // Only add the groups, this user is a subadmin of
316
+                $userGroups = array_values(array_intersect(
317
+                    $this->groupManager->getUserGroupIds($user),
318
+                    $subAdminOfGroups
319
+                ));
320
+                if( ($gid !== '_disabledUsers' && $user->isEnabled()) ||
321
+                    ($gid === '_disabledUsers' && !$user->isEnabled())
322
+                ) {
323
+                    $users[] = $this->formatUserForIndex($user, $userGroups);
324
+                }
325
+            }
326
+        }
327
+
328
+        return new DataResponse($users);
329
+    }
330
+
331
+    /**
332
+     * @NoAdminRequired
333
+     * @PasswordConfirmationRequired
334
+     *
335
+     * @param string $username
336
+     * @param string $password
337
+     * @param array $groups
338
+     * @param string $email
339
+     * @return DataResponse
340
+     */
341
+    public function create($username, $password, array $groups=[], $email='') {
342
+        if($email !== '' && !$this->mailer->validateMailAddress($email)) {
343
+            return new DataResponse(
344
+                [
345
+                    'message' => (string)$this->l10n->t('Invalid mail address')
346
+                ],
347
+                Http::STATUS_UNPROCESSABLE_ENTITY
348
+            );
349
+        }
350
+
351
+        $currentUser = $this->userSession->getUser();
352
+
353
+        if (!$this->isAdmin) {
354
+            if (!empty($groups)) {
355
+                foreach ($groups as $key => $group) {
356
+                    $groupObject = $this->groupManager->get($group);
357
+                    if($groupObject === null) {
358
+                        unset($groups[$key]);
359
+                        continue;
360
+                    }
361
+
362
+                    if (!$this->groupManager->getSubAdmin()->isSubAdminofGroup($currentUser, $groupObject)) {
363
+                        unset($groups[$key]);
364
+                    }
365
+                }
366
+            }
367
+
368
+            if (empty($groups)) {
369
+                return new DataResponse(
370
+                    [
371
+                        'message' => $this->l10n->t('No valid group selected'),
372
+                    ],
373
+                    Http::STATUS_FORBIDDEN
374
+                );
375
+            }
376
+        }
377
+
378
+        if ($this->userManager->userExists($username)) {
379
+            return new DataResponse(
380
+                [
381
+                    'message' => (string)$this->l10n->t('A user with that name already exists.')
382
+                ],
383
+                Http::STATUS_CONFLICT
384
+            );
385
+        }
386
+
387
+        $generatePasswordResetToken = false;
388
+        if ($password === '') {
389
+            if ($email === '') {
390
+                return new DataResponse(
391
+                    [
392
+                        'message' => (string)$this->l10n->t('To send a password link to the user an email address is required.')
393
+                    ],
394
+                    Http::STATUS_UNPROCESSABLE_ENTITY
395
+                );
396
+            }
397
+
398
+            $password = $this->secureRandom->generate(32);
399
+            $generatePasswordResetToken = true;
400
+        }
401
+
402
+        try {
403
+            $user = $this->userManager->createUser($username, $password);
404
+        } catch (\Exception $exception) {
405
+            $message = $exception->getMessage();
406
+            if (!$message) {
407
+                $message = $this->l10n->t('Unable to create user.');
408
+            }
409
+            return new DataResponse(
410
+                [
411
+                    'message' => (string) $message,
412
+                ],
413
+                Http::STATUS_FORBIDDEN
414
+            );
415
+        }
416
+
417
+        if($user instanceof IUser) {
418
+            if($groups !== null) {
419
+                foreach($groups as $groupName) {
420
+                    $group = $this->groupManager->get($groupName);
421
+
422
+                    if(empty($group)) {
423
+                        $group = $this->groupManager->createGroup($groupName);
424
+                    }
425
+                    $group->addUser($user);
426
+                }
427
+            }
428
+            /**
429
+             * Send new user mail only if a mail is set
430
+             */
431
+            if($email !== '') {
432
+                $user->setEMailAddress($email);
433
+                try {
434
+                    $emailTemplate = $this->newUserMailHelper->generateTemplate($user, $generatePasswordResetToken);
435
+                    $this->newUserMailHelper->sendMail($user, $emailTemplate);
436
+                } catch(\Exception $e) {
437
+                    $this->log->error("Can't send new user mail to $email: " . $e->getMessage(), ['app' => 'settings']);
438
+                }
439
+            }
440
+            // fetch users groups
441
+            $userGroups = $this->groupManager->getUserGroupIds($user);
442
+
443
+            return new DataResponse(
444
+                $this->formatUserForIndex($user, $userGroups),
445
+                Http::STATUS_CREATED
446
+            );
447
+        }
448
+
449
+        return new DataResponse(
450
+            [
451
+                'message' => (string) $this->l10n->t('Unable to create user.')
452
+            ],
453
+            Http::STATUS_FORBIDDEN
454
+        );
455
+
456
+    }
457
+
458
+    /**
459
+     * @NoAdminRequired
460
+     * @PasswordConfirmationRequired
461
+     *
462
+     * @param string $id
463
+     * @return DataResponse
464
+     */
465
+    public function destroy($id) {
466
+        $userId = $this->userSession->getUser()->getUID();
467
+        $user = $this->userManager->get($id);
468
+
469
+        if($userId === $id) {
470
+            return new DataResponse(
471
+                [
472
+                    'status' => 'error',
473
+                    'data' => [
474
+                        'message' => (string) $this->l10n->t('Unable to delete user.')
475
+                    ]
476
+                ],
477
+                Http::STATUS_FORBIDDEN
478
+            );
479
+        }
480
+
481
+        if(!$this->isAdmin && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)) {
482
+            return new DataResponse(
483
+                [
484
+                    'status' => 'error',
485
+                    'data' => [
486
+                        'message' => (string)$this->l10n->t('Authentication error')
487
+                    ]
488
+                ],
489
+                Http::STATUS_FORBIDDEN
490
+            );
491
+        }
492
+
493
+        if($user) {
494
+            if($user->delete()) {
495
+                return new DataResponse(
496
+                    [
497
+                        'status' => 'success',
498
+                        'data' => [
499
+                            'username' => $id
500
+                        ]
501
+                    ],
502
+                    Http::STATUS_NO_CONTENT
503
+                );
504
+            }
505
+        }
506
+
507
+        return new DataResponse(
508
+            [
509
+                'status' => 'error',
510
+                'data' => [
511
+                    'message' => (string)$this->l10n->t('Unable to delete user.')
512
+                ]
513
+            ],
514
+            Http::STATUS_FORBIDDEN
515
+        );
516
+    }
517
+
518
+    /**
519
+     * @NoAdminRequired
520
+     *
521
+     * @param string $id
522
+     * @param int $enabled
523
+     * @return DataResponse
524
+     */
525
+    public function setEnabled($id, $enabled) {
526
+        $enabled = (bool)$enabled;
527
+        if($enabled) {
528
+            $errorMsgGeneral = (string) $this->l10n->t('Error while enabling user.');
529
+        } else {
530
+            $errorMsgGeneral = (string) $this->l10n->t('Error while disabling user.');
531
+        }
532
+
533
+        $userId = $this->userSession->getUser()->getUID();
534
+        $user = $this->userManager->get($id);
535
+
536
+        if ($userId === $id) {
537
+            return new DataResponse(
538
+                [
539
+                    'status' => 'error',
540
+                    'data' => [
541
+                        'message' => $errorMsgGeneral
542
+                    ]
543
+                ], Http::STATUS_FORBIDDEN
544
+            );
545
+        }
546
+
547
+        if($user) {
548
+            if (!$this->isAdmin && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)) {
549
+                return new DataResponse(
550
+                    [
551
+                        'status' => 'error',
552
+                        'data' => [
553
+                            'message' => (string) $this->l10n->t('Authentication error')
554
+                        ]
555
+                    ],
556
+                    Http::STATUS_FORBIDDEN
557
+                );
558
+            }
559
+
560
+            $user->setEnabled($enabled);
561
+            return new DataResponse(
562
+                [
563
+                    'status' => 'success',
564
+                    'data' => [
565
+                        'username' => $id,
566
+                        'enabled' => $enabled
567
+                    ]
568
+                ]
569
+            );
570
+        } else {
571
+            return new DataResponse(
572
+                [
573
+                    'status' => 'error',
574
+                    'data' => [
575
+                        'message' => $errorMsgGeneral
576
+                    ]
577
+                ],
578
+                Http::STATUS_FORBIDDEN
579
+            );
580
+        }
581
+
582
+    }
583
+
584
+    /**
585
+     * Set the mail address of a user
586
+     *
587
+     * @NoAdminRequired
588
+     * @NoSubadminRequired
589
+     * @PasswordConfirmationRequired
590
+     *
591
+     * @param string $account
592
+     * @param bool $onlyVerificationCode only return verification code without updating the data
593
+     * @return DataResponse
594
+     */
595
+    public function getVerificationCode($account, $onlyVerificationCode) {
596
+
597
+        $user = $this->userSession->getUser();
598
+
599
+        if ($user === null) {
600
+            return new DataResponse([], Http::STATUS_BAD_REQUEST);
601
+        }
602
+
603
+        $accountData = $this->accountManager->getUser($user);
604
+        $cloudId = $user->getCloudId();
605
+        $message = "Use my Federated Cloud ID to share with me: " . $cloudId;
606
+        $signature = $this->signMessage($user, $message);
607
+
608
+        $code = $message . ' ' . $signature;
609
+        $codeMd5 = $message . ' ' . md5($signature);
610
+
611
+        switch ($account) {
612
+            case 'verify-twitter':
613
+                $accountData[AccountManager::PROPERTY_TWITTER]['verified'] = AccountManager::VERIFICATION_IN_PROGRESS;
614
+                $msg = $this->l10n->t('In order to verify your Twitter account post following tweet on Twitter (please make sure to post it without any line breaks):');
615
+                $code = $codeMd5;
616
+                $type = AccountManager::PROPERTY_TWITTER;
617
+                $data = $accountData[AccountManager::PROPERTY_TWITTER]['value'];
618
+                $accountData[AccountManager::PROPERTY_TWITTER]['signature'] = $signature;
619
+                break;
620
+            case 'verify-website':
621
+                $accountData[AccountManager::PROPERTY_WEBSITE]['verified'] = AccountManager::VERIFICATION_IN_PROGRESS;
622
+                $msg = $this->l10n->t('In order to verify your Website store following content in your web-root at \'.well-known/CloudIdVerificationCode.txt\' (please make sure that the complete text is in one line):');
623
+                $type = AccountManager::PROPERTY_WEBSITE;
624
+                $data = $accountData[AccountManager::PROPERTY_WEBSITE]['value'];
625
+                $accountData[AccountManager::PROPERTY_WEBSITE]['signature'] = $signature;
626
+                break;
627
+            default:
628
+                return new DataResponse([], Http::STATUS_BAD_REQUEST);
629
+        }
630
+
631
+        if ($onlyVerificationCode === false) {
632
+            $this->accountManager->updateUser($user, $accountData);
633
+
634
+            $this->jobList->add('OC\Settings\BackgroundJobs\VerifyUserData',
635
+                [
636
+                    'verificationCode' => $code,
637
+                    'data' => $data,
638
+                    'type' => $type,
639
+                    'uid' => $user->getUID(),
640
+                    'try' => 0,
641
+                    'lastRun' => $this->getCurrentTime()
642
+                ]
643
+            );
644
+        }
645
+
646
+        return new DataResponse(['msg' => $msg, 'code' => $code]);
647
+    }
648
+
649
+    /**
650
+     * get current timestamp
651
+     *
652
+     * @return int
653
+     */
654
+    protected function getCurrentTime() {
655
+        return time();
656
+    }
657
+
658
+    /**
659
+     * sign message with users private key
660
+     *
661
+     * @param IUser $user
662
+     * @param string $message
663
+     *
664
+     * @return string base64 encoded signature
665
+     */
666
+    protected function signMessage(IUser $user, $message) {
667
+        $privateKey = $this->keyManager->getKey($user)->getPrivate();
668
+        openssl_sign(json_encode($message), $signature, $privateKey, OPENSSL_ALGO_SHA512);
669
+        $signatureBase64 = base64_encode($signature);
670
+
671
+        return $signatureBase64;
672
+    }
673
+
674
+    /**
675
+     * @NoAdminRequired
676
+     * @NoSubadminRequired
677
+     * @PasswordConfirmationRequired
678
+     *
679
+     * @param string $avatarScope
680
+     * @param string $displayname
681
+     * @param string $displaynameScope
682
+     * @param string $phone
683
+     * @param string $phoneScope
684
+     * @param string $email
685
+     * @param string $emailScope
686
+     * @param string $website
687
+     * @param string $websiteScope
688
+     * @param string $address
689
+     * @param string $addressScope
690
+     * @param string $twitter
691
+     * @param string $twitterScope
692
+     * @return DataResponse
693
+     */
694
+    public function setUserSettings($avatarScope,
695
+                                    $displayname,
696
+                                    $displaynameScope,
697
+                                    $phone,
698
+                                    $phoneScope,
699
+                                    $email,
700
+                                    $emailScope,
701
+                                    $website,
702
+                                    $websiteScope,
703
+                                    $address,
704
+                                    $addressScope,
705
+                                    $twitter,
706
+                                    $twitterScope
707
+    ) {
708
+
709
+        if (!empty($email) && !$this->mailer->validateMailAddress($email)) {
710
+            return new DataResponse(
711
+                [
712
+                    'status' => 'error',
713
+                    'data' => [
714
+                        'message' => (string) $this->l10n->t('Invalid mail address')
715
+                    ]
716
+                ],
717
+                Http::STATUS_UNPROCESSABLE_ENTITY
718
+            );
719
+        }
720
+
721
+        $data = [
722
+            AccountManager::PROPERTY_AVATAR =>  ['scope' => $avatarScope],
723
+            AccountManager::PROPERTY_DISPLAYNAME => ['value' => $displayname, 'scope' => $displaynameScope],
724
+            AccountManager::PROPERTY_EMAIL=> ['value' => $email, 'scope' => $emailScope],
725
+            AccountManager::PROPERTY_WEBSITE => ['value' => $website, 'scope' => $websiteScope],
726
+            AccountManager::PROPERTY_ADDRESS => ['value' => $address, 'scope' => $addressScope],
727
+            AccountManager::PROPERTY_PHONE => ['value' => $phone, 'scope' => $phoneScope],
728
+            AccountManager::PROPERTY_TWITTER => ['value' => $twitter, 'scope' => $twitterScope]
729
+        ];
730
+
731
+        $user = $this->userSession->getUser();
732
+
733
+        try {
734
+            $this->saveUserSettings($user, $data);
735
+            return new DataResponse(
736
+                [
737
+                    'status' => 'success',
738
+                    'data' => [
739
+                        'userId' => $user->getUID(),
740
+                        'avatarScope' => $avatarScope,
741
+                        'displayname' => $displayname,
742
+                        'displaynameScope' => $displaynameScope,
743
+                        'email' => $email,
744
+                        'emailScope' => $emailScope,
745
+                        'website' => $website,
746
+                        'websiteScope' => $websiteScope,
747
+                        'address' => $address,
748
+                        'addressScope' => $addressScope,
749
+                        'message' => (string) $this->l10n->t('Settings saved')
750
+                    ]
751
+                ],
752
+                Http::STATUS_OK
753
+            );
754
+        } catch (ForbiddenException $e) {
755
+            return new DataResponse([
756
+                'status' => 'error',
757
+                'data' => [
758
+                    'message' => $e->getMessage()
759
+                ],
760
+            ]);
761
+        }
762
+
763
+    }
764
+
765
+
766
+    /**
767
+     * update account manager with new user data
768
+     *
769
+     * @param IUser $user
770
+     * @param array $data
771
+     * @throws ForbiddenException
772
+     */
773
+    protected function saveUserSettings(IUser $user, $data) {
774
+
775
+        // keep the user back-end up-to-date with the latest display name and email
776
+        // address
777
+        $oldDisplayName = $user->getDisplayName();
778
+        $oldDisplayName = is_null($oldDisplayName) ? '' : $oldDisplayName;
779
+        if (isset($data[AccountManager::PROPERTY_DISPLAYNAME]['value'])
780
+            && $oldDisplayName !== $data[AccountManager::PROPERTY_DISPLAYNAME]['value']
781
+        ) {
782
+            $result = $user->setDisplayName($data[AccountManager::PROPERTY_DISPLAYNAME]['value']);
783
+            if ($result === false) {
784
+                throw new ForbiddenException($this->l10n->t('Unable to change full name'));
785
+            }
786
+        }
787
+
788
+        $oldEmailAddress = $user->getEMailAddress();
789
+        $oldEmailAddress = is_null($oldEmailAddress) ? '' : $oldEmailAddress;
790
+        if (isset($data[AccountManager::PROPERTY_EMAIL]['value'])
791
+            && $oldEmailAddress !== $data[AccountManager::PROPERTY_EMAIL]['value']
792
+        ) {
793
+            // this is the only permission a backend provides and is also used
794
+            // for the permission of setting a email address
795
+            if (!$user->canChangeDisplayName()) {
796
+                throw new ForbiddenException($this->l10n->t('Unable to change email address'));
797
+            }
798
+            $user->setEMailAddress($data[AccountManager::PROPERTY_EMAIL]['value']);
799
+        }
800
+
801
+        $this->accountManager->updateUser($user, $data);
802
+    }
803
+
804
+    /**
805
+     * Count all unique users visible for the current admin/subadmin.
806
+     *
807
+     * @NoAdminRequired
808
+     *
809
+     * @return DataResponse
810
+     */
811
+    public function stats() {
812
+        $userCount = 0;
813
+        if ($this->isAdmin) {
814
+            $countByBackend = $this->userManager->countUsers();
815
+
816
+            if (!empty($countByBackend)) {
817
+                foreach ($countByBackend as $count) {
818
+                    $userCount += $count;
819
+                }
820
+            }
821
+        } else {
822
+            $groups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($this->userSession->getUser());
823
+
824
+            $uniqueUsers = [];
825
+            foreach ($groups as $group) {
826
+                foreach($group->getUsers() as $uid => $displayName) {
827
+                    $uniqueUsers[$uid] = true;
828
+                }
829
+            }
830
+
831
+            $userCount = count($uniqueUsers);
832
+        }
833
+
834
+        return new DataResponse(
835
+            [
836
+                'totalUsers' => $userCount
837
+            ]
838
+        );
839
+    }
840
+
841
+
842
+    /**
843
+     * Set the displayName of a user
844
+     *
845
+     * @NoAdminRequired
846
+     * @NoSubadminRequired
847
+     * @PasswordConfirmationRequired
848
+     * @todo merge into saveUserSettings
849
+     *
850
+     * @param string $username
851
+     * @param string $displayName
852
+     * @return DataResponse
853
+     */
854
+    public function setDisplayName($username, $displayName) {
855
+        $currentUser = $this->userSession->getUser();
856
+        $user = $this->userManager->get($username);
857
+
858
+        if ($user === null ||
859
+            !$user->canChangeDisplayName() ||
860
+            (
861
+                !$this->groupManager->isAdmin($currentUser->getUID()) &&
862
+                !$this->groupManager->getSubAdmin()->isUserAccessible($currentUser, $user) &&
863
+                $currentUser->getUID() !== $username
864
+
865
+            )
866
+        ) {
867
+            return new DataResponse([
868
+                'status' => 'error',
869
+                'data' => [
870
+                    'message' => $this->l10n->t('Authentication error'),
871
+                ],
872
+            ]);
873
+        }
874
+
875
+        $userData = $this->accountManager->getUser($user);
876
+        $userData[AccountManager::PROPERTY_DISPLAYNAME]['value'] = $displayName;
877
+
878
+
879
+        try {
880
+            $this->saveUserSettings($user, $userData);
881
+            return new DataResponse([
882
+                'status' => 'success',
883
+                'data' => [
884
+                    'message' => $this->l10n->t('Your full name has been changed.'),
885
+                    'username' => $username,
886
+                    'displayName' => $displayName,
887
+                ],
888
+            ]);
889
+        } catch (ForbiddenException $e) {
890
+            return new DataResponse([
891
+                'status' => 'error',
892
+                'data' => [
893
+                    'message' => $e->getMessage(),
894
+                    'displayName' => $user->getDisplayName(),
895
+                ],
896
+            ]);
897
+        }
898
+    }
899
+
900
+    /**
901
+     * Set the mail address of a user
902
+     *
903
+     * @NoAdminRequired
904
+     * @NoSubadminRequired
905
+     * @PasswordConfirmationRequired
906
+     *
907
+     * @param string $id
908
+     * @param string $mailAddress
909
+     * @return DataResponse
910
+     */
911
+    public function setEMailAddress($id, $mailAddress) {
912
+        $user = $this->userManager->get($id);
913
+        if (!$this->isAdmin
914
+            && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)
915
+        ) {
916
+            return new DataResponse(
917
+                [
918
+                    'status' => 'error',
919
+                    'data' => [
920
+                        'message' => (string) $this->l10n->t('Forbidden')
921
+                    ]
922
+                ],
923
+                Http::STATUS_FORBIDDEN
924
+            );
925
+        }
926
+
927
+        if($mailAddress !== '' && !$this->mailer->validateMailAddress($mailAddress)) {
928
+            return new DataResponse(
929
+                [
930
+                    'status' => 'error',
931
+                    'data' => [
932
+                        'message' => (string) $this->l10n->t('Invalid mail address')
933
+                    ]
934
+                ],
935
+                Http::STATUS_UNPROCESSABLE_ENTITY
936
+            );
937
+        }
938
+
939
+        if (!$user) {
940
+            return new DataResponse(
941
+                [
942
+                    'status' => 'error',
943
+                    'data' => [
944
+                        'message' => (string) $this->l10n->t('Invalid user')
945
+                    ]
946
+                ],
947
+                Http::STATUS_UNPROCESSABLE_ENTITY
948
+            );
949
+        }
950
+        // this is the only permission a backend provides and is also used
951
+        // for the permission of setting a email address
952
+        if (!$user->canChangeDisplayName()) {
953
+            return new DataResponse(
954
+                [
955
+                    'status' => 'error',
956
+                    'data' => [
957
+                        'message' => (string) $this->l10n->t('Unable to change mail address')
958
+                    ]
959
+                ],
960
+                Http::STATUS_FORBIDDEN
961
+            );
962
+        }
963
+
964
+        $userData = $this->accountManager->getUser($user);
965
+        $userData[AccountManager::PROPERTY_EMAIL]['value'] = $mailAddress;
966
+
967
+        try {
968
+            $this->saveUserSettings($user, $userData);
969
+            return new DataResponse(
970
+                [
971
+                    'status' => 'success',
972
+                    'data' => [
973
+                        'username' => $id,
974
+                        'mailAddress' => $mailAddress,
975
+                        'message' => (string) $this->l10n->t('Email saved')
976
+                    ]
977
+                ],
978
+                Http::STATUS_OK
979
+            );
980
+        } catch (ForbiddenException $e) {
981
+            return new DataResponse([
982
+                'status' => 'error',
983
+                'data' => [
984
+                    'message' => $e->getMessage()
985
+                ],
986
+            ]);
987
+        }
988
+    }
989 989
 
990 990
 }
Please login to merge, or discard this patch.
Spacing   +39 added lines, -39 removed lines patch added patch discarded remove patch
@@ -157,7 +157,7 @@  discard block
 block discarded – undo
157 157
 
158 158
 		// check for encryption state - TODO see formatUserForIndex
159 159
 		$this->isEncryptionAppEnabled = $appManager->isEnabledForUser('encryption');
160
-		if($this->isEncryptionAppEnabled) {
160
+		if ($this->isEncryptionAppEnabled) {
161 161
 			// putting this directly in empty is possible in PHP 5.5+
162 162
 			$result = $config->getAppValue('encryption', 'recoveryAdminEnabled', 0);
163 163
 			$this->isRestoreEnabled = !empty($result);
@@ -197,7 +197,7 @@  discard block
 block discarded – undo
197 197
 		}
198 198
 
199 199
 		$subAdminGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($user);
200
-		foreach($subAdminGroups as $key => $subAdminGroup) {
200
+		foreach ($subAdminGroups as $key => $subAdminGroup) {
201 201
 			$subAdminGroups[$key] = $subAdminGroup->getGID();
202 202
 		}
203 203
 
@@ -255,11 +255,11 @@  discard block
 block discarded – undo
255 255
 	 */
256 256
 	public function index($offset = 0, $limit = 10, $gid = '', $pattern = '', $backend = '') {
257 257
 		// Remove backends
258
-		if(!empty($backend)) {
258
+		if (!empty($backend)) {
259 259
 			$activeBackends = $this->userManager->getBackends();
260 260
 			$this->userManager->clearBackends();
261
-			foreach($activeBackends as $singleActiveBackend) {
262
-				if($backend === get_class($singleActiveBackend)) {
261
+			foreach ($activeBackends as $singleActiveBackend) {
262
+				if ($backend === get_class($singleActiveBackend)) {
263 263
 					$this->userManager->registerBackend($singleActiveBackend);
264 264
 					break;
265 265
 				}
@@ -268,14 +268,14 @@  discard block
 block discarded – undo
268 268
 
269 269
 		$users = [];
270 270
 		if ($this->isAdmin) {
271
-			if($gid !== '' && $gid !== '_disabledUsers') {
271
+			if ($gid !== '' && $gid !== '_disabledUsers') {
272 272
 				$batch = $this->getUsersForUID($this->groupManager->displayNamesInGroup($gid, $pattern, $limit, $offset));
273 273
 			} else {
274 274
 				$batch = $this->userManager->search($pattern, $limit, $offset);
275 275
 			}
276 276
 
277 277
 			foreach ($batch as $user) {
278
-				if( ($gid !== '_disabledUsers' && $user->isEnabled()) ||
278
+				if (($gid !== '_disabledUsers' && $user->isEnabled()) ||
279 279
 					($gid === '_disabledUsers' && !$user->isEnabled())
280 280
 				) {
281 281
 					$users[] = $this->formatUserForIndex($user);
@@ -292,17 +292,17 @@  discard block
 block discarded – undo
292 292
 			$subAdminOfGroups = $gids;
293 293
 
294 294
 			// Set the $gid parameter to an empty value if the subadmin has no rights to access a specific group
295
-			if($gid !== '' && $gid !== '_disabledUsers' && !in_array($gid, $subAdminOfGroups)) {
295
+			if ($gid !== '' && $gid !== '_disabledUsers' && !in_array($gid, $subAdminOfGroups)) {
296 296
 				$gid = '';
297 297
 			}
298 298
 
299 299
 			// Batch all groups the user is subadmin of when a group is specified
300 300
 			$batch = [];
301
-			if($gid === '') {
302
-				foreach($subAdminOfGroups as $group) {
301
+			if ($gid === '') {
302
+				foreach ($subAdminOfGroups as $group) {
303 303
 					$groupUsers = $this->groupManager->displayNamesInGroup($group, $pattern, $limit, $offset);
304 304
 
305
-					foreach($groupUsers as $uid => $displayName) {
305
+					foreach ($groupUsers as $uid => $displayName) {
306 306
 						$batch[$uid] = $displayName;
307 307
 					}
308 308
 				}
@@ -317,7 +317,7 @@  discard block
 block discarded – undo
317 317
 					$this->groupManager->getUserGroupIds($user),
318 318
 					$subAdminOfGroups
319 319
 				));
320
-				if( ($gid !== '_disabledUsers' && $user->isEnabled()) ||
320
+				if (($gid !== '_disabledUsers' && $user->isEnabled()) ||
321 321
 					($gid === '_disabledUsers' && !$user->isEnabled())
322 322
 				) {
323 323
 					$users[] = $this->formatUserForIndex($user, $userGroups);
@@ -338,11 +338,11 @@  discard block
 block discarded – undo
338 338
 	 * @param string $email
339 339
 	 * @return DataResponse
340 340
 	 */
341
-	public function create($username, $password, array $groups=[], $email='') {
342
-		if($email !== '' && !$this->mailer->validateMailAddress($email)) {
341
+	public function create($username, $password, array $groups = [], $email = '') {
342
+		if ($email !== '' && !$this->mailer->validateMailAddress($email)) {
343 343
 			return new DataResponse(
344 344
 				[
345
-					'message' => (string)$this->l10n->t('Invalid mail address')
345
+					'message' => (string) $this->l10n->t('Invalid mail address')
346 346
 				],
347 347
 				Http::STATUS_UNPROCESSABLE_ENTITY
348 348
 			);
@@ -354,7 +354,7 @@  discard block
 block discarded – undo
354 354
 			if (!empty($groups)) {
355 355
 				foreach ($groups as $key => $group) {
356 356
 					$groupObject = $this->groupManager->get($group);
357
-					if($groupObject === null) {
357
+					if ($groupObject === null) {
358 358
 						unset($groups[$key]);
359 359
 						continue;
360 360
 					}
@@ -378,7 +378,7 @@  discard block
 block discarded – undo
378 378
 		if ($this->userManager->userExists($username)) {
379 379
 			return new DataResponse(
380 380
 				[
381
-					'message' => (string)$this->l10n->t('A user with that name already exists.')
381
+					'message' => (string) $this->l10n->t('A user with that name already exists.')
382 382
 				],
383 383
 				Http::STATUS_CONFLICT
384 384
 			);
@@ -389,7 +389,7 @@  discard block
 block discarded – undo
389 389
 			if ($email === '') {
390 390
 				return new DataResponse(
391 391
 					[
392
-						'message' => (string)$this->l10n->t('To send a password link to the user an email address is required.')
392
+						'message' => (string) $this->l10n->t('To send a password link to the user an email address is required.')
393 393
 					],
394 394
 					Http::STATUS_UNPROCESSABLE_ENTITY
395 395
 				);
@@ -414,12 +414,12 @@  discard block
 block discarded – undo
414 414
 			);
415 415
 		}
416 416
 
417
-		if($user instanceof IUser) {
418
-			if($groups !== null) {
419
-				foreach($groups as $groupName) {
417
+		if ($user instanceof IUser) {
418
+			if ($groups !== null) {
419
+				foreach ($groups as $groupName) {
420 420
 					$group = $this->groupManager->get($groupName);
421 421
 
422
-					if(empty($group)) {
422
+					if (empty($group)) {
423 423
 						$group = $this->groupManager->createGroup($groupName);
424 424
 					}
425 425
 					$group->addUser($user);
@@ -428,13 +428,13 @@  discard block
 block discarded – undo
428 428
 			/**
429 429
 			 * Send new user mail only if a mail is set
430 430
 			 */
431
-			if($email !== '') {
431
+			if ($email !== '') {
432 432
 				$user->setEMailAddress($email);
433 433
 				try {
434 434
 					$emailTemplate = $this->newUserMailHelper->generateTemplate($user, $generatePasswordResetToken);
435 435
 					$this->newUserMailHelper->sendMail($user, $emailTemplate);
436
-				} catch(\Exception $e) {
437
-					$this->log->error("Can't send new user mail to $email: " . $e->getMessage(), ['app' => 'settings']);
436
+				} catch (\Exception $e) {
437
+					$this->log->error("Can't send new user mail to $email: ".$e->getMessage(), ['app' => 'settings']);
438 438
 				}
439 439
 			}
440 440
 			// fetch users groups
@@ -466,7 +466,7 @@  discard block
 block discarded – undo
466 466
 		$userId = $this->userSession->getUser()->getUID();
467 467
 		$user = $this->userManager->get($id);
468 468
 
469
-		if($userId === $id) {
469
+		if ($userId === $id) {
470 470
 			return new DataResponse(
471 471
 				[
472 472
 					'status' => 'error',
@@ -478,20 +478,20 @@  discard block
 block discarded – undo
478 478
 			);
479 479
 		}
480 480
 
481
-		if(!$this->isAdmin && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)) {
481
+		if (!$this->isAdmin && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)) {
482 482
 			return new DataResponse(
483 483
 				[
484 484
 					'status' => 'error',
485 485
 					'data' => [
486
-						'message' => (string)$this->l10n->t('Authentication error')
486
+						'message' => (string) $this->l10n->t('Authentication error')
487 487
 					]
488 488
 				],
489 489
 				Http::STATUS_FORBIDDEN
490 490
 			);
491 491
 		}
492 492
 
493
-		if($user) {
494
-			if($user->delete()) {
493
+		if ($user) {
494
+			if ($user->delete()) {
495 495
 				return new DataResponse(
496 496
 					[
497 497
 						'status' => 'success',
@@ -508,7 +508,7 @@  discard block
 block discarded – undo
508 508
 			[
509 509
 				'status' => 'error',
510 510
 				'data' => [
511
-					'message' => (string)$this->l10n->t('Unable to delete user.')
511
+					'message' => (string) $this->l10n->t('Unable to delete user.')
512 512
 				]
513 513
 			],
514 514
 			Http::STATUS_FORBIDDEN
@@ -523,8 +523,8 @@  discard block
 block discarded – undo
523 523
 	 * @return DataResponse
524 524
 	 */
525 525
 	public function setEnabled($id, $enabled) {
526
-		$enabled = (bool)$enabled;
527
-		if($enabled) {
526
+		$enabled = (bool) $enabled;
527
+		if ($enabled) {
528 528
 			$errorMsgGeneral = (string) $this->l10n->t('Error while enabling user.');
529 529
 		} else {
530 530
 			$errorMsgGeneral = (string) $this->l10n->t('Error while disabling user.');
@@ -544,7 +544,7 @@  discard block
 block discarded – undo
544 544
 			);
545 545
 		}
546 546
 
547
-		if($user) {
547
+		if ($user) {
548 548
 			if (!$this->isAdmin && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)) {
549 549
 				return new DataResponse(
550 550
 					[
@@ -602,11 +602,11 @@  discard block
 block discarded – undo
602 602
 
603 603
 		$accountData = $this->accountManager->getUser($user);
604 604
 		$cloudId = $user->getCloudId();
605
-		$message = "Use my Federated Cloud ID to share with me: " . $cloudId;
605
+		$message = "Use my Federated Cloud ID to share with me: ".$cloudId;
606 606
 		$signature = $this->signMessage($user, $message);
607 607
 
608
-		$code = $message . ' ' . $signature;
609
-		$codeMd5 = $message . ' ' . md5($signature);
608
+		$code = $message.' '.$signature;
609
+		$codeMd5 = $message.' '.md5($signature);
610 610
 
611 611
 		switch ($account) {
612 612
 			case 'verify-twitter':
@@ -823,7 +823,7 @@  discard block
 block discarded – undo
823 823
 
824 824
 			$uniqueUsers = [];
825 825
 			foreach ($groups as $group) {
826
-				foreach($group->getUsers() as $uid => $displayName) {
826
+				foreach ($group->getUsers() as $uid => $displayName) {
827 827
 					$uniqueUsers[$uid] = true;
828 828
 				}
829 829
 			}
@@ -924,7 +924,7 @@  discard block
 block discarded – undo
924 924
 			);
925 925
 		}
926 926
 
927
-		if($mailAddress !== '' && !$this->mailer->validateMailAddress($mailAddress)) {
927
+		if ($mailAddress !== '' && !$this->mailer->validateMailAddress($mailAddress)) {
928 928
 			return new DataResponse(
929 929
 				[
930 930
 					'status' => 'error',
Please login to merge, or discard this patch.