Completed
Pull Request — master (#4244)
by Lukas
14:28
created
settings/Controller/UsersController.php 3 patches
Unused Use Statements   -2 removed lines patch added patch discarded remove patch
@@ -34,11 +34,9 @@
 block discarded – undo
34 34
 use OC\AppFramework\Http;
35 35
 use OC\ForbiddenException;
36 36
 use OC\Mail\EMailTemplate;
37
-use OC\User\User;
38 37
 use OCP\App\IAppManager;
39 38
 use OCP\AppFramework\Controller;
40 39
 use OCP\AppFramework\Http\DataResponse;
41
-use OCP\AppFramework\Http\TemplateResponse;
42 40
 use OCP\IConfig;
43 41
 use OCP\IGroupManager;
44 42
 use OCP\IL10N;
Please login to merge, or discard this patch.
Spacing   +47 added lines, -47 removed lines patch added patch discarded remove patch
@@ -156,7 +156,7 @@  discard block
 block discarded – undo
156 156
 
157 157
 		// check for encryption state - TODO see formatUserForIndex
158 158
 		$this->isEncryptionAppEnabled = $appManager->isEnabledForUser('encryption');
159
-		if($this->isEncryptionAppEnabled) {
159
+		if ($this->isEncryptionAppEnabled) {
160 160
 			// putting this directly in empty is possible in PHP 5.5+
161 161
 			$result = $config->getAppValue('encryption', 'recoveryAdminEnabled', 0);
162 162
 			$this->isRestoreEnabled = !empty($result);
@@ -196,7 +196,7 @@  discard block
 block discarded – undo
196 196
 		}
197 197
 
198 198
 		$subAdminGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($user);
199
-		foreach($subAdminGroups as $key => $subAdminGroup) {
199
+		foreach ($subAdminGroups as $key => $subAdminGroup) {
200 200
 			$subAdminGroups[$key] = $subAdminGroup->getGID();
201 201
 		}
202 202
 
@@ -253,16 +253,16 @@  discard block
 block discarded – undo
253 253
 	 */
254 254
 	public function index($offset = 0, $limit = 10, $gid = '', $pattern = '', $backend = '') {
255 255
 		// FIXME: The JS sends the group '_everyone' instead of no GID for the "all users" group.
256
-		if($gid === '_everyone') {
256
+		if ($gid === '_everyone') {
257 257
 			$gid = '';
258 258
 		}
259 259
 
260 260
 		// Remove backends
261
-		if(!empty($backend)) {
261
+		if (!empty($backend)) {
262 262
 			$activeBackends = $this->userManager->getBackends();
263 263
 			$this->userManager->clearBackends();
264
-			foreach($activeBackends as $singleActiveBackend) {
265
-				if($backend === get_class($singleActiveBackend)) {
264
+			foreach ($activeBackends as $singleActiveBackend) {
265
+				if ($backend === get_class($singleActiveBackend)) {
266 266
 					$this->userManager->registerBackend($singleActiveBackend);
267 267
 					break;
268 268
 				}
@@ -272,7 +272,7 @@  discard block
 block discarded – undo
272 272
 		$users = [];
273 273
 		if ($this->isAdmin) {
274 274
 
275
-			if($gid !== '') {
275
+			if ($gid !== '') {
276 276
 				$batch = $this->getUsersForUID($this->groupManager->displayNamesInGroup($gid, $pattern, $limit, $offset));
277 277
 			} else {
278 278
 				$batch = $this->userManager->search($pattern, $limit, $offset);
@@ -292,17 +292,17 @@  discard block
 block discarded – undo
292 292
 			$subAdminOfGroups = $gids;
293 293
 
294 294
 			// Set the $gid parameter to an empty value if the subadmin has no rights to access a specific group
295
-			if($gid !== '' && !in_array($gid, $subAdminOfGroups)) {
295
+			if ($gid !== '' && !in_array($gid, $subAdminOfGroups)) {
296 296
 				$gid = '';
297 297
 			}
298 298
 
299 299
 			// Batch all groups the user is subadmin of when a group is specified
300 300
 			$batch = [];
301
-			if($gid === '') {
302
-				foreach($subAdminOfGroups as $group) {
301
+			if ($gid === '') {
302
+				foreach ($subAdminOfGroups as $group) {
303 303
 					$groupUsers = $this->groupManager->displayNamesInGroup($group, $pattern, $limit, $offset);
304 304
 
305
-					foreach($groupUsers as $uid => $displayName) {
305
+					foreach ($groupUsers as $uid => $displayName) {
306 306
 						$batch[$uid] = $displayName;
307 307
 					}
308 308
 				}
@@ -334,11 +334,11 @@  discard block
 block discarded – undo
334 334
 	 * @param string $email
335 335
 	 * @return DataResponse
336 336
 	 */
337
-	public function create($username, $password, array $groups=array(), $email='') {
338
-		if($email !== '' && !$this->mailer->validateMailAddress($email)) {
337
+	public function create($username, $password, array $groups = array(), $email = '') {
338
+		if ($email !== '' && !$this->mailer->validateMailAddress($email)) {
339 339
 			return new DataResponse(
340 340
 				array(
341
-					'message' => (string)$this->l10n->t('Invalid mail address')
341
+					'message' => (string) $this->l10n->t('Invalid mail address')
342 342
 				),
343 343
 				Http::STATUS_UNPROCESSABLE_ENTITY
344 344
 			);
@@ -350,7 +350,7 @@  discard block
 block discarded – undo
350 350
 			if (!empty($groups)) {
351 351
 				foreach ($groups as $key => $group) {
352 352
 					$groupObject = $this->groupManager->get($group);
353
-					if($groupObject === null) {
353
+					if ($groupObject === null) {
354 354
 						unset($groups[$key]);
355 355
 						continue;
356 356
 					}
@@ -374,7 +374,7 @@  discard block
 block discarded – undo
374 374
 		if ($this->userManager->userExists($username)) {
375 375
 			return new DataResponse(
376 376
 				array(
377
-					'message' => (string)$this->l10n->t('A user with that name already exists.')
377
+					'message' => (string) $this->l10n->t('A user with that name already exists.')
378 378
 				),
379 379
 				Http::STATUS_CONFLICT
380 380
 			);
@@ -385,7 +385,7 @@  discard block
 block discarded – undo
385 385
 			if ($email === '') {
386 386
 				return new DataResponse(
387 387
 					array(
388
-						'message' => (string)$this->l10n->t('To send a password link to the user an email address is required.')
388
+						'message' => (string) $this->l10n->t('To send a password link to the user an email address is required.')
389 389
 					),
390 390
 					Http::STATUS_UNPROCESSABLE_ENTITY
391 391
 				);
@@ -410,12 +410,12 @@  discard block
 block discarded – undo
410 410
 			);
411 411
 		}
412 412
 
413
-		if($user instanceof IUser) {
414
-			if($groups !== null) {
415
-				foreach($groups as $groupName) {
413
+		if ($user instanceof IUser) {
414
+			if ($groups !== null) {
415
+				foreach ($groups as $groupName) {
416 416
 					$group = $this->groupManager->get($groupName);
417 417
 
418
-					if(empty($group)) {
418
+					if (empty($group)) {
419 419
 						$group = $this->groupManager->createGroup($groupName);
420 420
 					}
421 421
 					$group->addUser($user);
@@ -424,19 +424,19 @@  discard block
 block discarded – undo
424 424
 			/**
425 425
 			 * Send new user mail only if a mail is set
426 426
 			 */
427
-			if($email !== '') {
427
+			if ($email !== '') {
428 428
 				$user->setEMailAddress($email);
429 429
 
430 430
 				if ($generatedPassword) {
431 431
 					$token = $this->secureRandom->generate(
432 432
 						21,
433
-						ISecureRandom::CHAR_DIGITS .
434
-						ISecureRandom::CHAR_LOWER .
433
+						ISecureRandom::CHAR_DIGITS.
434
+						ISecureRandom::CHAR_LOWER.
435 435
 						ISecureRandom::CHAR_UPPER
436 436
 					);
437
-					$tokenValue = $this->timeFactory->getTime() . ':' . $token;
437
+					$tokenValue = $this->timeFactory->getTime().':'.$token;
438 438
 					$mailAddress = !is_null($user->getEMailAddress()) ? $user->getEMailAddress() : '';
439
-					$encryptedValue = $this->crypto->encrypt($tokenValue, $mailAddress . $this->config->getSystemValue('secret'));
439
+					$encryptedValue = $this->crypto->encrypt($tokenValue, $mailAddress.$this->config->getSystemValue('secret'));
440 440
 					$this->config->setUserValue($username, 'core', 'lostpassword', $encryptedValue);
441 441
 
442 442
 					$link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', ['userId' => $username, 'token' => $token]);
@@ -472,7 +472,7 @@  discard block
 block discarded – undo
472 472
 
473 473
 				$emailTemplate->addFooter(
474 474
 					$this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('', 'logo-mail-footer.png')),
475
-					$this->defaults->getName() . ' - ' . $this->defaults->getSlogan() . '<br>' . $this->l10n->t('This is an automatically generated email, please do not reply.')
475
+					$this->defaults->getName().' - '.$this->defaults->getSlogan().'<br>'.$this->l10n->t('This is an automatically generated email, please do not reply.')
476 476
 				);
477 477
 
478 478
 				$mailContent = $emailTemplate->renderHTML();
@@ -488,8 +488,8 @@  discard block
 block discarded – undo
488 488
 					$message->setPlainBody($plainTextMailContent);
489 489
 					$message->setFrom([$this->fromMailAddress => $this->defaults->getName()]);
490 490
 					$this->mailer->send($message);
491
-				} catch(\Exception $e) {
492
-					$this->log->error("Can't send new user mail to $email: " . $e->getMessage(), array('app' => 'settings'));
491
+				} catch (\Exception $e) {
492
+					$this->log->error("Can't send new user mail to $email: ".$e->getMessage(), array('app' => 'settings'));
493 493
 				}
494 494
 			}
495 495
 			// fetch users groups
@@ -503,7 +503,7 @@  discard block
 block discarded – undo
503 503
 
504 504
 		return new DataResponse(
505 505
 			array(
506
-				'message' => (string)$this->l10n->t('Unable to create user.')
506
+				'message' => (string) $this->l10n->t('Unable to create user.')
507 507
 			),
508 508
 			Http::STATUS_FORBIDDEN
509 509
 		);
@@ -521,32 +521,32 @@  discard block
 block discarded – undo
521 521
 		$userId = $this->userSession->getUser()->getUID();
522 522
 		$user = $this->userManager->get($id);
523 523
 
524
-		if($userId === $id) {
524
+		if ($userId === $id) {
525 525
 			return new DataResponse(
526 526
 				array(
527 527
 					'status' => 'error',
528 528
 					'data' => array(
529
-						'message' => (string)$this->l10n->t('Unable to delete user.')
529
+						'message' => (string) $this->l10n->t('Unable to delete user.')
530 530
 					)
531 531
 				),
532 532
 				Http::STATUS_FORBIDDEN
533 533
 			);
534 534
 		}
535 535
 
536
-		if(!$this->isAdmin && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)) {
536
+		if (!$this->isAdmin && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)) {
537 537
 			return new DataResponse(
538 538
 				array(
539 539
 					'status' => 'error',
540 540
 					'data' => array(
541
-						'message' => (string)$this->l10n->t('Authentication error')
541
+						'message' => (string) $this->l10n->t('Authentication error')
542 542
 					)
543 543
 				),
544 544
 				Http::STATUS_FORBIDDEN
545 545
 			);
546 546
 		}
547 547
 
548
-		if($user) {
549
-			if($user->delete()) {
548
+		if ($user) {
549
+			if ($user->delete()) {
550 550
 				return new DataResponse(
551 551
 					array(
552 552
 						'status' => 'success',
@@ -563,7 +563,7 @@  discard block
 block discarded – undo
563 563
 			array(
564 564
 				'status' => 'error',
565 565
 				'data' => array(
566
-					'message' => (string)$this->l10n->t('Unable to delete user.')
566
+					'message' => (string) $this->l10n->t('Unable to delete user.')
567 567
 				)
568 568
 			),
569 569
 			Http::STATUS_FORBIDDEN
@@ -605,12 +605,12 @@  discard block
 block discarded – undo
605 605
 									$twitterScope
606 606
 	) {
607 607
 
608
-		if(!empty($email) && !$this->mailer->validateMailAddress($email)) {
608
+		if (!empty($email) && !$this->mailer->validateMailAddress($email)) {
609 609
 			return new DataResponse(
610 610
 				array(
611 611
 					'status' => 'error',
612 612
 					'data' => array(
613
-						'message' => (string)$this->l10n->t('Invalid mail address')
613
+						'message' => (string) $this->l10n->t('Invalid mail address')
614 614
 					)
615 615
 				),
616 616
 				Http::STATUS_UNPROCESSABLE_ENTITY
@@ -645,7 +645,7 @@  discard block
 block discarded – undo
645 645
 						'websiteScope' => $websiteScope,
646 646
 						'address' => $address,
647 647
 						'addressScope' => $addressScope,
648
-						'message' => (string)$this->l10n->t('Settings saved')
648
+						'message' => (string) $this->l10n->t('Settings saved')
649 649
 					)
650 650
 				),
651 651
 				Http::STATUS_OK
@@ -722,7 +722,7 @@  discard block
 block discarded – undo
722 722
 
723 723
 			$uniqueUsers = [];
724 724
 			foreach ($groups as $group) {
725
-				foreach($group->getUsers() as $uid => $displayName) {
725
+				foreach ($group->getUsers() as $uid => $displayName) {
726 726
 					$uniqueUsers[$uid] = true;
727 727
 				}
728 728
 			}
@@ -816,19 +816,19 @@  discard block
 block discarded – undo
816 816
 				array(
817 817
 					'status' => 'error',
818 818
 					'data' => array(
819
-						'message' => (string)$this->l10n->t('Forbidden')
819
+						'message' => (string) $this->l10n->t('Forbidden')
820 820
 					)
821 821
 				),
822 822
 				Http::STATUS_FORBIDDEN
823 823
 			);
824 824
 		}
825 825
 
826
-		if($mailAddress !== '' && !$this->mailer->validateMailAddress($mailAddress)) {
826
+		if ($mailAddress !== '' && !$this->mailer->validateMailAddress($mailAddress)) {
827 827
 			return new DataResponse(
828 828
 				array(
829 829
 					'status' => 'error',
830 830
 					'data' => array(
831
-						'message' => (string)$this->l10n->t('Invalid mail address')
831
+						'message' => (string) $this->l10n->t('Invalid mail address')
832 832
 					)
833 833
 				),
834 834
 				Http::STATUS_UNPROCESSABLE_ENTITY
@@ -840,7 +840,7 @@  discard block
 block discarded – undo
840 840
 				array(
841 841
 					'status' => 'error',
842 842
 					'data' => array(
843
-						'message' => (string)$this->l10n->t('Invalid user')
843
+						'message' => (string) $this->l10n->t('Invalid user')
844 844
 					)
845 845
 				),
846 846
 				Http::STATUS_UNPROCESSABLE_ENTITY
@@ -853,7 +853,7 @@  discard block
 block discarded – undo
853 853
 				array(
854 854
 					'status' => 'error',
855 855
 					'data' => array(
856
-						'message' => (string)$this->l10n->t('Unable to change mail address')
856
+						'message' => (string) $this->l10n->t('Unable to change mail address')
857 857
 					)
858 858
 				),
859 859
 				Http::STATUS_FORBIDDEN
@@ -871,7 +871,7 @@  discard block
 block discarded – undo
871 871
 					'data' => array(
872 872
 						'username' => $id,
873 873
 						'mailAddress' => $mailAddress,
874
-						'message' => (string)$this->l10n->t('Email saved')
874
+						'message' => (string) $this->l10n->t('Email saved')
875 875
 					)
876 876
 				),
877 877
 				Http::STATUS_OK
Please login to merge, or discard this patch.
Indentation   +827 added lines, -827 removed lines patch added patch discarded remove patch
@@ -58,832 +58,832 @@
 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 \OC_Defaults */
76
-	private $defaults;
77
-	/** @var IMailer */
78
-	private $mailer;
79
-	/** @var string */
80
-	private $fromMailAddress;
81
-	/** @var IURLGenerator */
82
-	private $urlGenerator;
83
-	/** @var bool contains the state of the encryption app */
84
-	private $isEncryptionAppEnabled;
85
-	/** @var bool contains the state of the admin recovery setting */
86
-	private $isRestoreEnabled = false;
87
-	/** @var IAvatarManager */
88
-	private $avatarManager;
89
-	/** @var AccountManager */
90
-	private $accountManager;
91
-	/** @var ISecureRandom */
92
-	private $secureRandom;
93
-	/** @var ITimeFactory */
94
-	private $timeFactory;
95
-	/** @var ICrypto */
96
-	private $crypto;
97
-
98
-
99
-	/**
100
-	 * @param string $appName
101
-	 * @param IRequest $request
102
-	 * @param IUserManager $userManager
103
-	 * @param IGroupManager $groupManager
104
-	 * @param IUserSession $userSession
105
-	 * @param IConfig $config
106
-	 * @param bool $isAdmin
107
-	 * @param IL10N $l10n
108
-	 * @param ILogger $log
109
-	 * @param \OC_Defaults $defaults
110
-	 * @param IMailer $mailer
111
-	 * @param string $fromMailAddress
112
-	 * @param IURLGenerator $urlGenerator
113
-	 * @param IAppManager $appManager
114
-	 * @param IAvatarManager $avatarManager
115
-	 * @param AccountManager $accountManager
116
-	 * @param ISecureRandom $secureRandom
117
-	 * @param ITimeFactory $timeFactory
118
-	 * @param ICrypto $crypto
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
-								\OC_Defaults $defaults,
130
-								IMailer $mailer,
131
-								$fromMailAddress,
132
-								IURLGenerator $urlGenerator,
133
-								IAppManager $appManager,
134
-								IAvatarManager $avatarManager,
135
-								AccountManager $accountManager,
136
-								ISecureRandom $secureRandom,
137
-								ITimeFactory $timeFactory,
138
-								ICrypto $crypto) {
139
-		parent::__construct($appName, $request);
140
-		$this->userManager = $userManager;
141
-		$this->groupManager = $groupManager;
142
-		$this->userSession = $userSession;
143
-		$this->config = $config;
144
-		$this->isAdmin = $isAdmin;
145
-		$this->l10n = $l10n;
146
-		$this->log = $log;
147
-		$this->defaults = $defaults;
148
-		$this->mailer = $mailer;
149
-		$this->fromMailAddress = $fromMailAddress;
150
-		$this->urlGenerator = $urlGenerator;
151
-		$this->avatarManager = $avatarManager;
152
-		$this->accountManager = $accountManager;
153
-		$this->secureRandom = $secureRandom;
154
-		$this->timeFactory = $timeFactory;
155
-		$this->crypto = $crypto;
156
-
157
-		// check for encryption state - TODO see formatUserForIndex
158
-		$this->isEncryptionAppEnabled = $appManager->isEnabledForUser('encryption');
159
-		if($this->isEncryptionAppEnabled) {
160
-			// putting this directly in empty is possible in PHP 5.5+
161
-			$result = $config->getAppValue('encryption', 'recoveryAdminEnabled', 0);
162
-			$this->isRestoreEnabled = !empty($result);
163
-		}
164
-	}
165
-
166
-	/**
167
-	 * @param IUser $user
168
-	 * @param array $userGroups
169
-	 * @return array
170
-	 */
171
-	private function formatUserForIndex(IUser $user, array $userGroups = null) {
172
-
173
-		// TODO: eliminate this encryption specific code below and somehow
174
-		// hook in additional user info from other apps
175
-
176
-		// recovery isn't possible if admin or user has it disabled and encryption
177
-		// is enabled - so we eliminate the else paths in the conditional tree
178
-		// below
179
-		$restorePossible = false;
180
-
181
-		if ($this->isEncryptionAppEnabled) {
182
-			if ($this->isRestoreEnabled) {
183
-				// check for the users recovery setting
184
-				$recoveryMode = $this->config->getUserValue($user->getUID(), 'encryption', 'recoveryEnabled', '0');
185
-				// method call inside empty is possible with PHP 5.5+
186
-				$recoveryModeEnabled = !empty($recoveryMode);
187
-				if ($recoveryModeEnabled) {
188
-					// user also has recovery mode enabled
189
-					$restorePossible = true;
190
-				}
191
-			}
192
-		} else {
193
-			// recovery is possible if encryption is disabled (plain files are
194
-			// available)
195
-			$restorePossible = true;
196
-		}
197
-
198
-		$subAdminGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($user);
199
-		foreach($subAdminGroups as $key => $subAdminGroup) {
200
-			$subAdminGroups[$key] = $subAdminGroup->getGID();
201
-		}
202
-
203
-		$displayName = $user->getEMailAddress();
204
-		if (is_null($displayName)) {
205
-			$displayName = '';
206
-		}
207
-
208
-		$avatarAvailable = false;
209
-		try {
210
-			$avatarAvailable = $this->avatarManager->getAvatar($user->getUID())->exists();
211
-		} catch (\Exception $e) {
212
-			//No avatar yet
213
-		}
214
-
215
-		return [
216
-			'name' => $user->getUID(),
217
-			'displayname' => $user->getDisplayName(),
218
-			'groups' => (empty($userGroups)) ? $this->groupManager->getUserGroupIds($user) : $userGroups,
219
-			'subadmin' => $subAdminGroups,
220
-			'quota' => $user->getQuota(),
221
-			'storageLocation' => $user->getHome(),
222
-			'lastLogin' => $user->getLastLogin() * 1000,
223
-			'backend' => $user->getBackendClassName(),
224
-			'email' => $displayName,
225
-			'isRestoreDisabled' => !$restorePossible,
226
-			'isAvatarAvailable' => $avatarAvailable,
227
-		];
228
-	}
229
-
230
-	/**
231
-	 * @param array $userIDs Array with schema [$uid => $displayName]
232
-	 * @return IUser[]
233
-	 */
234
-	private function getUsersForUID(array $userIDs) {
235
-		$users = [];
236
-		foreach ($userIDs as $uid => $displayName) {
237
-			$users[$uid] = $this->userManager->get($uid);
238
-		}
239
-		return $users;
240
-	}
241
-
242
-	/**
243
-	 * @NoAdminRequired
244
-	 *
245
-	 * @param int $offset
246
-	 * @param int $limit
247
-	 * @param string $gid GID to filter for
248
-	 * @param string $pattern Pattern to search for in the username
249
-	 * @param string $backend Backend to filter for (class-name)
250
-	 * @return DataResponse
251
-	 *
252
-	 * TODO: Tidy up and write unit tests - code is mainly static method calls
253
-	 */
254
-	public function index($offset = 0, $limit = 10, $gid = '', $pattern = '', $backend = '') {
255
-		// FIXME: The JS sends the group '_everyone' instead of no GID for the "all users" group.
256
-		if($gid === '_everyone') {
257
-			$gid = '';
258
-		}
259
-
260
-		// Remove backends
261
-		if(!empty($backend)) {
262
-			$activeBackends = $this->userManager->getBackends();
263
-			$this->userManager->clearBackends();
264
-			foreach($activeBackends as $singleActiveBackend) {
265
-				if($backend === get_class($singleActiveBackend)) {
266
-					$this->userManager->registerBackend($singleActiveBackend);
267
-					break;
268
-				}
269
-			}
270
-		}
271
-
272
-		$users = [];
273
-		if ($this->isAdmin) {
274
-
275
-			if($gid !== '') {
276
-				$batch = $this->getUsersForUID($this->groupManager->displayNamesInGroup($gid, $pattern, $limit, $offset));
277
-			} else {
278
-				$batch = $this->userManager->search($pattern, $limit, $offset);
279
-			}
280
-
281
-			foreach ($batch as $user) {
282
-				$users[] = $this->formatUserForIndex($user);
283
-			}
284
-
285
-		} else {
286
-			$subAdminOfGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($this->userSession->getUser());
287
-			// New class returns IGroup[] so convert back
288
-			$gids = [];
289
-			foreach ($subAdminOfGroups as $group) {
290
-				$gids[] = $group->getGID();
291
-			}
292
-			$subAdminOfGroups = $gids;
293
-
294
-			// Set the $gid parameter to an empty value if the subadmin has no rights to access a specific group
295
-			if($gid !== '' && !in_array($gid, $subAdminOfGroups)) {
296
-				$gid = '';
297
-			}
298
-
299
-			// Batch all groups the user is subadmin of when a group is specified
300
-			$batch = [];
301
-			if($gid === '') {
302
-				foreach($subAdminOfGroups as $group) {
303
-					$groupUsers = $this->groupManager->displayNamesInGroup($group, $pattern, $limit, $offset);
304
-
305
-					foreach($groupUsers as $uid => $displayName) {
306
-						$batch[$uid] = $displayName;
307
-					}
308
-				}
309
-			} else {
310
-				$batch = $this->groupManager->displayNamesInGroup($gid, $pattern, $limit, $offset);
311
-			}
312
-			$batch = $this->getUsersForUID($batch);
313
-
314
-			foreach ($batch as $user) {
315
-				// Only add the groups, this user is a subadmin of
316
-				$userGroups = array_values(array_intersect(
317
-					$this->groupManager->getUserGroupIds($user),
318
-					$subAdminOfGroups
319
-				));
320
-				$users[] = $this->formatUserForIndex($user, $userGroups);
321
-			}
322
-		}
323
-
324
-		return new DataResponse($users);
325
-	}
326
-
327
-	/**
328
-	 * @NoAdminRequired
329
-	 * @PasswordConfirmationRequired
330
-	 *
331
-	 * @param string $username
332
-	 * @param string $password
333
-	 * @param array $groups
334
-	 * @param string $email
335
-	 * @return DataResponse
336
-	 */
337
-	public function create($username, $password, array $groups=array(), $email='') {
338
-		if($email !== '' && !$this->mailer->validateMailAddress($email)) {
339
-			return new DataResponse(
340
-				array(
341
-					'message' => (string)$this->l10n->t('Invalid mail address')
342
-				),
343
-				Http::STATUS_UNPROCESSABLE_ENTITY
344
-			);
345
-		}
346
-
347
-		$currentUser = $this->userSession->getUser();
348
-
349
-		if (!$this->isAdmin) {
350
-			if (!empty($groups)) {
351
-				foreach ($groups as $key => $group) {
352
-					$groupObject = $this->groupManager->get($group);
353
-					if($groupObject === null) {
354
-						unset($groups[$key]);
355
-						continue;
356
-					}
357
-
358
-					if (!$this->groupManager->getSubAdmin()->isSubAdminofGroup($currentUser, $groupObject)) {
359
-						unset($groups[$key]);
360
-					}
361
-				}
362
-			}
363
-
364
-			if (empty($groups)) {
365
-				return new DataResponse(
366
-					array(
367
-						'message' => $this->l10n->t('No valid group selected'),
368
-					),
369
-					Http::STATUS_FORBIDDEN
370
-				);
371
-			}
372
-		}
373
-
374
-		if ($this->userManager->userExists($username)) {
375
-			return new DataResponse(
376
-				array(
377
-					'message' => (string)$this->l10n->t('A user with that name already exists.')
378
-				),
379
-				Http::STATUS_CONFLICT
380
-			);
381
-		}
382
-
383
-		$generatedPassword = false;
384
-		if ($password === '') {
385
-			if ($email === '') {
386
-				return new DataResponse(
387
-					array(
388
-						'message' => (string)$this->l10n->t('To send a password link to the user an email address is required.')
389
-					),
390
-					Http::STATUS_UNPROCESSABLE_ENTITY
391
-				);
392
-			}
393
-
394
-			$password = $this->secureRandom->generate(32);
395
-			$generatedPassword = true;
396
-		}
397
-
398
-		try {
399
-			$user = $this->userManager->createUser($username, $password);
400
-		} catch (\Exception $exception) {
401
-			$message = $exception->getMessage();
402
-			if (!$message) {
403
-				$message = $this->l10n->t('Unable to create user.');
404
-			}
405
-			return new DataResponse(
406
-				array(
407
-					'message' => (string) $message,
408
-				),
409
-				Http::STATUS_FORBIDDEN
410
-			);
411
-		}
412
-
413
-		if($user instanceof IUser) {
414
-			if($groups !== null) {
415
-				foreach($groups as $groupName) {
416
-					$group = $this->groupManager->get($groupName);
417
-
418
-					if(empty($group)) {
419
-						$group = $this->groupManager->createGroup($groupName);
420
-					}
421
-					$group->addUser($user);
422
-				}
423
-			}
424
-			/**
425
-			 * Send new user mail only if a mail is set
426
-			 */
427
-			if($email !== '') {
428
-				$user->setEMailAddress($email);
429
-
430
-				if ($generatedPassword) {
431
-					$token = $this->secureRandom->generate(
432
-						21,
433
-						ISecureRandom::CHAR_DIGITS .
434
-						ISecureRandom::CHAR_LOWER .
435
-						ISecureRandom::CHAR_UPPER
436
-					);
437
-					$tokenValue = $this->timeFactory->getTime() . ':' . $token;
438
-					$mailAddress = !is_null($user->getEMailAddress()) ? $user->getEMailAddress() : '';
439
-					$encryptedValue = $this->crypto->encrypt($tokenValue, $mailAddress . $this->config->getSystemValue('secret'));
440
-					$this->config->setUserValue($username, 'core', 'lostpassword', $encryptedValue);
441
-
442
-					$link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', ['userId' => $username, 'token' => $token]);
443
-				} else {
444
-					$link = $this->urlGenerator->getAbsoluteURL('/');
445
-				}
446
-
447
-				$emailTemplate = new EMailTemplate($this->defaults);
448
-
449
-				$emailTemplate->addHeader($this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('', 'logo-mail-header.png')));
450
-
451
-				$displayName = $user->getDisplayName();
452
-				if ($displayName === $username) {
453
-					$emailTemplate->addHeading($this->l10n->t('Welcome aboard'));
454
-				} else {
455
-					$emailTemplate->addHeading($this->l10n->t('Welcome aboard %s', [$displayName]));
456
-				}
457
-				$emailTemplate->addBodyText($this->l10n->t('You have now an %s account, you can add, protect, and share your data.', [$this->defaults->getName()]));
458
-				$emailTemplate->addBodyText($this->l10n->t('Your username is: %s', [$username]));
459
-
460
-				if ($generatedPassword) {
461
-					$leftButtonText = $this->l10n->t('Set your password');
462
-				} else {
463
-					$leftButtonText = $this->l10n->t('Go to %s', [$this->defaults->getName()]);
464
-				}
465
-
466
-				$emailTemplate->addBodyButtonGroup(
467
-					$leftButtonText,
468
-					$link,
469
-					$this->l10n->t('Install Client'),
470
-					'https://nextcloud.com/install/#install-clients'
471
-				);
472
-
473
-				$emailTemplate->addFooter(
474
-					$this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('', 'logo-mail-footer.png')),
475
-					$this->defaults->getName() . ' - ' . $this->defaults->getSlogan() . '<br>' . $this->l10n->t('This is an automatically generated email, please do not reply.')
476
-				);
477
-
478
-				$mailContent = $emailTemplate->renderHTML();
479
-				$plainTextMailContent = $emailTemplate->renderText();
480
-
481
-				$subject = $this->l10n->t('Your %s account was created', [$this->defaults->getName()]);
482
-
483
-				try {
484
-					$message = $this->mailer->createMessage();
485
-					$message->setTo([$email => $username]);
486
-					$message->setSubject($subject);
487
-					$message->setHtmlBody($mailContent);
488
-					$message->setPlainBody($plainTextMailContent);
489
-					$message->setFrom([$this->fromMailAddress => $this->defaults->getName()]);
490
-					$this->mailer->send($message);
491
-				} catch(\Exception $e) {
492
-					$this->log->error("Can't send new user mail to $email: " . $e->getMessage(), array('app' => 'settings'));
493
-				}
494
-			}
495
-			// fetch users groups
496
-			$userGroups = $this->groupManager->getUserGroupIds($user);
497
-
498
-			return new DataResponse(
499
-				$this->formatUserForIndex($user, $userGroups),
500
-				Http::STATUS_CREATED
501
-			);
502
-		}
503
-
504
-		return new DataResponse(
505
-			array(
506
-				'message' => (string)$this->l10n->t('Unable to create user.')
507
-			),
508
-			Http::STATUS_FORBIDDEN
509
-		);
510
-
511
-	}
512
-
513
-	/**
514
-	 * @NoAdminRequired
515
-	 * @PasswordConfirmationRequired
516
-	 *
517
-	 * @param string $id
518
-	 * @return DataResponse
519
-	 */
520
-	public function destroy($id) {
521
-		$userId = $this->userSession->getUser()->getUID();
522
-		$user = $this->userManager->get($id);
523
-
524
-		if($userId === $id) {
525
-			return new DataResponse(
526
-				array(
527
-					'status' => 'error',
528
-					'data' => array(
529
-						'message' => (string)$this->l10n->t('Unable to delete user.')
530
-					)
531
-				),
532
-				Http::STATUS_FORBIDDEN
533
-			);
534
-		}
535
-
536
-		if(!$this->isAdmin && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)) {
537
-			return new DataResponse(
538
-				array(
539
-					'status' => 'error',
540
-					'data' => array(
541
-						'message' => (string)$this->l10n->t('Authentication error')
542
-					)
543
-				),
544
-				Http::STATUS_FORBIDDEN
545
-			);
546
-		}
547
-
548
-		if($user) {
549
-			if($user->delete()) {
550
-				return new DataResponse(
551
-					array(
552
-						'status' => 'success',
553
-						'data' => array(
554
-							'username' => $id
555
-						)
556
-					),
557
-					Http::STATUS_NO_CONTENT
558
-				);
559
-			}
560
-		}
561
-
562
-		return new DataResponse(
563
-			array(
564
-				'status' => 'error',
565
-				'data' => array(
566
-					'message' => (string)$this->l10n->t('Unable to delete user.')
567
-				)
568
-			),
569
-			Http::STATUS_FORBIDDEN
570
-		);
571
-	}
572
-
573
-	/**
574
-	 * @NoAdminRequired
575
-	 * @NoSubadminRequired
576
-	 * @PasswordConfirmationRequired
577
-	 *
578
-	 * @param string $avatarScope
579
-	 * @param string $displayname
580
-	 * @param string $displaynameScope
581
-	 * @param string $phone
582
-	 * @param string $phoneScope
583
-	 * @param string $email
584
-	 * @param string $emailScope
585
-	 * @param string $website
586
-	 * @param string $websiteScope
587
-	 * @param string $address
588
-	 * @param string $addressScope
589
-	 * @param string $twitter
590
-	 * @param string $twitterScope
591
-	 * @return DataResponse
592
-	 */
593
-	public function setUserSettings($avatarScope,
594
-									$displayname,
595
-									$displaynameScope,
596
-									$phone,
597
-									$phoneScope,
598
-									$email,
599
-									$emailScope,
600
-									$website,
601
-									$websiteScope,
602
-									$address,
603
-									$addressScope,
604
-									$twitter,
605
-									$twitterScope
606
-	) {
607
-
608
-		if(!empty($email) && !$this->mailer->validateMailAddress($email)) {
609
-			return new DataResponse(
610
-				array(
611
-					'status' => 'error',
612
-					'data' => array(
613
-						'message' => (string)$this->l10n->t('Invalid mail address')
614
-					)
615
-				),
616
-				Http::STATUS_UNPROCESSABLE_ENTITY
617
-			);
618
-		}
619
-
620
-		$data = [
621
-			AccountManager::PROPERTY_AVATAR =>  ['scope' => $avatarScope],
622
-			AccountManager::PROPERTY_DISPLAYNAME => ['value' => $displayname, 'scope' => $displaynameScope],
623
-			AccountManager::PROPERTY_EMAIL=> ['value' => $email, 'scope' => $emailScope],
624
-			AccountManager::PROPERTY_WEBSITE => ['value' => $website, 'scope' => $websiteScope],
625
-			AccountManager::PROPERTY_ADDRESS => ['value' => $address, 'scope' => $addressScope],
626
-			AccountManager::PROPERTY_PHONE => ['value' => $phone, 'scope' => $phoneScope],
627
-			AccountManager::PROPERTY_TWITTER => ['value' => $twitter, 'scope' => $twitterScope]
628
-		];
629
-
630
-		$user = $this->userSession->getUser();
631
-
632
-		try {
633
-			$this->saveUserSettings($user, $data);
634
-			return new DataResponse(
635
-				array(
636
-					'status' => 'success',
637
-					'data' => array(
638
-						'userId' => $user->getUID(),
639
-						'avatarScope' => $avatarScope,
640
-						'displayname' => $displayname,
641
-						'displaynameScope' => $displaynameScope,
642
-						'email' => $email,
643
-						'emailScope' => $emailScope,
644
-						'website' => $website,
645
-						'websiteScope' => $websiteScope,
646
-						'address' => $address,
647
-						'addressScope' => $addressScope,
648
-						'message' => (string)$this->l10n->t('Settings saved')
649
-					)
650
-				),
651
-				Http::STATUS_OK
652
-			);
653
-		} catch (ForbiddenException $e) {
654
-			return new DataResponse([
655
-				'status' => 'error',
656
-				'data' => [
657
-					'message' => $e->getMessage()
658
-				],
659
-			]);
660
-		}
661
-
662
-	}
663
-
664
-
665
-	/**
666
-	 * update account manager with new user data
667
-	 *
668
-	 * @param IUser $user
669
-	 * @param array $data
670
-	 * @throws ForbiddenException
671
-	 */
672
-	protected function saveUserSettings(IUser $user, $data) {
673
-
674
-		// keep the user back-end up-to-date with the latest display name and email
675
-		// address
676
-		$oldDisplayName = $user->getDisplayName();
677
-		$oldDisplayName = is_null($oldDisplayName) ? '' : $oldDisplayName;
678
-		if (isset($data[AccountManager::PROPERTY_DISPLAYNAME]['value'])
679
-			&& $oldDisplayName !== $data[AccountManager::PROPERTY_DISPLAYNAME]['value']
680
-		) {
681
-			$result = $user->setDisplayName($data[AccountManager::PROPERTY_DISPLAYNAME]['value']);
682
-			if ($result === false) {
683
-				throw new ForbiddenException($this->l10n->t('Unable to change full name'));
684
-			}
685
-		}
686
-
687
-		$oldEmailAddress = $user->getEMailAddress();
688
-		$oldEmailAddress = is_null($oldEmailAddress) ? '' : $oldEmailAddress;
689
-		if (isset($data[AccountManager::PROPERTY_EMAIL]['value'])
690
-			&& $oldEmailAddress !== $data[AccountManager::PROPERTY_EMAIL]['value']
691
-		) {
692
-			// this is the only permission a backend provides and is also used
693
-			// for the permission of setting a email address
694
-			if (!$user->canChangeDisplayName()) {
695
-				throw new ForbiddenException($this->l10n->t('Unable to change email address'));
696
-			}
697
-			$user->setEMailAddress($data[AccountManager::PROPERTY_EMAIL]['value']);
698
-		}
699
-
700
-		$this->accountManager->updateUser($user, $data);
701
-	}
702
-
703
-	/**
704
-	 * Count all unique users visible for the current admin/subadmin.
705
-	 *
706
-	 * @NoAdminRequired
707
-	 *
708
-	 * @return DataResponse
709
-	 */
710
-	public function stats() {
711
-		$userCount = 0;
712
-		if ($this->isAdmin) {
713
-			$countByBackend = $this->userManager->countUsers();
714
-
715
-			if (!empty($countByBackend)) {
716
-				foreach ($countByBackend as $count) {
717
-					$userCount += $count;
718
-				}
719
-			}
720
-		} else {
721
-			$groups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($this->userSession->getUser());
722
-
723
-			$uniqueUsers = [];
724
-			foreach ($groups as $group) {
725
-				foreach($group->getUsers() as $uid => $displayName) {
726
-					$uniqueUsers[$uid] = true;
727
-				}
728
-			}
729
-
730
-			$userCount = count($uniqueUsers);
731
-		}
732
-
733
-		return new DataResponse(
734
-			[
735
-				'totalUsers' => $userCount
736
-			]
737
-		);
738
-	}
739
-
740
-
741
-	/**
742
-	 * Set the displayName of a user
743
-	 *
744
-	 * @NoAdminRequired
745
-	 * @NoSubadminRequired
746
-	 * @PasswordConfirmationRequired
747
-	 * @todo merge into saveUserSettings
748
-	 *
749
-	 * @param string $username
750
-	 * @param string $displayName
751
-	 * @return DataResponse
752
-	 */
753
-	public function setDisplayName($username, $displayName) {
754
-		$currentUser = $this->userSession->getUser();
755
-		$user = $this->userManager->get($username);
756
-
757
-		if ($user === null ||
758
-			!$user->canChangeDisplayName() ||
759
-			(
760
-				!$this->groupManager->isAdmin($currentUser->getUID()) &&
761
-				!$this->groupManager->getSubAdmin()->isUserAccessible($currentUser, $user) &&
762
-				$currentUser->getUID() !== $username
763
-
764
-			)
765
-		) {
766
-			return new DataResponse([
767
-				'status' => 'error',
768
-				'data' => [
769
-					'message' => $this->l10n->t('Authentication error'),
770
-				],
771
-			]);
772
-		}
773
-
774
-		$userData = $this->accountManager->getUser($user);
775
-		$userData[AccountManager::PROPERTY_DISPLAYNAME]['value'] = $displayName;
776
-
777
-
778
-		try {
779
-			$this->saveUserSettings($user, $userData);
780
-			return new DataResponse([
781
-				'status' => 'success',
782
-				'data' => [
783
-					'message' => $this->l10n->t('Your full name has been changed.'),
784
-					'username' => $username,
785
-					'displayName' => $displayName,
786
-				],
787
-			]);
788
-		} catch (ForbiddenException $e) {
789
-			return new DataResponse([
790
-				'status' => 'error',
791
-				'data' => [
792
-					'message' => $e->getMessage(),
793
-					'displayName' => $user->getDisplayName(),
794
-				],
795
-			]);
796
-		}
797
-	}
798
-
799
-	/**
800
-	 * Set the mail address of a user
801
-	 *
802
-	 * @NoAdminRequired
803
-	 * @NoSubadminRequired
804
-	 * @PasswordConfirmationRequired
805
-	 *
806
-	 * @param string $id
807
-	 * @param string $mailAddress
808
-	 * @return DataResponse
809
-	 */
810
-	public function setEMailAddress($id, $mailAddress) {
811
-		$user = $this->userManager->get($id);
812
-		if (!$this->isAdmin
813
-			&& !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)
814
-		) {
815
-			return new DataResponse(
816
-				array(
817
-					'status' => 'error',
818
-					'data' => array(
819
-						'message' => (string)$this->l10n->t('Forbidden')
820
-					)
821
-				),
822
-				Http::STATUS_FORBIDDEN
823
-			);
824
-		}
825
-
826
-		if($mailAddress !== '' && !$this->mailer->validateMailAddress($mailAddress)) {
827
-			return new DataResponse(
828
-				array(
829
-					'status' => 'error',
830
-					'data' => array(
831
-						'message' => (string)$this->l10n->t('Invalid mail address')
832
-					)
833
-				),
834
-				Http::STATUS_UNPROCESSABLE_ENTITY
835
-			);
836
-		}
837
-
838
-		if (!$user) {
839
-			return new DataResponse(
840
-				array(
841
-					'status' => 'error',
842
-					'data' => array(
843
-						'message' => (string)$this->l10n->t('Invalid user')
844
-					)
845
-				),
846
-				Http::STATUS_UNPROCESSABLE_ENTITY
847
-			);
848
-		}
849
-		// this is the only permission a backend provides and is also used
850
-		// for the permission of setting a email address
851
-		if (!$user->canChangeDisplayName()) {
852
-			return new DataResponse(
853
-				array(
854
-					'status' => 'error',
855
-					'data' => array(
856
-						'message' => (string)$this->l10n->t('Unable to change mail address')
857
-					)
858
-				),
859
-				Http::STATUS_FORBIDDEN
860
-			);
861
-		}
862
-
863
-		$userData = $this->accountManager->getUser($user);
864
-		$userData[AccountManager::PROPERTY_EMAIL]['value'] = $mailAddress;
865
-
866
-		try {
867
-			$this->saveUserSettings($user, $userData);
868
-			return new DataResponse(
869
-				array(
870
-					'status' => 'success',
871
-					'data' => array(
872
-						'username' => $id,
873
-						'mailAddress' => $mailAddress,
874
-						'message' => (string)$this->l10n->t('Email saved')
875
-					)
876
-				),
877
-				Http::STATUS_OK
878
-			);
879
-		} catch (ForbiddenException $e) {
880
-			return new DataResponse([
881
-				'status' => 'error',
882
-				'data' => [
883
-					'message' => $e->getMessage()
884
-				],
885
-			]);
886
-		}
887
-	}
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 \OC_Defaults */
76
+    private $defaults;
77
+    /** @var IMailer */
78
+    private $mailer;
79
+    /** @var string */
80
+    private $fromMailAddress;
81
+    /** @var IURLGenerator */
82
+    private $urlGenerator;
83
+    /** @var bool contains the state of the encryption app */
84
+    private $isEncryptionAppEnabled;
85
+    /** @var bool contains the state of the admin recovery setting */
86
+    private $isRestoreEnabled = false;
87
+    /** @var IAvatarManager */
88
+    private $avatarManager;
89
+    /** @var AccountManager */
90
+    private $accountManager;
91
+    /** @var ISecureRandom */
92
+    private $secureRandom;
93
+    /** @var ITimeFactory */
94
+    private $timeFactory;
95
+    /** @var ICrypto */
96
+    private $crypto;
97
+
98
+
99
+    /**
100
+     * @param string $appName
101
+     * @param IRequest $request
102
+     * @param IUserManager $userManager
103
+     * @param IGroupManager $groupManager
104
+     * @param IUserSession $userSession
105
+     * @param IConfig $config
106
+     * @param bool $isAdmin
107
+     * @param IL10N $l10n
108
+     * @param ILogger $log
109
+     * @param \OC_Defaults $defaults
110
+     * @param IMailer $mailer
111
+     * @param string $fromMailAddress
112
+     * @param IURLGenerator $urlGenerator
113
+     * @param IAppManager $appManager
114
+     * @param IAvatarManager $avatarManager
115
+     * @param AccountManager $accountManager
116
+     * @param ISecureRandom $secureRandom
117
+     * @param ITimeFactory $timeFactory
118
+     * @param ICrypto $crypto
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
+                                \OC_Defaults $defaults,
130
+                                IMailer $mailer,
131
+                                $fromMailAddress,
132
+                                IURLGenerator $urlGenerator,
133
+                                IAppManager $appManager,
134
+                                IAvatarManager $avatarManager,
135
+                                AccountManager $accountManager,
136
+                                ISecureRandom $secureRandom,
137
+                                ITimeFactory $timeFactory,
138
+                                ICrypto $crypto) {
139
+        parent::__construct($appName, $request);
140
+        $this->userManager = $userManager;
141
+        $this->groupManager = $groupManager;
142
+        $this->userSession = $userSession;
143
+        $this->config = $config;
144
+        $this->isAdmin = $isAdmin;
145
+        $this->l10n = $l10n;
146
+        $this->log = $log;
147
+        $this->defaults = $defaults;
148
+        $this->mailer = $mailer;
149
+        $this->fromMailAddress = $fromMailAddress;
150
+        $this->urlGenerator = $urlGenerator;
151
+        $this->avatarManager = $avatarManager;
152
+        $this->accountManager = $accountManager;
153
+        $this->secureRandom = $secureRandom;
154
+        $this->timeFactory = $timeFactory;
155
+        $this->crypto = $crypto;
156
+
157
+        // check for encryption state - TODO see formatUserForIndex
158
+        $this->isEncryptionAppEnabled = $appManager->isEnabledForUser('encryption');
159
+        if($this->isEncryptionAppEnabled) {
160
+            // putting this directly in empty is possible in PHP 5.5+
161
+            $result = $config->getAppValue('encryption', 'recoveryAdminEnabled', 0);
162
+            $this->isRestoreEnabled = !empty($result);
163
+        }
164
+    }
165
+
166
+    /**
167
+     * @param IUser $user
168
+     * @param array $userGroups
169
+     * @return array
170
+     */
171
+    private function formatUserForIndex(IUser $user, array $userGroups = null) {
172
+
173
+        // TODO: eliminate this encryption specific code below and somehow
174
+        // hook in additional user info from other apps
175
+
176
+        // recovery isn't possible if admin or user has it disabled and encryption
177
+        // is enabled - so we eliminate the else paths in the conditional tree
178
+        // below
179
+        $restorePossible = false;
180
+
181
+        if ($this->isEncryptionAppEnabled) {
182
+            if ($this->isRestoreEnabled) {
183
+                // check for the users recovery setting
184
+                $recoveryMode = $this->config->getUserValue($user->getUID(), 'encryption', 'recoveryEnabled', '0');
185
+                // method call inside empty is possible with PHP 5.5+
186
+                $recoveryModeEnabled = !empty($recoveryMode);
187
+                if ($recoveryModeEnabled) {
188
+                    // user also has recovery mode enabled
189
+                    $restorePossible = true;
190
+                }
191
+            }
192
+        } else {
193
+            // recovery is possible if encryption is disabled (plain files are
194
+            // available)
195
+            $restorePossible = true;
196
+        }
197
+
198
+        $subAdminGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($user);
199
+        foreach($subAdminGroups as $key => $subAdminGroup) {
200
+            $subAdminGroups[$key] = $subAdminGroup->getGID();
201
+        }
202
+
203
+        $displayName = $user->getEMailAddress();
204
+        if (is_null($displayName)) {
205
+            $displayName = '';
206
+        }
207
+
208
+        $avatarAvailable = false;
209
+        try {
210
+            $avatarAvailable = $this->avatarManager->getAvatar($user->getUID())->exists();
211
+        } catch (\Exception $e) {
212
+            //No avatar yet
213
+        }
214
+
215
+        return [
216
+            'name' => $user->getUID(),
217
+            'displayname' => $user->getDisplayName(),
218
+            'groups' => (empty($userGroups)) ? $this->groupManager->getUserGroupIds($user) : $userGroups,
219
+            'subadmin' => $subAdminGroups,
220
+            'quota' => $user->getQuota(),
221
+            'storageLocation' => $user->getHome(),
222
+            'lastLogin' => $user->getLastLogin() * 1000,
223
+            'backend' => $user->getBackendClassName(),
224
+            'email' => $displayName,
225
+            'isRestoreDisabled' => !$restorePossible,
226
+            'isAvatarAvailable' => $avatarAvailable,
227
+        ];
228
+    }
229
+
230
+    /**
231
+     * @param array $userIDs Array with schema [$uid => $displayName]
232
+     * @return IUser[]
233
+     */
234
+    private function getUsersForUID(array $userIDs) {
235
+        $users = [];
236
+        foreach ($userIDs as $uid => $displayName) {
237
+            $users[$uid] = $this->userManager->get($uid);
238
+        }
239
+        return $users;
240
+    }
241
+
242
+    /**
243
+     * @NoAdminRequired
244
+     *
245
+     * @param int $offset
246
+     * @param int $limit
247
+     * @param string $gid GID to filter for
248
+     * @param string $pattern Pattern to search for in the username
249
+     * @param string $backend Backend to filter for (class-name)
250
+     * @return DataResponse
251
+     *
252
+     * TODO: Tidy up and write unit tests - code is mainly static method calls
253
+     */
254
+    public function index($offset = 0, $limit = 10, $gid = '', $pattern = '', $backend = '') {
255
+        // FIXME: The JS sends the group '_everyone' instead of no GID for the "all users" group.
256
+        if($gid === '_everyone') {
257
+            $gid = '';
258
+        }
259
+
260
+        // Remove backends
261
+        if(!empty($backend)) {
262
+            $activeBackends = $this->userManager->getBackends();
263
+            $this->userManager->clearBackends();
264
+            foreach($activeBackends as $singleActiveBackend) {
265
+                if($backend === get_class($singleActiveBackend)) {
266
+                    $this->userManager->registerBackend($singleActiveBackend);
267
+                    break;
268
+                }
269
+            }
270
+        }
271
+
272
+        $users = [];
273
+        if ($this->isAdmin) {
274
+
275
+            if($gid !== '') {
276
+                $batch = $this->getUsersForUID($this->groupManager->displayNamesInGroup($gid, $pattern, $limit, $offset));
277
+            } else {
278
+                $batch = $this->userManager->search($pattern, $limit, $offset);
279
+            }
280
+
281
+            foreach ($batch as $user) {
282
+                $users[] = $this->formatUserForIndex($user);
283
+            }
284
+
285
+        } else {
286
+            $subAdminOfGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($this->userSession->getUser());
287
+            // New class returns IGroup[] so convert back
288
+            $gids = [];
289
+            foreach ($subAdminOfGroups as $group) {
290
+                $gids[] = $group->getGID();
291
+            }
292
+            $subAdminOfGroups = $gids;
293
+
294
+            // Set the $gid parameter to an empty value if the subadmin has no rights to access a specific group
295
+            if($gid !== '' && !in_array($gid, $subAdminOfGroups)) {
296
+                $gid = '';
297
+            }
298
+
299
+            // Batch all groups the user is subadmin of when a group is specified
300
+            $batch = [];
301
+            if($gid === '') {
302
+                foreach($subAdminOfGroups as $group) {
303
+                    $groupUsers = $this->groupManager->displayNamesInGroup($group, $pattern, $limit, $offset);
304
+
305
+                    foreach($groupUsers as $uid => $displayName) {
306
+                        $batch[$uid] = $displayName;
307
+                    }
308
+                }
309
+            } else {
310
+                $batch = $this->groupManager->displayNamesInGroup($gid, $pattern, $limit, $offset);
311
+            }
312
+            $batch = $this->getUsersForUID($batch);
313
+
314
+            foreach ($batch as $user) {
315
+                // Only add the groups, this user is a subadmin of
316
+                $userGroups = array_values(array_intersect(
317
+                    $this->groupManager->getUserGroupIds($user),
318
+                    $subAdminOfGroups
319
+                ));
320
+                $users[] = $this->formatUserForIndex($user, $userGroups);
321
+            }
322
+        }
323
+
324
+        return new DataResponse($users);
325
+    }
326
+
327
+    /**
328
+     * @NoAdminRequired
329
+     * @PasswordConfirmationRequired
330
+     *
331
+     * @param string $username
332
+     * @param string $password
333
+     * @param array $groups
334
+     * @param string $email
335
+     * @return DataResponse
336
+     */
337
+    public function create($username, $password, array $groups=array(), $email='') {
338
+        if($email !== '' && !$this->mailer->validateMailAddress($email)) {
339
+            return new DataResponse(
340
+                array(
341
+                    'message' => (string)$this->l10n->t('Invalid mail address')
342
+                ),
343
+                Http::STATUS_UNPROCESSABLE_ENTITY
344
+            );
345
+        }
346
+
347
+        $currentUser = $this->userSession->getUser();
348
+
349
+        if (!$this->isAdmin) {
350
+            if (!empty($groups)) {
351
+                foreach ($groups as $key => $group) {
352
+                    $groupObject = $this->groupManager->get($group);
353
+                    if($groupObject === null) {
354
+                        unset($groups[$key]);
355
+                        continue;
356
+                    }
357
+
358
+                    if (!$this->groupManager->getSubAdmin()->isSubAdminofGroup($currentUser, $groupObject)) {
359
+                        unset($groups[$key]);
360
+                    }
361
+                }
362
+            }
363
+
364
+            if (empty($groups)) {
365
+                return new DataResponse(
366
+                    array(
367
+                        'message' => $this->l10n->t('No valid group selected'),
368
+                    ),
369
+                    Http::STATUS_FORBIDDEN
370
+                );
371
+            }
372
+        }
373
+
374
+        if ($this->userManager->userExists($username)) {
375
+            return new DataResponse(
376
+                array(
377
+                    'message' => (string)$this->l10n->t('A user with that name already exists.')
378
+                ),
379
+                Http::STATUS_CONFLICT
380
+            );
381
+        }
382
+
383
+        $generatedPassword = false;
384
+        if ($password === '') {
385
+            if ($email === '') {
386
+                return new DataResponse(
387
+                    array(
388
+                        'message' => (string)$this->l10n->t('To send a password link to the user an email address is required.')
389
+                    ),
390
+                    Http::STATUS_UNPROCESSABLE_ENTITY
391
+                );
392
+            }
393
+
394
+            $password = $this->secureRandom->generate(32);
395
+            $generatedPassword = true;
396
+        }
397
+
398
+        try {
399
+            $user = $this->userManager->createUser($username, $password);
400
+        } catch (\Exception $exception) {
401
+            $message = $exception->getMessage();
402
+            if (!$message) {
403
+                $message = $this->l10n->t('Unable to create user.');
404
+            }
405
+            return new DataResponse(
406
+                array(
407
+                    'message' => (string) $message,
408
+                ),
409
+                Http::STATUS_FORBIDDEN
410
+            );
411
+        }
412
+
413
+        if($user instanceof IUser) {
414
+            if($groups !== null) {
415
+                foreach($groups as $groupName) {
416
+                    $group = $this->groupManager->get($groupName);
417
+
418
+                    if(empty($group)) {
419
+                        $group = $this->groupManager->createGroup($groupName);
420
+                    }
421
+                    $group->addUser($user);
422
+                }
423
+            }
424
+            /**
425
+             * Send new user mail only if a mail is set
426
+             */
427
+            if($email !== '') {
428
+                $user->setEMailAddress($email);
429
+
430
+                if ($generatedPassword) {
431
+                    $token = $this->secureRandom->generate(
432
+                        21,
433
+                        ISecureRandom::CHAR_DIGITS .
434
+                        ISecureRandom::CHAR_LOWER .
435
+                        ISecureRandom::CHAR_UPPER
436
+                    );
437
+                    $tokenValue = $this->timeFactory->getTime() . ':' . $token;
438
+                    $mailAddress = !is_null($user->getEMailAddress()) ? $user->getEMailAddress() : '';
439
+                    $encryptedValue = $this->crypto->encrypt($tokenValue, $mailAddress . $this->config->getSystemValue('secret'));
440
+                    $this->config->setUserValue($username, 'core', 'lostpassword', $encryptedValue);
441
+
442
+                    $link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', ['userId' => $username, 'token' => $token]);
443
+                } else {
444
+                    $link = $this->urlGenerator->getAbsoluteURL('/');
445
+                }
446
+
447
+                $emailTemplate = new EMailTemplate($this->defaults);
448
+
449
+                $emailTemplate->addHeader($this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('', 'logo-mail-header.png')));
450
+
451
+                $displayName = $user->getDisplayName();
452
+                if ($displayName === $username) {
453
+                    $emailTemplate->addHeading($this->l10n->t('Welcome aboard'));
454
+                } else {
455
+                    $emailTemplate->addHeading($this->l10n->t('Welcome aboard %s', [$displayName]));
456
+                }
457
+                $emailTemplate->addBodyText($this->l10n->t('You have now an %s account, you can add, protect, and share your data.', [$this->defaults->getName()]));
458
+                $emailTemplate->addBodyText($this->l10n->t('Your username is: %s', [$username]));
459
+
460
+                if ($generatedPassword) {
461
+                    $leftButtonText = $this->l10n->t('Set your password');
462
+                } else {
463
+                    $leftButtonText = $this->l10n->t('Go to %s', [$this->defaults->getName()]);
464
+                }
465
+
466
+                $emailTemplate->addBodyButtonGroup(
467
+                    $leftButtonText,
468
+                    $link,
469
+                    $this->l10n->t('Install Client'),
470
+                    'https://nextcloud.com/install/#install-clients'
471
+                );
472
+
473
+                $emailTemplate->addFooter(
474
+                    $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('', 'logo-mail-footer.png')),
475
+                    $this->defaults->getName() . ' - ' . $this->defaults->getSlogan() . '<br>' . $this->l10n->t('This is an automatically generated email, please do not reply.')
476
+                );
477
+
478
+                $mailContent = $emailTemplate->renderHTML();
479
+                $plainTextMailContent = $emailTemplate->renderText();
480
+
481
+                $subject = $this->l10n->t('Your %s account was created', [$this->defaults->getName()]);
482
+
483
+                try {
484
+                    $message = $this->mailer->createMessage();
485
+                    $message->setTo([$email => $username]);
486
+                    $message->setSubject($subject);
487
+                    $message->setHtmlBody($mailContent);
488
+                    $message->setPlainBody($plainTextMailContent);
489
+                    $message->setFrom([$this->fromMailAddress => $this->defaults->getName()]);
490
+                    $this->mailer->send($message);
491
+                } catch(\Exception $e) {
492
+                    $this->log->error("Can't send new user mail to $email: " . $e->getMessage(), array('app' => 'settings'));
493
+                }
494
+            }
495
+            // fetch users groups
496
+            $userGroups = $this->groupManager->getUserGroupIds($user);
497
+
498
+            return new DataResponse(
499
+                $this->formatUserForIndex($user, $userGroups),
500
+                Http::STATUS_CREATED
501
+            );
502
+        }
503
+
504
+        return new DataResponse(
505
+            array(
506
+                'message' => (string)$this->l10n->t('Unable to create user.')
507
+            ),
508
+            Http::STATUS_FORBIDDEN
509
+        );
510
+
511
+    }
512
+
513
+    /**
514
+     * @NoAdminRequired
515
+     * @PasswordConfirmationRequired
516
+     *
517
+     * @param string $id
518
+     * @return DataResponse
519
+     */
520
+    public function destroy($id) {
521
+        $userId = $this->userSession->getUser()->getUID();
522
+        $user = $this->userManager->get($id);
523
+
524
+        if($userId === $id) {
525
+            return new DataResponse(
526
+                array(
527
+                    'status' => 'error',
528
+                    'data' => array(
529
+                        'message' => (string)$this->l10n->t('Unable to delete user.')
530
+                    )
531
+                ),
532
+                Http::STATUS_FORBIDDEN
533
+            );
534
+        }
535
+
536
+        if(!$this->isAdmin && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)) {
537
+            return new DataResponse(
538
+                array(
539
+                    'status' => 'error',
540
+                    'data' => array(
541
+                        'message' => (string)$this->l10n->t('Authentication error')
542
+                    )
543
+                ),
544
+                Http::STATUS_FORBIDDEN
545
+            );
546
+        }
547
+
548
+        if($user) {
549
+            if($user->delete()) {
550
+                return new DataResponse(
551
+                    array(
552
+                        'status' => 'success',
553
+                        'data' => array(
554
+                            'username' => $id
555
+                        )
556
+                    ),
557
+                    Http::STATUS_NO_CONTENT
558
+                );
559
+            }
560
+        }
561
+
562
+        return new DataResponse(
563
+            array(
564
+                'status' => 'error',
565
+                'data' => array(
566
+                    'message' => (string)$this->l10n->t('Unable to delete user.')
567
+                )
568
+            ),
569
+            Http::STATUS_FORBIDDEN
570
+        );
571
+    }
572
+
573
+    /**
574
+     * @NoAdminRequired
575
+     * @NoSubadminRequired
576
+     * @PasswordConfirmationRequired
577
+     *
578
+     * @param string $avatarScope
579
+     * @param string $displayname
580
+     * @param string $displaynameScope
581
+     * @param string $phone
582
+     * @param string $phoneScope
583
+     * @param string $email
584
+     * @param string $emailScope
585
+     * @param string $website
586
+     * @param string $websiteScope
587
+     * @param string $address
588
+     * @param string $addressScope
589
+     * @param string $twitter
590
+     * @param string $twitterScope
591
+     * @return DataResponse
592
+     */
593
+    public function setUserSettings($avatarScope,
594
+                                    $displayname,
595
+                                    $displaynameScope,
596
+                                    $phone,
597
+                                    $phoneScope,
598
+                                    $email,
599
+                                    $emailScope,
600
+                                    $website,
601
+                                    $websiteScope,
602
+                                    $address,
603
+                                    $addressScope,
604
+                                    $twitter,
605
+                                    $twitterScope
606
+    ) {
607
+
608
+        if(!empty($email) && !$this->mailer->validateMailAddress($email)) {
609
+            return new DataResponse(
610
+                array(
611
+                    'status' => 'error',
612
+                    'data' => array(
613
+                        'message' => (string)$this->l10n->t('Invalid mail address')
614
+                    )
615
+                ),
616
+                Http::STATUS_UNPROCESSABLE_ENTITY
617
+            );
618
+        }
619
+
620
+        $data = [
621
+            AccountManager::PROPERTY_AVATAR =>  ['scope' => $avatarScope],
622
+            AccountManager::PROPERTY_DISPLAYNAME => ['value' => $displayname, 'scope' => $displaynameScope],
623
+            AccountManager::PROPERTY_EMAIL=> ['value' => $email, 'scope' => $emailScope],
624
+            AccountManager::PROPERTY_WEBSITE => ['value' => $website, 'scope' => $websiteScope],
625
+            AccountManager::PROPERTY_ADDRESS => ['value' => $address, 'scope' => $addressScope],
626
+            AccountManager::PROPERTY_PHONE => ['value' => $phone, 'scope' => $phoneScope],
627
+            AccountManager::PROPERTY_TWITTER => ['value' => $twitter, 'scope' => $twitterScope]
628
+        ];
629
+
630
+        $user = $this->userSession->getUser();
631
+
632
+        try {
633
+            $this->saveUserSettings($user, $data);
634
+            return new DataResponse(
635
+                array(
636
+                    'status' => 'success',
637
+                    'data' => array(
638
+                        'userId' => $user->getUID(),
639
+                        'avatarScope' => $avatarScope,
640
+                        'displayname' => $displayname,
641
+                        'displaynameScope' => $displaynameScope,
642
+                        'email' => $email,
643
+                        'emailScope' => $emailScope,
644
+                        'website' => $website,
645
+                        'websiteScope' => $websiteScope,
646
+                        'address' => $address,
647
+                        'addressScope' => $addressScope,
648
+                        'message' => (string)$this->l10n->t('Settings saved')
649
+                    )
650
+                ),
651
+                Http::STATUS_OK
652
+            );
653
+        } catch (ForbiddenException $e) {
654
+            return new DataResponse([
655
+                'status' => 'error',
656
+                'data' => [
657
+                    'message' => $e->getMessage()
658
+                ],
659
+            ]);
660
+        }
661
+
662
+    }
663
+
664
+
665
+    /**
666
+     * update account manager with new user data
667
+     *
668
+     * @param IUser $user
669
+     * @param array $data
670
+     * @throws ForbiddenException
671
+     */
672
+    protected function saveUserSettings(IUser $user, $data) {
673
+
674
+        // keep the user back-end up-to-date with the latest display name and email
675
+        // address
676
+        $oldDisplayName = $user->getDisplayName();
677
+        $oldDisplayName = is_null($oldDisplayName) ? '' : $oldDisplayName;
678
+        if (isset($data[AccountManager::PROPERTY_DISPLAYNAME]['value'])
679
+            && $oldDisplayName !== $data[AccountManager::PROPERTY_DISPLAYNAME]['value']
680
+        ) {
681
+            $result = $user->setDisplayName($data[AccountManager::PROPERTY_DISPLAYNAME]['value']);
682
+            if ($result === false) {
683
+                throw new ForbiddenException($this->l10n->t('Unable to change full name'));
684
+            }
685
+        }
686
+
687
+        $oldEmailAddress = $user->getEMailAddress();
688
+        $oldEmailAddress = is_null($oldEmailAddress) ? '' : $oldEmailAddress;
689
+        if (isset($data[AccountManager::PROPERTY_EMAIL]['value'])
690
+            && $oldEmailAddress !== $data[AccountManager::PROPERTY_EMAIL]['value']
691
+        ) {
692
+            // this is the only permission a backend provides and is also used
693
+            // for the permission of setting a email address
694
+            if (!$user->canChangeDisplayName()) {
695
+                throw new ForbiddenException($this->l10n->t('Unable to change email address'));
696
+            }
697
+            $user->setEMailAddress($data[AccountManager::PROPERTY_EMAIL]['value']);
698
+        }
699
+
700
+        $this->accountManager->updateUser($user, $data);
701
+    }
702
+
703
+    /**
704
+     * Count all unique users visible for the current admin/subadmin.
705
+     *
706
+     * @NoAdminRequired
707
+     *
708
+     * @return DataResponse
709
+     */
710
+    public function stats() {
711
+        $userCount = 0;
712
+        if ($this->isAdmin) {
713
+            $countByBackend = $this->userManager->countUsers();
714
+
715
+            if (!empty($countByBackend)) {
716
+                foreach ($countByBackend as $count) {
717
+                    $userCount += $count;
718
+                }
719
+            }
720
+        } else {
721
+            $groups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($this->userSession->getUser());
722
+
723
+            $uniqueUsers = [];
724
+            foreach ($groups as $group) {
725
+                foreach($group->getUsers() as $uid => $displayName) {
726
+                    $uniqueUsers[$uid] = true;
727
+                }
728
+            }
729
+
730
+            $userCount = count($uniqueUsers);
731
+        }
732
+
733
+        return new DataResponse(
734
+            [
735
+                'totalUsers' => $userCount
736
+            ]
737
+        );
738
+    }
739
+
740
+
741
+    /**
742
+     * Set the displayName of a user
743
+     *
744
+     * @NoAdminRequired
745
+     * @NoSubadminRequired
746
+     * @PasswordConfirmationRequired
747
+     * @todo merge into saveUserSettings
748
+     *
749
+     * @param string $username
750
+     * @param string $displayName
751
+     * @return DataResponse
752
+     */
753
+    public function setDisplayName($username, $displayName) {
754
+        $currentUser = $this->userSession->getUser();
755
+        $user = $this->userManager->get($username);
756
+
757
+        if ($user === null ||
758
+            !$user->canChangeDisplayName() ||
759
+            (
760
+                !$this->groupManager->isAdmin($currentUser->getUID()) &&
761
+                !$this->groupManager->getSubAdmin()->isUserAccessible($currentUser, $user) &&
762
+                $currentUser->getUID() !== $username
763
+
764
+            )
765
+        ) {
766
+            return new DataResponse([
767
+                'status' => 'error',
768
+                'data' => [
769
+                    'message' => $this->l10n->t('Authentication error'),
770
+                ],
771
+            ]);
772
+        }
773
+
774
+        $userData = $this->accountManager->getUser($user);
775
+        $userData[AccountManager::PROPERTY_DISPLAYNAME]['value'] = $displayName;
776
+
777
+
778
+        try {
779
+            $this->saveUserSettings($user, $userData);
780
+            return new DataResponse([
781
+                'status' => 'success',
782
+                'data' => [
783
+                    'message' => $this->l10n->t('Your full name has been changed.'),
784
+                    'username' => $username,
785
+                    'displayName' => $displayName,
786
+                ],
787
+            ]);
788
+        } catch (ForbiddenException $e) {
789
+            return new DataResponse([
790
+                'status' => 'error',
791
+                'data' => [
792
+                    'message' => $e->getMessage(),
793
+                    'displayName' => $user->getDisplayName(),
794
+                ],
795
+            ]);
796
+        }
797
+    }
798
+
799
+    /**
800
+     * Set the mail address of a user
801
+     *
802
+     * @NoAdminRequired
803
+     * @NoSubadminRequired
804
+     * @PasswordConfirmationRequired
805
+     *
806
+     * @param string $id
807
+     * @param string $mailAddress
808
+     * @return DataResponse
809
+     */
810
+    public function setEMailAddress($id, $mailAddress) {
811
+        $user = $this->userManager->get($id);
812
+        if (!$this->isAdmin
813
+            && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)
814
+        ) {
815
+            return new DataResponse(
816
+                array(
817
+                    'status' => 'error',
818
+                    'data' => array(
819
+                        'message' => (string)$this->l10n->t('Forbidden')
820
+                    )
821
+                ),
822
+                Http::STATUS_FORBIDDEN
823
+            );
824
+        }
825
+
826
+        if($mailAddress !== '' && !$this->mailer->validateMailAddress($mailAddress)) {
827
+            return new DataResponse(
828
+                array(
829
+                    'status' => 'error',
830
+                    'data' => array(
831
+                        'message' => (string)$this->l10n->t('Invalid mail address')
832
+                    )
833
+                ),
834
+                Http::STATUS_UNPROCESSABLE_ENTITY
835
+            );
836
+        }
837
+
838
+        if (!$user) {
839
+            return new DataResponse(
840
+                array(
841
+                    'status' => 'error',
842
+                    'data' => array(
843
+                        'message' => (string)$this->l10n->t('Invalid user')
844
+                    )
845
+                ),
846
+                Http::STATUS_UNPROCESSABLE_ENTITY
847
+            );
848
+        }
849
+        // this is the only permission a backend provides and is also used
850
+        // for the permission of setting a email address
851
+        if (!$user->canChangeDisplayName()) {
852
+            return new DataResponse(
853
+                array(
854
+                    'status' => 'error',
855
+                    'data' => array(
856
+                        'message' => (string)$this->l10n->t('Unable to change mail address')
857
+                    )
858
+                ),
859
+                Http::STATUS_FORBIDDEN
860
+            );
861
+        }
862
+
863
+        $userData = $this->accountManager->getUser($user);
864
+        $userData[AccountManager::PROPERTY_EMAIL]['value'] = $mailAddress;
865
+
866
+        try {
867
+            $this->saveUserSettings($user, $userData);
868
+            return new DataResponse(
869
+                array(
870
+                    'status' => 'success',
871
+                    'data' => array(
872
+                        'username' => $id,
873
+                        'mailAddress' => $mailAddress,
874
+                        'message' => (string)$this->l10n->t('Email saved')
875
+                    )
876
+                ),
877
+                Http::STATUS_OK
878
+            );
879
+        } catch (ForbiddenException $e) {
880
+            return new DataResponse([
881
+                'status' => 'error',
882
+                'data' => [
883
+                    'message' => $e->getMessage()
884
+                ],
885
+            ]);
886
+        }
887
+    }
888 888
 
889 889
 }
Please login to merge, or discard this patch.
lib/private/Mail/IEMailTemplate.php 1 patch
Indentation   +46 added lines, -46 removed lines patch added patch discarded remove patch
@@ -52,56 +52,56 @@
 block discarded – undo
52 52
  * $plainContent = $emailTemplate->renderText();
53 53
  */
54 54
 interface IEMailTemplate {
55
-	/**
56
-	 * Adds a header to the email
57
-	 *
58
-	 * @param string $logoUrl
59
-	 */
60
-	public function addHeader($logoUrl);
55
+    /**
56
+     * Adds a header to the email
57
+     *
58
+     * @param string $logoUrl
59
+     */
60
+    public function addHeader($logoUrl);
61 61
 
62
-	/**
63
-	 * Adds a heading to the email
64
-	 *
65
-	 * @param string $title
66
-	 */
67
-	public function addHeading($title);
62
+    /**
63
+     * Adds a heading to the email
64
+     *
65
+     * @param string $title
66
+     */
67
+    public function addHeading($title);
68 68
 
69
-	/**
70
-	 * Adds a paragraph to the body of the email
71
-	 *
72
-	 * @param string $text
73
-	 */
74
-	public function addBodyText($text);
69
+    /**
70
+     * Adds a paragraph to the body of the email
71
+     *
72
+     * @param string $text
73
+     */
74
+    public function addBodyText($text);
75 75
 
76
-	/**
77
-	 * Adds a button group of two buttons to the body of the email
78
-	 *
79
-	 * @param string $textLeft Text of left button
80
-	 * @param string $urlLeft URL of left button
81
-	 * @param string $textRight Text of right button
82
-	 * @param string $urlRight URL of right button
83
-	 */
84
-	public function addBodyButtonGroup($textLeft, $urlLeft, $textRight, $urlRight);
76
+    /**
77
+     * Adds a button group of two buttons to the body of the email
78
+     *
79
+     * @param string $textLeft Text of left button
80
+     * @param string $urlLeft URL of left button
81
+     * @param string $textRight Text of right button
82
+     * @param string $urlRight URL of right button
83
+     */
84
+    public function addBodyButtonGroup($textLeft, $urlLeft, $textRight, $urlRight);
85 85
 
86
-	/**
87
-	 * Adds a logo and a text to the footer. <br> in the text will be replaced by new lines in the plain text email
88
-	 *
89
-	 * @param string $logoUrl
90
-	 * @param string $text
91
-	 */
92
-	public function addFooter($logoUrl, $text);
86
+    /**
87
+     * Adds a logo and a text to the footer. <br> in the text will be replaced by new lines in the plain text email
88
+     *
89
+     * @param string $logoUrl
90
+     * @param string $text
91
+     */
92
+    public function addFooter($logoUrl, $text);
93 93
 
94
-	/**
95
-	 * Returns the rendered HTML email as string
96
-	 *
97
-	 * @return string
98
-	 */
99
-	public function renderHTML();
94
+    /**
95
+     * Returns the rendered HTML email as string
96
+     *
97
+     * @return string
98
+     */
99
+    public function renderHTML();
100 100
 
101
-	/**
102
-	 * Returns the rendered plain text email as string
103
-	 *
104
-	 * @return string
105
-	 */
106
-	public function renderText();
101
+    /**
102
+     * Returns the rendered plain text email as string
103
+     *
104
+     * @return string
105
+     */
106
+    public function renderText();
107 107
 }
108 108
\ No newline at end of file
Please login to merge, or discard this patch.
lib/private/Mail/EMailTemplate.php 2 patches
Indentation   +154 added lines, -154 removed lines patch added patch discarded remove patch
@@ -33,21 +33,21 @@  discard block
 block discarded – undo
33 33
  */
34 34
 class EMailTemplate implements IEMailTemplate {
35 35
 
36
-	/** @var \OC_Defaults */
37
-	protected $defaults;
38
-
39
-	/** @var string */
40
-	protected $htmlBody = '';
41
-	/** @var string */
42
-	protected $plainBody = '';
43
-	/** @var bool indicated if the footer is added */
44
-	protected $headerAdded = false;
45
-	/** @var bool indicated if the body is already opened */
46
-	protected $bodyOpened = false;
47
-	/** @var bool indicated if the footer is added */
48
-	protected $footerAdded = false;
49
-
50
-	protected $head = <<<EOF
36
+    /** @var \OC_Defaults */
37
+    protected $defaults;
38
+
39
+    /** @var string */
40
+    protected $htmlBody = '';
41
+    /** @var string */
42
+    protected $plainBody = '';
43
+    /** @var bool indicated if the footer is added */
44
+    protected $headerAdded = false;
45
+    /** @var bool indicated if the body is already opened */
46
+    protected $bodyOpened = false;
47
+    /** @var bool indicated if the footer is added */
48
+    protected $footerAdded = false;
49
+
50
+    protected $head = <<<EOF
51 51
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
52 52
 <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en" style="-webkit-font-smoothing:antialiased;background:#f3f3f3!important">
53 53
 <head>
@@ -65,7 +65,7 @@  discard block
 block discarded – undo
65 65
 				<center data-parsed="" style="min-width:580px;width:100%">
66 66
 EOF;
67 67
 
68
-	protected $tail = <<<EOF
68
+    protected $tail = <<<EOF
69 69
 					</center>
70 70
 				</td>
71 71
 			</tr>
@@ -76,7 +76,7 @@  discard block
 block discarded – undo
76 76
 </html>
77 77
 EOF;
78 78
 
79
-	protected $header = <<<EOF
79
+    protected $header = <<<EOF
80 80
 <table align="center" class="wrapper header float-center" style="Margin:0 auto;background:#8a8a8a;background-color:%s;border-collapse:collapse;border-spacing:0;float:none;margin:0 auto;padding:0;text-align:center;vertical-align:top;width:100%%">
81 81
 	<tr style="padding:0;text-align:left;vertical-align:top">
82 82
 		<td class="wrapper-inner" style="-moz-hyphens:auto;-webkit-hyphens:auto;Margin:0;border-collapse:collapse!important;color:#0a0a0a;font-family:Lucida Grande,Geneva,Verdana,sans-serif;font-size:16px;font-weight:400;hyphens:auto;line-height:1.3;margin:0;padding:20px;text-align:left;vertical-align:top;word-wrap:break-word">
@@ -109,7 +109,7 @@  discard block
 block discarded – undo
109 109
 </table>
110 110
 EOF;
111 111
 
112
-	protected $heading = <<<EOF
112
+    protected $heading = <<<EOF
113 113
 <table align="center" class="container main-heading float-center" style="Margin:0 auto;background:0 0!important;border-collapse:collapse;border-spacing:0;float:none;margin:0 auto;padding:0;text-align:center;vertical-align:top;width:580px">
114 114
 	<tbody>
115 115
 	<tr style="padding:0;text-align:left;vertical-align:top">
@@ -128,7 +128,7 @@  discard block
 block discarded – undo
128 128
 </table>
129 129
 EOF;
130 130
 
131
-	protected $bodyBegin = <<<EOF
131
+    protected $bodyBegin = <<<EOF
132 132
 <table align="center" class="wrapper content float-center" style="Margin:0 auto;border-collapse:collapse;border-spacing:0;float:none;margin:0 auto;padding:0;text-align:center;vertical-align:top;width:100%">
133 133
 	<tr style="padding:0;text-align:left;vertical-align:top">
134 134
 		<td class="wrapper-inner" style="-moz-hyphens:auto;-webkit-hyphens:auto;Margin:0;border-collapse:collapse!important;color:#0a0a0a;font-family:Lucida Grande,Geneva,Verdana,sans-serif;font-size:16px;font-weight:400;hyphens:auto;line-height:1.3;margin:0;padding:0;text-align:left;vertical-align:top;word-wrap:break-word">
@@ -145,7 +145,7 @@  discard block
 block discarded – undo
145 145
 						</table>
146 146
 EOF;
147 147
 
148
-	protected $bodyText = <<<EOF
148
+    protected $bodyText = <<<EOF
149 149
 <table class="row description" style="border-collapse:collapse;border-spacing:0;display:table;padding:0;position:relative;text-align:left;vertical-align:top;width:100%%">
150 150
 	<tbody>
151 151
 	<tr style="padding:0;text-align:left;vertical-align:top">
@@ -164,7 +164,7 @@  discard block
 block discarded – undo
164 164
 </table>
165 165
 EOF;
166 166
 
167
-	protected $buttonGroup = <<<EOF
167
+    protected $buttonGroup = <<<EOF
168 168
 <table class="spacer" style="border-collapse:collapse;border-spacing:0;padding:0;text-align:left;vertical-align:top;width:100%%">
169 169
 	<tbody>
170 170
 	<tr style="padding:0;text-align:left;vertical-align:top">
@@ -217,7 +217,7 @@  discard block
 block discarded – undo
217 217
 </table>
218 218
 EOF;
219 219
 
220
-	protected $bodyEnd = <<<EOF
220
+    protected $bodyEnd = <<<EOF
221 221
 
222 222
 					</td>
223 223
 				</tr>
@@ -228,7 +228,7 @@  discard block
 block discarded – undo
228 228
 </table>
229 229
 EOF;
230 230
 
231
-	protected $footer = <<<EOF
231
+    protected $footer = <<<EOF
232 232
 <table class="spacer float-center" style="Margin:0 auto;border-collapse:collapse;border-spacing:0;float:none;margin:0 auto;padding:0;text-align:center;vertical-align:top;width:100%%">
233 233
 	<tbody>
234 234
 	<tr style="padding:0;text-align:left;vertical-align:top">
@@ -256,136 +256,136 @@  discard block
 block discarded – undo
256 256
 EOF;
257 257
 
258 258
 
259
-	public function __construct(\OC_Defaults $defaults) {
260
-		$this->defaults = $defaults;
261
-
262
-		$this->htmlBody .= $this->head;
263
-	}
264
-
265
-	/**
266
-	 * Adds a header to the email
267
-	 *
268
-	 * @param string $logoUrl
269
-	 */
270
-	public function addHeader($logoUrl) {
271
-		if ($this->headerAdded) {
272
-			return;
273
-		}
274
-		$this->headerAdded = true;
275
-
276
-		$this->htmlBody .= vsprintf($this->header, [$this->defaults->getColorPrimary(), $logoUrl]);
277
-	}
278
-
279
-	/**
280
-	 * Adds a heading to the email
281
-	 *
282
-	 * @param string $title
283
-	 */
284
-	public function addHeading($title) {
285
-		if ($this->footerAdded) {
286
-			return;
287
-		}
288
-
289
-		$this->htmlBody .= vsprintf($this->heading, [$title]);
290
-		$this->plainBody .= $title . PHP_EOL . PHP_EOL;
291
-	}
292
-
293
-	/**
294
-	 * Adds a paragraph to the body of the email
295
-	 *
296
-	 * @param string $text
297
-	 */
298
-	public function addBodyText($text) {
299
-		if ($this->footerAdded) {
300
-			return;
301
-		}
302
-
303
-		if (!$this->bodyOpened) {
304
-			$this->htmlBody .= $this->bodyBegin;
305
-			$this->bodyOpened = true;
306
-		}
307
-
308
-		$this->htmlBody .= vsprintf($this->bodyText, [$text]);
309
-		$this->plainBody .= $text . PHP_EOL . PHP_EOL;
310
-	}
311
-
312
-	/**
313
-	 * Adds a button group of two buttons to the body of the email
314
-	 *
315
-	 * @param string $textLeft Text of left button
316
-	 * @param string $urlLeft URL of left button
317
-	 * @param string $textRight Text of right button
318
-	 * @param string $urlRight URL of right button
319
-	 */
320
-	public function addBodyButtonGroup($textLeft, $urlLeft, $textRight, $urlRight) {
321
-		if ($this->footerAdded) {
322
-			return;
323
-		}
324
-
325
-		if (!$this->bodyOpened) {
326
-			$this->htmlBody .= $this->bodyBegin;
327
-			$this->bodyOpened = true;
328
-		}
329
-
330
-		$color = $this->defaults->getColorPrimary();
331
-		$this->htmlBody .= vsprintf($this->buttonGroup, [$color, $color, $urlLeft, $color, $textLeft, $urlRight, $textRight]);
332
-		$this->plainBody .= $textLeft . ': ' . $urlLeft . PHP_EOL;
333
-		$this->plainBody .= $textRight . ': ' . $urlRight . PHP_EOL . PHP_EOL;
334
-
335
-	}
336
-
337
-	/**
338
-	 * Adds a logo and a text to the footer. <br> in the text will be replaced by new lines in the plain text email
339
-	 *
340
-	 * @param string $logoUrl
341
-	 * @param string $text
342
-	 */
343
-	public function addFooter($logoUrl, $text) {
344
-		if ($this->footerAdded) {
345
-			return;
346
-		}
347
-		$this->footerAdded = true;
348
-
349
-		if ($this->bodyOpened) {
350
-			$this->htmlBody .= $this->bodyEnd;
351
-			$this->bodyOpened = false;
352
-		}
353
-		$this->htmlBody .= vsprintf($this->footer, [$logoUrl, $text]);
354
-		$this->htmlBody .= $this->tail;
355
-		$this->plainBody .= '--' . PHP_EOL;
356
-		$this->plainBody .= str_replace('<br>', PHP_EOL, $text);
357
-	}
358
-
359
-	/**
360
-	 * Returns the rendered HTML email as string
361
-	 *
362
-	 * @return string
363
-	 */
364
-	public function renderHTML() {
365
-		if (!$this->footerAdded) {
366
-			$this->footerAdded = true;
367
-			if ($this->bodyOpened) {
368
-				$this->htmlBody .= $this->bodyEnd;
369
-			}
370
-			$this->htmlBody .= $this->tail;
371
-		}
372
-		return $this->htmlBody;
373
-	}
374
-
375
-	/**
376
-	 * Returns the rendered plain text email as string
377
-	 *
378
-	 * @return string
379
-	 */
380
-	public function renderText() {
381
-		if (!$this->footerAdded) {
382
-			$this->footerAdded = true;
383
-			if ($this->bodyOpened) {
384
-				$this->htmlBody .= $this->bodyEnd;
385
-			}
386
-			$this->htmlBody .= $this->tail;
387
-		}
388
-		return $this->plainBody;
389
-	}
259
+    public function __construct(\OC_Defaults $defaults) {
260
+        $this->defaults = $defaults;
261
+
262
+        $this->htmlBody .= $this->head;
263
+    }
264
+
265
+    /**
266
+     * Adds a header to the email
267
+     *
268
+     * @param string $logoUrl
269
+     */
270
+    public function addHeader($logoUrl) {
271
+        if ($this->headerAdded) {
272
+            return;
273
+        }
274
+        $this->headerAdded = true;
275
+
276
+        $this->htmlBody .= vsprintf($this->header, [$this->defaults->getColorPrimary(), $logoUrl]);
277
+    }
278
+
279
+    /**
280
+     * Adds a heading to the email
281
+     *
282
+     * @param string $title
283
+     */
284
+    public function addHeading($title) {
285
+        if ($this->footerAdded) {
286
+            return;
287
+        }
288
+
289
+        $this->htmlBody .= vsprintf($this->heading, [$title]);
290
+        $this->plainBody .= $title . PHP_EOL . PHP_EOL;
291
+    }
292
+
293
+    /**
294
+     * Adds a paragraph to the body of the email
295
+     *
296
+     * @param string $text
297
+     */
298
+    public function addBodyText($text) {
299
+        if ($this->footerAdded) {
300
+            return;
301
+        }
302
+
303
+        if (!$this->bodyOpened) {
304
+            $this->htmlBody .= $this->bodyBegin;
305
+            $this->bodyOpened = true;
306
+        }
307
+
308
+        $this->htmlBody .= vsprintf($this->bodyText, [$text]);
309
+        $this->plainBody .= $text . PHP_EOL . PHP_EOL;
310
+    }
311
+
312
+    /**
313
+     * Adds a button group of two buttons to the body of the email
314
+     *
315
+     * @param string $textLeft Text of left button
316
+     * @param string $urlLeft URL of left button
317
+     * @param string $textRight Text of right button
318
+     * @param string $urlRight URL of right button
319
+     */
320
+    public function addBodyButtonGroup($textLeft, $urlLeft, $textRight, $urlRight) {
321
+        if ($this->footerAdded) {
322
+            return;
323
+        }
324
+
325
+        if (!$this->bodyOpened) {
326
+            $this->htmlBody .= $this->bodyBegin;
327
+            $this->bodyOpened = true;
328
+        }
329
+
330
+        $color = $this->defaults->getColorPrimary();
331
+        $this->htmlBody .= vsprintf($this->buttonGroup, [$color, $color, $urlLeft, $color, $textLeft, $urlRight, $textRight]);
332
+        $this->plainBody .= $textLeft . ': ' . $urlLeft . PHP_EOL;
333
+        $this->plainBody .= $textRight . ': ' . $urlRight . PHP_EOL . PHP_EOL;
334
+
335
+    }
336
+
337
+    /**
338
+     * Adds a logo and a text to the footer. <br> in the text will be replaced by new lines in the plain text email
339
+     *
340
+     * @param string $logoUrl
341
+     * @param string $text
342
+     */
343
+    public function addFooter($logoUrl, $text) {
344
+        if ($this->footerAdded) {
345
+            return;
346
+        }
347
+        $this->footerAdded = true;
348
+
349
+        if ($this->bodyOpened) {
350
+            $this->htmlBody .= $this->bodyEnd;
351
+            $this->bodyOpened = false;
352
+        }
353
+        $this->htmlBody .= vsprintf($this->footer, [$logoUrl, $text]);
354
+        $this->htmlBody .= $this->tail;
355
+        $this->plainBody .= '--' . PHP_EOL;
356
+        $this->plainBody .= str_replace('<br>', PHP_EOL, $text);
357
+    }
358
+
359
+    /**
360
+     * Returns the rendered HTML email as string
361
+     *
362
+     * @return string
363
+     */
364
+    public function renderHTML() {
365
+        if (!$this->footerAdded) {
366
+            $this->footerAdded = true;
367
+            if ($this->bodyOpened) {
368
+                $this->htmlBody .= $this->bodyEnd;
369
+            }
370
+            $this->htmlBody .= $this->tail;
371
+        }
372
+        return $this->htmlBody;
373
+    }
374
+
375
+    /**
376
+     * Returns the rendered plain text email as string
377
+     *
378
+     * @return string
379
+     */
380
+    public function renderText() {
381
+        if (!$this->footerAdded) {
382
+            $this->footerAdded = true;
383
+            if ($this->bodyOpened) {
384
+                $this->htmlBody .= $this->bodyEnd;
385
+            }
386
+            $this->htmlBody .= $this->tail;
387
+        }
388
+        return $this->plainBody;
389
+    }
390 390
 }
391 391
 
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -287,7 +287,7 @@  discard block
 block discarded – undo
287 287
 		}
288 288
 
289 289
 		$this->htmlBody .= vsprintf($this->heading, [$title]);
290
-		$this->plainBody .= $title . PHP_EOL . PHP_EOL;
290
+		$this->plainBody .= $title.PHP_EOL.PHP_EOL;
291 291
 	}
292 292
 
293 293
 	/**
@@ -306,7 +306,7 @@  discard block
 block discarded – undo
306 306
 		}
307 307
 
308 308
 		$this->htmlBody .= vsprintf($this->bodyText, [$text]);
309
-		$this->plainBody .= $text . PHP_EOL . PHP_EOL;
309
+		$this->plainBody .= $text.PHP_EOL.PHP_EOL;
310 310
 	}
311 311
 
312 312
 	/**
@@ -329,8 +329,8 @@  discard block
 block discarded – undo
329 329
 
330 330
 		$color = $this->defaults->getColorPrimary();
331 331
 		$this->htmlBody .= vsprintf($this->buttonGroup, [$color, $color, $urlLeft, $color, $textLeft, $urlRight, $textRight]);
332
-		$this->plainBody .= $textLeft . ': ' . $urlLeft . PHP_EOL;
333
-		$this->plainBody .= $textRight . ': ' . $urlRight . PHP_EOL . PHP_EOL;
332
+		$this->plainBody .= $textLeft.': '.$urlLeft.PHP_EOL;
333
+		$this->plainBody .= $textRight.': '.$urlRight.PHP_EOL.PHP_EOL;
334 334
 
335 335
 	}
336 336
 
@@ -352,7 +352,7 @@  discard block
 block discarded – undo
352 352
 		}
353 353
 		$this->htmlBody .= vsprintf($this->footer, [$logoUrl, $text]);
354 354
 		$this->htmlBody .= $this->tail;
355
-		$this->plainBody .= '--' . PHP_EOL;
355
+		$this->plainBody .= '--'.PHP_EOL;
356 356
 		$this->plainBody .= str_replace('<br>', PHP_EOL, $text);
357 357
 	}
358 358
 
Please login to merge, or discard this patch.