Completed
Pull Request — master (#7169)
by Morris
17:51 queued 04:21
created
settings/Controller/UsersController.php 1 patch
Indentation   +979 added lines, -979 removed lines patch added patch discarded remove patch
@@ -69,984 +69,984 @@
 block discarded – undo
69 69
  * @package OC\Settings\Controller
70 70
  */
71 71
 class UsersController extends Controller {
72
-	/** @var IL10N */
73
-	private $l10n;
74
-	/** @var IUserSession */
75
-	private $userSession;
76
-	/** @var bool */
77
-	private $isAdmin;
78
-	/** @var IUserManager */
79
-	private $userManager;
80
-	/** @var IGroupManager */
81
-	private $groupManager;
82
-	/** @var IConfig */
83
-	private $config;
84
-	/** @var ILogger */
85
-	private $log;
86
-	/** @var IMailer */
87
-	private $mailer;
88
-	/** @var bool contains the state of the encryption app */
89
-	private $isEncryptionAppEnabled;
90
-	/** @var bool contains the state of the admin recovery setting */
91
-	private $isRestoreEnabled = false;
92
-	/** @var IAppManager */
93
-	private $appManager;
94
-	/** @var IAvatarManager */
95
-	private $avatarManager;
96
-	/** @var AccountManager */
97
-	private $accountManager;
98
-	/** @var ISecureRandom */
99
-	private $secureRandom;
100
-	/** @var NewUserMailHelper */
101
-	private $newUserMailHelper;
102
-	/** @var ITimeFactory */
103
-	private $timeFactory;
104
-	/** @var ICrypto */
105
-	private $crypto;
106
-	/** @var Manager */
107
-	private $keyManager;
108
-	/** @var IJobList */
109
-	private $jobList;
110
-
111
-	/** @var IUserMountCache */
112
-	private $userMountCache;
113
-
114
-	/** @var IManager */
115
-	private $encryptionManager;
116
-
117
-
118
-	/**
119
-	 * @param string $appName
120
-	 * @param IRequest $request
121
-	 * @param IUserManager $userManager
122
-	 * @param IGroupManager $groupManager
123
-	 * @param IUserSession $userSession
124
-	 * @param IConfig $config
125
-	 * @param bool $isAdmin
126
-	 * @param IL10N $l10n
127
-	 * @param ILogger $log
128
-	 * @param IMailer $mailer
129
-	 * @param IURLGenerator $urlGenerator
130
-	 * @param IAppManager $appManager
131
-	 * @param IAvatarManager $avatarManager
132
-	 * @param AccountManager $accountManager
133
-	 * @param ISecureRandom $secureRandom
134
-	 * @param NewUserMailHelper $newUserMailHelper
135
-	 * @param ITimeFactory $timeFactory
136
-	 * @param ICrypto $crypto
137
-	 * @param Manager $keyManager
138
-	 * @param IJobList $jobList
139
-	 * @param IUserMountCache $userMountCache
140
-	 * @param IManager $encryptionManager
141
-	 */
142
-	public function __construct($appName,
143
-								IRequest $request,
144
-								IUserManager $userManager,
145
-								IGroupManager $groupManager,
146
-								IUserSession $userSession,
147
-								IConfig $config,
148
-								$isAdmin,
149
-								IL10N $l10n,
150
-								ILogger $log,
151
-								IMailer $mailer,
152
-								IURLGenerator $urlGenerator,
153
-								IAppManager $appManager,
154
-								IAvatarManager $avatarManager,
155
-								AccountManager $accountManager,
156
-								ISecureRandom $secureRandom,
157
-								NewUserMailHelper $newUserMailHelper,
158
-								ITimeFactory $timeFactory,
159
-								ICrypto $crypto,
160
-								Manager $keyManager,
161
-								IJobList $jobList,
162
-								IUserMountCache $userMountCache,
163
-								IManager $encryptionManager) {
164
-		parent::__construct($appName, $request);
165
-		$this->userManager = $userManager;
166
-		$this->groupManager = $groupManager;
167
-		$this->userSession = $userSession;
168
-		$this->config = $config;
169
-		$this->isAdmin = $isAdmin;
170
-		$this->l10n = $l10n;
171
-		$this->log = $log;
172
-		$this->mailer = $mailer;
173
-		$this->appManager = $appManager;
174
-		$this->avatarManager = $avatarManager;
175
-		$this->accountManager = $accountManager;
176
-		$this->secureRandom = $secureRandom;
177
-		$this->newUserMailHelper = $newUserMailHelper;
178
-		$this->timeFactory = $timeFactory;
179
-		$this->crypto = $crypto;
180
-		$this->keyManager = $keyManager;
181
-		$this->jobList = $jobList;
182
-		$this->userMountCache = $userMountCache;
183
-		$this->encryptionManager = $encryptionManager;
184
-
185
-		// check for encryption state - TODO see formatUserForIndex
186
-		$this->isEncryptionAppEnabled = $appManager->isEnabledForUser('encryption');
187
-		if ($this->isEncryptionAppEnabled) {
188
-			// putting this directly in empty is possible in PHP 5.5+
189
-			$result = $config->getAppValue('encryption', 'recoveryAdminEnabled', '0');
190
-			$this->isRestoreEnabled = !empty($result);
191
-		}
192
-	}
193
-
194
-	/**
195
-	 * @param IUser $user
196
-	 * @param array|null $userGroups
197
-	 * @return array
198
-	 */
199
-	private function formatUserForIndex(IUser $user, array $userGroups = null) {
200
-
201
-		// TODO: eliminate this encryption specific code below and somehow
202
-		// hook in additional user info from other apps
203
-
204
-		// recovery isn't possible if admin or user has it disabled and encryption
205
-		// is enabled - so we eliminate the else paths in the conditional tree
206
-		// below
207
-		$restorePossible = false;
208
-
209
-		if ($this->isEncryptionAppEnabled) {
210
-			if ($this->isRestoreEnabled) {
211
-				// check for the users recovery setting
212
-				$recoveryMode = $this->config->getUserValue($user->getUID(), 'encryption', 'recoveryEnabled', '0');
213
-				// method call inside empty is possible with PHP 5.5+
214
-				$recoveryModeEnabled = !empty($recoveryMode);
215
-				if ($recoveryModeEnabled) {
216
-					// user also has recovery mode enabled
217
-					$restorePossible = true;
218
-				}
219
-			} else {
220
-				$modules = $this->encryptionManager->getEncryptionModules();
221
-				$restorePossible = true;
222
-				foreach ($modules as $id => $module) {
223
-					/* @var IEncryptionModule $instance */
224
-					$instance = call_user_func($module['callback']);
225
-					if ($instance->needDetailedAccessList()) {
226
-						$restorePossible = false;
227
-						break;
228
-					}
229
-				}
230
-			}
231
-		} else {
232
-			// recovery is possible if encryption is disabled (plain files are
233
-			// available)
234
-			$restorePossible = true;
235
-		}
236
-
237
-		$subAdminGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($user);
238
-		foreach ($subAdminGroups as $key => $subAdminGroup) {
239
-			$subAdminGroups[$key] = $subAdminGroup->getGID();
240
-		}
241
-
242
-		$displayName = $user->getEMailAddress();
243
-		if (is_null($displayName)) {
244
-			$displayName = '';
245
-		}
246
-
247
-		$avatarAvailable = false;
248
-		try {
249
-			$avatarAvailable = $this->avatarManager->getAvatar($user->getUID())->exists();
250
-		} catch (\Exception $e) {
251
-			//No avatar yet
252
-		}
253
-
254
-		return [
255
-			'name' => $user->getUID(),
256
-			'displayname' => $user->getDisplayName(),
257
-			'groups' => (empty($userGroups)) ? $this->groupManager->getUserGroupIds($user) : $userGroups,
258
-			'subadmin' => $subAdminGroups,
259
-			'quota' => $user->getQuota(),
260
-			'quota_bytes' => Util::computerFileSize($user->getQuota()),
261
-			'storageLocation' => $user->getHome(),
262
-			'lastLogin' => $user->getLastLogin() * 1000,
263
-			'backend' => $user->getBackendClassName(),
264
-			'email' => $displayName,
265
-			'isRestoreDisabled' => !$restorePossible,
266
-			'isAvatarAvailable' => $avatarAvailable,
267
-			'isEnabled' => $user->isEnabled(),
268
-		];
269
-	}
270
-
271
-	/**
272
-	 * @param array $userIDs Array with schema [$uid => $displayName]
273
-	 * @return IUser[]
274
-	 */
275
-	private function getUsersForUID(array $userIDs) {
276
-		$users = [];
277
-		foreach ($userIDs as $uid => $displayName) {
278
-			$users[$uid] = $this->userManager->get($uid);
279
-		}
280
-		return $users;
281
-	}
282
-
283
-	/**
284
-	 * @NoAdminRequired
285
-	 *
286
-	 * @param int $offset
287
-	 * @param int $limit
288
-	 * @param string $gid GID to filter for
289
-	 * @param string $pattern Pattern to search for in the username
290
-	 * @param string $backend Backend to filter for (class-name)
291
-	 * @return DataResponse
292
-	 *
293
-	 * TODO: Tidy up and write unit tests - code is mainly static method calls
294
-	 */
295
-	public function index($offset = 0, $limit = 10, $gid = '', $pattern = '', $backend = '') {
296
-		// Remove backends
297
-		if (!empty($backend)) {
298
-			$activeBackends = $this->userManager->getBackends();
299
-			$this->userManager->clearBackends();
300
-			foreach ($activeBackends as $singleActiveBackend) {
301
-				if ($backend === get_class($singleActiveBackend)) {
302
-					$this->userManager->registerBackend($singleActiveBackend);
303
-					break;
304
-				}
305
-			}
306
-		}
307
-
308
-		$userObjects = [];
309
-		$users = [];
310
-		if ($this->isAdmin) {
311
-			if ($gid !== '' && $gid !== '_disabledUsers' && $gid !== '_everyone') {
312
-				$batch = $this->getUsersForUID($this->groupManager->displayNamesInGroup($gid, $pattern, $limit, $offset));
313
-			} else {
314
-				$batch = $this->userManager->search($pattern, $limit, $offset);
315
-			}
316
-
317
-			foreach ($batch as $user) {
318
-				if (($gid !== '_disabledUsers' && $user->isEnabled()) ||
319
-					($gid === '_disabledUsers' && !$user->isEnabled())
320
-				) {
321
-					$userObjects[] = $user;
322
-					$users[] = $this->formatUserForIndex($user);
323
-				}
324
-			}
325
-
326
-		} else {
327
-			$subAdminOfGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($this->userSession->getUser());
328
-			// New class returns IGroup[] so convert back
329
-			$gids = [];
330
-			foreach ($subAdminOfGroups as $group) {
331
-				$gids[] = $group->getGID();
332
-			}
333
-			$subAdminOfGroups = $gids;
334
-
335
-			// Set the $gid parameter to an empty value if the subadmin has no rights to access a specific group
336
-			if ($gid !== '' && $gid !== '_disabledUsers' && !in_array($gid, $subAdminOfGroups)) {
337
-				$gid = '';
338
-			}
339
-
340
-			// Batch all groups the user is subadmin of when a group is specified
341
-			$batch = [];
342
-			if ($gid === '') {
343
-				foreach ($subAdminOfGroups as $group) {
344
-					$groupUsers = $this->groupManager->displayNamesInGroup($group, $pattern, $limit, $offset);
345
-
346
-					foreach ($groupUsers as $uid => $displayName) {
347
-						$batch[$uid] = $displayName;
348
-					}
349
-				}
350
-			} else {
351
-				$batch = $this->groupManager->displayNamesInGroup($gid, $pattern, $limit, $offset);
352
-			}
353
-			$batch = $this->getUsersForUID($batch);
354
-
355
-			foreach ($batch as $user) {
356
-				// Only add the groups, this user is a subadmin of
357
-				$userGroups = array_values(array_intersect(
358
-					$this->groupManager->getUserGroupIds($user),
359
-					$subAdminOfGroups
360
-				));
361
-				if (($gid !== '_disabledUsers' && $user->isEnabled()) ||
362
-					($gid === '_disabledUsers' && !$user->isEnabled())
363
-				) {
364
-					$userObjects[] = $user;
365
-					$users[] = $this->formatUserForIndex($user, $userGroups);
366
-				}
367
-			}
368
-		}
369
-
370
-		$usedSpace = $this->userMountCache->getUsedSpaceForUsers($userObjects);
371
-
372
-		foreach ($users as &$userData) {
373
-			$userData['size'] = isset($usedSpace[$userData['name']]) ? $usedSpace[$userData['name']] : 0;
374
-		}
375
-
376
-		return new DataResponse($users);
377
-	}
378
-
379
-	/**
380
-	 * @NoAdminRequired
381
-	 * @PasswordConfirmationRequired
382
-	 *
383
-	 * @param string $username
384
-	 * @param string $password
385
-	 * @param array $groups
386
-	 * @param string $email
387
-	 * @return DataResponse
388
-	 */
389
-	public function create($username, $password, array $groups = [], $email = '') {
390
-		if ($email !== '' && !$this->mailer->validateMailAddress($email)) {
391
-			return new DataResponse(
392
-				[
393
-					'message' => (string)$this->l10n->t('Invalid mail address')
394
-				],
395
-				Http::STATUS_UNPROCESSABLE_ENTITY
396
-			);
397
-		}
398
-
399
-		$currentUser = $this->userSession->getUser();
400
-
401
-		if (!$this->isAdmin) {
402
-			if (!empty($groups)) {
403
-				foreach ($groups as $key => $group) {
404
-					$groupObject = $this->groupManager->get($group);
405
-					if ($groupObject === null) {
406
-						unset($groups[$key]);
407
-						continue;
408
-					}
409
-
410
-					if (!$this->groupManager->getSubAdmin()->isSubAdminofGroup($currentUser, $groupObject)) {
411
-						unset($groups[$key]);
412
-					}
413
-				}
414
-			}
415
-
416
-			if (empty($groups)) {
417
-				return new DataResponse(
418
-					[
419
-						'message' => $this->l10n->t('No valid group selected'),
420
-					],
421
-					Http::STATUS_FORBIDDEN
422
-				);
423
-			}
424
-		}
425
-
426
-		if ($this->userManager->userExists($username)) {
427
-			return new DataResponse(
428
-				[
429
-					'message' => (string)$this->l10n->t('A user with that name already exists.')
430
-				],
431
-				Http::STATUS_CONFLICT
432
-			);
433
-		}
434
-
435
-		$generatePasswordResetToken = false;
436
-		if ($password === '') {
437
-			if ($email === '') {
438
-				return new DataResponse(
439
-					[
440
-						'message' => (string)$this->l10n->t('To send a password link to the user an email address is required.')
441
-					],
442
-					Http::STATUS_UNPROCESSABLE_ENTITY
443
-				);
444
-			}
445
-
446
-			$password = $this->secureRandom->generate(30);
447
-			// Make sure we pass the password_policy
448
-			$password .= $this->secureRandom->generate(2, '$!.,;:-~+*[]{}()');
449
-			$generatePasswordResetToken = true;
450
-		}
451
-
452
-		try {
453
-			$user = $this->userManager->createUser($username, $password);
454
-		} catch (\Exception $exception) {
455
-			$message = $exception->getMessage();
456
-			if ($exception instanceof HintException && $exception->getHint()) {
457
-				$message = $exception->getHint();
458
-			}
459
-			if (!$message) {
460
-				$message = $this->l10n->t('Unable to create user.');
461
-			}
462
-			return new DataResponse(
463
-				[
464
-					'message' => (string)$message,
465
-				],
466
-				Http::STATUS_FORBIDDEN
467
-			);
468
-		}
469
-
470
-		if ($user instanceof IUser) {
471
-			if ($groups !== null) {
472
-				foreach ($groups as $groupName) {
473
-					$group = $this->groupManager->get($groupName);
474
-
475
-					if (empty($group)) {
476
-						$group = $this->groupManager->createGroup($groupName);
477
-					}
478
-					$group->addUser($user);
479
-				}
480
-			}
481
-			/**
482
-			 * Send new user mail only if a mail is set
483
-			 */
484
-			if ($email !== '') {
485
-				$user->setEMailAddress($email);
486
-				try {
487
-					$emailTemplate = $this->newUserMailHelper->generateTemplate($user, $generatePasswordResetToken);
488
-					$this->newUserMailHelper->sendMail($user, $emailTemplate);
489
-				} catch (\Exception $e) {
490
-					$this->log->error("Can't send new user mail to $email: " . $e->getMessage(), ['app' => 'settings']);
491
-				}
492
-			}
493
-			// fetch users groups
494
-			$userGroups = $this->groupManager->getUserGroupIds($user);
495
-
496
-			return new DataResponse(
497
-				$this->formatUserForIndex($user, $userGroups),
498
-				Http::STATUS_CREATED
499
-			);
500
-		}
501
-
502
-		return new DataResponse(
503
-			[
504
-				'message' => (string)$this->l10n->t('Unable to create user.')
505
-			],
506
-			Http::STATUS_FORBIDDEN
507
-		);
508
-
509
-	}
510
-
511
-	/**
512
-	 * @NoAdminRequired
513
-	 * @PasswordConfirmationRequired
514
-	 *
515
-	 * @param string $id
516
-	 * @return DataResponse
517
-	 */
518
-	public function destroy($id) {
519
-		$userId = $this->userSession->getUser()->getUID();
520
-		$user = $this->userManager->get($id);
521
-
522
-		if ($userId === $id) {
523
-			return new DataResponse(
524
-				[
525
-					'status' => 'error',
526
-					'data' => [
527
-						'message' => (string)$this->l10n->t('Unable to delete user.')
528
-					]
529
-				],
530
-				Http::STATUS_FORBIDDEN
531
-			);
532
-		}
533
-
534
-		if (!$this->isAdmin && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)) {
535
-			return new DataResponse(
536
-				[
537
-					'status' => 'error',
538
-					'data' => [
539
-						'message' => (string)$this->l10n->t('Authentication error')
540
-					]
541
-				],
542
-				Http::STATUS_FORBIDDEN
543
-			);
544
-		}
545
-
546
-		if ($user) {
547
-			if ($user->delete()) {
548
-				return new DataResponse(
549
-					[
550
-						'status' => 'success',
551
-						'data' => [
552
-							'username' => $id
553
-						]
554
-					],
555
-					Http::STATUS_NO_CONTENT
556
-				);
557
-			}
558
-		}
559
-
560
-		return new DataResponse(
561
-			[
562
-				'status' => 'error',
563
-				'data' => [
564
-					'message' => (string)$this->l10n->t('Unable to delete user.')
565
-				]
566
-			],
567
-			Http::STATUS_FORBIDDEN
568
-		);
569
-	}
570
-
571
-	/**
572
-	 * @NoAdminRequired
573
-	 *
574
-	 * @param string $id
575
-	 * @param int $enabled
576
-	 * @return DataResponse
577
-	 */
578
-	public function setEnabled($id, $enabled) {
579
-		$enabled = (bool)$enabled;
580
-		if ($enabled) {
581
-			$errorMsgGeneral = (string)$this->l10n->t('Error while enabling user.');
582
-		} else {
583
-			$errorMsgGeneral = (string)$this->l10n->t('Error while disabling user.');
584
-		}
585
-
586
-		$userId = $this->userSession->getUser()->getUID();
587
-		$user = $this->userManager->get($id);
588
-
589
-		if ($userId === $id) {
590
-			return new DataResponse(
591
-				[
592
-					'status' => 'error',
593
-					'data' => [
594
-						'message' => $errorMsgGeneral
595
-					]
596
-				], Http::STATUS_FORBIDDEN
597
-			);
598
-		}
599
-
600
-		if ($user) {
601
-			if (!$this->isAdmin && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)) {
602
-				return new DataResponse(
603
-					[
604
-						'status' => 'error',
605
-						'data' => [
606
-							'message' => (string)$this->l10n->t('Authentication error')
607
-						]
608
-					],
609
-					Http::STATUS_FORBIDDEN
610
-				);
611
-			}
612
-
613
-			$user->setEnabled($enabled);
614
-			return new DataResponse(
615
-				[
616
-					'status' => 'success',
617
-					'data' => [
618
-						'username' => $id,
619
-						'enabled' => $enabled
620
-					]
621
-				]
622
-			);
623
-		} else {
624
-			return new DataResponse(
625
-				[
626
-					'status' => 'error',
627
-					'data' => [
628
-						'message' => $errorMsgGeneral
629
-					]
630
-				],
631
-				Http::STATUS_FORBIDDEN
632
-			);
633
-		}
634
-
635
-	}
636
-
637
-	/**
638
-	 * Set the mail address of a user
639
-	 *
640
-	 * @NoAdminRequired
641
-	 * @NoSubadminRequired
642
-	 * @PasswordConfirmationRequired
643
-	 *
644
-	 * @param string $account
645
-	 * @param bool $onlyVerificationCode only return verification code without updating the data
646
-	 * @return DataResponse
647
-	 */
648
-	public function getVerificationCode($account, $onlyVerificationCode) {
649
-
650
-		$user = $this->userSession->getUser();
651
-
652
-		if ($user === null) {
653
-			return new DataResponse([], Http::STATUS_BAD_REQUEST);
654
-		}
655
-
656
-		$accountData = $this->accountManager->getUser($user);
657
-		$cloudId = $user->getCloudId();
658
-		$message = "Use my Federated Cloud ID to share with me: " . $cloudId;
659
-		$signature = $this->signMessage($user, $message);
660
-
661
-		$code = $message . ' ' . $signature;
662
-		$codeMd5 = $message . ' ' . md5($signature);
663
-
664
-		switch ($account) {
665
-			case 'verify-twitter':
666
-				$accountData[AccountManager::PROPERTY_TWITTER]['verified'] = AccountManager::VERIFICATION_IN_PROGRESS;
667
-				$msg = $this->l10n->t('In order to verify your Twitter account, post the following tweet on Twitter (please make sure to post it without any line breaks):');
668
-				$code = $codeMd5;
669
-				$type = AccountManager::PROPERTY_TWITTER;
670
-				$data = $accountData[AccountManager::PROPERTY_TWITTER]['value'];
671
-				$accountData[AccountManager::PROPERTY_TWITTER]['signature'] = $signature;
672
-				break;
673
-			case 'verify-website':
674
-				$accountData[AccountManager::PROPERTY_WEBSITE]['verified'] = AccountManager::VERIFICATION_IN_PROGRESS;
675
-				$msg = $this->l10n->t('In order to verify your Website, store the following content in your web-root at \'.well-known/CloudIdVerificationCode.txt\' (please make sure that the complete text is in one line):');
676
-				$type = AccountManager::PROPERTY_WEBSITE;
677
-				$data = $accountData[AccountManager::PROPERTY_WEBSITE]['value'];
678
-				$accountData[AccountManager::PROPERTY_WEBSITE]['signature'] = $signature;
679
-				break;
680
-			default:
681
-				return new DataResponse([], Http::STATUS_BAD_REQUEST);
682
-		}
683
-
684
-		if ($onlyVerificationCode === false) {
685
-			$this->accountManager->updateUser($user, $accountData);
686
-
687
-			$this->jobList->add('OC\Settings\BackgroundJobs\VerifyUserData',
688
-				[
689
-					'verificationCode' => $code,
690
-					'data' => $data,
691
-					'type' => $type,
692
-					'uid' => $user->getUID(),
693
-					'try' => 0,
694
-					'lastRun' => $this->getCurrentTime()
695
-				]
696
-			);
697
-		}
698
-
699
-		return new DataResponse(['msg' => $msg, 'code' => $code]);
700
-	}
701
-
702
-	/**
703
-	 * get current timestamp
704
-	 *
705
-	 * @return int
706
-	 */
707
-	protected function getCurrentTime() {
708
-		return time();
709
-	}
710
-
711
-	/**
712
-	 * sign message with users private key
713
-	 *
714
-	 * @param IUser $user
715
-	 * @param string $message
716
-	 *
717
-	 * @return string base64 encoded signature
718
-	 */
719
-	protected function signMessage(IUser $user, $message) {
720
-		$privateKey = $this->keyManager->getKey($user)->getPrivate();
721
-		openssl_sign(json_encode($message), $signature, $privateKey, OPENSSL_ALGO_SHA512);
722
-		$signatureBase64 = base64_encode($signature);
723
-
724
-		return $signatureBase64;
725
-	}
726
-
727
-	/**
728
-	 * @NoAdminRequired
729
-	 * @NoSubadminRequired
730
-	 * @PasswordConfirmationRequired
731
-	 *
732
-	 * @param string $avatarScope
733
-	 * @param string $displayname
734
-	 * @param string $displaynameScope
735
-	 * @param string $phone
736
-	 * @param string $phoneScope
737
-	 * @param string $email
738
-	 * @param string $emailScope
739
-	 * @param string $website
740
-	 * @param string $websiteScope
741
-	 * @param string $address
742
-	 * @param string $addressScope
743
-	 * @param string $twitter
744
-	 * @param string $twitterScope
745
-	 * @return DataResponse
746
-	 */
747
-	public function setUserSettings($avatarScope,
748
-									$displayname,
749
-									$displaynameScope,
750
-									$phone,
751
-									$phoneScope,
752
-									$email,
753
-									$emailScope,
754
-									$website,
755
-									$websiteScope,
756
-									$address,
757
-									$addressScope,
758
-									$twitter,
759
-									$twitterScope
760
-	) {
761
-
762
-		if (!empty($email) && !$this->mailer->validateMailAddress($email)) {
763
-			return new DataResponse(
764
-				[
765
-					'status' => 'error',
766
-					'data' => [
767
-						'message' => (string)$this->l10n->t('Invalid mail address')
768
-					]
769
-				],
770
-				Http::STATUS_UNPROCESSABLE_ENTITY
771
-			);
772
-		}
773
-
774
-		$user = $this->userSession->getUser();
775
-
776
-		$data = $this->accountManager->getUser($user);
777
-
778
-		$data[AccountManager::PROPERTY_AVATAR] = ['scope' => $avatarScope];
779
-		if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
780
-			$data[AccountManager::PROPERTY_DISPLAYNAME] = ['value' => $displayname, 'scope' => $displaynameScope];
781
-			$data[AccountManager::PROPERTY_EMAIL] = ['value' => $email, 'scope' => $emailScope];
782
-		}
783
-
784
-		if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
785
-			$federatedFileSharing = new \OCA\FederatedFileSharing\AppInfo\Application();
786
-			$shareProvider = $federatedFileSharing->getFederatedShareProvider();
787
-			if ($shareProvider->isLookupServerUploadEnabled()) {
788
-				$data[AccountManager::PROPERTY_WEBSITE] = ['value' => $website, 'scope' => $websiteScope];
789
-				$data[AccountManager::PROPERTY_ADDRESS] = ['value' => $address, 'scope' => $addressScope];
790
-				$data[AccountManager::PROPERTY_PHONE] = ['value' => $phone, 'scope' => $phoneScope];
791
-				$data[AccountManager::PROPERTY_TWITTER] = ['value' => $twitter, 'scope' => $twitterScope];
792
-			}
793
-		}
794
-
795
-		try {
796
-			$this->saveUserSettings($user, $data);
797
-			return new DataResponse(
798
-				[
799
-					'status' => 'success',
800
-					'data' => [
801
-						'userId' => $user->getUID(),
802
-						'avatarScope' => $data[AccountManager::PROPERTY_AVATAR]['scope'],
803
-						'displayname' => $data[AccountManager::PROPERTY_DISPLAYNAME]['value'],
804
-						'displaynameScope' => $data[AccountManager::PROPERTY_DISPLAYNAME]['scope'],
805
-						'email' => $data[AccountManager::PROPERTY_EMAIL]['value'],
806
-						'emailScope' => $data[AccountManager::PROPERTY_EMAIL]['scope'],
807
-						'website' => $data[AccountManager::PROPERTY_WEBSITE]['value'],
808
-						'websiteScope' => $data[AccountManager::PROPERTY_WEBSITE]['scope'],
809
-						'address' => $data[AccountManager::PROPERTY_ADDRESS]['value'],
810
-						'addressScope' => $data[AccountManager::PROPERTY_ADDRESS]['scope'],
811
-						'message' => (string)$this->l10n->t('Settings saved')
812
-					]
813
-				],
814
-				Http::STATUS_OK
815
-			);
816
-		} catch (ForbiddenException $e) {
817
-			return new DataResponse([
818
-				'status' => 'error',
819
-				'data' => [
820
-					'message' => $e->getMessage()
821
-				],
822
-			]);
823
-		}
824
-
825
-	}
826
-
827
-
828
-	/**
829
-	 * update account manager with new user data
830
-	 *
831
-	 * @param IUser $user
832
-	 * @param array $data
833
-	 * @throws ForbiddenException
834
-	 */
835
-	protected function saveUserSettings(IUser $user, $data) {
836
-
837
-		// keep the user back-end up-to-date with the latest display name and email
838
-		// address
839
-		$oldDisplayName = $user->getDisplayName();
840
-		$oldDisplayName = is_null($oldDisplayName) ? '' : $oldDisplayName;
841
-		if (isset($data[AccountManager::PROPERTY_DISPLAYNAME]['value'])
842
-			&& $oldDisplayName !== $data[AccountManager::PROPERTY_DISPLAYNAME]['value']
843
-		) {
844
-			$result = $user->setDisplayName($data[AccountManager::PROPERTY_DISPLAYNAME]['value']);
845
-			if ($result === false) {
846
-				throw new ForbiddenException($this->l10n->t('Unable to change full name'));
847
-			}
848
-		}
849
-
850
-		$oldEmailAddress = $user->getEMailAddress();
851
-		$oldEmailAddress = is_null($oldEmailAddress) ? '' : $oldEmailAddress;
852
-		if (isset($data[AccountManager::PROPERTY_EMAIL]['value'])
853
-			&& $oldEmailAddress !== $data[AccountManager::PROPERTY_EMAIL]['value']
854
-		) {
855
-			// this is the only permission a backend provides and is also used
856
-			// for the permission of setting a email address
857
-			if (!$user->canChangeDisplayName()) {
858
-				throw new ForbiddenException($this->l10n->t('Unable to change email address'));
859
-			}
860
-			$user->setEMailAddress($data[AccountManager::PROPERTY_EMAIL]['value']);
861
-		}
862
-
863
-		$this->accountManager->updateUser($user, $data);
864
-	}
865
-
866
-	/**
867
-	 * Count all unique users visible for the current admin/subadmin.
868
-	 *
869
-	 * @NoAdminRequired
870
-	 *
871
-	 * @return DataResponse
872
-	 */
873
-	public function stats() {
874
-		$userCount = 0;
875
-		if ($this->isAdmin) {
876
-			$countByBackend = $this->userManager->countUsers();
877
-
878
-			if (!empty($countByBackend)) {
879
-				foreach ($countByBackend as $count) {
880
-					$userCount += $count;
881
-				}
882
-			}
883
-		} else {
884
-			$groups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($this->userSession->getUser());
885
-
886
-			$uniqueUsers = [];
887
-			foreach ($groups as $group) {
888
-				foreach ($group->getUsers() as $uid => $displayName) {
889
-					$uniqueUsers[$uid] = true;
890
-				}
891
-			}
892
-
893
-			$userCount = count($uniqueUsers);
894
-		}
895
-
896
-		return new DataResponse(
897
-			[
898
-				'totalUsers' => $userCount
899
-			]
900
-		);
901
-	}
902
-
903
-
904
-	/**
905
-	 * Set the displayName of a user
906
-	 *
907
-	 * @NoAdminRequired
908
-	 * @NoSubadminRequired
909
-	 * @PasswordConfirmationRequired
910
-	 * @todo merge into saveUserSettings
911
-	 *
912
-	 * @param string $username
913
-	 * @param string $displayName
914
-	 * @return DataResponse
915
-	 */
916
-	public function setDisplayName($username, $displayName) {
917
-		$currentUser = $this->userSession->getUser();
918
-		$user = $this->userManager->get($username);
919
-
920
-		if ($user === null ||
921
-			!$user->canChangeDisplayName() ||
922
-			(
923
-				!$this->groupManager->isAdmin($currentUser->getUID()) &&
924
-				!$this->groupManager->getSubAdmin()->isUserAccessible($currentUser, $user) &&
925
-				$currentUser->getUID() !== $username
926
-
927
-			)
928
-		) {
929
-			return new DataResponse([
930
-				'status' => 'error',
931
-				'data' => [
932
-					'message' => $this->l10n->t('Authentication error'),
933
-				],
934
-			]);
935
-		}
936
-
937
-		$userData = $this->accountManager->getUser($user);
938
-		$userData[AccountManager::PROPERTY_DISPLAYNAME]['value'] = $displayName;
939
-
940
-
941
-		try {
942
-			$this->saveUserSettings($user, $userData);
943
-			return new DataResponse([
944
-				'status' => 'success',
945
-				'data' => [
946
-					'message' => $this->l10n->t('Your full name has been changed.'),
947
-					'username' => $username,
948
-					'displayName' => $displayName,
949
-				],
950
-			]);
951
-		} catch (ForbiddenException $e) {
952
-			return new DataResponse([
953
-				'status' => 'error',
954
-				'data' => [
955
-					'message' => $e->getMessage(),
956
-					'displayName' => $user->getDisplayName(),
957
-				],
958
-			]);
959
-		}
960
-	}
961
-
962
-	/**
963
-	 * Set the mail address of a user
964
-	 *
965
-	 * @NoAdminRequired
966
-	 * @NoSubadminRequired
967
-	 * @PasswordConfirmationRequired
968
-	 *
969
-	 * @param string $id
970
-	 * @param string $mailAddress
971
-	 * @return DataResponse
972
-	 */
973
-	public function setEMailAddress($id, $mailAddress) {
974
-		$user = $this->userManager->get($id);
975
-		if (!$this->isAdmin
976
-			&& !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)
977
-		) {
978
-			return new DataResponse(
979
-				[
980
-					'status' => 'error',
981
-					'data' => [
982
-						'message' => (string)$this->l10n->t('Forbidden')
983
-					]
984
-				],
985
-				Http::STATUS_FORBIDDEN
986
-			);
987
-		}
988
-
989
-		if ($mailAddress !== '' && !$this->mailer->validateMailAddress($mailAddress)) {
990
-			return new DataResponse(
991
-				[
992
-					'status' => 'error',
993
-					'data' => [
994
-						'message' => (string)$this->l10n->t('Invalid mail address')
995
-					]
996
-				],
997
-				Http::STATUS_UNPROCESSABLE_ENTITY
998
-			);
999
-		}
1000
-
1001
-		if (!$user) {
1002
-			return new DataResponse(
1003
-				[
1004
-					'status' => 'error',
1005
-					'data' => [
1006
-						'message' => (string)$this->l10n->t('Invalid user')
1007
-					]
1008
-				],
1009
-				Http::STATUS_UNPROCESSABLE_ENTITY
1010
-			);
1011
-		}
1012
-		// this is the only permission a backend provides and is also used
1013
-		// for the permission of setting a email address
1014
-		if (!$user->canChangeDisplayName()) {
1015
-			return new DataResponse(
1016
-				[
1017
-					'status' => 'error',
1018
-					'data' => [
1019
-						'message' => (string)$this->l10n->t('Unable to change mail address')
1020
-					]
1021
-				],
1022
-				Http::STATUS_FORBIDDEN
1023
-			);
1024
-		}
1025
-
1026
-		$userData = $this->accountManager->getUser($user);
1027
-		$userData[AccountManager::PROPERTY_EMAIL]['value'] = $mailAddress;
1028
-
1029
-		try {
1030
-			$this->saveUserSettings($user, $userData);
1031
-			return new DataResponse(
1032
-				[
1033
-					'status' => 'success',
1034
-					'data' => [
1035
-						'username' => $id,
1036
-						'mailAddress' => $mailAddress,
1037
-						'message' => (string)$this->l10n->t('Email saved')
1038
-					]
1039
-				],
1040
-				Http::STATUS_OK
1041
-			);
1042
-		} catch (ForbiddenException $e) {
1043
-			return new DataResponse([
1044
-				'status' => 'error',
1045
-				'data' => [
1046
-					'message' => $e->getMessage()
1047
-				],
1048
-			]);
1049
-		}
1050
-	}
72
+    /** @var IL10N */
73
+    private $l10n;
74
+    /** @var IUserSession */
75
+    private $userSession;
76
+    /** @var bool */
77
+    private $isAdmin;
78
+    /** @var IUserManager */
79
+    private $userManager;
80
+    /** @var IGroupManager */
81
+    private $groupManager;
82
+    /** @var IConfig */
83
+    private $config;
84
+    /** @var ILogger */
85
+    private $log;
86
+    /** @var IMailer */
87
+    private $mailer;
88
+    /** @var bool contains the state of the encryption app */
89
+    private $isEncryptionAppEnabled;
90
+    /** @var bool contains the state of the admin recovery setting */
91
+    private $isRestoreEnabled = false;
92
+    /** @var IAppManager */
93
+    private $appManager;
94
+    /** @var IAvatarManager */
95
+    private $avatarManager;
96
+    /** @var AccountManager */
97
+    private $accountManager;
98
+    /** @var ISecureRandom */
99
+    private $secureRandom;
100
+    /** @var NewUserMailHelper */
101
+    private $newUserMailHelper;
102
+    /** @var ITimeFactory */
103
+    private $timeFactory;
104
+    /** @var ICrypto */
105
+    private $crypto;
106
+    /** @var Manager */
107
+    private $keyManager;
108
+    /** @var IJobList */
109
+    private $jobList;
110
+
111
+    /** @var IUserMountCache */
112
+    private $userMountCache;
113
+
114
+    /** @var IManager */
115
+    private $encryptionManager;
116
+
117
+
118
+    /**
119
+     * @param string $appName
120
+     * @param IRequest $request
121
+     * @param IUserManager $userManager
122
+     * @param IGroupManager $groupManager
123
+     * @param IUserSession $userSession
124
+     * @param IConfig $config
125
+     * @param bool $isAdmin
126
+     * @param IL10N $l10n
127
+     * @param ILogger $log
128
+     * @param IMailer $mailer
129
+     * @param IURLGenerator $urlGenerator
130
+     * @param IAppManager $appManager
131
+     * @param IAvatarManager $avatarManager
132
+     * @param AccountManager $accountManager
133
+     * @param ISecureRandom $secureRandom
134
+     * @param NewUserMailHelper $newUserMailHelper
135
+     * @param ITimeFactory $timeFactory
136
+     * @param ICrypto $crypto
137
+     * @param Manager $keyManager
138
+     * @param IJobList $jobList
139
+     * @param IUserMountCache $userMountCache
140
+     * @param IManager $encryptionManager
141
+     */
142
+    public function __construct($appName,
143
+                                IRequest $request,
144
+                                IUserManager $userManager,
145
+                                IGroupManager $groupManager,
146
+                                IUserSession $userSession,
147
+                                IConfig $config,
148
+                                $isAdmin,
149
+                                IL10N $l10n,
150
+                                ILogger $log,
151
+                                IMailer $mailer,
152
+                                IURLGenerator $urlGenerator,
153
+                                IAppManager $appManager,
154
+                                IAvatarManager $avatarManager,
155
+                                AccountManager $accountManager,
156
+                                ISecureRandom $secureRandom,
157
+                                NewUserMailHelper $newUserMailHelper,
158
+                                ITimeFactory $timeFactory,
159
+                                ICrypto $crypto,
160
+                                Manager $keyManager,
161
+                                IJobList $jobList,
162
+                                IUserMountCache $userMountCache,
163
+                                IManager $encryptionManager) {
164
+        parent::__construct($appName, $request);
165
+        $this->userManager = $userManager;
166
+        $this->groupManager = $groupManager;
167
+        $this->userSession = $userSession;
168
+        $this->config = $config;
169
+        $this->isAdmin = $isAdmin;
170
+        $this->l10n = $l10n;
171
+        $this->log = $log;
172
+        $this->mailer = $mailer;
173
+        $this->appManager = $appManager;
174
+        $this->avatarManager = $avatarManager;
175
+        $this->accountManager = $accountManager;
176
+        $this->secureRandom = $secureRandom;
177
+        $this->newUserMailHelper = $newUserMailHelper;
178
+        $this->timeFactory = $timeFactory;
179
+        $this->crypto = $crypto;
180
+        $this->keyManager = $keyManager;
181
+        $this->jobList = $jobList;
182
+        $this->userMountCache = $userMountCache;
183
+        $this->encryptionManager = $encryptionManager;
184
+
185
+        // check for encryption state - TODO see formatUserForIndex
186
+        $this->isEncryptionAppEnabled = $appManager->isEnabledForUser('encryption');
187
+        if ($this->isEncryptionAppEnabled) {
188
+            // putting this directly in empty is possible in PHP 5.5+
189
+            $result = $config->getAppValue('encryption', 'recoveryAdminEnabled', '0');
190
+            $this->isRestoreEnabled = !empty($result);
191
+        }
192
+    }
193
+
194
+    /**
195
+     * @param IUser $user
196
+     * @param array|null $userGroups
197
+     * @return array
198
+     */
199
+    private function formatUserForIndex(IUser $user, array $userGroups = null) {
200
+
201
+        // TODO: eliminate this encryption specific code below and somehow
202
+        // hook in additional user info from other apps
203
+
204
+        // recovery isn't possible if admin or user has it disabled and encryption
205
+        // is enabled - so we eliminate the else paths in the conditional tree
206
+        // below
207
+        $restorePossible = false;
208
+
209
+        if ($this->isEncryptionAppEnabled) {
210
+            if ($this->isRestoreEnabled) {
211
+                // check for the users recovery setting
212
+                $recoveryMode = $this->config->getUserValue($user->getUID(), 'encryption', 'recoveryEnabled', '0');
213
+                // method call inside empty is possible with PHP 5.5+
214
+                $recoveryModeEnabled = !empty($recoveryMode);
215
+                if ($recoveryModeEnabled) {
216
+                    // user also has recovery mode enabled
217
+                    $restorePossible = true;
218
+                }
219
+            } else {
220
+                $modules = $this->encryptionManager->getEncryptionModules();
221
+                $restorePossible = true;
222
+                foreach ($modules as $id => $module) {
223
+                    /* @var IEncryptionModule $instance */
224
+                    $instance = call_user_func($module['callback']);
225
+                    if ($instance->needDetailedAccessList()) {
226
+                        $restorePossible = false;
227
+                        break;
228
+                    }
229
+                }
230
+            }
231
+        } else {
232
+            // recovery is possible if encryption is disabled (plain files are
233
+            // available)
234
+            $restorePossible = true;
235
+        }
236
+
237
+        $subAdminGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($user);
238
+        foreach ($subAdminGroups as $key => $subAdminGroup) {
239
+            $subAdminGroups[$key] = $subAdminGroup->getGID();
240
+        }
241
+
242
+        $displayName = $user->getEMailAddress();
243
+        if (is_null($displayName)) {
244
+            $displayName = '';
245
+        }
246
+
247
+        $avatarAvailable = false;
248
+        try {
249
+            $avatarAvailable = $this->avatarManager->getAvatar($user->getUID())->exists();
250
+        } catch (\Exception $e) {
251
+            //No avatar yet
252
+        }
253
+
254
+        return [
255
+            'name' => $user->getUID(),
256
+            'displayname' => $user->getDisplayName(),
257
+            'groups' => (empty($userGroups)) ? $this->groupManager->getUserGroupIds($user) : $userGroups,
258
+            'subadmin' => $subAdminGroups,
259
+            'quota' => $user->getQuota(),
260
+            'quota_bytes' => Util::computerFileSize($user->getQuota()),
261
+            'storageLocation' => $user->getHome(),
262
+            'lastLogin' => $user->getLastLogin() * 1000,
263
+            'backend' => $user->getBackendClassName(),
264
+            'email' => $displayName,
265
+            'isRestoreDisabled' => !$restorePossible,
266
+            'isAvatarAvailable' => $avatarAvailable,
267
+            'isEnabled' => $user->isEnabled(),
268
+        ];
269
+    }
270
+
271
+    /**
272
+     * @param array $userIDs Array with schema [$uid => $displayName]
273
+     * @return IUser[]
274
+     */
275
+    private function getUsersForUID(array $userIDs) {
276
+        $users = [];
277
+        foreach ($userIDs as $uid => $displayName) {
278
+            $users[$uid] = $this->userManager->get($uid);
279
+        }
280
+        return $users;
281
+    }
282
+
283
+    /**
284
+     * @NoAdminRequired
285
+     *
286
+     * @param int $offset
287
+     * @param int $limit
288
+     * @param string $gid GID to filter for
289
+     * @param string $pattern Pattern to search for in the username
290
+     * @param string $backend Backend to filter for (class-name)
291
+     * @return DataResponse
292
+     *
293
+     * TODO: Tidy up and write unit tests - code is mainly static method calls
294
+     */
295
+    public function index($offset = 0, $limit = 10, $gid = '', $pattern = '', $backend = '') {
296
+        // Remove backends
297
+        if (!empty($backend)) {
298
+            $activeBackends = $this->userManager->getBackends();
299
+            $this->userManager->clearBackends();
300
+            foreach ($activeBackends as $singleActiveBackend) {
301
+                if ($backend === get_class($singleActiveBackend)) {
302
+                    $this->userManager->registerBackend($singleActiveBackend);
303
+                    break;
304
+                }
305
+            }
306
+        }
307
+
308
+        $userObjects = [];
309
+        $users = [];
310
+        if ($this->isAdmin) {
311
+            if ($gid !== '' && $gid !== '_disabledUsers' && $gid !== '_everyone') {
312
+                $batch = $this->getUsersForUID($this->groupManager->displayNamesInGroup($gid, $pattern, $limit, $offset));
313
+            } else {
314
+                $batch = $this->userManager->search($pattern, $limit, $offset);
315
+            }
316
+
317
+            foreach ($batch as $user) {
318
+                if (($gid !== '_disabledUsers' && $user->isEnabled()) ||
319
+                    ($gid === '_disabledUsers' && !$user->isEnabled())
320
+                ) {
321
+                    $userObjects[] = $user;
322
+                    $users[] = $this->formatUserForIndex($user);
323
+                }
324
+            }
325
+
326
+        } else {
327
+            $subAdminOfGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($this->userSession->getUser());
328
+            // New class returns IGroup[] so convert back
329
+            $gids = [];
330
+            foreach ($subAdminOfGroups as $group) {
331
+                $gids[] = $group->getGID();
332
+            }
333
+            $subAdminOfGroups = $gids;
334
+
335
+            // Set the $gid parameter to an empty value if the subadmin has no rights to access a specific group
336
+            if ($gid !== '' && $gid !== '_disabledUsers' && !in_array($gid, $subAdminOfGroups)) {
337
+                $gid = '';
338
+            }
339
+
340
+            // Batch all groups the user is subadmin of when a group is specified
341
+            $batch = [];
342
+            if ($gid === '') {
343
+                foreach ($subAdminOfGroups as $group) {
344
+                    $groupUsers = $this->groupManager->displayNamesInGroup($group, $pattern, $limit, $offset);
345
+
346
+                    foreach ($groupUsers as $uid => $displayName) {
347
+                        $batch[$uid] = $displayName;
348
+                    }
349
+                }
350
+            } else {
351
+                $batch = $this->groupManager->displayNamesInGroup($gid, $pattern, $limit, $offset);
352
+            }
353
+            $batch = $this->getUsersForUID($batch);
354
+
355
+            foreach ($batch as $user) {
356
+                // Only add the groups, this user is a subadmin of
357
+                $userGroups = array_values(array_intersect(
358
+                    $this->groupManager->getUserGroupIds($user),
359
+                    $subAdminOfGroups
360
+                ));
361
+                if (($gid !== '_disabledUsers' && $user->isEnabled()) ||
362
+                    ($gid === '_disabledUsers' && !$user->isEnabled())
363
+                ) {
364
+                    $userObjects[] = $user;
365
+                    $users[] = $this->formatUserForIndex($user, $userGroups);
366
+                }
367
+            }
368
+        }
369
+
370
+        $usedSpace = $this->userMountCache->getUsedSpaceForUsers($userObjects);
371
+
372
+        foreach ($users as &$userData) {
373
+            $userData['size'] = isset($usedSpace[$userData['name']]) ? $usedSpace[$userData['name']] : 0;
374
+        }
375
+
376
+        return new DataResponse($users);
377
+    }
378
+
379
+    /**
380
+     * @NoAdminRequired
381
+     * @PasswordConfirmationRequired
382
+     *
383
+     * @param string $username
384
+     * @param string $password
385
+     * @param array $groups
386
+     * @param string $email
387
+     * @return DataResponse
388
+     */
389
+    public function create($username, $password, array $groups = [], $email = '') {
390
+        if ($email !== '' && !$this->mailer->validateMailAddress($email)) {
391
+            return new DataResponse(
392
+                [
393
+                    'message' => (string)$this->l10n->t('Invalid mail address')
394
+                ],
395
+                Http::STATUS_UNPROCESSABLE_ENTITY
396
+            );
397
+        }
398
+
399
+        $currentUser = $this->userSession->getUser();
400
+
401
+        if (!$this->isAdmin) {
402
+            if (!empty($groups)) {
403
+                foreach ($groups as $key => $group) {
404
+                    $groupObject = $this->groupManager->get($group);
405
+                    if ($groupObject === null) {
406
+                        unset($groups[$key]);
407
+                        continue;
408
+                    }
409
+
410
+                    if (!$this->groupManager->getSubAdmin()->isSubAdminofGroup($currentUser, $groupObject)) {
411
+                        unset($groups[$key]);
412
+                    }
413
+                }
414
+            }
415
+
416
+            if (empty($groups)) {
417
+                return new DataResponse(
418
+                    [
419
+                        'message' => $this->l10n->t('No valid group selected'),
420
+                    ],
421
+                    Http::STATUS_FORBIDDEN
422
+                );
423
+            }
424
+        }
425
+
426
+        if ($this->userManager->userExists($username)) {
427
+            return new DataResponse(
428
+                [
429
+                    'message' => (string)$this->l10n->t('A user with that name already exists.')
430
+                ],
431
+                Http::STATUS_CONFLICT
432
+            );
433
+        }
434
+
435
+        $generatePasswordResetToken = false;
436
+        if ($password === '') {
437
+            if ($email === '') {
438
+                return new DataResponse(
439
+                    [
440
+                        'message' => (string)$this->l10n->t('To send a password link to the user an email address is required.')
441
+                    ],
442
+                    Http::STATUS_UNPROCESSABLE_ENTITY
443
+                );
444
+            }
445
+
446
+            $password = $this->secureRandom->generate(30);
447
+            // Make sure we pass the password_policy
448
+            $password .= $this->secureRandom->generate(2, '$!.,;:-~+*[]{}()');
449
+            $generatePasswordResetToken = true;
450
+        }
451
+
452
+        try {
453
+            $user = $this->userManager->createUser($username, $password);
454
+        } catch (\Exception $exception) {
455
+            $message = $exception->getMessage();
456
+            if ($exception instanceof HintException && $exception->getHint()) {
457
+                $message = $exception->getHint();
458
+            }
459
+            if (!$message) {
460
+                $message = $this->l10n->t('Unable to create user.');
461
+            }
462
+            return new DataResponse(
463
+                [
464
+                    'message' => (string)$message,
465
+                ],
466
+                Http::STATUS_FORBIDDEN
467
+            );
468
+        }
469
+
470
+        if ($user instanceof IUser) {
471
+            if ($groups !== null) {
472
+                foreach ($groups as $groupName) {
473
+                    $group = $this->groupManager->get($groupName);
474
+
475
+                    if (empty($group)) {
476
+                        $group = $this->groupManager->createGroup($groupName);
477
+                    }
478
+                    $group->addUser($user);
479
+                }
480
+            }
481
+            /**
482
+             * Send new user mail only if a mail is set
483
+             */
484
+            if ($email !== '') {
485
+                $user->setEMailAddress($email);
486
+                try {
487
+                    $emailTemplate = $this->newUserMailHelper->generateTemplate($user, $generatePasswordResetToken);
488
+                    $this->newUserMailHelper->sendMail($user, $emailTemplate);
489
+                } catch (\Exception $e) {
490
+                    $this->log->error("Can't send new user mail to $email: " . $e->getMessage(), ['app' => 'settings']);
491
+                }
492
+            }
493
+            // fetch users groups
494
+            $userGroups = $this->groupManager->getUserGroupIds($user);
495
+
496
+            return new DataResponse(
497
+                $this->formatUserForIndex($user, $userGroups),
498
+                Http::STATUS_CREATED
499
+            );
500
+        }
501
+
502
+        return new DataResponse(
503
+            [
504
+                'message' => (string)$this->l10n->t('Unable to create user.')
505
+            ],
506
+            Http::STATUS_FORBIDDEN
507
+        );
508
+
509
+    }
510
+
511
+    /**
512
+     * @NoAdminRequired
513
+     * @PasswordConfirmationRequired
514
+     *
515
+     * @param string $id
516
+     * @return DataResponse
517
+     */
518
+    public function destroy($id) {
519
+        $userId = $this->userSession->getUser()->getUID();
520
+        $user = $this->userManager->get($id);
521
+
522
+        if ($userId === $id) {
523
+            return new DataResponse(
524
+                [
525
+                    'status' => 'error',
526
+                    'data' => [
527
+                        'message' => (string)$this->l10n->t('Unable to delete user.')
528
+                    ]
529
+                ],
530
+                Http::STATUS_FORBIDDEN
531
+            );
532
+        }
533
+
534
+        if (!$this->isAdmin && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)) {
535
+            return new DataResponse(
536
+                [
537
+                    'status' => 'error',
538
+                    'data' => [
539
+                        'message' => (string)$this->l10n->t('Authentication error')
540
+                    ]
541
+                ],
542
+                Http::STATUS_FORBIDDEN
543
+            );
544
+        }
545
+
546
+        if ($user) {
547
+            if ($user->delete()) {
548
+                return new DataResponse(
549
+                    [
550
+                        'status' => 'success',
551
+                        'data' => [
552
+                            'username' => $id
553
+                        ]
554
+                    ],
555
+                    Http::STATUS_NO_CONTENT
556
+                );
557
+            }
558
+        }
559
+
560
+        return new DataResponse(
561
+            [
562
+                'status' => 'error',
563
+                'data' => [
564
+                    'message' => (string)$this->l10n->t('Unable to delete user.')
565
+                ]
566
+            ],
567
+            Http::STATUS_FORBIDDEN
568
+        );
569
+    }
570
+
571
+    /**
572
+     * @NoAdminRequired
573
+     *
574
+     * @param string $id
575
+     * @param int $enabled
576
+     * @return DataResponse
577
+     */
578
+    public function setEnabled($id, $enabled) {
579
+        $enabled = (bool)$enabled;
580
+        if ($enabled) {
581
+            $errorMsgGeneral = (string)$this->l10n->t('Error while enabling user.');
582
+        } else {
583
+            $errorMsgGeneral = (string)$this->l10n->t('Error while disabling user.');
584
+        }
585
+
586
+        $userId = $this->userSession->getUser()->getUID();
587
+        $user = $this->userManager->get($id);
588
+
589
+        if ($userId === $id) {
590
+            return new DataResponse(
591
+                [
592
+                    'status' => 'error',
593
+                    'data' => [
594
+                        'message' => $errorMsgGeneral
595
+                    ]
596
+                ], Http::STATUS_FORBIDDEN
597
+            );
598
+        }
599
+
600
+        if ($user) {
601
+            if (!$this->isAdmin && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)) {
602
+                return new DataResponse(
603
+                    [
604
+                        'status' => 'error',
605
+                        'data' => [
606
+                            'message' => (string)$this->l10n->t('Authentication error')
607
+                        ]
608
+                    ],
609
+                    Http::STATUS_FORBIDDEN
610
+                );
611
+            }
612
+
613
+            $user->setEnabled($enabled);
614
+            return new DataResponse(
615
+                [
616
+                    'status' => 'success',
617
+                    'data' => [
618
+                        'username' => $id,
619
+                        'enabled' => $enabled
620
+                    ]
621
+                ]
622
+            );
623
+        } else {
624
+            return new DataResponse(
625
+                [
626
+                    'status' => 'error',
627
+                    'data' => [
628
+                        'message' => $errorMsgGeneral
629
+                    ]
630
+                ],
631
+                Http::STATUS_FORBIDDEN
632
+            );
633
+        }
634
+
635
+    }
636
+
637
+    /**
638
+     * Set the mail address of a user
639
+     *
640
+     * @NoAdminRequired
641
+     * @NoSubadminRequired
642
+     * @PasswordConfirmationRequired
643
+     *
644
+     * @param string $account
645
+     * @param bool $onlyVerificationCode only return verification code without updating the data
646
+     * @return DataResponse
647
+     */
648
+    public function getVerificationCode($account, $onlyVerificationCode) {
649
+
650
+        $user = $this->userSession->getUser();
651
+
652
+        if ($user === null) {
653
+            return new DataResponse([], Http::STATUS_BAD_REQUEST);
654
+        }
655
+
656
+        $accountData = $this->accountManager->getUser($user);
657
+        $cloudId = $user->getCloudId();
658
+        $message = "Use my Federated Cloud ID to share with me: " . $cloudId;
659
+        $signature = $this->signMessage($user, $message);
660
+
661
+        $code = $message . ' ' . $signature;
662
+        $codeMd5 = $message . ' ' . md5($signature);
663
+
664
+        switch ($account) {
665
+            case 'verify-twitter':
666
+                $accountData[AccountManager::PROPERTY_TWITTER]['verified'] = AccountManager::VERIFICATION_IN_PROGRESS;
667
+                $msg = $this->l10n->t('In order to verify your Twitter account, post the following tweet on Twitter (please make sure to post it without any line breaks):');
668
+                $code = $codeMd5;
669
+                $type = AccountManager::PROPERTY_TWITTER;
670
+                $data = $accountData[AccountManager::PROPERTY_TWITTER]['value'];
671
+                $accountData[AccountManager::PROPERTY_TWITTER]['signature'] = $signature;
672
+                break;
673
+            case 'verify-website':
674
+                $accountData[AccountManager::PROPERTY_WEBSITE]['verified'] = AccountManager::VERIFICATION_IN_PROGRESS;
675
+                $msg = $this->l10n->t('In order to verify your Website, store the following content in your web-root at \'.well-known/CloudIdVerificationCode.txt\' (please make sure that the complete text is in one line):');
676
+                $type = AccountManager::PROPERTY_WEBSITE;
677
+                $data = $accountData[AccountManager::PROPERTY_WEBSITE]['value'];
678
+                $accountData[AccountManager::PROPERTY_WEBSITE]['signature'] = $signature;
679
+                break;
680
+            default:
681
+                return new DataResponse([], Http::STATUS_BAD_REQUEST);
682
+        }
683
+
684
+        if ($onlyVerificationCode === false) {
685
+            $this->accountManager->updateUser($user, $accountData);
686
+
687
+            $this->jobList->add('OC\Settings\BackgroundJobs\VerifyUserData',
688
+                [
689
+                    'verificationCode' => $code,
690
+                    'data' => $data,
691
+                    'type' => $type,
692
+                    'uid' => $user->getUID(),
693
+                    'try' => 0,
694
+                    'lastRun' => $this->getCurrentTime()
695
+                ]
696
+            );
697
+        }
698
+
699
+        return new DataResponse(['msg' => $msg, 'code' => $code]);
700
+    }
701
+
702
+    /**
703
+     * get current timestamp
704
+     *
705
+     * @return int
706
+     */
707
+    protected function getCurrentTime() {
708
+        return time();
709
+    }
710
+
711
+    /**
712
+     * sign message with users private key
713
+     *
714
+     * @param IUser $user
715
+     * @param string $message
716
+     *
717
+     * @return string base64 encoded signature
718
+     */
719
+    protected function signMessage(IUser $user, $message) {
720
+        $privateKey = $this->keyManager->getKey($user)->getPrivate();
721
+        openssl_sign(json_encode($message), $signature, $privateKey, OPENSSL_ALGO_SHA512);
722
+        $signatureBase64 = base64_encode($signature);
723
+
724
+        return $signatureBase64;
725
+    }
726
+
727
+    /**
728
+     * @NoAdminRequired
729
+     * @NoSubadminRequired
730
+     * @PasswordConfirmationRequired
731
+     *
732
+     * @param string $avatarScope
733
+     * @param string $displayname
734
+     * @param string $displaynameScope
735
+     * @param string $phone
736
+     * @param string $phoneScope
737
+     * @param string $email
738
+     * @param string $emailScope
739
+     * @param string $website
740
+     * @param string $websiteScope
741
+     * @param string $address
742
+     * @param string $addressScope
743
+     * @param string $twitter
744
+     * @param string $twitterScope
745
+     * @return DataResponse
746
+     */
747
+    public function setUserSettings($avatarScope,
748
+                                    $displayname,
749
+                                    $displaynameScope,
750
+                                    $phone,
751
+                                    $phoneScope,
752
+                                    $email,
753
+                                    $emailScope,
754
+                                    $website,
755
+                                    $websiteScope,
756
+                                    $address,
757
+                                    $addressScope,
758
+                                    $twitter,
759
+                                    $twitterScope
760
+    ) {
761
+
762
+        if (!empty($email) && !$this->mailer->validateMailAddress($email)) {
763
+            return new DataResponse(
764
+                [
765
+                    'status' => 'error',
766
+                    'data' => [
767
+                        'message' => (string)$this->l10n->t('Invalid mail address')
768
+                    ]
769
+                ],
770
+                Http::STATUS_UNPROCESSABLE_ENTITY
771
+            );
772
+        }
773
+
774
+        $user = $this->userSession->getUser();
775
+
776
+        $data = $this->accountManager->getUser($user);
777
+
778
+        $data[AccountManager::PROPERTY_AVATAR] = ['scope' => $avatarScope];
779
+        if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
780
+            $data[AccountManager::PROPERTY_DISPLAYNAME] = ['value' => $displayname, 'scope' => $displaynameScope];
781
+            $data[AccountManager::PROPERTY_EMAIL] = ['value' => $email, 'scope' => $emailScope];
782
+        }
783
+
784
+        if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
785
+            $federatedFileSharing = new \OCA\FederatedFileSharing\AppInfo\Application();
786
+            $shareProvider = $federatedFileSharing->getFederatedShareProvider();
787
+            if ($shareProvider->isLookupServerUploadEnabled()) {
788
+                $data[AccountManager::PROPERTY_WEBSITE] = ['value' => $website, 'scope' => $websiteScope];
789
+                $data[AccountManager::PROPERTY_ADDRESS] = ['value' => $address, 'scope' => $addressScope];
790
+                $data[AccountManager::PROPERTY_PHONE] = ['value' => $phone, 'scope' => $phoneScope];
791
+                $data[AccountManager::PROPERTY_TWITTER] = ['value' => $twitter, 'scope' => $twitterScope];
792
+            }
793
+        }
794
+
795
+        try {
796
+            $this->saveUserSettings($user, $data);
797
+            return new DataResponse(
798
+                [
799
+                    'status' => 'success',
800
+                    'data' => [
801
+                        'userId' => $user->getUID(),
802
+                        'avatarScope' => $data[AccountManager::PROPERTY_AVATAR]['scope'],
803
+                        'displayname' => $data[AccountManager::PROPERTY_DISPLAYNAME]['value'],
804
+                        'displaynameScope' => $data[AccountManager::PROPERTY_DISPLAYNAME]['scope'],
805
+                        'email' => $data[AccountManager::PROPERTY_EMAIL]['value'],
806
+                        'emailScope' => $data[AccountManager::PROPERTY_EMAIL]['scope'],
807
+                        'website' => $data[AccountManager::PROPERTY_WEBSITE]['value'],
808
+                        'websiteScope' => $data[AccountManager::PROPERTY_WEBSITE]['scope'],
809
+                        'address' => $data[AccountManager::PROPERTY_ADDRESS]['value'],
810
+                        'addressScope' => $data[AccountManager::PROPERTY_ADDRESS]['scope'],
811
+                        'message' => (string)$this->l10n->t('Settings saved')
812
+                    ]
813
+                ],
814
+                Http::STATUS_OK
815
+            );
816
+        } catch (ForbiddenException $e) {
817
+            return new DataResponse([
818
+                'status' => 'error',
819
+                'data' => [
820
+                    'message' => $e->getMessage()
821
+                ],
822
+            ]);
823
+        }
824
+
825
+    }
826
+
827
+
828
+    /**
829
+     * update account manager with new user data
830
+     *
831
+     * @param IUser $user
832
+     * @param array $data
833
+     * @throws ForbiddenException
834
+     */
835
+    protected function saveUserSettings(IUser $user, $data) {
836
+
837
+        // keep the user back-end up-to-date with the latest display name and email
838
+        // address
839
+        $oldDisplayName = $user->getDisplayName();
840
+        $oldDisplayName = is_null($oldDisplayName) ? '' : $oldDisplayName;
841
+        if (isset($data[AccountManager::PROPERTY_DISPLAYNAME]['value'])
842
+            && $oldDisplayName !== $data[AccountManager::PROPERTY_DISPLAYNAME]['value']
843
+        ) {
844
+            $result = $user->setDisplayName($data[AccountManager::PROPERTY_DISPLAYNAME]['value']);
845
+            if ($result === false) {
846
+                throw new ForbiddenException($this->l10n->t('Unable to change full name'));
847
+            }
848
+        }
849
+
850
+        $oldEmailAddress = $user->getEMailAddress();
851
+        $oldEmailAddress = is_null($oldEmailAddress) ? '' : $oldEmailAddress;
852
+        if (isset($data[AccountManager::PROPERTY_EMAIL]['value'])
853
+            && $oldEmailAddress !== $data[AccountManager::PROPERTY_EMAIL]['value']
854
+        ) {
855
+            // this is the only permission a backend provides and is also used
856
+            // for the permission of setting a email address
857
+            if (!$user->canChangeDisplayName()) {
858
+                throw new ForbiddenException($this->l10n->t('Unable to change email address'));
859
+            }
860
+            $user->setEMailAddress($data[AccountManager::PROPERTY_EMAIL]['value']);
861
+        }
862
+
863
+        $this->accountManager->updateUser($user, $data);
864
+    }
865
+
866
+    /**
867
+     * Count all unique users visible for the current admin/subadmin.
868
+     *
869
+     * @NoAdminRequired
870
+     *
871
+     * @return DataResponse
872
+     */
873
+    public function stats() {
874
+        $userCount = 0;
875
+        if ($this->isAdmin) {
876
+            $countByBackend = $this->userManager->countUsers();
877
+
878
+            if (!empty($countByBackend)) {
879
+                foreach ($countByBackend as $count) {
880
+                    $userCount += $count;
881
+                }
882
+            }
883
+        } else {
884
+            $groups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($this->userSession->getUser());
885
+
886
+            $uniqueUsers = [];
887
+            foreach ($groups as $group) {
888
+                foreach ($group->getUsers() as $uid => $displayName) {
889
+                    $uniqueUsers[$uid] = true;
890
+                }
891
+            }
892
+
893
+            $userCount = count($uniqueUsers);
894
+        }
895
+
896
+        return new DataResponse(
897
+            [
898
+                'totalUsers' => $userCount
899
+            ]
900
+        );
901
+    }
902
+
903
+
904
+    /**
905
+     * Set the displayName of a user
906
+     *
907
+     * @NoAdminRequired
908
+     * @NoSubadminRequired
909
+     * @PasswordConfirmationRequired
910
+     * @todo merge into saveUserSettings
911
+     *
912
+     * @param string $username
913
+     * @param string $displayName
914
+     * @return DataResponse
915
+     */
916
+    public function setDisplayName($username, $displayName) {
917
+        $currentUser = $this->userSession->getUser();
918
+        $user = $this->userManager->get($username);
919
+
920
+        if ($user === null ||
921
+            !$user->canChangeDisplayName() ||
922
+            (
923
+                !$this->groupManager->isAdmin($currentUser->getUID()) &&
924
+                !$this->groupManager->getSubAdmin()->isUserAccessible($currentUser, $user) &&
925
+                $currentUser->getUID() !== $username
926
+
927
+            )
928
+        ) {
929
+            return new DataResponse([
930
+                'status' => 'error',
931
+                'data' => [
932
+                    'message' => $this->l10n->t('Authentication error'),
933
+                ],
934
+            ]);
935
+        }
936
+
937
+        $userData = $this->accountManager->getUser($user);
938
+        $userData[AccountManager::PROPERTY_DISPLAYNAME]['value'] = $displayName;
939
+
940
+
941
+        try {
942
+            $this->saveUserSettings($user, $userData);
943
+            return new DataResponse([
944
+                'status' => 'success',
945
+                'data' => [
946
+                    'message' => $this->l10n->t('Your full name has been changed.'),
947
+                    'username' => $username,
948
+                    'displayName' => $displayName,
949
+                ],
950
+            ]);
951
+        } catch (ForbiddenException $e) {
952
+            return new DataResponse([
953
+                'status' => 'error',
954
+                'data' => [
955
+                    'message' => $e->getMessage(),
956
+                    'displayName' => $user->getDisplayName(),
957
+                ],
958
+            ]);
959
+        }
960
+    }
961
+
962
+    /**
963
+     * Set the mail address of a user
964
+     *
965
+     * @NoAdminRequired
966
+     * @NoSubadminRequired
967
+     * @PasswordConfirmationRequired
968
+     *
969
+     * @param string $id
970
+     * @param string $mailAddress
971
+     * @return DataResponse
972
+     */
973
+    public function setEMailAddress($id, $mailAddress) {
974
+        $user = $this->userManager->get($id);
975
+        if (!$this->isAdmin
976
+            && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)
977
+        ) {
978
+            return new DataResponse(
979
+                [
980
+                    'status' => 'error',
981
+                    'data' => [
982
+                        'message' => (string)$this->l10n->t('Forbidden')
983
+                    ]
984
+                ],
985
+                Http::STATUS_FORBIDDEN
986
+            );
987
+        }
988
+
989
+        if ($mailAddress !== '' && !$this->mailer->validateMailAddress($mailAddress)) {
990
+            return new DataResponse(
991
+                [
992
+                    'status' => 'error',
993
+                    'data' => [
994
+                        'message' => (string)$this->l10n->t('Invalid mail address')
995
+                    ]
996
+                ],
997
+                Http::STATUS_UNPROCESSABLE_ENTITY
998
+            );
999
+        }
1000
+
1001
+        if (!$user) {
1002
+            return new DataResponse(
1003
+                [
1004
+                    'status' => 'error',
1005
+                    'data' => [
1006
+                        'message' => (string)$this->l10n->t('Invalid user')
1007
+                    ]
1008
+                ],
1009
+                Http::STATUS_UNPROCESSABLE_ENTITY
1010
+            );
1011
+        }
1012
+        // this is the only permission a backend provides and is also used
1013
+        // for the permission of setting a email address
1014
+        if (!$user->canChangeDisplayName()) {
1015
+            return new DataResponse(
1016
+                [
1017
+                    'status' => 'error',
1018
+                    'data' => [
1019
+                        'message' => (string)$this->l10n->t('Unable to change mail address')
1020
+                    ]
1021
+                ],
1022
+                Http::STATUS_FORBIDDEN
1023
+            );
1024
+        }
1025
+
1026
+        $userData = $this->accountManager->getUser($user);
1027
+        $userData[AccountManager::PROPERTY_EMAIL]['value'] = $mailAddress;
1028
+
1029
+        try {
1030
+            $this->saveUserSettings($user, $userData);
1031
+            return new DataResponse(
1032
+                [
1033
+                    'status' => 'success',
1034
+                    'data' => [
1035
+                        'username' => $id,
1036
+                        'mailAddress' => $mailAddress,
1037
+                        'message' => (string)$this->l10n->t('Email saved')
1038
+                    ]
1039
+                ],
1040
+                Http::STATUS_OK
1041
+            );
1042
+        } catch (ForbiddenException $e) {
1043
+            return new DataResponse([
1044
+                'status' => 'error',
1045
+                'data' => [
1046
+                    'message' => $e->getMessage()
1047
+                ],
1048
+            ]);
1049
+        }
1050
+    }
1051 1051
 
