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