Completed
Pull Request — master (#3869)
by Jan-Christoph
22:08
created
settings/routes.php 1 patch
Indentation   +52 added lines, -52 removed lines patch added patch discarded remove patch
@@ -36,77 +36,77 @@
 block discarded – undo
36 36
 
37 37
 $application = new Application();
38 38
 $application->registerRoutes($this, [
39
-	'resources' => [
40
-		'users' => ['url' => '/settings/users/users'],
41
-		'AuthSettings' => ['url' => '/settings/personal/authtokens'],
42
-	],
43
-	'routes' => [
44
-		['name' => 'MailSettings#setMailSettings', 'url' => '/settings/admin/mailsettings', 'verb' => 'POST'],
45
-		['name' => 'MailSettings#storeCredentials', 'url' => '/settings/admin/mailsettings/credentials', 'verb' => 'POST'],
46
-		['name' => 'MailSettings#sendTestMail', 'url' => '/settings/admin/mailtest', 'verb' => 'POST'],
47
-		['name' => 'Encryption#startMigration', 'url' => '/settings/admin/startmigration', 'verb' => 'POST'],
48
-		['name' => 'AppSettings#listCategories', 'url' => '/settings/apps/categories', 'verb' => 'GET'],
49
-		['name' => 'AppSettings#viewApps', 'url' => '/settings/apps', 'verb' => 'GET'],
50
-		['name' => 'AppSettings#listApps', 'url' => '/settings/apps/list', 'verb' => 'GET'],
51
-		['name' => 'SecuritySettings#trustedDomains', 'url' => '/settings/admin/security/trustedDomains', 'verb' => 'POST'],
52
-		['name' => 'Users#setDisplayName', 'url' => '/settings/users/{username}/displayName', 'verb' => 'POST'],
53
-		['name' => 'Users#setEMailAddress', 'url' => '/settings/users/{id}/mailAddress', 'verb' => 'PUT'],
54
-		['name' => 'Users#setUserSettings', 'url' => '/settings/users/{username}/settings', 'verb' => 'PUT'],
55
-		['name' => 'Users#getVerificationCode', 'url' => '/settings/users/{account}/verify', 'verb' => 'GET'],
56
-		['name' => 'Users#stats', 'url' => '/settings/users/stats', 'verb' => 'GET'],
57
-		['name' => 'LogSettings#setLogLevel', 'url' => '/settings/admin/log/level', 'verb' => 'POST'],
58
-		['name' => 'LogSettings#getEntries', 'url' => '/settings/admin/log/entries', 'verb' => 'GET'],
59
-		['name' => 'LogSettings#download', 'url' => '/settings/admin/log/download', 'verb' => 'GET'],
60
-		['name' => 'CheckSetup#check', 'url' => '/settings/ajax/checksetup', 'verb' => 'GET'],
61
-		['name' => 'CheckSetup#getFailedIntegrityCheckFiles', 'url' => '/settings/integrity/failed', 'verb' => 'GET'],
62
-		['name' => 'CheckSetup#rescanFailedIntegrityCheck', 'url' => '/settings/integrity/rescan', 'verb' => 'GET'],
63
-		['name' => 'Certificate#addPersonalRootCertificate', 'url' => '/settings/personal/certificate', 'verb' => 'POST'],
64
-		['name' => 'Certificate#removePersonalRootCertificate', 'url' => '/settings/personal/certificate/{certificateIdentifier}', 'verb' => 'DELETE'],
65
-		['name' => 'Certificate#addSystemRootCertificate', 'url' => '/settings/admin/certificate', 'verb' => 'POST'],
66
-		['name' => 'Certificate#removeSystemRootCertificate', 'url' => '/settings/admin/certificate/{certificateIdentifier}', 'verb' => 'DELETE'],
67
-		['name' => 'AdminSettings#index', 'url' => '/settings/admin/{section}', 'verb' => 'GET', 'defaults' => ['section' => 'server']],
68
-		['name' => 'AdminSettings#form', 'url' => '/settings/admin/{section}', 'verb' => 'GET'],
69
-		['name' => 'ChangePassword#changePersonalPassword', 'url' => '/settings/personal/changepassword', 'verb' => 'POST'],
70
-		['name' => 'ChangePassword#changeUserPassword', 'url' => '/settings/users/changepassword', 'verb' => 'POST'],
71
-		['name' => 'Personal#setLanguage', 'url' => '/settings/ajax/setlanguage.php', 'verb' => 'POST'],
72
-		['name' => 'Groups#index', 'url' => '/settings/users/groups', 'verb' => 'GET'],
73
-		['name' => 'Groups#show', 'url' => '/settings/users/groups/{id}', 'requirements' => ['id' => '[^?]*'], 'verb' => 'GET'],
74
-		['name' => 'Groups#create', 'url' => '/settings/users/groups', 'verb' => 'POST'],
75
-		['name' => 'Groups#update', 'url' => '/settings/users/groups/{id}', 'requirements' => ['id' => '[^?]*'], 'verb' => 'PUT'],
76
-		['name' => 'Groups#destroy', 'url' => '/settings/users/groups/{id}', 'requirements' => ['id' => '[^?]*'], 'verb' => 'DELETE'],
77
-	]
39
+    'resources' => [
40
+        'users' => ['url' => '/settings/users/users'],
41
+        'AuthSettings' => ['url' => '/settings/personal/authtokens'],
42
+    ],
43
+    'routes' => [
44
+        ['name' => 'MailSettings#setMailSettings', 'url' => '/settings/admin/mailsettings', 'verb' => 'POST'],
45
+        ['name' => 'MailSettings#storeCredentials', 'url' => '/settings/admin/mailsettings/credentials', 'verb' => 'POST'],
46
+        ['name' => 'MailSettings#sendTestMail', 'url' => '/settings/admin/mailtest', 'verb' => 'POST'],
47
+        ['name' => 'Encryption#startMigration', 'url' => '/settings/admin/startmigration', 'verb' => 'POST'],
48
+        ['name' => 'AppSettings#listCategories', 'url' => '/settings/apps/categories', 'verb' => 'GET'],
49
+        ['name' => 'AppSettings#viewApps', 'url' => '/settings/apps', 'verb' => 'GET'],
50
+        ['name' => 'AppSettings#listApps', 'url' => '/settings/apps/list', 'verb' => 'GET'],
51
+        ['name' => 'SecuritySettings#trustedDomains', 'url' => '/settings/admin/security/trustedDomains', 'verb' => 'POST'],
52
+        ['name' => 'Users#setDisplayName', 'url' => '/settings/users/{username}/displayName', 'verb' => 'POST'],
53
+        ['name' => 'Users#setEMailAddress', 'url' => '/settings/users/{id}/mailAddress', 'verb' => 'PUT'],
54
+        ['name' => 'Users#setUserSettings', 'url' => '/settings/users/{username}/settings', 'verb' => 'PUT'],
55
+        ['name' => 'Users#getVerificationCode', 'url' => '/settings/users/{account}/verify', 'verb' => 'GET'],
56
+        ['name' => 'Users#stats', 'url' => '/settings/users/stats', 'verb' => 'GET'],
57
+        ['name' => 'LogSettings#setLogLevel', 'url' => '/settings/admin/log/level', 'verb' => 'POST'],
58
+        ['name' => 'LogSettings#getEntries', 'url' => '/settings/admin/log/entries', 'verb' => 'GET'],
59
+        ['name' => 'LogSettings#download', 'url' => '/settings/admin/log/download', 'verb' => 'GET'],
60
+        ['name' => 'CheckSetup#check', 'url' => '/settings/ajax/checksetup', 'verb' => 'GET'],
61
+        ['name' => 'CheckSetup#getFailedIntegrityCheckFiles', 'url' => '/settings/integrity/failed', 'verb' => 'GET'],
62
+        ['name' => 'CheckSetup#rescanFailedIntegrityCheck', 'url' => '/settings/integrity/rescan', 'verb' => 'GET'],
63
+        ['name' => 'Certificate#addPersonalRootCertificate', 'url' => '/settings/personal/certificate', 'verb' => 'POST'],
64
+        ['name' => 'Certificate#removePersonalRootCertificate', 'url' => '/settings/personal/certificate/{certificateIdentifier}', 'verb' => 'DELETE'],
65
+        ['name' => 'Certificate#addSystemRootCertificate', 'url' => '/settings/admin/certificate', 'verb' => 'POST'],
66
+        ['name' => 'Certificate#removeSystemRootCertificate', 'url' => '/settings/admin/certificate/{certificateIdentifier}', 'verb' => 'DELETE'],
67
+        ['name' => 'AdminSettings#index', 'url' => '/settings/admin/{section}', 'verb' => 'GET', 'defaults' => ['section' => 'server']],
68
+        ['name' => 'AdminSettings#form', 'url' => '/settings/admin/{section}', 'verb' => 'GET'],
69
+        ['name' => 'ChangePassword#changePersonalPassword', 'url' => '/settings/personal/changepassword', 'verb' => 'POST'],
70
+        ['name' => 'ChangePassword#changeUserPassword', 'url' => '/settings/users/changepassword', 'verb' => 'POST'],
71
+        ['name' => 'Personal#setLanguage', 'url' => '/settings/ajax/setlanguage.php', 'verb' => 'POST'],
72
+        ['name' => 'Groups#index', 'url' => '/settings/users/groups', 'verb' => 'GET'],
73
+        ['name' => 'Groups#show', 'url' => '/settings/users/groups/{id}', 'requirements' => ['id' => '[^?]*'], 'verb' => 'GET'],
74
+        ['name' => 'Groups#create', 'url' => '/settings/users/groups', 'verb' => 'POST'],
75
+        ['name' => 'Groups#update', 'url' => '/settings/users/groups/{id}', 'requirements' => ['id' => '[^?]*'], 'verb' => 'PUT'],
76
+        ['name' => 'Groups#destroy', 'url' => '/settings/users/groups/{id}', 'requirements' => ['id' => '[^?]*'], 'verb' => 'DELETE'],
77
+    ]
78 78
 ]);
79 79
 
80 80
 /** @var $this \OCP\Route\IRouter */
81 81
 
82 82
 // Settings pages
83 83
 $this->create('settings_help', '/settings/help')
84
-	->actionInclude('settings/help.php');
84
+    ->actionInclude('settings/help.php');
85 85
 $this->create('settings_personal', '/settings/personal')
86
-	->actionInclude('settings/personal.php');
86
+    ->actionInclude('settings/personal.php');
87 87
 $this->create('settings_users', '/settings/users')
88
-	->actionInclude('settings/users.php');
88
+    ->actionInclude('settings/users.php');
89 89
 // Settings ajax actions
90 90
 // users
91 91
 $this->create('settings_ajax_setquota', '/settings/ajax/setquota.php')
92
-	->actionInclude('settings/ajax/setquota.php');
92
+    ->actionInclude('settings/ajax/setquota.php');
93 93
 $this->create('settings_ajax_togglegroups', '/settings/ajax/togglegroups.php')
94
-	->actionInclude('settings/ajax/togglegroups.php');
94
+    ->actionInclude('settings/ajax/togglegroups.php');
95 95
 $this->create('settings_ajax_togglesubadmins', '/settings/ajax/togglesubadmins.php')
96
-	->actionInclude('settings/ajax/togglesubadmins.php');
96
+    ->actionInclude('settings/ajax/togglesubadmins.php');
97 97
 $this->create('settings_ajax_changegorupname', '/settings/ajax/changegroupname.php')
98
-	->actionInclude('settings/ajax/changegroupname.php');
98
+    ->actionInclude('settings/ajax/changegroupname.php');
99 99
 // apps
100 100
 $this->create('settings_ajax_enableapp', '/settings/ajax/enableapp.php')
101
-	->actionInclude('settings/ajax/enableapp.php');
101
+    ->actionInclude('settings/ajax/enableapp.php');
102 102
 $this->create('settings_ajax_disableapp', '/settings/ajax/disableapp.php')
103
-	->actionInclude('settings/ajax/disableapp.php');
103
+    ->actionInclude('settings/ajax/disableapp.php');
104 104
 $this->create('settings_ajax_updateapp', '/settings/ajax/updateapp.php')
105
-	->actionInclude('settings/ajax/updateapp.php');
105
+    ->actionInclude('settings/ajax/updateapp.php');
106 106
 $this->create('settings_ajax_uninstallapp', '/settings/ajax/uninstallapp.php')
107
-	->actionInclude('settings/ajax/uninstallapp.php');
107
+    ->actionInclude('settings/ajax/uninstallapp.php');
108 108
 $this->create('settings_ajax_navigationdetect', '/settings/ajax/navigationdetect.php')
109
-	->actionInclude('settings/ajax/navigationdetect.php');
109
+    ->actionInclude('settings/ajax/navigationdetect.php');
110 110
 // admin
111 111
 $this->create('settings_ajax_excludegroups', '/settings/ajax/excludegroups.php')
112
-	->actionInclude('settings/ajax/excludegroups.php');
112
+    ->actionInclude('settings/ajax/excludegroups.php');
Please login to merge, or discard this patch.
settings/Controller/UsersController.php 1 patch
Indentation   +853 added lines, -853 removed lines patch added patch discarded remove patch
@@ -58,858 +58,858 @@
 block discarded – undo
58 58
  * @package OC\Settings\Controller
59 59
  */
60 60
 class UsersController extends Controller {
61
-	/** @var IL10N */
62
-	private $l10n;
63
-	/** @var IUserSession */
64
-	private $userSession;
65
-	/** @var bool */
66
-	private $isAdmin;
67
-	/** @var IUserManager */
68
-	private $userManager;
69
-	/** @var IGroupManager */
70
-	private $groupManager;
71
-	/** @var IConfig */
72
-	private $config;
73
-	/** @var ILogger */
74
-	private $log;
75
-	/** @var IMailer */
76
-	private $mailer;
77
-	/** @var bool contains the state of the encryption app */
78
-	private $isEncryptionAppEnabled;
79
-	/** @var bool contains the state of the admin recovery setting */
80
-	private $isRestoreEnabled = false;
81
-	/** @var IAvatarManager */
82
-	private $avatarManager;
83
-	/** @var AccountManager */
84
-	private $accountManager;
85
-	/** @var ISecureRandom */
86
-	private $secureRandom;
87
-	/** @var NewUserMailHelper */
88
-	private $newUserMailHelper;
89
-	/** @var ITimeFactory */
90
-	private $timeFactory;
91
-	/** @var ICrypto */
92
-	private $crypto;
93
-	/** @var Manager */
94
-	private $keyManager;
95
-	/** @var IJobList */
96
-	private $jobList;
97
-
98
-	/**
99
-	 * @param string $appName
100
-	 * @param IRequest $request
101
-	 * @param IUserManager $userManager
102
-	 * @param IGroupManager $groupManager
103
-	 * @param IUserSession $userSession
104
-	 * @param IConfig $config
105
-	 * @param bool $isAdmin
106
-	 * @param IL10N $l10n
107
-	 * @param ILogger $log
108
-	 * @param IMailer $mailer
109
-	 * @param IURLGenerator $urlGenerator
110
-	 * @param IAppManager $appManager
111
-	 * @param IAvatarManager $avatarManager
112
-	 * @param AccountManager $accountManager
113
-	 * @param ISecureRandom $secureRandom
114
-	 * @param NewUserMailHelper $newUserMailHelper
115
-	 * @param ITimeFactory $timeFactory
116
-	 * @param ICrypto $crypto
117
-	 * @param Manager $keyManager
118
-	 * @param IJobList $jobList
119
-	 */
120
-	public function __construct($appName,
121
-								IRequest $request,
122
-								IUserManager $userManager,
123
-								IGroupManager $groupManager,
124
-								IUserSession $userSession,
125
-								IConfig $config,
126
-								$isAdmin,
127
-								IL10N $l10n,
128
-								ILogger $log,
129
-								IMailer $mailer,
130
-								IURLGenerator $urlGenerator,
131
-								IAppManager $appManager,
132
-								IAvatarManager $avatarManager,
133
-								AccountManager $accountManager,
134
-								ISecureRandom $secureRandom,
135
-								NewUserMailHelper $newUserMailHelper,
136
-								ITimeFactory $timeFactory,
137
-								ICrypto $crypto,
138
-								Manager $keyManager,
139
-								IJobList $jobList) {
140
-		parent::__construct($appName, $request);
141
-		$this->userManager = $userManager;
142
-		$this->groupManager = $groupManager;
143
-		$this->userSession = $userSession;
144
-		$this->config = $config;
145
-		$this->isAdmin = $isAdmin;
146
-		$this->l10n = $l10n;
147
-		$this->log = $log;
148
-		$this->mailer = $mailer;
149
-		$this->avatarManager = $avatarManager;
150
-		$this->accountManager = $accountManager;
151
-		$this->secureRandom = $secureRandom;
152
-		$this->newUserMailHelper = $newUserMailHelper;
153
-		$this->timeFactory = $timeFactory;
154
-		$this->crypto = $crypto;
155
-		$this->keyManager = $keyManager;
156
-		$this->jobList = $jobList;
157
-
158
-		// check for encryption state - TODO see formatUserForIndex
159
-		$this->isEncryptionAppEnabled = $appManager->isEnabledForUser('encryption');
160
-		if($this->isEncryptionAppEnabled) {
161
-			// putting this directly in empty is possible in PHP 5.5+
162
-			$result = $config->getAppValue('encryption', 'recoveryAdminEnabled', 0);
163
-			$this->isRestoreEnabled = !empty($result);
164
-		}
165
-	}
166
-
167
-	/**
168
-	 * @param IUser $user
169
-	 * @param array $userGroups
170
-	 * @return array
171
-	 */
172
-	private function formatUserForIndex(IUser $user, array $userGroups = null) {
173
-
174
-		// TODO: eliminate this encryption specific code below and somehow
175
-		// hook in additional user info from other apps
176
-
177
-		// recovery isn't possible if admin or user has it disabled and encryption
178
-		// is enabled - so we eliminate the else paths in the conditional tree
179
-		// below
180
-		$restorePossible = false;
181
-
182
-		if ($this->isEncryptionAppEnabled) {
183
-			if ($this->isRestoreEnabled) {
184
-				// check for the users recovery setting
185
-				$recoveryMode = $this->config->getUserValue($user->getUID(), 'encryption', 'recoveryEnabled', '0');
186
-				// method call inside empty is possible with PHP 5.5+
187
-				$recoveryModeEnabled = !empty($recoveryMode);
188
-				if ($recoveryModeEnabled) {
189
-					// user also has recovery mode enabled
190
-					$restorePossible = true;
191
-				}
192
-			}
193
-		} else {
194
-			// recovery is possible if encryption is disabled (plain files are
195
-			// available)
196
-			$restorePossible = true;
197
-		}
198
-
199
-		$subAdminGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($user);
200
-		foreach($subAdminGroups as $key => $subAdminGroup) {
201
-			$subAdminGroups[$key] = $subAdminGroup->getGID();
202
-		}
203
-
204
-		$displayName = $user->getEMailAddress();
205
-		if (is_null($displayName)) {
206
-			$displayName = '';
207
-		}
208
-
209
-		$avatarAvailable = false;
210
-		try {
211
-			$avatarAvailable = $this->avatarManager->getAvatar($user->getUID())->exists();
212
-		} catch (\Exception $e) {
213
-			//No avatar yet
214
-		}
215
-
216
-		return [
217
-			'name' => $user->getUID(),
218
-			'displayname' => $user->getDisplayName(),
219
-			'groups' => (empty($userGroups)) ? $this->groupManager->getUserGroupIds($user) : $userGroups,
220
-			'subadmin' => $subAdminGroups,
221
-			'quota' => $user->getQuota(),
222
-			'storageLocation' => $user->getHome(),
223
-			'lastLogin' => $user->getLastLogin() * 1000,
224
-			'backend' => $user->getBackendClassName(),
225
-			'email' => $displayName,
226
-			'isRestoreDisabled' => !$restorePossible,
227
-			'isAvatarAvailable' => $avatarAvailable,
228
-		];
229
-	}
230
-
231
-	/**
232
-	 * @param array $userIDs Array with schema [$uid => $displayName]
233
-	 * @return IUser[]
234
-	 */
235
-	private function getUsersForUID(array $userIDs) {
236
-		$users = [];
237
-		foreach ($userIDs as $uid => $displayName) {
238
-			$users[$uid] = $this->userManager->get($uid);
239
-		}
240
-		return $users;
241
-	}
242
-
243
-	/**
244
-	 * @NoAdminRequired
245
-	 *
246
-	 * @param int $offset
247
-	 * @param int $limit
248
-	 * @param string $gid GID to filter for
249
-	 * @param string $pattern Pattern to search for in the username
250
-	 * @param string $backend Backend to filter for (class-name)
251
-	 * @return DataResponse
252
-	 *
253
-	 * TODO: Tidy up and write unit tests - code is mainly static method calls
254
-	 */
255
-	public function index($offset = 0, $limit = 10, $gid = '', $pattern = '', $backend = '') {
256
-		// FIXME: The JS sends the group '_everyone' instead of no GID for the "all users" group.
257
-		if($gid === '_everyone') {
258
-			$gid = '';
259
-		}
260
-
261
-		// Remove backends
262
-		if(!empty($backend)) {
263
-			$activeBackends = $this->userManager->getBackends();
264
-			$this->userManager->clearBackends();
265
-			foreach($activeBackends as $singleActiveBackend) {
266
-				if($backend === get_class($singleActiveBackend)) {
267
-					$this->userManager->registerBackend($singleActiveBackend);
268
-					break;
269
-				}
270
-			}
271
-		}
272
-
273
-		$users = [];
274
-		if ($this->isAdmin) {
275
-
276
-			if($gid !== '') {
277
-				$batch = $this->getUsersForUID($this->groupManager->displayNamesInGroup($gid, $pattern, $limit, $offset));
278
-			} else {
279
-				$batch = $this->userManager->search($pattern, $limit, $offset);
280
-			}
281
-
282
-			foreach ($batch as $user) {
283
-				$users[] = $this->formatUserForIndex($user);
284
-			}
285
-
286
-		} else {
287
-			$subAdminOfGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($this->userSession->getUser());
288
-			// New class returns IGroup[] so convert back
289
-			$gids = [];
290
-			foreach ($subAdminOfGroups as $group) {
291
-				$gids[] = $group->getGID();
292
-			}
293
-			$subAdminOfGroups = $gids;
294
-
295
-			// Set the $gid parameter to an empty value if the subadmin has no rights to access a specific group
296
-			if($gid !== '' && !in_array($gid, $subAdminOfGroups)) {
297
-				$gid = '';
298
-			}
299
-
300
-			// Batch all groups the user is subadmin of when a group is specified
301
-			$batch = [];
302
-			if($gid === '') {
303
-				foreach($subAdminOfGroups as $group) {
304
-					$groupUsers = $this->groupManager->displayNamesInGroup($group, $pattern, $limit, $offset);
305
-
306
-					foreach($groupUsers as $uid => $displayName) {
307
-						$batch[$uid] = $displayName;
308
-					}
309
-				}
310
-			} else {
311
-				$batch = $this->groupManager->displayNamesInGroup($gid, $pattern, $limit, $offset);
312
-			}
313
-			$batch = $this->getUsersForUID($batch);
314
-
315
-			foreach ($batch as $user) {
316
-				// Only add the groups, this user is a subadmin of
317
-				$userGroups = array_values(array_intersect(
318
-					$this->groupManager->getUserGroupIds($user),
319
-					$subAdminOfGroups
320
-				));
321
-				$users[] = $this->formatUserForIndex($user, $userGroups);
322
-			}
323
-		}
324
-
325
-		return new DataResponse($users);
326
-	}
327
-
328
-	/**
329
-	 * @NoAdminRequired
330
-	 * @PasswordConfirmationRequired
331
-	 *
332
-	 * @param string $username
333
-	 * @param string $password
334
-	 * @param array $groups
335
-	 * @param string $email
336
-	 * @return DataResponse
337
-	 */
338
-	public function create($username, $password, array $groups=array(), $email='') {
339
-		if($email !== '' && !$this->mailer->validateMailAddress($email)) {
340
-			return new DataResponse(
341
-				array(
342
-					'message' => (string)$this->l10n->t('Invalid mail address')
343
-				),
344
-				Http::STATUS_UNPROCESSABLE_ENTITY
345
-			);
346
-		}
347
-
348
-		$currentUser = $this->userSession->getUser();
349
-
350
-		if (!$this->isAdmin) {
351
-			if (!empty($groups)) {
352
-				foreach ($groups as $key => $group) {
353
-					$groupObject = $this->groupManager->get($group);
354
-					if($groupObject === null) {
355
-						unset($groups[$key]);
356
-						continue;
357
-					}
358
-
359
-					if (!$this->groupManager->getSubAdmin()->isSubAdminofGroup($currentUser, $groupObject)) {
360
-						unset($groups[$key]);
361
-					}
362
-				}
363
-			}
364
-
365
-			if (empty($groups)) {
366
-				return new DataResponse(
367
-					array(
368
-						'message' => $this->l10n->t('No valid group selected'),
369
-					),
370
-					Http::STATUS_FORBIDDEN
371
-				);
372
-			}
373
-		}
374
-
375
-		if ($this->userManager->userExists($username)) {
376
-			return new DataResponse(
377
-				array(
378
-					'message' => (string)$this->l10n->t('A user with that name already exists.')
379
-				),
380
-				Http::STATUS_CONFLICT
381
-			);
382
-		}
383
-
384
-		$generatePasswordResetToken = false;
385
-		if ($password === '') {
386
-			if ($email === '') {
387
-				return new DataResponse(
388
-					array(
389
-						'message' => (string)$this->l10n->t('To send a password link to the user an email address is required.')
390
-					),
391
-					Http::STATUS_UNPROCESSABLE_ENTITY
392
-				);
393
-			}
394
-
395
-			$password = $this->secureRandom->generate(32);
396
-			$generatePasswordResetToken = true;
397
-		}
398
-
399
-		try {
400
-			$user = $this->userManager->createUser($username, $password);
401
-		} catch (\Exception $exception) {
402
-			$message = $exception->getMessage();
403
-			if (!$message) {
404
-				$message = $this->l10n->t('Unable to create user.');
405
-			}
406
-			return new DataResponse(
407
-				array(
408
-					'message' => (string) $message,
409
-				),
410
-				Http::STATUS_FORBIDDEN
411
-			);
412
-		}
413
-
414
-		if($user instanceof IUser) {
415
-			if($groups !== null) {
416
-				foreach($groups as $groupName) {
417
-					$group = $this->groupManager->get($groupName);
418
-
419
-					if(empty($group)) {
420
-						$group = $this->groupManager->createGroup($groupName);
421
-					}
422
-					$group->addUser($user);
423
-				}
424
-			}
425
-			/**
426
-			 * Send new user mail only if a mail is set
427
-			 */
428
-			if($email !== '') {
429
-				$user->setEMailAddress($email);
430
-				try {
431
-					$emailTemplate = $this->newUserMailHelper->generateTemplate($user, $generatePasswordResetToken);
432
-					$this->newUserMailHelper->sendMail($user, $emailTemplate);
433
-				} catch(\Exception $e) {
434
-					$this->log->error("Can't send new user mail to $email: " . $e->getMessage(), array('app' => 'settings'));
435
-				}
436
-			}
437
-			// fetch users groups
438
-			$userGroups = $this->groupManager->getUserGroupIds($user);
439
-
440
-			return new DataResponse(
441
-				$this->formatUserForIndex($user, $userGroups),
442
-				Http::STATUS_CREATED
443
-			);
444
-		}
445
-
446
-		return new DataResponse(
447
-			array(
448
-				'message' => (string)$this->l10n->t('Unable to create user.')
449
-			),
450
-			Http::STATUS_FORBIDDEN
451
-		);
452
-
453
-	}
454
-
455
-	/**
456
-	 * @NoAdminRequired
457
-	 * @PasswordConfirmationRequired
458
-	 *
459
-	 * @param string $id
460
-	 * @return DataResponse
461
-	 */
462
-	public function destroy($id) {
463
-		$userId = $this->userSession->getUser()->getUID();
464
-		$user = $this->userManager->get($id);
465
-
466
-		if($userId === $id) {
467
-			return new DataResponse(
468
-				array(
469
-					'status' => 'error',
470
-					'data' => array(
471
-						'message' => (string)$this->l10n->t('Unable to delete user.')
472
-					)
473
-				),
474
-				Http::STATUS_FORBIDDEN
475
-			);
476
-		}
477
-
478
-		if(!$this->isAdmin && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)) {
479
-			return new DataResponse(
480
-				array(
481
-					'status' => 'error',
482
-					'data' => array(
483
-						'message' => (string)$this->l10n->t('Authentication error')
484
-					)
485
-				),
486
-				Http::STATUS_FORBIDDEN
487
-			);
488
-		}
489
-
490
-		if($user) {
491
-			if($user->delete()) {
492
-				return new DataResponse(
493
-					array(
494
-						'status' => 'success',
495
-						'data' => array(
496
-							'username' => $id
497
-						)
498
-					),
499
-					Http::STATUS_NO_CONTENT
500
-				);
501
-			}
502
-		}
503
-
504
-		return new DataResponse(
505
-			array(
506
-				'status' => 'error',
507
-				'data' => array(
508
-					'message' => (string)$this->l10n->t('Unable to delete user.')
509
-				)
510
-			),
511
-			Http::STATUS_FORBIDDEN
512
-		);
513
-	}
514
-
515
-	/**
516
-	 * @NoAdminRequired
517
-	 * @NoSubadminRequired
518
-	 * @PasswordConfirmationRequired
519
-	 *
520
-	 * @param string $account
521
-	 * @return DataResponse
522
-	 */
523
-	public function getVerificationCode($account) {
524
-
525
-		$user = $this->userSession->getUser();
526
-
527
-		if ($user === null) {
528
-			return new DataResponse([], Http::STATUS_BAD_REQUEST);
529
-		}
530
-
531
-		$accountData = $this->accountManager->getUser($user);
532
-		$cloudId = $user->getCloudId();
533
-		$message = "Use my Federated Cloud ID to share with me: " . $cloudId;
534
-		$signature = $this->signMessage($user, $message);
535
-
536
-		$code = $message . ' ' . $signature;
537
-		$codeMd5 = $message . ' ' . md5($signature);
538
-
539
-		switch ($account) {
540
-			case 'verify-twitter':
541
-				$accountData[AccountManager::PROPERTY_TWITTER]['verified'] = AccountManager::VERIFICATION_IN_PROGRESS;
542
-				$msg = $this->l10n->t('In order to verify your Twitter account post following tweet on Twitter:');
543
-				$code = $codeMd5;
544
-				$type = AccountManager::PROPERTY_TWITTER;
545
-				$data = $accountData[AccountManager::PROPERTY_TWITTER]['value'];
546
-				break;
547
-			case 'verify-website':
548
-				$accountData[AccountManager::PROPERTY_WEBSITE]['verified'] = AccountManager::VERIFICATION_IN_PROGRESS;
549
-				$msg = $this->l10n->t('In order to verify your Website store following content in your web-root at \'CloudIdVerificationCode.txt\':');
550
-				$type = AccountManager::PROPERTY_WEBSITE;
551
-				$data = $accountData[AccountManager::PROPERTY_WEBSITE]['value'];
552
-				break;
553
-			default:
554
-				return new DataResponse([], Http::STATUS_BAD_REQUEST);
555
-		}
556
-
557
-		$this->accountManager->updateUser($user, $accountData);
558
-
559
-
560
-		$this->jobList->add('OC\Settings\BackgroundJobs\VerifyUserData',
561
-			[
562
-				'verificationCode' => $code,
563
-				'data' => $data,
564
-				'type' => $type,
565
-				'uid' => $user->getUID(),
566
-				'try' => 0,
567
-				'lastRun' => $this->getCurrentTime()
568
-			]
569
-		);
570
-
571
-		return new DataResponse(['msg' => $msg, 'code' => $code]);
572
-	}
573
-
574
-	/**
575
-	 * get current timestamp
576
-	 *
577
-	 * @return int
578
-	 */
579
-	protected function getCurrentTime() {
580
-		return time();
581
-	}
582
-
583
-	/**
584
-	 * sign message with users private key
585
-	 *
586
-	 * @param IUser $user
587
-	 * @param string $message
588
-	 *
589
-	 * @return string base64 encoded signature
590
-	 */
591
-	protected function signMessage(IUser $user, $message) {
592
-		$privateKey = $this->keyManager->getKey($user)->getPrivate();
593
-		openssl_sign(json_encode($message), $signature, $privateKey, OPENSSL_ALGO_SHA512);
594
-		$signatureBase64 = base64_encode($signature);
595
-
596
-		return $signatureBase64;
597
-	}
598
-
599
-	/**
600
-	 * @NoAdminRequired
601
-	 * @NoSubadminRequired
602
-	 * @PasswordConfirmationRequired
603
-	 *
604
-	 * @param string $avatarScope
605
-	 * @param string $displayname
606
-	 * @param string $displaynameScope
607
-	 * @param string $phone
608
-	 * @param string $phoneScope
609
-	 * @param string $email
610
-	 * @param string $emailScope
611
-	 * @param string $website
612
-	 * @param string $websiteScope
613
-	 * @param string $address
614
-	 * @param string $addressScope
615
-	 * @param string $twitter
616
-	 * @param string $twitterScope
617
-	 * @return DataResponse
618
-	 */
619
-	public function setUserSettings($avatarScope,
620
-									$displayname,
621
-									$displaynameScope,
622
-									$phone,
623
-									$phoneScope,
624
-									$email,
625
-									$emailScope,
626
-									$website,
627
-									$websiteScope,
628
-									$address,
629
-									$addressScope,
630
-									$twitter,
631
-									$twitterScope
632
-	) {
633
-
634
-		if(!empty($email) && !$this->mailer->validateMailAddress($email)) {
635
-			return new DataResponse(
636
-				array(
637
-					'status' => 'error',
638
-					'data' => array(
639
-						'message' => (string)$this->l10n->t('Invalid mail address')
640
-					)
641
-				),
642
-				Http::STATUS_UNPROCESSABLE_ENTITY
643
-			);
644
-		}
645
-
646
-		$data = [
647
-			AccountManager::PROPERTY_AVATAR =>  ['scope' => $avatarScope],
648
-			AccountManager::PROPERTY_DISPLAYNAME => ['value' => $displayname, 'scope' => $displaynameScope],
649
-			AccountManager::PROPERTY_EMAIL=> ['value' => $email, 'scope' => $emailScope],
650
-			AccountManager::PROPERTY_WEBSITE => ['value' => $website, 'scope' => $websiteScope],
651
-			AccountManager::PROPERTY_ADDRESS => ['value' => $address, 'scope' => $addressScope],
652
-			AccountManager::PROPERTY_PHONE => ['value' => $phone, 'scope' => $phoneScope],
653
-			AccountManager::PROPERTY_TWITTER => ['value' => $twitter, 'scope' => $twitterScope]
654
-		];
655
-
656
-		$user = $this->userSession->getUser();
657
-
658
-		try {
659
-			$this->saveUserSettings($user, $data);
660
-			return new DataResponse(
661
-				array(
662
-					'status' => 'success',
663
-					'data' => array(
664
-						'userId' => $user->getUID(),
665
-						'avatarScope' => $avatarScope,
666
-						'displayname' => $displayname,
667
-						'displaynameScope' => $displaynameScope,
668
-						'email' => $email,
669
-						'emailScope' => $emailScope,
670
-						'website' => $website,
671
-						'websiteScope' => $websiteScope,
672
-						'address' => $address,
673
-						'addressScope' => $addressScope,
674
-						'message' => (string)$this->l10n->t('Settings saved')
675
-					)
676
-				),
677
-				Http::STATUS_OK
678
-			);
679
-		} catch (ForbiddenException $e) {
680
-			return new DataResponse([
681
-				'status' => 'error',
682
-				'data' => [
683
-					'message' => $e->getMessage()
684
-				],
685
-			]);
686
-		}
687
-
688
-	}
689
-
690
-
691
-	/**
692
-	 * update account manager with new user data
693
-	 *
694
-	 * @param IUser $user
695
-	 * @param array $data
696
-	 * @throws ForbiddenException
697
-	 */
698
-	protected function saveUserSettings(IUser $user, $data) {
699
-
700
-		// keep the user back-end up-to-date with the latest display name and email
701
-		// address
702
-		$oldDisplayName = $user->getDisplayName();
703
-		$oldDisplayName = is_null($oldDisplayName) ? '' : $oldDisplayName;
704
-		if (isset($data[AccountManager::PROPERTY_DISPLAYNAME]['value'])
705
-			&& $oldDisplayName !== $data[AccountManager::PROPERTY_DISPLAYNAME]['value']
706
-		) {
707
-			$result = $user->setDisplayName($data[AccountManager::PROPERTY_DISPLAYNAME]['value']);
708
-			if ($result === false) {
709
-				throw new ForbiddenException($this->l10n->t('Unable to change full name'));
710
-			}
711
-		}
712
-
713
-		$oldEmailAddress = $user->getEMailAddress();
714
-		$oldEmailAddress = is_null($oldEmailAddress) ? '' : $oldEmailAddress;
715
-		if (isset($data[AccountManager::PROPERTY_EMAIL]['value'])
716
-			&& $oldEmailAddress !== $data[AccountManager::PROPERTY_EMAIL]['value']
717
-		) {
718
-			// this is the only permission a backend provides and is also used
719
-			// for the permission of setting a email address
720
-			if (!$user->canChangeDisplayName()) {
721
-				throw new ForbiddenException($this->l10n->t('Unable to change email address'));
722
-			}
723
-			$user->setEMailAddress($data[AccountManager::PROPERTY_EMAIL]['value']);
724
-		}
725
-
726
-		$this->accountManager->updateUser($user, $data);
727
-	}
728
-
729
-	/**
730
-	 * Count all unique users visible for the current admin/subadmin.
731
-	 *
732
-	 * @NoAdminRequired
733
-	 *
734
-	 * @return DataResponse
735
-	 */
736
-	public function stats() {
737
-		$userCount = 0;
738
-		if ($this->isAdmin) {
739
-			$countByBackend = $this->userManager->countUsers();
740
-
741
-			if (!empty($countByBackend)) {
742
-				foreach ($countByBackend as $count) {
743
-					$userCount += $count;
744
-				}
745
-			}
746
-		} else {
747
-			$groups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($this->userSession->getUser());
748
-
749
-			$uniqueUsers = [];
750
-			foreach ($groups as $group) {
751
-				foreach($group->getUsers() as $uid => $displayName) {
752
-					$uniqueUsers[$uid] = true;
753
-				}
754
-			}
755
-
756
-			$userCount = count($uniqueUsers);
757
-		}
758
-
759
-		return new DataResponse(
760
-			[
761
-				'totalUsers' => $userCount
762
-			]
763
-		);
764
-	}
765
-
766
-
767
-	/**
768
-	 * Set the displayName of a user
769
-	 *
770
-	 * @NoAdminRequired
771
-	 * @NoSubadminRequired
772
-	 * @PasswordConfirmationRequired
773
-	 * @todo merge into saveUserSettings
774
-	 *
775
-	 * @param string $username
776
-	 * @param string $displayName
777
-	 * @return DataResponse
778
-	 */
779
-	public function setDisplayName($username, $displayName) {
780
-		$currentUser = $this->userSession->getUser();
781
-		$user = $this->userManager->get($username);
782
-
783
-		if ($user === null ||
784
-			!$user->canChangeDisplayName() ||
785
-			(
786
-				!$this->groupManager->isAdmin($currentUser->getUID()) &&
787
-				!$this->groupManager->getSubAdmin()->isUserAccessible($currentUser, $user) &&
788
-				$currentUser->getUID() !== $username
789
-
790
-			)
791
-		) {
792
-			return new DataResponse([
793
-				'status' => 'error',
794
-				'data' => [
795
-					'message' => $this->l10n->t('Authentication error'),
796
-				],
797
-			]);
798
-		}
799
-
800
-		$userData = $this->accountManager->getUser($user);
801
-		$userData[AccountManager::PROPERTY_DISPLAYNAME]['value'] = $displayName;
802
-
803
-
804
-		try {
805
-			$this->saveUserSettings($user, $userData);
806
-			return new DataResponse([
807
-				'status' => 'success',
808
-				'data' => [
809
-					'message' => $this->l10n->t('Your full name has been changed.'),
810
-					'username' => $username,
811
-					'displayName' => $displayName,
812
-				],
813
-			]);
814
-		} catch (ForbiddenException $e) {
815
-			return new DataResponse([
816
-				'status' => 'error',
817
-				'data' => [
818
-					'message' => $e->getMessage(),
819
-					'displayName' => $user->getDisplayName(),
820
-				],
821
-			]);
822
-		}
823
-	}
824
-
825
-	/**
826
-	 * Set the mail address of a user
827
-	 *
828
-	 * @NoAdminRequired
829
-	 * @NoSubadminRequired
830
-	 * @PasswordConfirmationRequired
831
-	 *
832
-	 * @param string $id
833
-	 * @param string $mailAddress
834
-	 * @return DataResponse
835
-	 */
836
-	public function setEMailAddress($id, $mailAddress) {
837
-		$user = $this->userManager->get($id);
838
-		if (!$this->isAdmin
839
-			&& !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)
840
-		) {
841
-			return new DataResponse(
842
-				array(
843
-					'status' => 'error',
844
-					'data' => array(
845
-						'message' => (string)$this->l10n->t('Forbidden')
846
-					)
847
-				),
848
-				Http::STATUS_FORBIDDEN
849
-			);
850
-		}
851
-
852
-		if($mailAddress !== '' && !$this->mailer->validateMailAddress($mailAddress)) {
853
-			return new DataResponse(
854
-				array(
855
-					'status' => 'error',
856
-					'data' => array(
857
-						'message' => (string)$this->l10n->t('Invalid mail address')
858
-					)
859
-				),
860
-				Http::STATUS_UNPROCESSABLE_ENTITY
861
-			);
862
-		}
863
-
864
-		if (!$user) {
865
-			return new DataResponse(
866
-				array(
867
-					'status' => 'error',
868
-					'data' => array(
869
-						'message' => (string)$this->l10n->t('Invalid user')
870
-					)
871
-				),
872
-				Http::STATUS_UNPROCESSABLE_ENTITY
873
-			);
874
-		}
875
-		// this is the only permission a backend provides and is also used
876
-		// for the permission of setting a email address
877
-		if (!$user->canChangeDisplayName()) {
878
-			return new DataResponse(
879
-				array(
880
-					'status' => 'error',
881
-					'data' => array(
882
-						'message' => (string)$this->l10n->t('Unable to change mail address')
883
-					)
884
-				),
885
-				Http::STATUS_FORBIDDEN
886
-			);
887
-		}
888
-
889
-		$userData = $this->accountManager->getUser($user);
890
-		$userData[AccountManager::PROPERTY_EMAIL]['value'] = $mailAddress;
891
-
892
-		try {
893
-			$this->saveUserSettings($user, $userData);
894
-			return new DataResponse(
895
-				array(
896
-					'status' => 'success',
897
-					'data' => array(
898
-						'username' => $id,
899
-						'mailAddress' => $mailAddress,
900
-						'message' => (string)$this->l10n->t('Email saved')
901
-					)
902
-				),
903
-				Http::STATUS_OK
904
-			);
905
-		} catch (ForbiddenException $e) {
906
-			return new DataResponse([
907
-				'status' => 'error',
908
-				'data' => [
909
-					'message' => $e->getMessage()
910
-				],
911
-			]);
912
-		}
913
-	}
61
+    /** @var IL10N */
62
+    private $l10n;
63
+    /** @var IUserSession */
64
+    private $userSession;
65
+    /** @var bool */
66
+    private $isAdmin;
67
+    /** @var IUserManager */
68
+    private $userManager;
69
+    /** @var IGroupManager */
70
+    private $groupManager;
71
+    /** @var IConfig */
72
+    private $config;
73
+    /** @var ILogger */
74
+    private $log;
75
+    /** @var IMailer */
76
+    private $mailer;
77
+    /** @var bool contains the state of the encryption app */
78
+    private $isEncryptionAppEnabled;
79
+    /** @var bool contains the state of the admin recovery setting */
80
+    private $isRestoreEnabled = false;
81
+    /** @var IAvatarManager */
82
+    private $avatarManager;
83
+    /** @var AccountManager */
84
+    private $accountManager;
85
+    /** @var ISecureRandom */
86
+    private $secureRandom;
87
+    /** @var NewUserMailHelper */
88
+    private $newUserMailHelper;
89
+    /** @var ITimeFactory */
90
+    private $timeFactory;
91
+    /** @var ICrypto */
92
+    private $crypto;
93
+    /** @var Manager */
94
+    private $keyManager;
95
+    /** @var IJobList */
96
+    private $jobList;
97
+
98
+    /**
99
+     * @param string $appName
100
+     * @param IRequest $request
101
+     * @param IUserManager $userManager
102
+     * @param IGroupManager $groupManager
103
+     * @param IUserSession $userSession
104
+     * @param IConfig $config
105
+     * @param bool $isAdmin
106
+     * @param IL10N $l10n
107
+     * @param ILogger $log
108
+     * @param IMailer $mailer
109
+     * @param IURLGenerator $urlGenerator
110
+     * @param IAppManager $appManager
111
+     * @param IAvatarManager $avatarManager
112
+     * @param AccountManager $accountManager
113
+     * @param ISecureRandom $secureRandom
114
+     * @param NewUserMailHelper $newUserMailHelper
115
+     * @param ITimeFactory $timeFactory
116
+     * @param ICrypto $crypto
117
+     * @param Manager $keyManager
118
+     * @param IJobList $jobList
119
+     */
120
+    public function __construct($appName,
121
+                                IRequest $request,
122
+                                IUserManager $userManager,
123
+                                IGroupManager $groupManager,
124
+                                IUserSession $userSession,
125
+                                IConfig $config,
126
+                                $isAdmin,
127
+                                IL10N $l10n,
128
+                                ILogger $log,
129
+                                IMailer $mailer,
130
+                                IURLGenerator $urlGenerator,
131
+                                IAppManager $appManager,
132
+                                IAvatarManager $avatarManager,
133
+                                AccountManager $accountManager,
134
+                                ISecureRandom $secureRandom,
135
+                                NewUserMailHelper $newUserMailHelper,
136
+                                ITimeFactory $timeFactory,
137
+                                ICrypto $crypto,
138
+                                Manager $keyManager,
139
+                                IJobList $jobList) {
140
+        parent::__construct($appName, $request);
141
+        $this->userManager = $userManager;
142
+        $this->groupManager = $groupManager;
143
+        $this->userSession = $userSession;
144
+        $this->config = $config;
145
+        $this->isAdmin = $isAdmin;
146
+        $this->l10n = $l10n;
147
+        $this->log = $log;
148
+        $this->mailer = $mailer;
149
+        $this->avatarManager = $avatarManager;
150
+        $this->accountManager = $accountManager;
151
+        $this->secureRandom = $secureRandom;
152
+        $this->newUserMailHelper = $newUserMailHelper;
153
+        $this->timeFactory = $timeFactory;
154
+        $this->crypto = $crypto;
155
+        $this->keyManager = $keyManager;
156
+        $this->jobList = $jobList;
157
+
158
+        // check for encryption state - TODO see formatUserForIndex
159
+        $this->isEncryptionAppEnabled = $appManager->isEnabledForUser('encryption');
160
+        if($this->isEncryptionAppEnabled) {
161
+            // putting this directly in empty is possible in PHP 5.5+
162
+            $result = $config->getAppValue('encryption', 'recoveryAdminEnabled', 0);
163
+            $this->isRestoreEnabled = !empty($result);
164
+        }
165
+    }
166
+
167
+    /**
168
+     * @param IUser $user
169
+     * @param array $userGroups
170
+     * @return array
171
+     */
172
+    private function formatUserForIndex(IUser $user, array $userGroups = null) {
173
+
174
+        // TODO: eliminate this encryption specific code below and somehow
175
+        // hook in additional user info from other apps
176
+
177
+        // recovery isn't possible if admin or user has it disabled and encryption
178
+        // is enabled - so we eliminate the else paths in the conditional tree
179
+        // below
180
+        $restorePossible = false;
181
+
182
+        if ($this->isEncryptionAppEnabled) {
183
+            if ($this->isRestoreEnabled) {
184
+                // check for the users recovery setting
185
+                $recoveryMode = $this->config->getUserValue($user->getUID(), 'encryption', 'recoveryEnabled', '0');
186
+                // method call inside empty is possible with PHP 5.5+
187
+                $recoveryModeEnabled = !empty($recoveryMode);
188
+                if ($recoveryModeEnabled) {
189
+                    // user also has recovery mode enabled
190
+                    $restorePossible = true;
191
+                }
192
+            }
193
+        } else {
194
+            // recovery is possible if encryption is disabled (plain files are
195
+            // available)
196
+            $restorePossible = true;
197
+        }
198
+
199
+        $subAdminGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($user);
200
+        foreach($subAdminGroups as $key => $subAdminGroup) {
201
+            $subAdminGroups[$key] = $subAdminGroup->getGID();
202
+        }
203
+
204
+        $displayName = $user->getEMailAddress();
205
+        if (is_null($displayName)) {
206
+            $displayName = '';
207
+        }
208
+
209
+        $avatarAvailable = false;
210
+        try {
211
+            $avatarAvailable = $this->avatarManager->getAvatar($user->getUID())->exists();
212
+        } catch (\Exception $e) {
213
+            //No avatar yet
214
+        }
215
+
216
+        return [
217
+            'name' => $user->getUID(),
218
+            'displayname' => $user->getDisplayName(),
219
+            'groups' => (empty($userGroups)) ? $this->groupManager->getUserGroupIds($user) : $userGroups,
220
+            'subadmin' => $subAdminGroups,
221
+            'quota' => $user->getQuota(),
222
+            'storageLocation' => $user->getHome(),
223
+            'lastLogin' => $user->getLastLogin() * 1000,
224
+            'backend' => $user->getBackendClassName(),
225
+            'email' => $displayName,
226
+            'isRestoreDisabled' => !$restorePossible,
227
+            'isAvatarAvailable' => $avatarAvailable,
228
+        ];
229
+    }
230
+
231
+    /**
232
+     * @param array $userIDs Array with schema [$uid => $displayName]
233
+     * @return IUser[]
234
+     */
235
+    private function getUsersForUID(array $userIDs) {
236
+        $users = [];
237
+        foreach ($userIDs as $uid => $displayName) {
238
+            $users[$uid] = $this->userManager->get($uid);
239
+        }
240
+        return $users;
241
+    }
242
+
243
+    /**
244
+     * @NoAdminRequired
245
+     *
246
+     * @param int $offset
247
+     * @param int $limit
248
+     * @param string $gid GID to filter for
249
+     * @param string $pattern Pattern to search for in the username
250
+     * @param string $backend Backend to filter for (class-name)
251
+     * @return DataResponse
252
+     *
253
+     * TODO: Tidy up and write unit tests - code is mainly static method calls
254
+     */
255
+    public function index($offset = 0, $limit = 10, $gid = '', $pattern = '', $backend = '') {
256
+        // FIXME: The JS sends the group '_everyone' instead of no GID for the "all users" group.
257
+        if($gid === '_everyone') {
258
+            $gid = '';
259
+        }
260
+
261
+        // Remove backends
262
+        if(!empty($backend)) {
263
+            $activeBackends = $this->userManager->getBackends();
264
+            $this->userManager->clearBackends();
265
+            foreach($activeBackends as $singleActiveBackend) {
266
+                if($backend === get_class($singleActiveBackend)) {
267
+                    $this->userManager->registerBackend($singleActiveBackend);
268
+                    break;
269
+                }
270
+            }
271
+        }
272
+
273
+        $users = [];
274
+        if ($this->isAdmin) {
275
+
276
+            if($gid !== '') {
277
+                $batch = $this->getUsersForUID($this->groupManager->displayNamesInGroup($gid, $pattern, $limit, $offset));
278
+            } else {
279
+                $batch = $this->userManager->search($pattern, $limit, $offset);
280
+            }
281
+
282
+            foreach ($batch as $user) {
283
+                $users[] = $this->formatUserForIndex($user);
284
+            }
285
+
286
+        } else {
287
+            $subAdminOfGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($this->userSession->getUser());
288
+            // New class returns IGroup[] so convert back
289
+            $gids = [];
290
+            foreach ($subAdminOfGroups as $group) {
291
+                $gids[] = $group->getGID();
292
+            }
293
+            $subAdminOfGroups = $gids;
294
+
295
+            // Set the $gid parameter to an empty value if the subadmin has no rights to access a specific group
296
+            if($gid !== '' && !in_array($gid, $subAdminOfGroups)) {
297
+                $gid = '';
298
+            }
299
+
300
+            // Batch all groups the user is subadmin of when a group is specified
301
+            $batch = [];
302
+            if($gid === '') {
303
+                foreach($subAdminOfGroups as $group) {
304
+                    $groupUsers = $this->groupManager->displayNamesInGroup($group, $pattern, $limit, $offset);
305
+
306
+                    foreach($groupUsers as $uid => $displayName) {
307
+                        $batch[$uid] = $displayName;
308
+                    }
309
+                }
310
+            } else {
311
+                $batch = $this->groupManager->displayNamesInGroup($gid, $pattern, $limit, $offset);
312
+            }
313
+            $batch = $this->getUsersForUID($batch);
314
+
315
+            foreach ($batch as $user) {
316
+                // Only add the groups, this user is a subadmin of
317
+                $userGroups = array_values(array_intersect(
318
+                    $this->groupManager->getUserGroupIds($user),
319
+                    $subAdminOfGroups
320
+                ));
321
+                $users[] = $this->formatUserForIndex($user, $userGroups);
322
+            }
323
+        }
324
+
325
+        return new DataResponse($users);
326
+    }
327
+
328
+    /**
329
+     * @NoAdminRequired
330
+     * @PasswordConfirmationRequired
331
+     *
332
+     * @param string $username
333
+     * @param string $password
334
+     * @param array $groups
335
+     * @param string $email
336
+     * @return DataResponse
337
+     */
338
+    public function create($username, $password, array $groups=array(), $email='') {
339
+        if($email !== '' && !$this->mailer->validateMailAddress($email)) {
340
+            return new DataResponse(
341
+                array(
342
+                    'message' => (string)$this->l10n->t('Invalid mail address')
343
+                ),
344
+                Http::STATUS_UNPROCESSABLE_ENTITY
345
+            );
346
+        }
347
+
348
+        $currentUser = $this->userSession->getUser();
349
+
350
+        if (!$this->isAdmin) {
351
+            if (!empty($groups)) {
352
+                foreach ($groups as $key => $group) {
353
+                    $groupObject = $this->groupManager->get($group);
354
+                    if($groupObject === null) {
355
+                        unset($groups[$key]);
356
+                        continue;
357
+                    }
358
+
359
+                    if (!$this->groupManager->getSubAdmin()->isSubAdminofGroup($currentUser, $groupObject)) {
360
+                        unset($groups[$key]);
361
+                    }
362
+                }
363
+            }
364
+
365
+            if (empty($groups)) {
366
+                return new DataResponse(
367
+                    array(
368
+                        'message' => $this->l10n->t('No valid group selected'),
369
+                    ),
370
+                    Http::STATUS_FORBIDDEN
371
+                );
372
+            }
373
+        }
374
+
375
+        if ($this->userManager->userExists($username)) {
376
+            return new DataResponse(
377
+                array(
378
+                    'message' => (string)$this->l10n->t('A user with that name already exists.')
379
+                ),
380
+                Http::STATUS_CONFLICT
381
+            );
382
+        }
383
+
384
+        $generatePasswordResetToken = false;
385
+        if ($password === '') {
386
+            if ($email === '') {
387
+                return new DataResponse(
388
+                    array(
389
+                        'message' => (string)$this->l10n->t('To send a password link to the user an email address is required.')
390
+                    ),
391
+                    Http::STATUS_UNPROCESSABLE_ENTITY
392
+                );
393
+            }
394
+
395
+            $password = $this->secureRandom->generate(32);
396
+            $generatePasswordResetToken = true;
397
+        }
398
+
399
+        try {
400
+            $user = $this->userManager->createUser($username, $password);
401
+        } catch (\Exception $exception) {
402
+            $message = $exception->getMessage();
403
+            if (!$message) {
404
+                $message = $this->l10n->t('Unable to create user.');
405
+            }
406
+            return new DataResponse(
407
+                array(
408
+                    'message' => (string) $message,
409
+                ),
410
+                Http::STATUS_FORBIDDEN
411
+            );
412
+        }
413
+
414
+        if($user instanceof IUser) {
415
+            if($groups !== null) {
416
+                foreach($groups as $groupName) {
417
+                    $group = $this->groupManager->get($groupName);
418
+
419
+                    if(empty($group)) {
420
+                        $group = $this->groupManager->createGroup($groupName);
421
+                    }
422
+                    $group->addUser($user);
423
+                }
424
+            }
425
+            /**
426
+             * Send new user mail only if a mail is set
427
+             */
428
+            if($email !== '') {
429
+                $user->setEMailAddress($email);
430
+                try {
431
+                    $emailTemplate = $this->newUserMailHelper->generateTemplate($user, $generatePasswordResetToken);
432
+                    $this->newUserMailHelper->sendMail($user, $emailTemplate);
433
+                } catch(\Exception $e) {
434
+                    $this->log->error("Can't send new user mail to $email: " . $e->getMessage(), array('app' => 'settings'));
435
+                }
436
+            }
437
+            // fetch users groups
438
+            $userGroups = $this->groupManager->getUserGroupIds($user);
439
+
440
+            return new DataResponse(
441
+                $this->formatUserForIndex($user, $userGroups),
442
+                Http::STATUS_CREATED
443
+            );
444
+        }
445
+
446
+        return new DataResponse(
447
+            array(
448
+                'message' => (string)$this->l10n->t('Unable to create user.')
449
+            ),
450
+            Http::STATUS_FORBIDDEN
451
+        );
452
+
453
+    }
454
+
455
+    /**
456
+     * @NoAdminRequired
457
+     * @PasswordConfirmationRequired
458
+     *
459
+     * @param string $id
460
+     * @return DataResponse
461
+     */
462
+    public function destroy($id) {
463
+        $userId = $this->userSession->getUser()->getUID();
464
+        $user = $this->userManager->get($id);
465
+
466
+        if($userId === $id) {
467
+            return new DataResponse(
468
+                array(
469
+                    'status' => 'error',
470
+                    'data' => array(
471
+                        'message' => (string)$this->l10n->t('Unable to delete user.')
472
+                    )
473
+                ),
474
+                Http::STATUS_FORBIDDEN
475
+            );
476
+        }
477
+
478
+        if(!$this->isAdmin && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)) {
479
+            return new DataResponse(
480
+                array(
481
+                    'status' => 'error',
482
+                    'data' => array(
483
+                        'message' => (string)$this->l10n->t('Authentication error')
484
+                    )
485
+                ),
486
+                Http::STATUS_FORBIDDEN
487
+            );
488
+        }
489
+
490
+        if($user) {
491
+            if($user->delete()) {
492
+                return new DataResponse(
493
+                    array(
494
+                        'status' => 'success',
495
+                        'data' => array(
496
+                            'username' => $id
497
+                        )
498
+                    ),
499
+                    Http::STATUS_NO_CONTENT
500
+                );
501
+            }
502
+        }
503
+
504
+        return new DataResponse(
505
+            array(
506
+                'status' => 'error',
507
+                'data' => array(
508
+                    'message' => (string)$this->l10n->t('Unable to delete user.')
509
+                )
510
+            ),
511
+            Http::STATUS_FORBIDDEN
512
+        );
513
+    }
514
+
515
+    /**
516
+     * @NoAdminRequired
517
+     * @NoSubadminRequired
518
+     * @PasswordConfirmationRequired
519
+     *
520
+     * @param string $account
521
+     * @return DataResponse
522
+     */
523
+    public function getVerificationCode($account) {
524
+
525
+        $user = $this->userSession->getUser();
526
+
527
+        if ($user === null) {
528
+            return new DataResponse([], Http::STATUS_BAD_REQUEST);
529
+        }
530
+
531
+        $accountData = $this->accountManager->getUser($user);
532
+        $cloudId = $user->getCloudId();
533
+        $message = "Use my Federated Cloud ID to share with me: " . $cloudId;
534
+        $signature = $this->signMessage($user, $message);
535
+
536
+        $code = $message . ' ' . $signature;
537
+        $codeMd5 = $message . ' ' . md5($signature);
538
+
539
+        switch ($account) {
540
+            case 'verify-twitter':
541
+                $accountData[AccountManager::PROPERTY_TWITTER]['verified'] = AccountManager::VERIFICATION_IN_PROGRESS;
542
+                $msg = $this->l10n->t('In order to verify your Twitter account post following tweet on Twitter:');
543
+                $code = $codeMd5;
544
+                $type = AccountManager::PROPERTY_TWITTER;
545
+                $data = $accountData[AccountManager::PROPERTY_TWITTER]['value'];
546
+                break;
547
+            case 'verify-website':
548
+                $accountData[AccountManager::PROPERTY_WEBSITE]['verified'] = AccountManager::VERIFICATION_IN_PROGRESS;
549
+                $msg = $this->l10n->t('In order to verify your Website store following content in your web-root at \'CloudIdVerificationCode.txt\':');
550
+                $type = AccountManager::PROPERTY_WEBSITE;
551
+                $data = $accountData[AccountManager::PROPERTY_WEBSITE]['value'];
552
+                break;
553
+            default:
554
+                return new DataResponse([], Http::STATUS_BAD_REQUEST);
555
+        }
556
+
557
+        $this->accountManager->updateUser($user, $accountData);
558
+
559
+
560
+        $this->jobList->add('OC\Settings\BackgroundJobs\VerifyUserData',
561
+            [
562
+                'verificationCode' => $code,
563
+                'data' => $data,
564
+                'type' => $type,
565
+                'uid' => $user->getUID(),
566
+                'try' => 0,
567
+                'lastRun' => $this->getCurrentTime()
568
+            ]
569
+        );
570
+
571
+        return new DataResponse(['msg' => $msg, 'code' => $code]);
572
+    }
573
+
574
+    /**
575
+     * get current timestamp
576
+     *
577
+     * @return int
578
+     */
579
+    protected function getCurrentTime() {
580
+        return time();
581
+    }
582
+
583
+    /**
584
+     * sign message with users private key
585
+     *
586
+     * @param IUser $user
587
+     * @param string $message
588
+     *
589
+     * @return string base64 encoded signature
590
+     */
591
+    protected function signMessage(IUser $user, $message) {
592
+        $privateKey = $this->keyManager->getKey($user)->getPrivate();
593
+        openssl_sign(json_encode($message), $signature, $privateKey, OPENSSL_ALGO_SHA512);
594
+        $signatureBase64 = base64_encode($signature);
595
+
596
+        return $signatureBase64;
597
+    }
598
+
599
+    /**
600
+     * @NoAdminRequired
601
+     * @NoSubadminRequired
602
+     * @PasswordConfirmationRequired
603
+     *
604
+     * @param string $avatarScope
605
+     * @param string $displayname
606
+     * @param string $displaynameScope
607
+     * @param string $phone
608
+     * @param string $phoneScope
609
+     * @param string $email
610
+     * @param string $emailScope
611
+     * @param string $website
612
+     * @param string $websiteScope
613
+     * @param string $address
614
+     * @param string $addressScope
615
+     * @param string $twitter
616
+     * @param string $twitterScope
617
+     * @return DataResponse
618
+     */
619
+    public function setUserSettings($avatarScope,
620
+                                    $displayname,
621
+                                    $displaynameScope,
622
+                                    $phone,
623
+                                    $phoneScope,
624
+                                    $email,
625
+                                    $emailScope,
626
+                                    $website,
627
+                                    $websiteScope,
628
+                                    $address,
629
+                                    $addressScope,
630
+                                    $twitter,
631
+                                    $twitterScope
632
+    ) {
633
+
634
+        if(!empty($email) && !$this->mailer->validateMailAddress($email)) {
635
+            return new DataResponse(
636
+                array(
637
+                    'status' => 'error',
638
+                    'data' => array(
639
+                        'message' => (string)$this->l10n->t('Invalid mail address')
640
+                    )
641
+                ),
642
+                Http::STATUS_UNPROCESSABLE_ENTITY
643
+            );
644
+        }
645
+
646
+        $data = [
647
+            AccountManager::PROPERTY_AVATAR =>  ['scope' => $avatarScope],
648
+            AccountManager::PROPERTY_DISPLAYNAME => ['value' => $displayname, 'scope' => $displaynameScope],
649
+            AccountManager::PROPERTY_EMAIL=> ['value' => $email, 'scope' => $emailScope],
650
+            AccountManager::PROPERTY_WEBSITE => ['value' => $website, 'scope' => $websiteScope],
651
+            AccountManager::PROPERTY_ADDRESS => ['value' => $address, 'scope' => $addressScope],
652
+            AccountManager::PROPERTY_PHONE => ['value' => $phone, 'scope' => $phoneScope],
653
+            AccountManager::PROPERTY_TWITTER => ['value' => $twitter, 'scope' => $twitterScope]
654
+        ];
655
+
656
+        $user = $this->userSession->getUser();
657
+
658
+        try {
659
+            $this->saveUserSettings($user, $data);
660
+            return new DataResponse(
661
+                array(
662
+                    'status' => 'success',
663
+                    'data' => array(
664
+                        'userId' => $user->getUID(),
665
+                        'avatarScope' => $avatarScope,
666
+                        'displayname' => $displayname,
667
+                        'displaynameScope' => $displaynameScope,
668
+                        'email' => $email,
669
+                        'emailScope' => $emailScope,
670
+                        'website' => $website,
671
+                        'websiteScope' => $websiteScope,
672
+                        'address' => $address,
673
+                        'addressScope' => $addressScope,
674
+                        'message' => (string)$this->l10n->t('Settings saved')
675
+                    )
676
+                ),
677
+                Http::STATUS_OK
678
+            );
679
+        } catch (ForbiddenException $e) {
680
+            return new DataResponse([
681
+                'status' => 'error',
682
+                'data' => [
683
+                    'message' => $e->getMessage()
684
+                ],
685
+            ]);
686
+        }
687
+
688
+    }
689
+
690
+
691
+    /**
692
+     * update account manager with new user data
693
+     *
694
+     * @param IUser $user
695
+     * @param array $data
696
+     * @throws ForbiddenException
697
+     */
698
+    protected function saveUserSettings(IUser $user, $data) {
699
+
700
+        // keep the user back-end up-to-date with the latest display name and email
701
+        // address
702
+        $oldDisplayName = $user->getDisplayName();
703
+        $oldDisplayName = is_null($oldDisplayName) ? '' : $oldDisplayName;
704
+        if (isset($data[AccountManager::PROPERTY_DISPLAYNAME]['value'])
705
+            && $oldDisplayName !== $data[AccountManager::PROPERTY_DISPLAYNAME]['value']
706
+        ) {
707
+            $result = $user->setDisplayName($data[AccountManager::PROPERTY_DISPLAYNAME]['value']);
708
+            if ($result === false) {
709
+                throw new ForbiddenException($this->l10n->t('Unable to change full name'));
710
+            }
711
+        }
712
+
713
+        $oldEmailAddress = $user->getEMailAddress();
714
+        $oldEmailAddress = is_null($oldEmailAddress) ? '' : $oldEmailAddress;
715
+        if (isset($data[AccountManager::PROPERTY_EMAIL]['value'])
716
+            && $oldEmailAddress !== $data[AccountManager::PROPERTY_EMAIL]['value']
717
+        ) {
718
+            // this is the only permission a backend provides and is also used
719
+            // for the permission of setting a email address
720
+            if (!$user->canChangeDisplayName()) {
721
+                throw new ForbiddenException($this->l10n->t('Unable to change email address'));
722
+            }
723
+            $user->setEMailAddress($data[AccountManager::PROPERTY_EMAIL]['value']);
724
+        }
725
+
726
+        $this->accountManager->updateUser($user, $data);
727
+    }
728
+
729
+    /**
730
+     * Count all unique users visible for the current admin/subadmin.
731
+     *
732
+     * @NoAdminRequired
733
+     *
734
+     * @return DataResponse
735
+     */
736
+    public function stats() {
737
+        $userCount = 0;
738
+        if ($this->isAdmin) {
739
+            $countByBackend = $this->userManager->countUsers();
740
+
741
+            if (!empty($countByBackend)) {
742
+                foreach ($countByBackend as $count) {
743
+                    $userCount += $count;
744
+                }
745
+            }
746
+        } else {
747
+            $groups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($this->userSession->getUser());
748
+
749
+            $uniqueUsers = [];
750
+            foreach ($groups as $group) {
751
+                foreach($group->getUsers() as $uid => $displayName) {
752
+                    $uniqueUsers[$uid] = true;
753
+                }
754
+            }
755
+
756
+            $userCount = count($uniqueUsers);
757
+        }
758
+
759
+        return new DataResponse(
760
+            [
761
+                'totalUsers' => $userCount
762
+            ]
763
+        );
764
+    }
765
+
766
+
767
+    /**
768
+     * Set the displayName of a user
769
+     *
770
+     * @NoAdminRequired
771
+     * @NoSubadminRequired
772
+     * @PasswordConfirmationRequired
773
+     * @todo merge into saveUserSettings
774
+     *
775
+     * @param string $username
776
+     * @param string $displayName
777
+     * @return DataResponse
778
+     */
779
+    public function setDisplayName($username, $displayName) {
780
+        $currentUser = $this->userSession->getUser();
781
+        $user = $this->userManager->get($username);
782
+
783
+        if ($user === null ||
784
+            !$user->canChangeDisplayName() ||
785
+            (
786
+                !$this->groupManager->isAdmin($currentUser->getUID()) &&
787
+                !$this->groupManager->getSubAdmin()->isUserAccessible($currentUser, $user) &&
788
+                $currentUser->getUID() !== $username
789
+
790
+            )
791
+        ) {
792
+            return new DataResponse([
793
+                'status' => 'error',
794
+                'data' => [
795
+                    'message' => $this->l10n->t('Authentication error'),
796
+                ],
797
+            ]);
798
+        }
799
+
800
+        $userData = $this->accountManager->getUser($user);
801
+        $userData[AccountManager::PROPERTY_DISPLAYNAME]['value'] = $displayName;
802
+
803
+
804
+        try {
805
+            $this->saveUserSettings($user, $userData);
806
+            return new DataResponse([
807
+                'status' => 'success',
808
+                'data' => [
809
+                    'message' => $this->l10n->t('Your full name has been changed.'),
810
+                    'username' => $username,
811
+                    'displayName' => $displayName,
812
+                ],
813
+            ]);
814
+        } catch (ForbiddenException $e) {
815
+            return new DataResponse([
816
+                'status' => 'error',
817
+                'data' => [
818
+                    'message' => $e->getMessage(),
819
+                    'displayName' => $user->getDisplayName(),
820
+                ],
821
+            ]);
822
+        }
823
+    }
824
+
825
+    /**
826
+     * Set the mail address of a user
827
+     *
828
+     * @NoAdminRequired
829
+     * @NoSubadminRequired
830
+     * @PasswordConfirmationRequired
831
+     *
832
+     * @param string $id
833
+     * @param string $mailAddress
834
+     * @return DataResponse
835
+     */
836
+    public function setEMailAddress($id, $mailAddress) {
837
+        $user = $this->userManager->get($id);
838
+        if (!$this->isAdmin
839
+            && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)
840
+        ) {
841
+            return new DataResponse(
842
+                array(
843
+                    'status' => 'error',
844
+                    'data' => array(
845
+                        'message' => (string)$this->l10n->t('Forbidden')
846
+                    )
847
+                ),
848
+                Http::STATUS_FORBIDDEN
849
+            );
850
+        }
851
+
852
+        if($mailAddress !== '' && !$this->mailer->validateMailAddress($mailAddress)) {
853
+            return new DataResponse(
854
+                array(
855
+                    'status' => 'error',
856
+                    'data' => array(
857
+                        'message' => (string)$this->l10n->t('Invalid mail address')
858
+                    )
859
+                ),
860
+                Http::STATUS_UNPROCESSABLE_ENTITY
861
+            );
862
+        }
863
+
864
+        if (!$user) {
865
+            return new DataResponse(
866
+                array(
867
+                    'status' => 'error',
868
+                    'data' => array(
869
+                        'message' => (string)$this->l10n->t('Invalid user')
870
+                    )
871
+                ),
872
+                Http::STATUS_UNPROCESSABLE_ENTITY
873
+            );
874
+        }
875
+        // this is the only permission a backend provides and is also used
876
+        // for the permission of setting a email address
877
+        if (!$user->canChangeDisplayName()) {
878
+            return new DataResponse(
879
+                array(
880
+                    'status' => 'error',
881
+                    'data' => array(
882
+                        'message' => (string)$this->l10n->t('Unable to change mail address')
883
+                    )
884
+                ),
885
+                Http::STATUS_FORBIDDEN
886
+            );
887
+        }
888
+
889
+        $userData = $this->accountManager->getUser($user);
890
+        $userData[AccountManager::PROPERTY_EMAIL]['value'] = $mailAddress;
891
+
892
+        try {
893
+            $this->saveUserSettings($user, $userData);
894
+            return new DataResponse(
895
+                array(
896
+                    'status' => 'success',
897
+                    'data' => array(
898
+                        'username' => $id,
899
+                        'mailAddress' => $mailAddress,
900
+                        'message' => (string)$this->l10n->t('Email saved')
901
+                    )
902
+                ),
903
+                Http::STATUS_OK
904
+            );
905
+        } catch (ForbiddenException $e) {
906
+            return new DataResponse([
907
+                'status' => 'error',
908
+                'data' => [
909
+                    'message' => $e->getMessage()
910
+                ],
911
+            ]);
912
+        }
913
+    }
914 914
 