1052 1052
 }
Please login to merge, or discard this patch.
lib/private/User/Database.php 2 patches
Indentation   +323 added lines, -323 removed lines patch added patch discarded remove patch
@@ -65,327 +65,327 @@
 block discarded – undo
65 65
  * Class for user management in a SQL Database (e.g. MySQL, SQLite)
66 66
  */
67 67
 class Database extends Backend implements IUserBackend {
68
-	/** @var CappedMemoryCache */
69
-	private $cache;
70
-
71
-	/** @var EventDispatcher */
72
-	private $eventDispatcher;
73
-
74
-	/**
75
-	 * \OC\User\Database constructor.
76
-	 *
77
-	 * @param EventDispatcher $eventDispatcher
78
-	 */
79
-	public function __construct($eventDispatcher = null) {
80
-		$this->cache = new CappedMemoryCache();
81
-		$this->eventDispatcher = $eventDispatcher ? $eventDispatcher : \OC::$server->getEventDispatcher();
82
-	}
83
-
84
-	/**
85
-	 * Create a new user
86
-	 * @param string $uid The username of the user to create
87
-	 * @param string $password The password of the new user
88
-	 * @return bool
89
-	 *
90
-	 * Creates a new user. Basic checking of username is done in OC_User
91
-	 * itself, not in its subclasses.
92
-	 */
93
-	public function createUser($uid, $password) {
94
-		if (!$this->userExists($uid)) {
95
-			$event = new GenericEvent($password);
96
-			$this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
97
-			$query = \OC_DB::prepare('INSERT INTO `*PREFIX*users` ( `uid`, `password` ) VALUES( ?, ? )');
98
-			try {
99
-				$result = $query->execute(array($uid, \OC::$server->getHasher()->hash($password)));
100
-			} catch (\Exception $e) {
101
-				$result = false;
102
-			}
103
-
104
-			// Clear cache
105
-			unset($this->cache[$uid]);
106
-
107
-			return $result ? true : false;
108
-		}
109
-
110
-		return false;
111
-	}
112
-
113
-	/**
114
-	 * delete a user
115
-	 * @param string $uid The username of the user to delete
116
-	 * @return bool
117
-	 *
118
-	 * Deletes a user
119
-	 */
120
-	public function deleteUser($uid) {
121
-		// Delete user-group-relation
122
-		$query = \OC_DB::prepare('DELETE FROM `*PREFIX*users` WHERE `uid` = ?');
123
-		$result = $query->execute(array($uid));
124
-
125
-		if (isset($this->cache[$uid])) {
126
-			unset($this->cache[$uid]);
127
-		}
128
-
129
-		return $result ? true : false;
130
-	}
131
-
132
-	/**
133
-	 * Set password
134
-	 * @param string $uid The username
135
-	 * @param string $password The new password
136
-	 * @return bool
137
-	 *
138
-	 * Change the password of a user
139
-	 */
140
-	public function setPassword($uid, $password) {
141
-		if ($this->userExists($uid)) {
142
-			$event = new GenericEvent($password);
143
-			$this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
144
-			$query = \OC_DB::prepare('UPDATE `*PREFIX*users` SET `password` = ? WHERE `uid` = ?');
145
-			$result = $query->execute(array(\OC::$server->getHasher()->hash($password), $uid));
146
-
147
-			return $result ? true : false;
148
-		}
149
-
150
-		return false;
151
-	}
152
-
153
-	/**
154
-	 * Set display name
155
-	 * @param string $uid The username
156
-	 * @param string $displayName The new display name
157
-	 * @return bool
158
-	 *
159
-	 * Change the display name of a user
160
-	 */
161
-	public function setDisplayName($uid, $displayName) {
162
-		if ($this->userExists($uid)) {
163
-			$query = \OC_DB::prepare('UPDATE `*PREFIX*users` SET `displayname` = ? WHERE LOWER(`uid`) = LOWER(?)');
164
-			$query->execute(array($displayName, $uid));
165
-			$this->cache[$uid]['displayname'] = $displayName;
166
-
167
-			return true;
168
-		}
169
-
170
-		return false;
171
-	}
172
-
173
-	/**
174
-	 * get display name of the user
175
-	 * @param string $uid user ID of the user
176
-	 * @return string display name
177
-	 */
178
-	public function getDisplayName($uid) {
179
-		$this->loadUser($uid);
180
-		return empty($this->cache[$uid]['displayname']) ? $uid : $this->cache[$uid]['displayname'];
181
-	}
182
-
183
-	/**
184
-	 * Get a list of all display names and user ids.
185
-	 *
186
-	 * @param string $search
187
-	 * @param string|null $limit
188
-	 * @param string|null $offset
189
-	 * @return array an array of all displayNames (value) and the corresponding uids (key)
190
-	 */
191
-	public function getDisplayNames($search = '', $limit = null, $offset = null) {
192
-		$parameters = [];
193
-		$searchLike = '';
194
-		if ($search !== '') {
195
-			$parameters[] = '%' . \OC::$server->getDatabaseConnection()->escapeLikeParameter($search) . '%';
196
-			$parameters[] = '%' . \OC::$server->getDatabaseConnection()->escapeLikeParameter($search) . '%';
197
-			$searchLike = ' WHERE LOWER(`displayname`) LIKE LOWER(?) OR '
198
-				. 'LOWER(`uid`) LIKE LOWER(?)';
199
-		}
200
-
201
-		$displayNames = array();
202
-		$query = \OC_DB::prepare('SELECT `uid`, `displayname` FROM `*PREFIX*users`'
203
-			. $searchLike .' ORDER BY LOWER(`displayname`), LOWER(`uid`) ASC', $limit, $offset);
204
-		$result = $query->execute($parameters);
205
-		while ($row = $result->fetchRow()) {
206
-			$displayNames[$row['uid']] = $row['displayname'];
207
-		}
208
-
209
-		return $displayNames;
210
-	}
211
-
212
-	/**
213
-	 * Check if the password is correct
214
-	 * @param string $uid The username
215
-	 * @param string $password The password
216
-	 * @return string
217
-	 *
218
-	 * Check if the password is correct without logging in the user
219
-	 * returns the user id or false
220
-	 */
221
-	public function checkPassword($uid, $password) {
222
-		$query = \OC_DB::prepare('SELECT `uid`, `password` FROM `*PREFIX*users` WHERE LOWER(`uid`) = LOWER(?)');
223
-		$result = $query->execute(array($uid));
224
-
225
-		$row = $result->fetchRow();
226
-		if ($row) {
227
-			$storedHash = $row['password'];
228
-			$newHash = '';
229
-			if(\OC::$server->getHasher()->verify($password, $storedHash, $newHash)) {
230
-				if(!empty($newHash)) {
231
-					$this->setPassword($uid, $password);
232
-				}
233
-				return $row['uid'];
234
-			}
235
-
236
-		}
237
-
238
-		return false;
239
-	}
240
-
241
-	/**
242
-	 * Load an user in the cache
243
-	 * @param string $uid the username
244
-	 * @return boolean true if user was found, false otherwise
245
-	 */
246
-	private function loadUser($uid) {
247
-		$uid = (string) $uid;
248
-		if (!isset($this->cache[$uid])) {
249
-			//guests $uid could be NULL or ''
250
-			if ($uid === '') {
251
-				$this->cache[$uid]=false;
252
-				return true;
253
-			}
254
-
255
-			$query = \OC_DB::prepare('SELECT `uid`, `displayname` FROM `*PREFIX*users` WHERE LOWER(`uid`) = LOWER(?)');
256
-			$result = $query->execute(array($uid));
257
-
258
-			if ($result === false) {
259
-				Util::writeLog('core', \OC_DB::getErrorMessage(), Util::ERROR);
260
-				return false;
261
-			}
262
-
263
-			$this->cache[$uid] = false;
264
-
265
-			// "uid" is primary key, so there can only be a single result
266
-			if ($row = $result->fetchRow()) {
267
-				$this->cache[$uid]['uid'] = $row['uid'];
268
-				$this->cache[$uid]['displayname'] = $row['displayname'];
269
-				$result->closeCursor();
270
-			} else {
271
-				$result->closeCursor();
272
-				return false;
273
-			}
274
-		}
275
-
276
-		return true;
277
-	}
278
-
279
-	/**
280
-	 * Get a list of all users
281
-	 *
282
-	 * @param string $search
283
-	 * @param null|int $limit
284
-	 * @param null|int $offset
285
-	 * @return string[] an array of all uids
286
-	 */
287
-	public function getUsers($search = '', $limit = null, $offset = null) {
288
-		$parameters = [];
289
-		$searchLike = '';
290
-		if ($search !== '') {
291
-			$parameters[] = '%' . \OC::$server->getDatabaseConnection()->escapeLikeParameter($search) . '%';
292
-			$searchLike = ' WHERE LOWER(`uid`) LIKE LOWER(?)';
293
-			$parameters[] = '%' . \OC::$server->getDatabaseConnection()->escapeLikeParameter($search) . '%';
294
-			$searchLike .= ' OR LOWER(`displayname`) LIKE LOWER(?)';
295
-		}
296
-
297
-		$query = \OC_DB::prepare('SELECT `uid` FROM `*PREFIX*users`' . $searchLike . ' ORDER BY LOWER(`uid`) ASC', $limit, $offset);
298
-		$result = $query->execute($parameters);
299
-		$users = array();
300
-		while ($row = $result->fetchRow()) {
301
-			$users[] = $row['uid'];
302
-		}
303
-		return $users;
304
-	}
305
-
306
-	/**
307
-	 * check if a user exists
308
-	 * @param string $uid the username
309
-	 * @return boolean
310
-	 */
311
-	public function userExists($uid) {
312
-		$this->loadUser($uid);
313
-		return $this->cache[$uid] !== false;
314
-	}
315
-
316
-	/**
317
-	 * get the user's home directory
318
-	 * @param string $uid the username
319
-	 * @return string|false
320
-	 */
321
-	public function getHome($uid) {
322
-		if ($this->userExists($uid)) {
323
-			return \OC::$server->getConfig()->getSystemValue("datadirectory", \OC::$SERVERROOT . "/data") . '/' . $uid;
324
-		}
325
-
326
-		return false;
327
-	}
328
-
329
-	/**
330
-	 * @return bool
331
-	 */
332
-	public function hasUserListings() {
333
-		return true;
334
-	}
335
-
336
-	/**
337
-	 * counts the users in the database
338
-	 *
339
-	 * @return int|bool
340
-	 */
341
-	public function countUsers() {
342
-		$query = \OC_DB::prepare('SELECT COUNT(*) FROM `*PREFIX*users`');
343
-		$result = $query->execute();
344
-		if ($result === false) {
345
-			Util::writeLog('core', \OC_DB::getErrorMessage(), Util::ERROR);
346
-			return false;
347
-		}
348
-		return $result->fetchOne();
349
-	}
350
-
351
-	/**
352
-	 * returns the username for the given login name in the correct casing
353
-	 *
354
-	 * @param string $loginName
355
-	 * @return string|false
356
-	 */
357
-	public function loginName2UserName($loginName) {
358
-		if ($this->userExists($loginName)) {
359
-			return $this->cache[$loginName]['uid'];
360
-		}
361
-
362
-		return false;
363
-	}
364
-
365
-	/**
366
-	 * Backend name to be shown in user management
367
-	 * @return string the name of the backend to be shown
368
-	 */
369
-	public function getBackendName(){
370
-		return 'Database';
371
-	}
372
-
373
-	public static function preLoginNameUsedAsUserName($param) {
374
-		if(!isset($param['uid'])) {
375
-			throw new \Exception('key uid is expected to be set in $param');
376
-		}
377
-
378
-		$backends = \OC::$server->getUserManager()->getBackends();
379
-		foreach ($backends as $backend) {
380
-			if ($backend instanceof Database) {
381
-				/** @var \OC\User\Database $backend */
382
-				$uid = $backend->loginName2UserName($param['uid']);
383
-				if ($uid !== false) {
384
-					$param['uid'] = $uid;
385
-					return;
386
-				}
387
-			}
388
-		}
389
-
390
-	}
68
+    /** @var CappedMemoryCache */
69
+    private $cache;
70
+
71
+    /** @var EventDispatcher */
72
+    private $eventDispatcher;
73
+
74
+    /**
75
+     * \OC\User\Database constructor.
76
+     *
77
+     * @param EventDispatcher $eventDispatcher
78
+     */
79
+    public function __construct($eventDispatcher = null) {
80
+        $this->cache = new CappedMemoryCache();
81
+        $this->eventDispatcher = $eventDispatcher ? $eventDispatcher : \OC::$server->getEventDispatcher();
82
+    }
83
+
84
+    /**
85
+     * Create a new user
86
+     * @param string $uid The username of the user to create
87
+     * @param string $password The password of the new user
88
+     * @return bool
89
+     *
90
+     * Creates a new user. Basic checking of username is done in OC_User
91
+     * itself, not in its subclasses.
92
+     */
93
+    public function createUser($uid, $password) {
94
+        if (!$this->userExists($uid)) {
95
+            $event = new GenericEvent($password);
96
+            $this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
97
+            $query = \OC_DB::prepare('INSERT INTO `*PREFIX*users` ( `uid`, `password` ) VALUES( ?, ? )');
98
+            try {
99
+                $result = $query->execute(array($uid, \OC::$server->getHasher()->hash($password)));
100
+            } catch (\Exception $e) {
101
+                $result = false;
102
+            }
103
+
104
+            // Clear cache
105
+            unset($this->cache[$uid]);
106
+
107
+            return $result ? true : false;
108
+        }
109
+
110
+        return false;
111
+    }
112
+
113
+    /**
114
+     * delete a user
115
+     * @param string $uid The username of the user to delete
116
+     * @return bool
117
+     *
118
+     * Deletes a user
119
+     */
120
+    public function deleteUser($uid) {
121
+        // Delete user-group-relation
122
+        $query = \OC_DB::prepare('DELETE FROM `*PREFIX*users` WHERE `uid` = ?');
123
+        $result = $query->execute(array($uid));
124
+
125
+        if (isset($this->cache[$uid])) {
126
+            unset($this->cache[$uid]);
127
+        }
128
+
129
+        return $result ? true : false;
130
+    }
131
+
132
+    /**
133
+     * Set password
134
+     * @param string $uid The username
135
+     * @param string $password The new password
136
+     * @return bool
137
+     *
138
+     * Change the password of a user
139
+     */
140
+    public function setPassword($uid, $password) {
141
+        if ($this->userExists($uid)) {
142
+            $event = new GenericEvent($password);
143
+            $this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
144
+            $query = \OC_DB::prepare('UPDATE `*PREFIX*users` SET `password` = ? WHERE `uid` = ?');
145
+            $result = $query->execute(array(\OC::$server->getHasher()->hash($password), $uid));
146
+
147
+            return $result ? true : false;
148
+        }
149
+
150
+        return false;
151
+    }
152
+
153
+    /**
154
+     * Set display name
155
+     * @param string $uid The username
156
+     * @param string $displayName The new display name
157
+     * @return bool
158
+     *
159
+     * Change the display name of a user
160
+     */
161
+    public function setDisplayName($uid, $displayName) {
162
+        if ($this->userExists($uid)) {
163
+            $query = \OC_DB::prepare('UPDATE `*PREFIX*users` SET `displayname` = ? WHERE LOWER(`uid`) = LOWER(?)');
164
+            $query->execute(array($displayName, $uid));
165
+            $this->cache[$uid]['displayname'] = $displayName;
166
+
167
+            return true;
168
+        }
169
+
170
+        return false;
171
+    }
172
+
173
+    /**
174
+     * get display name of the user
175
+     * @param string $uid user ID of the user
176
+     * @return string display name
177
+     */
178
+    public function getDisplayName($uid) {
179
+        $this->loadUser($uid);
180
+        return empty($this->cache[$uid]['displayname']) ? $uid : $this->cache[$uid]['displayname'];
181
+    }
182
+
183
+    /**
184
+     * Get a list of all display names and user ids.
185
+     *
186
+     * @param string $search
187
+     * @param string|null $limit
188
+     * @param string|null $offset
189
+     * @return array an array of all displayNames (value) and the corresponding uids (key)
190
+     */
191
+    public function getDisplayNames($search = '', $limit = null, $offset = null) {
192
+        $parameters = [];
193
+        $searchLike = '';
194
+        if ($search !== '') {
195
+            $parameters[] = '%' . \OC::$server->getDatabaseConnection()->escapeLikeParameter($search) . '%';
196
+            $parameters[] = '%' . \OC::$server->getDatabaseConnection()->escapeLikeParameter($search) . '%';
197
+            $searchLike = ' WHERE LOWER(`displayname`) LIKE LOWER(?) OR '
198
+                . 'LOWER(`uid`) LIKE LOWER(?)';
199
+        }
200
+
201
+        $displayNames = array();
202
+        $query = \OC_DB::prepare('SELECT `uid`, `displayname` FROM `*PREFIX*users`'
203
+            . $searchLike .' ORDER BY LOWER(`displayname`), LOWER(`uid`) ASC', $limit, $offset);
204
+        $result = $query->execute($parameters);
205
+        while ($row = $result->fetchRow()) {
206
+            $displayNames[$row['uid']] = $row['displayname'];
207
+        }
208
+
209
+        return $displayNames;
210
+    }
211
+
212
+    /**
213
+     * Check if the password is correct
214
+     * @param string $uid The username
215
+     * @param string $password The password
216
+     * @return string
217
+     *
218
+     * Check if the password is correct without logging in the user
219
+     * returns the user id or false
220
+     */
221
+    public function checkPassword($uid, $password) {
222
+        $query = \OC_DB::prepare('SELECT `uid`, `password` FROM `*PREFIX*users` WHERE LOWER(`uid`) = LOWER(?)');
223
+        $result = $query->execute(array($uid));
224
+
225
+        $row = $result->fetchRow();
226
+        if ($row) {
227
+            $storedHash = $row['password'];
228
+            $newHash = '';
229
+            if(\OC::$server->getHasher()->verify($password, $storedHash, $newHash)) {
230
+                if(!empty($newHash)) {
231
+                    $this->setPassword($uid, $password);
232
+                }
233
+                return $row['uid'];
234
+            }
235
+
236
+        }
237
+
238
+        return false;
239
+    }
240
+
241
+    /**
242
+     * Load an user in the cache
243
+     * @param string $uid the username
244
+     * @return boolean true if user was found, false otherwise
245
+     */
246
+    private function loadUser($uid) {
247
+        $uid = (string) $uid;
248
+        if (!isset($this->cache[$uid])) {
249
+            //guests $uid could be NULL or ''
250
+            if ($uid === '') {
251
+                $this->cache[$uid]=false;
252
+                return true;
253
+            }
254
+
255
+            $query = \OC_DB::prepare('SELECT `uid`, `displayname` FROM `*PREFIX*users` WHERE LOWER(`uid`) = LOWER(?)');
256
+            $result = $query->execute(array($uid));
257
+
258
+            if ($result === false) {
259
+                Util::writeLog('core', \OC_DB::getErrorMessage(), Util::ERROR);
260
+                return false;
261
+            }
262
+
263
+            $this->cache[$uid] = false;
264
+
265
+            // "uid" is primary key, so there can only be a single result
266
+            if ($row = $result->fetchRow()) {
267
+                $this->cache[$uid]['uid'] = $row['uid'];
268
+                $this->cache[$uid]['displayname'] = $row['displayname'];
269
+                $result->closeCursor();
270
+            } else {
271
+                $result->closeCursor();
272
+                return false;
273
+            }
274
+        }
275
+
276
+        return true;
277
+    }
278
+
279
+    /**
280
+     * Get a list of all users
281
+     *
282
+     * @param string $search
283
+     * @param null|int $limit
284
+     * @param null|int $offset
285
+     * @return string[] an array of all uids
286
+     */
287
+    public function getUsers($search = '', $limit = null, $offset = null) {
288
+        $parameters = [];
289
+        $searchLike = '';
290
+        if ($search !== '') {
291
+            $parameters[] = '%' . \OC::$server->getDatabaseConnection()->escapeLikeParameter($search) . '%';
292
+            $searchLike = ' WHERE LOWER(`uid`) LIKE LOWER(?)';
293
+            $parameters[] = '%' . \OC::$server->getDatabaseConnection()->escapeLikeParameter($search) . '%';
294
+            $searchLike .= ' OR LOWER(`displayname`) LIKE LOWER(?)';
295
+        }
296
+
297
+        $query = \OC_DB::prepare('SELECT `uid` FROM `*PREFIX*users`' . $searchLike . ' ORDER BY LOWER(`uid`) ASC', $limit, $offset);
298
+        $result = $query->execute($parameters);
299
+        $users = array();
300
+        while ($row = $result->fetchRow()) {
301
+            $users[] = $row['uid'];
302
+        }
303
+        return $users;
304
+    }
305
+
306
+    /**
307
+     * check if a user exists
308
+     * @param string $uid the username
309
+     * @return boolean
310
+     */
311
+    public function userExists($uid) {
312
+        $this->loadUser($uid);
313
+        return $this->cache[$uid] !== false;
314
+    }
315
+
316
+    /**
317
+     * get the user's home directory
318
+     * @param string $uid the username
319
+     * @return string|false
320
+     */
321
+    public function getHome($uid) {
322
+        if ($this->userExists($uid)) {
323
+            return \OC::$server->getConfig()->getSystemValue("datadirectory", \OC::$SERVERROOT . "/data") . '/' . $uid;
324
+        }
325
+
326
+        return false;
327
+    }
328
+
329
+    /**
330
+     * @return bool
331
+     */
332
+    public function hasUserListings() {
333
+        return true;
334
+    }
335
+
336
+    /**
337
+     * counts the users in the database
338
+     *
339
+     * @return int|bool
340
+     */
341
+    public function countUsers() {
342
+        $query = \OC_DB::prepare('SELECT COUNT(*) FROM `*PREFIX*users`');
343
+        $result = $query->execute();
344
+        if ($result === false) {
345
+            Util::writeLog('core', \OC_DB::getErrorMessage(), Util::ERROR);
346
+            return false;
347
+        }
348
+        return $result->fetchOne();
349
+    }
350
+
351
+    /**
352
+     * returns the username for the given login name in the correct casing
353
+     *
354
+     * @param string $loginName
355
+     * @return string|false
356
+     */
357
+    public function loginName2UserName($loginName) {
358
+        if ($this->userExists($loginName)) {
359
+            return $this->cache[$loginName]['uid'];
360
+        }
361
+
362
+        return false;
363
+    }
364
+
365
+    /**
366
+     * Backend name to be shown in user management
367
+     * @return string the name of the backend to be shown
368
+     */
369
+    public function getBackendName(){
370
+        return 'Database';
371
+    }
372
+
373
+    public static function preLoginNameUsedAsUserName($param) {
374
+        if(!isset($param['uid'])) {
375
+            throw new \Exception('key uid is expected to be set in $param');
376
+        }
377
+
378
+        $backends = \OC::$server->getUserManager()->getBackends();
379
+        foreach ($backends as $backend) {
380
+            if ($backend instanceof Database) {
381
+                /** @var \OC\User\Database $backend */
382
+                $uid = $backend->loginName2UserName($param['uid']);
383
+                if ($uid !== false) {
384
+                    $param['uid'] = $uid;
385
+                    return;
386
+                }
387
+            }
388
+        }
389
+
390
+    }
391 391
 }
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -192,15 +192,15 @@  discard block
 block discarded – undo
