Passed
Push — master ( 53fd49...95d1cf )
by Roeland
12:52 queued 10s
created
apps/provisioning_api/lib/Controller/UsersController.php 1 patch
Indentation   +853 added lines, -853 removed lines patch added patch discarded remove patch
@@ -54,857 +54,857 @@
 block discarded – undo
54 54
 
55 55
 class UsersController extends AUserData {
56 56
 
57
-	/** @var IAppManager */
58
-	private $appManager;
59
-	/** @var ILogger */
60
-	private $logger;
61
-	/** @var IFactory */
62
-	private $l10nFactory;
63
-	/** @var NewUserMailHelper */
64
-	private $newUserMailHelper;
65
-	/** @var FederatedFileSharingFactory */
66
-	private $federatedFileSharingFactory;
67
-	/** @var ISecureRandom */
68
-	private $secureRandom;
69
-
70
-	/**
71
-	 * @param string $appName
72
-	 * @param IRequest $request
73
-	 * @param IUserManager $userManager
74
-	 * @param IConfig $config
75
-	 * @param IAppManager $appManager
76
-	 * @param IGroupManager $groupManager
77
-	 * @param IUserSession $userSession
78
-	 * @param AccountManager $accountManager
79
-	 * @param ILogger $logger
80
-	 * @param IFactory $l10nFactory
81
-	 * @param NewUserMailHelper $newUserMailHelper
82
-	 * @param FederatedFileSharingFactory $federatedFileSharingFactory
83
-	 * @param ISecureRandom $secureRandom
84
-	 */
85
-	public function __construct(string $appName,
86
-								IRequest $request,
87
-								IUserManager $userManager,
88
-								IConfig $config,
89
-								IAppManager $appManager,
90
-								IGroupManager $groupManager,
91
-								IUserSession $userSession,
92
-								AccountManager $accountManager,
93
-								ILogger $logger,
94
-								IFactory $l10nFactory,
95
-								NewUserMailHelper $newUserMailHelper,
96
-								FederatedFileSharingFactory $federatedFileSharingFactory,
97
-								ISecureRandom $secureRandom) {
98
-		parent::__construct($appName,
99
-							$request,
100
-							$userManager,
101
-							$config,
102
-							$groupManager,
103
-							$userSession,
104
-							$accountManager);
105
-
106
-		$this->appManager = $appManager;
107
-		$this->logger = $logger;
108
-		$this->l10nFactory = $l10nFactory;
109
-		$this->newUserMailHelper = $newUserMailHelper;
110
-		$this->federatedFileSharingFactory = $federatedFileSharingFactory;
111
-		$this->secureRandom = $secureRandom;
112
-	}
113
-
114
-	/**
115
-	 * @NoAdminRequired
116
-	 *
117
-	 * returns a list of users
118
-	 *
119
-	 * @param string $search
120
-	 * @param int $limit
121
-	 * @param int $offset
122
-	 * @return DataResponse
123
-	 */
124
-	public function getUsers(string $search = '', $limit = null, $offset = 0): DataResponse {
125
-		$user = $this->userSession->getUser();
126
-		$users = [];
127
-
128
-		// Admin? Or SubAdmin?
129
-		$uid = $user->getUID();
130
-		$subAdminManager = $this->groupManager->getSubAdmin();
131
-		if ($this->groupManager->isAdmin($uid)){
132
-			$users = $this->userManager->search($search, $limit, $offset);
133
-		} else if ($subAdminManager->isSubAdmin($user)) {
134
-			$subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
135
-			foreach ($subAdminOfGroups as $key => $group) {
136
-				$subAdminOfGroups[$key] = $group->getGID();
137
-			}
138
-
139
-			$users = [];
140
-			foreach ($subAdminOfGroups as $group) {
141
-				$users = array_merge($users, $this->groupManager->displayNamesInGroup($group, $search, $limit, $offset));
142
-			}
143
-		}
144
-
145
-		$users = array_keys($users);
146
-
147
-		return new DataResponse([
148
-			'users' => $users
149
-		]);
150
-	}
151
-
152
-	/**
153
-	 * @NoAdminRequired
154
-	 *
155
-	 * returns a list of users and their data
156
-	 */
157
-	public function getUsersDetails(string $search = '', $limit = null, $offset = 0): DataResponse {
158
-		$currentUser = $this->userSession->getUser();
159
-		$users = [];
160
-
161
-		// Admin? Or SubAdmin?
162
-		$uid = $currentUser->getUID();
163
-		$subAdminManager = $this->groupManager->getSubAdmin();
164
-		if ($this->groupManager->isAdmin($uid)){
165
-			$users = $this->userManager->search($search, $limit, $offset);
166
-			$users = array_keys($users);
167
-		} else if ($subAdminManager->isSubAdmin($currentUser)) {
168
-			$subAdminOfGroups = $subAdminManager->getSubAdminsGroups($currentUser);
169
-			foreach ($subAdminOfGroups as $key => $group) {
170
-				$subAdminOfGroups[$key] = $group->getGID();
171
-			}
172
-
173
-			$users = [];
174
-			foreach ($subAdminOfGroups as $group) {
175
-				$users[] = array_keys($this->groupManager->displayNamesInGroup($group, $search, $limit, $offset));
176
-			}
177
-			$users = array_merge(...$users);
178
-		}
179
-
180
-		$usersDetails = [];
181
-		foreach ($users as $userId) {
182
-			$userId = (string) $userId;
183
-			$userData = $this->getUserData($userId);
184
-			// Do not insert empty entry
185
-			if (!empty($userData)) {
186
-				$usersDetails[$userId] = $userData;
187
-			} else {
188
-				// Logged user does not have permissions to see this user
189
-				// only showing its id
190
-				$usersDetails[$userId] = ['id' => $userId];
191
-			}
192
-		}
193
-
194
-		return new DataResponse([
195
-			'users' => $usersDetails
196
-		]);
197
-	}
198
-
199
-	/**
200
-	 * @PasswordConfirmationRequired
201
-	 * @NoAdminRequired
202
-	 *
203
-	 * @param string $userid
204
-	 * @param string $password
205
-	 * @param string $displayName
206
-	 * @param string $email
207
-	 * @param array $groups
208
-	 * @param array $subadmin
209
-	 * @param string $quota
210
-	 * @param string $language
211
-	 * @return DataResponse
212
-	 * @throws OCSException
213
-	 */
214
-	public function addUser(string $userid,
215
-							string $password = '',
216
-							string $displayName = '',
217
-							string $email = '',
218
-							array $groups = [],
219
-							array $subadmin = [],
220
-							string $quota = '',
221
-							string $language = ''): DataResponse {
222
-		$user = $this->userSession->getUser();
223
-		$isAdmin = $this->groupManager->isAdmin($user->getUID());
224
-		$subAdminManager = $this->groupManager->getSubAdmin();
225
-
226
-		if ($this->userManager->userExists($userid)) {
227
-			$this->logger->error('Failed addUser attempt: User already exists.', ['app' => 'ocs_api']);
228
-			throw new OCSException('User already exists', 102);
229
-		}
230
-
231
-		if ($groups !== []) {
232
-			foreach ($groups as $group) {
233
-				if (!$this->groupManager->groupExists($group)) {
234
-					throw new OCSException('group '.$group.' does not exist', 104);
235
-				}
236
-				if (!$isAdmin && !$subAdminManager->isSubAdminOfGroup($user, $this->groupManager->get($group))) {
237
-					throw new OCSException('insufficient privileges for group '. $group, 105);
238
-				}
239
-			}
240
-		} else {
241
-			if (!$isAdmin) {
242
-				throw new OCSException('no group specified (required for subadmins)', 106);
243
-			}
244
-		}
245
-
246
-		$subadminGroups = [];
247
-		if ($subadmin !== []) {
248
-			foreach ($subadmin as $groupid) {
249
-				$group = $this->groupManager->get($groupid);
250
-				// Check if group exists
251
-				if ($group === null) {
252
-					throw new OCSException('Subadmin group does not exist',  102);
253
-				}
254
-				// Check if trying to make subadmin of admin group
255
-				if ($group->getGID() === 'admin') {
256
-					throw new OCSException('Cannot create subadmins for admin group', 103);
257
-				}
258
-				// Check if has permission to promote subadmins
259
-				if (!$subAdminManager->isSubAdminOfGroup($user, $group) && !$isAdmin) {
260
-					throw new OCSForbiddenException('No permissions to promote subadmins');
261
-				}
262
-				$subadminGroups[] = $group;
263
-			}
264
-		}
265
-
266
-		$generatePasswordResetToken = false;
267
-		if ($password === '') {
268
-			if ($email === '') {
269
-				throw new OCSException('To send a password link to the user an email address is required.', 108);
270
-			}
271
-
272
-			$password = $this->secureRandom->generate(10);
273
-			// Make sure we pass the password_policy
274
-			$password .= $this->secureRandom->generate(2, '$!.,;:-~+*[]{}()');
275
-			$generatePasswordResetToken = true;
276
-		}
277
-
278
-		try {
279
-			$newUser = $this->userManager->createUser($userid, $password);
280
-			$this->logger->info('Successful addUser call with userid: ' . $userid, ['app' => 'ocs_api']);
281
-
282
-			foreach ($groups as $group) {
283
-				$this->groupManager->get($group)->addUser($newUser);
284
-				$this->logger->info('Added userid ' . $userid . ' to group ' . $group, ['app' => 'ocs_api']);
285
-			}
286
-			foreach ($subadminGroups as $group) {
287
-				$subAdminManager->createSubAdmin($newUser, $group);
288
-			}
289
-
290
-			if ($displayName !== '') {
291
-				$this->editUser($userid, 'display', $displayName);
292
-			}
293
-
294
-			if ($quota !== '') {
295
-				$this->editUser($userid, 'quota', $quota);
296
-			}
297
-
298
-			if ($language !== '') {
299
-				$this->editUser($userid, 'language', $language);
300
-			}
301
-
302
-			// Send new user mail only if a mail is set
303
-			if ($email !== '') {
304
-				$newUser->setEMailAddress($email);
305
-				try {
306
-					$emailTemplate = $this->newUserMailHelper->generateTemplate($newUser, $generatePasswordResetToken);
307
-					$this->newUserMailHelper->sendMail($newUser, $emailTemplate);
308
-				} catch (\Exception $e) {
309
-					$this->logger->logException($e, [
310
-						'message' => "Can't send new user mail to $email",
311
-						'level' => ILogger::ERROR,
312
-						'app' => 'ocs_api',
313
-					]);
314
-					throw new OCSException('Unable to send the invitation mail', 109);
315
-				}
316
-			}
317
-
318
-			return new DataResponse();
319
-
320
-		} catch (HintException $e ) {
321
-			$this->logger->logException($e, [
322
-				'message' => 'Failed addUser attempt with hint exception.',
323
-				'level' => ILogger::WARN,
324
-				'app' => 'ocs_api',
325
-			]);
326
-			throw new OCSException($e->getHint(), 107);
327
-		} catch (\Exception $e) {
328
-			$this->logger->logException($e, [
329
-				'message' => 'Failed addUser attempt with exception.',
330
-				'level' => ILogger::ERROR,
331
-				'app' => 'ocs_api',
332
-			]);
333
-			throw new OCSException('Bad request', 101);
334
-		}
335
-	}
336
-
337
-	/**
338
-	 * @NoAdminRequired
339
-	 * @NoSubAdminRequired
340
-	 *
341
-	 * gets user info
342
-	 *
343
-	 * @param string $userId
344
-	 * @return DataResponse
345
-	 * @throws OCSException
346
-	 */
347
-	public function getUser(string $userId): DataResponse {
348
-		$data = $this->getUserData($userId);
349
-		// getUserData returns empty array if not enough permissions
350
-		if (empty($data)) {
351
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
352
-		}
353
-		return new DataResponse($data);
354
-	}
355
-
356
-	/**
357
-	 * @NoAdminRequired
358
-	 * @NoSubAdminRequired
359
-	 *
360
-	 * gets user info from the currently logged in user
361
-	 *
362
-	 * @return DataResponse
363
-	 * @throws OCSException
364
-	 */
365
-	public function getCurrentUser(): DataResponse {
366
-		$user = $this->userSession->getUser();
367
-		if ($user) {
368
-			$data =  $this->getUserData($user->getUID());
369
-			// rename "displayname" to "display-name" only for this call to keep
370
-			// the API stable.
371
-			$data['display-name'] = $data['displayname'];
372
-			unset($data['displayname']);
373
-			return new DataResponse($data);
374
-
375
-		}
376
-
377
-		throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
378
-	}
379
-
380
-	/**
381
-	 * @NoAdminRequired
382
-	 * @NoSubAdminRequired
383
-	 */
384
-	public function getEditableFields(): DataResponse {
385
-		$permittedFields = [];
386
-
387
-		// Editing self (display, email)
388
-		if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
389
-			$permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
390
-			$permittedFields[] = AccountManager::PROPERTY_EMAIL;
391
-		}
392
-
393
-		if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
394
-			$federatedFileSharing = $this->federatedFileSharingFactory->get();
395
-			$shareProvider = $federatedFileSharing->getFederatedShareProvider();
396
-			if ($shareProvider->isLookupServerUploadEnabled()) {
397
-				$permittedFields[] = AccountManager::PROPERTY_PHONE;
398
-				$permittedFields[] = AccountManager::PROPERTY_ADDRESS;
399
-				$permittedFields[] = AccountManager::PROPERTY_WEBSITE;
400
-				$permittedFields[] = AccountManager::PROPERTY_TWITTER;
401
-			}
402
-		}
403
-
404
-		return new DataResponse($permittedFields);
405
-	}
406
-
407
-	/**
408
-	 * @NoAdminRequired
409
-	 * @NoSubAdminRequired
410
-	 * @PasswordConfirmationRequired
411
-	 *
412
-	 * edit users
413
-	 *
414
-	 * @param string $userId
415
-	 * @param string $key
416
-	 * @param string $value
417
-	 * @return DataResponse
418
-	 * @throws OCSException
419
-	 */
420
-	public function editUser(string $userId, string $key, string $value): DataResponse {
421
-		$currentLoggedInUser = $this->userSession->getUser();
422
-
423
-		$targetUser = $this->userManager->get($userId);
424
-		if ($targetUser === null) {
425
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
426
-		}
427
-
428
-		$permittedFields = [];
429
-		if ($targetUser->getUID() === $currentLoggedInUser->getUID()) {
430
-			// Editing self (display, email)
431
-			if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
432
-				$permittedFields[] = 'display';
433
-				$permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
434
-				$permittedFields[] = AccountManager::PROPERTY_EMAIL;
435
-			}
436
-
437
-			$permittedFields[] = 'password';
438
-			if ($this->config->getSystemValue('force_language', false) === false ||
439
-				$this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
440
-				$permittedFields[] = 'language';
441
-			}
442
-
443
-			if ($this->config->getSystemValue('force_locale', false) === false ||
444
-				$this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
445
-				$permittedFields[] = 'locale';
446
-			}
447
-
448
-			if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
449
-				$federatedFileSharing = new \OCA\FederatedFileSharing\AppInfo\Application();
450
-				$shareProvider = $federatedFileSharing->getFederatedShareProvider();
451
-				if ($shareProvider->isLookupServerUploadEnabled()) {
452
-					$permittedFields[] = AccountManager::PROPERTY_PHONE;
453
-					$permittedFields[] = AccountManager::PROPERTY_ADDRESS;
454
-					$permittedFields[] = AccountManager::PROPERTY_WEBSITE;
455
-					$permittedFields[] = AccountManager::PROPERTY_TWITTER;
456
-				}
457
-			}
458
-
459
-			// If admin they can edit their own quota
460
-			if ($this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
461
-				$permittedFields[] = 'quota';
462
-			}
463
-		} else {
464
-			// Check if admin / subadmin
465
-			$subAdminManager = $this->groupManager->getSubAdmin();
466
-			if ($subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
467
-			|| $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
468
-				// They have permissions over the user
469
-				$permittedFields[] = 'display';
470
-				$permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
471
-				$permittedFields[] = AccountManager::PROPERTY_EMAIL;
472
-				$permittedFields[] = 'password';
473
-				$permittedFields[] = 'language';
474
-				$permittedFields[] = 'locale';
475
-				$permittedFields[] = AccountManager::PROPERTY_PHONE;
476
-				$permittedFields[] = AccountManager::PROPERTY_ADDRESS;
477
-				$permittedFields[] = AccountManager::PROPERTY_WEBSITE;
478
-				$permittedFields[] = AccountManager::PROPERTY_TWITTER;
479
-				$permittedFields[] = 'quota';
480
-			} else {
481
-				// No rights
482
-				throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
483
-			}
484
-		}
485
-		// Check if permitted to edit this field
486
-		if (!in_array($key, $permittedFields)) {
487
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
488
-		}
489
-		// Process the edit
490
-		switch($key) {
491
-			case 'display':
492
-			case AccountManager::PROPERTY_DISPLAYNAME:
493
-				$targetUser->setDisplayName($value);
494
-				break;
495
-			case 'quota':
496
-				$quota = $value;
497
-				if ($quota !== 'none' && $quota !== 'default') {
498
-					if (is_numeric($quota)) {
499
-						$quota = (float) $quota;
500
-					} else {
501
-						$quota = \OCP\Util::computerFileSize($quota);
502
-					}
503
-					if ($quota === false) {
504
-						throw new OCSException('Invalid quota value '.$value, 103);
505
-					}
506
-					if ($quota === -1) {
507
-						$quota = 'none';
508
-					} else {
509
-						$quota = \OCP\Util::humanFileSize($quota);
510
-					}
511
-				}
512
-				$targetUser->setQuota($quota);
513
-				break;
514
-			case 'password':
515
-				try {
516
-					$targetUser->setPassword($value);
517
-				} catch (HintException $e) { // password policy error
518
-					throw new OCSException($e->getMessage(), 103);
519
-				}
520
-				break;
521
-			case 'language':
522
-				$languagesCodes = $this->l10nFactory->findAvailableLanguages();
523
-				if (!in_array($value, $languagesCodes, true) && $value !== 'en') {
524
-					throw new OCSException('Invalid language', 102);
525
-				}
526
-				$this->config->setUserValue($targetUser->getUID(), 'core', 'lang', $value);
527
-				break;
528
-			case 'locale':
529
-				if (!$this->l10nFactory->localeExists($value)) {
530
-					throw new OCSException('Invalid locale', 102);
531
-				}
532
-				$this->config->setUserValue($targetUser->getUID(), 'core', 'locale', $value);
533
-				break;
534
-			case AccountManager::PROPERTY_EMAIL:
535
-				if (filter_var($value, FILTER_VALIDATE_EMAIL) || $value === '') {
536
-					$targetUser->setEMailAddress($value);
537
-				} else {
538
-					throw new OCSException('', 102);
539
-				}
540
-				break;
541
-			case AccountManager::PROPERTY_PHONE:
542
-			case AccountManager::PROPERTY_ADDRESS:
543
-			case AccountManager::PROPERTY_WEBSITE:
544
-			case AccountManager::PROPERTY_TWITTER:
545
-				$userAccount = $this->accountManager->getUser($targetUser);
546
-				if ($userAccount[$key]['value'] !== $value) {
547
-					$userAccount[$key]['value'] = $value;
548
-					$this->accountManager->updateUser($targetUser, $userAccount);
549
-				}
550
-				break;
551
-			default:
552
-				throw new OCSException('', 103);
553
-		}
554
-		return new DataResponse();
555
-	}
556
-
557
-	/**
558
-	 * @PasswordConfirmationRequired
559
-	 * @NoAdminRequired
560
-	 *
561
-	 * @param string $userId
562
-	 * @return DataResponse
563
-	 * @throws OCSException
564
-	 */
565
-	public function deleteUser(string $userId): DataResponse {
566
-		$currentLoggedInUser = $this->userSession->getUser();
567
-
568
-		$targetUser = $this->userManager->get($userId);
569
-
570
-		if ($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
571
-			throw new OCSException('', 101);
572
-		}
573
-
574
-		// If not permitted
575
-		$subAdminManager = $this->groupManager->getSubAdmin();
576
-		if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
577
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
578
-		}
579
-
580
-		// Go ahead with the delete
581
-		if ($targetUser->delete()) {
582
-			return new DataResponse();
583
-		} else {
584
-			throw new OCSException('', 101);
585
-		}
586
-	}
587
-
588
-	/**
589
-	 * @PasswordConfirmationRequired
590
-	 * @NoAdminRequired
591
-	 *
592
-	 * @param string $userId
593
-	 * @return DataResponse
594
-	 * @throws OCSException
595
-	 * @throws OCSForbiddenException
596
-	 */
597
-	public function disableUser(string $userId): DataResponse {
598
-		return $this->setEnabled($userId, false);
599
-	}
600
-
601
-	/**
602
-	 * @PasswordConfirmationRequired
603
-	 * @NoAdminRequired
604
-	 *
605
-	 * @param string $userId
606
-	 * @return DataResponse
607
-	 * @throws OCSException
608
-	 * @throws OCSForbiddenException
609
-	 */
610
-	public function enableUser(string $userId): DataResponse {
611
-		return $this->setEnabled($userId, true);
612
-	}
613
-
614
-	/**
615
-	 * @param string $userId
616
-	 * @param bool $value
617
-	 * @return DataResponse
618
-	 * @throws OCSException
619
-	 */
620
-	private function setEnabled(string $userId, bool $value): DataResponse {
621
-		$currentLoggedInUser = $this->userSession->getUser();
622
-
623
-		$targetUser = $this->userManager->get($userId);
624
-		if ($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
625
-			throw new OCSException('', 101);
626
-		}
627
-
628
-		// If not permitted
629
-		$subAdminManager = $this->groupManager->getSubAdmin();
630
-		if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
631
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
632
-		}
633
-
634
-		// enable/disable the user now
635
-		$targetUser->setEnabled($value);
636
-		return new DataResponse();
637
-	}
638
-
639
-	/**
640
-	 * @NoAdminRequired
641
-	 * @NoSubAdminRequired
642
-	 *
643
-	 * @param string $userId
644
-	 * @return DataResponse
645
-	 * @throws OCSException
646
-	 */
647
-	public function getUsersGroups(string $userId): DataResponse {
648
-		$loggedInUser = $this->userSession->getUser();
649
-
650
-		$targetUser = $this->userManager->get($userId);
651
-		if ($targetUser === null) {
652
-			throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
653
-		}
654
-
655
-		if ($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) {
656
-			// Self lookup or admin lookup
657
-			return new DataResponse([
658
-				'groups' => $this->groupManager->getUserGroupIds($targetUser)
659
-			]);
660
-		} else {
661
-			$subAdminManager = $this->groupManager->getSubAdmin();
662
-
663
-			// Looking up someone else
664
-			if ($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) {
665
-				// Return the group that the method caller is subadmin of for the user in question
666
-				/** @var IGroup[] $getSubAdminsGroups */
667
-				$getSubAdminsGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
668
-				foreach ($getSubAdminsGroups as $key => $group) {
669
-					$getSubAdminsGroups[$key] = $group->getGID();
670
-				}
671
-				$groups = array_intersect(
672
-					$getSubAdminsGroups,
673
-					$this->groupManager->getUserGroupIds($targetUser)
674
-				);
675
-				return new DataResponse(['groups' => $groups]);
676
-			} else {
677
-				// Not permitted
678
-				throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
679
-			}
680
-		}
681
-
682
-	}
683
-
684
-	/**
685
-	 * @PasswordConfirmationRequired
686
-	 * @NoAdminRequired
687
-	 *
688
-	 * @param string $userId
689
-	 * @param string $groupid
690
-	 * @return DataResponse
691
-	 * @throws OCSException
692
-	 */
693
-	public function addToGroup(string $userId, string $groupid = ''): DataResponse {
694
-		if ($groupid === '') {
695
-			throw new OCSException('', 101);
696
-		}
697
-
698
-		$group = $this->groupManager->get($groupid);
699
-		$targetUser = $this->userManager->get($userId);
700
-		if ($group === null) {
701
-			throw new OCSException('', 102);
702
-		}
703
-		if ($targetUser === null) {
704
-			throw new OCSException('', 103);
705
-		}
706
-
707
-		// If they're not an admin, check they are a subadmin of the group in question
708
-		$loggedInUser = $this->userSession->getUser();
709
-		$subAdminManager = $this->groupManager->getSubAdmin();
710
-		if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
711
-			throw new OCSException('', 104);
712
-		}
713
-
714
-		// Add user to group
715
-		$group->addUser($targetUser);
716
-		return new DataResponse();
717
-	}
718
-
719
-	/**
720
-	 * @PasswordConfirmationRequired
721
-	 * @NoAdminRequired
722
-	 *
723
-	 * @param string $userId
724
-	 * @param string $groupid
725
-	 * @return DataResponse
726
-	 * @throws OCSException
727
-	 */
728
-	public function removeFromGroup(string $userId, string $groupid): DataResponse {
729
-		$loggedInUser = $this->userSession->getUser();
730
-
731
-		if ($groupid === null || trim($groupid) === '') {
732
-			throw new OCSException('', 101);
733
-		}
734
-
735
-		$group = $this->groupManager->get($groupid);
736
-		if ($group === null) {
737
-			throw new OCSException('', 102);
738
-		}
739
-
740
-		$targetUser = $this->userManager->get($userId);
741
-		if ($targetUser === null) {
742
-			throw new OCSException('', 103);
743
-		}
744
-
745
-		// If they're not an admin, check they are a subadmin of the group in question
746
-		$subAdminManager = $this->groupManager->getSubAdmin();
747
-		if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
748
-			throw new OCSException('', 104);
749
-		}
750
-
751
-		// Check they aren't removing themselves from 'admin' or their 'subadmin; group
752
-		if ($targetUser->getUID() === $loggedInUser->getUID()) {
753
-			if ($this->groupManager->isAdmin($loggedInUser->getUID())) {
754
-				if ($group->getGID() === 'admin') {
755
-					throw new OCSException('Cannot remove yourself from the admin group', 105);
756
-				}
757
-			} else {
758
-				// Not an admin, so the user must be a subadmin of this group, but that is not allowed.
759
-				throw new OCSException('Cannot remove yourself from this group as you are a SubAdmin', 105);
760
-			}
761
-
762
-		} else if (!$this->groupManager->isAdmin($loggedInUser->getUID())) {
763
-			/** @var IGroup[] $subAdminGroups */
764
-			$subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
765
-			$subAdminGroups = array_map(function (IGroup $subAdminGroup) {
766
-				return $subAdminGroup->getGID();
767
-			}, $subAdminGroups);
768
-			$userGroups = $this->groupManager->getUserGroupIds($targetUser);
769
-			$userSubAdminGroups = array_intersect($subAdminGroups, $userGroups);
770
-
771
-			if (count($userSubAdminGroups) <= 1) {
772
-				// Subadmin must not be able to remove a user from all their subadmin groups.
773
-				throw new OCSException('Cannot remove user from this group as this is the only remaining group you are a SubAdmin of', 105);
774
-			}
775
-		}
776
-
777
-		// Remove user from group
778
-		$group->removeUser($targetUser);
779
-		return new DataResponse();
780
-	}
781
-
782
-	/**
783
-	 * Creates a subadmin
784
-	 *
785
-	 * @PasswordConfirmationRequired
786
-	 *
787
-	 * @param string $userId
788
-	 * @param string $groupid
789
-	 * @return DataResponse
790
-	 * @throws OCSException
791
-	 */
792
-	public function addSubAdmin(string $userId, string $groupid): DataResponse {
793
-		$group = $this->groupManager->get($groupid);
794
-		$user = $this->userManager->get($userId);
795
-
796
-		// Check if the user exists
797
-		if ($user === null) {
798
-			throw new OCSException('User does not exist', 101);
799
-		}
800
-		// Check if group exists
801
-		if ($group === null) {
802
-			throw new OCSException('Group does not exist',  102);
803
-		}
804
-		// Check if trying to make subadmin of admin group
805
-		if ($group->getGID() === 'admin') {
806
-			throw new OCSException('Cannot create subadmins for admin group', 103);
807
-		}
808
-
809
-		$subAdminManager = $this->groupManager->getSubAdmin();
810
-
811
-		// We cannot be subadmin twice
812
-		if ($subAdminManager->isSubAdminOfGroup($user, $group)) {
813
-			return new DataResponse();
814
-		}
815
-		// Go
816
-		$subAdminManager->createSubAdmin($user, $group);
817
-		return new DataResponse();
818
-	}
819
-
820
-	/**
821
-	 * Removes a subadmin from a group
822
-	 *
823
-	 * @PasswordConfirmationRequired
824
-	 *
825
-	 * @param string $userId
826
-	 * @param string $groupid
827
-	 * @return DataResponse
828
-	 * @throws OCSException
829
-	 */
830
-	public function removeSubAdmin(string $userId, string $groupid): DataResponse {
831
-		$group = $this->groupManager->get($groupid);
832
-		$user = $this->userManager->get($userId);
833
-		$subAdminManager = $this->groupManager->getSubAdmin();
834
-
835
-		// Check if the user exists
836
-		if ($user === null) {
837
-			throw new OCSException('User does not exist', 101);
838
-		}
839
-		// Check if the group exists
840
-		if ($group === null) {
841
-			throw new OCSException('Group does not exist', 101);
842
-		}
843
-		// Check if they are a subadmin of this said group
844
-		if (!$subAdminManager->isSubAdminOfGroup($user, $group)) {
845
-			throw new OCSException('User is not a subadmin of this group', 102);
846
-		}
847
-
848
-		// Go
849
-		$subAdminManager->deleteSubAdmin($user, $group);
850
-		return new DataResponse();
851
-	}
852
-
853
-	/**
854
-	 * Get the groups a user is a subadmin of
855
-	 *
856
-	 * @param string $userId
857
-	 * @return DataResponse
858
-	 * @throws OCSException
859
-	 */
860
-	public function getUserSubAdminGroups(string $userId): DataResponse {
861
-		$groups = $this->getUserSubAdminGroupsData($userId);
862
-		return new DataResponse($groups);
863
-	}
864
-
865
-	/**
866
-	 * @NoAdminRequired
867
-	 * @PasswordConfirmationRequired
868
-	 *
869
-	 * resend welcome message
870
-	 *
871
-	 * @param string $userId
872
-	 * @return DataResponse
873
-	 * @throws OCSException
874
-	 */
875
-	public function resendWelcomeMessage(string $userId): DataResponse {
876
-		$currentLoggedInUser = $this->userSession->getUser();
877
-
878
-		$targetUser = $this->userManager->get($userId);
879
-		if ($targetUser === null) {
880
-			throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
881
-		}
882
-
883
-		// Check if admin / subadmin
884
-		$subAdminManager = $this->groupManager->getSubAdmin();
885
-		if (!$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
886
-			&& !$this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
887
-			// No rights
888
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
889
-		}
890
-
891
-		$email = $targetUser->getEMailAddress();
892
-		if ($email === '' || $email === null) {
893
-			throw new OCSException('Email address not available', 101);
894
-		}
895
-
896
-		try {
897
-			$emailTemplate = $this->newUserMailHelper->generateTemplate($targetUser, false);
898
-			$this->newUserMailHelper->sendMail($targetUser, $emailTemplate);
899
-		} catch(\Exception $e) {
900
-			$this->logger->logException($e, [
901
-				'message' => "Can't send new user mail to $email",
902
-				'level' => ILogger::ERROR,
903
-				'app' => 'settings',
904
-			]);
905
-			throw new OCSException('Sending email failed', 102);
906
-		}
907
-
908
-		return new DataResponse();
909
-	}
57
+    /** @var IAppManager */
58
+    private $appManager;
59
+    /** @var ILogger */
60
+    private $logger;
61
+    /** @var IFactory */
62
+    private $l10nFactory;
63
+    /** @var NewUserMailHelper */
64
+    private $newUserMailHelper;
65
+    /** @var FederatedFileSharingFactory */
66
+    private $federatedFileSharingFactory;
67
+    /** @var ISecureRandom */
68
+    private $secureRandom;
69
+
70
+    /**
71
+     * @param string $appName
72
+     * @param IRequest $request
73
+     * @param IUserManager $userManager
74
+     * @param IConfig $config
75
+     * @param IAppManager $appManager
76
+     * @param IGroupManager $groupManager
77
+     * @param IUserSession $userSession
78
+     * @param AccountManager $accountManager
79
+     * @param ILogger $logger
80
+     * @param IFactory $l10nFactory
81
+     * @param NewUserMailHelper $newUserMailHelper
82
+     * @param FederatedFileSharingFactory $federatedFileSharingFactory
83
+     * @param ISecureRandom $secureRandom
84
+     */
85
+    public function __construct(string $appName,
86
+                                IRequest $request,
87
+                                IUserManager $userManager,
88
+                                IConfig $config,
89
+                                IAppManager $appManager,
90
+                                IGroupManager $groupManager,
91
+                                IUserSession $userSession,
92
+                                AccountManager $accountManager,
93
+                                ILogger $logger,
94
+                                IFactory $l10nFactory,
95
+                                NewUserMailHelper $newUserMailHelper,
96
+                                FederatedFileSharingFactory $federatedFileSharingFactory,
97
+                                ISecureRandom $secureRandom) {
98
+        parent::__construct($appName,
99
+                            $request,
100
+                            $userManager,
101
+                            $config,
102
+                            $groupManager,
103
+                            $userSession,
104
+                            $accountManager);
105
+
106
+        $this->appManager = $appManager;
107
+        $this->logger = $logger;
108
+        $this->l10nFactory = $l10nFactory;
109
+        $this->newUserMailHelper = $newUserMailHelper;
110
+        $this->federatedFileSharingFactory = $federatedFileSharingFactory;
111
+        $this->secureRandom = $secureRandom;
112
+    }
113
+
114
+    /**
115
+     * @NoAdminRequired
116
+     *
117
+     * returns a list of users
118
+     *
119
+     * @param string $search
120
+     * @param int $limit
121
+     * @param int $offset
122
+     * @return DataResponse
123
+     */
124
+    public function getUsers(string $search = '', $limit = null, $offset = 0): DataResponse {
125
+        $user = $this->userSession->getUser();
126
+        $users = [];
127
+
128
+        // Admin? Or SubAdmin?
129
+        $uid = $user->getUID();
130
+        $subAdminManager = $this->groupManager->getSubAdmin();
131
+        if ($this->groupManager->isAdmin($uid)){
132
+            $users = $this->userManager->search($search, $limit, $offset);
133
+        } else if ($subAdminManager->isSubAdmin($user)) {
134
+            $subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
135
+            foreach ($subAdminOfGroups as $key => $group) {
136
+                $subAdminOfGroups[$key] = $group->getGID();
137
+            }
138
+
139
+            $users = [];
140
+            foreach ($subAdminOfGroups as $group) {
141
+                $users = array_merge($users, $this->groupManager->displayNamesInGroup($group, $search, $limit, $offset));
142
+            }
143
+        }
144
+
145
+        $users = array_keys($users);
146
+
147
+        return new DataResponse([
148
+            'users' => $users
149
+        ]);
150
+    }
151
+
152
+    /**
153
+     * @NoAdminRequired
154
+     *
155
+     * returns a list of users and their data
156
+     */
157
+    public function getUsersDetails(string $search = '', $limit = null, $offset = 0): DataResponse {
158
+        $currentUser = $this->userSession->getUser();
159
+        $users = [];
160
+
161
+        // Admin? Or SubAdmin?
162
+        $uid = $currentUser->getUID();
163
+        $subAdminManager = $this->groupManager->getSubAdmin();
164
+        if ($this->groupManager->isAdmin($uid)){
165
+            $users = $this->userManager->search($search, $limit, $offset);
166
+            $users = array_keys($users);
167
+        } else if ($subAdminManager->isSubAdmin($currentUser)) {
168
+            $subAdminOfGroups = $subAdminManager->getSubAdminsGroups($currentUser);
169
+            foreach ($subAdminOfGroups as $key => $group) {
170
+                $subAdminOfGroups[$key] = $group->getGID();
171
+            }
172
+
173
+            $users = [];
174
+            foreach ($subAdminOfGroups as $group) {
175
+                $users[] = array_keys($this->groupManager->displayNamesInGroup($group, $search, $limit, $offset));
176
+            }
177
+            $users = array_merge(...$users);
178
+        }
179
+
180
+        $usersDetails = [];
181
+        foreach ($users as $userId) {
182
+            $userId = (string) $userId;
183
+            $userData = $this->getUserData($userId);
184
+            // Do not insert empty entry
185
+            if (!empty($userData)) {
186
+                $usersDetails[$userId] = $userData;
187
+            } else {
188
+                // Logged user does not have permissions to see this user
189
+                // only showing its id
190
+                $usersDetails[$userId] = ['id' => $userId];
191
+            }
192
+        }
193
+
194
+        return new DataResponse([
195
+            'users' => $usersDetails
196
+        ]);
197
+    }
198
+
199
+    /**
200
+     * @PasswordConfirmationRequired
201
+     * @NoAdminRequired
202
+     *
203
+     * @param string $userid
204
+     * @param string $password
205
+     * @param string $displayName
206
+     * @param string $email
207
+     * @param array $groups
208
+     * @param array $subadmin
209
+     * @param string $quota
210
+     * @param string $language
211
+     * @return DataResponse
212
+     * @throws OCSException
213
+     */
214
+    public function addUser(string $userid,
215
+                            string $password = '',
216
+                            string $displayName = '',
217
+                            string $email = '',
218
+                            array $groups = [],
219
+                            array $subadmin = [],
220
+                            string $quota = '',
221
+                            string $language = ''): DataResponse {
222
+        $user = $this->userSession->getUser();
223
+        $isAdmin = $this->groupManager->isAdmin($user->getUID());
224
+        $subAdminManager = $this->groupManager->getSubAdmin();
225
+
226
+        if ($this->userManager->userExists($userid)) {
227
+            $this->logger->error('Failed addUser attempt: User already exists.', ['app' => 'ocs_api']);
228
+            throw new OCSException('User already exists', 102);
229
+        }
230
+
231
+        if ($groups !== []) {
232
+            foreach ($groups as $group) {
233
+                if (!$this->groupManager->groupExists($group)) {
234
+                    throw new OCSException('group '.$group.' does not exist', 104);
235
+                }
236
+                if (!$isAdmin && !$subAdminManager->isSubAdminOfGroup($user, $this->groupManager->get($group))) {
237
+                    throw new OCSException('insufficient privileges for group '. $group, 105);
238
+                }
239
+            }
240
+        } else {
241
+            if (!$isAdmin) {
242
+                throw new OCSException('no group specified (required for subadmins)', 106);
243
+            }
244
+        }
245
+
246
+        $subadminGroups = [];
247
+        if ($subadmin !== []) {
248
+            foreach ($subadmin as $groupid) {
249
+                $group = $this->groupManager->get($groupid);
250
+                // Check if group exists
251
+                if ($group === null) {
252
+                    throw new OCSException('Subadmin group does not exist',  102);
253
+                }
254
+                // Check if trying to make subadmin of admin group
255
+                if ($group->getGID() === 'admin') {
256
+                    throw new OCSException('Cannot create subadmins for admin group', 103);
257
+                }
258
+                // Check if has permission to promote subadmins
259
+                if (!$subAdminManager->isSubAdminOfGroup($user, $group) && !$isAdmin) {
260
+                    throw new OCSForbiddenException('No permissions to promote subadmins');
261
+                }
262
+                $subadminGroups[] = $group;
263
+            }
264
+        }
265
+
266
+        $generatePasswordResetToken = false;
267
+        if ($password === '') {
268
+            if ($email === '') {
269
+                throw new OCSException('To send a password link to the user an email address is required.', 108);
270
+            }
271
+
272
+            $password = $this->secureRandom->generate(10);
273
+            // Make sure we pass the password_policy
274
+            $password .= $this->secureRandom->generate(2, '$!.,;:-~+*[]{}()');
275
+            $generatePasswordResetToken = true;
276
+        }
277
+
278
+        try {
279
+            $newUser = $this->userManager->createUser($userid, $password);
280
+            $this->logger->info('Successful addUser call with userid: ' . $userid, ['app' => 'ocs_api']);
281
+
282
+            foreach ($groups as $group) {
283
+                $this->groupManager->get($group)->addUser($newUser);
284
+                $this->logger->info('Added userid ' . $userid . ' to group ' . $group, ['app' => 'ocs_api']);
285
+            }
286
+            foreach ($subadminGroups as $group) {
287
+                $subAdminManager->createSubAdmin($newUser, $group);
288
+            }
289
+
290
+            if ($displayName !== '') {
291
+                $this->editUser($userid, 'display', $displayName);
292
+            }
293
+
294
+            if ($quota !== '') {
295
+                $this->editUser($userid, 'quota', $quota);
296
+            }
297
+
298
+            if ($language !== '') {
299
+                $this->editUser($userid, 'language', $language);
300
+            }
301
+
302
+            // Send new user mail only if a mail is set
303
+            if ($email !== '') {
304
+                $newUser->setEMailAddress($email);
305
+                try {
306
+                    $emailTemplate = $this->newUserMailHelper->generateTemplate($newUser, $generatePasswordResetToken);
307
+                    $this->newUserMailHelper->sendMail($newUser, $emailTemplate);
308
+                } catch (\Exception $e) {
309
+                    $this->logger->logException($e, [
310
+                        'message' => "Can't send new user mail to $email",
311
+                        'level' => ILogger::ERROR,
312
+                        'app' => 'ocs_api',
313
+                    ]);
314
+                    throw new OCSException('Unable to send the invitation mail', 109);
315
+                }
316
+            }
317
+
318
+            return new DataResponse();
319
+
320
+        } catch (HintException $e ) {
321
+            $this->logger->logException($e, [
322
+                'message' => 'Failed addUser attempt with hint exception.',
323
+                'level' => ILogger::WARN,
324
+                'app' => 'ocs_api',
325
+            ]);
326
+            throw new OCSException($e->getHint(), 107);
327
+        } catch (\Exception $e) {
328
+            $this->logger->logException($e, [
329
+                'message' => 'Failed addUser attempt with exception.',
330
+                'level' => ILogger::ERROR,
331
+                'app' => 'ocs_api',
332
+            ]);
333
+            throw new OCSException('Bad request', 101);
334
+        }
335
+    }
336
+
337
+    /**
338
+     * @NoAdminRequired
339
+     * @NoSubAdminRequired
340
+     *
341
+     * gets user info
342
+     *
343
+     * @param string $userId
344
+     * @return DataResponse
345
+     * @throws OCSException
346
+     */
347
+    public function getUser(string $userId): DataResponse {
348
+        $data = $this->getUserData($userId);
349
+        // getUserData returns empty array if not enough permissions
350
+        if (empty($data)) {
351
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
352
+        }
353
+        return new DataResponse($data);
354
+    }
355
+
356
+    /**
357
+     * @NoAdminRequired
358
+     * @NoSubAdminRequired
359
+     *
360
+     * gets user info from the currently logged in user
361
+     *
362
+     * @return DataResponse
363
+     * @throws OCSException
364
+     */
365
+    public function getCurrentUser(): DataResponse {
366
+        $user = $this->userSession->getUser();
367
+        if ($user) {
368
+            $data =  $this->getUserData($user->getUID());
369
+            // rename "displayname" to "display-name" only for this call to keep
370
+            // the API stable.
371
+            $data['display-name'] = $data['displayname'];
372
+            unset($data['displayname']);
373
+            return new DataResponse($data);
374
+
375
+        }
376
+
377
+        throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
378
+    }
379
+
380
+    /**
381
+     * @NoAdminRequired
382
+     * @NoSubAdminRequired
383
+     */
384
+    public function getEditableFields(): DataResponse {
385
+        $permittedFields = [];
386
+
387
+        // Editing self (display, email)
388
+        if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
389
+            $permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
390
+            $permittedFields[] = AccountManager::PROPERTY_EMAIL;
391
+        }
392
+
393
+        if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
394
+            $federatedFileSharing = $this->federatedFileSharingFactory->get();
395
+            $shareProvider = $federatedFileSharing->getFederatedShareProvider();
396
+            if ($shareProvider->isLookupServerUploadEnabled()) {
397
+                $permittedFields[] = AccountManager::PROPERTY_PHONE;
398
+                $permittedFields[] = AccountManager::PROPERTY_ADDRESS;
399
+                $permittedFields[] = AccountManager::PROPERTY_WEBSITE;
400
+                $permittedFields[] = AccountManager::PROPERTY_TWITTER;
401
+            }
402
+        }
403
+
404
+        return new DataResponse($permittedFields);
405
+    }
406
+
407
+    /**
408
+     * @NoAdminRequired
409
+     * @NoSubAdminRequired
410
+     * @PasswordConfirmationRequired
411
+     *
412
+     * edit users
413
+     *
414
+     * @param string $userId
415
+     * @param string $key
416
+     * @param string $value
417
+     * @return DataResponse
418
+     * @throws OCSException
419
+     */
420
+    public function editUser(string $userId, string $key, string $value): DataResponse {
421
+        $currentLoggedInUser = $this->userSession->getUser();
422
+
423
+        $targetUser = $this->userManager->get($userId);
424
+        if ($targetUser === null) {
425
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
426
+        }
427
+
428
+        $permittedFields = [];
429
+        if ($targetUser->getUID() === $currentLoggedInUser->getUID()) {
430
+            // Editing self (display, email)
431
+            if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
432
+                $permittedFields[] = 'display';
433
+                $permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
434
+                $permittedFields[] = AccountManager::PROPERTY_EMAIL;
435
+            }
436
+
437
+            $permittedFields[] = 'password';
438
+            if ($this->config->getSystemValue('force_language', false) === false ||
439
+                $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
440
+                $permittedFields[] = 'language';
441
+            }
442
+
443
+            if ($this->config->getSystemValue('force_locale', false) === false ||
444
+                $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
445
+                $permittedFields[] = 'locale';
446
+            }
447
+
448
+            if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
449
+                $federatedFileSharing = new \OCA\FederatedFileSharing\AppInfo\Application();
450
+                $shareProvider = $federatedFileSharing->getFederatedShareProvider();
451
+                if ($shareProvider->isLookupServerUploadEnabled()) {
452
+                    $permittedFields[] = AccountManager::PROPERTY_PHONE;
453
+                    $permittedFields[] = AccountManager::PROPERTY_ADDRESS;
454
+                    $permittedFields[] = AccountManager::PROPERTY_WEBSITE;
455
+                    $permittedFields[] = AccountManager::PROPERTY_TWITTER;
456
+                }
457
+            }
458
+
459
+            // If admin they can edit their own quota
460
+            if ($this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
461
+                $permittedFields[] = 'quota';
462
+            }
463
+        } else {
464
+            // Check if admin / subadmin
465
+            $subAdminManager = $this->groupManager->getSubAdmin();
466
+            if ($subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
467
+            || $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
468
+                // They have permissions over the user
469
+                $permittedFields[] = 'display';
470
+                $permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
471
+                $permittedFields[] = AccountManager::PROPERTY_EMAIL;
472
+                $permittedFields[] = 'password';
473
+                $permittedFields[] = 'language';
474
+                $permittedFields[] = 'locale';
475
+                $permittedFields[] = AccountManager::PROPERTY_PHONE;
476
+                $permittedFields[] = AccountManager::PROPERTY_ADDRESS;
477
+                $permittedFields[] = AccountManager::PROPERTY_WEBSITE;
478
+                $permittedFields[] = AccountManager::PROPERTY_TWITTER;
479
+                $permittedFields[] = 'quota';
480
+            } else {
481
+                // No rights
482
+                throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
483
+            }
484
+        }
485
+        // Check if permitted to edit this field
486
+        if (!in_array($key, $permittedFields)) {
487
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
488
+        }
489
+        // Process the edit
490
+        switch($key) {
491
+            case 'display':
492
+            case AccountManager::PROPERTY_DISPLAYNAME:
493
+                $targetUser->setDisplayName($value);
494
+                break;
495
+            case 'quota':
496
+                $quota = $value;
497
+                if ($quota !== 'none' && $quota !== 'default') {
498
+                    if (is_numeric($quota)) {
499
+                        $quota = (float) $quota;
500
+                    } else {
501
+                        $quota = \OCP\Util::computerFileSize($quota);
502
+                    }
503
+                    if ($quota === false) {
504
+                        throw new OCSException('Invalid quota value '.$value, 103);
505
+                    }
506
+                    if ($quota === -1) {
507
+                        $quota = 'none';
508
+                    } else {
509
+                        $quota = \OCP\Util::humanFileSize($quota);
510
+                    }
511
+                }
512
+                $targetUser->setQuota($quota);
513
+                break;
514
+            case 'password':
515
+                try {
516
+                    $targetUser->setPassword($value);
517
+                } catch (HintException $e) { // password policy error
518
+                    throw new OCSException($e->getMessage(), 103);
519
+                }
520
+                break;
521
+            case 'language':
522
+                $languagesCodes = $this->l10nFactory->findAvailableLanguages();
523
+                if (!in_array($value, $languagesCodes, true) && $value !== 'en') {
524
+                    throw new OCSException('Invalid language', 102);
525
+                }
526
+                $this->config->setUserValue($targetUser->getUID(), 'core', 'lang', $value);
527
+                break;
528
+            case 'locale':
529
+                if (!$this->l10nFactory->localeExists($value)) {
530
+                    throw new OCSException('Invalid locale', 102);
531
+                }
532
+                $this->config->setUserValue($targetUser->getUID(), 'core', 'locale', $value);
533
+                break;
534
+            case AccountManager::PROPERTY_EMAIL:
535
+                if (filter_var($value, FILTER_VALIDATE_EMAIL) || $value === '') {
536
+                    $targetUser->setEMailAddress($value);
537
+                } else {
538
+                    throw new OCSException('', 102);
539
+                }
540
+                break;
541
+            case AccountManager::PROPERTY_PHONE:
542
+            case AccountManager::PROPERTY_ADDRESS:
543
+            case AccountManager::PROPERTY_WEBSITE:
544
+            case AccountManager::PROPERTY_TWITTER:
545
+                $userAccount = $this->accountManager->getUser($targetUser);
546
+                if ($userAccount[$key]['value'] !== $value) {
547
+                    $userAccount[$key]['value'] = $value;
548
+                    $this->accountManager->updateUser($targetUser, $userAccount);
549
+                }
550
+                break;
551
+            default:
552
+                throw new OCSException('', 103);
553
+        }
554
+        return new DataResponse();
555
+    }
556
+
557
+    /**
558
+     * @PasswordConfirmationRequired
559
+     * @NoAdminRequired
560
+     *
561
+     * @param string $userId
562
+     * @return DataResponse
563
+     * @throws OCSException
564
+     */
565
+    public function deleteUser(string $userId): DataResponse {
566
+        $currentLoggedInUser = $this->userSession->getUser();
567
+
568
+        $targetUser = $this->userManager->get($userId);
569
+
570
+        if ($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
571
+            throw new OCSException('', 101);
572
+        }
573
+
574
+        // If not permitted
575
+        $subAdminManager = $this->groupManager->getSubAdmin();
576
+        if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
577
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
578
+        }
579
+
580
+        // Go ahead with the delete
581
+        if ($targetUser->delete()) {
582
+            return new DataResponse();
583
+        } else {
584
+            throw new OCSException('', 101);
585
+        }
586
+    }
587
+
588
+    /**
589
+     * @PasswordConfirmationRequired
590
+     * @NoAdminRequired
591
+     *
592
+     * @param string $userId
593
+     * @return DataResponse
594
+     * @throws OCSException
595
+     * @throws OCSForbiddenException
596
+     */
597
+    public function disableUser(string $userId): DataResponse {
598
+        return $this->setEnabled($userId, false);
599
+    }
600
+
601
+    /**
602
+     * @PasswordConfirmationRequired
603
+     * @NoAdminRequired
604
+     *
605
+     * @param string $userId
606
+     * @return DataResponse
607
+     * @throws OCSException
608
+     * @throws OCSForbiddenException
609
+     */
610
+    public function enableUser(string $userId): DataResponse {
611
+        return $this->setEnabled($userId, true);
612
+    }
613
+
614
+    /**
615
+     * @param string $userId
616
+     * @param bool $value
617
+     * @return DataResponse
618
+     * @throws OCSException
619
+     */
620
+    private function setEnabled(string $userId, bool $value): DataResponse {
621
+        $currentLoggedInUser = $this->userSession->getUser();
622
+
623
+        $targetUser = $this->userManager->get($userId);
624
+        if ($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
625
+            throw new OCSException('', 101);
626
+        }
627
+
628
+        // If not permitted
629
+        $subAdminManager = $this->groupManager->getSubAdmin();
630
+        if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
631
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
632
+        }
633
+
634
+        // enable/disable the user now
635
+        $targetUser->setEnabled($value);
636
+        return new DataResponse();
637
+    }
638
+
639
+    /**
640
+     * @NoAdminRequired
641
+     * @NoSubAdminRequired
642
+     *
643
+     * @param string $userId
644
+     * @return DataResponse
645
+     * @throws OCSException
646
+     */
647
+    public function getUsersGroups(string $userId): DataResponse {
648
+        $loggedInUser = $this->userSession->getUser();
649
+
650
+        $targetUser = $this->userManager->get($userId);
651
+        if ($targetUser === null) {
652
+            throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
653
+        }
654
+
655
+        if ($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) {
656
+            // Self lookup or admin lookup
657
+            return new DataResponse([
658
+                'groups' => $this->groupManager->getUserGroupIds($targetUser)
659
+            ]);
660
+        } else {
661
+            $subAdminManager = $this->groupManager->getSubAdmin();
662
+
663
+            // Looking up someone else
664
+            if ($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) {
665
+                // Return the group that the method caller is subadmin of for the user in question
666
+                /** @var IGroup[] $getSubAdminsGroups */
667
+                $getSubAdminsGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
668
+                foreach ($getSubAdminsGroups as $key => $group) {
669
+                    $getSubAdminsGroups[$key] = $group->getGID();
670
+                }
671
+                $groups = array_intersect(
672
+                    $getSubAdminsGroups,
673
+                    $this->groupManager->getUserGroupIds($targetUser)
674
+                );
675
+                return new DataResponse(['groups' => $groups]);
676
+            } else {
677
+                // Not permitted
678
+                throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
679
+            }
680
+        }
681
+
682
+    }
683
+
684
+    /**
685
+     * @PasswordConfirmationRequired
686
+     * @NoAdminRequired
687
+     *
688
+     * @param string $userId
689
+     * @param string $groupid
690
+     * @return DataResponse
691
+     * @throws OCSException
692
+     */
693
+    public function addToGroup(string $userId, string $groupid = ''): DataResponse {
694
+        if ($groupid === '') {
695
+            throw new OCSException('', 101);
696
+        }
697
+
698
+        $group = $this->groupManager->get($groupid);
699
+        $targetUser = $this->userManager->get($userId);
700
+        if ($group === null) {
701
+            throw new OCSException('', 102);
702
+        }
703
+        if ($targetUser === null) {
704
+            throw new OCSException('', 103);
705
+        }
706
+
707
+        // If they're not an admin, check they are a subadmin of the group in question
708
+        $loggedInUser = $this->userSession->getUser();
709
+        $subAdminManager = $this->groupManager->getSubAdmin();
710
+        if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
711
+            throw new OCSException('', 104);
712
+        }
713
+
714
+        // Add user to group
715
+        $group->addUser($targetUser);
716
+        return new DataResponse();
717
+    }
718
+
719
+    /**
720
+     * @PasswordConfirmationRequired
721
+     * @NoAdminRequired
722
+     *
723
+     * @param string $userId
724
+     * @param string $groupid
725
+     * @return DataResponse
726
+     * @throws OCSException
727
+     */
728
+    public function removeFromGroup(string $userId, string $groupid): DataResponse {
729
+        $loggedInUser = $this->userSession->getUser();
730
+
731
+        if ($groupid === null || trim($groupid) === '') {
732
+            throw new OCSException('', 101);
733
+        }
734
+
735
+        $group = $this->groupManager->get($groupid);
736
+        if ($group === null) {
737
+            throw new OCSException('', 102);
738
+        }
739
+
740
+        $targetUser = $this->userManager->get($userId);
741
+        if ($targetUser === null) {
742
+            throw new OCSException('', 103);
743
+        }
744
+
745
+        // If they're not an admin, check they are a subadmin of the group in question
746
+        $subAdminManager = $this->groupManager->getSubAdmin();
747
+        if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
748
+            throw new OCSException('', 104);
749
+        }
750
+
751
+        // Check they aren't removing themselves from 'admin' or their 'subadmin; group
752
+        if ($targetUser->getUID() === $loggedInUser->getUID()) {
753
+            if ($this->groupManager->isAdmin($loggedInUser->getUID())) {
754
+                if ($group->getGID() === 'admin') {
755
+                    throw new OCSException('Cannot remove yourself from the admin group', 105);
756
+                }
757
+            } else {
758
+                // Not an admin, so the user must be a subadmin of this group, but that is not allowed.
759
+                throw new OCSException('Cannot remove yourself from this group as you are a SubAdmin', 105);
760
+            }
761
+
762
+        } else if (!$this->groupManager->isAdmin($loggedInUser->getUID())) {
763
+            /** @var IGroup[] $subAdminGroups */
764
+            $subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
765
+            $subAdminGroups = array_map(function (IGroup $subAdminGroup) {
766
+                return $subAdminGroup->getGID();
767
+            }, $subAdminGroups);
768
+            $userGroups = $this->groupManager->getUserGroupIds($targetUser);
769
+            $userSubAdminGroups = array_intersect($subAdminGroups, $userGroups);
770
+
771
+            if (count($userSubAdminGroups) <= 1) {
772
+                // Subadmin must not be able to remove a user from all their subadmin groups.
773
+                throw new OCSException('Cannot remove user from this group as this is the only remaining group you are a SubAdmin of', 105);
774
+            }
775
+        }
776
+
777
+        // Remove user from group
778
+        $group->removeUser($targetUser);
779
+        return new DataResponse();
780
+    }
781
+
782
+    /**
783
+     * Creates a subadmin
784
+     *
785
+     * @PasswordConfirmationRequired
786
+     *
787
+     * @param string $userId
788
+     * @param string $groupid
789
+     * @return DataResponse
790
+     * @throws OCSException
791
+     */
792
+    public function addSubAdmin(string $userId, string $groupid): DataResponse {
793
+        $group = $this->groupManager->get($groupid);
794
+        $user = $this->userManager->get($userId);
795
+
796
+        // Check if the user exists
797
+        if ($user === null) {
798
+            throw new OCSException('User does not exist', 101);
799
+        }
800
+        // Check if group exists
801
+        if ($group === null) {
802
+            throw new OCSException('Group does not exist',  102);
803
+        }
804
+        // Check if trying to make subadmin of admin group
805
+        if ($group->getGID() === 'admin') {
806
+            throw new OCSException('Cannot create subadmins for admin group', 103);
807
+        }
808
+
809
+        $subAdminManager = $this->groupManager->getSubAdmin();
810
+
811
+        // We cannot be subadmin twice
812
+        if ($subAdminManager->isSubAdminOfGroup($user, $group)) {
813
+            return new DataResponse();
814
+        }
815
+        // Go
816
+        $subAdminManager->createSubAdmin($user, $group);
817
+        return new DataResponse();
818
+    }
819
+
820
+    /**
821
+     * Removes a subadmin from a group
822
+     *
823
+     * @PasswordConfirmationRequired
824
+     *
825
+     * @param string $userId
826
+     * @param string $groupid
827
+     * @return DataResponse
828
+     * @throws OCSException
829
+     */
830
+    public function removeSubAdmin(string $userId, string $groupid): DataResponse {
831
+        $group = $this->groupManager->get($groupid);
832
+        $user = $this->userManager->get($userId);
833
+        $subAdminManager = $this->groupManager->getSubAdmin();
834
+
835
+        // Check if the user exists
836
+        if ($user === null) {
837
+            throw new OCSException('User does not exist', 101);
838
+        }
839
+        // Check if the group exists
840
+        if ($group === null) {
841
+            throw new OCSException('Group does not exist', 101);
842
+        }
843
+        // Check if they are a subadmin of this said group
844
+        if (!$subAdminManager->isSubAdminOfGroup($user, $group)) {
845
+            throw new OCSException('User is not a subadmin of this group', 102);
846
+        }
847
+
848
+        // Go
849
+        $subAdminManager->deleteSubAdmin($user, $group);
850
+        return new DataResponse();
851
+    }
852
+
853
+    /**
854
+     * Get the groups a user is a subadmin of
855
+     *
856
+     * @param string $userId
857
+     * @return DataResponse
858
+     * @throws OCSException
859
+     */
860
+    public function getUserSubAdminGroups(string $userId): DataResponse {
861
+        $groups = $this->getUserSubAdminGroupsData($userId);
862
+        return new DataResponse($groups);
863
+    }
864
+
865
+    /**
866
+     * @NoAdminRequired
867
+     * @PasswordConfirmationRequired
868
+     *
869
+     * resend welcome message
870
+     *
871
+     * @param string $userId
872
+     * @return DataResponse
873
+     * @throws OCSException
874
+     */
875
+    public function resendWelcomeMessage(string $userId): DataResponse {
876
+        $currentLoggedInUser = $this->userSession->getUser();
877
+
878
+        $targetUser = $this->userManager->get($userId);
879
+        if ($targetUser === null) {
880
+            throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
881
+        }
882
+
883
+        // Check if admin / subadmin
884
+        $subAdminManager = $this->groupManager->getSubAdmin();
885
+        if (!$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
886
+            && !$this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
887
+            // No rights
888
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
889
+        }
890
+
891
+        $email = $targetUser->getEMailAddress();
892
+        if ($email === '' || $email === null) {
893
+            throw new OCSException('Email address not available', 101);
894
+        }
895
+
896
+        try {
897
+            $emailTemplate = $this->newUserMailHelper->generateTemplate($targetUser, false);
898
+            $this->newUserMailHelper->sendMail($targetUser, $emailTemplate);
899
+        } catch(\Exception $e) {
900
+            $this->logger->logException($e, [
901
+                'message' => "Can't send new user mail to $email",
902
+                'level' => ILogger::ERROR,
903
+                'app' => 'settings',
904
+            ]);
905
+            throw new OCSException('Sending email failed', 102);
906
+        }
907
+
908
+        return new DataResponse();
909
+    }
910 910
 }
Please login to merge, or discard this patch.