915 915
 }
Please login to merge, or discard this patch.
lib/private/Accounts/Hooks.php 1 patch
Indentation   +68 added lines, -68 removed lines patch added patch discarded remove patch
@@ -27,73 +27,73 @@
 block discarded – undo
27 27
 
28 28
 class Hooks {
29 29
 
30
-	/** @var  AccountManager */
31
-	private $accountManager = null;
32
-
33
-	/** @var ILogger */
34
-	private $logger;
35
-
36
-	/**
37
-	 * Hooks constructor.
38
-	 *
39
-	 * @param ILogger $logger
40
-	 */
41
-	public function __construct(ILogger $logger) {
42
-		$this->logger = $logger;
43
-	}
44
-
45
-	/**
46
-	 * update accounts table if email address or display name was changed from outside
47
-	 *
48
-	 * @param array $params
49
-	 */
50
-	public function changeUserHook($params) {
51
-
52
-		$accountManager = $this->getAccountManager();
53
-
54
-		/** @var IUser $user */
55
-		$user = isset($params['user']) ? $params['user'] : null;
56
-		$feature = isset($params['feature']) ? $params['feature'] : null;
57
-		$newValue = isset($params['value']) ? $params['value'] : null;
58
-
59
-		if (is_null($user) || is_null($feature) || is_null($newValue)) {
60
-			$this->logger->warning('Missing expected parameters in change user hook');
61
-			return;
62
-		}
63
-
64
-		$accountData = $accountManager->getUser($user);
65
-
66
-		switch ($feature) {
67
-			case 'eMailAddress':
68
-				if ($accountData[AccountManager::PROPERTY_EMAIL]['value'] !== $newValue) {
69
-					$accountData[AccountManager::PROPERTY_EMAIL]['value'] = $newValue;
70
-					$accountManager->updateUser($user, $accountData);
71
-				}
72
-				break;
73
-			case 'displayName':
74
-				if ($accountData[AccountManager::PROPERTY_DISPLAYNAME]['value'] !== $newValue) {
75
-					$accountData[AccountManager::PROPERTY_DISPLAYNAME]['value'] = $newValue;
76
-					$accountManager->updateUser($user, $accountData);
77
-				}
78
-				break;
79
-		}
80
-
81
-	}
82
-
83
-	/**
84
-	 * return instance of accountManager
85
-	 *
86
-	 * @return AccountManager
87
-	 */
88
-	protected function getAccountManager() {
89
-		if (is_null($this->accountManager)) {
90
-			$this->accountManager = new AccountManager(
91
-				\OC::$server->getDatabaseConnection(),
92
-				\OC::$server->getEventDispatcher(),
93
-				\OC::$server->getJobList()
94
-			);
95
-		}
96
-		return $this->accountManager;
97
-	}
30
+    /** @var  AccountManager */
31
+    private $accountManager = null;
32
+
33
+    /** @var ILogger */
34
+    private $logger;
35
+
36
+    /**
37
+     * Hooks constructor.
38
+     *
39
+     * @param ILogger $logger
40
+     */
41
+    public function __construct(ILogger $logger) {
42
+        $this->logger = $logger;
43
+    }
44
+
45
+    /**
46
+     * update accounts table if email address or display name was changed from outside
47
+     *
48
+     * @param array $params
49
+     */
50
+    public function changeUserHook($params) {
51
+
52
+        $accountManager = $this->getAccountManager();
53
+
54
+        /** @var IUser $user */
55
+        $user = isset($params['user']) ? $params['user'] : null;
56
+        $feature = isset($params['feature']) ? $params['feature'] : null;
57
+        $newValue = isset($params['value']) ? $params['value'] : null;
58
+
59
+        if (is_null($user) || is_null($feature) || is_null($newValue)) {
60
+            $this->logger->warning('Missing expected parameters in change user hook');
61
+            return;
62
+        }
63
+
64
+        $accountData = $accountManager->getUser($user);
65
+
66
+        switch ($feature) {
67
+            case 'eMailAddress':
68
+                if ($accountData[AccountManager::PROPERTY_EMAIL]['value'] !== $newValue) {
69
+                    $accountData[AccountManager::PROPERTY_EMAIL]['value'] = $newValue;
70
+                    $accountManager->updateUser($user, $accountData);
71
+                }
72
+                break;
73
+            case 'displayName':
74
+                if ($accountData[AccountManager::PROPERTY_DISPLAYNAME]['value'] !== $newValue) {
75
+                    $accountData[AccountManager::PROPERTY_DISPLAYNAME]['value'] = $newValue;
76
+                    $accountManager->updateUser($user, $accountData);
77
+                }
78
+                break;
79
+        }
80
+
81
+    }
82
+
83
+    /**
84
+     * return instance of accountManager
85
+     *
86
+     * @return AccountManager
87
+     */
88
+    protected function getAccountManager() {
89
+        if (is_null($this->accountManager)) {
90
+            $this->accountManager = new AccountManager(
91
+                \OC::$server->getDatabaseConnection(),
92
+                \OC::$server->getEventDispatcher(),
93
+                \OC::$server->getJobList()
94
+            );
95
+        }
96
+        return $this->accountManager;
97
+    }
98 98
 
99 99
 }
