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