Completed
Pull Request — master (#8824)
by John
14:22
created
settings/templates/settings.php 2 patches
Indentation   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -13,7 +13,6 @@  discard block
 block discarded – undo
13 13
  * $tmpl = new OC_Template('settings', 'settings', 'user');
14 14
  * $tmpl->assign('serverData', $serverData);
15 15
  * $tmpl->printPage();
16
-
17 16
  */
18 17
 
19 18
 script('settings', 'main');
@@ -21,7 +20,7 @@  discard block
 block discarded – undo
21 20
 
22 21
 // Did we have some data to inject ?
23 22
 if(is_array($_['serverData'])) {
24
-	$serverData = json_encode($_['serverData']);
23
+    $serverData = json_encode($_['serverData']);
25 24
 ?>
26 25
 <span id="serverData" data-server="<?php p($serverData);?>"></span>
27 26
 <?php } ?>
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -20,8 +20,8 @@
 block discarded – undo
20 20
 style('settings', 'settings');
21 21
 
22 22
 // Did we have some data to inject ?
23
-if(is_array($_['serverData'])) {
23
+if (is_array($_['serverData'])) {
24 24
 	$serverData = json_encode($_['serverData']);
25 25
 ?>
26
-<span id="serverData" data-server="<?php p($serverData);?>"></span>
26
+<span id="serverData" data-server="<?php p($serverData); ?>"></span>
27 27
 <?php } ?>
Please login to merge, or discard this patch.
settings/main.php 1 patch
Indentation   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -20,5 +20,5 @@
 block discarded – undo
20 20
  *
21 21
  */
22 22
 
23
- $tmpl = new OC_Template("settings", "settings", "user");
24
- $tmpl->printPage();
23
+    $tmpl = new OC_Template("settings", "settings", "user");
24
+    $tmpl->printPage();
Please login to merge, or discard this patch.
settings/routes.php 1 patch
Indentation   +52 added lines, -52 removed lines patch added patch discarded remove patch
@@ -38,76 +38,76 @@
 block discarded – undo
38 38
 
39 39
 $application = new Application();
40 40
 $application->registerRoutes($this, [
41
-	'resources' => [
42
-		'users' => ['url' => '/settings/users/users'],
43
-		'AuthSettings' => ['url' => '/settings/personal/authtokens'],
44
-	],
45
-	'routes' => [
46
-		['name' => 'MailSettings#setMailSettings', 'url' => '/settings/admin/mailsettings', 'verb' => 'POST'],
47
-		['name' => 'MailSettings#storeCredentials', 'url' => '/settings/admin/mailsettings/credentials', 'verb' => 'POST'],
48
-		['name' => 'MailSettings#sendTestMail', 'url' => '/settings/admin/mailtest', 'verb' => 'POST'],
49
-		['name' => 'Encryption#startMigration', 'url' => '/settings/admin/startmigration', 'verb' => 'POST'],
50
-		['name' => 'AppSettings#listCategories', 'url' => '/settings/apps/categories', 'verb' => 'GET'],
51
-		['name' => 'AppSettings#viewApps', 'url' => '/settings/apps', 'verb' => 'GET'],
52
-		['name' => 'AppSettings#listApps', 'url' => '/settings/apps/list', 'verb' => 'GET'],
53
-		['name' => 'SecuritySettings#trustedDomains', 'url' => '/settings/admin/security/trustedDomains', 'verb' => 'POST'],
54
-		['name' => 'Users#setDisplayName', 'url' => '/settings/users/{id}/displayName', 'verb' => 'PUT'],
55
-		['name' => 'Users#setEMailAddress', 'url' => '/settings/users/{id}/mailAddress', 'verb' => 'PUT'],
56
-		['name' => 'Users#setUserSettings', 'url' => '/settings/users/{username}/settings', 'verb' => 'PUT'],
57
-		['name' => 'Users#getVerificationCode', 'url' => '/settings/users/{account}/verify', 'verb' => 'GET'],
58
-		['name' => 'Users#setEnabled', 'url' => '/settings/users/{id}/setEnabled', 'verb' => 'POST'],
59
-		['name' => 'Users#stats', 'url' => '/settings/users/stats', 'verb' => 'GET'],
60
-		['name' => 'LogSettings#setLogLevel', 'url' => '/settings/admin/log/level', 'verb' => 'POST'],
61
-		['name' => 'LogSettings#getEntries', 'url' => '/settings/admin/log/entries', 'verb' => 'GET'],
62
-		['name' => 'LogSettings#download', 'url' => '/settings/admin/log/download', 'verb' => 'GET'],
63
-		['name' => 'CheckSetup#check', 'url' => '/settings/ajax/checksetup', 'verb' => 'GET'],
64
-		['name' => 'CheckSetup#getFailedIntegrityCheckFiles', 'url' => '/settings/integrity/failed', 'verb' => 'GET'],
65
-		['name' => 'CheckSetup#rescanFailedIntegrityCheck', 'url' => '/settings/integrity/rescan', 'verb' => 'GET'],
66
-		['name' => 'Certificate#addPersonalRootCertificate', 'url' => '/settings/personal/certificate', 'verb' => 'POST'],
67
-		['name' => 'Certificate#removePersonalRootCertificate', 'url' => '/settings/personal/certificate/{certificateIdentifier}', 'verb' => 'DELETE'],
68
-		['name' => 'Certificate#addSystemRootCertificate', 'url' => '/settings/admin/certificate', 'verb' => 'POST'],
69
-		['name' => 'Certificate#removeSystemRootCertificate', 'url' => '/settings/admin/certificate/{certificateIdentifier}', 'verb' => 'DELETE'],
70
-		['name' => 'PersonalSettings#index', 'url' => '/settings/user/{section}', 'verb' => 'GET', 'defaults' => ['section' => 'personal-info']],
71
-		['name' => 'AdminSettings#index', 'url' => '/settings/admin/{section}', 'verb' => 'GET', 'defaults' => ['section' => 'server']],
72
-		['name' => 'AdminSettings#form', 'url' => '/settings/admin/{section}', 'verb' => 'GET'],
73
-		['name' => 'ChangePassword#changePersonalPassword', 'url' => '/settings/personal/changepassword', 'verb' => 'POST'],
74
-		['name' => 'ChangePassword#changeUserPassword', 'url' => '/settings/users/changepassword', 'verb' => 'POST'],
75
-		['name' => 'Groups#index', 'url' => '/settings/users/groups', 'verb' => 'GET'],
76
-		['name' => 'Groups#show', 'url' => '/settings/users/groups/{id}', 'requirements' => ['id' => '[^?]*'], 'verb' => 'GET'],
77
-		['name' => 'Groups#create', 'url' => '/settings/users/groups', 'verb' => 'POST'],
78
-		['name' => 'Groups#update', 'url' => '/settings/users/groups/{id}', 'requirements' => ['id' => '[^?]*'], 'verb' => 'PUT'],
79
-		['name' => 'Groups#destroy', 'url' => '/settings/users/groups/{id}', 'requirements' => ['id' => '[^?]*'], 'verb' => 'DELETE'],
80
-	]
41
+    'resources' => [
42
+        'users' => ['url' => '/settings/users/users'],
43
+        'AuthSettings' => ['url' => '/settings/personal/authtokens'],
44
+    ],
45
+    'routes' => [
46
+        ['name' => 'MailSettings#setMailSettings', 'url' => '/settings/admin/mailsettings', 'verb' => 'POST'],
47
+        ['name' => 'MailSettings#storeCredentials', 'url' => '/settings/admin/mailsettings/credentials', 'verb' => 'POST'],
48
+        ['name' => 'MailSettings#sendTestMail', 'url' => '/settings/admin/mailtest', 'verb' => 'POST'],
49
+        ['name' => 'Encryption#startMigration', 'url' => '/settings/admin/startmigration', 'verb' => 'POST'],
50
+        ['name' => 'AppSettings#listCategories', 'url' => '/settings/apps/categories', 'verb' => 'GET'],
51
+        ['name' => 'AppSettings#viewApps', 'url' => '/settings/apps', 'verb' => 'GET'],
52
+        ['name' => 'AppSettings#listApps', 'url' => '/settings/apps/list', 'verb' => 'GET'],
53
+        ['name' => 'SecuritySettings#trustedDomains', 'url' => '/settings/admin/security/trustedDomains', 'verb' => 'POST'],
54
+        ['name' => 'Users#setDisplayName', 'url' => '/settings/users/{id}/displayName', 'verb' => 'PUT'],
55
+        ['name' => 'Users#setEMailAddress', 'url' => '/settings/users/{id}/mailAddress', 'verb' => 'PUT'],
56
+        ['name' => 'Users#setUserSettings', 'url' => '/settings/users/{username}/settings', 'verb' => 'PUT'],
57
+        ['name' => 'Users#getVerificationCode', 'url' => '/settings/users/{account}/verify', 'verb' => 'GET'],
58
+        ['name' => 'Users#setEnabled', 'url' => '/settings/users/{id}/setEnabled', 'verb' => 'POST'],
59
+        ['name' => 'Users#stats', 'url' => '/settings/users/stats', 'verb' => 'GET'],
60
+        ['name' => 'LogSettings#setLogLevel', 'url' => '/settings/admin/log/level', 'verb' => 'POST'],
61
+        ['name' => 'LogSettings#getEntries', 'url' => '/settings/admin/log/entries', 'verb' => 'GET'],
62
+        ['name' => 'LogSettings#download', 'url' => '/settings/admin/log/download', 'verb' => 'GET'],
63
+        ['name' => 'CheckSetup#check', 'url' => '/settings/ajax/checksetup', 'verb' => 'GET'],
64
+        ['name' => 'CheckSetup#getFailedIntegrityCheckFiles', 'url' => '/settings/integrity/failed', 'verb' => 'GET'],
65
+        ['name' => 'CheckSetup#rescanFailedIntegrityCheck', 'url' => '/settings/integrity/rescan', 'verb' => 'GET'],
66
+        ['name' => 'Certificate#addPersonalRootCertificate', 'url' => '/settings/personal/certificate', 'verb' => 'POST'],
67
+        ['name' => 'Certificate#removePersonalRootCertificate', 'url' => '/settings/personal/certificate/{certificateIdentifier}', 'verb' => 'DELETE'],
68
+        ['name' => 'Certificate#addSystemRootCertificate', 'url' => '/settings/admin/certificate', 'verb' => 'POST'],
69
+        ['name' => 'Certificate#removeSystemRootCertificate', 'url' => '/settings/admin/certificate/{certificateIdentifier}', 'verb' => 'DELETE'],
70
+        ['name' => 'PersonalSettings#index', 'url' => '/settings/user/{section}', 'verb' => 'GET', 'defaults' => ['section' => 'personal-info']],
71
+        ['name' => 'AdminSettings#index', 'url' => '/settings/admin/{section}', 'verb' => 'GET', 'defaults' => ['section' => 'server']],
72
+        ['name' => 'AdminSettings#form', 'url' => '/settings/admin/{section}', 'verb' => 'GET'],
73
+        ['name' => 'ChangePassword#changePersonalPassword', 'url' => '/settings/personal/changepassword', 'verb' => 'POST'],
74
+        ['name' => 'ChangePassword#changeUserPassword', 'url' => '/settings/users/changepassword', 'verb' => 'POST'],
75
+        ['name' => 'Groups#index', 'url' => '/settings/users/groups', 'verb' => 'GET'],
76
+        ['name' => 'Groups#show', 'url' => '/settings/users/groups/{id}', 'requirements' => ['id' => '[^?]*'], 'verb' => 'GET'],
77
+        ['name' => 'Groups#create', 'url' => '/settings/users/groups', 'verb' => 'POST'],
78
+        ['name' => 'Groups#update', 'url' => '/settings/users/groups/{id}', 'requirements' => ['id' => '[^?]*'], 'verb' => 'PUT'],
79
+        ['name' => 'Groups#destroy', 'url' => '/settings/users/groups/{id}', 'requirements' => ['id' => '[^?]*'], 'verb' => 'DELETE'],
80
+    ]
81 81
 ]);
82 82
 
83 83
 /** @var $this \OCP\Route\IRouter */
84 84
 
85 85
 // Settings pages
86 86
 $this->create('settings_help', '/settings/help')
87
-	->actionInclude('settings/help.php');
87
+    ->actionInclude('settings/help.php');
88 88
 $this->create('settings_users', '/settings/users')
89
-	->actionInclude('settings/users.php');
89
+    ->actionInclude('settings/users.php');
90 90
 // Settings ajax actions
91 91
 // users
92 92
 $this->create('settings_ajax_setquota', '/settings/ajax/setquota.php')
93
-	->actionInclude('settings/ajax/setquota.php');
93
+    ->actionInclude('settings/ajax/setquota.php');
94 94
 $this->create('settings_ajax_togglegroups', '/settings/ajax/togglegroups.php')
95
-	->actionInclude('settings/ajax/togglegroups.php');
95
+    ->actionInclude('settings/ajax/togglegroups.php');
96 96
 $this->create('settings_ajax_togglesubadmins', '/settings/ajax/togglesubadmins.php')
97
-	->actionInclude('settings/ajax/togglesubadmins.php');
97
+    ->actionInclude('settings/ajax/togglesubadmins.php');
98 98
 $this->create('settings_ajax_changegorupname', '/settings/ajax/changegroupname.php')
99
-	->actionInclude('settings/ajax/changegroupname.php');
99
+    ->actionInclude('settings/ajax/changegroupname.php');
100 100
 // apps
101 101
 $this->create('settings_ajax_enableapp', '/settings/ajax/enableapp.php')
102
-	->actionInclude('settings/ajax/enableapp.php');
102
+    ->actionInclude('settings/ajax/enableapp.php');
103 103
 $this->create('settings_ajax_disableapp', '/settings/ajax/disableapp.php')
104
-	->actionInclude('settings/ajax/disableapp.php');
104
+    ->actionInclude('settings/ajax/disableapp.php');
105 105
 $this->create('settings_ajax_updateapp', '/settings/ajax/updateapp.php')
106
-	->actionInclude('settings/ajax/updateapp.php');
106
+    ->actionInclude('settings/ajax/updateapp.php');
107 107
 $this->create('settings_ajax_uninstallapp', '/settings/ajax/uninstallapp.php')
108
-	->actionInclude('settings/ajax/uninstallapp.php');
108
+    ->actionInclude('settings/ajax/uninstallapp.php');
109 109
 $this->create('settings_ajax_navigationdetect', '/settings/ajax/navigationdetect.php')
110
-	->actionInclude('settings/ajax/navigationdetect.php');
110
+    ->actionInclude('settings/ajax/navigationdetect.php');
111 111
 // admin
112 112
 $this->create('settings_ajax_excludegroups', '/settings/ajax/excludegroups.php')
113
-	->actionInclude('settings/ajax/excludegroups.php');
113
+    ->actionInclude('settings/ajax/excludegroups.php');
Please login to merge, or discard this patch.
apps/provisioning_api/lib/Controller/UsersController.php 4 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -196,7 +196,7 @@
 block discarded – undo
196 196
 	 * @param string $password
197 197
 	 * @param string $email
198 198
 	 * @param array $groups
199
-	 * @param array $subadmins
199
+	 * @param array $subadmin
200 200
 	 * @param string $quota
201 201
 	 * @return DataResponse
202 202
 	 * @throws OCSException
Please login to merge, or discard this patch.
Indentation   +835 added lines, -835 removed lines patch added patch discarded remove patch
@@ -52,839 +52,839 @@
 block discarded – undo
52 52
 
53 53
 class UsersController extends AUserData {
54 54
 
55
-	/** @var IAppManager */
56
-	private $appManager;
57
-	/** @var ILogger */
58
-	private $logger;
59
-	/** @var IFactory */
60
-	private $l10nFactory;
61
-	/** @var NewUserMailHelper */
62
-	private $newUserMailHelper;
63
-	/** @var FederatedFileSharingFactory */
64
-	private $federatedFileSharingFactory;
65
-	/** @var ISecureRandom */
66
-	private $secureRandom;
67
-
68
-	/**
69
-	 * @param string $appName
70
-	 * @param IRequest $request
71
-	 * @param IUserManager $userManager
72
-	 * @param IConfig $config
73
-	 * @param IAppManager $appManager
74
-	 * @param IGroupManager $groupManager
75
-	 * @param IUserSession $userSession
76
-	 * @param AccountManager $accountManager
77
-	 * @param ILogger $logger
78
-	 * @param IFactory $l10nFactory
79
-	 * @param NewUserMailHelper $newUserMailHelper
80
-	 * @param FederatedFileSharingFactory $federatedFileSharingFactory
81
-	 * @param ISecureRandom $secureRandom
82
-	 */
83
-	public function __construct(string $appName,
84
-								IRequest $request,
85
-								IUserManager $userManager,
86
-								IConfig $config,
87
-								IAppManager $appManager,
88
-								IGroupManager $groupManager,
89
-								IUserSession $userSession,
90
-								AccountManager $accountManager,
91
-								ILogger $logger,
92
-								IFactory $l10nFactory,
93
-								NewUserMailHelper $newUserMailHelper,
94
-								FederatedFileSharingFactory $federatedFileSharingFactory,
95
-								ISecureRandom $secureRandom) {
96
-		parent::__construct($appName,
97
-							$request,
98
-							$userManager,
99
-							$config,
100
-							$groupManager,
101
-							$userSession,
102
-							$accountManager);
103
-
104
-		$this->appManager = $appManager;
105
-		$this->logger = $logger;
106
-		$this->l10nFactory = $l10nFactory;
107
-		$this->newUserMailHelper = $newUserMailHelper;
108
-		$this->federatedFileSharingFactory = $federatedFileSharingFactory;
109
-		$this->secureRandom = $secureRandom;
110
-	}
111
-
112
-	/**
113
-	 * @NoAdminRequired
114
-	 *
115
-	 * returns a list of users
116
-	 *
117
-	 * @param string $search
118
-	 * @param int $limit
119
-	 * @param int $offset
120
-	 * @return DataResponse
121
-	 */
122
-	public function getUsers(string $search = '', $limit = null, $offset = 0): DataResponse {
123
-		$user = $this->userSession->getUser();
124
-		$users = [];
125
-
126
-		// Admin? Or SubAdmin?
127
-		$uid = $user->getUID();
128
-		$subAdminManager = $this->groupManager->getSubAdmin();
129
-		if ($this->groupManager->isAdmin($uid)){
130
-			$users = $this->userManager->search($search, $limit, $offset);
131
-		} else if ($subAdminManager->isSubAdmin($user)) {
132
-			$subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
133
-			foreach ($subAdminOfGroups as $key => $group) {
134
-				$subAdminOfGroups[$key] = $group->getGID();
135
-			}
136
-
137
-			$users = [];
138
-			foreach ($subAdminOfGroups as $group) {
139
-				$users = array_merge($users, $this->groupManager->displayNamesInGroup($group, $search, $limit, $offset));
140
-			}
141
-		}
142
-
143
-		$users = array_keys($users);
144
-
145
-		return new DataResponse([
146
-			'users' => $users
147
-		]);
148
-	}
149
-
150
-	/**
151
-	 * @NoAdminRequired
152
-	 *
153
-	 * returns a list of users and their data
154
-	 */
155
-	public function getUsersDetails(string $search = '', $limit = null, $offset = 0): DataResponse {
156
-		$user = $this->userSession->getUser();
157
-		$users = [];
158
-
159
-		// Admin? Or SubAdmin?
160
-		$uid = $user->getUID();
161
-		$subAdminManager = $this->groupManager->getSubAdmin();
162
-		if ($this->groupManager->isAdmin($uid)){
163
-			$users = $this->userManager->search($search, $limit, $offset);
164
-		} else if ($subAdminManager->isSubAdmin($user)) {
165
-			$subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
166
-			foreach ($subAdminOfGroups as $key => $group) {
167
-				$subAdminOfGroups[$key] = $group->getGID();
168
-			}
169
-
170
-			$users = [];
171
-			foreach ($subAdminOfGroups as $group) {
172
-				$users = array_merge($users, $this->groupManager->displayNamesInGroup($group, $search, $limit, $offset));
173
-			}
174
-		}
175
-
176
-		$users = array_keys($users);
177
-		$usersDetails = [];
178
-		foreach ($users as $key => $userId) {
179
-			$userData = $this->getUserData($userId);
180
-			// Do not insert empty entry
181
-			if (!empty($userData)) {
182
-				$usersDetails[$userId] = $userData;
183
-			}
184
-		}
185
-
186
-		return new DataResponse([
187
-			'users' => $usersDetails
188
-		]);
189
-	}
190
-
191
-	/**
192
-	 * @PasswordConfirmationRequired
193
-	 * @NoAdminRequired
194
-	 *
195
-	 * @param string $userid
196
-	 * @param string $password
197
-	 * @param string $email
198
-	 * @param array $groups
199
-	 * @param array $subadmins
200
-	 * @param string $quota
201
-	 * @return DataResponse
202
-	 * @throws OCSException
203
-	 */
204
-	public function addUser(string $userid,
205
-							string $password = '',
206
-							string $email = '',
207
-							array $groups = [],
208
-							array $subadmin = [],
209
-							string $quota = ''): DataResponse {
210
-		$user = $this->userSession->getUser();
211
-		$isAdmin = $this->groupManager->isAdmin($user->getUID());
212
-		$subAdminManager = $this->groupManager->getSubAdmin();
213
-
214
-		if ($this->userManager->userExists($userid)) {
215
-			$this->logger->error('Failed addUser attempt: User already exists.', ['app' => 'ocs_api']);
216
-			throw new OCSException('User already exists', 102);
217
-		}
218
-
219
-		if ($groups !== []) {
220
-			foreach ($groups as $group) {
221
-				if (!$this->groupManager->groupExists($group)) {
222
-					throw new OCSException('group '.$group.' does not exist', 104);
223
-				}
224
-				if (!$isAdmin && !$subAdminManager->isSubAdminOfGroup($user, $this->groupManager->get($group))) {
225
-					throw new OCSException('insufficient privileges for group '. $group, 105);
226
-				}
227
-			}
228
-		} else {
229
-			if (!$isAdmin) {
230
-				throw new OCSException('no group specified (required for subadmins)', 106);
231
-			}
232
-		}
233
-
234
-		$subadminGroups = [];
235
-		if ($subadmin !== []) {
236
-			foreach ($subadmin as $groupid) {
237
-				$group = $this->groupManager->get($groupid);
238
-				// Check if group exists
239
-				if ($group === null) {
240
-					throw new OCSException('Subadmin group does not exist',  102);
241
-				}
242
-				// Check if trying to make subadmin of admin group
243
-				if ($group->getGID() === 'admin') {
244
-					throw new OCSException('Cannot create subadmins for admin group', 103);
245
-				}
246
-				// Check if has permission to promote subadmins
247
-				if (!$subAdminManager->isSubAdminOfGroup($user, $group) && !$isAdmin) {
248
-					throw new OCSForbiddenException('No permissions to promote subadmins');
249
-				}
250
-				$subadminGroups[] = $group;
251
-			}
252
-		}
253
-
254
-		$generatePasswordResetToken = false;
255
-		if ($password === '') {
256
-			if ($email === '') {
257
-				throw new OCSException('To send a password link to the user an email address is required.', 108);
258
-			}
259
-
260
-			$password = $this->secureRandom->generate(10);
261
-			// Make sure we pass the password_policy
262
-			$password .= $this->secureRandom->generate(2, '$!.,;:-~+*[]{}()');
263
-			$generatePasswordResetToken = true;
264
-		}
265
-
266
-		try {
267
-			$newUser = $this->userManager->createUser($userid, $password);
268
-			$this->logger->info('Successful addUser call with userid: ' . $userid, ['app' => 'ocs_api']);
269
-
270
-			foreach ($groups as $group) {
271
-				$this->groupManager->get($group)->addUser($newUser);
272
-				$this->logger->info('Added userid ' . $userid . ' to group ' . $group, ['app' => 'ocs_api']);
273
-			}
274
-			foreach ($subadminGroups as $group) {
275
-				$subAdminManager->createSubAdmin($newUser, $group);
276
-			}
277
-
278
-			if ($quota !== '') {
279
-				$this->editUser($userid, 'quota', $quota);
280
-			}
281
-
282
-			// Send new user mail only if a mail is set
283
-			if ($email !== '') {
284
-				$newUser->setEMailAddress($email);
285
-				try {
286
-					$emailTemplate = $this->newUserMailHelper->generateTemplate($newUser, $generatePasswordResetToken);
287
-					$this->newUserMailHelper->sendMail($newUser, $emailTemplate);
288
-				} catch (\Exception $e) {
289
-					$this->logger->logException($e, [
290
-						'message' => "Can't send new user mail to $email",
291
-						'level' => \OCP\Util::ERROR,
292
-						'app' => 'ocs_api',
293
-					]);
294
-					throw new OCSException('Unable to send the invitation mail', 109);
295
-				}
296
-			}
297
-
298
-			return new DataResponse();
299
-
300
-		} catch (HintException $e ) {
301
-			$this->logger->logException($e, [
302
-				'message' => 'Failed addUser attempt with hint exception.',
303
-				'level' => \OCP\Util::WARN,
304
-				'app' => 'ocs_api',
305
-			]);
306
-			throw new OCSException($e->getHint(), 107);
307
-		} catch (\Exception $e) {
308
-			$this->logger->logException($e, [
309
-				'message' => 'Failed addUser attempt with exception.',
310
-				'level' => \OCP\Util::ERROR,
311
-				'app' => 'ocs_api',
312
-			]);
313
-			throw new OCSException('Bad request', 101);
314
-		}
315
-	}
316
-
317
-	/**
318
-	 * @NoAdminRequired
319
-	 * @NoSubAdminRequired
320
-	 *
321
-	 * gets user info
322
-	 *
323
-	 * @param string $userId
324
-	 * @return DataResponse
325
-	 * @throws OCSException
326
-	 */
327
-	public function getUser(string $userId): DataResponse {
328
-		$data = $this->getUserData($userId);
329
-		// getUserData returns empty array if not enough permissions
330
-		if (empty($data)) {
331
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
332
-		}
333
-		return new DataResponse($data);
334
-	}
335
-
336
-	/**
337
-	 * @NoAdminRequired
338
-	 * @NoSubAdminRequired
339
-	 *
340
-	 * gets user info from the currently logged in user
341
-	 *
342
-	 * @return DataResponse
343
-	 * @throws OCSException
344
-	 */
345
-	public function getCurrentUser(): DataResponse {
346
-		$user = $this->userSession->getUser();
347
-		if ($user) {
348
-			$data =  $this->getUserData($user->getUID());
349
-			// rename "displayname" to "display-name" only for this call to keep
350
-			// the API stable.
351
-			$data['display-name'] = $data['displayname'];
352
-			unset($data['displayname']);
353
-			return new DataResponse($data);
354
-
355
-		}
356
-
357
-		throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
358
-	}
359
-
360
-	/**
361
-	 * @NoAdminRequired
362
-	 * @NoSubAdminRequired
363
-	 */
364
-	public function getEditableFields(): DataResponse {
365
-		$permittedFields = [];
366
-
367
-		// Editing self (display, email)
368
-		if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
369
-			$permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
370
-			$permittedFields[] = AccountManager::PROPERTY_EMAIL;
371
-		}
372
-
373
-		if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
374
-			$federatedFileSharing = $this->federatedFileSharingFactory->get();
375
-			$shareProvider = $federatedFileSharing->getFederatedShareProvider();
376
-			if ($shareProvider->isLookupServerUploadEnabled()) {
377
-				$permittedFields[] = AccountManager::PROPERTY_PHONE;
378
-				$permittedFields[] = AccountManager::PROPERTY_ADDRESS;
379
-				$permittedFields[] = AccountManager::PROPERTY_WEBSITE;
380
-				$permittedFields[] = AccountManager::PROPERTY_TWITTER;
381
-			}
382
-		}
383
-
384
-		return new DataResponse($permittedFields);
385
-	}
386
-
387
-	/**
388
-	 * @NoAdminRequired
389
-	 * @NoSubAdminRequired
390
-	 * @PasswordConfirmationRequired
391
-	 *
392
-	 * edit users
393
-	 *
394
-	 * @param string $userId
395
-	 * @param string $key
396
-	 * @param string $value
397
-	 * @return DataResponse
398
-	 * @throws OCSException
399
-	 */
400
-	public function editUser(string $userId, string $key, string $value): DataResponse {
401
-		$currentLoggedInUser = $this->userSession->getUser();
402
-
403
-		$targetUser = $this->userManager->get($userId);
404
-		if ($targetUser === null) {
405
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
406
-		}
407
-
408
-		$permittedFields = [];
409
-		if ($targetUser->getUID() === $currentLoggedInUser->getUID()) {
410
-			// Editing self (display, email)
411
-			if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
412
-				$permittedFields[] = 'display';
413
-				$permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
414
-				$permittedFields[] = AccountManager::PROPERTY_EMAIL;
415
-			}
416
-
417
-			$permittedFields[] = 'password';
418
-			if ($this->config->getSystemValue('force_language', false) === false ||
419
-				$this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
420
-				$permittedFields[] = 'language';
421
-			}
422
-
423
-			if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
424
-				$federatedFileSharing = new \OCA\FederatedFileSharing\AppInfo\Application();
425
-				$shareProvider = $federatedFileSharing->getFederatedShareProvider();
426
-				if ($shareProvider->isLookupServerUploadEnabled()) {
427
-					$permittedFields[] = AccountManager::PROPERTY_PHONE;
428
-					$permittedFields[] = AccountManager::PROPERTY_ADDRESS;
429
-					$permittedFields[] = AccountManager::PROPERTY_WEBSITE;
430
-					$permittedFields[] = AccountManager::PROPERTY_TWITTER;
431
-				}
432
-			}
433
-
434
-			// If admin they can edit their own quota
435
-			if ($this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
436
-				$permittedFields[] = 'quota';
437
-			}
438
-		} else {
439
-			// Check if admin / subadmin
440
-			$subAdminManager = $this->groupManager->getSubAdmin();
441
-			if ($subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
442
-			|| $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
443
-				// They have permissions over the user
444
-				$permittedFields[] = 'display';
445
-				$permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
446
-				$permittedFields[] = AccountManager::PROPERTY_EMAIL;
447
-				$permittedFields[] = 'password';
448
-				$permittedFields[] = 'language';
449
-				$permittedFields[] = AccountManager::PROPERTY_PHONE;
450
-				$permittedFields[] = AccountManager::PROPERTY_ADDRESS;
451
-				$permittedFields[] = AccountManager::PROPERTY_WEBSITE;
452
-				$permittedFields[] = AccountManager::PROPERTY_TWITTER;
453
-				$permittedFields[] = 'quota';
454
-			} else {
455
-				// No rights
456
-				throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
457
-			}
458
-		}
459
-		// Check if permitted to edit this field
460
-		if (!in_array($key, $permittedFields)) {
461
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
462
-		}
463
-		// Process the edit
464
-		switch($key) {
465
-			case 'display':
466
-			case AccountManager::PROPERTY_DISPLAYNAME:
467
-				$targetUser->setDisplayName($value);
468
-				break;
469
-			case 'quota':
470
-				$quota = $value;
471
-				if ($quota !== 'none' && $quota !== 'default') {
472
-					if (is_numeric($quota)) {
473
-						$quota = (float) $quota;
474
-					} else {
475
-						$quota = \OCP\Util::computerFileSize($quota);
476
-					}
477
-					if ($quota === false) {
478
-						throw new OCSException('Invalid quota value '.$value, 103);
479
-					}
480
-					if ($quota === 0) {
481
-						$quota = 'default';
482
-					}else if ($quota === -1) {
483
-						$quota = 'none';
484
-					} else {
485
-						$quota = \OCP\Util::humanFileSize($quota);
486
-					}
487
-				}
488
-				$targetUser->setQuota($quota);
489
-				break;
490
-			case 'password':
491
-				$targetUser->setPassword($value);
492
-				break;
493
-			case 'language':
494
-				$languagesCodes = $this->l10nFactory->findAvailableLanguages();
495
-				if (!in_array($value, $languagesCodes, true) && $value !== 'en') {
496
-					throw new OCSException('Invalid language', 102);
497
-				}
498
-				$this->config->setUserValue($targetUser->getUID(), 'core', 'lang', $value);
499
-				break;
500
-			case AccountManager::PROPERTY_EMAIL:
501
-				if (filter_var($value, FILTER_VALIDATE_EMAIL) || $value === '') {
502
-					$targetUser->setEMailAddress($value);
503
-				} else {
504
-					throw new OCSException('', 102);
505
-				}
506
-				break;
507
-			case AccountManager::PROPERTY_PHONE:
508
-			case AccountManager::PROPERTY_ADDRESS:
509
-			case AccountManager::PROPERTY_WEBSITE:
510
-			case AccountManager::PROPERTY_TWITTER:
511
-				$userAccount = $this->accountManager->getUser($targetUser);
512
-				if ($userAccount[$key]['value'] !== $value) {
513
-					$userAccount[$key]['value'] = $value;
514
-					$this->accountManager->updateUser($targetUser, $userAccount);
515
-				}
516
-				break;
517
-			default:
518
-				throw new OCSException('', 103);
519
-		}
520
-		return new DataResponse();
521
-	}
522
-
523
-	/**
524
-	 * @PasswordConfirmationRequired
525
-	 * @NoAdminRequired
526
-	 *
527
-	 * @param string $userId
528
-	 * @return DataResponse
529
-	 * @throws OCSException
530
-	 */
531
-	public function deleteUser(string $userId): DataResponse {
532
-		$currentLoggedInUser = $this->userSession->getUser();
533
-
534
-		$targetUser = $this->userManager->get($userId);
535
-
536
-		if ($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
537
-			throw new OCSException('', 101);
538
-		}
539
-
540
-		// If not permitted
541
-		$subAdminManager = $this->groupManager->getSubAdmin();
542
-		if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
543
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
544
-		}
545
-
546
-		// Go ahead with the delete
547
-		if ($targetUser->delete()) {
548
-			return new DataResponse();
549
-		} else {
550
-			throw new OCSException('', 101);
551
-		}
552
-	}
553
-
554
-	/**
555
-	 * @PasswordConfirmationRequired
556
-	 * @NoAdminRequired
557
-	 *
558
-	 * @param string $userId
559
-	 * @return DataResponse
560
-	 * @throws OCSException
561
-	 * @throws OCSForbiddenException
562
-	 */
563
-	public function disableUser(string $userId): DataResponse {
564
-		return $this->setEnabled($userId, false);
565
-	}
566
-
567
-	/**
568
-	 * @PasswordConfirmationRequired
569
-	 * @NoAdminRequired
570
-	 *
571
-	 * @param string $userId
572
-	 * @return DataResponse
573
-	 * @throws OCSException
574
-	 * @throws OCSForbiddenException
575
-	 */
576
-	public function enableUser(string $userId): DataResponse {
577
-		return $this->setEnabled($userId, true);
578
-	}
579
-
580
-	/**
581
-	 * @param string $userId
582
-	 * @param bool $value
583
-	 * @return DataResponse
584
-	 * @throws OCSException
585
-	 */
586
-	private function setEnabled(string $userId, bool $value): DataResponse {
587
-		$currentLoggedInUser = $this->userSession->getUser();
588
-
589
-		$targetUser = $this->userManager->get($userId);
590
-		if ($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
591
-			throw new OCSException('', 101);
592
-		}
593
-
594
-		// If not permitted
595
-		$subAdminManager = $this->groupManager->getSubAdmin();
596
-		if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
597
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
598
-		}
599
-
600
-		// enable/disable the user now
601
-		$targetUser->setEnabled($value);
602
-		return new DataResponse();
603
-	}
604
-
605
-	/**
606
-	 * @NoAdminRequired
607
-	 * @NoSubAdminRequired
608
-	 *
609
-	 * @param string $userId
610
-	 * @return DataResponse
611
-	 * @throws OCSException
612
-	 */
613
-	public function getUsersGroups(string $userId): DataResponse {
614
-		$loggedInUser = $this->userSession->getUser();
615
-
616
-		$targetUser = $this->userManager->get($userId);
617
-		if ($targetUser === null) {
618
-			throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
619
-		}
620
-
621
-		if ($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) {
622
-			// Self lookup or admin lookup
623
-			return new DataResponse([
624
-				'groups' => $this->groupManager->getUserGroupIds($targetUser)
625
-			]);
626
-		} else {
627
-			$subAdminManager = $this->groupManager->getSubAdmin();
628
-
629
-			// Looking up someone else
630
-			if ($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) {
631
-				// Return the group that the method caller is subadmin of for the user in question
632
-				/** @var IGroup[] $getSubAdminsGroups */
633
-				$getSubAdminsGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
634
-				foreach ($getSubAdminsGroups as $key => $group) {
635
-					$getSubAdminsGroups[$key] = $group->getGID();
636
-				}
637
-				$groups = array_intersect(
638
-					$getSubAdminsGroups,
639
-					$this->groupManager->getUserGroupIds($targetUser)
640
-				);
641
-				return new DataResponse(['groups' => $groups]);
642
-			} else {
643
-				// Not permitted
644
-				throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
645
-			}
646
-		}
647
-
648
-	}
649
-
650
-	/**
651
-	 * @PasswordConfirmationRequired
652
-	 * @NoAdminRequired
653
-	 *
654
-	 * @param string $userId
655
-	 * @param string $groupid
656
-	 * @return DataResponse
657
-	 * @throws OCSException
658
-	 */
659
-	public function addToGroup(string $userId, string $groupid = ''): DataResponse {
660
-		if ($groupid === '') {
661
-			throw new OCSException('', 101);
662
-		}
663
-
664
-		$group = $this->groupManager->get($groupid);
665
-		$targetUser = $this->userManager->get($userId);
666
-		if ($group === null) {
667
-			throw new OCSException('', 102);
668
-		}
669
-		if ($targetUser === null) {
670
-			throw new OCSException('', 103);
671
-		}
672
-
673
-		// If they're not an admin, check they are a subadmin of the group in question
674
-		$loggedInUser = $this->userSession->getUser();
675
-		$subAdminManager = $this->groupManager->getSubAdmin();
676
-		if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
677
-			throw new OCSException('', 104);
678
-		}
679
-
680
-		// Add user to group
681
-		$group->addUser($targetUser);
682
-		return new DataResponse();
683
-	}
684
-
685
-	/**
686
-	 * @PasswordConfirmationRequired
687
-	 * @NoAdminRequired
688
-	 *
689
-	 * @param string $userId
690
-	 * @param string $groupid
691
-	 * @return DataResponse
692
-	 * @throws OCSException
693
-	 */
694
-	public function removeFromGroup(string $userId, string $groupid): DataResponse {
695
-		$loggedInUser = $this->userSession->getUser();
696
-
697
-		if ($groupid === null || trim($groupid) === '') {
698
-			throw new OCSException('', 101);
699
-		}
700
-
701
-		$group = $this->groupManager->get($groupid);
702
-		if ($group === null) {
703
-			throw new OCSException('', 102);
704
-		}
705
-
706
-		$targetUser = $this->userManager->get($userId);
707
-		if ($targetUser === null) {
708
-			throw new OCSException('', 103);
709
-		}
710
-
711
-		// If they're not an admin, check they are a subadmin of the group in question
712
-		$subAdminManager = $this->groupManager->getSubAdmin();
713
-		if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
714
-			throw new OCSException('', 104);
715
-		}
716
-
717
-		// Check they aren't removing themselves from 'admin' or their 'subadmin; group
718
-		if ($targetUser->getUID() === $loggedInUser->getUID()) {
719
-			if ($this->groupManager->isAdmin($loggedInUser->getUID())) {
720
-				if ($group->getGID() === 'admin') {
721
-					throw new OCSException('Cannot remove yourself from the admin group', 105);
722
-				}
723
-			} else {
724
-				// Not an admin, so the user must be a subadmin of this group, but that is not allowed.
725
-				throw new OCSException('Cannot remove yourself from this group as you are a SubAdmin', 105);
726
-			}
727
-
728
-		} else if (!$this->groupManager->isAdmin($loggedInUser->getUID())) {
729
-			/** @var IGroup[] $subAdminGroups */
730
-			$subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
731
-			$subAdminGroups = array_map(function (IGroup $subAdminGroup) {
732
-				return $subAdminGroup->getGID();
733
-			}, $subAdminGroups);
734
-			$userGroups = $this->groupManager->getUserGroupIds($targetUser);
735
-			$userSubAdminGroups = array_intersect($subAdminGroups, $userGroups);
736
-
737
-			if (count($userSubAdminGroups) <= 1) {
738
-				// Subadmin must not be able to remove a user from all their subadmin groups.
739
-				throw new OCSException('Cannot remove user from this group as this is the only remaining group you are a SubAdmin of', 105);
740
-			}
741
-		}
742
-
743
-		// Remove user from group
744
-		$group->removeUser($targetUser);
745
-		return new DataResponse();
746
-	}
747
-
748
-	/**
749
-	 * Creates a subadmin
750
-	 *
751
-	 * @PasswordConfirmationRequired
752
-	 *
753
-	 * @param string $userId
754
-	 * @param string $groupid
755
-	 * @return DataResponse
756
-	 * @throws OCSException
757
-	 */
758
-	public function addSubAdmin(string $userId, string $groupid): DataResponse {
759
-		$group = $this->groupManager->get($groupid);
760
-		$user = $this->userManager->get($userId);
761
-
762
-		// Check if the user exists
763
-		if ($user === null) {
764
-			throw new OCSException('User does not exist', 101);
765
-		}
766
-		// Check if group exists
767
-		if ($group === null) {
768
-			throw new OCSException('Group does not exist',  102);
769
-		}
770
-		// Check if trying to make subadmin of admin group
771
-		if ($group->getGID() === 'admin') {
772
-			throw new OCSException('Cannot create subadmins for admin group', 103);
773
-		}
774
-
775
-		$subAdminManager = $this->groupManager->getSubAdmin();
776
-
777
-		// We cannot be subadmin twice
778
-		if ($subAdminManager->isSubAdminOfGroup($user, $group)) {
779
-			return new DataResponse();
780
-		}
781
-		// Go
782
-		if ($subAdminManager->createSubAdmin($user, $group)) {
783
-			return new DataResponse();
784
-		} else {
785
-			throw new OCSException('Unknown error occurred', 103);
786
-		}
787
-	}
788
-
789
-	/**
790
-	 * Removes a subadmin from a group
791
-	 *
792
-	 * @PasswordConfirmationRequired
793
-	 *
794
-	 * @param string $userId
795
-	 * @param string $groupid
796
-	 * @return DataResponse
797
-	 * @throws OCSException
798
-	 */
799
-	public function removeSubAdmin(string $userId, string $groupid): DataResponse {
800
-		$group = $this->groupManager->get($groupid);
801
-		$user = $this->userManager->get($userId);
802
-		$subAdminManager = $this->groupManager->getSubAdmin();
803
-
804
-		// Check if the user exists
805
-		if ($user === null) {
806
-			throw new OCSException('User does not exist', 101);
807
-		}
808
-		// Check if the group exists
809
-		if ($group === null) {
810
-			throw new OCSException('Group does not exist', 101);
811
-		}
812
-		// Check if they are a subadmin of this said group
813
-		if (!$subAdminManager->isSubAdminOfGroup($user, $group)) {
814
-			throw new OCSException('User is not a subadmin of this group', 102);
815
-		}
816
-
817
-		// Go
818
-		if ($subAdminManager->deleteSubAdmin($user, $group)) {
819
-			return new DataResponse();
820
-		} else {
821
-			throw new OCSException('Unknown error occurred', 103);
822
-		}
823
-	}
824
-
825
-	/**
826
-	 * Get the groups a user is a subadmin of
827
-	 *
828
-	 * @param string $userId
829
-	 * @return DataResponse
830
-	 * @throws OCSException
831
-	 */
832
-	public function getUserSubAdminGroups(string $userId): DataResponse {
833
-		$groups = $this->getUserSubAdminGroupsData($userId);
834
-		return new DataResponse($groups);
835
-	}
836
-
837
-	/**
838
-	 * @NoAdminRequired
839
-	 * @PasswordConfirmationRequired
840
-	 *
841
-	 * resend welcome message
842
-	 *
843
-	 * @param string $userId
844
-	 * @return DataResponse
845
-	 * @throws OCSException
846
-	 */
847
-	public function resendWelcomeMessage(string $userId): DataResponse {
848
-		$currentLoggedInUser = $this->userSession->getUser();
849
-
850
-		$targetUser = $this->userManager->get($userId);
851
-		if ($targetUser === null) {
852
-			throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
853
-		}
854
-
855
-		// Check if admin / subadmin
856
-		$subAdminManager = $this->groupManager->getSubAdmin();
857
-		if (!$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
858
-			&& !$this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
859
-			// No rights
860
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
861
-		}
862
-
863
-		$email = $targetUser->getEMailAddress();
864
-		if ($email === '' || $email === null) {
865
-			throw new OCSException('Email address not available', 101);
866
-		}
867
-		$username = $targetUser->getUID();
868
-		$lang = $this->config->getUserValue($username, 'core', 'lang', 'en');
869
-		if (!$this->l10nFactory->languageExists('settings', $lang)) {
870
-			$lang = 'en';
871
-		}
872
-
873
-		$l10n = $this->l10nFactory->get('settings', $lang);
874
-
875
-		try {
876
-			$this->newUserMailHelper->setL10N($l10n);
877
-			$emailTemplate = $this->newUserMailHelper->generateTemplate($targetUser, false);
878
-			$this->newUserMailHelper->sendMail($targetUser, $emailTemplate);
879
-		} catch(\Exception $e) {
880
-			$this->logger->logException($e, [
881
-				'message' => "Can't send new user mail to $email",
882
-				'level' => \OCP\Util::ERROR,
883
-				'app' => 'settings',
884
-			]);
885
-			throw new OCSException('Sending email failed', 102);
886
-		}
887
-
888
-		return new DataResponse();
889
-	}
55
+    /** @var IAppManager */
56
+    private $appManager;
57
+    /** @var ILogger */
58
+    private $logger;
59
+    /** @var IFactory */
60
+    private $l10nFactory;
61
+    /** @var NewUserMailHelper */
62
+    private $newUserMailHelper;
63
+    /** @var FederatedFileSharingFactory */
64
+    private $federatedFileSharingFactory;
65
+    /** @var ISecureRandom */
66
+    private $secureRandom;
67
+
68
+    /**
69
+     * @param string $appName
70
+     * @param IRequest $request
71
+     * @param IUserManager $userManager
72
+     * @param IConfig $config
73
+     * @param IAppManager $appManager
74
+     * @param IGroupManager $groupManager
75
+     * @param IUserSession $userSession
76
+     * @param AccountManager $accountManager
77
+     * @param ILogger $logger
78
+     * @param IFactory $l10nFactory
79
+     * @param NewUserMailHelper $newUserMailHelper
80
+     * @param FederatedFileSharingFactory $federatedFileSharingFactory
81
+     * @param ISecureRandom $secureRandom
82
+     */
83
+    public function __construct(string $appName,
84
+                                IRequest $request,
85
+                                IUserManager $userManager,
86
+                                IConfig $config,
87
+                                IAppManager $appManager,
88
+                                IGroupManager $groupManager,
89
+                                IUserSession $userSession,
90
+                                AccountManager $accountManager,
91
+                                ILogger $logger,
92
+                                IFactory $l10nFactory,
93
+                                NewUserMailHelper $newUserMailHelper,
94
+                                FederatedFileSharingFactory $federatedFileSharingFactory,
95
+                                ISecureRandom $secureRandom) {
96
+        parent::__construct($appName,
97
+                            $request,
98
+                            $userManager,
99
+                            $config,
100
+                            $groupManager,
101
+                            $userSession,
102
+                            $accountManager);
103
+
104
+        $this->appManager = $appManager;
105
+        $this->logger = $logger;
106
+        $this->l10nFactory = $l10nFactory;
107
+        $this->newUserMailHelper = $newUserMailHelper;
108
+        $this->federatedFileSharingFactory = $federatedFileSharingFactory;
109
+        $this->secureRandom = $secureRandom;
110
+    }
111
+
112
+    /**
113
+     * @NoAdminRequired
114
+     *
115
+     * returns a list of users
116
+     *
117
+     * @param string $search
118
+     * @param int $limit
119
+     * @param int $offset
120
+     * @return DataResponse
121
+     */
122
+    public function getUsers(string $search = '', $limit = null, $offset = 0): DataResponse {
123
+        $user = $this->userSession->getUser();
124
+        $users = [];
125
+
126
+        // Admin? Or SubAdmin?
127
+        $uid = $user->getUID();
128
+        $subAdminManager = $this->groupManager->getSubAdmin();
129
+        if ($this->groupManager->isAdmin($uid)){
130
+            $users = $this->userManager->search($search, $limit, $offset);
131
+        } else if ($subAdminManager->isSubAdmin($user)) {
132
+            $subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
133
+            foreach ($subAdminOfGroups as $key => $group) {
134
+                $subAdminOfGroups[$key] = $group->getGID();
135
+            }
136
+
137
+            $users = [];
138
+            foreach ($subAdminOfGroups as $group) {
139
+                $users = array_merge($users, $this->groupManager->displayNamesInGroup($group, $search, $limit, $offset));
140
+            }
141
+        }
142
+
143
+        $users = array_keys($users);
144
+
145
+        return new DataResponse([
146
+            'users' => $users
147
+        ]);
148
+    }
149
+
150
+    /**
151
+     * @NoAdminRequired
152
+     *
153
+     * returns a list of users and their data
154
+     */
155
+    public function getUsersDetails(string $search = '', $limit = null, $offset = 0): DataResponse {
156
+        $user = $this->userSession->getUser();
157
+        $users = [];
158
+
159
+        // Admin? Or SubAdmin?
160
+        $uid = $user->getUID();
161
+        $subAdminManager = $this->groupManager->getSubAdmin();
162
+        if ($this->groupManager->isAdmin($uid)){
163
+            $users = $this->userManager->search($search, $limit, $offset);
164
+        } else if ($subAdminManager->isSubAdmin($user)) {
165
+            $subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
166
+            foreach ($subAdminOfGroups as $key => $group) {
167
+                $subAdminOfGroups[$key] = $group->getGID();
168
+            }
169
+
170
+            $users = [];
171
+            foreach ($subAdminOfGroups as $group) {
172
+                $users = array_merge($users, $this->groupManager->displayNamesInGroup($group, $search, $limit, $offset));
173
+            }
174
+        }
175
+
176
+        $users = array_keys($users);
177
+        $usersDetails = [];
178
+        foreach ($users as $key => $userId) {
179
+            $userData = $this->getUserData($userId);
180
+            // Do not insert empty entry
181
+            if (!empty($userData)) {
182
+                $usersDetails[$userId] = $userData;
183
+            }
184
+        }
185
+
186
+        return new DataResponse([
187
+            'users' => $usersDetails
188
+        ]);
189
+    }
190
+
191
+    /**
192
+     * @PasswordConfirmationRequired
193
+     * @NoAdminRequired
194
+     *
195
+     * @param string $userid
196
+     * @param string $password
197
+     * @param string $email
198
+     * @param array $groups
199
+     * @param array $subadmins
200
+     * @param string $quota
201
+     * @return DataResponse
202
+     * @throws OCSException
203
+     */
204
+    public function addUser(string $userid,
205
+                            string $password = '',
206
+                            string $email = '',
207
+                            array $groups = [],
208
+                            array $subadmin = [],
209
+                            string $quota = ''): DataResponse {
210
+        $user = $this->userSession->getUser();
211
+        $isAdmin = $this->groupManager->isAdmin($user->getUID());
212
+        $subAdminManager = $this->groupManager->getSubAdmin();
213
+
214
+        if ($this->userManager->userExists($userid)) {
215
+            $this->logger->error('Failed addUser attempt: User already exists.', ['app' => 'ocs_api']);
216
+            throw new OCSException('User already exists', 102);
217
+        }
218
+
219
+        if ($groups !== []) {
220
+            foreach ($groups as $group) {
221
+                if (!$this->groupManager->groupExists($group)) {
222
+                    throw new OCSException('group '.$group.' does not exist', 104);
223
+                }
224
+                if (!$isAdmin && !$subAdminManager->isSubAdminOfGroup($user, $this->groupManager->get($group))) {
225
+                    throw new OCSException('insufficient privileges for group '. $group, 105);
226
+                }
227
+            }
228
+        } else {
229
+            if (!$isAdmin) {
230
+                throw new OCSException('no group specified (required for subadmins)', 106);
231
+            }
232
+        }
233
+
234
+        $subadminGroups = [];
235
+        if ($subadmin !== []) {
236
+            foreach ($subadmin as $groupid) {
237
+                $group = $this->groupManager->get($groupid);
238
+                // Check if group exists
239
+                if ($group === null) {
240
+                    throw new OCSException('Subadmin group does not exist',  102);
241
+                }
242
+                // Check if trying to make subadmin of admin group
243
+                if ($group->getGID() === 'admin') {
244
+                    throw new OCSException('Cannot create subadmins for admin group', 103);
245
+                }
246
+                // Check if has permission to promote subadmins
247
+                if (!$subAdminManager->isSubAdminOfGroup($user, $group) && !$isAdmin) {
248
+                    throw new OCSForbiddenException('No permissions to promote subadmins');
249
+                }
250
+                $subadminGroups[] = $group;
251
+            }
252
+        }
253
+
254
+        $generatePasswordResetToken = false;
255
+        if ($password === '') {
256
+            if ($email === '') {
257
+                throw new OCSException('To send a password link to the user an email address is required.', 108);
258
+            }
259
+
260
+            $password = $this->secureRandom->generate(10);
261
+            // Make sure we pass the password_policy
262
+            $password .= $this->secureRandom->generate(2, '$!.,;:-~+*[]{}()');
263
+            $generatePasswordResetToken = true;
264
+        }
265
+
266
+        try {
267
+            $newUser = $this->userManager->createUser($userid, $password);
268
+            $this->logger->info('Successful addUser call with userid: ' . $userid, ['app' => 'ocs_api']);
269
+
270
+            foreach ($groups as $group) {
271
+                $this->groupManager->get($group)->addUser($newUser);
272
+                $this->logger->info('Added userid ' . $userid . ' to group ' . $group, ['app' => 'ocs_api']);
273
+            }
274
+            foreach ($subadminGroups as $group) {
275
+                $subAdminManager->createSubAdmin($newUser, $group);
276
+            }
277
+
278
+            if ($quota !== '') {
279
+                $this->editUser($userid, 'quota', $quota);
280
+            }
281
+
282
+            // Send new user mail only if a mail is set
283
+            if ($email !== '') {
284
+                $newUser->setEMailAddress($email);
285
+                try {
286
+                    $emailTemplate = $this->newUserMailHelper->generateTemplate($newUser, $generatePasswordResetToken);
287
+                    $this->newUserMailHelper->sendMail($newUser, $emailTemplate);
288
+                } catch (\Exception $e) {
289
+                    $this->logger->logException($e, [
290
+                        'message' => "Can't send new user mail to $email",
291
+                        'level' => \OCP\Util::ERROR,
292
+                        'app' => 'ocs_api',
293
+                    ]);
294
+                    throw new OCSException('Unable to send the invitation mail', 109);
295
+                }
296
+            }
297
+
298
+            return new DataResponse();
299
+
300
+        } catch (HintException $e ) {
301
+            $this->logger->logException($e, [
302
+                'message' => 'Failed addUser attempt with hint exception.',
303
+                'level' => \OCP\Util::WARN,
304
+                'app' => 'ocs_api',
305
+            ]);
306
+            throw new OCSException($e->getHint(), 107);
307
+        } catch (\Exception $e) {
308
+            $this->logger->logException($e, [
309
+                'message' => 'Failed addUser attempt with exception.',
310
+                'level' => \OCP\Util::ERROR,
311
+                'app' => 'ocs_api',
312
+            ]);
313
+            throw new OCSException('Bad request', 101);
314
+        }
315
+    }
316
+
317
+    /**
318
+     * @NoAdminRequired
319
+     * @NoSubAdminRequired
320
+     *
321
+     * gets user info
322
+     *
323
+     * @param string $userId
324
+     * @return DataResponse
325
+     * @throws OCSException
326
+     */
327
+    public function getUser(string $userId): DataResponse {
328
+        $data = $this->getUserData($userId);
329
+        // getUserData returns empty array if not enough permissions
330
+        if (empty($data)) {
331
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
332
+        }
333
+        return new DataResponse($data);
334
+    }
335
+
336
+    /**
337
+     * @NoAdminRequired
338
+     * @NoSubAdminRequired
339
+     *
340
+     * gets user info from the currently logged in user
341
+     *
342
+     * @return DataResponse
343
+     * @throws OCSException
344
+     */
345
+    public function getCurrentUser(): DataResponse {
346
+        $user = $this->userSession->getUser();
347
+        if ($user) {
348
+            $data =  $this->getUserData($user->getUID());
349
+            // rename "displayname" to "display-name" only for this call to keep
350
+            // the API stable.
351
+            $data['display-name'] = $data['displayname'];
352
+            unset($data['displayname']);
353
+            return new DataResponse($data);
354
+
355
+        }
356
+
357
+        throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
358
+    }
359
+
360
+    /**
361
+     * @NoAdminRequired
362
+     * @NoSubAdminRequired
363
+     */
364
+    public function getEditableFields(): DataResponse {
365
+        $permittedFields = [];
366
+
367
+        // Editing self (display, email)
368
+        if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
369
+            $permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
370
+            $permittedFields[] = AccountManager::PROPERTY_EMAIL;
371
+        }
372
+
373
+        if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
374
+            $federatedFileSharing = $this->federatedFileSharingFactory->get();
375
+            $shareProvider = $federatedFileSharing->getFederatedShareProvider();
376
+            if ($shareProvider->isLookupServerUploadEnabled()) {
377
+                $permittedFields[] = AccountManager::PROPERTY_PHONE;
378
+                $permittedFields[] = AccountManager::PROPERTY_ADDRESS;
379
+                $permittedFields[] = AccountManager::PROPERTY_WEBSITE;
380
+                $permittedFields[] = AccountManager::PROPERTY_TWITTER;
381
+            }
382
+        }
383
+
384
+        return new DataResponse($permittedFields);
385
+    }
386
+
387
+    /**
388
+     * @NoAdminRequired
389
+     * @NoSubAdminRequired
390
+     * @PasswordConfirmationRequired
391
+     *
392
+     * edit users
393
+     *
394
+     * @param string $userId
395
+     * @param string $key
396
+     * @param string $value
397
+     * @return DataResponse
398
+     * @throws OCSException
399
+     */
400
+    public function editUser(string $userId, string $key, string $value): DataResponse {
401
+        $currentLoggedInUser = $this->userSession->getUser();
402
+
403
+        $targetUser = $this->userManager->get($userId);
404
+        if ($targetUser === null) {
405
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
406
+        }
407
+
408
+        $permittedFields = [];
409
+        if ($targetUser->getUID() === $currentLoggedInUser->getUID()) {
410
+            // Editing self (display, email)
411
+            if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
412
+                $permittedFields[] = 'display';
413
+                $permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
414
+                $permittedFields[] = AccountManager::PROPERTY_EMAIL;
415
+            }
416
+
417
+            $permittedFields[] = 'password';
418
+            if ($this->config->getSystemValue('force_language', false) === false ||
419
+                $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
420
+                $permittedFields[] = 'language';
421
+            }
422
+
423
+            if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
424
+                $federatedFileSharing = new \OCA\FederatedFileSharing\AppInfo\Application();
425
+                $shareProvider = $federatedFileSharing->getFederatedShareProvider();
426
+                if ($shareProvider->isLookupServerUploadEnabled()) {
427
+                    $permittedFields[] = AccountManager::PROPERTY_PHONE;
428
+                    $permittedFields[] = AccountManager::PROPERTY_ADDRESS;
429
+                    $permittedFields[] = AccountManager::PROPERTY_WEBSITE;
430
+                    $permittedFields[] = AccountManager::PROPERTY_TWITTER;
431
+                }
432
+            }
433
+
434
+            // If admin they can edit their own quota
435
+            if ($this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
436
+                $permittedFields[] = 'quota';
437
+            }
438
+        } else {
439
+            // Check if admin / subadmin
440
+            $subAdminManager = $this->groupManager->getSubAdmin();
441
+            if ($subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
442
+            || $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
443
+                // They have permissions over the user
444
+                $permittedFields[] = 'display';
445
+                $permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
446
+                $permittedFields[] = AccountManager::PROPERTY_EMAIL;
447
+                $permittedFields[] = 'password';
448
+                $permittedFields[] = 'language';
449
+                $permittedFields[] = AccountManager::PROPERTY_PHONE;
450
+                $permittedFields[] = AccountManager::PROPERTY_ADDRESS;
451
+                $permittedFields[] = AccountManager::PROPERTY_WEBSITE;
452
+                $permittedFields[] = AccountManager::PROPERTY_TWITTER;
453
+                $permittedFields[] = 'quota';
454
+            } else {
455
+                // No rights
456
+                throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
457
+            }
458
+        }
459
+        // Check if permitted to edit this field
460
+        if (!in_array($key, $permittedFields)) {
461
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
462
+        }
463
+        // Process the edit
464
+        switch($key) {
465
+            case 'display':
466
+            case AccountManager::PROPERTY_DISPLAYNAME:
467
+                $targetUser->setDisplayName($value);
468
+                break;
469
+            case 'quota':
470
+                $quota = $value;
471
+                if ($quota !== 'none' && $quota !== 'default') {
472
+                    if (is_numeric($quota)) {
473
+                        $quota = (float) $quota;
474
+                    } else {
475
+                        $quota = \OCP\Util::computerFileSize($quota);
476
+                    }
477
+                    if ($quota === false) {
478
+                        throw new OCSException('Invalid quota value '.$value, 103);
479
+                    }
480
+                    if ($quota === 0) {
481
+                        $quota = 'default';
482
+                    }else if ($quota === -1) {
483
+                        $quota = 'none';
484
+                    } else {
485
+                        $quota = \OCP\Util::humanFileSize($quota);
486
+                    }
487
+                }
488
+                $targetUser->setQuota($quota);
489
+                break;
490
+            case 'password':
491
+                $targetUser->setPassword($value);
492
+                break;
493
+            case 'language':
494
+                $languagesCodes = $this->l10nFactory->findAvailableLanguages();
495
+                if (!in_array($value, $languagesCodes, true) && $value !== 'en') {
496
+                    throw new OCSException('Invalid language', 102);
497
+                }
498
+                $this->config->setUserValue($targetUser->getUID(), 'core', 'lang', $value);
499
+                break;
500
+            case AccountManager::PROPERTY_EMAIL:
501
+                if (filter_var($value, FILTER_VALIDATE_EMAIL) || $value === '') {
502
+                    $targetUser->setEMailAddress($value);
503
+                } else {
504
+                    throw new OCSException('', 102);
505
+                }
506
+                break;
507
+            case AccountManager::PROPERTY_PHONE:
508
+            case AccountManager::PROPERTY_ADDRESS:
509
+            case AccountManager::PROPERTY_WEBSITE:
510
+            case AccountManager::PROPERTY_TWITTER:
511
+                $userAccount = $this->accountManager->getUser($targetUser);
512
+                if ($userAccount[$key]['value'] !== $value) {
513
+                    $userAccount[$key]['value'] = $value;
514
+                    $this->accountManager->updateUser($targetUser, $userAccount);
515
+                }
516
+                break;
517
+            default:
518
+                throw new OCSException('', 103);
519
+        }
520
+        return new DataResponse();
521
+    }
522
+
523
+    /**
524
+     * @PasswordConfirmationRequired
525
+     * @NoAdminRequired
526
+     *
527
+     * @param string $userId
528
+     * @return DataResponse
529
+     * @throws OCSException
530
+     */
531
+    public function deleteUser(string $userId): DataResponse {
532
+        $currentLoggedInUser = $this->userSession->getUser();
533
+
534
+        $targetUser = $this->userManager->get($userId);
535
+
536
+        if ($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
537
+            throw new OCSException('', 101);
538
+        }
539
+
540
+        // If not permitted
541
+        $subAdminManager = $this->groupManager->getSubAdmin();
542
+        if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
543
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
544
+        }
545
+
546
+        // Go ahead with the delete
547
+        if ($targetUser->delete()) {
548
+            return new DataResponse();
549
+        } else {
550
+            throw new OCSException('', 101);
551
+        }
552
+    }
553
+
554
+    /**
555
+     * @PasswordConfirmationRequired
556
+     * @NoAdminRequired
557
+     *
558
+     * @param string $userId
559
+     * @return DataResponse
560
+     * @throws OCSException
561
+     * @throws OCSForbiddenException
562
+     */
563
+    public function disableUser(string $userId): DataResponse {
564
+        return $this->setEnabled($userId, false);
565
+    }
566
+
567
+    /**
568
+     * @PasswordConfirmationRequired
569
+     * @NoAdminRequired
570
+     *
571
+     * @param string $userId
572
+     * @return DataResponse
573
+     * @throws OCSException
574
+     * @throws OCSForbiddenException
575
+     */
576
+    public function enableUser(string $userId): DataResponse {
577
+        return $this->setEnabled($userId, true);
578
+    }
579
+
580
+    /**
581
+     * @param string $userId
582
+     * @param bool $value
583
+     * @return DataResponse
584
+     * @throws OCSException
585
+     */
586
+    private function setEnabled(string $userId, bool $value): DataResponse {
587
+        $currentLoggedInUser = $this->userSession->getUser();
588
+
589
+        $targetUser = $this->userManager->get($userId);
590
+        if ($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
591
+            throw new OCSException('', 101);
592
+        }
593
+
594
+        // If not permitted
595
+        $subAdminManager = $this->groupManager->getSubAdmin();
596
+        if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
597
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
598
+        }
599
+
600
+        // enable/disable the user now
601
+        $targetUser->setEnabled($value);
602
+        return new DataResponse();
603
+    }
604
+
605
+    /**
606
+     * @NoAdminRequired
607
+     * @NoSubAdminRequired
608
+     *
609
+     * @param string $userId
610
+     * @return DataResponse
611
+     * @throws OCSException
612
+     */
613
+    public function getUsersGroups(string $userId): DataResponse {
614
+        $loggedInUser = $this->userSession->getUser();
615
+
616
+        $targetUser = $this->userManager->get($userId);
617
+        if ($targetUser === null) {
618
+            throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
619
+        }
620
+
621
+        if ($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) {
622
+            // Self lookup or admin lookup
623
+            return new DataResponse([
624
+                'groups' => $this->groupManager->getUserGroupIds($targetUser)
625
+            ]);
626
+        } else {
627
+            $subAdminManager = $this->groupManager->getSubAdmin();
628
+
629
+            // Looking up someone else
630
+            if ($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) {
631
+                // Return the group that the method caller is subadmin of for the user in question
632
+                /** @var IGroup[] $getSubAdminsGroups */
633
+                $getSubAdminsGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
634
+                foreach ($getSubAdminsGroups as $key => $group) {
635
+                    $getSubAdminsGroups[$key] = $group->getGID();
636
+                }
637
+                $groups = array_intersect(
638
+                    $getSubAdminsGroups,
639
+                    $this->groupManager->getUserGroupIds($targetUser)
640
+                );
641
+                return new DataResponse(['groups' => $groups]);
642
+            } else {
643
+                // Not permitted
644
+                throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
645
+            }
646
+        }
647
+
648
+    }
649
+
650
+    /**
651
+     * @PasswordConfirmationRequired
652
+     * @NoAdminRequired
653
+     *
654
+     * @param string $userId
655
+     * @param string $groupid
656
+     * @return DataResponse
657
+     * @throws OCSException
658
+     */
659
+    public function addToGroup(string $userId, string $groupid = ''): DataResponse {
660
+        if ($groupid === '') {
661
+            throw new OCSException('', 101);
662
+        }
663
+
664
+        $group = $this->groupManager->get($groupid);
665
+        $targetUser = $this->userManager->get($userId);
666
+        if ($group === null) {
667
+            throw new OCSException('', 102);
668
+        }
669
+        if ($targetUser === null) {
670
+            throw new OCSException('', 103);
671
+        }
672
+
673
+        // If they're not an admin, check they are a subadmin of the group in question
674
+        $loggedInUser = $this->userSession->getUser();
675
+        $subAdminManager = $this->groupManager->getSubAdmin();
676
+        if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
677
+            throw new OCSException('', 104);
678
+        }
679
+
680
+        // Add user to group
681
+        $group->addUser($targetUser);
682
+        return new DataResponse();
683
+    }
684
+
685
+    /**
686
+     * @PasswordConfirmationRequired
687
+     * @NoAdminRequired
688
+     *
689
+     * @param string $userId
690
+     * @param string $groupid
691
+     * @return DataResponse
692
+     * @throws OCSException
693
+     */
694
+    public function removeFromGroup(string $userId, string $groupid): DataResponse {
695
+        $loggedInUser = $this->userSession->getUser();
696
+
697
+        if ($groupid === null || trim($groupid) === '') {
698
+            throw new OCSException('', 101);
699
+        }
700
+
701
+        $group = $this->groupManager->get($groupid);
702
+        if ($group === null) {
703
+            throw new OCSException('', 102);
704
+        }
705
+
706
+        $targetUser = $this->userManager->get($userId);
707
+        if ($targetUser === null) {
708
+            throw new OCSException('', 103);
709
+        }
710
+
711
+        // If they're not an admin, check they are a subadmin of the group in question
712
+        $subAdminManager = $this->groupManager->getSubAdmin();
713
+        if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
714
+            throw new OCSException('', 104);
715
+        }
716
+
717
+        // Check they aren't removing themselves from 'admin' or their 'subadmin; group
718
+        if ($targetUser->getUID() === $loggedInUser->getUID()) {
719
+            if ($this->groupManager->isAdmin($loggedInUser->getUID())) {
720
+                if ($group->getGID() === 'admin') {
721
+                    throw new OCSException('Cannot remove yourself from the admin group', 105);
722
+                }
723
+            } else {
724
+                // Not an admin, so the user must be a subadmin of this group, but that is not allowed.
725
+                throw new OCSException('Cannot remove yourself from this group as you are a SubAdmin', 105);
726
+            }
727
+
728
+        } else if (!$this->groupManager->isAdmin($loggedInUser->getUID())) {
729
+            /** @var IGroup[] $subAdminGroups */
730
+            $subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
731
+            $subAdminGroups = array_map(function (IGroup $subAdminGroup) {
732
+                return $subAdminGroup->getGID();
733
+            }, $subAdminGroups);
734
+            $userGroups = $this->groupManager->getUserGroupIds($targetUser);
735
+            $userSubAdminGroups = array_intersect($subAdminGroups, $userGroups);
736
+
737
+            if (count($userSubAdminGroups) <= 1) {
738
+                // Subadmin must not be able to remove a user from all their subadmin groups.
739
+                throw new OCSException('Cannot remove user from this group as this is the only remaining group you are a SubAdmin of', 105);
740
+            }
741
+        }
742
+
743
+        // Remove user from group
744
+        $group->removeUser($targetUser);
745
+        return new DataResponse();
746
+    }
747
+
748
+    /**
749
+     * Creates a subadmin
750
+     *
751
+     * @PasswordConfirmationRequired
752
+     *
753
+     * @param string $userId
754
+     * @param string $groupid
755
+     * @return DataResponse
756
+     * @throws OCSException
757
+     */
758
+    public function addSubAdmin(string $userId, string $groupid): DataResponse {
759
+        $group = $this->groupManager->get($groupid);
760
+        $user = $this->userManager->get($userId);
761
+
762
+        // Check if the user exists
763
+        if ($user === null) {
764
+            throw new OCSException('User does not exist', 101);
765
+        }
766
+        // Check if group exists
767
+        if ($group === null) {
768
+            throw new OCSException('Group does not exist',  102);
769
+        }
770
+        // Check if trying to make subadmin of admin group
771
+        if ($group->getGID() === 'admin') {
772
+            throw new OCSException('Cannot create subadmins for admin group', 103);
773
+        }
774
+
775
+        $subAdminManager = $this->groupManager->getSubAdmin();
776
+
777
+        // We cannot be subadmin twice
778
+        if ($subAdminManager->isSubAdminOfGroup($user, $group)) {
779
+            return new DataResponse();
780
+        }
781
+        // Go
782
+        if ($subAdminManager->createSubAdmin($user, $group)) {
783
+            return new DataResponse();
784
+        } else {
785
+            throw new OCSException('Unknown error occurred', 103);
786
+        }
787
+    }
788
+
789
+    /**
790
+     * Removes a subadmin from a group
791
+     *
792
+     * @PasswordConfirmationRequired
793
+     *
794
+     * @param string $userId
795
+     * @param string $groupid
796
+     * @return DataResponse
797
+     * @throws OCSException
798
+     */
799
+    public function removeSubAdmin(string $userId, string $groupid): DataResponse {
800
+        $group = $this->groupManager->get($groupid);
801
+        $user = $this->userManager->get($userId);
802
+        $subAdminManager = $this->groupManager->getSubAdmin();
803
+
804
+        // Check if the user exists
805
+        if ($user === null) {
806
+            throw new OCSException('User does not exist', 101);
807
+        }
808
+        // Check if the group exists
809
+        if ($group === null) {
810
+            throw new OCSException('Group does not exist', 101);
811
+        }
812
+        // Check if they are a subadmin of this said group
813
+        if (!$subAdminManager->isSubAdminOfGroup($user, $group)) {
814
+            throw new OCSException('User is not a subadmin of this group', 102);
815
+        }
816
+
817
+        // Go
818
+        if ($subAdminManager->deleteSubAdmin($user, $group)) {
819
+            return new DataResponse();
820
+        } else {
821
+            throw new OCSException('Unknown error occurred', 103);
822
+        }
823
+    }
824
+
825
+    /**
826
+     * Get the groups a user is a subadmin of
827
+     *
828
+     * @param string $userId
829
+     * @return DataResponse
830
+     * @throws OCSException
831
+     */
832
+    public function getUserSubAdminGroups(string $userId): DataResponse {
833
+        $groups = $this->getUserSubAdminGroupsData($userId);
834
+        return new DataResponse($groups);
835
+    }
836
+
837
+    /**
838
+     * @NoAdminRequired
839
+     * @PasswordConfirmationRequired
840
+     *
841
+     * resend welcome message
842
+     *
843
+     * @param string $userId
844
+     * @return DataResponse
845
+     * @throws OCSException
846
+     */
847
+    public function resendWelcomeMessage(string $userId): DataResponse {
848
+        $currentLoggedInUser = $this->userSession->getUser();
849
+
850
+        $targetUser = $this->userManager->get($userId);
851
+        if ($targetUser === null) {
852
+            throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
853
+        }
854
+
855
+        // Check if admin / subadmin
856
+        $subAdminManager = $this->groupManager->getSubAdmin();
857
+        if (!$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
858
+            && !$this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
859
+            // No rights
860
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
861
+        }
862
+
863
+        $email = $targetUser->getEMailAddress();
864
+        if ($email === '' || $email === null) {
865
+            throw new OCSException('Email address not available', 101);
866
+        }
867
+        $username = $targetUser->getUID();
868
+        $lang = $this->config->getUserValue($username, 'core', 'lang', 'en');
869
+        if (!$this->l10nFactory->languageExists('settings', $lang)) {
870
+            $lang = 'en';
871
+        }
872
+
873
+        $l10n = $this->l10nFactory->get('settings', $lang);
874
+
875
+        try {
876
+            $this->newUserMailHelper->setL10N($l10n);
877
+            $emailTemplate = $this->newUserMailHelper->generateTemplate($targetUser, false);
878
+            $this->newUserMailHelper->sendMail($targetUser, $emailTemplate);
879
+        } catch(\Exception $e) {
880
+            $this->logger->logException($e, [
881
+                'message' => "Can't send new user mail to $email",
882
+                'level' => \OCP\Util::ERROR,
883
+                'app' => 'settings',
884
+            ]);
885
+            throw new OCSException('Sending email failed', 102);
886
+        }
887
+
888
+        return new DataResponse();
889
+    }
890 890
 }
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 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
  *