Please login to merge, or discard this patch.
apps/lookup_server_connector/lib/UpdateLookupServer.php 1 patch
Indentation   +95 added lines, -95 removed lines patch added patch discarded remove patch
@@ -35,107 +35,107 @@
 block discarded – undo
35 35
  * @package OCA\LookupServerConnector
36 36
  */
37 37
 class UpdateLookupServer {
38
-	/** @var AccountManager */
39
-	private $accountManager;
40
-	/** @var IClientService */
41
-	private $clientService;
42
-	/** @var Signer */
43
-	private $signer;
44
-	/** @var IJobList */
45
-	private $jobList;
46
-	/** @var string URL point to lookup server */
47
-	private $lookupServer = 'https://lookup.nextcloud.com';
38
+    /** @var AccountManager */
39
+    private $accountManager;
40
+    /** @var IClientService */
41
+    private $clientService;
42
+    /** @var Signer */
43
+    private $signer;
44
+    /** @var IJobList */
45
+    private $jobList;
46
+    /** @var string URL point to lookup server */
47
+    private $lookupServer = 'https://lookup.nextcloud.com';
48 48
 
49
-	/**
50
-	 * @param AccountManager $accountManager
51
-	 * @param IClientService $clientService
52
-	 * @param Signer $signer
53
-	 * @param IJobList $jobList
54
-	 * @param string $lookupServer if nothing is given we use the default lookup server
55
-	 */
56
-	public function __construct(AccountManager $accountManager,
57
-								IClientService $clientService,
58
-								Signer $signer,
59
-								IJobList $jobList,
60
-								$lookupServer = '') {
61
-		$this->accountManager = $accountManager;
62
-		$this->clientService = $clientService;
63
-		$this->signer = $signer;
64
-		$this->jobList = $jobList;
65
-		if ($lookupServer !== '') {
66
-			$this->lookupServer = $lookupServer;
67
-		}
68
-		$this->lookupServer = rtrim($this->lookupServer, '/');
69
-		$this->lookupServer .= '/users';
70
-	}
49
+    /**
50
+     * @param AccountManager $accountManager
51
+     * @param IClientService $clientService
52
+     * @param Signer $signer
53
+     * @param IJobList $jobList
54
+     * @param string $lookupServer if nothing is given we use the default lookup server
55
+     */
56
+    public function __construct(AccountManager $accountManager,
57
+                                IClientService $clientService,
58
+                                Signer $signer,
59
+                                IJobList $jobList,
60
+                                $lookupServer = '') {
61
+        $this->accountManager = $accountManager;
62
+        $this->clientService = $clientService;
63
+        $this->signer = $signer;
64
+        $this->jobList = $jobList;
65
+        if ($lookupServer !== '') {
66
+            $this->lookupServer = $lookupServer;
67
+        }
68
+        $this->lookupServer = rtrim($this->lookupServer, '/');
69
+        $this->lookupServer .= '/users';
70
+    }
71 71
 
72
-	/**
73
-	 * @param IUser $user
74
-	 */
75
-	public function userUpdated(IUser $user) {
76
-		$userData = $this->accountManager->getUser($user);
77
-		$publicData = [];
72
+    /**
73
+     * @param IUser $user
74
+     */
75
+    public function userUpdated(IUser $user) {
76
+        $userData = $this->accountManager->getUser($user);
77
+        $publicData = [];
78 78
 
79
-		foreach ($userData as $key => $data) {
80
-			if ($data['scope'] === AccountManager::VISIBILITY_PUBLIC) {
81
-				$publicData[$key] = $data;
82
-			}
83
-		}
79
+        foreach ($userData as $key => $data) {
80
+            if ($data['scope'] === AccountManager::VISIBILITY_PUBLIC) {
81
+                $publicData[$key] = $data;
82
+            }
83
+        }
84 84
 
85
-		$this->sendToLookupServer($user, $publicData);
86
-	}
85
+        $this->sendToLookupServer($user, $publicData);
86
+    }
87 87
 
88
-	/**
89
-	 * send public user data to the lookup server
90
-	 *
91
-	 * @param IUser $user
92
-	 * @param array $publicData
93
-	 */
94
-	protected function sendToLookupServer(IUser $user, array $publicData) {
88
+    /**
89
+     * send public user data to the lookup server
90
+     *
91
+     * @param IUser $user
92
+     * @param array $publicData
93
+     */
94
+    protected function sendToLookupServer(IUser $user, array $publicData) {
95 95
 
96
-		$dataArray = ['federationId' => $user->getCloudId()];
96
+        $dataArray = ['federationId' => $user->getCloudId()];
97 97
 
98
-		if (!empty($publicData)) {
99
-			$dataArray['name'] = isset($publicData[AccountManager::PROPERTY_DISPLAYNAME]) ? $publicData[AccountManager::PROPERTY_DISPLAYNAME]['value'] : '';
100
-			$dataArray['email'] = isset($publicData[AccountManager::PROPERTY_EMAIL]) ? $publicData[AccountManager::PROPERTY_EMAIL]['value'] : '';
101
-			$dataArray['address'] = isset($publicData[AccountManager::PROPERTY_ADDRESS]) ? $publicData[AccountManager::PROPERTY_ADDRESS]['value'] : '';
102
-			$dataArray['website'] = isset($publicData[AccountManager::PROPERTY_WEBSITE]) ? $publicData[AccountManager::PROPERTY_WEBSITE]['value'] : '';
103
-			$dataArray['twitter'] = isset($publicData[AccountManager::PROPERTY_TWITTER]) ? $publicData[AccountManager::PROPERTY_TWITTER]['value'] : '';
104
-			$dataArray['phone'] = isset($publicData[AccountManager::PROPERTY_PHONE]) ? $publicData[AccountManager::PROPERTY_PHONE]['value'] : '';
105
-			$dataArray['verificationStatus'] =
106
-				[
107
-					AccountManager::PROPERTY_WEBSITE => isset($publicData[AccountManager::PROPERTY_WEBSITE]) ? $publicData[AccountManager::PROPERTY_WEBSITE]['verified'] : '',
108
-					AccountManager::PROPERTY_TWITTER => isset($publicData[AccountManager::PROPERTY_TWITTER]) ? $publicData[AccountManager::PROPERTY_TWITTER]['verified'] : '',
109
-				];
110
-		}
98
+        if (!empty($publicData)) {
99
+            $dataArray['name'] = isset($publicData[AccountManager::PROPERTY_DISPLAYNAME]) ? $publicData[AccountManager::PROPERTY_DISPLAYNAME]['value'] : '';
100
+            $dataArray['email'] = isset($publicData[AccountManager::PROPERTY_EMAIL]) ? $publicData[AccountManager::PROPERTY_EMAIL]['value'] : '';
101
+            $dataArray['address'] = isset($publicData[AccountManager::PROPERTY_ADDRESS]) ? $publicData[AccountManager::PROPERTY_ADDRESS]['value'] : '';
102
+            $dataArray['website'] = isset($publicData[AccountManager::PROPERTY_WEBSITE]) ? $publicData[AccountManager::PROPERTY_WEBSITE]['value'] : '';
103
+            $dataArray['twitter'] = isset($publicData[AccountManager::PROPERTY_TWITTER]) ? $publicData[AccountManager::PROPERTY_TWITTER]['value'] : '';
104
+            $dataArray['phone'] = isset($publicData[AccountManager::PROPERTY_PHONE]) ? $publicData[AccountManager::PROPERTY_PHONE]['value'] : '';
105
+            $dataArray['verificationStatus'] =
106
+                [
107
+                    AccountManager::PROPERTY_WEBSITE => isset($publicData[AccountManager::PROPERTY_WEBSITE]) ? $publicData[AccountManager::PROPERTY_WEBSITE]['verified'] : '',
108
+                    AccountManager::PROPERTY_TWITTER => isset($publicData[AccountManager::PROPERTY_TWITTER]) ? $publicData[AccountManager::PROPERTY_TWITTER]['verified'] : '',
109
+                ];
110
+        }
111 111
 
112
-		$dataArray = $this->signer->sign('lookupserver', $dataArray, $user);
113
-		$httpClient = $this->clientService->newClient();
114
-		try {
115
-			if (empty($publicData)) {
116
-				$httpClient->delete($this->lookupServer,
117
-					[
118
-						'body' => json_encode($dataArray),
119
-						'timeout' => 10,
120
-						'connect_timeout' => 3,
121
-					]
122
-				);
123
-			} else {
124
-				$httpClient->post($this->lookupServer,
125
-					[
126
-						'body' => json_encode($dataArray),
127
-						'timeout' => 10,
128
-						'connect_timeout' => 3,
129
-					]
130
-				);
131
-			}
132
-		} catch (\Exception $e) {
133
-			$this->jobList->add(RetryJob::class,
134
-				[
135
-					'dataArray' => $dataArray,
136
-					'retryNo' => 0,
137
-				]
138
-			);
139
-		}
140
-	}
112
+        $dataArray = $this->signer->sign('lookupserver', $dataArray, $user);
113
+        $httpClient = $this->clientService->newClient();
114
+        try {
115
+            if (empty($publicData)) {
116
+                $httpClient->delete($this->lookupServer,
117
+                    [
118
+                        'body' => json_encode($dataArray),
119
+                        'timeout' => 10,
120
+                        'connect_timeout' => 3,
121
+                    ]
122
+                );
123
+            } else {
124
+                $httpClient->post($this->lookupServer,
125
+                    [
126
+                        'body' => json_encode($dataArray),
127
+                        'timeout' => 10,
128
+                        'connect_timeout' => 3,
129
+                    ]
130
+                );
131
+            }
132
+        } catch (\Exception $e) {
133
+            $this->jobList->add(RetryJob::class,
134
+                [
135
+                    'dataArray' => $dataArray,
136
+                    'retryNo' => 0,
137
+                ]
138
+            );
139
+        }
140
+    }
141 141
 }