192 192
 		$parameters = [];
193 193
 		$searchLike = '';
194 194
 		if ($search !== '') {
195
-			$parameters[] = '%' . \OC::$server->getDatabaseConnection()->escapeLikeParameter($search) . '%';
196
-			$parameters[] = '%' . \OC::$server->getDatabaseConnection()->escapeLikeParameter($search) . '%';
195
+			$parameters[] = '%'.\OC::$server->getDatabaseConnection()->escapeLikeParameter($search).'%';
196
+			$parameters[] = '%'.\OC::$server->getDatabaseConnection()->escapeLikeParameter($search).'%';
197 197
 			$searchLike = ' WHERE LOWER(`displayname`) LIKE LOWER(?) OR '
198 198
 				. 'LOWER(`uid`) LIKE LOWER(?)';
199 199
 		}
200 200
 
201 201
 		$displayNames = array();
202 202
 		$query = \OC_DB::prepare('SELECT `uid`, `displayname` FROM `*PREFIX*users`'
203
-			. $searchLike .' ORDER BY LOWER(`displayname`), LOWER(`uid`) ASC', $limit, $offset);
203
+			. $searchLike.' ORDER BY LOWER(`displayname`), LOWER(`uid`) ASC', $limit, $offset);
204 204
 		$result = $query->execute($parameters);