@@ -126,7 +126,7 @@  discard block
 block discarded – undo
126 126
 		// Admin? Or SubAdmin?
127 127
 		$uid = $user->getUID();
128 128
 		$subAdminManager = $this->groupManager->getSubAdmin();
129
-		if ($this->groupManager->isAdmin($uid)){
129
+		if ($this->groupManager->isAdmin($uid)) {
130 130
 			$users = $this->userManager->search($search, $limit, $offset);
131 131
 		} else if ($subAdminManager->isSubAdmin($user)) {
132 132
 			$subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
@@ -159,7 +159,7 @@  discard block
 block discarded – undo
159 159
 		// Admin? Or SubAdmin?
160 160
 		$uid = $user->getUID();
161 161
 		$subAdminManager = $this->groupManager->getSubAdmin();
162
-		if ($this->groupManager->isAdmin($uid)){
162
+		if ($this->groupManager->isAdmin($uid)) {
163 163
 			$users = $this->userManager->search($search, $limit, $offset);
164 164
 		} else if ($subAdminManager->isSubAdmin($user)) {
165 165
 			$subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
@@ -222,7 +222,7 @@  discard block
 block discarded – undo
222 222
 					throw new OCSException('group '.$group.' does not exist', 104);
223 223
 				}
224 224
 				if (!$isAdmin && !$subAdminManager->isSubAdminOfGroup($user, $this->groupManager->get($group))) {
225
-					throw new OCSException('insufficient privileges for group '. $group, 105);
225
+					throw new OCSException('insufficient privileges for group '.$group, 105);
226 226
 				}
227 227
 			}
228 228
 		} else {
@@ -237,7 +237,7 @@  discard block
 block discarded – undo
237 237
 				$group = $this->groupManager->get($groupid);
238 238
 				// Check if group exists
239 239
 				if ($group === null) {
240
-					throw new OCSException('Subadmin group does not exist',  102);
240
+					throw new OCSException('Subadmin group does not exist', 102);
241 241
 				}
242 242
 				// Check if trying to make subadmin of admin group
243 243
 				if ($group->getGID() === 'admin') {
@@ -265,11 +265,11 @@  discard block
 block discarded – undo
265 265
 
266 266
 		try {
267 267
 			$newUser = $this->userManager->createUser($userid, $password);
268
-			$this->logger->info('Successful addUser call with userid: ' . $userid, ['app' => 'ocs_api']);
268
+			$this->logger->info('Successful addUser call with userid: '.$userid, ['app' => 'ocs_api']);
269 269
 
270 270
 			foreach ($groups as $group) {
271 271
 				$this->groupManager->get($group)->addUser($newUser);
272
-				$this->logger->info('Added userid ' . $userid . ' to group ' . $group, ['app' => 'ocs_api']);
272
+				$this->logger->info('Added userid '.$userid.' to group '.$group, ['app' => 'ocs_api']);
273 273
 			}
274 274
 			foreach ($subadminGroups as $group) {
275 275
 				$subAdminManager->createSubAdmin($newUser, $group);
@@ -297,7 +297,7 @@  discard block
 block discarded – undo
297 297
 
298 298
 			return new DataResponse();
299 299
 
300
-		} catch (HintException $e ) {
300
+		} catch (HintException $e) {
301 301
 			$this->logger->logException($e, [
302 302
 				'message' => 'Failed addUser attempt with hint exception.',
303 303
 				'level' => \OCP\Util::WARN,
@@ -345,7 +345,7 @@  discard block
 block discarded – undo
345 345
 	public function getCurrentUser(): DataResponse {
346 346
 		$user = $this->userSession->getUser();
347 347
 		if ($user) {
348
-			$data =  $this->getUserData($user->getUID());
348
+			$data = $this->getUserData($user->getUID());
349 349
 			// rename "displayname" to "display-name" only for this call to keep
350 350
 			// the API stable.
351 351
 			$data['display-name'] = $data['displayname'];
@@ -461,7 +461,7 @@  discard block
 block discarded – undo
461 461
 			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
462 462
 		}
463 463
 		// Process the edit
464
-		switch($key) {
464
+		switch ($key) {
465 465
 			case 'display':
466 466
 			case AccountManager::PROPERTY_DISPLAYNAME:
467 467
 				$targetUser->setDisplayName($value);
@@ -479,7 +479,7 @@  discard block
 block discarded – undo
479 479
 					}
480 480
 					if ($quota === 0) {
481 481
 						$quota = 'default';
482
-					}else if ($quota === -1) {
482
+					} else if ($quota === -1) {
483 483
 						$quota = 'none';
484 484
 					} else {
485 485
 						$quota = \OCP\Util::humanFileSize($quota);
@@ -728,7 +728,7 @@  discard block
 block discarded – undo
728 728
 		} else if (!$this->groupManager->isAdmin($loggedInUser->getUID())) {
729 729
 			/** @var IGroup[] $subAdminGroups */
730 730
 			$subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
731
-			$subAdminGroups = array_map(function (IGroup $subAdminGroup) {
731
+			$subAdminGroups = array_map(function(IGroup $subAdminGroup) {
732 732
 				return $subAdminGroup->getGID();
733 733
 			}, $subAdminGroups);
734 734
 			$userGroups = $this->groupManager->getUserGroupIds($targetUser);
@@ -765,7 +765,7 @@  discard block
 block discarded – undo
765 765
 		}
766 766
 		// Check if group exists
767 767
 		if ($group === null) {
768
-			throw new OCSException('Group does not exist',  102);
768
+			throw new OCSException('Group does not exist', 102);
769 769
 		}
770 770
 		// Check if trying to make subadmin of admin group
771 771
 		if ($group->getGID() === 'admin') {
@@ -876,7 +876,7 @@  discard block
 block discarded – undo
876 876
 			$this->newUserMailHelper->setL10N($l10n);
877 877
 			$emailTemplate = $this->newUserMailHelper->generateTemplate($targetUser, false);
878 878
 			$this->newUserMailHelper->sendMail($targetUser, $emailTemplate);
879
-		} catch(\Exception $e) {
879
+		} catch (\Exception $e) {
880 880
 			$this->logger->logException($e, [
881 881
 				'message' => "Can't send new user mail to $email",
882 882
 				'level' => \OCP\Util::ERROR,
Please login to merge, or discard this patch.
Braces   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -479,7 +479,7 @@
 block discarded – undo
479 479
 					}
480 480
 					if ($quota === 0) {
481 481
 						$quota = 'default';
482
-					}else if ($quota === -1) {
482
+					} else if ($quota === -1) {
483 483
 						$quota = 'none';
484 484
 					} else {
485 485
 						$quota = \OCP\Util::humanFileSize($quota);
Please login to merge, or discard this patch.
settings/users.php 2 patches
Indentation   +38 added lines, -38 removed lines patch added patch discarded remove patch
@@ -47,18 +47,18 @@  discard block
 block discarded – undo
47 47
 /* SORT OPTION: SORT_USERCOUNT or SORT_GROUPNAME */
48 48
 $sortGroupsBy = \OC\Group\MetaData::SORT_USERCOUNT;
49 49
 if ($config->getSystemValue('sort_groups_by_name', false)) {
50
-	$sortGroupsBy = \OC\Group\MetaData::SORT_GROUPNAME;
50
+    $sortGroupsBy = \OC\Group\MetaData::SORT_GROUPNAME;
51 51
 } else {
52
-	$isLDAPUsed = false;
53
-	if ($appManager->isEnabledForUser('user_ldap')) {
54
-		$isLDAPUsed =
55
-			$groupManager->isBackendUsed('\OCA\User_LDAP\Group_LDAP')
56
-			|| $groupManager->isBackendUsed('\OCA\User_LDAP\Group_Proxy');
57
-		if ($isLDAPUsed) {
58
-			// LDAP user count can be slow, so we sort by group name here
59
-			$sortGroupsBy = \OC\Group\MetaData::SORT_GROUPNAME;
60
-		}
61
-	}
52
+    $isLDAPUsed = false;
53
+    if ($appManager->isEnabledForUser('user_ldap')) {
54
+        $isLDAPUsed =
55
+            $groupManager->isBackendUsed('\OCA\User_LDAP\Group_LDAP')
56
+            || $groupManager->isBackendUsed('\OCA\User_LDAP\Group_Proxy');
57
+        if ($isLDAPUsed) {
58
+            // LDAP user count can be slow, so we sort by group name here
59
+            $sortGroupsBy = \OC\Group\MetaData::SORT_GROUPNAME;
60
+        }
61
+    }
62 62
 }
63 63
 
64 64
 /* ENCRYPTION CONFIG */
@@ -73,42 +73,42 @@  discard block
 block discarded – undo
73 73
 $isAdmin = \OC_User::isAdminUser($uid);
74 74
 
75 75
 $groupsInfo = new \OC\Group\MetaData(
76
-	$uid,
77
-	$isAdmin,
78
-	$groupManager,
79
-	\OC::$server->getUserSession()
76
+    $uid,
77
+    $isAdmin,
78
+    $groupManager,
79
+    \OC::$server->getUserSession()
80 80
 );
81 81
 
82 82
 $groupsInfo->setSorting($sortGroupsBy);
83 83
 list($adminGroup, $groups) = $groupsInfo->get();
84 84
 
85 85
 if ($isAdmin) {
86
-	$subAdmins = \OC::$server->getGroupManager()->getSubAdmin()->getAllSubAdmins();
87
-	// New class returns IUser[] so convert back
88
-	$result = [];
89
-	foreach ($subAdmins as $subAdmin) {
90
-		$result[] = [
91
-			'gid' => $subAdmin['group']->getGID(),
92
-			'uid' => $subAdmin['user']->getUID(),
93
-		];
94
-	}
95
-	$subAdmins = $result;
86
+    $subAdmins = \OC::$server->getGroupManager()->getSubAdmin()->getAllSubAdmins();
87
+    // New class returns IUser[] so convert back
88
+    $result = [];
89
+    foreach ($subAdmins as $subAdmin) {
90
+        $result[] = [
91
+            'gid' => $subAdmin['group']->getGID(),
92
+            'uid' => $subAdmin['user']->getUID(),
93
+        ];
94
+    }
95
+    $subAdmins = $result;
96 96
 } else {
97
-	/* Retrieve group IDs from $groups array, so we can pass that information into OC_Group::displayNamesInGroups() */
98
-	$gids = array();
99
-	foreach($groups as $group) {
100
-		if (isset($group['id'])) {
101
-			$gids[] = $group['id'];
102
-		}
103
-	}
104
-	$subAdmins = false;
97
+    /* Retrieve group IDs from $groups array, so we can pass that information into OC_Group::displayNamesInGroups() */
98
+    $gids = array();
99
+    foreach($groups as $group) {
100
+        if (isset($group['id'])) {
101
+            $gids[] = $group['id'];
102
+        }
103
+    }
104
+    $subAdmins = false;
105 105
 }
106 106
 
107 107
 $disabledUsers = $isLDAPUsed ? 0 : $userManager->countDisabledUsers();
108 108
 $disabledUsersGroup = [
109
-	'id' => '_disabled',
110
-	'name' => 'Disabled users',
111
-	'usercount' => $disabledUsers
109
+    'id' => '_disabled',
110
+    'name' => 'Disabled users',
111
+    'usercount' => $disabledUsers
112 112
 ];
113 113
 $allGroups = array_merge_recursive($adminGroup, $groups);
114 114
 
@@ -116,7 +116,7 @@  discard block
 block discarded – undo
116 116
 $quotaPreset = $config->getAppValue('files', 'quota_preset', '1 GB, 5 GB, 10 GB');
117 117
 $quotaPreset = explode(',', $quotaPreset);
118 118
 foreach ($quotaPreset as &$preset) {
119
-	$preset = trim($preset);
119
+    $preset = trim($preset);
120 120
 }
121 121
 $quotaPreset = array_diff($quotaPreset, array('default', 'none'));
122 122
 $defaultQuota = $config->getAppValue('files', 'default_quota', 'none');
@@ -125,7 +125,7 @@  discard block
 block discarded – undo
125 125
 
126 126
 /* TOTAL USERS COUNT */
127 127
 function addition($v, $w) {
128
-	return $v+$w;
128
+    return $v+$w;
129 129
 }
130 130
 $userCount = array_reduce($userManager->countUsers(), 'addition', 0);
131 131
 
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -97,7 +97,7 @@  discard block
 block discarded – undo
97 97
 } else {
98 98
 	/* Retrieve group IDs from $groups array, so we can pass that information into OC_Group::displayNamesInGroups() */
99 99
 	$gids = array();
100
-	foreach($groups as $group) {
100
+	foreach ($groups as $group) {
101 101
 		if (isset($group['id'])) {
102 102
 			$gids[] = $group['id'];
103 103
 		}
@@ -126,7 +126,7 @@  discard block
 block discarded – undo
126 126
 
127 127
 /* TOTAL USERS COUNT */
128 128
 function addition($v, $w) {
129
-	return $v+$w;
129
+	return $v + $w;
130 130
 }
131 131
 $userCount = array_reduce($userManager->countUsers(), 'addition', 0);
132 132
 
@@ -142,7 +142,7 @@  discard block
 block discarded – undo
142 142
 $serverData['subadmins'] = $subAdmins;
143 143
 $serverData['sortGroups'] = $sortGroupsBy;
144 144
 $serverData['quotaPreset'] = $quotaPreset;
145
-$serverData['userCount'] = $userCount-$disabledUsers;
145
+$serverData['userCount'] = $userCount - $disabledUsers;
146 146
 $serverData['languages'] = $languages;
147 147
 // Settings
148 148
 $serverData['defaultQuota'] = $defaultQuota;
Please login to merge, or discard this patch.
lib/private/Settings/Personal/PersonalInfo.php 2 patches
Indentation   +200 added lines, -200 removed lines patch added patch discarded remove patch
@@ -40,205 +40,205 @@
 block discarded – undo
40 40
 
41 41
 class PersonalInfo implements ISettings {
42 42
 
43
-	/** @var IConfig */
44
-	private $config;
45
-	/** @var IUserManager */
46
-	private $userManager;
47
-	/** @var AccountManager */
48
-	private $accountManager;
49
-	/** @var IGroupManager */
50
-	private $groupManager;
51
-	/** @var IAppManager */
52
-	private $appManager;
53
-	/** @var IFactory */
54
-	private $l10nFactory;
55
-	/** @var IL10N */
56
-	private $l;
57
-
58
-	/**
59
-	 * @param IConfig $config
60
-	 * @param IUserManager $userManager
61
-	 * @param IGroupManager $groupManager
62
-	 * @param AccountManager $accountManager
63
-	 * @param IFactory $l10nFactory
64
-	 * @param IL10N $l
65
-	 */
66
-	public function __construct(
67
-		IConfig $config,
68
-		IUserManager $userManager,
69
-		IGroupManager $groupManager,
70
-		AccountManager $accountManager,
71
-		IAppManager $appManager,
72
-		IFactory $l10nFactory,
73
-		IL10N $l
74
-	) {
75
-		$this->config = $config;
76
-		$this->userManager = $userManager;
77
-		$this->accountManager = $accountManager;
78
-		$this->groupManager = $groupManager;
79
-		$this->appManager = $appManager;
80
-		$this->l10nFactory = $l10nFactory;
81
-		$this->l = $l;
82
-	}
83
-
84
-	/**
85
-	 * @return TemplateResponse returns the instance with all parameters set, ready to be rendered
86
-	 * @since 9.1
87
-	 */
88
-	public function getForm() {
89
-		$federatedFileSharingEnabled = $this->appManager->isEnabledForUser('federatedfilesharing');
90
-		$lookupServerUploadEnabled = false;
91
-		if($federatedFileSharingEnabled) {
92
-			$federatedFileSharing = new Application();
93
-			$shareProvider = $federatedFileSharing->getFederatedShareProvider();
94
-			$lookupServerUploadEnabled = $shareProvider->isLookupServerUploadEnabled();
95
-		}
96
-
97
-		$uid = \OC_User::getUser();
98
-		$user = $this->userManager->get($uid);
99
-		$userData = $this->accountManager->getUser($user);
100
-
101
-		$storageInfo = \OC_Helper::getStorageInfo('/');
102
-		if ($storageInfo['quota'] === FileInfo::SPACE_UNLIMITED) {
103
-			$totalSpace = $this->l->t('Unlimited');
104
-		} else {
105
-			$totalSpace = \OC_Helper::humanFileSize($storageInfo['total']);
106
-		}
107
-
108
-		$languageParameters = $this->getLanguages($user);
109
-		$messageParameters = $this->getMessageParameters($userData);
110
-
111
-		$parameters = [
112
-			'total_space' => $totalSpace,
113
-			'usage' => \OC_Helper::humanFileSize($storageInfo['used']),
114
-			'usage_relative' => round($storageInfo['relative']),
115
-			'quota' => $storageInfo['quota'],
116
-			'avatarChangeSupported' => $user->canChangeAvatar(),
117
-			'lookupServerUploadEnabled' => $lookupServerUploadEnabled,
118
-			'avatarScope' => $userData[AccountManager::PROPERTY_AVATAR]['scope'],
119
-			'displayNameChangeSupported' => $user->canChangeDisplayName(),
120
-			'displayName' => $userData[AccountManager::PROPERTY_DISPLAYNAME]['value'],
121
-			'displayNameScope' => $userData[AccountManager::PROPERTY_DISPLAYNAME]['scope'],
122
-			'email' => $userData[AccountManager::PROPERTY_EMAIL]['value'],
123
-			'emailScope' => $userData[AccountManager::PROPERTY_EMAIL]['scope'],
124
-			'emailVerification' => $userData[AccountManager::PROPERTY_EMAIL]['verified'],
125
-			'phone' => $userData[AccountManager::PROPERTY_PHONE]['value'],
126
-			'phoneScope' => $userData[AccountManager::PROPERTY_PHONE]['scope'],
127
-			'address' => $userData[AccountManager::PROPERTY_ADDRESS]['value'],
128
-			'addressScope' => $userData[AccountManager::PROPERTY_ADDRESS]['scope'],
129
-			'website' =>  $userData[AccountManager::PROPERTY_WEBSITE]['value'],
130
-			'websiteScope' =>  $userData[AccountManager::PROPERTY_WEBSITE]['scope'],
131
-			'websiteVerification' => $userData[AccountManager::PROPERTY_WEBSITE]['verified'],
132
-			'twitter' => $userData[AccountManager::PROPERTY_TWITTER]['value'],
133
-			'twitterScope' => $userData[AccountManager::PROPERTY_TWITTER]['scope'],
134
-			'twitterVerification' => $userData[AccountManager::PROPERTY_TWITTER]['verified'],
135
-			'groups' => $this->getGroups($user),
136
-			'passwordChangeSupported' => $user->canChangePassword(),
137
-		] + $messageParameters + $languageParameters;
138
-
139
-
140
-		return new TemplateResponse('settings', 'settings/personal/personal.info', $parameters, '');
141
-	}
142
-
143
-	/**
144
-	 * @return string the section ID, e.g. 'sharing'
145
-	 * @since 9.1
146
-	 */
147
-	public function getSection() {
148
-		return 'personal-info';
149
-	}
150
-
151
-	/**
152
-	 * @return int whether the form should be rather on the top or bottom of
153
-	 * the admin section. The forms are arranged in ascending order of the
154
-	 * priority values. It is required to return a value between 0 and 100.
155
-	 *
156
-	 * E.g.: 70
157
-	 * @since 9.1
158
-	 */
159
-	public function getPriority() {
160
-		return 10;
161
-	}
162
-
163
-	/**
164
-	 * returns a sorted list of the user's group GIDs
165
-	 *
166
-	 * @param IUser $user
167
-	 * @return array
168
-	 */
169
-	private function getGroups(IUser $user) {
170
-		$groups = array_map(
171
-			function(IGroup $group) {
172
-				return $group->getDisplayName();
173
-			},
174
-			$this->groupManager->getUserGroups($user)
175
-		);
176
-		sort($groups);
177
-
178
-		return $groups;
179
-	}
180
-
181
-	/**
182
-	 * returns the user language, common language and other languages in an
183
-	 * associative array
184
-	 *
185
-	 * @param IUser $user
186
-	 * @return array
187
-	 */
188
-	private function getLanguages(IUser $user) {
189
-		$forceLanguage = $this->config->getSystemValue('force_language', false);
190
-		if($forceLanguage !== false) {
191
-			return [];
192
-		}
193
-
194
-		$uid = $user->getUID();
195
-
196
-		$userConfLang = $this->config->getUserValue($uid, 'core', 'lang', $this->l10nFactory->findLanguage());
197
-		$languages = $this->l10nFactory->getLanguages();
198
-
199
-		// associate the user language with the proper array
200
-		$userLangIndex = array_search($userConfLang, array_column($languages['commonlanguages'], 'code'));
201
-		$userLang = $languages['commonlanguages'][$userLangIndex];
202
-		// search in the other languages
203
-		if ($userLangIndex === false) {
204
-			$userLangIndex = array_search($userConfLang, array_column($languages['languages'], 'code'));		
205
-			$userLang = $languages['languages'][$userLangIndex];
206
-		}
207
-		// if user language is not available but set somehow: show the actual code as name
208
-		if (!is_array($userLang)) {
209
-			$userLang = [
210
-				'code' => $userConfLang,
211
-				'name' => $userConfLang,
212
-			];
213
-		}
214
-
215
-		return array_merge(
216
-			array('activelanguage' => $userLang),
217
-			$languages
218
-		);
219
-	}
220
-
221
-	/**
222
-	 * @param array $userData
223
-	 * @return array
224
-	 */
225
-	private function getMessageParameters(array $userData) {
226
-		$needVerifyMessage = [AccountManager::PROPERTY_EMAIL, AccountManager::PROPERTY_WEBSITE, AccountManager::PROPERTY_TWITTER];
227
-		$messageParameters = [];
228
-		foreach ($needVerifyMessage as $property) {
229
-			switch ($userData[$property]['verified']) {
230
-				case AccountManager::VERIFIED:
231
-					$message = $this->l->t('Verifying');
232
-					break;
233
-				case AccountManager::VERIFICATION_IN_PROGRESS:
234
-					$message = $this->l->t('Verifying …');
235
-					break;
236
-				default:
237
-					$message = $this->l->t('Verify');
238
-			}
239
-			$messageParameters[$property . 'Message'] = $message;
240
-		}
241
-		return $messageParameters;
242
-	}
43
+    /** @var IConfig */
44
+    private $config;
45
+    /** @var IUserManager */
46
+    private $userManager;
47
+    /** @var AccountManager */
48
+    private $accountManager;
49
+    /** @var IGroupManager */
50
+    private $groupManager;
51
+    /** @var IAppManager */
52
+    private $appManager;
53
+    /** @var IFactory */
54
+    private $l10nFactory;
55
+    /** @var IL10N */
56
+    private $l;
57
+
58
+    /**
59
+     * @param IConfig $config
60
+     * @param IUserManager $userManager
61
+     * @param IGroupManager $groupManager
62
+     * @param AccountManager $accountManager
63
+     * @param IFactory $l10nFactory
64
+     * @param IL10N $l
65
+     */
66
+    public function __construct(
67
+        IConfig $config,
68
+        IUserManager $userManager,
69
+        IGroupManager $groupManager,
70
+        AccountManager $accountManager,
71
+        IAppManager $appManager,
72
+        IFactory $l10nFactory,
73
+        IL10N $l
74
+    ) {
75
+        $this->config = $config;
76
+        $this->userManager = $userManager;
77
+        $this->accountManager = $accountManager;
78
+        $this->groupManager = $groupManager;
79
+        $this->appManager = $appManager;
80
+        $this->l10nFactory = $l10nFactory;
81
+        $this->l = $l;
82
+    }
83
+
84
+    /**
85
+     * @return TemplateResponse returns the instance with all parameters set, ready to be rendered
86
+     * @since 9.1
87
+     */
88
+    public function getForm() {
89
+        $federatedFileSharingEnabled = $this->appManager->isEnabledForUser('federatedfilesharing');
90
+        $lookupServerUploadEnabled = false;
91
+        if($federatedFileSharingEnabled) {
92
+            $federatedFileSharing = new Application();
93
+            $shareProvider = $federatedFileSharing->getFederatedShareProvider();
94
+            $lookupServerUploadEnabled = $shareProvider->isLookupServerUploadEnabled();
95
+        }
96
+
97
+        $uid = \OC_User::getUser();
98
+        $user = $this->userManager->get($uid);
99
+        $userData = $this->accountManager->getUser($user);
100
+
101
+        $storageInfo = \OC_Helper::getStorageInfo('/');
102
+        if ($storageInfo['quota'] === FileInfo::SPACE_UNLIMITED) {
103
+            $totalSpace = $this->l->t('Unlimited');
104
+        } else {
105
+            $totalSpace = \OC_Helper::humanFileSize($storageInfo['total']);
106
+        }
107
+
108
+        $languageParameters = $this->getLanguages($user);
109
+        $messageParameters = $this->getMessageParameters($userData);
110
+
111
+        $parameters = [
112
+            'total_space' => $totalSpace,
113
+            'usage' => \OC_Helper::humanFileSize($storageInfo['used']),
114
+            'usage_relative' => round($storageInfo['relative']),
115
+            'quota' => $storageInfo['quota'],
116
+            'avatarChangeSupported' => $user->canChangeAvatar(),
117
+            'lookupServerUploadEnabled' => $lookupServerUploadEnabled,
118
+            'avatarScope' => $userData[AccountManager::PROPERTY_AVATAR]['scope'],
119
+            'displayNameChangeSupported' => $user->canChangeDisplayName(),
120
+            'displayName' => $userData[AccountManager::PROPERTY_DISPLAYNAME]['value'],
121
+            'displayNameScope' => $userData[AccountManager::PROPERTY_DISPLAYNAME]['scope'],
122
+            'email' => $userData[AccountManager::PROPERTY_EMAIL]['value'],
123
+            'emailScope' => $userData[AccountManager::PROPERTY_EMAIL]['scope'],
124
+            'emailVerification' => $userData[AccountManager::PROPERTY_EMAIL]['verified'],
125
+            'phone' => $userData[AccountManager::PROPERTY_PHONE]['value'],
126
+            'phoneScope' => $userData[AccountManager::PROPERTY_PHONE]['scope'],
127
+            'address' => $userData[AccountManager::PROPERTY_ADDRESS]['value'],
128
+            'addressScope' => $userData[AccountManager::PROPERTY_ADDRESS]['scope'],
129
+            'website' =>  $userData[AccountManager::PROPERTY_WEBSITE]['value'],
130
+            'websiteScope' =>  $userData[AccountManager::PROPERTY_WEBSITE]['scope'],
131
+            'websiteVerification' => $userData[AccountManager::PROPERTY_WEBSITE]['verified'],
132
+            'twitter' => $userData[AccountManager::PROPERTY_TWITTER]['value'],
133
+            'twitterScope' => $userData[AccountManager::PROPERTY_TWITTER]['scope'],
134
+            'twitterVerification' => $userData[AccountManager::PROPERTY_TWITTER]['verified'],
135
+            'groups' => $this->getGroups($user),
136
+            'passwordChangeSupported' => $user->canChangePassword(),
137
+        ] + $messageParameters + $languageParameters;
138
+
139
+
140
+        return new TemplateResponse('settings', 'settings/personal/personal.info', $parameters, '');
141
+    }
142
+
143
+    /**
144
+     * @return string the section ID, e.g. 'sharing'
145
+     * @since 9.1
146
+     */
147
+    public function getSection() {
148
+        return 'personal-info';
149
+    }
150
+
151
+    /**
152
+     * @return int whether the form should be rather on the top or bottom of
153
+     * the admin section. The forms are arranged in ascending order of the
154
+     * priority values. It is required to return a value between 0 and 100.
155
+     *
156
+     * E.g.: 70
157
+     * @since 9.1
158
+     */
159
+    public function getPriority() {
160
+        return 10;
161
+    }
162
+
163
+    /**
164
+     * returns a sorted list of the user's group GIDs
165
+     *
166
+     * @param IUser $user
167
+     * @return array
168
+     */
169
+    private function getGroups(IUser $user) {
170
+        $groups = array_map(
171
+            function(IGroup $group) {
172
+                return $group->getDisplayName();
173
+            },
174
+            $this->groupManager->getUserGroups($user)
175
+        );
176
+        sort($groups);
177
+
178
+        return $groups;
179
+    }
180
+
181
+    /**
182
+     * returns the user language, common language and other languages in an
183
+     * associative array
184
+     *
185
+     * @param IUser $user
186
+     * @return array
187
+     */
188
+    private function getLanguages(IUser $user) {
189
+        $forceLanguage = $this->config->getSystemValue('force_language', false);
190
+        if($forceLanguage !== false) {
191
+            return [];
192
+        }
193
+
194
+        $uid = $user->getUID();
195
+
196
+        $userConfLang = $this->config->getUserValue($uid, 'core', 'lang', $this->l10nFactory->findLanguage());
197
+        $languages = $this->l10nFactory->getLanguages();
198
+
199
+        // associate the user language with the proper array
200
+        $userLangIndex = array_search($userConfLang, array_column($languages['commonlanguages'], 'code'));
201
+        $userLang = $languages['commonlanguages'][$userLangIndex];
202
+        // search in the other languages
203
+        if ($userLangIndex === false) {
204
+            $userLangIndex = array_search($userConfLang, array_column($languages['languages'], 'code'));		
205
+            $userLang = $languages['languages'][$userLangIndex];
206
+        }
207
+        // if user language is not available but set somehow: show the actual code as name
208
+        if (!is_array($userLang)) {
209
+            $userLang = [
210
+                'code' => $userConfLang,
211
+                'name' => $userConfLang,
212
+            ];
213
+        }
214
+
215
+        return array_merge(
216
+            array('activelanguage' => $userLang),
217
+            $languages
218
+        );
219
+    }
220
+
221
+    /**
222
+     * @param array $userData
223
+     * @return array
224
+     */
225
+    private function getMessageParameters(array $userData) {
226
+        $needVerifyMessage = [AccountManager::PROPERTY_EMAIL, AccountManager::PROPERTY_WEBSITE, AccountManager::PROPERTY_TWITTER];
227
+        $messageParameters = [];
228
+        foreach ($needVerifyMessage as $property) {
229
+            switch ($userData[$property]['verified']) {
230
+                case AccountManager::VERIFIED:
231
+                    $message = $this->l->t('Verifying');
232
+                    break;
233
+                case AccountManager::VERIFICATION_IN_PROGRESS:
234
+                    $message = $this->l->t('Verifying …');
235
+                    break;
236
+                default:
237
+                    $message = $this->l->t('Verify');
238
+            }
239
+            $messageParameters[$property . 'Message'] = $message;
240
+        }
241
+        return $messageParameters;
242
+    }
243 243
 
244 244
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -88,7 +88,7 @@  discard block
 block discarded – undo
88 88
 	public function getForm() {
89 89
 		$federatedFileSharingEnabled = $this->appManager->isEnabledForUser('federatedfilesharing');
90 90
 		$lookupServerUploadEnabled = false;
91
-		if($federatedFileSharingEnabled) {
91
+		if ($federatedFileSharingEnabled) {
92 92
 			$federatedFileSharing = new Application();
93 93
 			$shareProvider = $federatedFileSharing->getFederatedShareProvider();
94 94
 			$lookupServerUploadEnabled = $shareProvider->isLookupServerUploadEnabled();
@@ -187,7 +187,7 @@  discard block
 block discarded – undo
187 187
 	 */
188 188
 	private function getLanguages(IUser $user) {
189 189
 		$forceLanguage = $this->config->getSystemValue('force_language', false);
190
-		if($forceLanguage !== false) {
190
+		if ($forceLanguage !== false) {
191 191
 			return [];
192 192
 		}
193 193
 
@@ -236,7 +236,7 @@  discard block
 block discarded – undo
236 236
 				default:
237 237
 					$message = $this->l->t('Verify');
238 238
 			}
239
-			$messageParameters[$property . 'Message'] = $message;
239
+			$messageParameters[$property.'Message'] = $message;
240 240
 		}
241 241
 		return $messageParameters;
242 242
 	}
Please login to merge, or discard this patch.
lib/private/L10N/Factory.php 2 patches
Indentation   +476 added lines, -476 removed lines patch added patch discarded remove patch
@@ -40,480 +40,480 @@
 block discarded – undo
40 40
  */
41 41
 class Factory implements IFactory {
42 42
 
43
-	/** @var string */
44
-	protected $requestLanguage = '';
45
-
46
-	/**
47
-	 * cached instances
48
-	 * @var array Structure: Lang => App => \OCP\IL10N
49
-	 */
50
-	protected $instances = [];
51
-
52
-	/**
53
-	 * @var array Structure: App => string[]
54
-	 */
55
-	protected $availableLanguages = [];
56
-
57
-	/**
58
-	 * @var array Structure: string => callable
59
-	 */
60
-	protected $pluralFunctions = [];
61
-
62
-	const COMMON_LANGUAGE_CODES = [
63
-		'en', 'es', 'fr', 'de', 'de_DE', 'ja', 'ar', 'ru', 'nl', 'it',
64
-		'pt_BR', 'pt_PT', 'da', 'fi_FI', 'nb_NO', 'sv', 'tr', 'zh_CN', 'ko'
65
-	];
66
-
67
-	/** @var IConfig */
68
-	protected $config;
69
-
70
-	/** @var IRequest */
71
-	protected $request;
72
-
73
-	/** @var IUserSession */
74
-	protected $userSession;
75
-
76
-	/** @var string */
77
-	protected $serverRoot;
78
-
79
-	/**
80
-	 * @param IConfig $config
81
-	 * @param IRequest $request
82
-	 * @param IUserSession $userSession
83
-	 * @param string $serverRoot
84
-	 */
85
-	public function __construct(IConfig $config,
86
-								IRequest $request,
87
-								IUserSession $userSession,
88
-								$serverRoot) {
89
-		$this->config = $config;
90
-		$this->request = $request;
91
-		$this->userSession = $userSession;
92
-		$this->serverRoot = $serverRoot;
93
-	}
94
-
95
-	/**
96
-	 * Get a language instance
97
-	 *
98
-	 * @param string $app
99
-	 * @param string|null $lang
100
-	 * @return \OCP\IL10N
101
-	 */
102
-	public function get($app, $lang = null) {
103
-		$app = \OC_App::cleanAppId($app);
104
-		if ($lang !== null) {
105
-			$lang = str_replace(array('\0', '/', '\\', '..'), '', (string) $lang);
106
-		}
107
-
108
-		$forceLang = $this->config->getSystemValue('force_language', false);
109
-		if (is_string($forceLang)) {
110
-			$lang = $forceLang;
111
-		}
112
-
113
-		if ($lang === null || !$this->languageExists($app, $lang)) {
114
-			$lang = $this->findLanguage($app);
115
-		}
116
-
117
-		if (!isset($this->instances[$lang][$app])) {
118
-			$this->instances[$lang][$app] = new L10N(
119
-				$this, $app, $lang,
120
-				$this->getL10nFilesForApp($app, $lang)
121
-			);
122
-		}
123
-
124
-		return $this->instances[$lang][$app];
125
-	}
126
-
127
-	/**
128
-	 * Find the best language
129
-	 *
130
-	 * @param string|null $app App id or null for core
131
-	 * @return string language If nothing works it returns 'en'
132
-	 */
133
-	public function findLanguage($app = null) {
134
-		if ($this->requestLanguage !== '' && $this->languageExists($app, $this->requestLanguage)) {
135
-			return $this->requestLanguage;
136
-		}
137
-
138
-		/**
139
-		 * At this point Nextcloud might not yet be installed and thus the lookup
140
-		 * in the preferences table might fail. For this reason we need to check
141
-		 * whether the instance has already been installed
142
-		 *
143
-		 * @link https://github.com/owncloud/core/issues/21955
144
-		 */
145
-		if ($this->config->getSystemValue('installed', false)) {
146
-			$userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() :  null;
147
-			if (!is_null($userId)) {
148
-				$userLang = $this->config->getUserValue($userId, 'core', 'lang', null);
149
-			} else {
150
-				$userLang = null;
151
-			}
152
-		} else {
153
-			$userId = null;
154
-			$userLang = null;
155
-		}
156
-
157
-		if ($userLang) {
158
-			$this->requestLanguage = $userLang;
159
-			if ($this->languageExists($app, $userLang)) {
160
-				return $userLang;
161
-			}
162
-		}
163
-
164
-		try {
165
-			// Try to get the language from the Request
166
-			$lang = $this->getLanguageFromRequest($app);
167
-			if ($userId !== null && $app === null && !$userLang) {
168
-				$this->config->setUserValue($userId, 'core', 'lang', $lang);
169
-			}
170
-			return $lang;
171
-		} catch (LanguageNotFoundException $e) {
172
-			// Finding language from request failed fall back to default language
173
-			$defaultLanguage = $this->config->getSystemValue('default_language', false);
174
-			if ($defaultLanguage !== false && $this->languageExists($app, $defaultLanguage)) {
175
-				return $defaultLanguage;
176
-			}
177
-		}
178
-
179
-		// We could not find any language so fall back to english
180
-		return 'en';
181
-	}
182
-
183
-	/**
184
-	 * Find all available languages for an app
185
-	 *
186
-	 * @param string|null $app App id or null for core
187
-	 * @return array an array of available languages
188
-	 */
189
-	public function findAvailableLanguages($app = null) {
190
-		$key = $app;
191
-		if ($key === null) {
192
-			$key = 'null';
193
-		}
194
-
195
-		// also works with null as key
196
-		if (!empty($this->availableLanguages[$key])) {
197
-			return $this->availableLanguages[$key];
198
-		}
199
-
200
-		$available = ['en']; //english is always available
201
-		$dir = $this->findL10nDir($app);
202
-		if (is_dir($dir)) {
203
-			$files = scandir($dir);
204
-			if ($files !== false) {
205
-				foreach ($files as $file) {
206
-					if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
207
-						$available[] = substr($file, 0, -5);
208
-					}
209
-				}
210
-			}
211
-		}
212
-
213
-		// merge with translations from theme
214
-		$theme = $this->config->getSystemValue('theme');
215
-		if (!empty($theme)) {
216
-			$themeDir = $this->serverRoot . '/themes/' . $theme . substr($dir, strlen($this->serverRoot));
217
-
218
-			if (is_dir($themeDir)) {
219
-				$files = scandir($themeDir);
220
-				if ($files !== false) {
221
-					foreach ($files as $file) {
222
-						if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
223
-							$available[] = substr($file, 0, -5);
224
-						}
225
-					}
226
-				}
227
-			}
228
-		}
229
-
230
-		$this->availableLanguages[$key] = $available;
231
-		return $available;
232
-	}
233
-
234
-	/**
235
-	 * @param string|null $app App id or null for core
236
-	 * @param string $lang
237
-	 * @return bool
238
-	 */
239
-	public function languageExists($app, $lang) {
240
-		if ($lang === 'en') {//english is always available
241
-			return true;
242
-		}
243
-
244
-		$languages = $this->findAvailableLanguages($app);
245
-		return array_search($lang, $languages) !== false;
246
-	}
247
-
248
-	/**
249
-	 * @param string|null $app
250
-	 * @return string
251
-	 * @throws LanguageNotFoundException
252
-	 */
253
-	private function getLanguageFromRequest($app) {
254
-		$header = $this->request->getHeader('ACCEPT_LANGUAGE');
255
-		if ($header !== '') {
256
-			$available = $this->findAvailableLanguages($app);
257
-
258
-			// E.g. make sure that 'de' is before 'de_DE'.
259
-			sort($available);
260
-
261
-			$preferences = preg_split('/,\s*/', strtolower($header));
262
-			foreach ($preferences as $preference) {
263
-				list($preferred_language) = explode(';', $preference);
264
-				$preferred_language = str_replace('-', '_', $preferred_language);
265
-
266
-				foreach ($available as $available_language) {
267
-					if ($preferred_language === strtolower($available_language)) {
268
-						return $this->respectDefaultLanguage($app, $available_language);
269
-					}
270
-				}
271
-
272
-				// Fallback from de_De to de
273
-				foreach ($available as $available_language) {
274
-					if (substr($preferred_language, 0, 2) === $available_language) {
275
-						return $available_language;
276
-					}
277
-				}
278
-			}
279
-		}
280
-
281
-		throw new LanguageNotFoundException();
282
-	}
283
-
284
-	/**
285
-	 * if default language is set to de_DE (formal German) this should be
286
-	 * preferred to 'de' (non-formal German) if possible
287
-	 *
288
-	 * @param string|null $app
289
-	 * @param string $lang
290
-	 * @return string
291
-	 */
292
-	protected function respectDefaultLanguage($app, $lang) {
293
-		$result = $lang;
294
-		$defaultLanguage = $this->config->getSystemValue('default_language', false);
295
-
296
-		// use formal version of german ("Sie" instead of "Du") if the default
297
-		// language is set to 'de_DE' if possible
298
-		if (is_string($defaultLanguage) &&
299
-			strtolower($lang) === 'de' &&
300
-			strtolower($defaultLanguage) === 'de_de' &&
301
-			$this->languageExists($app, 'de_DE')
302
-		) {
303
-			$result = 'de_DE';
304
-		}
305
-
306
-		return $result;
307
-	}
308
-
309
-	/**
310
-	 * Checks if $sub is a subdirectory of $parent
311
-	 *
312
-	 * @param string $sub
313
-	 * @param string $parent
314
-	 * @return bool
315
-	 */
316
-	private function isSubDirectory($sub, $parent) {
317
-		// Check whether $sub contains no ".."
318
-		if (strpos($sub, '..') !== false) {
319
-			return false;
320
-		}
321
-
322
-		// Check whether $sub is a subdirectory of $parent
323
-		if (strpos($sub, $parent) === 0) {
324
-			return true;
325
-		}
326
-
327
-		return false;
328
-	}
329
-
330
-	/**
331
-	 * Get a list of language files that should be loaded
332
-	 *
333
-	 * @param string $app
334
-	 * @param string $lang
335
-	 * @return string[]
336
-	 */
337
-	// FIXME This method is only public, until OC_L10N does not need it anymore,
338
-	// FIXME This is also the reason, why it is not in the public interface
339
-	public function getL10nFilesForApp($app, $lang) {
340
-		$languageFiles = [];
341
-
342
-		$i18nDir = $this->findL10nDir($app);
343
-		$transFile = strip_tags($i18nDir) . strip_tags($lang) . '.json';
344
-
345
-		if (($this->isSubDirectory($transFile, $this->serverRoot . '/core/l10n/')
346
-				|| $this->isSubDirectory($transFile, $this->serverRoot . '/lib/l10n/')
347
-				|| $this->isSubDirectory($transFile, $this->serverRoot . '/settings/l10n/')
348
-				|| $this->isSubDirectory($transFile, \OC_App::getAppPath($app) . '/l10n/')
349
-			)
350
-			&& file_exists($transFile)) {
351
-			// load the translations file
352
-			$languageFiles[] = $transFile;
353
-		}
354
-
355
-		// merge with translations from theme
356
-		$theme = $this->config->getSystemValue('theme');
357
-		if (!empty($theme)) {
358
-			$transFile = $this->serverRoot . '/themes/' . $theme . substr($transFile, strlen($this->serverRoot));
359
-			if (file_exists($transFile)) {
360
-				$languageFiles[] = $transFile;
361
-			}
362
-		}
363
-
364
-		return $languageFiles;
365
-	}
366
-
367
-	/**
368
-	 * find the l10n directory
369
-	 *
370
-	 * @param string $app App id or empty string for core
371
-	 * @return string directory
372
-	 */
373
-	protected function findL10nDir($app = null) {
374
-		if (in_array($app, ['core', 'lib', 'settings'])) {
375
-			if (file_exists($this->serverRoot . '/' . $app . '/l10n/')) {
376
-				return $this->serverRoot . '/' . $app . '/l10n/';
377
-			}
378
-		} else if ($app && \OC_App::getAppPath($app) !== false) {
379
-			// Check if the app is in the app folder
380
-			return \OC_App::getAppPath($app) . '/l10n/';
381
-		}
382
-		return $this->serverRoot . '/core/l10n/';
383
-	}
384
-
385
-
386
-	/**
387
-	 * Creates a function from the plural string
388
-	 *
389
-	 * Parts of the code is copied from Habari:
390
-	 * https://github.com/habari/system/blob/master/classes/locale.php
391
-	 * @param string $string
392
-	 * @return string
393
-	 */
394
-	public function createPluralFunction($string) {
395
-		if (isset($this->pluralFunctions[$string])) {
396
-			return $this->pluralFunctions[$string];
397
-		}
398
-
399
-		if (preg_match( '/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
400
-			// sanitize
401
-			$nplurals = preg_replace( '/[^0-9]/', '', $matches[1] );
402
-			$plural = preg_replace( '#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2] );
403
-
404
-			$body = str_replace(
405
-				array( 'plural', 'n', '$n$plurals', ),
406
-				array( '$plural', '$n', '$nplurals', ),
407
-				'nplurals='. $nplurals . '; plural=' . $plural
408
-			);
409
-
410
-			// add parents
411
-			// important since PHP's ternary evaluates from left to right
412
-			$body .= ';';
413
-			$res = '';
414
-			$p = 0;
415
-			$length = strlen($body);
416
-			for($i = 0; $i < $length; $i++) {
417
-				$ch = $body[$i];
418
-				switch ( $ch ) {
419
-					case '?':
420
-						$res .= ' ? (';
421
-						$p++;
422
-						break;
423
-					case ':':
424
-						$res .= ') : (';
425
-						break;
426
-					case ';':
427
-						$res .= str_repeat( ')', $p ) . ';';
428
-						$p = 0;
429
-						break;
430
-					default:
431
-						$res .= $ch;
432
-				}
433
-			}
434
-
435
-			$body = $res . 'return ($plural>=$nplurals?$nplurals-1:$plural);';
436
-			$function = create_function('$n', $body);
437
-			$this->pluralFunctions[$string] = $function;
438
-			return $function;
439
-		} else {
440
-			// default: one plural form for all cases but n==1 (english)
441
-			$function = create_function(
442
-				'$n',
443
-				'$nplurals=2;$plural=($n==1?0:1);return ($plural>=$nplurals?$nplurals-1:$plural);'
444
-			);
445
-			$this->pluralFunctions[$string] = $function;
446
-			return $function;
447
-		}
448
-	}
449
-
450
-	/**
451
-	 * returns the common language and other languages in an
452
-	 * associative array
453
-	 *
454
-	 * @return array
455
-	 */
456
-	public function getLanguages() {
457
-		$forceLanguage = $this->config->getSystemValue('force_language', false);
458
-		if ($forceLanguage !== false) {
459
-			return [];
460
-		}
461
-
462
-		$languageCodes = $this->findAvailableLanguages();
463
-
464
-		$commonLanguages = [];
465
-		$languages = [];
466
-
467
-		foreach($languageCodes as $lang) {
468
-			$l = $this->get('lib', $lang);
469
-			// TRANSLATORS this is the language name for the language switcher in the personal settings and should be the localized version
470
-			$potentialName = (string) $l->t('__language_name__');
471
-			if ($l->getLanguageCode() === $lang && $potentialName[0] !== '_') {//first check if the language name is in the translation file
472
-				$ln = array(
473
-					'code' => $lang,
474
-					'name' => $potentialName
475
-				);
476
-			} else if ($lang === 'en') {
477
-				$ln = array(
478
-					'code' => $lang,
479
-					'name' => 'English (US)'
480
-				);
481
-			} else {//fallback to language code
482
-				$ln = array(
483
-					'code' => $lang,
484
-					'name' => $lang
485
-				);
486
-			}
487
-
488
-			// put appropriate languages into appropriate arrays, to print them sorted
489
-			// common languages -> divider -> other languages
490
-			if (in_array($lang, self::COMMON_LANGUAGE_CODES)) {
491
-				$commonLanguages[array_search($lang, self::COMMON_LANGUAGE_CODES)] = $ln;
492
-			} else {
493
-				$languages[] = $ln;
494
-			}
495
-		}
496
-
497
-		ksort($commonLanguages);
498
-
499
-		// sort now by displayed language not the iso-code
500
-		usort( $languages, function ($a, $b) {
501
-			if ($a['code'] === $a['name'] && $b['code'] !== $b['name']) {
502
-				// If a doesn't have a name, but b does, list b before a
503
-				return 1;
504
-			}
505
-			if ($a['code'] !== $a['name'] && $b['code'] === $b['name']) {
506
-				// If a does have a name, but b doesn't, list a before b
507
-				return -1;
508
-			}
509
-			// Otherwise compare the names
510
-			return strcmp($a['name'], $b['name']);
511
-		});
512
-
513
-		return [
514
-			// reset indexes
515
-			'commonlanguages' => array_values($commonLanguages),
516
-			'languages' => $languages
517
-		];
518
-	}
43
+    /** @var string */
44
+    protected $requestLanguage = '';
45
+
46
+    /**
47
+     * cached instances
48
+     * @var array Structure: Lang => App => \OCP\IL10N
49
+     */
50
+    protected $instances = [];
51
+
52
+    /**
53
+     * @var array Structure: App => string[]
54
+     */
55
+    protected $availableLanguages = [];
56
+
57
+    /**
58
+     * @var array Structure: string => callable
59
+     */
60
+    protected $pluralFunctions = [];
61
+
62
+    const COMMON_LANGUAGE_CODES = [
63
+        'en', 'es', 'fr', 'de', 'de_DE', 'ja', 'ar', 'ru', 'nl', 'it',
64
+        'pt_BR', 'pt_PT', 'da', 'fi_FI', 'nb_NO', 'sv', 'tr', 'zh_CN', 'ko'
65
+    ];
66
+
67
+    /** @var IConfig */
68
+    protected $config;
69
+
70
+    /** @var IRequest */
71
+    protected $request;
72
+
73
+    /** @var IUserSession */
74
+    protected $userSession;
75
+
76
+    /** @var string */
77
+    protected $serverRoot;
78
+
79
+    /**
80
+     * @param IConfig $config
81
+     * @param IRequest $request
82
+     * @param IUserSession $userSession
83
+     * @param string $serverRoot
84
+     */
85
+    public function __construct(IConfig $config,
86
+                                IRequest $request,
87
+                                IUserSession $userSession,
88
+                                $serverRoot) {
89
+        $this->config = $config;
90
+        $this->request = $request;
91
+        $this->userSession = $userSession;
92
+        $this->serverRoot = $serverRoot;
93
+    }
94
+
95
+    /**
96
+     * Get a language instance
97
+     *
98
+     * @param string $app
99
+     * @param string|null $lang
100
+     * @return \OCP\IL10N
101
+     */
102
+    public function get($app, $lang = null) {
103
+        $app = \OC_App::cleanAppId($app);
104
+        if ($lang !== null) {
105
+            $lang = str_replace(array('\0', '/', '\\', '..'), '', (string) $lang);
106
+        }
107
+
108
+        $forceLang = $this->config->getSystemValue('force_language', false);
109
+        if (is_string($forceLang)) {
110
+            $lang = $forceLang;
111
+        }
112
+
113
+        if ($lang === null || !$this->languageExists($app, $lang)) {
114
+            $lang = $this->findLanguage($app);
115
+        }
116
+
117
+        if (!isset($this->instances[$lang][$app])) {
118
+            $this->instances[$lang][$app] = new L10N(
119
+                $this, $app, $lang,
120
+                $this->getL10nFilesForApp($app, $lang)
121
+            );
122
+        }
123
+
124
+        return $this->instances[$lang][$app];
125
+    }
126
+
127
+    /**
128
+     * Find the best language
129
+     *
130
+     * @param string|null $app App id or null for core
131
+     * @return string language If nothing works it returns 'en'
132
+     */
133
+    public function findLanguage($app = null) {
134
+        if ($this->requestLanguage !== '' && $this->languageExists($app, $this->requestLanguage)) {
135
+            return $this->requestLanguage;
136
+        }
137
+
138
+        /**
139
+         * At this point Nextcloud might not yet be installed and thus the lookup
140
+         * in the preferences table might fail. For this reason we need to check
141
+         * whether the instance has already been installed
142
+         *
143
+         * @link https://github.com/owncloud/core/issues/21955
144
+         */
145
+        if ($this->config->getSystemValue('installed', false)) {
146
+            $userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() :  null;
147
+            if (!is_null($userId)) {
148
+                $userLang = $this->config->getUserValue($userId, 'core', 'lang', null);
149
+            } else {
150
+                $userLang = null;
151
+            }
152
+        } else {
153
+            $userId = null;
154
+            $userLang = null;
155
+        }
156
+
157
+        if ($userLang) {
158
+            $this->requestLanguage = $userLang;
159
+            if ($this->languageExists($app, $userLang)) {
160
+                return $userLang;
161
+            }
162
+        }
163
+
164
+        try {
165
+            // Try to get the language from the Request
166
+            $lang = $this->getLanguageFromRequest($app);
167
+            if ($userId !== null && $app === null && !$userLang) {
168
+                $this->config->setUserValue($userId, 'core', 'lang', $lang);
169
+            }
170
+            return $lang;
171
+        } catch (LanguageNotFoundException $e) {
172
+            // Finding language from request failed fall back to default language
173
+            $defaultLanguage = $this->config->getSystemValue('default_language', false);
174
+            if ($defaultLanguage !== false && $this->languageExists($app, $defaultLanguage)) {
175
+                return $defaultLanguage;
176
+            }
177
+        }
178
+
179
+        // We could not find any language so fall back to english
180
+        return 'en';
181
+    }
182
+
183
+    /**
184
+     * Find all available languages for an app
185
+     *
186
+     * @param string|null $app App id or null for core
187
+     * @return array an array of available languages
188
+     */
189
+    public function findAvailableLanguages($app = null) {
190
+        $key = $app;
191
+        if ($key === null) {
192
+            $key = 'null';
193
+        }
194
+
195
+        // also works with null as key
196
+        if (!empty($this->availableLanguages[$key])) {
197
+            return $this->availableLanguages[$key];
198
+        }
199
+
200
+        $available = ['en']; //english is always available
201
+        $dir = $this->findL10nDir($app);
202
+        if (is_dir($dir)) {
203
+            $files = scandir($dir);
204
+            if ($files !== false) {
205
+                foreach ($files as $file) {
206
+                    if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
207
+                        $available[] = substr($file, 0, -5);
208
+                    }
209
+                }
210
+            }
211
+        }
212
+
213
+        // merge with translations from theme
214
+        $theme = $this->config->getSystemValue('theme');
215
+        if (!empty($theme)) {
216
+            $themeDir = $this->serverRoot . '/themes/' . $theme . substr($dir, strlen($this->serverRoot));
217
+
218
+            if (is_dir($themeDir)) {
219
+                $files = scandir($themeDir);
220
+                if ($files !== false) {
221
+                    foreach ($files as $file) {
222
+                        if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
223
+                            $available[] = substr($file, 0, -5);
224
+                        }
225
+                    }
226
+                }
227
+            }
228
+        }
229
+
230
+        $this->availableLanguages[$key] = $available;
231
+        return $available;
232
+    }
233
+
234
+    /**
235
+     * @param string|null $app App id or null for core
236
+     * @param string $lang
237
+     * @return bool
238
+     */
239
+    public function languageExists($app, $lang) {
240
+        if ($lang === 'en') {//english is always available
241
+            return true;
242
+        }
243
+
244
+        $languages = $this->findAvailableLanguages($app);
245
+        return array_search($lang, $languages) !== false;
246
+    }
247
+
248
+    /**
249
+     * @param string|null $app
250
+     * @return string
251
+     * @throws LanguageNotFoundException
252
+     */
253
+    private function getLanguageFromRequest($app) {
254
+        $header = $this->request->getHeader('ACCEPT_LANGUAGE');
255
+        if ($header !== '') {
256
+            $available = $this->findAvailableLanguages($app);
257
+
258
+            // E.g. make sure that 'de' is before 'de_DE'.
259
+            sort($available);
260
+
261
+            $preferences = preg_split('/,\s*/', strtolower($header));
262
+            foreach ($preferences as $preference) {
263
+                list($preferred_language) = explode(';', $preference);
264
+                $preferred_language = str_replace('-', '_', $preferred_language);
265
+
266
+                foreach ($available as $available_language) {
267
+                    if ($preferred_language === strtolower($available_language)) {
268
+                        return $this->respectDefaultLanguage($app, $available_language);
269
+                    }
270
+                }
271
+
272
+                // Fallback from de_De to de
273
+                foreach ($available as $available_language) {
274
+                    if (substr($preferred_language, 0, 2) === $available_language) {
275
+                        return $available_language;
276
+                    }
277
+                }
278
+            }
279
+        }
280
+
281
+        throw new LanguageNotFoundException();
282
+    }
283
+
284
+    /**
285
+     * if default language is set to de_DE (formal German) this should be
286
+     * preferred to 'de' (non-formal German) if possible
287
+     *
288
+     * @param string|null $app
289
+     * @param string $lang
290
+     * @return string
291
+     */
292
+    protected function respectDefaultLanguage($app, $lang) {
293
+        $result = $lang;
294
+        $defaultLanguage = $this->config->getSystemValue('default_language', false);
295
+
296
+        // use formal version of german ("Sie" instead of "Du") if the default
297
+        // language is set to 'de_DE' if possible
298
+        if (is_string($defaultLanguage) &&
299
+            strtolower($lang) === 'de' &&
300
+            strtolower($defaultLanguage) === 'de_de' &&
301
+            $this->languageExists($app, 'de_DE')
302
+        ) {
303
+            $result = 'de_DE';
304
+        }
305
+
306
+        return $result;
307
+    }
308
+
309
+    /**
310
+     * Checks if $sub is a subdirectory of $parent
311
+     *
312
+     * @param string $sub
313
+     * @param string $parent
314
+     * @return bool
315
+     */
316
+    private function isSubDirectory($sub, $parent) {
317
+        // Check whether $sub contains no ".."
318
+        if (strpos($sub, '..') !== false) {
319
+            return false;
320
+        }
321
+
322
+        // Check whether $sub is a subdirectory of $parent
323
+        if (strpos($sub, $parent) === 0) {
324
+            return true;
325
+        }
326
+
327
+        return false;
328
+    }
329
+
330
+    /**
331
+     * Get a list of language files that should be loaded
332
+     *
333
+     * @param string $app
334
+     * @param string $lang
335
+     * @return string[]
336
+     */
337
+    // FIXME This method is only public, until OC_L10N does not need it anymore,
338
+    // FIXME This is also the reason, why it is not in the public interface
339
+    public function getL10nFilesForApp($app, $lang) {
340
+        $languageFiles = [];
341
+
342
+        $i18nDir = $this->findL10nDir($app);
343
+        $transFile = strip_tags($i18nDir) . strip_tags($lang) . '.json';
344
+
345
+        if (($this->isSubDirectory($transFile, $this->serverRoot . '/core/l10n/')
346
+                || $this->isSubDirectory($transFile, $this->serverRoot . '/lib/l10n/')
347
+                || $this->isSubDirectory($transFile, $this->serverRoot . '/settings/l10n/')
348
+                || $this->isSubDirectory($transFile, \OC_App::getAppPath($app) . '/l10n/')
349
+            )
350
+            && file_exists($transFile)) {
351
+            // load the translations file
352
+            $languageFiles[] = $transFile;
353
+        }
354
+
355
+        // merge with translations from theme
356
+        $theme = $this->config->getSystemValue('theme');
357
+        if (!empty($theme)) {
358
+            $transFile = $this->serverRoot . '/themes/' . $theme . substr($transFile, strlen($this->serverRoot));
359
+            if (file_exists($transFile)) {
360
+                $languageFiles[] = $transFile;
361
+            }
362
+        }
363
+
364
+        return $languageFiles;
365
+    }
366
+
367
+    /**
368
+     * find the l10n directory
369
+     *
370
+     * @param string $app App id or empty string for core
371
+     * @return string directory
372
+     */
373
+    protected function findL10nDir($app = null) {
374
+        if (in_array($app, ['core', 'lib', 'settings'])) {
375
+            if (file_exists($this->serverRoot . '/' . $app . '/l10n/')) {
376
+                return $this->serverRoot . '/' . $app . '/l10n/';
377
+            }
378
+        } else if ($app && \OC_App::getAppPath($app) !== false) {
379
+            // Check if the app is in the app folder
380
+            return \OC_App::getAppPath($app) . '/l10n/';
381
+        }
382
+        return $this->serverRoot . '/core/l10n/';
383
+    }
384
+
385
+
386
+    /**
387
+     * Creates a function from the plural string
388
+     *
389
+     * Parts of the code is copied from Habari:
390
+     * https://github.com/habari/system/blob/master/classes/locale.php
391
+     * @param string $string
392
+     * @return string
393
+     */
394
+    public function createPluralFunction($string) {
395
+        if (isset($this->pluralFunctions[$string])) {
396
+            return $this->pluralFunctions[$string];
397
+        }
398
+
399
+        if (preg_match( '/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
400
+            // sanitize
401
+            $nplurals = preg_replace( '/[^0-9]/', '', $matches[1] );
402
+            $plural = preg_replace( '#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2] );
403
+
404
+            $body = str_replace(
405
+                array( 'plural', 'n', '$n$plurals', ),
406
+                array( '$plural', '$n', '$nplurals', ),
407
+                'nplurals='. $nplurals . '; plural=' . $plural
408
+            );
409
+
410
+            // add parents
411
+            // important since PHP's ternary evaluates from left to right
412
+            $body .= ';';
413
+            $res = '';
414
+            $p = 0;
415
+            $length = strlen($body);
416
+            for($i = 0; $i < $length; $i++) {
417
+                $ch = $body[$i];
418
+                switch ( $ch ) {
419
+                    case '?':
420
+                        $res .= ' ? (';
421
+                        $p++;
422
+                        break;
423
+                    case ':':
424
+                        $res .= ') : (';
425
+                        break;
426
+                    case ';':
427
+                        $res .= str_repeat( ')', $p ) . ';';
428
+                        $p = 0;
429
+                        break;
430
+                    default:
431
+                        $res .= $ch;
432
+                }
433
+            }
434
+
435
+            $body = $res . 'return ($plural>=$nplurals?$nplurals-1:$plural);';
436
+            $function = create_function('$n', $body);
437
+            $this->pluralFunctions[$string] = $function;
438
+            return $function;
439
+        } else {
440
+            // default: one plural form for all cases but n==1 (english)
441
+            $function = create_function(
442
+                '$n',
443
+                '$nplurals=2;$plural=($n==1?0:1);return ($plural>=$nplurals?$nplurals-1:$plural);'
444
+            );
445
+            $this->pluralFunctions[$string] = $function;
446
+            return $function;
447
+        }
448
+    }
449
+
450
+    /**
451
+     * returns the common language and other languages in an
452
+     * associative array
453
+     *
454
+     * @return array
455
+     */
456
+    public function getLanguages() {
457
+        $forceLanguage = $this->config->getSystemValue('force_language', false);
458
+        if ($forceLanguage !== false) {
459
+            return [];
460
+        }
461
+
462
+        $languageCodes = $this->findAvailableLanguages();
463
+
464
+        $commonLanguages = [];
465
+        $languages = [];
466
+
467
+        foreach($languageCodes as $lang) {
468
+            $l = $this->get('lib', $lang);
469
+            // TRANSLATORS this is the language name for the language switcher in the personal settings and should be the localized version
470
+            $potentialName = (string) $l->t('__language_name__');
471
+            if ($l->getLanguageCode() === $lang && $potentialName[0] !== '_') {//first check if the language name is in the translation file
472
+                $ln = array(
473
+                    'code' => $lang,
474
+                    'name' => $potentialName
475
+                );
476
+            } else if ($lang === 'en') {
477
+                $ln = array(
478
+                    'code' => $lang,
479
+                    'name' => 'English (US)'
480
+                );
481
+            } else {//fallback to language code
482
+                $ln = array(
483
+                    'code' => $lang,
484
+                    'name' => $lang
485
+                );
486
+            }
487
+
488
+            // put appropriate languages into appropriate arrays, to print them sorted
489
+            // common languages -> divider -> other languages
490
+            if (in_array($lang, self::COMMON_LANGUAGE_CODES)) {
491
+                $commonLanguages[array_search($lang, self::COMMON_LANGUAGE_CODES)] = $ln;
492
+            } else {
493
+                $languages[] = $ln;
494
+            }
495
+        }
496
+
497
+        ksort($commonLanguages);
498
+
499
+        // sort now by displayed language not the iso-code
500
+        usort( $languages, function ($a, $b) {
501
+            if ($a['code'] === $a['name'] && $b['code'] !== $b['name']) {
502
+                // If a doesn't have a name, but b does, list b before a
503
+                return 1;
504
+            }
505
+            if ($a['code'] !== $a['name'] && $b['code'] === $b['name']) {
506
+                // If a does have a name, but b doesn't, list a before b
507
+                return -1;
508
+            }
509
+            // Otherwise compare the names
510
+            return strcmp($a['name'], $b['name']);
511
+        });
512
+
513
+        return [
514
+            // reset indexes
515
+            'commonlanguages' => array_values($commonLanguages),
516
+            'languages' => $languages
517
+        ];
518
+    }
519 519
 }
Please login to merge, or discard this patch.
Spacing   +24 added lines, -24 removed lines patch added patch discarded remove patch
@@ -143,7 +143,7 @@  discard block
 block discarded – undo
143 143
 		 * @link https://github.com/owncloud/core/issues/21955
144 144
 		 */
145 145
 		if ($this->config->getSystemValue('installed', false)) {
146
-			$userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() :  null;
146
+			$userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() : null;
147 147
 			if (!is_null($userId)) {
148 148
 				$userLang = $this->config->getUserValue($userId, 'core', 'lang', null);
149 149
 			} else {
@@ -213,7 +213,7 @@  discard block
 block discarded – undo
213 213
 		// merge with translations from theme
214 214
 		$theme = $this->config->getSystemValue('theme');
215 215
 		if (!empty($theme)) {
216
-			$themeDir = $this->serverRoot . '/themes/' . $theme . substr($dir, strlen($this->serverRoot));
216
+			$themeDir = $this->serverRoot.'/themes/'.$theme.substr($dir, strlen($this->serverRoot));
217 217
 
218 218
 			if (is_dir($themeDir)) {
219 219
 				$files = scandir($themeDir);
@@ -340,12 +340,12 @@  discard block
 block discarded – undo
340 340
 		$languageFiles = [];
341 341
 
342 342
 		$i18nDir = $this->findL10nDir($app);
343
-		$transFile = strip_tags($i18nDir) . strip_tags($lang) . '.json';
343
+		$transFile = strip_tags($i18nDir).strip_tags($lang).'.json';
344 344
 
345
-		if (($this->isSubDirectory($transFile, $this->serverRoot . '/core/l10n/')
346
-				|| $this->isSubDirectory($transFile, $this->serverRoot . '/lib/l10n/')
347
-				|| $this->isSubDirectory($transFile, $this->serverRoot . '/settings/l10n/')
348
-				|| $this->isSubDirectory($transFile, \OC_App::getAppPath($app) . '/l10n/')
345
+		if (($this->isSubDirectory($transFile, $this->serverRoot.'/core/l10n/')
346
+				|| $this->isSubDirectory($transFile, $this->serverRoot.'/lib/l10n/')
347
+				|| $this->isSubDirectory($transFile, $this->serverRoot.'/settings/l10n/')
348
+				|| $this->isSubDirectory($transFile, \OC_App::getAppPath($app).'/l10n/')
349 349
 			)
350 350
 			&& file_exists($transFile)) {
351 351
 			// load the translations file
@@ -355,7 +355,7 @@  discard block
 block discarded – undo
355 355
 		// merge with translations from theme
356 356
 		$theme = $this->config->getSystemValue('theme');
357 357
 		if (!empty($theme)) {
358
-			$transFile = $this->serverRoot . '/themes/' . $theme . substr($transFile, strlen($this->serverRoot));
358
+			$transFile = $this->serverRoot.'/themes/'.$theme.substr($transFile, strlen($this->serverRoot));
359 359
 			if (file_exists($transFile)) {
360 360
 				$languageFiles[] = $transFile;
361 361
 			}
@@ -372,14 +372,14 @@  discard block
 block discarded – undo
372 372
 	 */
373 373
 	protected function findL10nDir($app = null) {
374 374
 		if (in_array($app, ['core', 'lib', 'settings'])) {
375
-			if (file_exists($this->serverRoot . '/' . $app . '/l10n/')) {
376
-				return $this->serverRoot . '/' . $app . '/l10n/';
375
+			if (file_exists($this->serverRoot.'/'.$app.'/l10n/')) {
376
+				return $this->serverRoot.'/'.$app.'/l10n/';
377 377
 			}
378 378
 		} else if ($app && \OC_App::getAppPath($app) !== false) {
379 379
 			// Check if the app is in the app folder
380
-			return \OC_App::getAppPath($app) . '/l10n/';
380
+			return \OC_App::getAppPath($app).'/l10n/';
381 381
 		}
382
-		return $this->serverRoot . '/core/l10n/';
382
+		return $this->serverRoot.'/core/l10n/';
383 383
 	}
384 384
 
385 385
 
@@ -396,15 +396,15 @@  discard block
 block discarded – undo
396 396
 			return $this->pluralFunctions[$string];
397 397
 		}
398 398
 
399
-		if (preg_match( '/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
399
+		if (preg_match('/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
400 400
 			// sanitize
401
-			$nplurals = preg_replace( '/[^0-9]/', '', $matches[1] );
402
-			$plural = preg_replace( '#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2] );
401
+			$nplurals = preg_replace('/[^0-9]/', '', $matches[1]);
402
+			$plural = preg_replace('#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2]);
403 403
 
404 404
 			$body = str_replace(
405
-				array( 'plural', 'n', '$n$plurals', ),
406
-				array( '$plural', '$n', '$nplurals', ),
407
-				'nplurals='. $nplurals . '; plural=' . $plural
405
+				array('plural', 'n', '$n$plurals',),
406
+				array('$plural', '$n', '$nplurals',),
407
+				'nplurals='.$nplurals.'; plural='.$plural
408 408
 			);
409 409
 
410 410
 			// add parents
@@ -413,9 +413,9 @@  discard block
 block discarded – undo
413 413
 			$res = '';
414 414
 			$p = 0;
415 415
 			$length = strlen($body);
416
-			for($i = 0; $i < $length; $i++) {
416
+			for ($i = 0; $i < $length; $i++) {
417 417
 				$ch = $body[$i];
418
-				switch ( $ch ) {
418
+				switch ($ch) {
419 419
 					case '?':
420 420
 						$res .= ' ? (';
421 421
 						$p++;
@@ -424,7 +424,7 @@  discard block
 block discarded – undo
424 424
 						$res .= ') : (';
425 425
 						break;
426 426
 					case ';':
427
-						$res .= str_repeat( ')', $p ) . ';';
427
+						$res .= str_repeat(')', $p).';';
428 428
 						$p = 0;
429 429
 						break;
430 430
 					default:
@@ -432,7 +432,7 @@  discard block
 block discarded – undo
432 432
 				}
433 433
 			}
434 434
 
435
-			$body = $res . 'return ($plural>=$nplurals?$nplurals-1:$plural);';
435
+			$body = $res.'return ($plural>=$nplurals?$nplurals-1:$plural);';
436 436
 			$function = create_function('$n', $body);
437 437
 			$this->pluralFunctions[$string] = $function;
438 438
 			return $function;
@@ -464,7 +464,7 @@  discard block
 block discarded – undo
464 464
 		$commonLanguages = [];
465 465
 		$languages = [];
466 466
 
467
-		foreach($languageCodes as $lang) {
467
+		foreach ($languageCodes as $lang) {
468 468
 			$l = $this->get('lib', $lang);
469 469
 			// TRANSLATORS this is the language name for the language switcher in the personal settings and should be the localized version
470 470
 			$potentialName = (string) $l->t('__language_name__');
@@ -497,7 +497,7 @@  discard block
 block discarded – undo
497 497
 		ksort($commonLanguages);
498 498
 
499 499
 		// sort now by displayed language not the iso-code
500
-		usort( $languages, function ($a, $b) {
500
+		usort($languages, function($a, $b) {
501 501
 			if ($a['code'] === $a['name'] && $b['code'] !== $b['name']) {
502 502
 				// If a doesn't have a name, but b does, list b before a
503 503
 				return 1;
Please login to merge, or discard this patch.