Please login to merge, or discard this patch.
apps/lookup_server_connector/appinfo/app.php 1 patch
Indentation   +23 added lines, -23 removed lines patch added patch discarded remove patch
@@ -22,30 +22,30 @@
 block discarded – undo
22 22
 $dispatcher = \OC::$server->getEventDispatcher();
23 23
 
24 24
 $dispatcher->addListener('OC\AccountManager::userUpdated', function(\Symfony\Component\EventDispatcher\GenericEvent $event) {
25
-	$user = $event->getSubject();
25
+    $user = $event->getSubject();
26 26
 
27
-	$keyManager = new \OC\Security\IdentityProof\Manager(
28
-		\OC::$server->getAppDataDir('identityproof'),
29
-		\OC::$server->getCrypto()
30
-	);
27
+    $keyManager = new \OC\Security\IdentityProof\Manager(
28
+        \OC::$server->getAppDataDir('identityproof'),
29
+        \OC::$server->getCrypto()
30
+    );
31 31
 
32
-	$config = \OC::$server->getConfig();
33
-	$lookupServer = $config->getSystemValue('lookup_server', '');
32
+    $config = \OC::$server->getConfig();
33
+    $lookupServer = $config->getSystemValue('lookup_server', '');
34 34
 
35
-	$updateLookupServer = new \OCA\LookupServerConnector\UpdateLookupServer(
36
-		new \OC\Accounts\AccountManager(
37
-			\OC::$server->getDatabaseConnection(),
38
-			\OC::$server->getEventDispatcher(),
39
-			\OC::$server->getJobList()
40
-		),
41
-		\OC::$server->getHTTPClientService(),
42
-		new \OC\Security\IdentityProof\Signer(
43
-			$keyManager,
44
-			new \OC\AppFramework\Utility\TimeFactory(),
45
-			\OC::$server->getUserManager()
46
-		),
47
-		\OC::$server->getJobList(),
48
-		$lookupServer
49
-	);
50
-	$updateLookupServer->userUpdated($user);
35
+    $updateLookupServer = new \OCA\LookupServerConnector\UpdateLookupServer(
36
+        new \OC\Accounts\AccountManager(
37
+            \OC::$server->getDatabaseConnection(),
38
+            \OC::$server->getEventDispatcher(),
39
+            \OC::$server->getJobList()
40
+        ),
41
+        \OC::$server->getHTTPClientService(),
42
+        new \OC\Security\IdentityProof\Signer(
43
+            $keyManager,
44
+            new \OC\AppFramework\Utility\TimeFactory(),
45
+            \OC::$server->getUserManager()
46
+        ),
47
+        \OC::$server->getJobList(),
48
+        $lookupServer
49
+    );
50
+    $updateLookupServer->userUpdated($user);
51 51
 });
