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