205 205
 		while ($row = $result->fetchRow()) {
206 206
 			$displayNames[$row['uid']] = $row['displayname'];
@@ -226,8 +226,8 @@  discard block
 block discarded – undo
226 226
 		if ($row) {
227 227
 			$storedHash = $row['password'];
228 228
 			$newHash = '';
229
-			if(\OC::$server->getHasher()->verify($password, $storedHash, $newHash)) {
230
-				if(!empty($newHash)) {
229
+			if (\OC::$server->getHasher()->verify($password, $storedHash, $newHash)) {
230
+				if (!empty($newHash)) {
231 231
 					$this->setPassword($uid, $password);
232 232
 				}
233 233
 				return $row['uid'];
@@ -248,7 +248,7 @@  discard block
 block discarded – undo
248 248
 		if (!isset($this->cache[$uid])) {
249 249
 			//guests $uid could be NULL or ''
250 250
 			if ($uid === '') {
251
-				$this->cache[$uid]=false;
251
+				$this->cache[$uid] = false;
252 252
 				return true;
253 253
 			}
254 254
 
@@ -288,13 +288,13 @@  discard block
 block discarded – undo
288 288
 		$parameters = [];
289 289
 		$searchLike = '';
290 290
 		if ($search !== '') {
291
-			$parameters[] = '%' . \OC::$server->getDatabaseConnection()->escapeLikeParameter($search) . '%';
291
+			$parameters[] = '%'.\OC::$server->getDatabaseConnection()->escapeLikeParameter($search).'%';
292 292
 			$searchLike = ' WHERE LOWER(`uid`) LIKE LOWER(?)';
293
-			$parameters[] = '%' . \OC::$server->getDatabaseConnection()->escapeLikeParameter($search) . '%';
293
+			$parameters[] = '%'.\OC::$server->getDatabaseConnection()->escapeLikeParameter($search).'%';
294 294
 			$searchLike .= ' OR LOWER(`displayname`) LIKE LOWER(?)';
295 295
 		}
296 296
 
297
-		$query = \OC_DB::prepare('SELECT `uid` FROM `*PREFIX*users`' . $searchLike . ' ORDER BY LOWER(`uid`) ASC', $limit, $offset);
297
+		$query = \OC_DB::prepare('SELECT `uid` FROM `*PREFIX*users`'.$searchLike.' ORDER BY LOWER(`uid`) ASC', $limit, $offset);
298 298
 		$result = $query->execute($parameters);
299 299
 		$users = array();
300 300
 		while ($row = $result->fetchRow()) {
@@ -320,7 +320,7 @@  discard block
 block discarded – undo
320 320
 	 */
321 321
 	public function getHome($uid) {
322 322
 		if ($this->userExists($uid)) {
323
-			return \OC::$server->getConfig()->getSystemValue("datadirectory", \OC::$SERVERROOT . "/data") . '/' . $uid;
323
+			return \OC::$server->getConfig()->getSystemValue("datadirectory", \OC::$SERVERROOT."/data").'/'.$uid;
324 324
 		}
325 325
 
326 326
 		return false;
@@ -366,12 +366,12 @@  discard block
 block discarded – undo
366 366
 	 * Backend name to be shown in user management
367 367
 	 * @return string the name of the backend to be shown
368 368
 	 */
369
-	public function getBackendName(){
369
+	public function getBackendName() {
370 370
 		return 'Database';
371 371
 	}
372 372
 
373 373
 	public static function preLoginNameUsedAsUserName($param) {
374
-		if(!isset($param['uid'])) {
374
+		if (!isset($param['uid'])) {
375 375
 			throw new \Exception('key uid is expected to be set in $param');
376 376
 		}
377 377
 
Please login to merge, or discard this patch.