Please login to merge, or discard this patch.
settings/personal.php 1 patch
Indentation   +67 added lines, -67 removed lines patch added patch discarded remove patch
@@ -41,9 +41,9 @@  discard block
 block discarded – undo
41 41
 $defaults = \OC::$server->getThemingDefaults();
42 42
 $certificateManager = \OC::$server->getCertificateManager();
43 43
 $accountManager = new \OC\Accounts\AccountManager(
44
-	\OC::$server->getDatabaseConnection(),
45
-	\OC::$server->getEventDispatcher(),
46
-	\OC::$server->getJobList()
44
+    \OC::$server->getDatabaseConnection(),
45
+    \OC::$server->getEventDispatcher(),
46
+    \OC::$server->getJobList()
47 47
 );
48 48
 $config = \OC::$server->getConfig();
49 49
 $urlGenerator = \OC::$server->getURLGenerator();
@@ -78,72 +78,72 @@  discard block
 block discarded – undo
78 78
 
79 79
 // array of common languages
80 80
 $commonLangCodes = array(
81
-	'en', 'es', 'fr', 'de', 'de_DE', 'ja', 'ar', 'ru', 'nl', 'it', 'pt_BR', 'pt_PT', 'da', 'fi_FI', 'nb_NO', 'sv', 'tr', 'zh_CN', 'ko'
81
+    'en', 'es', 'fr', 'de', 'de_DE', 'ja', 'ar', 'ru', 'nl', 'it', 'pt_BR', 'pt_PT', 'da', 'fi_FI', 'nb_NO', 'sv', 'tr', 'zh_CN', 'ko'
82 82
 );
83 83
 
84 84
 $languages=array();
85 85
 $commonLanguages = array();
86 86
 foreach($languageCodes as $lang) {
87
-	$l = \OC::$server->getL10N('settings', $lang);
88
-	// TRANSLATORS this is the language name for the language switcher in the personal settings and should be the localized version
89
-	$potentialName = (string) $l->t('__language_name__');
90
-	if($l->getLanguageCode() === $lang && substr($potentialName, 0, 1) !== '_') {//first check if the language name is in the translation file
91
-		$ln = array('code' => $lang, 'name' => $potentialName);
92
-	} elseif ($lang === 'en') {
93
-		$ln = ['code' => $lang, 'name' => 'English (US)'];
94
-	}else{//fallback to language code
95
-		$ln=array('code'=>$lang, 'name'=>$lang);
96
-	}
97
-
98
-	// put appropriate languages into appropriate arrays, to print them sorted
99
-	// used language -> common languages -> divider -> other languages
100
-	if ($lang === $userLang) {
101
-		$userLang = $ln;
102
-	} elseif (in_array($lang, $commonLangCodes)) {
103
-		$commonLanguages[array_search($lang, $commonLangCodes)]=$ln;
104
-	} else {
105
-		$languages[]=$ln;
106
-	}
87
+    $l = \OC::$server->getL10N('settings', $lang);
88
+    // TRANSLATORS this is the language name for the language switcher in the personal settings and should be the localized version
89
+    $potentialName = (string) $l->t('__language_name__');
90
+    if($l->getLanguageCode() === $lang && substr($potentialName, 0, 1) !== '_') {//first check if the language name is in the translation file
91
+        $ln = array('code' => $lang, 'name' => $potentialName);
92
+    } elseif ($lang === 'en') {
93
+        $ln = ['code' => $lang, 'name' => 'English (US)'];
94
+    }else{//fallback to language code
95
+        $ln=array('code'=>$lang, 'name'=>$lang);
96
+    }
97
+
98
+    // put appropriate languages into appropriate arrays, to print them sorted
99
+    // used language -> common languages -> divider -> other languages
100
+    if ($lang === $userLang) {
101
+        $userLang = $ln;
102
+    } elseif (in_array($lang, $commonLangCodes)) {
103
+        $commonLanguages[array_search($lang, $commonLangCodes)]=$ln;
104
+    } else {
105
+        $languages[]=$ln;
106
+    }
107 107
 }
108 108
 
109 109
 // if user language is not available but set somehow: show the actual code as name
110 110
 if (!is_array($userLang)) {
111
-	$userLang = [
112
-		'code' => $userLang,
113
-		'name' => $userLang,
114
-	];
111
+    $userLang = [
112
+        'code' => $userLang,
113
+        'name' => $userLang,
114
+    ];
115 115
 }
116 116
 
117 117
 ksort($commonLanguages);
118 118
 
119 119
 // sort now by displayed language not the iso-code
120 120
 usort( $languages, function ($a, $b) {
121
-	if ($a['code'] === $a['name'] && $b['code'] !== $b['name']) {
122
-		// If a doesn't have a name, but b does, list b before a
123
-		return 1;
124
-	}
125
-	if ($a['code'] !== $a['name'] && $b['code'] === $b['name']) {
126
-		// If a does have a name, but b doesn't, list a before b
127
-		return -1;
128
-	}
129
-	// Otherwise compare the names
130
-	return strcmp($a['name'], $b['name']);
121
+    if ($a['code'] === $a['name'] && $b['code'] !== $b['name']) {
122
+        // If a doesn't have a name, but b does, list b before a
123
+        return 1;
124
+    }
125
+    if ($a['code'] !== $a['name'] && $b['code'] === $b['name']) {
126
+        // If a does have a name, but b doesn't, list a before b
127
+        return -1;
128
+    }
129
+    // Otherwise compare the names
130
+    return strcmp($a['name'], $b['name']);
131 131
 });
132 132
 
133 133
 //links to clients
134 134
 $clients = array(
135
-	'desktop' => $config->getSystemValue('customclient_desktop', $defaults->getSyncClientUrl()),
136
-	'android' => $config->getSystemValue('customclient_android', $defaults->getAndroidClientUrl()),
137
-	'ios'     => $config->getSystemValue('customclient_ios', $defaults->getiOSClientUrl())
135
+    'desktop' => $config->getSystemValue('customclient_desktop', $defaults->getSyncClientUrl()),
136
+    'android' => $config->getSystemValue('customclient_android', $defaults->getAndroidClientUrl()),
137
+    'ios'     => $config->getSystemValue('customclient_ios', $defaults->getiOSClientUrl())
138 138
 );
139 139
 
140 140
 // only show root certificate import if external storages are enabled
141 141
 $enableCertImport = false;
142 142
 $externalStorageEnabled = \OC::$server->getAppManager()->isEnabledForUser('files_external');
143 143
 if ($externalStorageEnabled) {
144
-	/** @var \OCA\Files_External\Service\BackendService $backendService */
145
-	$backendService = \OC_Mount_Config::$app->getContainer()->query('\OCA\Files_External\Service\BackendService');
146
-	$enableCertImport = $backendService->isUserMountingAllowed();
144
+    /** @var \OCA\Files_External\Service\BackendService $backendService */
145
+    $backendService = \OC_Mount_Config::$app->getContainer()->query('\OCA\Files_External\Service\BackendService');
146
+    $enableCertImport = $backendService->isUserMountingAllowed();
147 147
 }
148 148
 
149 149
 
@@ -152,9 +152,9 @@  discard block
 block discarded – undo
152 152
 $tmpl = new OC_Template( 'settings', 'personal', 'user');
153 153
 $tmpl->assign('usage', OC_Helper::humanFileSize($storageInfo['used']));
154 154
 if ($storageInfo['quota'] === \OCP\Files\FileInfo::SPACE_UNLIMITED) {
155
-	$totalSpace = $l->t('Unlimited');
155
+    $totalSpace = $l->t('Unlimited');
156 156
 } else {
157
-	$totalSpace = OC_Helper::humanFileSize($storageInfo['total']);
157
+    $totalSpace = OC_Helper::humanFileSize($storageInfo['total']);
158 158
 }
159 159
 
160 160
 $uid = $user->getUID();
@@ -212,30 +212,30 @@  discard block
 block discarded – undo
212 212
 
213 213
 // add bottom hardcoded forms from the template
214 214
 if ($enableCertImport) {
215
-	$certificatesTemplate = new OC_Template('settings', 'certificates');
216
-	$certificatesTemplate->assign('type', 'personal');
217
-	$certificatesTemplate->assign('uploadRoute', 'settings.Certificate.addPersonalRootCertificate');
218
-	$certificatesTemplate->assign('certs', $certificateManager->listCertificates());
219
-	$certificatesTemplate->assign('urlGenerator', $urlGenerator);
220
-	$forms[] = $certificatesTemplate->fetchPage();
215
+    $certificatesTemplate = new OC_Template('settings', 'certificates');
216
+    $certificatesTemplate->assign('type', 'personal');
217
+    $certificatesTemplate->assign('uploadRoute', 'settings.Certificate.addPersonalRootCertificate');
218
+    $certificatesTemplate->assign('certs', $certificateManager->listCertificates());
219
+    $certificatesTemplate->assign('urlGenerator', $urlGenerator);
220
+    $forms[] = $certificatesTemplate->fetchPage();
221 221
 }
222 222
 
223 223
 $formsMap = array_map(function($form){
224
-	if (preg_match('%(<h2(?P<class>[^>]*)>.*?</h2>)%i', $form, $regs)) {
225
-		$sectionName = str_replace('<h2'.$regs['class'].'>', '', $regs[0]);
226
-		$sectionName = str_replace('</h2>', '', $sectionName);
227
-		$anchor = strtolower($sectionName);
228
-		$anchor = str_replace(' ', '-', $anchor);
229
-
230
-		return array(
231
-			'anchor' => $anchor,
232
-			'section-name' => $sectionName,
233
-			'form' => $form
234
-		);
235
-	}
236
-	return array(
237
-		'form' => $form
238
-	);
224
+    if (preg_match('%(<h2(?P<class>[^>]*)>.*?</h2>)%i', $form, $regs)) {
225
+        $sectionName = str_replace('<h2'.$regs['class'].'>', '', $regs[0]);
226
+        $sectionName = str_replace('</h2>', '', $sectionName);
227
+        $anchor = strtolower($sectionName);
228
+        $anchor = str_replace(' ', '-', $anchor);
229
+
230
+        return array(
231
+            'anchor' => $anchor,
232
+            'section-name' => $sectionName,
233
+            'form' => $form
234
+        );
235
+    }
236
+    return array(
237
+        'form' => $form
238
+    );
239 239
 }, $forms);
240 240
 
241 241
 $formsAndMore = array_merge($formsAndMore, $formsMap);
Please login to merge, or discard this patch.
apps/sharebymail/lib/Activity.php 1 patch
Indentation   +268 added lines, -268 removed lines patch added patch discarded remove patch
@@ -33,272 +33,272 @@
 block discarded – undo
33 33
 
34 34
 class Activity implements IProvider {
35 35
 
36
-	/** @var IFactory */
37
-	protected $languageFactory;
38
-
39
-	/** @var IL10N */
40
-	protected $l;
41
-
42
-	/** @var IURLGenerator */
43
-	protected $url;
44
-
45
-	/** @var IManager */
46
-	protected $activityManager;
47
-
48
-	/** @var IUserManager */
49
-	protected $userManager;
50
-	/** @var IContactsManager */
51
-	protected $contactsManager;
52
-
53
-	/** @var array */
54
-	protected $displayNames = [];
55
-
56
-	/** @var array */
57
-	protected $contactNames = [];
58
-
59
-	const SUBJECT_SHARED_EMAIL_SELF = 'shared_with_email_self';
60
-	const SUBJECT_SHARED_EMAIL_BY = 'shared_with_email_by';
61
-	const SUBJECT_SHARED_EMAIL_PASSWORD_SEND = 'shared_with_email_password_send';
62
-	const SUBJECT_SHARED_EMAIL_PASSWORD_SEND_SELF = 'shared_with_email_password_send_self';
63
-
64
-	/**
65
-	 * @param IFactory $languageFactory
66
-	 * @param IURLGenerator $url
67
-	 * @param IManager $activityManager
68
-	 * @param IUserManager $userManager
69
-	 * @param IContactsManager $contactsManager
70
-	 */
71
-	public function __construct(IFactory $languageFactory, IURLGenerator $url, IManager $activityManager, IUserManager $userManager, IContactsManager $contactsManager) {
72
-		$this->languageFactory = $languageFactory;
73
-		$this->url = $url;
74
-		$this->activityManager = $activityManager;
75
-		$this->userManager = $userManager;
76
-		$this->contactsManager = $contactsManager;
77
-	}
78
-
79
-	/**
80
-	 * @param string $language
81
-	 * @param IEvent $event
82
-	 * @param IEvent|null $previousEvent
83
-	 * @return IEvent
84
-	 * @throws \InvalidArgumentException
85
-	 * @since 11.0.0
86
-	 */
87
-	public function parse($language, IEvent $event, IEvent $previousEvent = null) {
88
-		if ($event->getApp() !== 'sharebymail') {
89
-			throw new \InvalidArgumentException();
90
-		}
91
-
92
-		$this->l = $this->languageFactory->get('sharebymail', $language);
93
-
94
-		if ($this->activityManager->isFormattingFilteredObject()) {
95
-			try {
96
-				return $this->parseShortVersion($event);
97
-			} catch (\InvalidArgumentException $e) {
98
-				// Ignore and simply use the long version...
99
-			}
100
-		}
101
-
102
-		return $this->parseLongVersion($event);
103
-	}
104
-
105
-	/**
106
-	 * @param IEvent $event
107
-	 * @return IEvent
108
-	 * @throws \InvalidArgumentException
109
-	 * @since 11.0.0
110
-	 */
111
-	public function parseShortVersion(IEvent $event) {
112
-		$parsedParameters = $this->getParsedParameters($event);
113
-
114
-		if ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_SELF) {
115
-			$event->setParsedSubject($this->l->t('Shared with %1$s', [
116
-					$parsedParameters['email']['name'],
117
-				]))
118
-				->setRichSubject($this->l->t('Shared with {email}'), [
119
-					'email' => $parsedParameters['email'],
120
-				])
121
-				->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
122
-		} else if ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_BY) {
123
-			$event->setParsedSubject($this->l->t('Shared with %1$s by %2$s', [
124
-				$parsedParameters['email']['name'],
125
-				$parsedParameters['actor']['name'],
126
-			]))
127
-				->setRichSubject($this->l->t('Shared with {email} by {actor}'), [
128
-					'email' => $parsedParameters['email'],
129
-					'actor' => $parsedParameters['actor'],
130
-				])
131
-				->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
132
-		} else if ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_PASSWORD_SEND) {
133
-			$event->setParsedSubject($this->l->t('Password for mail share sent to %1$s', [
134
-				$parsedParameters['email']['name']
135
-			]))
136
-				->setRichSubject($this->l->t('Password for mail share sent to {email}'), [
137
-					'email' => $parsedParameters['email']
138
-				])
139
-				->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
140
-		} else if ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_PASSWORD_SEND_SELF) {
141
-			$event->setParsedSubject($this->l->t('Password for mail share sent to you'))
142
-				->setRichSubject($this->l->t('Password for mail share sent to you'))
143
-				->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
144
-		} else {
145
-			throw new \InvalidArgumentException();
146
-		}
147
-
148
-		return $event;
149
-	}
150
-
151
-	/**
152
-	 * @param IEvent $event
153
-	 * @return IEvent
154
-	 * @throws \InvalidArgumentException
155
-	 * @since 11.0.0
156
-	 */
157
-	public function parseLongVersion(IEvent $event) {
158
-		$parsedParameters = $this->getParsedParameters($event);
159
-
160
-		if ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_SELF) {
161
-			$event->setParsedSubject($this->l->t('You shared %1$s with %2$s by mail', [
162
-					$parsedParameters['file']['path'],
163
-					$parsedParameters['email']['name'],
164
-				]))
165
-				->setRichSubject($this->l->t('You shared {file} with {email} by mail'), $parsedParameters)
166
-				->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
167
-		} else if ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_BY) {
168
-			$event->setParsedSubject($this->l->t('%3$s shared %1$s with %2$s by mail', [
169
-				$parsedParameters['file']['path'],
170
-				$parsedParameters['email']['name'],
171
-				$parsedParameters['actor']['name'],
172
-			]))
173
-				->setRichSubject($this->l->t('{actor} shared {file} with {email} by mail'), $parsedParameters)
174
-				->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
175
-		} else if ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_PASSWORD_SEND) {
176
-			$event->setParsedSubject($this->l->t('Password to access %1$s was sent to %2s', [
177
-				$parsedParameters['file']['path'],
178
-				$parsedParameters['email']['name']
179
-			]))
180
-				->setRichSubject($this->l->t('Password to access {file} was sent to {email}'), $parsedParameters)
181
-				->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
182
-		} else if ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_PASSWORD_SEND_SELF) {
183
-			$event->setParsedSubject(
184
-				$this->l->t('Password to access %1$s was sent to you',
185
-					[$parsedParameters['file']['path']]))
186
-				->setRichSubject($this->l->t('Password to access {file} was sent to you'), $parsedParameters)
187
-				->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
188
-
189
-		} else {
190
-			throw new \InvalidArgumentException();
191
-		}
192
-
193
-		return $event;
194
-	}
195
-
196
-	protected function getParsedParameters(IEvent $event) {
197
-		$subject = $event->getSubject();
198
-		$parameters = $event->getSubjectParameters();
199
-
200
-		switch ($subject) {
201
-			case self::SUBJECT_SHARED_EMAIL_SELF:
202
-				return [
203
-					'file' => $this->generateFileParameter((int) $event->getObjectId(), $parameters[0]),
204
-					'email' => $this->generateEmailParameter($parameters[1]),
205
-				];
206
-			case self::SUBJECT_SHARED_EMAIL_BY:
207
-				return [
208
-					'file' => $this->generateFileParameter((int) $event->getObjectId(), $parameters[0]),
209
-					'email' => $this->generateEmailParameter($parameters[1]),
210
-					'actor' => $this->generateUserParameter($parameters[2]),
211
-				];
212
-			case self::SUBJECT_SHARED_EMAIL_PASSWORD_SEND:
213
-				return [
214
-					'file' => $this->generateFileParameter((int) $event->getObjectId(), $parameters[0]),
215
-					'email' => $this->generateEmailParameter($parameters[1]),
216
-				];
217
-			case self::SUBJECT_SHARED_EMAIL_PASSWORD_SEND_SELF:
218
-				return [
219
-					'file' => $this->generateFileParameter((int) $event->getObjectId(), $parameters[0]),
220
-				];
221
-		}
222
-		throw new \InvalidArgumentException();
223
-	}
224
-
225
-	/**
226
-	 * @param int $id
227
-	 * @param string $path
228
-	 * @return array
229
-	 */
230
-	protected function generateFileParameter($id, $path) {
231
-		return [
232
-			'type' => 'file',
233
-			'id' => $id,
234
-			'name' => basename($path),
235
-			'path' => trim($path, '/'),
236
-			'link' => $this->url->linkToRouteAbsolute('files.viewcontroller.showFile', ['fileid' => $id]),
237
-		];
238
-	}
239
-
240
-	/**
241
-	 * @param string $email
242
-	 * @return array
243
-	 */
244
-	protected function generateEmailParameter($email) {
245
-		if (!isset($this->contactNames[$email])) {
246
-			$this->contactNames[$email] = $this->getContactName($email);
247
-		}
248
-
249
-		return [
250
-			'type' => 'email',
251
-			'id' => $email,
252
-			'name' => $this->contactNames[$email],
253
-		];
254
-	}
255
-
256
-	/**
257
-	 * @param string $uid
258
-	 * @return array
259
-	 */
260
-	protected function generateUserParameter($uid) {
261
-		if (!isset($this->displayNames[$uid])) {
262
-			$this->displayNames[$uid] = $this->getDisplayName($uid);
263
-		}
264
-
265
-		return [
266
-			'type' => 'user',
267
-			'id' => $uid,
268
-			'name' => $this->displayNames[$uid],
269
-		];
270
-	}
271
-
272
-	/**
273
-	 * @param string $email
274
-	 * @return string
275
-	 */
276
-	protected function getContactName($email) {
277
-		$addressBookContacts = $this->contactsManager->search($email, ['EMAIL']);
278
-
279
-		foreach ($addressBookContacts as $contact) {
280
-			if (isset($contact['isLocalSystemBook'])) {
281
-				continue;
282
-			}
283
-
284
-			if (in_array($email, $contact['EMAIL'])) {
285
-				return $contact['FN'];
286
-			}
287
-		}
288
-
289
-		return $email;
290
-	}
291
-
292
-	/**
293
-	 * @param string $uid
294
-	 * @return string
295
-	 */
296
-	protected function getDisplayName($uid) {
297
-		$user = $this->userManager->get($uid);
298
-		if ($user instanceof IUser) {
299
-			return $user->getDisplayName();
300
-		} else {
301
-			return $uid;
302
-		}
303
-	}
36
+    /** @var IFactory */
37
+    protected $languageFactory;
38
+
39
+    /** @var IL10N */
40
+    protected $l;
41
+
42
+    /** @var IURLGenerator */
43
+    protected $url;
44
+
45
+    /** @var IManager */
46
+    protected $activityManager;
47
+
48
+    /** @var IUserManager */
49
+    protected $userManager;
50
+    /** @var IContactsManager */
51
+    protected $contactsManager;
52
+
53
+    /** @var array */
54
+    protected $displayNames = [];
55
+
56
+    /** @var array */
57
+    protected $contactNames = [];
58
+
59
+    const SUBJECT_SHARED_EMAIL_SELF = 'shared_with_email_self';
60
+    const SUBJECT_SHARED_EMAIL_BY = 'shared_with_email_by';
61
+    const SUBJECT_SHARED_EMAIL_PASSWORD_SEND = 'shared_with_email_password_send';
62
+    const SUBJECT_SHARED_EMAIL_PASSWORD_SEND_SELF = 'shared_with_email_password_send_self';
63
+
64
+    /**
65
+     * @param IFactory $languageFactory
66
+     * @param IURLGenerator $url
67
+     * @param IManager $activityManager
68
+     * @param IUserManager $userManager
69
+     * @param IContactsManager $contactsManager
70
+     */
71
+    public function __construct(IFactory $languageFactory, IURLGenerator $url, IManager $activityManager, IUserManager $userManager, IContactsManager $contactsManager) {
72
+        $this->languageFactory = $languageFactory;
73
+        $this->url = $url;
74
+        $this->activityManager = $activityManager;
75
+        $this->userManager = $userManager;
76
+        $this->contactsManager = $contactsManager;
77
+    }
78
+
79
+    /**
80
+     * @param string $language
81
+     * @param IEvent $event
82
+     * @param IEvent|null $previousEvent
83
+     * @return IEvent
84
+     * @throws \InvalidArgumentException
85
+     * @since 11.0.0
86
+     */
87
+    public function parse($language, IEvent $event, IEvent $previousEvent = null) {
88
+        if ($event->getApp() !== 'sharebymail') {
89
+            throw new \InvalidArgumentException();
90
+        }
91
+
92
+        $this->l = $this->languageFactory->get('sharebymail', $language);
93
+
94
+        if ($this->activityManager->isFormattingFilteredObject()) {
95
+            try {
96
+                return $this->parseShortVersion($event);
97
+            } catch (\InvalidArgumentException $e) {
98
+                // Ignore and simply use the long version...
99
+            }
100
+        }
101
+
102
+        return $this->parseLongVersion($event);
103
+    }
104
+
105
+    /**
106
+     * @param IEvent $event
107
+     * @return IEvent
108
+     * @throws \InvalidArgumentException
109
+     * @since 11.0.0
110
+     */
111
+    public function parseShortVersion(IEvent $event) {
112
+        $parsedParameters = $this->getParsedParameters($event);
113
+
114
+        if ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_SELF) {
115
+            $event->setParsedSubject($this->l->t('Shared with %1$s', [
116
+                    $parsedParameters['email']['name'],
117
+                ]))
118
+                ->setRichSubject($this->l->t('Shared with {email}'), [
119
+                    'email' => $parsedParameters['email'],
120
+                ])
121
+                ->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
122
+        } else if ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_BY) {
123
+            $event->setParsedSubject($this->l->t('Shared with %1$s by %2$s', [
124
+                $parsedParameters['email']['name'],
125
+                $parsedParameters['actor']['name'],
126
+            ]))
127
+                ->setRichSubject($this->l->t('Shared with {email} by {actor}'), [
128
+                    'email' => $parsedParameters['email'],
129
+                    'actor' => $parsedParameters['actor'],
130
+                ])
131
+                ->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
132
+        } else if ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_PASSWORD_SEND) {
133
+            $event->setParsedSubject($this->l->t('Password for mail share sent to %1$s', [
134
+                $parsedParameters['email']['name']
135
+            ]))
136
+                ->setRichSubject($this->l->t('Password for mail share sent to {email}'), [
137
+                    'email' => $parsedParameters['email']
138
+                ])
139
+                ->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
140
+        } else if ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_PASSWORD_SEND_SELF) {
141
+            $event->setParsedSubject($this->l->t('Password for mail share sent to you'))
142
+                ->setRichSubject($this->l->t('Password for mail share sent to you'))
143
+                ->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
144
+        } else {
145
+            throw new \InvalidArgumentException();
146
+        }
147
+
148
+        return $event;
149
+    }
150
+
151
+    /**
152
+     * @param IEvent $event
153
+     * @return IEvent
154
+     * @throws \InvalidArgumentException
155
+     * @since 11.0.0
156
+     */
157
+    public function parseLongVersion(IEvent $event) {
158
+        $parsedParameters = $this->getParsedParameters($event);
159
+
160
+        if ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_SELF) {
161
+            $event->setParsedSubject($this->l->t('You shared %1$s with %2$s by mail', [
162
+                    $parsedParameters['file']['path'],
163
+                    $parsedParameters['email']['name'],
164
+                ]))
165
+                ->setRichSubject($this->l->t('You shared {file} with {email} by mail'), $parsedParameters)
166
+                ->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
167
+        } else if ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_BY) {
168
+            $event->setParsedSubject($this->l->t('%3$s shared %1$s with %2$s by mail', [
169
+                $parsedParameters['file']['path'],
170
+                $parsedParameters['email']['name'],
171
+                $parsedParameters['actor']['name'],
172
+            ]))
173
+                ->setRichSubject($this->l->t('{actor} shared {file} with {email} by mail'), $parsedParameters)
174
+                ->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
175
+        } else if ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_PASSWORD_SEND) {
176
+            $event->setParsedSubject($this->l->t('Password to access %1$s was sent to %2s', [
177
+                $parsedParameters['file']['path'],
178
+                $parsedParameters['email']['name']
179
+            ]))
180
+                ->setRichSubject($this->l->t('Password to access {file} was sent to {email}'), $parsedParameters)
181
+                ->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
182
+        } else if ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_PASSWORD_SEND_SELF) {
183
+            $event->setParsedSubject(
184
+                $this->l->t('Password to access %1$s was sent to you',
185
+                    [$parsedParameters['file']['path']]))
186
+                ->setRichSubject($this->l->t('Password to access {file} was sent to you'), $parsedParameters)
187
+                ->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
188
+
189
+        } else {
190
+            throw new \InvalidArgumentException();
191
+        }
192
+
193
+        return $event;
194
+    }
195
+
196
+    protected function getParsedParameters(IEvent $event) {
197
+        $subject = $event->getSubject();
198
+        $parameters = $event->getSubjectParameters();
199
+
200
+        switch ($subject) {
201
+            case self::SUBJECT_SHARED_EMAIL_SELF:
202
+                return [
203
+                    'file' => $this->generateFileParameter((int) $event->getObjectId(), $parameters[0]),
204
+                    'email' => $this->generateEmailParameter($parameters[1]),
205
+                ];
206
+            case self::SUBJECT_SHARED_EMAIL_BY:
207
+                return [
208
+                    'file' => $this->generateFileParameter((int) $event->getObjectId(), $parameters[0]),
209
+                    'email' => $this->generateEmailParameter($parameters[1]),
210
+                    'actor' => $this->generateUserParameter($parameters[2]),
211
+                ];
212
+            case self::SUBJECT_SHARED_EMAIL_PASSWORD_SEND:
213
+                return [
214
+                    'file' => $this->generateFileParameter((int) $event->getObjectId(), $parameters[0]),
215
+                    'email' => $this->generateEmailParameter($parameters[1]),
216
+                ];
217
+            case self::SUBJECT_SHARED_EMAIL_PASSWORD_SEND_SELF:
218
+                return [
219
+                    'file' => $this->generateFileParameter((int) $event->getObjectId(), $parameters[0]),
220
+                ];
221
+        }
222
+        throw new \InvalidArgumentException();
223
+    }
224
+
225
+    /**
226
+     * @param int $id
227
+     * @param string $path
228
+     * @return array
229
+     */
230
+    protected function generateFileParameter($id, $path) {
231
+        return [
232
+            'type' => 'file',
233
+            'id' => $id,
234
+            'name' => basename($path),
235
+            'path' => trim($path, '/'),
236
+            'link' => $this->url->linkToRouteAbsolute('files.viewcontroller.showFile', ['fileid' => $id]),
237
+        ];
238
+    }
239
+
240
+    /**
241
+     * @param string $email
242
+     * @return array
243
+     */
244
+    protected function generateEmailParameter($email) {
245
+        if (!isset($this->contactNames[$email])) {
246
+            $this->contactNames[$email] = $this->getContactName($email);
247
+        }
248
+
249
+        return [
250
+            'type' => 'email',
251
+            'id' => $email,
252
+            'name' => $this->contactNames[$email],
253
+        ];
254
+    }
255
+
256
+    /**
257
+     * @param string $uid
258
+     * @return array
259
+     */
260
+    protected function generateUserParameter($uid) {
261
+        if (!isset($this->displayNames[$uid])) {
262
+            $this->displayNames[$uid] = $this->getDisplayName($uid);
263
+        }
264
+
265
+        return [
266
+            'type' => 'user',
267
+            'id' => $uid,
268
+            'name' => $this->displayNames[$uid],
269
+        ];
270
+    }
271
+
272
+    /**
273
+     * @param string $email
274
+     * @return string
275
+     */
276
+    protected function getContactName($email) {
277
+        $addressBookContacts = $this->contactsManager->search($email, ['EMAIL']);
278
+
279
+        foreach ($addressBookContacts as $contact) {
280
+            if (isset($contact['isLocalSystemBook'])) {
281
+                continue;
282
+            }
283
+
284
+            if (in_array($email, $contact['EMAIL'])) {
285
+                return $contact['FN'];
286
+            }
287
+        }
288
+
289
+        return $email;
290
+    }
291
+
292
+    /**
293
+     * @param string $uid
294
+     * @return string
295
+     */
296
+    protected function getDisplayName($uid) {
297
+        $user = $this->userManager->get($uid);
298
+        if ($user instanceof IUser) {
299
+            return $user->getDisplayName();
300
+        } else {
301
+            return $uid;
302
+        }
303
+    }
304 304
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/User/User.php 1 patch
Indentation   +643 added lines, -643 removed lines patch added patch discarded remove patch
@@ -43,653 +43,653 @@
 block discarded – undo
43 43
  * represents an LDAP user, gets and holds user-specific information from LDAP
44 44
  */
45 45
 class User {
46
-	/**
47
-	 * @var IUserTools
48
-	 */
49
-	protected $access;
50
-	/**
51
-	 * @var Connection
52
-	 */
53
-	protected $connection;
54
-	/**
55
-	 * @var IConfig
56
-	 */
57
-	protected $config;
58
-	/**
59
-	 * @var FilesystemHelper
60
-	 */
61
-	protected $fs;
62
-	/**
63
-	 * @var Image
64
-	 */
65
-	protected $image;
66
-	/**
67
-	 * @var LogWrapper
68
-	 */
69
-	protected $log;
70
-	/**
71
-	 * @var IAvatarManager
72
-	 */
73
-	protected $avatarManager;
74
-	/**
75
-	 * @var IUserManager
76
-	 */
77
-	protected $userManager;
78
-	/**
79
-	 * @var INotificationManager
80
-	 */
81
-	protected $notificationManager;
82
-	/**
83
-	 * @var string
84
-	 */
85
-	protected $dn;
86
-	/**
87
-	 * @var string
88
-	 */
89
-	protected $uid;
90
-	/**
91
-	 * @var string[]
92
-	 */
93
-	protected $refreshedFeatures = array();
94
-	/**
95
-	 * @var string
96
-	 */
97
-	protected $avatarImage;
98
-
99
-	/**
100
-	 * DB config keys for user preferences
101
-	 */
102
-	const USER_PREFKEY_FIRSTLOGIN  = 'firstLoginAccomplished';
103
-	const USER_PREFKEY_LASTREFRESH = 'lastFeatureRefresh';
104
-
105
-	/**
106
-	 * @brief constructor, make sure the subclasses call this one!
107
-	 * @param string $username the internal username
108
-	 * @param string $dn the LDAP DN
109
-	 * @param IUserTools $access an instance that implements IUserTools for
110
-	 * LDAP interaction
111
-	 * @param IConfig $config
112
-	 * @param FilesystemHelper $fs
113
-	 * @param Image $image any empty instance
114
-	 * @param LogWrapper $log
115
-	 * @param IAvatarManager $avatarManager
116
-	 * @param IUserManager $userManager
117
-	 * @param INotificationManager $notificationManager
118
-	 */
119
-	public function __construct($username, $dn, IUserTools $access,
120
-		IConfig $config, FilesystemHelper $fs, Image $image,
121
-		LogWrapper $log, IAvatarManager $avatarManager, IUserManager $userManager,
122
-		INotificationManager $notificationManager) {
46
+    /**
47
+     * @var IUserTools
48
+     */
49
+    protected $access;
50
+    /**
51
+     * @var Connection
52
+     */
53
+    protected $connection;
54
+    /**
55
+     * @var IConfig
56
+     */
57
+    protected $config;
58
+    /**
59
+     * @var FilesystemHelper
60
+     */
61
+    protected $fs;
62
+    /**
63
+     * @var Image
64
+     */
65
+    protected $image;
66
+    /**
67
+     * @var LogWrapper
68
+     */
69
+    protected $log;
70
+    /**
71
+     * @var IAvatarManager
72
+     */
73
+    protected $avatarManager;
74
+    /**
75
+     * @var IUserManager
76
+     */
77
+    protected $userManager;
78
+    /**
79
+     * @var INotificationManager
80
+     */
81
+    protected $notificationManager;
82
+    /**
83
+     * @var string
84
+     */
85
+    protected $dn;
86
+    /**
87
+     * @var string
88
+     */
89
+    protected $uid;
90
+    /**
91
+     * @var string[]
92
+     */
93
+    protected $refreshedFeatures = array();
94
+    /**
95
+     * @var string
96
+     */
97
+    protected $avatarImage;
98
+
99
+    /**
100
+     * DB config keys for user preferences
101
+     */
102
+    const USER_PREFKEY_FIRSTLOGIN  = 'firstLoginAccomplished';
103
+    const USER_PREFKEY_LASTREFRESH = 'lastFeatureRefresh';
104
+
105
+    /**
106
+     * @brief constructor, make sure the subclasses call this one!
107
+     * @param string $username the internal username
108
+     * @param string $dn the LDAP DN
109
+     * @param IUserTools $access an instance that implements IUserTools for
110
+     * LDAP interaction
111
+     * @param IConfig $config
112
+     * @param FilesystemHelper $fs
113
+     * @param Image $image any empty instance
114
+     * @param LogWrapper $log
115
+     * @param IAvatarManager $avatarManager
116
+     * @param IUserManager $userManager
117
+     * @param INotificationManager $notificationManager
118
+     */
119
+    public function __construct($username, $dn, IUserTools $access,
120
+        IConfig $config, FilesystemHelper $fs, Image $image,
121
+        LogWrapper $log, IAvatarManager $avatarManager, IUserManager $userManager,
122
+        INotificationManager $notificationManager) {
123 123
 	
124
-		if ($username === null) {
125
-			$log->log("uid for '$dn' must not be null!", Util::ERROR);
126
-			throw new \InvalidArgumentException('uid must not be null!');
127
-		} else if ($username === '') {
128
-			$log->log("uid for '$dn' must not be an empty string", Util::ERROR);
129
-			throw new \InvalidArgumentException('uid must not be an empty string!');
130
-		}
131
-
132
-		$this->access              = $access;
133
-		$this->connection          = $access->getConnection();
134
-		$this->config              = $config;
135
-		$this->fs                  = $fs;
136
-		$this->dn                  = $dn;
137
-		$this->uid                 = $username;
138
-		$this->image               = $image;
139
-		$this->log                 = $log;
140
-		$this->avatarManager       = $avatarManager;
141
-		$this->userManager         = $userManager;
142
-		$this->notificationManager = $notificationManager;
143
-
144
-		\OCP\Util::connectHook('OC_User', 'post_login', $this, 'handlePasswordExpiry');
145
-	}
146
-
147
-	/**
148
-	 * @brief updates properties like email, quota or avatar provided by LDAP
149
-	 * @return null
150
-	 */
151
-	public function update() {
152
-		if(is_null($this->dn)) {
153
-			return null;
154
-		}
155
-
156
-		$hasLoggedIn = $this->config->getUserValue($this->uid, 'user_ldap',
157
-				self::USER_PREFKEY_FIRSTLOGIN, 0);
158
-
159
-		if($this->needsRefresh()) {
160
-			$this->updateEmail();
161
-			$this->updateQuota();
162
-			if($hasLoggedIn !== 0) {
163
-				//we do not need to try it, when the user has not been logged in
164
-				//before, because the file system will not be ready.
165
-				$this->updateAvatar();
166
-				//in order to get an avatar as soon as possible, mark the user
167
-				//as refreshed only when updating the avatar did happen
168
-				$this->markRefreshTime();
169
-			}
170
-		}
171
-	}
172
-
173
-	/**
174
-	 * processes results from LDAP for attributes as returned by getAttributesToRead()
175
-	 * @param array $ldapEntry the user entry as retrieved from LDAP
176
-	 */
177
-	public function processAttributes($ldapEntry) {
178
-		$this->markRefreshTime();
179
-		//Quota
180
-		$attr = strtolower($this->connection->ldapQuotaAttribute);
181
-		if(isset($ldapEntry[$attr])) {
182
-			$this->updateQuota($ldapEntry[$attr][0]);
183
-		} else {
184
-			if ($this->connection->ldapQuotaDefault !== '') {
185
-				$this->updateQuota();
186
-			}
187
-		}
188
-		unset($attr);
189
-
190
-		//Email
191
-		$attr = strtolower($this->connection->ldapEmailAttribute);
192
-		if(isset($ldapEntry[$attr])) {
193
-			$this->updateEmail($ldapEntry[$attr][0]);
194
-		}
195
-		unset($attr);
196
-
197
-		//displayName
198
-		$displayName = $displayName2 = '';
199
-		$attr = strtolower($this->connection->ldapUserDisplayName);
200
-		if(isset($ldapEntry[$attr])) {
201
-			$displayName = strval($ldapEntry[$attr][0]);
202
-		}
203
-		$attr = strtolower($this->connection->ldapUserDisplayName2);
204
-		if(isset($ldapEntry[$attr])) {
205
-			$displayName2 = strval($ldapEntry[$attr][0]);
206
-		}
207
-		if ($displayName !== '') {
208
-			$this->composeAndStoreDisplayName($displayName);
209
-			$this->access->cacheUserDisplayName(
210
-				$this->getUsername(),
211
-				$displayName,
212
-				$displayName2
213
-			);
214
-		}
215
-		unset($attr);
216
-
217
-		// LDAP Username, needed for s2s sharing
218
-		if(isset($ldapEntry['uid'])) {
219
-			$this->storeLDAPUserName($ldapEntry['uid'][0]);
220
-		} else if(isset($ldapEntry['samaccountname'])) {
221
-			$this->storeLDAPUserName($ldapEntry['samaccountname'][0]);
222
-		}
223
-
224
-		//homePath
225
-		if(strpos($this->connection->homeFolderNamingRule, 'attr:') === 0) {
226
-			$attr = strtolower(substr($this->connection->homeFolderNamingRule, strlen('attr:')));
227
-			if(isset($ldapEntry[$attr])) {
228
-				$this->access->cacheUserHome(
229
-					$this->getUsername(), $this->getHomePath($ldapEntry[$attr][0]));
230
-			}
231
-		}
232
-
233
-		//memberOf groups
234
-		$cacheKey = 'getMemberOf'.$this->getUsername();
235
-		$groups = false;
236
-		if(isset($ldapEntry['memberof'])) {
237
-			$groups = $ldapEntry['memberof'];
238
-		}
239
-		$this->connection->writeToCache($cacheKey, $groups);
240
-
241
-		//Avatar
242
-		$attrs = array('jpegphoto', 'thumbnailphoto');
243
-		foreach ($attrs as $attr)  {
244
-			if(isset($ldapEntry[$attr])) {
245
-				$this->avatarImage = $ldapEntry[$attr][0];
246
-				// the call to the method that saves the avatar in the file
247
-				// system must be postponed after the login. It is to ensure
248
-				// external mounts are mounted properly (e.g. with login
249
-				// credentials from the session).
250
-				\OCP\Util::connectHook('OC_User', 'post_login', $this, 'updateAvatarPostLogin');
251
-				break;
252
-			}
253
-		}
254
-	}
255
-
256
-	/**
257
-	 * @brief returns the LDAP DN of the user
258
-	 * @return string
259
-	 */
260
-	public function getDN() {
261
-		return $this->dn;
262
-	}
263
-
264
-	/**
265
-	 * @brief returns the Nextcloud internal username of the user
266
-	 * @return string
267
-	 */
268
-	public function getUsername() {
269
-		return $this->uid;
270
-	}
271
-
272
-	/**
273
-	 * returns the home directory of the user if specified by LDAP settings
274
-	 * @param string $valueFromLDAP
275
-	 * @return bool|string
276
-	 * @throws \Exception
277
-	 */
278
-	public function getHomePath($valueFromLDAP = null) {
279
-		$path = strval($valueFromLDAP);
280
-		$attr = null;
281
-
282
-		if (is_null($valueFromLDAP)
283
-		   && strpos($this->access->connection->homeFolderNamingRule, 'attr:') === 0
284
-		   && $this->access->connection->homeFolderNamingRule !== 'attr:')
285
-		{
286
-			$attr = substr($this->access->connection->homeFolderNamingRule, strlen('attr:'));
287
-			$homedir = $this->access->readAttribute(
288
-				$this->access->username2dn($this->getUsername()), $attr);
289
-			if ($homedir && isset($homedir[0])) {
290
-				$path = $homedir[0];
291
-			}
292
-		}
293
-
294
-		if ($path !== '') {
295
-			//if attribute's value is an absolute path take this, otherwise append it to data dir
296
-			//check for / at the beginning or pattern c:\ resp. c:/
297
-			if(   '/' !== $path[0]
298
-			   && !(3 < strlen($path) && ctype_alpha($path[0])
299
-			       && $path[1] === ':' && ('\\' === $path[2] || '/' === $path[2]))
300
-			) {
301
-				$path = $this->config->getSystemValue('datadirectory',
302
-						\OC::$SERVERROOT.'/data' ) . '/' . $path;
303
-			}
304
-			//we need it to store it in the DB as well in case a user gets
305
-			//deleted so we can clean up afterwards
306
-			$this->config->setUserValue(
307
-				$this->getUsername(), 'user_ldap', 'homePath', $path
308
-			);
309
-			return $path;
310
-		}
311
-
312
-		if(    !is_null($attr)
313
-			&& $this->config->getAppValue('user_ldap', 'enforce_home_folder_naming_rule', true)
314
-		) {
315
-			// a naming rule attribute is defined, but it doesn't exist for that LDAP user
316
-			throw new \Exception('Home dir attribute can\'t be read from LDAP for uid: ' . $this->getUsername());
317
-		}
318
-
319
-		//false will apply default behaviour as defined and done by OC_User
320
-		$this->config->setUserValue($this->getUsername(), 'user_ldap', 'homePath', '');
321
-		return false;
322
-	}
323
-
324
-	public function getMemberOfGroups() {
325
-		$cacheKey = 'getMemberOf'.$this->getUsername();
326
-		$memberOfGroups = $this->connection->getFromCache($cacheKey);
327
-		if(!is_null($memberOfGroups)) {
328
-			return $memberOfGroups;
329
-		}
330
-		$groupDNs = $this->access->readAttribute($this->getDN(), 'memberOf');
331
-		$this->connection->writeToCache($cacheKey, $groupDNs);
332
-		return $groupDNs;
333
-	}
334
-
335
-	/**
336
-	 * @brief reads the image from LDAP that shall be used as Avatar
337
-	 * @return string data (provided by LDAP) | false
338
-	 */
339
-	public function getAvatarImage() {
340
-		if(!is_null($this->avatarImage)) {
341
-			return $this->avatarImage;
342
-		}
343
-
344
-		$this->avatarImage = false;
345
-		$attributes = array('jpegPhoto', 'thumbnailPhoto');
346
-		foreach($attributes as $attribute) {
347
-			$result = $this->access->readAttribute($this->dn, $attribute);
348
-			if($result !== false && is_array($result) && isset($result[0])) {
349
-				$this->avatarImage = $result[0];
350
-				break;
351
-			}
352
-		}
353
-
354
-		return $this->avatarImage;
355
-	}
356
-
357
-	/**
358
-	 * @brief marks the user as having logged in at least once
359
-	 * @return null
360
-	 */
361
-	public function markLogin() {
362
-		$this->config->setUserValue(
363
-			$this->uid, 'user_ldap', self::USER_PREFKEY_FIRSTLOGIN, 1);
364
-	}
365
-
366
-	/**
367
-	 * @brief marks the time when user features like email have been updated
368
-	 * @return null
369
-	 */
370
-	public function markRefreshTime() {
371
-		$this->config->setUserValue(
372
-			$this->uid, 'user_ldap', self::USER_PREFKEY_LASTREFRESH, time());
373
-	}
374
-
375
-	/**
376
-	 * @brief checks whether user features needs to be updated again by
377
-	 * comparing the difference of time of the last refresh to now with the
378
-	 * desired interval
379
-	 * @return bool
380
-	 */
381
-	private function needsRefresh() {
382
-		$lastChecked = $this->config->getUserValue($this->uid, 'user_ldap',
383
-			self::USER_PREFKEY_LASTREFRESH, 0);
384
-
385
-		//TODO make interval configurable
386
-		if((time() - intval($lastChecked)) < 86400 ) {
387
-			return false;
388
-		}
389
-		return  true;
390
-	}
391
-
392
-	/**
393
-	 * Stores a key-value pair in relation to this user
394
-	 *
395
-	 * @param string $key
396
-	 * @param string $value
397
-	 */
398
-	private function store($key, $value) {
399
-		$this->config->setUserValue($this->uid, 'user_ldap', $key, $value);
400
-	}
401
-
402
-	/**
403
-	 * Composes the display name and stores it in the database. The final
404
-	 * display name is returned.
405
-	 *
406
-	 * @param string $displayName
407
-	 * @param string $displayName2
408
-	 * @returns string the effective display name
409
-	 */
410
-	public function composeAndStoreDisplayName($displayName, $displayName2 = '') {
411
-		$displayName2 = strval($displayName2);
412
-		if($displayName2 !== '') {
413
-			$displayName .= ' (' . $displayName2 . ')';
414
-		}
415
-		$this->store('displayName', $displayName);
416
-		return $displayName;
417
-	}
418
-
419
-	/**
420
-	 * Stores the LDAP Username in the Database
421
-	 * @param string $userName
422
-	 */
423
-	public function storeLDAPUserName($userName) {
424
-		$this->store('uid', $userName);
425
-	}
426
-
427
-	/**
428
-	 * @brief checks whether an update method specified by feature was run
429
-	 * already. If not, it will marked like this, because it is expected that
430
-	 * the method will be run, when false is returned.
431
-	 * @param string $feature email | quota | avatar (can be extended)
432
-	 * @return bool
433
-	 */
434
-	private function wasRefreshed($feature) {
435
-		if(isset($this->refreshedFeatures[$feature])) {
436
-			return true;
437
-		}
438
-		$this->refreshedFeatures[$feature] = 1;
439
-		return false;
440
-	}
441
-
442
-	/**
443
-	 * fetches the email from LDAP and stores it as Nextcloud user value
444
-	 * @param string $valueFromLDAP if known, to save an LDAP read request
445
-	 * @return null
446
-	 */
447
-	public function updateEmail($valueFromLDAP = null) {
448
-		if($this->wasRefreshed('email')) {
449
-			return;
450
-		}
451
-		$email = strval($valueFromLDAP);
452
-		if(is_null($valueFromLDAP)) {
453
-			$emailAttribute = $this->connection->ldapEmailAttribute;
454
-			if ($emailAttribute !== '') {
455
-				$aEmail = $this->access->readAttribute($this->dn, $emailAttribute);
456
-				if(is_array($aEmail) && (count($aEmail) > 0)) {
457
-					$email = strval($aEmail[0]);
458
-				}
459
-			}
460
-		}
461
-		if ($email !== '') {
462
-			$user = $this->userManager->get($this->uid);
463
-			if (!is_null($user)) {
464
-				$currentEmail = strval($user->getEMailAddress());
465
-				if ($currentEmail !== $email) {
466
-					$user->setEMailAddress($email);
467
-				}
468
-			}
469
-		}
470
-	}
471
-
472
-	/**
473
-	 * Overall process goes as follow:
474
-	 * 1. fetch the quota from LDAP and check if it's parseable with the "verifyQuotaValue" function
475
-	 * 2. if the value can't be fetched, is empty or not parseable, use the default LDAP quota
476
-	 * 3. if the default LDAP quota can't be parsed, use the Nextcloud's default quota (use 'default')
477
-	 * 4. check if the target user exists and set the quota for the user.
478
-	 *
479
-	 * In order to improve performance and prevent an unwanted extra LDAP call, the $valueFromLDAP
480
-	 * parameter can be passed with the value of the attribute. This value will be considered as the
481
-	 * quota for the user coming from the LDAP server (step 1 of the process) It can be useful to
482
-	 * fetch all the user's attributes in one call and use the fetched values in this function.
483
-	 * The expected value for that parameter is a string describing the quota for the user. Valid
484
-	 * values are 'none' (unlimited), 'default' (the Nextcloud's default quota), '1234' (quota in
485
-	 * bytes), '1234 MB' (quota in MB - check the \OC_Helper::computerFileSize method for more info)
486
-	 *
487
-	 * fetches the quota from LDAP and stores it as Nextcloud user value
488
-	 * @param string $valueFromLDAP the quota attribute's value can be passed,
489
-	 * to save the readAttribute request
490
-	 * @return null
491
-	 */
492
-	public function updateQuota($valueFromLDAP = null) {
493
-		if($this->wasRefreshed('quota')) {
494
-			return;
495
-		}
496
-
497
-		$quota = false;
498
-		if(is_null($valueFromLDAP)) {
499
-			$quotaAttribute = $this->connection->ldapQuotaAttribute;
500
-			if ($quotaAttribute !== '') {
501
-				$aQuota = $this->access->readAttribute($this->dn, $quotaAttribute);
502
-				if($aQuota && (count($aQuota) > 0)) {
503
-					if ($this->verifyQuotaValue($aQuota[0])) {
504
-						$quota = $aQuota[0];
505
-					} else {
506
-						$this->log->log('not suitable LDAP quota found for user ' . $this->uid . ': [' . $aQuota[0] . ']', \OCP\Util::WARN);
507
-					}
508
-				}
509
-			}
510
-		} else {
511
-			if ($this->verifyQuotaValue($valueFromLDAP)) {
512
-				$quota = $valueFromLDAP;
513
-			} else {
514
-				$this->log->log('not suitable LDAP quota found for user ' . $this->uid . ': [' . $valueFromLDAP . ']', \OCP\Util::WARN);
515
-			}
516
-		}
517
-
518
-		if ($quota === false) {
519
-			// quota not found using the LDAP attribute (or not parseable). Try the default quota
520
-			$defaultQuota = $this->connection->ldapQuotaDefault;
521
-			if ($this->verifyQuotaValue($defaultQuota)) {
522
-				$quota = $defaultQuota;
523
-			}
524
-		}
525
-
526
-		$targetUser = $this->userManager->get($this->uid);
527
-		if ($targetUser) {
528
-			if($quota !== false) {
529
-				$targetUser->setQuota($quota);
530
-			} else {
531
-				$this->log->log('not suitable default quota found for user ' . $this->uid . ': [' . $defaultQuota . ']', \OCP\Util::WARN);
532
-				$targetUser->setQuota('default');
533
-			}
534
-		} else {
535
-			$this->log->log('trying to set a quota for user ' . $this->uid . ' but the user is missing', \OCP\Util::ERROR);
536
-		}
537
-	}
538
-
539
-	private function verifyQuotaValue($quotaValue) {
540
-		return $quotaValue === 'none' || $quotaValue === 'default' || \OC_Helper::computerFileSize($quotaValue) !== false;
541
-	}
542
-
543
-	/**
544
-	 * called by a post_login hook to save the avatar picture
545
-	 *
546
-	 * @param array $params
547
-	 */
548
-	public function updateAvatarPostLogin($params) {
549
-		if(isset($params['uid']) && $params['uid'] === $this->getUsername()) {
550
-			$this->updateAvatar();
551
-		}
552
-	}
553
-
554
-	/**
555
-	 * @brief attempts to get an image from LDAP and sets it as Nextcloud avatar
556
-	 * @return null
557
-	 */
558
-	public function updateAvatar() {
559
-		if($this->wasRefreshed('avatar')) {
560
-			return;
561
-		}
562
-		$avatarImage = $this->getAvatarImage();
563
-		if($avatarImage === false) {
564
-			//not set, nothing left to do;
565
-			return;
566
-		}
567
-		$this->image->loadFromBase64(base64_encode($avatarImage));
568
-		$this->setOwnCloudAvatar();
569
-	}
570
-
571
-	/**
572
-	 * @brief sets an image as Nextcloud avatar
573
-	 * @return null
574
-	 */
575
-	private function setOwnCloudAvatar() {
576
-		if(!$this->image->valid()) {
577
-			$this->log->log('jpegPhoto data invalid for '.$this->dn, \OCP\Util::ERROR);
578
-			return;
579
-		}
580
-		//make sure it is a square and not bigger than 128x128
581
-		$size = min(array($this->image->width(), $this->image->height(), 128));
582
-		if(!$this->image->centerCrop($size)) {
583
-			$this->log->log('croping image for avatar failed for '.$this->dn, \OCP\Util::ERROR);
584
-			return;
585
-		}
586
-
587
-		if(!$this->fs->isLoaded()) {
588
-			$this->fs->setup($this->uid);
589
-		}
590
-
591
-		try {
592
-			$avatar = $this->avatarManager->getAvatar($this->uid);
593
-			$avatar->set($this->image);
594
-		} catch (\Exception $e) {
595
-			\OC::$server->getLogger()->notice(
596
-				'Could not set avatar for ' . $this->dn	. ', because: ' . $e->getMessage(),
597
-				['app' => 'user_ldap']);
598
-		}
599
-	}
600
-
601
-	/**
602
-	 * called by a post_login hook to handle password expiry
603
-	 *
604
-	 * @param array $params
605
-	 */
606
-	public function handlePasswordExpiry($params) {
607
-		$ppolicyDN = $this->connection->ldapDefaultPPolicyDN;
608
-		if (empty($ppolicyDN) || (intval($this->connection->turnOnPasswordChange) !== 1)) {
609
-			return;//password expiry handling disabled
610
-		}
611
-		$uid = $params['uid'];
612
-		if(isset($uid) && $uid === $this->getUsername()) {
613
-			//retrieve relevant user attributes
614
-			$result = $this->access->search('objectclass=*', $this->dn, ['pwdpolicysubentry', 'pwdgraceusetime', 'pwdreset', 'pwdchangedtime']);
124
+        if ($username === null) {
125
+            $log->log("uid for '$dn' must not be null!", Util::ERROR);
126
+            throw new \InvalidArgumentException('uid must not be null!');
127
+        } else if ($username === '') {
128
+            $log->log("uid for '$dn' must not be an empty string", Util::ERROR);
129
+            throw new \InvalidArgumentException('uid must not be an empty string!');
130
+        }
131
+
132
+        $this->access              = $access;
133
+        $this->connection          = $access->getConnection();
134
+        $this->config              = $config;
135
+        $this->fs                  = $fs;
136
+        $this->dn                  = $dn;
137
+        $this->uid                 = $username;
138
+        $this->image               = $image;
139
+        $this->log                 = $log;
140
+        $this->avatarManager       = $avatarManager;
141
+        $this->userManager         = $userManager;
142
+        $this->notificationManager = $notificationManager;
143
+
144
+        \OCP\Util::connectHook('OC_User', 'post_login', $this, 'handlePasswordExpiry');
145
+    }
146
+
147
+    /**
148
+     * @brief updates properties like email, quota or avatar provided by LDAP
149
+     * @return null
150
+     */
151
+    public function update() {
152
+        if(is_null($this->dn)) {
153
+            return null;
154
+        }
155
+
156
+        $hasLoggedIn = $this->config->getUserValue($this->uid, 'user_ldap',
157
+                self::USER_PREFKEY_FIRSTLOGIN, 0);
158
+
159
+        if($this->needsRefresh()) {
160
+            $this->updateEmail();
161
+            $this->updateQuota();
162
+            if($hasLoggedIn !== 0) {
163
+                //we do not need to try it, when the user has not been logged in
164
+                //before, because the file system will not be ready.
165
+                $this->updateAvatar();
166
+                //in order to get an avatar as soon as possible, mark the user
167
+                //as refreshed only when updating the avatar did happen
168
+                $this->markRefreshTime();
169
+            }
170
+        }
171
+    }
172
+
173
+    /**
174
+     * processes results from LDAP for attributes as returned by getAttributesToRead()
175
+     * @param array $ldapEntry the user entry as retrieved from LDAP
176
+     */
177
+    public function processAttributes($ldapEntry) {
178
+        $this->markRefreshTime();
179
+        //Quota
180
+        $attr = strtolower($this->connection->ldapQuotaAttribute);
181
+        if(isset($ldapEntry[$attr])) {
182
+            $this->updateQuota($ldapEntry[$attr][0]);
183
+        } else {
184
+            if ($this->connection->ldapQuotaDefault !== '') {
185
+                $this->updateQuota();
186
+            }
187
+        }
188
+        unset($attr);
189
+
190
+        //Email
191
+        $attr = strtolower($this->connection->ldapEmailAttribute);
192
+        if(isset($ldapEntry[$attr])) {
193
+            $this->updateEmail($ldapEntry[$attr][0]);
194
+        }
195
+        unset($attr);
196
+
197
+        //displayName
198
+        $displayName = $displayName2 = '';
199
+        $attr = strtolower($this->connection->ldapUserDisplayName);
200
+        if(isset($ldapEntry[$attr])) {
201
+            $displayName = strval($ldapEntry[$attr][0]);
202
+        }
203
+        $attr = strtolower($this->connection->ldapUserDisplayName2);
204
+        if(isset($ldapEntry[$attr])) {
205
+            $displayName2 = strval($ldapEntry[$attr][0]);
206
+        }
207
+        if ($displayName !== '') {
208
+            $this->composeAndStoreDisplayName($displayName);
209
+            $this->access->cacheUserDisplayName(
210
+                $this->getUsername(),
211
+                $displayName,
212
+                $displayName2
213
+            );
214
+        }
215
+        unset($attr);
216
+
217
+        // LDAP Username, needed for s2s sharing
218
+        if(isset($ldapEntry['uid'])) {
219
+            $this->storeLDAPUserName($ldapEntry['uid'][0]);
220
+        } else if(isset($ldapEntry['samaccountname'])) {
221
+            $this->storeLDAPUserName($ldapEntry['samaccountname'][0]);
222
+        }
223
+
224
+        //homePath
225
+        if(strpos($this->connection->homeFolderNamingRule, 'attr:') === 0) {
226
+            $attr = strtolower(substr($this->connection->homeFolderNamingRule, strlen('attr:')));
227
+            if(isset($ldapEntry[$attr])) {
228
+                $this->access->cacheUserHome(
229
+                    $this->getUsername(), $this->getHomePath($ldapEntry[$attr][0]));
230
+            }
231
+        }
232
+
233
+        //memberOf groups
234
+        $cacheKey = 'getMemberOf'.$this->getUsername();
235
+        $groups = false;
236
+        if(isset($ldapEntry['memberof'])) {
237
+            $groups = $ldapEntry['memberof'];
238
+        }
239
+        $this->connection->writeToCache($cacheKey, $groups);
240
+
241
+        //Avatar
242
+        $attrs = array('jpegphoto', 'thumbnailphoto');
243
+        foreach ($attrs as $attr)  {
244
+            if(isset($ldapEntry[$attr])) {
245
+                $this->avatarImage = $ldapEntry[$attr][0];
246
+                // the call to the method that saves the avatar in the file
247
+                // system must be postponed after the login. It is to ensure
248
+                // external mounts are mounted properly (e.g. with login
249
+                // credentials from the session).
250
+                \OCP\Util::connectHook('OC_User', 'post_login', $this, 'updateAvatarPostLogin');
251
+                break;
252
+            }
253
+        }
254
+    }
255
+
256
+    /**
257
+     * @brief returns the LDAP DN of the user
258
+     * @return string
259
+     */
260
+    public function getDN() {
261
+        return $this->dn;
262
+    }
263
+
264
+    /**
265
+     * @brief returns the Nextcloud internal username of the user
266
+     * @return string
267
+     */
268
+    public function getUsername() {
269
+        return $this->uid;
270
+    }
271
+
272
+    /**
273
+     * returns the home directory of the user if specified by LDAP settings
274
+     * @param string $valueFromLDAP
275
+     * @return bool|string
276
+     * @throws \Exception
277
+     */
278
+    public function getHomePath($valueFromLDAP = null) {
279
+        $path = strval($valueFromLDAP);
280
+        $attr = null;
281
+
282
+        if (is_null($valueFromLDAP)
283
+           && strpos($this->access->connection->homeFolderNamingRule, 'attr:') === 0
284
+           && $this->access->connection->homeFolderNamingRule !== 'attr:')
285
+        {
286
+            $attr = substr($this->access->connection->homeFolderNamingRule, strlen('attr:'));
287
+            $homedir = $this->access->readAttribute(
288
+                $this->access->username2dn($this->getUsername()), $attr);
289
+            if ($homedir && isset($homedir[0])) {
290
+                $path = $homedir[0];
291
+            }
292
+        }
293
+
294
+        if ($path !== '') {
295
+            //if attribute's value is an absolute path take this, otherwise append it to data dir
296
+            //check for / at the beginning or pattern c:\ resp. c:/
297
+            if(   '/' !== $path[0]
298
+               && !(3 < strlen($path) && ctype_alpha($path[0])
299
+                   && $path[1] === ':' && ('\\' === $path[2] || '/' === $path[2]))
300
+            ) {
301
+                $path = $this->config->getSystemValue('datadirectory',
302
+                        \OC::$SERVERROOT.'/data' ) . '/' . $path;
303
+            }
304
+            //we need it to store it in the DB as well in case a user gets
305
+            //deleted so we can clean up afterwards
306
+            $this->config->setUserValue(
307
+                $this->getUsername(), 'user_ldap', 'homePath', $path
308
+            );
309
+            return $path;
310
+        }
311
+
312
+        if(    !is_null($attr)
313
+            && $this->config->getAppValue('user_ldap', 'enforce_home_folder_naming_rule', true)
314
+        ) {
315
+            // a naming rule attribute is defined, but it doesn't exist for that LDAP user
316
+            throw new \Exception('Home dir attribute can\'t be read from LDAP for uid: ' . $this->getUsername());
317
+        }
318
+
319
+        //false will apply default behaviour as defined and done by OC_User
320
+        $this->config->setUserValue($this->getUsername(), 'user_ldap', 'homePath', '');
321
+        return false;
322
+    }
323
+
324
+    public function getMemberOfGroups() {
325
+        $cacheKey = 'getMemberOf'.$this->getUsername();
326
+        $memberOfGroups = $this->connection->getFromCache($cacheKey);
327
+        if(!is_null($memberOfGroups)) {
328
+            return $memberOfGroups;
329
+        }
330
+        $groupDNs = $this->access->readAttribute($this->getDN(), 'memberOf');
331
+        $this->connection->writeToCache($cacheKey, $groupDNs);
332
+        return $groupDNs;
333
+    }
334
+
335
+    /**
336
+     * @brief reads the image from LDAP that shall be used as Avatar
337
+     * @return string data (provided by LDAP) | false
338
+     */
339
+    public function getAvatarImage() {
340
+        if(!is_null($this->avatarImage)) {
341
+            return $this->avatarImage;
342
+        }
343
+
344
+        $this->avatarImage = false;
345
+        $attributes = array('jpegPhoto', 'thumbnailPhoto');
346
+        foreach($attributes as $attribute) {
347
+            $result = $this->access->readAttribute($this->dn, $attribute);
348
+            if($result !== false && is_array($result) && isset($result[0])) {
349
+                $this->avatarImage = $result[0];
350
+                break;
351
+            }
352
+        }
353
+
354
+        return $this->avatarImage;
355
+    }
356
+
357
+    /**
358
+     * @brief marks the user as having logged in at least once
359
+     * @return null
360
+     */
361
+    public function markLogin() {
362
+        $this->config->setUserValue(
363
+            $this->uid, 'user_ldap', self::USER_PREFKEY_FIRSTLOGIN, 1);
364
+    }
365
+
366
+    /**
367
+     * @brief marks the time when user features like email have been updated
368
+     * @return null
369
+     */
370
+    public function markRefreshTime() {
371
+        $this->config->setUserValue(
372
+            $this->uid, 'user_ldap', self::USER_PREFKEY_LASTREFRESH, time());
373
+    }
374
+
375
+    /**
376
+     * @brief checks whether user features needs to be updated again by
377
+     * comparing the difference of time of the last refresh to now with the
378
+     * desired interval
379
+     * @return bool
380
+     */
381
+    private function needsRefresh() {
382
+        $lastChecked = $this->config->getUserValue($this->uid, 'user_ldap',
383
+            self::USER_PREFKEY_LASTREFRESH, 0);
384
+
385
+        //TODO make interval configurable
386
+        if((time() - intval($lastChecked)) < 86400 ) {
387
+            return false;
388
+        }
389
+        return  true;
390
+    }
391
+
392
+    /**
393
+     * Stores a key-value pair in relation to this user
394
+     *
395
+     * @param string $key
396
+     * @param string $value
397
+     */
398
+    private function store($key, $value) {
399
+        $this->config->setUserValue($this->uid, 'user_ldap', $key, $value);
400
+    }
401
+
402
+    /**
403
+     * Composes the display name and stores it in the database. The final
404
+     * display name is returned.
405
+     *
406
+     * @param string $displayName
407
+     * @param string $displayName2
408
+     * @returns string the effective display name
409
+     */
410
+    public function composeAndStoreDisplayName($displayName, $displayName2 = '') {
411
+        $displayName2 = strval($displayName2);
412
+        if($displayName2 !== '') {
413
+            $displayName .= ' (' . $displayName2 . ')';
414
+        }
415
+        $this->store('displayName', $displayName);
416
+        return $displayName;
417
+    }
418
+
419
+    /**
420
+     * Stores the LDAP Username in the Database
421
+     * @param string $userName
422
+     */
423
+    public function storeLDAPUserName($userName) {
424
+        $this->store('uid', $userName);
425
+    }
426
+
427
+    /**
428
+     * @brief checks whether an update method specified by feature was run
429
+     * already. If not, it will marked like this, because it is expected that
430
+     * the method will be run, when false is returned.
431
+     * @param string $feature email | quota | avatar (can be extended)
432
+     * @return bool
433
+     */
434
+    private function wasRefreshed($feature) {
435
+        if(isset($this->refreshedFeatures[$feature])) {
436
+            return true;
437
+        }
438
+        $this->refreshedFeatures[$feature] = 1;
439
+        return false;
440
+    }
441
+
442
+    /**
443
+     * fetches the email from LDAP and stores it as Nextcloud user value
444
+     * @param string $valueFromLDAP if known, to save an LDAP read request
445
+     * @return null
446
+     */
447
+    public function updateEmail($valueFromLDAP = null) {
448
+        if($this->wasRefreshed('email')) {
449
+            return;
450
+        }
451
+        $email = strval($valueFromLDAP);
452
+        if(is_null($valueFromLDAP)) {
453
+            $emailAttribute = $this->connection->ldapEmailAttribute;
454
+            if ($emailAttribute !== '') {
455
+                $aEmail = $this->access->readAttribute($this->dn, $emailAttribute);
456
+                if(is_array($aEmail) && (count($aEmail) > 0)) {
457
+                    $email = strval($aEmail[0]);
458
+                }
459
+            }
460
+        }
461
+        if ($email !== '') {
462
+            $user = $this->userManager->get($this->uid);
463
+            if (!is_null($user)) {
464
+                $currentEmail = strval($user->getEMailAddress());
465
+                if ($currentEmail !== $email) {
466
+                    $user->setEMailAddress($email);
467
+                }
468
+            }
469
+        }
470
+    }
471
+
472
+    /**
473
+     * Overall process goes as follow:
474
+     * 1. fetch the quota from LDAP and check if it's parseable with the "verifyQuotaValue" function
475
+     * 2. if the value can't be fetched, is empty or not parseable, use the default LDAP quota
476
+     * 3. if the default LDAP quota can't be parsed, use the Nextcloud's default quota (use 'default')
477
+     * 4. check if the target user exists and set the quota for the user.
478
+     *
479
+     * In order to improve performance and prevent an unwanted extra LDAP call, the $valueFromLDAP
480
+     * parameter can be passed with the value of the attribute. This value will be considered as the
481
+     * quota for the user coming from the LDAP server (step 1 of the process) It can be useful to
482
+     * fetch all the user's attributes in one call and use the fetched values in this function.
483
+     * The expected value for that parameter is a string describing the quota for the user. Valid
484
+     * values are 'none' (unlimited), 'default' (the Nextcloud's default quota), '1234' (quota in
485
+     * bytes), '1234 MB' (quota in MB - check the \OC_Helper::computerFileSize method for more info)
486
+     *
487
+     * fetches the quota from LDAP and stores it as Nextcloud user value
488
+     * @param string $valueFromLDAP the quota attribute's value can be passed,
489
+     * to save the readAttribute request
490
+     * @return null
491
+     */
492
+    public function updateQuota($valueFromLDAP = null) {
493
+        if($this->wasRefreshed('quota')) {
494
+            return;
495
+        }
496
+
497
+        $quota = false;
498
+        if(is_null($valueFromLDAP)) {
499
+            $quotaAttribute = $this->connection->ldapQuotaAttribute;
500
+            if ($quotaAttribute !== '') {
501
+                $aQuota = $this->access->readAttribute($this->dn, $quotaAttribute);
502
+                if($aQuota && (count($aQuota) > 0)) {
503
+                    if ($this->verifyQuotaValue($aQuota[0])) {
504
+                        $quota = $aQuota[0];
505
+                    } else {
506
+                        $this->log->log('not suitable LDAP quota found for user ' . $this->uid . ': [' . $aQuota[0] . ']', \OCP\Util::WARN);
507
+                    }
508
+                }
509
+            }
510
+        } else {
511
+            if ($this->verifyQuotaValue($valueFromLDAP)) {
512
+                $quota = $valueFromLDAP;
513
+            } else {
514
+                $this->log->log('not suitable LDAP quota found for user ' . $this->uid . ': [' . $valueFromLDAP . ']', \OCP\Util::WARN);
515
+            }
516
+        }
517
+
518
+        if ($quota === false) {
519
+            // quota not found using the LDAP attribute (or not parseable). Try the default quota
520
+            $defaultQuota = $this->connection->ldapQuotaDefault;
521
+            if ($this->verifyQuotaValue($defaultQuota)) {
522
+                $quota = $defaultQuota;
523
+            }
524
+        }
525
+
526
+        $targetUser = $this->userManager->get($this->uid);
527
+        if ($targetUser) {
528
+            if($quota !== false) {
529
+                $targetUser->setQuota($quota);
530
+            } else {
531
+                $this->log->log('not suitable default quota found for user ' . $this->uid . ': [' . $defaultQuota . ']', \OCP\Util::WARN);
532
+                $targetUser->setQuota('default');
533
+            }
534
+        } else {
535
+            $this->log->log('trying to set a quota for user ' . $this->uid . ' but the user is missing', \OCP\Util::ERROR);
536
+        }
537
+    }
538
+
539
+    private function verifyQuotaValue($quotaValue) {
540
+        return $quotaValue === 'none' || $quotaValue === 'default' || \OC_Helper::computerFileSize($quotaValue) !== false;
541
+    }
542
+
543
+    /**
544
+     * called by a post_login hook to save the avatar picture
545
+     *
546
+     * @param array $params
547
+     */
548
+    public function updateAvatarPostLogin($params) {
549
+        if(isset($params['uid']) && $params['uid'] === $this->getUsername()) {
550
+            $this->updateAvatar();
551
+        }
552
+    }
553
+
554
+    /**
555
+     * @brief attempts to get an image from LDAP and sets it as Nextcloud avatar
556
+     * @return null
557
+     */
558
+    public function updateAvatar() {
559
+        if($this->wasRefreshed('avatar')) {
560
+            return;
561
+        }
562
+        $avatarImage = $this->getAvatarImage();
563
+        if($avatarImage === false) {
564
+            //not set, nothing left to do;
565
+            return;
566
+        }
567
+        $this->image->loadFromBase64(base64_encode($avatarImage));
568
+        $this->setOwnCloudAvatar();
569
+    }
570
+
571
+    /**
572
+     * @brief sets an image as Nextcloud avatar
573
+     * @return null
574
+     */
575
+    private function setOwnCloudAvatar() {
576
+        if(!$this->image->valid()) {
577
+            $this->log->log('jpegPhoto data invalid for '.$this->dn, \OCP\Util::ERROR);
578
+            return;
579
+        }
580
+        //make sure it is a square and not bigger than 128x128
581
+        $size = min(array($this->image->width(), $this->image->height(), 128));
582
+        if(!$this->image->centerCrop($size)) {
583
+            $this->log->log('croping image for avatar failed for '.$this->dn, \OCP\Util::ERROR);
584
+            return;
585
+        }
586
+
587
+        if(!$this->fs->isLoaded()) {
588
+            $this->fs->setup($this->uid);
589
+        }
590
+
591
+        try {
592
+            $avatar = $this->avatarManager->getAvatar($this->uid);
593
+            $avatar->set($this->image);
594
+        } catch (\Exception $e) {
595
+            \OC::$server->getLogger()->notice(
596
+                'Could not set avatar for ' . $this->dn	. ', because: ' . $e->getMessage(),
597
+                ['app' => 'user_ldap']);
598
+        }
599
+    }
600
+
601
+    /**
602
+     * called by a post_login hook to handle password expiry
603
+     *
604
+     * @param array $params
605
+     */
606
+    public function handlePasswordExpiry($params) {
607
+        $ppolicyDN = $this->connection->ldapDefaultPPolicyDN;
608
+        if (empty($ppolicyDN) || (intval($this->connection->turnOnPasswordChange) !== 1)) {
609
+            return;//password expiry handling disabled
610
+        }
611
+        $uid = $params['uid'];
612
+        if(isset($uid) && $uid === $this->getUsername()) {
613
+            //retrieve relevant user attributes
614
+            $result = $this->access->search('objectclass=*', $this->dn, ['pwdpolicysubentry', 'pwdgraceusetime', 'pwdreset', 'pwdchangedtime']);
615 615
 			
616
-			if(array_key_exists('pwdpolicysubentry', $result[0])) {
617
-				$pwdPolicySubentry = $result[0]['pwdpolicysubentry'];
618
-				if($pwdPolicySubentry && (count($pwdPolicySubentry) > 0)){
619
-					$ppolicyDN = $pwdPolicySubentry[0];//custom ppolicy DN
620
-				}
621
-			}
616
+            if(array_key_exists('pwdpolicysubentry', $result[0])) {
617
+                $pwdPolicySubentry = $result[0]['pwdpolicysubentry'];
618
+                if($pwdPolicySubentry && (count($pwdPolicySubentry) > 0)){
619
+                    $ppolicyDN = $pwdPolicySubentry[0];//custom ppolicy DN
620
+                }
621
+            }
622 622
 			
623
-			$pwdGraceUseTime = array_key_exists('pwdgraceusetime', $result[0]) ? $result[0]['pwdgraceusetime'] : null;
624
-			$pwdReset = array_key_exists('pwdreset', $result[0]) ? $result[0]['pwdreset'] : null;
625
-			$pwdChangedTime = array_key_exists('pwdchangedtime', $result[0]) ? $result[0]['pwdchangedtime'] : null;
623
+            $pwdGraceUseTime = array_key_exists('pwdgraceusetime', $result[0]) ? $result[0]['pwdgraceusetime'] : null;
624
+            $pwdReset = array_key_exists('pwdreset', $result[0]) ? $result[0]['pwdreset'] : null;
625
+            $pwdChangedTime = array_key_exists('pwdchangedtime', $result[0]) ? $result[0]['pwdchangedtime'] : null;
626 626
 			
627
-			//retrieve relevant password policy attributes
628
-			$cacheKey = 'ppolicyAttributes' . $ppolicyDN;
629
-			$result = $this->connection->getFromCache($cacheKey);
630
-			if(is_null($result)) {
631
-				$result = $this->access->search('objectclass=*', $ppolicyDN, ['pwdgraceauthnlimit', 'pwdmaxage', 'pwdexpirewarning']);
632
-				$this->connection->writeToCache($cacheKey, $result);
633
-			}
627
+            //retrieve relevant password policy attributes
628
+            $cacheKey = 'ppolicyAttributes' . $ppolicyDN;
629
+            $result = $this->connection->getFromCache($cacheKey);
630
+            if(is_null($result)) {
631
+                $result = $this->access->search('objectclass=*', $ppolicyDN, ['pwdgraceauthnlimit', 'pwdmaxage', 'pwdexpirewarning']);
632
+                $this->connection->writeToCache($cacheKey, $result);
633
+            }
634 634
 			
635
-			$pwdGraceAuthNLimit = array_key_exists('pwdgraceauthnlimit', $result[0]) ? $result[0]['pwdgraceauthnlimit'] : null;
636
-			$pwdMaxAge = array_key_exists('pwdmaxage', $result[0]) ? $result[0]['pwdmaxage'] : null;
637
-			$pwdExpireWarning = array_key_exists('pwdexpirewarning', $result[0]) ? $result[0]['pwdexpirewarning'] : null;
635
+            $pwdGraceAuthNLimit = array_key_exists('pwdgraceauthnlimit', $result[0]) ? $result[0]['pwdgraceauthnlimit'] : null;
636
+            $pwdMaxAge = array_key_exists('pwdmaxage', $result[0]) ? $result[0]['pwdmaxage'] : null;
637
+            $pwdExpireWarning = array_key_exists('pwdexpirewarning', $result[0]) ? $result[0]['pwdexpirewarning'] : null;
638 638
 			
639
-			//handle grace login
640
-			$pwdGraceUseTimeCount = count($pwdGraceUseTime);
641
-			if($pwdGraceUseTime && $pwdGraceUseTimeCount > 0) { //was this a grace login?
642
-				if($pwdGraceAuthNLimit 
643
-					&& (count($pwdGraceAuthNLimit) > 0)
644
-					&&($pwdGraceUseTimeCount < intval($pwdGraceAuthNLimit[0]))) { //at least one more grace login available?
645
-					$this->config->setUserValue($uid, 'user_ldap', 'needsPasswordReset', 'true');
646
-					header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute(
647
-					'user_ldap.renewPassword.showRenewPasswordForm', array('user' => $uid)));
648
-				} else { //no more grace login available
649
-					header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute(
650
-					'user_ldap.renewPassword.showLoginFormInvalidPassword', array('user' => $uid)));
651
-				}
652
-				exit();
653
-			}
654
-			//handle pwdReset attribute
655
-			if($pwdReset && (count($pwdReset) > 0) && $pwdReset[0] === 'TRUE') { //user must change his password
656
-				$this->config->setUserValue($uid, 'user_ldap', 'needsPasswordReset', 'true');
657
-				header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute(
658
-				'user_ldap.renewPassword.showRenewPasswordForm', array('user' => $uid)));
659
-				exit();
660
-			}
661
-			//handle password expiry warning
662
-			if($pwdChangedTime && (count($pwdChangedTime) > 0)) {
663
-				if($pwdMaxAge && (count($pwdMaxAge) > 0)
664
-					&& $pwdExpireWarning && (count($pwdExpireWarning) > 0)) {
665
-					$pwdMaxAgeInt = intval($pwdMaxAge[0]);
666
-					$pwdExpireWarningInt = intval($pwdExpireWarning[0]);
667
-					if($pwdMaxAgeInt > 0 && $pwdExpireWarningInt > 0){
668
-						$pwdChangedTimeDt = \DateTime::createFromFormat('YmdHisZ', $pwdChangedTime[0]);
669
-						$pwdChangedTimeDt->add(new \DateInterval('PT'.$pwdMaxAgeInt.'S'));
670
-						$currentDateTime = new \DateTime();
671
-						$secondsToExpiry = $pwdChangedTimeDt->getTimestamp() - $currentDateTime->getTimestamp();
672
-						if($secondsToExpiry <= $pwdExpireWarningInt) {
673
-							//remove last password expiry warning if any
674
-							$notification = $this->notificationManager->createNotification();
675
-							$notification->setApp('user_ldap')
676
-								->setUser($uid)
677
-								->setObject('pwd_exp_warn', $uid)
678
-							;
679
-							$this->notificationManager->markProcessed($notification);
680
-							//create new password expiry warning
681
-							$notification = $this->notificationManager->createNotification();
682
-							$notification->setApp('user_ldap')
683
-								->setUser($uid)
684
-								->setDateTime($currentDateTime)
685
-								->setObject('pwd_exp_warn', $uid) 
686
-								->setSubject('pwd_exp_warn_days', [(int) ceil($secondsToExpiry / 60 / 60 / 24)])
687
-							;
688
-							$this->notificationManager->notify($notification);
689
-						}
690
-					}
691
-				}
692
-			}
693
-		}
694
-	}
639
+            //handle grace login
640
+            $pwdGraceUseTimeCount = count($pwdGraceUseTime);
641
+            if($pwdGraceUseTime && $pwdGraceUseTimeCount > 0) { //was this a grace login?
642
+                if($pwdGraceAuthNLimit 
643
+                    && (count($pwdGraceAuthNLimit) > 0)
644
+                    &&($pwdGraceUseTimeCount < intval($pwdGraceAuthNLimit[0]))) { //at least one more grace login available?
645
+                    $this->config->setUserValue($uid, 'user_ldap', 'needsPasswordReset', 'true');
646
+                    header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute(
647
+                    'user_ldap.renewPassword.showRenewPasswordForm', array('user' => $uid)));
648
+                } else { //no more grace login available
649
+                    header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute(
650
+                    'user_ldap.renewPassword.showLoginFormInvalidPassword', array('user' => $uid)));
651
+                }
652
+                exit();
653
+            }
654
+            //handle pwdReset attribute
655
+            if($pwdReset && (count($pwdReset) > 0) && $pwdReset[0] === 'TRUE') { //user must change his password
656
+                $this->config->setUserValue($uid, 'user_ldap', 'needsPasswordReset', 'true');
657
+                header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute(
658
+                'user_ldap.renewPassword.showRenewPasswordForm', array('user' => $uid)));
659
+                exit();
660
+            }
661
+            //handle password expiry warning
662
+            if($pwdChangedTime && (count($pwdChangedTime) > 0)) {
663
+                if($pwdMaxAge && (count($pwdMaxAge) > 0)
664
+                    && $pwdExpireWarning && (count($pwdExpireWarning) > 0)) {
665
+                    $pwdMaxAgeInt = intval($pwdMaxAge[0]);
666
+                    $pwdExpireWarningInt = intval($pwdExpireWarning[0]);
667
+                    if($pwdMaxAgeInt > 0 && $pwdExpireWarningInt > 0){
668
+                        $pwdChangedTimeDt = \DateTime::createFromFormat('YmdHisZ', $pwdChangedTime[0]);
669
+                        $pwdChangedTimeDt->add(new \DateInterval('PT'.$pwdMaxAgeInt.'S'));
670
+                        $currentDateTime = new \DateTime();
671
+                        $secondsToExpiry = $pwdChangedTimeDt->getTimestamp() - $currentDateTime->getTimestamp();
672
+                        if($secondsToExpiry <= $pwdExpireWarningInt) {
673
+                            //remove last password expiry warning if any
674
+                            $notification = $this->notificationManager->createNotification();
675
+                            $notification->setApp('user_ldap')
676
+                                ->setUser($uid)
677
+                                ->setObject('pwd_exp_warn', $uid)
678
+                            ;
679
+                            $this->notificationManager->markProcessed($notification);
680
+                            //create new password expiry warning
681
+                            $notification = $this->notificationManager->createNotification();
682
+                            $notification->setApp('user_ldap')
683
+                                ->setUser($uid)
684
+                                ->setDateTime($currentDateTime)
685
+                                ->setObject('pwd_exp_warn', $uid) 
686
+                                ->setSubject('pwd_exp_warn_days', [(int) ceil($secondsToExpiry / 60 / 60 / 24)])
687
+                            ;
688
+                            $this->notificationManager->notify($notification);
689
+                        }
690
+                    }
691
+                }
692
+            }
693
+        }
694
+    }
695 695
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/Notification/Notifier.php 1 patch
Indentation   +43 added lines, -43 removed lines patch added patch discarded remove patch
@@ -32,52 +32,52 @@
 block discarded – undo
32 32
 
33 33
 class Notifier implements INotifier {
34 34
 
35
-	/** @var IFactory */
36
-	protected $l10nFactory;
35
+    /** @var IFactory */
36
+    protected $l10nFactory;
37 37
 
38
-	/**
39
-	 * @param IFactory $l10nFactory
40
-	 */
41
-	 public function __construct(\OCP\L10N\IFactory $l10nFactory) {
42
-		$this->l10nFactory = $l10nFactory;
43
-	}
38
+    /**
39
+     * @param IFactory $l10nFactory
40
+     */
41
+        public function __construct(\OCP\L10N\IFactory $l10nFactory) {
42
+        $this->l10nFactory = $l10nFactory;
43
+    }
44 44
 
45
-	/**
46
-	 * @param INotification $notification
47
-	 * @param string $languageCode The code of the language that should be used to prepare the notification
48
-	 * @return INotification
49
-	 * @throws \InvalidArgumentException When the notification was not prepared by a notifier
50
-	 */
51
-	public function prepare(INotification $notification, $languageCode) {
52
-		if ($notification->getApp() !== 'user_ldap') {
53
-			// Not my app => throw
54
-			throw new \InvalidArgumentException();
55
-		}
45
+    /**
46
+     * @param INotification $notification
47
+     * @param string $languageCode The code of the language that should be used to prepare the notification
48
+     * @return INotification
49
+     * @throws \InvalidArgumentException When the notification was not prepared by a notifier
50
+     */
51
+    public function prepare(INotification $notification, $languageCode) {
52
+        if ($notification->getApp() !== 'user_ldap') {
53
+            // Not my app => throw
54
+            throw new \InvalidArgumentException();
55
+        }
56 56
 
57
-		// Read the language from the notification
58
-		$l = $this->l10nFactory->get('user_ldap', $languageCode);
57
+        // Read the language from the notification
58
+        $l = $this->l10nFactory->get('user_ldap', $languageCode);
59 59
 
60
-		switch ($notification->getSubject()) {
61
-			// Deal with known subjects
62
-			case 'pwd_exp_warn_days':
63
-				$params = $notification->getSubjectParameters();
64
-				$days = (int) $params[0];
65
-				if ($days === 2) {
66
-					$notification->setParsedSubject($l->t('Your password will expire tomorrow.', $days));
67
-				} else if ($days === 1) {
68
-					$notification->setParsedSubject($l->t('Your password will expire today.', $days));
69
-				} else {
70
-					$notification->setParsedSubject($l->n(
71
-						'Your password will expire within %n day.',
72
-						'Your password will expire within %n days.',
73
-						$days
74
-					));
75
-				}
76
-				return $notification;
60
+        switch ($notification->getSubject()) {
61
+            // Deal with known subjects
62
+            case 'pwd_exp_warn_days':
63
+                $params = $notification->getSubjectParameters();
64
+                $days = (int) $params[0];
65
+                if ($days === 2) {
66
+                    $notification->setParsedSubject($l->t('Your password will expire tomorrow.', $days));
67
+                } else if ($days === 1) {
68
+                    $notification->setParsedSubject($l->t('Your password will expire today.', $days));
69
+                } else {
70
+                    $notification->setParsedSubject($l->n(
71
+                        'Your password will expire within %n day.',
72
+                        'Your password will expire within %n days.',
73
+                        $days
74
+                    ));
75
+                }
76
+                return $notification;
77 77
 
78
-			default:
79
-				// Unknown subject => Unknown notification => throw
80
-				throw new \InvalidArgumentException();
81
-		}
82
-	}
78
+            default:
79
+                // Unknown subject => Unknown notification => throw
80
+                throw new \InvalidArgumentException();
81
+        }
82
+    }
83 83
 }
Please login to merge, or discard this patch.