Completed
Pull Request — master (#1234)
by Christoph
19:05 queued 04:48
created
settings/users.php 2 patches
Indentation   +38 added lines, -38 removed lines patch added patch discarded remove patch
@@ -46,13 +46,13 @@  discard block
 block discarded – undo
46 46
 $sortGroupsBy = \OC\Group\MetaData::SORT_USERCOUNT;
47 47
 
48 48
 if (\OC_App::isEnabled('user_ldap')) {
49
-	$isLDAPUsed =
50
-		   $groupManager->isBackendUsed('\OCA\User_LDAP\Group_LDAP')
51
-		|| $groupManager->isBackendUsed('\OCA\User_LDAP\Group_Proxy');
52
-	if ($isLDAPUsed) {
53
-		// LDAP user count can be slow, so we sort by group name here
54
-		$sortGroupsBy = \OC\Group\MetaData::SORT_GROUPNAME;
55
-	}
49
+    $isLDAPUsed =
50
+            $groupManager->isBackendUsed('\OCA\User_LDAP\Group_LDAP')
51
+        || $groupManager->isBackendUsed('\OCA\User_LDAP\Group_Proxy');
52
+    if ($isLDAPUsed) {
53
+        // LDAP user count can be slow, so we sort by group name here
54
+        $sortGroupsBy = \OC\Group\MetaData::SORT_GROUPNAME;
55
+    }
56 56
 }
57 57
 
58 58
 $config = \OC::$server->getConfig();
@@ -62,62 +62,62 @@  discard block
 block discarded – undo
62 62
 $isDisabled = !OC_User::isEnabled(OC_User::getUser());
63 63
 
64 64
 $groupsInfo = new \OC\Group\MetaData(
65
-	OC_User::getUser(),
66
-	$isAdmin,
67
-	$groupManager,
68
-	\OC::$server->getUserSession()
65
+    OC_User::getUser(),
66
+    $isAdmin,
67
+    $groupManager,
68
+    \OC::$server->getUserSession()
69 69
 );
70 70
 
71 71
 $groupsInfo->setSorting($sortGroupsBy);
72 72
 list($adminGroup, $groups) = $groupsInfo->get();
73 73
 
74 74
 $recoveryAdminEnabled = OC_App::isEnabled('encryption') &&
75
-					    $config->getAppValue( 'encryption', 'recoveryAdminEnabled', null );
75
+                        $config->getAppValue( 'encryption', 'recoveryAdminEnabled', null );
76 76
 
77 77
 if($isAdmin) {
78
-	$subAdmins = \OC::$server->getGroupManager()->getSubAdmin()->getAllSubAdmins();
79
-	// New class returns IUser[] so convert back
80
-	$result = [];
81
-	foreach ($subAdmins as $subAdmin) {
82
-		$result[] = [
83
-			'gid' => $subAdmin['group']->getGID(),
84
-			'uid' => $subAdmin['user']->getUID(),
85
-		];
86
-	}
87
-	$subAdmins = $result;
78
+    $subAdmins = \OC::$server->getGroupManager()->getSubAdmin()->getAllSubAdmins();
79
+    // New class returns IUser[] so convert back
80
+    $result = [];
81
+    foreach ($subAdmins as $subAdmin) {
82
+        $result[] = [
83
+            'gid' => $subAdmin['group']->getGID(),
84
+            'uid' => $subAdmin['user']->getUID(),
85
+        ];
86
+    }
87
+    $subAdmins = $result;
88 88
 }else{
89
-	/* Retrieve group IDs from $groups array, so we can pass that information into OC_Group::displayNamesInGroups() */
90
-	$gids = array();
91
-	foreach($groups as $group) {
92
-		if (isset($group['id'])) {
93
-			$gids[] = $group['id'];
94
-		}
95
-	}
96
-	$subAdmins = false;
89
+    /* Retrieve group IDs from $groups array, so we can pass that information into OC_Group::displayNamesInGroups() */
90
+    $gids = array();
91
+    foreach($groups as $group) {
92
+        if (isset($group['id'])) {
93
+            $gids[] = $group['id'];
94
+        }
95
+    }
96
+    $subAdmins = false;
97 97
 }
98 98
 $disabledUsers = 0;
99 99
 foreach (OC_User::getUsers() as $uid) {
100
-	if(!$userManager->get($uid)->isEnabled()) {
101
-		$disabledUsers++;
102
-	}
100
+    if(!$userManager->get($uid)->isEnabled()) {
101
+        $disabledUsers++;
102
+    }
103 103
 }
104 104
 $disabledUsersGroup = array(
105
-	'id' => '_disabledUsers',
106
-	'name' => '_disabledUsers',
107
-	'usercount' => $disabledUsers
105
+    'id' => '_disabledUsers',
106
+    'name' => '_disabledUsers',
107
+    'usercount' => $disabledUsers
108 108
 );
109 109
 
110 110
 // load preset quotas
111 111
 $quotaPreset=$config->getAppValue('files', 'quota_preset', '1 GB, 5 GB, 10 GB');
112 112
 $quotaPreset=explode(',', $quotaPreset);
113 113
 foreach($quotaPreset as &$preset) {
114
-	$preset=trim($preset);
114
+    $preset=trim($preset);
115 115
 }
116 116
 $quotaPreset=array_diff($quotaPreset, array('default', 'none'));
117 117
 
118 118
 $defaultQuota=$config->getAppValue('files', 'default_quota', 'none');
119 119
 $defaultQuotaIsUserDefined=array_search($defaultQuota, $quotaPreset)===false
120
-	&& array_search($defaultQuota, array('none', 'default'))===false;
120
+    && array_search($defaultQuota, array('none', 'default'))===false;
121 121
 
122 122
 \OC::$server->getEventDispatcher()->dispatch('OC\Settings\Users::loadAdditionalScripts');
123 123
 
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -72,9 +72,9 @@  discard block
 block discarded – undo
72 72
 list($adminGroup, $groups) = $groupsInfo->get();
73 73
 
74 74
 $recoveryAdminEnabled = OC_App::isEnabled('encryption') &&
75
-					    $config->getAppValue( 'encryption', 'recoveryAdminEnabled', null );
75
+					    $config->getAppValue('encryption', 'recoveryAdminEnabled', null);
76 76
 
77
-if($isAdmin) {
77
+if ($isAdmin) {
78 78
 	$subAdmins = \OC::$server->getGroupManager()->getSubAdmin()->getAllSubAdmins();
79 79
 	// New class returns IUser[] so convert back
80 80
 	$result = [];
@@ -85,10 +85,10 @@  discard block
 block discarded – undo
85 85
 		];
86 86
 	}
87 87
 	$subAdmins = $result;
88
-}else{
88
+} else {
89 89
 	/* Retrieve group IDs from $groups array, so we can pass that information into OC_Group::displayNamesInGroups() */
90 90
 	$gids = array();
91
-	foreach($groups as $group) {
91
+	foreach ($groups as $group) {
92 92
 		if (isset($group['id'])) {
93 93
 			$gids[] = $group['id'];
94 94
 		}
@@ -97,7 +97,7 @@  discard block
 block discarded – undo
97 97
 }
98 98
 $disabledUsers = 0;
99 99
 foreach (OC_User::getUsers() as $uid) {
100
-	if(!$userManager->get($uid)->isEnabled()) {
100
+	if (!$userManager->get($uid)->isEnabled()) {
101 101
 		$disabledUsers++;
102 102
 	}
103 103
 }
@@ -108,16 +108,16 @@  discard block
 block discarded – undo
108 108
 );
109 109
 
110 110
 // load preset quotas
111
-$quotaPreset=$config->getAppValue('files', 'quota_preset', '1 GB, 5 GB, 10 GB');
112
-$quotaPreset=explode(',', $quotaPreset);
113
-foreach($quotaPreset as &$preset) {
114
-	$preset=trim($preset);
111
+$quotaPreset = $config->getAppValue('files', 'quota_preset', '1 GB, 5 GB, 10 GB');
112
+$quotaPreset = explode(',', $quotaPreset);
113
+foreach ($quotaPreset as &$preset) {
114
+	$preset = trim($preset);
115 115
 }
116
-$quotaPreset=array_diff($quotaPreset, array('default', 'none'));
116
+$quotaPreset = array_diff($quotaPreset, array('default', 'none'));
117 117
 
118
-$defaultQuota=$config->getAppValue('files', 'default_quota', 'none');
119
-$defaultQuotaIsUserDefined=array_search($defaultQuota, $quotaPreset)===false
120
-	&& array_search($defaultQuota, array('none', 'default'))===false;
118
+$defaultQuota = $config->getAppValue('files', 'default_quota', 'none');
119
+$defaultQuotaIsUserDefined = array_search($defaultQuota, $quotaPreset) === false
120
+	&& array_search($defaultQuota, array('none', 'default')) === false;
121 121
 
122 122
 \OC::$server->getEventDispatcher()->dispatch('OC\Settings\Users::loadAdditionalScripts');
123 123
 
@@ -126,7 +126,7 @@  discard block
 block discarded – undo
126 126
 $tmpl->assign('sortGroups', $sortGroupsBy);
127 127
 $tmpl->assign('adminGroup', $adminGroup);
128 128
 $tmpl->assign('disabledUsersGroup', $disabledUsersGroup);
129
-$tmpl->assign('isAdmin', (int)$isAdmin);
129
+$tmpl->assign('isAdmin', (int) $isAdmin);
130 130
 $tmpl->assign('subadmins', $subAdmins);
131 131
 $tmpl->assign('numofgroups', count($groups) + count($adminGroup));
132 132
 $tmpl->assign('quota_preset', $quotaPreset);
Please login to merge, or discard this patch.
settings/templates/users/part.grouplist.php 1 patch
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -28,33 +28,33 @@
 block discarded – undo
28 28
 	</li>
29 29
 
30 30
 	<!-- The Admin Group -->
31
-	<?php foreach($_["adminGroup"] as $adminGroup): ?>
32
-		<li data-gid="admin" data-usercount="<?php if($adminGroup['usercount'] > 0) { p($adminGroup['usercount']); } ?>" class="isgroup">
31
+	<?php foreach ($_["adminGroup"] as $adminGroup): ?>
32
+		<li data-gid="admin" data-usercount="<?php if ($adminGroup['usercount'] > 0) { p($adminGroup['usercount']); } ?>" class="isgroup">
33 33
 			<a href="#"><span class="groupname"><?php p($l->t('Admins')); ?></span></a>
34 34
 			<span class="utils">
35
-				<span class="usercount"><?php if($adminGroup['usercount'] > 0) { p($adminGroup['usercount']); } ?></span>
35
+				<span class="usercount"><?php if ($adminGroup['usercount'] > 0) { p($adminGroup['usercount']); } ?></span>
36 36
 			</span>
37 37
 		</li>
38 38
 	<?php endforeach; ?>
39 39
 
40 40
 	<!-- Disabled Users -->
41 41
 	<?php $disabledUsersGroup = $_["disabledUsersGroup"] ?>
42
-	<li data-gid="_disabledUsers" data-usercount="<?php if($disabledUsersGroup['usercount'] > 0) { p($disabledUsersGroup['usercount']); } ?>" class="isgroup">
42
+	<li data-gid="_disabledUsers" data-usercount="<?php if ($disabledUsersGroup['usercount'] > 0) { p($disabledUsersGroup['usercount']); } ?>" class="isgroup">
43 43
 		<a href="#"><span class="groupname"><?php p($l->t('Disabled')); ?></span></a>
44 44
 		<span class="utils">
45
-			<span class="usercount"><?php if($disabledUsersGroup['usercount'] > 0) { p($disabledUsersGroup['usercount']); } ?></span>
45
+			<span class="usercount"><?php if ($disabledUsersGroup['usercount'] > 0) { p($disabledUsersGroup['usercount']); } ?></span>
46 46
 		</span>
47 47
 	</li>
48 48
 
49 49
 	<!--List of Groups-->
50
-	<?php foreach($_["groups"] as $group): ?>
50
+	<?php foreach ($_["groups"] as $group): ?>
51 51
 		<li data-gid="<?php p($group['name']) ?>" data-usercount="<?php p($group['usercount']) ?>" class="isgroup">
52 52
 			<a href="#" class="dorename">
53 53
 				<span class="groupname"><?php p($group['name']); ?></span>
54 54
 			</a>
55 55
 			<span class="utils">
56
-				<span class="usercount"><?php if($group['usercount'] > 0) { p($group['usercount']); } ?></span>
57
-				<?php if($_['isAdmin']): ?>
56
+				<span class="usercount"><?php if ($group['usercount'] > 0) { p($group['usercount']); } ?></span>
57
+				<?php if ($_['isAdmin']): ?>
58 58
 				<a href="#" class="action delete" original-title="<?php p($l->t('Delete'))?>">
59 59
 					<img src="<?php print_unescaped(image_path('core', 'actions/delete.svg')) ?>" />
60 60
 				</a>
Please login to merge, or discard this patch.
settings/routes.php 1 patch
Indentation   +48 added lines, -48 removed lines patch added patch discarded remove patch
@@ -36,73 +36,73 @@
 block discarded – undo
36 36
 
37 37
 $application = new Application();
38 38
 $application->registerRoutes($this, [
39
-	'resources' => [
40
-		'groups' => ['url' => '/settings/users/groups'],
41
-		'users' => ['url' => '/settings/users/users'],
42
-		'AuthSettings' => ['url' => '/settings/personal/authtokens'],
43
-	],
44
-	'routes' => [
45
-		['name' => 'MailSettings#setMailSettings', 'url' => '/settings/admin/mailsettings', 'verb' => 'POST'],
46
-		['name' => 'MailSettings#storeCredentials', 'url' => '/settings/admin/mailsettings/credentials', 'verb' => 'POST'],
47
-		['name' => 'MailSettings#sendTestMail', 'url' => '/settings/admin/mailtest', 'verb' => 'POST'],
48
-		['name' => 'Encryption#startMigration', 'url' => '/settings/admin/startmigration', 'verb' => 'POST'],
49
-		['name' => 'AppSettings#listCategories', 'url' => '/settings/apps/categories', 'verb' => 'GET'],
50
-		['name' => 'AppSettings#viewApps', 'url' => '/settings/apps', 'verb' => 'GET'],
51
-		['name' => 'AppSettings#listApps', 'url' => '/settings/apps/list', 'verb' => 'GET'],
52
-		['name' => 'SecuritySettings#trustedDomains', 'url' => '/settings/admin/security/trustedDomains', 'verb' => 'POST'],
53
-		['name' => 'Users#setDisplayName', 'url' => '/settings/users/{username}/displayName', 'verb' => 'POST'],
54
-		['name' => 'Users#setEMailAddress', 'url' => '/settings/users/{id}/mailAddress', 'verb' => 'PUT'],
55
-		['name' => 'Users#setUserSettings', 'url' => '/settings/users/{username}/settings', 'verb' => 'PUT'],
56
-		['name' => 'Users#setEnabled', 'url' => '/settings/users/{id}/setEnabled', 'verb' => 'POST'],
57
-		['name' => 'Users#stats', 'url' => '/settings/users/stats', 'verb' => 'GET'],
58
-		['name' => 'LogSettings#setLogLevel', 'url' => '/settings/admin/log/level', 'verb' => 'POST'],
59
-		['name' => 'LogSettings#getEntries', 'url' => '/settings/admin/log/entries', 'verb' => 'GET'],
60
-		['name' => 'LogSettings#download', 'url' => '/settings/admin/log/download', 'verb' => 'GET'],
61
-		['name' => 'CheckSetup#check', 'url' => '/settings/ajax/checksetup', 'verb' => 'GET'],
62
-		['name' => 'CheckSetup#getFailedIntegrityCheckFiles', 'url' => '/settings/integrity/failed', 'verb' => 'GET'],
63
-		['name' => 'CheckSetup#rescanFailedIntegrityCheck', 'url' => '/settings/integrity/rescan', 'verb' => 'GET'],
64
-		['name' => 'Certificate#addPersonalRootCertificate', 'url' => '/settings/personal/certificate', 'verb' => 'POST'],
65
-		['name' => 'Certificate#removePersonalRootCertificate', 'url' => '/settings/personal/certificate/{certificateIdentifier}', 'verb' => 'DELETE'],
66
-		['name' => 'Certificate#addSystemRootCertificate', 'url' => '/settings/admin/certificate', 'verb' => 'POST'],
67
-		['name' => 'Certificate#removeSystemRootCertificate', 'url' => '/settings/admin/certificate/{certificateIdentifier}', 'verb' => 'DELETE'],
68
-		['name' => 'AdminSettings#index', 'url' => '/settings/admin/{section}', 'verb' => 'GET', 'defaults' => ['section' => 'server']],
69
-		['name' => 'AdminSettings#form', 'url' => '/settings/admin/{section}', 'verb' => 'GET'],
70
-		['name' => 'ChangePassword#changePersonalPassword', 'url' => '/settings/personal/changepassword', 'verb' => 'POST'],
71
-		['name' => 'ChangePassword#changeUserPassword', 'url' => '/settings/users/changepassword', 'verb' => 'POST'],
72
-		['name' => 'Personal#setLanguage', 'url' => '/settings/ajax/setlanguage.php', 'verb' => 'POST'],
73
-	]
39
+    'resources' => [
40
+        'groups' => ['url' => '/settings/users/groups'],
41
+        'users' => ['url' => '/settings/users/users'],
42
+        'AuthSettings' => ['url' => '/settings/personal/authtokens'],
43
+    ],
44
+    'routes' => [
45
+        ['name' => 'MailSettings#setMailSettings', 'url' => '/settings/admin/mailsettings', 'verb' => 'POST'],
46
+        ['name' => 'MailSettings#storeCredentials', 'url' => '/settings/admin/mailsettings/credentials', 'verb' => 'POST'],
47
+        ['name' => 'MailSettings#sendTestMail', 'url' => '/settings/admin/mailtest', 'verb' => 'POST'],
48
+        ['name' => 'Encryption#startMigration', 'url' => '/settings/admin/startmigration', 'verb' => 'POST'],
49
+        ['name' => 'AppSettings#listCategories', 'url' => '/settings/apps/categories', 'verb' => 'GET'],
50
+        ['name' => 'AppSettings#viewApps', 'url' => '/settings/apps', 'verb' => 'GET'],
51
+        ['name' => 'AppSettings#listApps', 'url' => '/settings/apps/list', 'verb' => 'GET'],
52
+        ['name' => 'SecuritySettings#trustedDomains', 'url' => '/settings/admin/security/trustedDomains', 'verb' => 'POST'],
53
+        ['name' => 'Users#setDisplayName', 'url' => '/settings/users/{username}/displayName', 'verb' => 'POST'],
54
+        ['name' => 'Users#setEMailAddress', 'url' => '/settings/users/{id}/mailAddress', 'verb' => 'PUT'],
55
+        ['name' => 'Users#setUserSettings', 'url' => '/settings/users/{username}/settings', 'verb' => 'PUT'],
56
+        ['name' => 'Users#setEnabled', 'url' => '/settings/users/{id}/setEnabled', 'verb' => 'POST'],
57
+        ['name' => 'Users#stats', 'url' => '/settings/users/stats', 'verb' => 'GET'],
58
+        ['name' => 'LogSettings#setLogLevel', 'url' => '/settings/admin/log/level', 'verb' => 'POST'],
59
+        ['name' => 'LogSettings#getEntries', 'url' => '/settings/admin/log/entries', 'verb' => 'GET'],
60
+        ['name' => 'LogSettings#download', 'url' => '/settings/admin/log/download', 'verb' => 'GET'],
61
+        ['name' => 'CheckSetup#check', 'url' => '/settings/ajax/checksetup', 'verb' => 'GET'],
62
+        ['name' => 'CheckSetup#getFailedIntegrityCheckFiles', 'url' => '/settings/integrity/failed', 'verb' => 'GET'],
63
+        ['name' => 'CheckSetup#rescanFailedIntegrityCheck', 'url' => '/settings/integrity/rescan', 'verb' => 'GET'],
64
+        ['name' => 'Certificate#addPersonalRootCertificate', 'url' => '/settings/personal/certificate', 'verb' => 'POST'],
65
+        ['name' => 'Certificate#removePersonalRootCertificate', 'url' => '/settings/personal/certificate/{certificateIdentifier}', 'verb' => 'DELETE'],
66
+        ['name' => 'Certificate#addSystemRootCertificate', 'url' => '/settings/admin/certificate', 'verb' => 'POST'],
67
+        ['name' => 'Certificate#removeSystemRootCertificate', 'url' => '/settings/admin/certificate/{certificateIdentifier}', 'verb' => 'DELETE'],
68
+        ['name' => 'AdminSettings#index', 'url' => '/settings/admin/{section}', 'verb' => 'GET', 'defaults' => ['section' => 'server']],
69
+        ['name' => 'AdminSettings#form', 'url' => '/settings/admin/{section}', 'verb' => 'GET'],
70
+        ['name' => 'ChangePassword#changePersonalPassword', 'url' => '/settings/personal/changepassword', 'verb' => 'POST'],
71
+        ['name' => 'ChangePassword#changeUserPassword', 'url' => '/settings/users/changepassword', 'verb' => 'POST'],
72
+        ['name' => 'Personal#setLanguage', 'url' => '/settings/ajax/setlanguage.php', 'verb' => 'POST'],
73
+    ]
74 74
 ]);
75 75
 
76 76
 /** @var $this \OCP\Route\IRouter */
77 77
 
78 78
 // Settings pages
79 79
 $this->create('settings_help', '/settings/help')
80
-	->actionInclude('settings/help.php');
80
+    ->actionInclude('settings/help.php');
81 81
 $this->create('settings_personal', '/settings/personal')
82
-	->actionInclude('settings/personal.php');
82
+    ->actionInclude('settings/personal.php');
83 83
 $this->create('settings_users', '/settings/users')
84
-	->actionInclude('settings/users.php');
84
+    ->actionInclude('settings/users.php');
85 85
 // Settings ajax actions
86 86
 // users
87 87
 $this->create('settings_ajax_setquota', '/settings/ajax/setquota.php')
88
-	->actionInclude('settings/ajax/setquota.php');
88
+    ->actionInclude('settings/ajax/setquota.php');
89 89
 $this->create('settings_ajax_togglegroups', '/settings/ajax/togglegroups.php')
90
-	->actionInclude('settings/ajax/togglegroups.php');
90
+    ->actionInclude('settings/ajax/togglegroups.php');
91 91
 $this->create('settings_ajax_togglesubadmins', '/settings/ajax/togglesubadmins.php')
92
-	->actionInclude('settings/ajax/togglesubadmins.php');
92
+    ->actionInclude('settings/ajax/togglesubadmins.php');
93 93
 $this->create('settings_ajax_changegorupname', '/settings/ajax/changegroupname.php')
94
-	->actionInclude('settings/ajax/changegroupname.php');
94
+    ->actionInclude('settings/ajax/changegroupname.php');
95 95
 // apps
96 96
 $this->create('settings_ajax_enableapp', '/settings/ajax/enableapp.php')
97
-	->actionInclude('settings/ajax/enableapp.php');
97
+    ->actionInclude('settings/ajax/enableapp.php');
98 98
 $this->create('settings_ajax_disableapp', '/settings/ajax/disableapp.php')
99
-	->actionInclude('settings/ajax/disableapp.php');
99
+    ->actionInclude('settings/ajax/disableapp.php');
100 100
 $this->create('settings_ajax_updateapp', '/settings/ajax/updateapp.php')
101
-	->actionInclude('settings/ajax/updateapp.php');
101
+    ->actionInclude('settings/ajax/updateapp.php');
102 102
 $this->create('settings_ajax_uninstallapp', '/settings/ajax/uninstallapp.php')
103
-	->actionInclude('settings/ajax/uninstallapp.php');
103
+    ->actionInclude('settings/ajax/uninstallapp.php');
104 104
 $this->create('settings_ajax_navigationdetect', '/settings/ajax/navigationdetect.php')
105
-	->actionInclude('settings/ajax/navigationdetect.php');
105
+    ->actionInclude('settings/ajax/navigationdetect.php');
106 106
 // admin
107 107
 $this->create('settings_ajax_excludegroups', '/settings/ajax/excludegroups.php')
108
-	->actionInclude('settings/ajax/excludegroups.php');
108
+    ->actionInclude('settings/ajax/excludegroups.php');
Please login to merge, or discard this patch.
settings/Controller/UsersController.php 2 patches
Indentation   +884 added lines, -884 removed lines patch added patch discarded remove patch
@@ -54,889 +54,889 @@
 block discarded – undo
54 54
  * @package OC\Settings\Controller
55 55
  */
56 56
 class UsersController extends Controller {
57
-	/** @var IL10N */
58
-	private $l10n;
59
-	/** @var IUserSession */
60
-	private $userSession;
61
-	/** @var bool */
62
-	private $isAdmin;
63
-	/** @var IUserManager */
64
-	private $userManager;
65
-	/** @var IGroupManager */
66
-	private $groupManager;
67
-	/** @var IConfig */
68
-	private $config;
69
-	/** @var ILogger */
70
-	private $log;
71
-	/** @var IMailer */
72
-	private $mailer;
73
-	/** @var bool contains the state of the encryption app */
74
-	private $isEncryptionAppEnabled;
75
-	/** @var bool contains the state of the admin recovery setting */
76
-	private $isRestoreEnabled = false;
77
-	/** @var IAvatarManager */
78
-	private $avatarManager;
79
-	/** @var AccountManager */
80
-	private $accountManager;
81
-	/** @var ISecureRandom */
82
-	private $secureRandom;
83
-	/** @var NewUserMailHelper */
84
-	private $newUserMailHelper;
85
-
86
-	/**
87
-	 * @param string $appName
88
-	 * @param IRequest $request
89
-	 * @param IUserManager $userManager
90
-	 * @param IGroupManager $groupManager
91
-	 * @param IUserSession $userSession
92
-	 * @param IConfig $config
93
-	 * @param bool $isAdmin
94
-	 * @param IL10N $l10n
95
-	 * @param ILogger $log
96
-	 * @param IMailer $mailer
97
-	 * @param IURLGenerator $urlGenerator
98
-	 * @param IAppManager $appManager
99
-	 * @param IAvatarManager $avatarManager
100
-	 * @param AccountManager $accountManager
101
-	 * @param ISecureRandom $secureRandom
102
-	 * @param NewUserMailHelper $newUserMailHelper
103
-	 */
104
-	public function __construct($appName,
105
-								IRequest $request,
106
-								IUserManager $userManager,
107
-								IGroupManager $groupManager,
108
-								IUserSession $userSession,
109
-								IConfig $config,
110
-								$isAdmin,
111
-								IL10N $l10n,
112
-								ILogger $log,
113
-								IMailer $mailer,
114
-								IURLGenerator $urlGenerator,
115
-								IAppManager $appManager,
116
-								IAvatarManager $avatarManager,
117
-								AccountManager $accountManager,
118
-								ISecureRandom $secureRandom,
119
-								NewUserMailHelper $newUserMailHelper) {
120
-		parent::__construct($appName, $request);
121
-		$this->userManager = $userManager;
122
-		$this->groupManager = $groupManager;
123
-		$this->userSession = $userSession;
124
-		$this->config = $config;
125
-		$this->isAdmin = $isAdmin;
126
-		$this->l10n = $l10n;
127
-		$this->log = $log;
128
-		$this->mailer = $mailer;
129
-		$this->avatarManager = $avatarManager;
130
-		$this->accountManager = $accountManager;
131
-		$this->secureRandom = $secureRandom;
132
-		$this->newUserMailHelper = $newUserMailHelper;
133
-
134
-		// check for encryption state - TODO see formatUserForIndex
135
-		$this->isEncryptionAppEnabled = $appManager->isEnabledForUser('encryption');
136
-		if($this->isEncryptionAppEnabled) {
137
-			// putting this directly in empty is possible in PHP 5.5+
138
-			$result = $config->getAppValue('encryption', 'recoveryAdminEnabled', 0);
139
-			$this->isRestoreEnabled = !empty($result);
140
-		}
141
-	}
142
-
143
-	/**
144
-	 * @param IUser $user
145
-	 * @param array $userGroups
146
-	 * @return array
147
-	 */
148
-	private function formatUserForIndex(IUser $user, array $userGroups = null) {
149
-
150
-		// TODO: eliminate this encryption specific code below and somehow
151
-		// hook in additional user info from other apps
152
-
153
-		// recovery isn't possible if admin or user has it disabled and encryption
154
-		// is enabled - so we eliminate the else paths in the conditional tree
155
-		// below
156
-		$restorePossible = false;
157
-
158
-		if ($this->isEncryptionAppEnabled) {
159
-			if ($this->isRestoreEnabled) {
160
-				// check for the users recovery setting
161
-				$recoveryMode = $this->config->getUserValue($user->getUID(), 'encryption', 'recoveryEnabled', '0');
162
-				// method call inside empty is possible with PHP 5.5+
163
-				$recoveryModeEnabled = !empty($recoveryMode);
164
-				if ($recoveryModeEnabled) {
165
-					// user also has recovery mode enabled
166
-					$restorePossible = true;
167
-				}
168
-			}
169
-		} else {
170
-			// recovery is possible if encryption is disabled (plain files are
171
-			// available)
172
-			$restorePossible = true;
173
-		}
174
-
175
-		$subAdminGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($user);
176
-		foreach($subAdminGroups as $key => $subAdminGroup) {
177
-			$subAdminGroups[$key] = $subAdminGroup->getGID();
178
-		}
179
-
180
-		$displayName = $user->getEMailAddress();
181
-		if (is_null($displayName)) {
182
-			$displayName = '';
183
-		}
184
-
185
-		$avatarAvailable = false;
186
-		try {
187
-			$avatarAvailable = $this->avatarManager->getAvatar($user->getUID())->exists();
188
-		} catch (\Exception $e) {
189
-			//No avatar yet
190
-		}
191
-
192
-		return [
193
-			'name' => $user->getUID(),
194
-			'displayname' => $user->getDisplayName(),
195
-			'groups' => (empty($userGroups)) ? $this->groupManager->getUserGroupIds($user) : $userGroups,
196
-			'subadmin' => $subAdminGroups,
197
-			'quota' => $user->getQuota(),
198
-			'storageLocation' => $user->getHome(),
199
-			'lastLogin' => $user->getLastLogin() * 1000,
200
-			'backend' => $user->getBackendClassName(),
201
-			'email' => $displayName,
202
-			'isRestoreDisabled' => !$restorePossible,
203
-			'isAvatarAvailable' => $avatarAvailable,
204
-			'isEnabled' => $user->isEnabled(),
205
-		];
206
-	}
207
-
208
-	/**
209
-	 * @param array $userIDs Array with schema [$uid => $displayName]
210
-	 * @return IUser[]
211
-	 */
212
-	private function getUsersForUID(array $userIDs) {
213
-		$users = [];
214
-		foreach ($userIDs as $uid => $displayName) {
215
-			$users[$uid] = $this->userManager->get($uid);
216
-		}
217
-		return $users;
218
-	}
219
-
220
-	/**
221
-	 * @NoAdminRequired
222
-	 *
223
-	 * @param int $offset
224
-	 * @param int $limit
225
-	 * @param string $gid GID to filter for
226
-	 * @param string $pattern Pattern to search for in the username
227
-	 * @param string $backend Backend to filter for (class-name)
228
-	 * @return DataResponse
229
-	 *
230
-	 * TODO: Tidy up and write unit tests - code is mainly static method calls
231
-	 */
232
-	public function index($offset = 0, $limit = 10, $gid = '', $pattern = '', $backend = '') {
233
-		// Remove backends
234
-		if(!empty($backend)) {
235
-			$activeBackends = $this->userManager->getBackends();
236
-			$this->userManager->clearBackends();
237
-			foreach($activeBackends as $singleActiveBackend) {
238
-				if($backend === get_class($singleActiveBackend)) {
239
-					$this->userManager->registerBackend($singleActiveBackend);
240
-					break;
241
-				}
242
-			}
243
-		}
244
-
245
-		$users = [];
246
-		if ($this->isAdmin) {
247
-			if($gid !== '' && $gid !== '_disabledUsers') {
248
-				$batch = $this->getUsersForUID($this->groupManager->displayNamesInGroup($gid, $pattern, $limit, $offset));
249
-			} else {
250
-				$batch = $this->userManager->search($pattern, $limit, $offset);
251
-			}
252
-
253
-			foreach ($batch as $user) {
254
-				if( ($gid !== '_disabledUsers' && $user->isEnabled()) ||
255
-					($gid === '_disabledUsers' && !$user->isEnabled())
256
-				) {
257
-					$users[] = $this->formatUserForIndex($user);
258
-				}
259
-			}
260
-
261
-		} else {
262
-			$subAdminOfGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($this->userSession->getUser());
263
-			// New class returns IGroup[] so convert back
264
-			$gids = [];
265
-			foreach ($subAdminOfGroups as $group) {
266
-				$gids[] = $group->getGID();
267
-			}
268
-			$subAdminOfGroups = $gids;
269
-
270
-			// Set the $gid parameter to an empty value if the subadmin has no rights to access a specific group
271
-			if($gid !== '' && $gid !== '_disabledUsers' && !in_array($gid, $subAdminOfGroups)) {
272
-				$gid = '';
273
-			}
274
-
275
-			// Batch all groups the user is subadmin of when a group is specified
276
-			$batch = [];
277
-			if($gid === '') {
278
-				foreach($subAdminOfGroups as $group) {
279
-					$groupUsers = $this->groupManager->displayNamesInGroup($group, $pattern, $limit, $offset);
280
-
281
-					foreach($groupUsers as $uid => $displayName) {
282
-						$batch[$uid] = $displayName;
283
-					}
284
-				}
285
-			} else {
286
-				$batch = $this->groupManager->displayNamesInGroup($gid, $pattern, $limit, $offset);
287
-			}
288
-			$batch = $this->getUsersForUID($batch);
289
-
290
-			foreach ($batch as $user) {
291
-				// Only add the groups, this user is a subadmin of
292
-				$userGroups = array_values(array_intersect(
293
-					$this->groupManager->getUserGroupIds($user),
294
-					$subAdminOfGroups
295
-				));
296
-				if( ($gid !== '_disabledUsers' && $user->isEnabled()) ||
297
-					($gid === '_disabledUsers' && !$user->isEnabled())
298
-				) {
299
-					$users[] = $this->formatUserForIndex($user, $userGroups);
300
-				}
301
-			}
302
-		}
303
-
304
-		return new DataResponse($users);
305
-	}
306
-
307
-	/**
308
-	 * @NoAdminRequired
309
-	 * @PasswordConfirmationRequired
310
-	 *
311
-	 * @param string $username
312
-	 * @param string $password
313
-	 * @param array $groups
314
-	 * @param string $email
315
-	 * @return DataResponse
316
-	 */
317
-	public function create($username, $password, array $groups=[], $email='') {
318
-		if($email !== '' && !$this->mailer->validateMailAddress($email)) {
319
-			return new DataResponse(
320
-				[
321
-					'message' => (string)$this->l10n->t('Invalid mail address')
322
-				],
323
-				Http::STATUS_UNPROCESSABLE_ENTITY
324
-			);
325
-		}
326
-
327
-		$currentUser = $this->userSession->getUser();
328
-
329
-		if (!$this->isAdmin) {
330
-			if (!empty($groups)) {
331
-				foreach ($groups as $key => $group) {
332
-					$groupObject = $this->groupManager->get($group);
333
-					if($groupObject === null) {
334
-						unset($groups[$key]);
335
-						continue;
336
-					}
337
-
338
-					if (!$this->groupManager->getSubAdmin()->isSubAdminofGroup($currentUser, $groupObject)) {
339
-						unset($groups[$key]);
340
-					}
341
-				}
342
-			}
343
-
344
-			if (empty($groups)) {
345
-				return new DataResponse(
346
-					[
347
-						'message' => $this->l10n->t('No valid group selected'),
348
-					],
349
-					Http::STATUS_FORBIDDEN
350
-				);
351
-			}
352
-		}
353
-
354
-		if ($this->userManager->userExists($username)) {
355
-			return new DataResponse(
356
-				[
357
-					'message' => (string)$this->l10n->t('A user with that name already exists.')
358
-				],
359
-				Http::STATUS_CONFLICT
360
-			);
361
-		}
362
-
363
-		$generatePasswordResetToken = false;
364
-		if ($password === '') {
365
-			if ($email === '') {
366
-				return new DataResponse(
367
-					[
368
-						'message' => (string)$this->l10n->t('To send a password link to the user an email address is required.')
369
-					],
370
-					Http::STATUS_UNPROCESSABLE_ENTITY
371
-				);
372
-			}
373
-
374
-			$password = $this->secureRandom->generate(32);
375
-			$generatePasswordResetToken = true;
376
-		}
377
-
378
-		try {
379
-			$user = $this->userManager->createUser($username, $password);
380
-		} catch (\Exception $exception) {
381
-			$message = $exception->getMessage();
382
-			if (!$message) {
383
-				$message = $this->l10n->t('Unable to create user.');
384
-			}
385
-			return new DataResponse(
386
-				[
387
-					'message' => (string) $message,
388
-				],
389
-				Http::STATUS_FORBIDDEN
390
-			);
391
-		}
392
-
393
-		if($user instanceof IUser) {
394
-			if($groups !== null) {
395
-				foreach($groups as $groupName) {
396
-					$group = $this->groupManager->get($groupName);
397
-
398
-					if(empty($group)) {
399
-						$group = $this->groupManager->createGroup($groupName);
400
-					}
401
-					$group->addUser($user);
402
-				}
403
-			}
404
-			/**
405
-			 * Send new user mail only if a mail is set
406
-			 */
407
-			if($email !== '') {
408
-				$user->setEMailAddress($email);
409
-				try {
410
-					$emailTemplate = $this->newUserMailHelper->generateTemplate($user, $generatePasswordResetToken);
411
-					$this->newUserMailHelper->sendMail($user, $emailTemplate);
412
-				} catch(\Exception $e) {
413
-					$this->log->error("Can't send new user mail to $email: " . $e->getMessage(), ['app' => 'settings']);
414
-				}
415
-			}
416
-			// fetch users groups
417
-			$userGroups = $this->groupManager->getUserGroupIds($user);
418
-
419
-			return new DataResponse(
420
-				$this->formatUserForIndex($user, $userGroups),
421
-				Http::STATUS_CREATED
422
-			);
423
-		}
424
-
425
-		return new DataResponse(
426
-			[
427
-				'message' => (string) $this->l10n->t('Unable to create user.')
428
-			],
429
-			Http::STATUS_FORBIDDEN
430
-		);
431
-
432
-	}
433
-
434
-	/**
435
-	 * @NoAdminRequired
436
-	 * @PasswordConfirmationRequired
437
-	 *
438
-	 * @param string $id
439
-	 * @return DataResponse
440
-	 */
441
-	public function destroy($id) {
442
-		$userId = $this->userSession->getUser()->getUID();
443
-		$user = $this->userManager->get($id);
444
-
445
-		if($userId === $id) {
446
-			return new DataResponse(
447
-				[
448
-					'status' => 'error',
449
-					'data' => [
450
-						'message' => (string) $this->l10n->t('Unable to delete user.')
451
-					]
452
-				],
453
-				Http::STATUS_FORBIDDEN
454
-			);
455
-		}
456
-
457
-		if(!$this->isAdmin && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)) {
458
-			return new DataResponse(
459
-				[
460
-					'status' => 'error',
461
-					'data' => [
462
-						'message' => (string)$this->l10n->t('Authentication error')
463
-					]
464
-				],
465
-				Http::STATUS_FORBIDDEN
466
-			);
467
-		}
468
-
469
-		if($user) {
470
-			if($user->delete()) {
471
-				return new DataResponse(
472
-					[
473
-						'status' => 'success',
474
-						'data' => [
475
-							'username' => $id
476
-						]
477
-					],
478
-					Http::STATUS_NO_CONTENT
479
-				);
480
-			}
481
-		}
482
-
483
-		return new DataResponse(
484
-			[
485
-				'status' => 'error',
486
-				'data' => [
487
-					'message' => (string)$this->l10n->t('Unable to delete user.')
488
-				]
489
-			],
490
-			Http::STATUS_FORBIDDEN
491
-		);
492
-	}
493
-
494
-	/**
495
-	 * @NoAdminRequired
496
-	 *
497
-	 * @param string $id
498
-	 * @return DataResponse
499
-	 */
500
-	public function disable($id) {
501
-		$userId = $this->userSession->getUser()->getUID();
502
-		$user = $this->userManager->get($id);
503
-
504
-		if ($userId === $id) {
505
-			return new DataResponse(
506
-				[
507
-					'status' => 'error',
508
-					'data' => [
509
-						'message' => (string) $this->l10n->t('Error while disabling user.')
510
-					]
511
-				], Http::STATUS_FORBIDDEN
512
-			);
513
-		}
514
-
515
-		if ($user) {
516
-			if(!$this->isAdmin && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)) {
517
-				return new DataResponse(
518
-					[
519
-						'status' => 'error',
520
-						'data' => [
521
-							'message' => (string) $this->l10n->t('Authentication error')
522
-						]
523
-					],
524
-					Http::STATUS_FORBIDDEN
525
-				);
526
-			}
527
-
528
-			$user->setEnabled(false);
529
-			return new DataResponse(
530
-				[
531
-					'status' => 'success',
532
-					'data' => [
533
-						'username' => $id,
534
-						'enabled' => 0
535
-					]
536
-				]
537
-			);
538
-		} else {
539
-			return new DataResponse(
540
-				[
541
-					'status' => 'error',
542
-					'data' => [
543
-						'message' => (string) $this->l10n->t('Error while disabling user.')
544
-					]
545
-				],
546
-				Http::STATUS_FORBIDDEN
547
-			);
548
-		}
549
-	}
550
-
551
-	/**
552
-	 * @NoAdminRequired
553
-	 *
554
-	 * @param string $id
555
-	 * @return DataResponse
556
-	 */
557
-	public function enable($id) {
558
-		$userId = $this->userSession->getUser()->getUID();
559
-		$user = $this->userManager->get($id);
560
-
561
-		if ($userId === $id) {
562
-			return new DataResponse(
563
-				[
564
-					'status' => 'error',
565
-					'data' => [
566
-						'message' => (string) $this->l10n->t('Error while enabling user.')
567
-				]
568
-				],
569
-				Http::STATUS_FORBIDDEN
570
-			);
571
-		}
572
-
573
-		if($user) {
574
-			if (!$this->isAdmin && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)) {
575
-				return new DataResponse(
576
-					[
577
-						'status' => 'error',
578
-						'data' => [
579
-							'message' => (string) $this->l10n->t('Authentication error')
580
-						]
581
-					],
582
-					Http::STATUS_FORBIDDEN
583
-				);
584
-			}
585
-
586
-			$user->setEnabled(true);
587
-			return new DataResponse(
588
-				[
589
-					'status' => 'success',
590
-					'data' => [
591
-						'username' => $id,
592
-						'enabled' => 1
593
-					]
594
-				]
595
-			);
596
-		} else {
597
-			return new DataResponse(
598
-				[
599
-					'status' => 'error',
600
-					'data' => [
601
-						'message' => (string) $this->l10n->t('Error while enabling user.')
602
-					]
603
-				],
604
-				Http::STATUS_FORBIDDEN
605
-			);
606
-		}
607
-	}
608
-
609
-	/**
610
-	 * @NoAdminRequired
611
-	 *
612
-	 * @param string $id
613
-	 * @param int $enabled
614
-	 * @return DataResponse
615
-	 */
616
-	public function setEnabled($id, $enabled) {
617
-		if ((bool) $enabled) {
618
-			return $this->enable($id);
619
-		} else {
620
-			return $this->disable($id);
621
-		}
622
-	}
623
-
624
-	/**
625
-	 * Set the mail address of a user
626
-	 *
627
-	 * @NoAdminRequired
628
-	 * @NoSubadminRequired
629
-	 * @PasswordConfirmationRequired
630
-	 *
631
-	 * @param string $avatarScope
632
-	 * @param string $displayname
633
-	 * @param string $displaynameScope
634
-	 * @param string $phone
635
-	 * @param string $phoneScope
636
-	 * @param string $email
637
-	 * @param string $emailScope
638
-	 * @param string $website
639
-	 * @param string $websiteScope
640
-	 * @param string $address
641
-	 * @param string $addressScope
642
-	 * @param string $twitter
643
-	 * @param string $twitterScope
644
-	 * @return DataResponse
645
-	 */
646
-	public function setUserSettings($avatarScope,
647
-									$displayname,
648
-									$displaynameScope,
649
-									$phone,
650
-									$phoneScope,
651
-									$email,
652
-									$emailScope,
653
-									$website,
654
-									$websiteScope,
655
-									$address,
656
-									$addressScope,
657
-									$twitter,
658
-									$twitterScope
659
-	) {
660
-
661
-		if (!empty($email) && !$this->mailer->validateMailAddress($email)) {
662
-			return new DataResponse(
663
-				[
664
-					'status' => 'error',
665
-					'data' => [
666
-						'message' => (string) $this->l10n->t('Invalid mail address')
667
-					]
668
-				],
669
-				Http::STATUS_UNPROCESSABLE_ENTITY
670
-			);
671
-		}
672
-
673
-		$data = [
674
-			AccountManager::PROPERTY_AVATAR =>  ['scope' => $avatarScope],
675
-			AccountManager::PROPERTY_DISPLAYNAME => ['value' => $displayname, 'scope' => $displaynameScope],
676
-			AccountManager::PROPERTY_EMAIL=> ['value' => $email, 'scope' => $emailScope],
677
-			AccountManager::PROPERTY_WEBSITE => ['value' => $website, 'scope' => $websiteScope],
678
-			AccountManager::PROPERTY_ADDRESS => ['value' => $address, 'scope' => $addressScope],
679
-			AccountManager::PROPERTY_PHONE => ['value' => $phone, 'scope' => $phoneScope],
680
-			AccountManager::PROPERTY_TWITTER => ['value' => $twitter, 'scope' => $twitterScope]
681
-		];
682
-
683
-		$user = $this->userSession->getUser();
684
-
685
-		try {
686
-			$this->saveUserSettings($user, $data);
687
-			return new DataResponse(
688
-				[
689
-					'status' => 'success',
690
-					'data' => [
691
-						'userId' => $user->getUID(),
692
-						'avatarScope' => $avatarScope,
693
-						'displayname' => $displayname,
694
-						'displaynameScope' => $displaynameScope,
695
-						'email' => $email,
696
-						'emailScope' => $emailScope,
697
-						'website' => $website,
698
-						'websiteScope' => $websiteScope,
699
-						'address' => $address,
700
-						'addressScope' => $addressScope,
701
-						'message' => (string) $this->l10n->t('Settings saved')
702
-					]
703
-				],
704
-				Http::STATUS_OK
705
-			);
706
-		} catch (ForbiddenException $e) {
707
-			return new DataResponse([
708
-				'status' => 'error',
709
-				'data' => [
710
-					'message' => $e->getMessage()
711
-				],
712
-			]);
713
-		}
714
-
715
-	}
716
-
717
-
718
-	/**
719
-	 * update account manager with new user data
720
-	 *
721
-	 * @param IUser $user
722
-	 * @param array $data
723
-	 * @throws ForbiddenException
724
-	 */
725
-	protected function saveUserSettings(IUser $user, $data) {
726
-
727
-		// keep the user back-end up-to-date with the latest display name and email
728
-		// address
729
-		$oldDisplayName = $user->getDisplayName();
730
-		$oldDisplayName = is_null($oldDisplayName) ? '' : $oldDisplayName;
731
-		if (isset($data[AccountManager::PROPERTY_DISPLAYNAME]['value'])
732
-			&& $oldDisplayName !== $data[AccountManager::PROPERTY_DISPLAYNAME]['value']
733
-		) {
734
-			$result = $user->setDisplayName($data[AccountManager::PROPERTY_DISPLAYNAME]['value']);
735
-			if ($result === false) {
736
-				throw new ForbiddenException($this->l10n->t('Unable to change full name'));
737
-			}
738
-		}
739
-
740
-		$oldEmailAddress = $user->getEMailAddress();
741
-		$oldEmailAddress = is_null($oldEmailAddress) ? '' : $oldEmailAddress;
742
-		if (isset($data[AccountManager::PROPERTY_EMAIL]['value'])
743
-			&& $oldEmailAddress !== $data[AccountManager::PROPERTY_EMAIL]['value']
744
-		) {
745
-			// this is the only permission a backend provides and is also used
746
-			// for the permission of setting a email address
747
-			if (!$user->canChangeDisplayName()) {
748
-				throw new ForbiddenException($this->l10n->t('Unable to change email address'));
749
-			}
750
-			$user->setEMailAddress($data[AccountManager::PROPERTY_EMAIL]['value']);
751
-		}
752
-
753
-		$this->accountManager->updateUser($user, $data);
754
-	}
755
-
756
-	/**
757
-	 * Count all unique users visible for the current admin/subadmin.
758
-	 *
759
-	 * @NoAdminRequired
760
-	 *
761
-	 * @return DataResponse
762
-	 */
763
-	public function stats() {
764
-		$userCount = 0;
765
-		if ($this->isAdmin) {
766
-			$countByBackend = $this->userManager->countUsers();
767
-
768
-			if (!empty($countByBackend)) {
769
-				foreach ($countByBackend as $count) {
770
-					$userCount += $count;
771
-				}
772
-			}
773
-		} else {
774
-			$groups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($this->userSession->getUser());
775
-
776
-			$uniqueUsers = [];
777
-			foreach ($groups as $group) {
778
-				foreach($group->getUsers() as $uid => $displayName) {
779
-					$uniqueUsers[$uid] = true;
780
-				}
781
-			}
782
-
783
-			$userCount = count($uniqueUsers);
784
-		}
785
-
786
-		return new DataResponse(
787
-			[
788
-				'totalUsers' => $userCount
789
-			]
790
-		);
791
-	}
792
-
793
-
794
-	/**
795
-	 * Set the displayName of a user
796
-	 *
797
-	 * @NoAdminRequired
798
-	 * @NoSubadminRequired
799
-	 * @PasswordConfirmationRequired
800
-	 * @todo merge into saveUserSettings
801
-	 *
802
-	 * @param string $username
803
-	 * @param string $displayName
804
-	 * @return DataResponse
805
-	 */
806
-	public function setDisplayName($username, $displayName) {
807
-		$currentUser = $this->userSession->getUser();
808
-		$user = $this->userManager->get($username);
809
-
810
-		if ($user === null ||
811
-			!$user->canChangeDisplayName() ||
812
-			(
813
-				!$this->groupManager->isAdmin($currentUser->getUID()) &&
814
-				!$this->groupManager->getSubAdmin()->isUserAccessible($currentUser, $user) &&
815
-				$currentUser->getUID() !== $username
816
-
817
-			)
818
-		) {
819
-			return new DataResponse([
820
-				'status' => 'error',
821
-				'data' => [
822
-					'message' => $this->l10n->t('Authentication error'),
823
-				],
824
-			]);
825
-		}
826
-
827
-		$userData = $this->accountManager->getUser($user);
828
-		$userData[AccountManager::PROPERTY_DISPLAYNAME]['value'] = $displayName;
829
-
830
-
831
-		try {
832
-			$this->saveUserSettings($user, $userData);
833
-			return new DataResponse([
834
-				'status' => 'success',
835
-				'data' => [
836
-					'message' => $this->l10n->t('Your full name has been changed.'),
837
-					'username' => $username,
838
-					'displayName' => $displayName,
839
-				],
840
-			]);
841
-		} catch (ForbiddenException $e) {
842
-			return new DataResponse([
843
-				'status' => 'error',
844
-				'data' => [
845
-					'message' => $e->getMessage(),
846
-					'displayName' => $user->getDisplayName(),
847
-				],
848
-			]);
849
-		}
850
-	}
851
-
852
-	/**
853
-	 * Set the mail address of a user
854
-	 *
855
-	 * @NoAdminRequired
856
-	 * @NoSubadminRequired
857
-	 * @PasswordConfirmationRequired
858
-	 *
859
-	 * @param string $id
860
-	 * @param string $mailAddress
861
-	 * @return DataResponse
862
-	 */
863
-	public function setEMailAddress($id, $mailAddress) {
864
-		$user = $this->userManager->get($id);
865
-		if (!$this->isAdmin
866
-			&& !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)
867
-		) {
868
-			return new DataResponse(
869
-				[
870
-					'status' => 'error',
871
-					'data' => [
872
-						'message' => (string) $this->l10n->t('Forbidden')
873
-					]
874
-				],
875
-				Http::STATUS_FORBIDDEN
876
-			);
877
-		}
878
-
879
-		if($mailAddress !== '' && !$this->mailer->validateMailAddress($mailAddress)) {
880
-			return new DataResponse(
881
-				[
882
-					'status' => 'error',
883
-					'data' => [
884
-						'message' => (string) $this->l10n->t('Invalid mail address')
885
-					]
886
-				],
887
-				Http::STATUS_UNPROCESSABLE_ENTITY
888
-			);
889
-		}
890
-
891
-		if (!$user) {
892
-			return new DataResponse(
893
-				[
894
-					'status' => 'error',
895
-					'data' => [
896
-						'message' => (string) $this->l10n->t('Invalid user')
897
-					]
898
-				],
899
-				Http::STATUS_UNPROCESSABLE_ENTITY
900
-			);
901
-		}
902
-		// this is the only permission a backend provides and is also used
903
-		// for the permission of setting a email address
904
-		if (!$user->canChangeDisplayName()) {
905
-			return new DataResponse(
906
-				[
907
-					'status' => 'error',
908
-					'data' => [
909
-						'message' => (string) $this->l10n->t('Unable to change mail address')
910
-					]
911
-				],
912
-				Http::STATUS_FORBIDDEN
913
-			);
914
-		}
915
-
916
-		$userData = $this->accountManager->getUser($user);
917
-		$userData[AccountManager::PROPERTY_EMAIL]['value'] = $mailAddress;
918
-
919
-		try {
920
-			$this->saveUserSettings($user, $userData);
921
-			return new DataResponse(
922
-				[
923
-					'status' => 'success',
924
-					'data' => [
925
-						'username' => $id,
926
-						'mailAddress' => $mailAddress,
927
-						'message' => (string) $this->l10n->t('Email saved')
928
-					]
929
-				],
930
-				Http::STATUS_OK
931
-			);
932
-		} catch (ForbiddenException $e) {
933
-			return new DataResponse([
934
-				'status' => 'error',
935
-				'data' => [
936
-					'message' => $e->getMessage()
937
-				],
938
-			]);
939
-		}
940
-	}
57
+    /** @var IL10N */
58
+    private $l10n;
59
+    /** @var IUserSession */
60
+    private $userSession;
61
+    /** @var bool */
62
+    private $isAdmin;
63
+    /** @var IUserManager */
64
+    private $userManager;
65
+    /** @var IGroupManager */
66
+    private $groupManager;
67
+    /** @var IConfig */
68
+    private $config;
69
+    /** @var ILogger */
70
+    private $log;
71
+    /** @var IMailer */
72
+    private $mailer;
73
+    /** @var bool contains the state of the encryption app */
74
+    private $isEncryptionAppEnabled;
75
+    /** @var bool contains the state of the admin recovery setting */
76
+    private $isRestoreEnabled = false;
77
+    /** @var IAvatarManager */
78
+    private $avatarManager;
79
+    /** @var AccountManager */
80
+    private $accountManager;
81
+    /** @var ISecureRandom */
82
+    private $secureRandom;
83
+    /** @var NewUserMailHelper */
84
+    private $newUserMailHelper;
85
+
86
+    /**
87
+     * @param string $appName
88
+     * @param IRequest $request
89
+     * @param IUserManager $userManager
90
+     * @param IGroupManager $groupManager
91
+     * @param IUserSession $userSession
92
+     * @param IConfig $config
93
+     * @param bool $isAdmin
94
+     * @param IL10N $l10n
95
+     * @param ILogger $log
96
+     * @param IMailer $mailer
97
+     * @param IURLGenerator $urlGenerator
98
+     * @param IAppManager $appManager
99
+     * @param IAvatarManager $avatarManager
100
+     * @param AccountManager $accountManager
101
+     * @param ISecureRandom $secureRandom
102
+     * @param NewUserMailHelper $newUserMailHelper
103
+     */
104
+    public function __construct($appName,
105
+                                IRequest $request,
106
+                                IUserManager $userManager,
107
+                                IGroupManager $groupManager,
108
+                                IUserSession $userSession,
109
+                                IConfig $config,
110
+                                $isAdmin,
111
+                                IL10N $l10n,
112
+                                ILogger $log,
113
+                                IMailer $mailer,
114
+                                IURLGenerator $urlGenerator,
115
+                                IAppManager $appManager,
116
+                                IAvatarManager $avatarManager,
117
+                                AccountManager $accountManager,
118
+                                ISecureRandom $secureRandom,
119
+                                NewUserMailHelper $newUserMailHelper) {
120
+        parent::__construct($appName, $request);
121
+        $this->userManager = $userManager;
122
+        $this->groupManager = $groupManager;
123
+        $this->userSession = $userSession;
124
+        $this->config = $config;
125
+        $this->isAdmin = $isAdmin;
126
+        $this->l10n = $l10n;
127
+        $this->log = $log;
128
+        $this->mailer = $mailer;
129
+        $this->avatarManager = $avatarManager;
130
+        $this->accountManager = $accountManager;
131
+        $this->secureRandom = $secureRandom;
132
+        $this->newUserMailHelper = $newUserMailHelper;
133
+
134
+        // check for encryption state - TODO see formatUserForIndex
135
+        $this->isEncryptionAppEnabled = $appManager->isEnabledForUser('encryption');
136
+        if($this->isEncryptionAppEnabled) {
137
+            // putting this directly in empty is possible in PHP 5.5+
138
+            $result = $config->getAppValue('encryption', 'recoveryAdminEnabled', 0);
139
+            $this->isRestoreEnabled = !empty($result);
140
+        }
141
+    }
142
+
143
+    /**
144
+     * @param IUser $user
145
+     * @param array $userGroups
146
+     * @return array
147
+     */
148
+    private function formatUserForIndex(IUser $user, array $userGroups = null) {
149
+
150
+        // TODO: eliminate this encryption specific code below and somehow
151
+        // hook in additional user info from other apps
152
+
153
+        // recovery isn't possible if admin or user has it disabled and encryption
154
+        // is enabled - so we eliminate the else paths in the conditional tree
155
+        // below
156
+        $restorePossible = false;
157
+
158
+        if ($this->isEncryptionAppEnabled) {
159
+            if ($this->isRestoreEnabled) {
160
+                // check for the users recovery setting
161
+                $recoveryMode = $this->config->getUserValue($user->getUID(), 'encryption', 'recoveryEnabled', '0');
162
+                // method call inside empty is possible with PHP 5.5+
163
+                $recoveryModeEnabled = !empty($recoveryMode);
164
+                if ($recoveryModeEnabled) {
165
+                    // user also has recovery mode enabled
166
+                    $restorePossible = true;
167
+                }
168
+            }
169
+        } else {
170
+            // recovery is possible if encryption is disabled (plain files are
171
+            // available)
172
+            $restorePossible = true;
173
+        }
174
+
175
+        $subAdminGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($user);
176
+        foreach($subAdminGroups as $key => $subAdminGroup) {
177
+            $subAdminGroups[$key] = $subAdminGroup->getGID();
178
+        }
179
+
180
+        $displayName = $user->getEMailAddress();
181
+        if (is_null($displayName)) {
182
+            $displayName = '';
183
+        }
184
+
185
+        $avatarAvailable = false;
186
+        try {
187
+            $avatarAvailable = $this->avatarManager->getAvatar($user->getUID())->exists();
188
+        } catch (\Exception $e) {
189
+            //No avatar yet
190
+        }
191
+
192
+        return [
193
+            'name' => $user->getUID(),
194
+            'displayname' => $user->getDisplayName(),
195
+            'groups' => (empty($userGroups)) ? $this->groupManager->getUserGroupIds($user) : $userGroups,
196
+            'subadmin' => $subAdminGroups,
197
+            'quota' => $user->getQuota(),
198
+            'storageLocation' => $user->getHome(),
199
+            'lastLogin' => $user->getLastLogin() * 1000,
200
+            'backend' => $user->getBackendClassName(),
201
+            'email' => $displayName,
202
+            'isRestoreDisabled' => !$restorePossible,
203
+            'isAvatarAvailable' => $avatarAvailable,
204
+            'isEnabled' => $user->isEnabled(),
205
+        ];
206
+    }
207
+
208
+    /**
209
+     * @param array $userIDs Array with schema [$uid => $displayName]
210
+     * @return IUser[]
211
+     */
212
+    private function getUsersForUID(array $userIDs) {
213
+        $users = [];
214
+        foreach ($userIDs as $uid => $displayName) {
215
+            $users[$uid] = $this->userManager->get($uid);
216
+        }
217
+        return $users;
218
+    }
219
+
220
+    /**
221
+     * @NoAdminRequired
222
+     *
223
+     * @param int $offset
224
+     * @param int $limit
225
+     * @param string $gid GID to filter for
226
+     * @param string $pattern Pattern to search for in the username
227
+     * @param string $backend Backend to filter for (class-name)
228
+     * @return DataResponse
229
+     *
230
+     * TODO: Tidy up and write unit tests - code is mainly static method calls
231
+     */
232
+    public function index($offset = 0, $limit = 10, $gid = '', $pattern = '', $backend = '') {
233
+        // Remove backends
234
+        if(!empty($backend)) {
235
+            $activeBackends = $this->userManager->getBackends();
236
+            $this->userManager->clearBackends();
237
+            foreach($activeBackends as $singleActiveBackend) {
238
+                if($backend === get_class($singleActiveBackend)) {
239
+                    $this->userManager->registerBackend($singleActiveBackend);
240
+                    break;
241
+                }
242
+            }
243
+        }
244
+
245
+        $users = [];
246
+        if ($this->isAdmin) {
247
+            if($gid !== '' && $gid !== '_disabledUsers') {
248
+                $batch = $this->getUsersForUID($this->groupManager->displayNamesInGroup($gid, $pattern, $limit, $offset));
249
+            } else {
250
+                $batch = $this->userManager->search($pattern, $limit, $offset);
251
+            }
252
+
253
+            foreach ($batch as $user) {
254
+                if( ($gid !== '_disabledUsers' && $user->isEnabled()) ||
255
+                    ($gid === '_disabledUsers' && !$user->isEnabled())
256
+                ) {
257
+                    $users[] = $this->formatUserForIndex($user);
258
+                }
259
+            }
260
+
261
+        } else {
262
+            $subAdminOfGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($this->userSession->getUser());
263
+            // New class returns IGroup[] so convert back
264
+            $gids = [];
265
+            foreach ($subAdminOfGroups as $group) {
266
+                $gids[] = $group->getGID();
267
+            }
268
+            $subAdminOfGroups = $gids;
269
+
270
+            // Set the $gid parameter to an empty value if the subadmin has no rights to access a specific group
271
+            if($gid !== '' && $gid !== '_disabledUsers' && !in_array($gid, $subAdminOfGroups)) {
272
+                $gid = '';
273
+            }
274
+
275
+            // Batch all groups the user is subadmin of when a group is specified
276
+            $batch = [];
277
+            if($gid === '') {
278
+                foreach($subAdminOfGroups as $group) {
279
+                    $groupUsers = $this->groupManager->displayNamesInGroup($group, $pattern, $limit, $offset);
280
+
281
+                    foreach($groupUsers as $uid => $displayName) {
282
+                        $batch[$uid] = $displayName;
283
+                    }
284
+                }
285
+            } else {
286
+                $batch = $this->groupManager->displayNamesInGroup($gid, $pattern, $limit, $offset);
287
+            }
288
+            $batch = $this->getUsersForUID($batch);
289
+
290
+            foreach ($batch as $user) {
291
+                // Only add the groups, this user is a subadmin of
292
+                $userGroups = array_values(array_intersect(
293
+                    $this->groupManager->getUserGroupIds($user),
294
+                    $subAdminOfGroups
295
+                ));
296
+                if( ($gid !== '_disabledUsers' && $user->isEnabled()) ||
297
+                    ($gid === '_disabledUsers' && !$user->isEnabled())
298
+                ) {
299
+                    $users[] = $this->formatUserForIndex($user, $userGroups);
300
+                }
301
+            }
302
+        }
303
+
304
+        return new DataResponse($users);
305
+    }
306
+
307
+    /**
308
+     * @NoAdminRequired
309
+     * @PasswordConfirmationRequired
310
+     *
311
+     * @param string $username
312
+     * @param string $password
313
+     * @param array $groups
314
+     * @param string $email
315
+     * @return DataResponse
316
+     */
317
+    public function create($username, $password, array $groups=[], $email='') {
318
+        if($email !== '' && !$this->mailer->validateMailAddress($email)) {
319
+            return new DataResponse(
320
+                [
321
+                    'message' => (string)$this->l10n->t('Invalid mail address')
322
+                ],
323
+                Http::STATUS_UNPROCESSABLE_ENTITY
324
+            );
325
+        }
326
+
327
+        $currentUser = $this->userSession->getUser();
328
+
329
+        if (!$this->isAdmin) {
330
+            if (!empty($groups)) {
331
+                foreach ($groups as $key => $group) {
332
+                    $groupObject = $this->groupManager->get($group);
333
+                    if($groupObject === null) {
334
+                        unset($groups[$key]);
335
+                        continue;
336
+                    }
337
+
338
+                    if (!$this->groupManager->getSubAdmin()->isSubAdminofGroup($currentUser, $groupObject)) {
339
+                        unset($groups[$key]);
340
+                    }
341
+                }
342
+            }
343
+
344
+            if (empty($groups)) {
345
+                return new DataResponse(
346
+                    [
347
+                        'message' => $this->l10n->t('No valid group selected'),
348
+                    ],
349
+                    Http::STATUS_FORBIDDEN
350
+                );
351
+            }
352
+        }
353
+
354
+        if ($this->userManager->userExists($username)) {
355
+            return new DataResponse(
356
+                [
357
+                    'message' => (string)$this->l10n->t('A user with that name already exists.')
358
+                ],
359
+                Http::STATUS_CONFLICT
360
+            );
361
+        }
362
+
363
+        $generatePasswordResetToken = false;
364
+        if ($password === '') {
365
+            if ($email === '') {
366
+                return new DataResponse(
367
+                    [
368
+                        'message' => (string)$this->l10n->t('To send a password link to the user an email address is required.')
369
+                    ],
370
+                    Http::STATUS_UNPROCESSABLE_ENTITY
371
+                );
372
+            }
373
+
374
+            $password = $this->secureRandom->generate(32);
375
+            $generatePasswordResetToken = true;
376
+        }
377
+
378
+        try {
379
+            $user = $this->userManager->createUser($username, $password);
380
+        } catch (\Exception $exception) {
381
+            $message = $exception->getMessage();
382
+            if (!$message) {
383
+                $message = $this->l10n->t('Unable to create user.');
384
+            }
385
+            return new DataResponse(
386
+                [
387
+                    'message' => (string) $message,
388
+                ],
389
+                Http::STATUS_FORBIDDEN
390
+            );
391
+        }
392
+
393
+        if($user instanceof IUser) {
394
+            if($groups !== null) {
395
+                foreach($groups as $groupName) {
396
+                    $group = $this->groupManager->get($groupName);
397
+
398
+                    if(empty($group)) {
399
+                        $group = $this->groupManager->createGroup($groupName);
400
+                    }
401
+                    $group->addUser($user);
402
+                }
403
+            }
404
+            /**
405
+             * Send new user mail only if a mail is set
406
+             */
407
+            if($email !== '') {
408
+                $user->setEMailAddress($email);
409
+                try {
410
+                    $emailTemplate = $this->newUserMailHelper->generateTemplate($user, $generatePasswordResetToken);
411
+                    $this->newUserMailHelper->sendMail($user, $emailTemplate);
412
+                } catch(\Exception $e) {
413
+                    $this->log->error("Can't send new user mail to $email: " . $e->getMessage(), ['app' => 'settings']);
414
+                }
415
+            }
416
+            // fetch users groups
417
+            $userGroups = $this->groupManager->getUserGroupIds($user);
418
+
419
+            return new DataResponse(
420
+                $this->formatUserForIndex($user, $userGroups),
421
+                Http::STATUS_CREATED
422
+            );
423
+        }
424
+
425
+        return new DataResponse(
426
+            [
427
+                'message' => (string) $this->l10n->t('Unable to create user.')
428
+            ],
429
+            Http::STATUS_FORBIDDEN
430
+        );
431
+
432
+    }
433
+
434
+    /**
435
+     * @NoAdminRequired
436
+     * @PasswordConfirmationRequired
437
+     *
438
+     * @param string $id
439
+     * @return DataResponse
440
+     */
441
+    public function destroy($id) {
442
+        $userId = $this->userSession->getUser()->getUID();
443
+        $user = $this->userManager->get($id);
444
+
445
+        if($userId === $id) {
446
+            return new DataResponse(
447
+                [
448
+                    'status' => 'error',
449
+                    'data' => [
450
+                        'message' => (string) $this->l10n->t('Unable to delete user.')
451
+                    ]
452
+                ],
453
+                Http::STATUS_FORBIDDEN
454
+            );
455
+        }
456
+
457
+        if(!$this->isAdmin && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)) {
458
+            return new DataResponse(
459
+                [
460
+                    'status' => 'error',
461
+                    'data' => [
462
+                        'message' => (string)$this->l10n->t('Authentication error')
463
+                    ]
464
+                ],
465
+                Http::STATUS_FORBIDDEN
466
+            );
467
+        }
468
+
469
+        if($user) {
470
+            if($user->delete()) {
471
+                return new DataResponse(
472
+                    [
473
+                        'status' => 'success',
474
+                        'data' => [
475
+                            'username' => $id
476
+                        ]
477
+                    ],
478
+                    Http::STATUS_NO_CONTENT
479
+                );
480
+            }
481
+        }
482
+
483
+        return new DataResponse(
484
+            [
485
+                'status' => 'error',
486
+                'data' => [
487
+                    'message' => (string)$this->l10n->t('Unable to delete user.')
488
+                ]
489
+            ],
490
+            Http::STATUS_FORBIDDEN
491
+        );
492
+    }
493
+
494
+    /**
495
+     * @NoAdminRequired
496
+     *
497
+     * @param string $id
498
+     * @return DataResponse
499
+     */
500
+    public function disable($id) {
501
+        $userId = $this->userSession->getUser()->getUID();
502
+        $user = $this->userManager->get($id);
503
+
504
+        if ($userId === $id) {
505
+            return new DataResponse(
506
+                [
507
+                    'status' => 'error',
508
+                    'data' => [
509
+                        'message' => (string) $this->l10n->t('Error while disabling user.')
510
+                    ]
511
+                ], Http::STATUS_FORBIDDEN
512
+            );
513
+        }
514
+
515
+        if ($user) {
516
+            if(!$this->isAdmin && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)) {
517
+                return new DataResponse(
518
+                    [
519
+                        'status' => 'error',
520
+                        'data' => [
521
+                            'message' => (string) $this->l10n->t('Authentication error')
522
+                        ]
523
+                    ],
524
+                    Http::STATUS_FORBIDDEN
525
+                );
526
+            }
527
+
528
+            $user->setEnabled(false);
529
+            return new DataResponse(
530
+                [
531
+                    'status' => 'success',
532
+                    'data' => [
533
+                        'username' => $id,
534
+                        'enabled' => 0
535
+                    ]
536
+                ]
537
+            );
538
+        } else {
539
+            return new DataResponse(
540
+                [
541
+                    'status' => 'error',
542
+                    'data' => [
543
+                        'message' => (string) $this->l10n->t('Error while disabling user.')
544
+                    ]
545
+                ],
546
+                Http::STATUS_FORBIDDEN
547
+            );
548
+        }
549
+    }
550
+
551
+    /**
552
+     * @NoAdminRequired
553
+     *
554
+     * @param string $id
555
+     * @return DataResponse
556
+     */
557
+    public function enable($id) {
558
+        $userId = $this->userSession->getUser()->getUID();
559
+        $user = $this->userManager->get($id);
560
+
561
+        if ($userId === $id) {
562
+            return new DataResponse(
563
+                [
564
+                    'status' => 'error',
565
+                    'data' => [
566
+                        'message' => (string) $this->l10n->t('Error while enabling user.')
567
+                ]
568
+                ],
569
+                Http::STATUS_FORBIDDEN
570
+            );
571
+        }
572
+
573
+        if($user) {
574
+            if (!$this->isAdmin && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)) {
575
+                return new DataResponse(
576
+                    [
577
+                        'status' => 'error',
578
+                        'data' => [
579
+                            'message' => (string) $this->l10n->t('Authentication error')
580
+                        ]
581
+                    ],
582
+                    Http::STATUS_FORBIDDEN
583
+                );
584
+            }
585
+
586
+            $user->setEnabled(true);
587
+            return new DataResponse(
588
+                [
589
+                    'status' => 'success',
590
+                    'data' => [
591
+                        'username' => $id,
592
+                        'enabled' => 1
593
+                    ]
594
+                ]
595
+            );
596
+        } else {
597
+            return new DataResponse(
598
+                [
599
+                    'status' => 'error',
600
+                    'data' => [
601
+                        'message' => (string) $this->l10n->t('Error while enabling user.')
602
+                    ]
603
+                ],
604
+                Http::STATUS_FORBIDDEN
605
+            );
606
+        }
607
+    }
608
+
609
+    /**
610
+     * @NoAdminRequired
611
+     *
612
+     * @param string $id
613
+     * @param int $enabled
614
+     * @return DataResponse
615
+     */
616
+    public function setEnabled($id, $enabled) {
617
+        if ((bool) $enabled) {
618
+            return $this->enable($id);
619
+        } else {
620
+            return $this->disable($id);
621
+        }
622
+    }
623
+
624
+    /**
625
+     * Set the mail address of a user
626
+     *
627
+     * @NoAdminRequired
628
+     * @NoSubadminRequired
629
+     * @PasswordConfirmationRequired
630
+     *
631
+     * @param string $avatarScope
632
+     * @param string $displayname
633
+     * @param string $displaynameScope
634
+     * @param string $phone
635
+     * @param string $phoneScope
636
+     * @param string $email
637
+     * @param string $emailScope
638
+     * @param string $website
639
+     * @param string $websiteScope
640
+     * @param string $address
641
+     * @param string $addressScope
642
+     * @param string $twitter
643
+     * @param string $twitterScope
644
+     * @return DataResponse
645
+     */
646
+    public function setUserSettings($avatarScope,
647
+                                    $displayname,
648
+                                    $displaynameScope,
649
+                                    $phone,
650
+                                    $phoneScope,
651
+                                    $email,
652
+                                    $emailScope,
653
+                                    $website,
654
+                                    $websiteScope,
655
+                                    $address,
656
+                                    $addressScope,
657
+                                    $twitter,
658
+                                    $twitterScope
659
+    ) {
660
+
661
+        if (!empty($email) && !$this->mailer->validateMailAddress($email)) {
662
+            return new DataResponse(
663
+                [
664
+                    'status' => 'error',
665
+                    'data' => [
666
+                        'message' => (string) $this->l10n->t('Invalid mail address')
667
+                    ]
668
+                ],
669
+                Http::STATUS_UNPROCESSABLE_ENTITY
670
+            );
671
+        }
672
+
673
+        $data = [
674
+            AccountManager::PROPERTY_AVATAR =>  ['scope' => $avatarScope],
675
+            AccountManager::PROPERTY_DISPLAYNAME => ['value' => $displayname, 'scope' => $displaynameScope],
676
+            AccountManager::PROPERTY_EMAIL=> ['value' => $email, 'scope' => $emailScope],
677
+            AccountManager::PROPERTY_WEBSITE => ['value' => $website, 'scope' => $websiteScope],
678
+            AccountManager::PROPERTY_ADDRESS => ['value' => $address, 'scope' => $addressScope],
679
+            AccountManager::PROPERTY_PHONE => ['value' => $phone, 'scope' => $phoneScope],
680
+            AccountManager::PROPERTY_TWITTER => ['value' => $twitter, 'scope' => $twitterScope]
681
+        ];
682
+
683
+        $user = $this->userSession->getUser();
684
+
685
+        try {
686
+            $this->saveUserSettings($user, $data);
687
+            return new DataResponse(
688
+                [
689
+                    'status' => 'success',
690
+                    'data' => [
691
+                        'userId' => $user->getUID(),
692
+                        'avatarScope' => $avatarScope,
693
+                        'displayname' => $displayname,
694
+                        'displaynameScope' => $displaynameScope,
695
+                        'email' => $email,
696
+                        'emailScope' => $emailScope,
697
+                        'website' => $website,
698
+                        'websiteScope' => $websiteScope,
699
+                        'address' => $address,
700
+                        'addressScope' => $addressScope,
701
+                        'message' => (string) $this->l10n->t('Settings saved')
702
+                    ]
703
+                ],
704
+                Http::STATUS_OK
705
+            );
706
+        } catch (ForbiddenException $e) {
707
+            return new DataResponse([
708
+                'status' => 'error',
709
+                'data' => [
710
+                    'message' => $e->getMessage()
711
+                ],
712
+            ]);
713
+        }
714
+
715
+    }
716
+
717
+
718
+    /**
719
+     * update account manager with new user data
720
+     *
721
+     * @param IUser $user
722
+     * @param array $data
723
+     * @throws ForbiddenException
724
+     */
725
+    protected function saveUserSettings(IUser $user, $data) {
726
+
727
+        // keep the user back-end up-to-date with the latest display name and email
728
+        // address
729
+        $oldDisplayName = $user->getDisplayName();
730
+        $oldDisplayName = is_null($oldDisplayName) ? '' : $oldDisplayName;
731
+        if (isset($data[AccountManager::PROPERTY_DISPLAYNAME]['value'])
732
+            && $oldDisplayName !== $data[AccountManager::PROPERTY_DISPLAYNAME]['value']
733
+        ) {
734
+            $result = $user->setDisplayName($data[AccountManager::PROPERTY_DISPLAYNAME]['value']);
735
+            if ($result === false) {
736
+                throw new ForbiddenException($this->l10n->t('Unable to change full name'));
737
+            }
738
+        }
739
+
740
+        $oldEmailAddress = $user->getEMailAddress();
741
+        $oldEmailAddress = is_null($oldEmailAddress) ? '' : $oldEmailAddress;
742
+        if (isset($data[AccountManager::PROPERTY_EMAIL]['value'])
743
+            && $oldEmailAddress !== $data[AccountManager::PROPERTY_EMAIL]['value']
744
+        ) {
745
+            // this is the only permission a backend provides and is also used
746
+            // for the permission of setting a email address
747
+            if (!$user->canChangeDisplayName()) {
748
+                throw new ForbiddenException($this->l10n->t('Unable to change email address'));
749
+            }
750
+            $user->setEMailAddress($data[AccountManager::PROPERTY_EMAIL]['value']);
751
+        }
752
+
753
+        $this->accountManager->updateUser($user, $data);
754
+    }
755
+
756
+    /**
757
+     * Count all unique users visible for the current admin/subadmin.
758
+     *
759
+     * @NoAdminRequired
760
+     *
761
+     * @return DataResponse
762
+     */
763
+    public function stats() {
764
+        $userCount = 0;
765
+        if ($this->isAdmin) {
766
+            $countByBackend = $this->userManager->countUsers();
767
+
768
+            if (!empty($countByBackend)) {
769
+                foreach ($countByBackend as $count) {
770
+                    $userCount += $count;
771
+                }
772
+            }
773
+        } else {
774
+            $groups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($this->userSession->getUser());
775
+
776
+            $uniqueUsers = [];
777
+            foreach ($groups as $group) {
778
+                foreach($group->getUsers() as $uid => $displayName) {
779
+                    $uniqueUsers[$uid] = true;
780
+                }
781
+            }
782
+
783
+            $userCount = count($uniqueUsers);
784
+        }
785
+
786
+        return new DataResponse(
787
+            [
788
+                'totalUsers' => $userCount
789
+            ]
790
+        );
791
+    }
792
+
793
+
794
+    /**
795
+     * Set the displayName of a user
796
+     *
797
+     * @NoAdminRequired
798
+     * @NoSubadminRequired
799
+     * @PasswordConfirmationRequired
800
+     * @todo merge into saveUserSettings
801
+     *
802
+     * @param string $username
803
+     * @param string $displayName
804
+     * @return DataResponse
805
+     */
806
+    public function setDisplayName($username, $displayName) {
807
+        $currentUser = $this->userSession->getUser();
808
+        $user = $this->userManager->get($username);
809
+
810
+        if ($user === null ||
811
+            !$user->canChangeDisplayName() ||
812
+            (
813
+                !$this->groupManager->isAdmin($currentUser->getUID()) &&
814
+                !$this->groupManager->getSubAdmin()->isUserAccessible($currentUser, $user) &&
815
+                $currentUser->getUID() !== $username
816
+
817
+            )
818
+        ) {
819
+            return new DataResponse([
820
+                'status' => 'error',
821
+                'data' => [
822
+                    'message' => $this->l10n->t('Authentication error'),
823
+                ],
824
+            ]);
825
+        }
826
+
827
+        $userData = $this->accountManager->getUser($user);
828
+        $userData[AccountManager::PROPERTY_DISPLAYNAME]['value'] = $displayName;
829
+
830
+
831
+        try {
832
+            $this->saveUserSettings($user, $userData);
833
+            return new DataResponse([
834
+                'status' => 'success',
835
+                'data' => [
836
+                    'message' => $this->l10n->t('Your full name has been changed.'),
837
+                    'username' => $username,
838
+                    'displayName' => $displayName,
839
+                ],
840
+            ]);
841
+        } catch (ForbiddenException $e) {
842
+            return new DataResponse([
843
+                'status' => 'error',
844
+                'data' => [
845
+                    'message' => $e->getMessage(),
846
+                    'displayName' => $user->getDisplayName(),
847
+                ],
848
+            ]);
849
+        }
850
+    }
851
+
852
+    /**
853
+     * Set the mail address of a user
854
+     *
855
+     * @NoAdminRequired
856
+     * @NoSubadminRequired
857
+     * @PasswordConfirmationRequired
858
+     *
859
+     * @param string $id
860
+     * @param string $mailAddress
861
+     * @return DataResponse
862
+     */
863
+    public function setEMailAddress($id, $mailAddress) {
864
+        $user = $this->userManager->get($id);
865
+        if (!$this->isAdmin
866
+            && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)
867
+        ) {
868
+            return new DataResponse(
869
+                [
870
+                    'status' => 'error',
871
+                    'data' => [
872
+                        'message' => (string) $this->l10n->t('Forbidden')
873
+                    ]
874
+                ],
875
+                Http::STATUS_FORBIDDEN
876
+            );
877
+        }
878
+
879
+        if($mailAddress !== '' && !$this->mailer->validateMailAddress($mailAddress)) {
880
+            return new DataResponse(
881
+                [
882
+                    'status' => 'error',
883
+                    'data' => [
884
+                        'message' => (string) $this->l10n->t('Invalid mail address')
885
+                    ]
886
+                ],
887
+                Http::STATUS_UNPROCESSABLE_ENTITY
888
+            );
889
+        }
890
+
891
+        if (!$user) {
892
+            return new DataResponse(
893
+                [
894
+                    'status' => 'error',
895
+                    'data' => [
896
+                        'message' => (string) $this->l10n->t('Invalid user')
897
+                    ]
898
+                ],
899
+                Http::STATUS_UNPROCESSABLE_ENTITY
900
+            );
901
+        }
902
+        // this is the only permission a backend provides and is also used
903
+        // for the permission of setting a email address
904
+        if (!$user->canChangeDisplayName()) {
905
+            return new DataResponse(
906
+                [
907
+                    'status' => 'error',
908
+                    'data' => [
909
+                        'message' => (string) $this->l10n->t('Unable to change mail address')
910
+                    ]
911
+                ],
912
+                Http::STATUS_FORBIDDEN
913
+            );
914
+        }
915
+
916
+        $userData = $this->accountManager->getUser($user);
917
+        $userData[AccountManager::PROPERTY_EMAIL]['value'] = $mailAddress;
918
+
919
+        try {
920
+            $this->saveUserSettings($user, $userData);
921
+            return new DataResponse(
922
+                [
923
+                    'status' => 'success',
924
+                    'data' => [
925
+                        'username' => $id,
926
+                        'mailAddress' => $mailAddress,
927
+                        'message' => (string) $this->l10n->t('Email saved')
928
+                    ]
929
+                ],
930
+                Http::STATUS_OK
931
+            );
932
+        } catch (ForbiddenException $e) {
933
+            return new DataResponse([
934
+                'status' => 'error',
935
+                'data' => [
936
+                    'message' => $e->getMessage()
937
+                ],
938
+            ]);
939
+        }
940
+    }
941 941
 
942 942
 }
Please login to merge, or discard this patch.
Spacing   +35 added lines, -35 removed lines patch added patch discarded remove patch
@@ -133,7 +133,7 @@  discard block
 block discarded – undo
133 133
 
134 134
 		// check for encryption state - TODO see formatUserForIndex
135 135
 		$this->isEncryptionAppEnabled = $appManager->isEnabledForUser('encryption');
136
-		if($this->isEncryptionAppEnabled) {
136
+		if ($this->isEncryptionAppEnabled) {
137 137
 			// putting this directly in empty is possible in PHP 5.5+
138 138
 			$result = $config->getAppValue('encryption', 'recoveryAdminEnabled', 0);
139 139
 			$this->isRestoreEnabled = !empty($result);
@@ -173,7 +173,7 @@  discard block
 block discarded – undo
173 173
 		}
174 174
 
175 175
 		$subAdminGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($user);
176
-		foreach($subAdminGroups as $key => $subAdminGroup) {
176
+		foreach ($subAdminGroups as $key => $subAdminGroup) {
177 177
 			$subAdminGroups[$key] = $subAdminGroup->getGID();
178 178
 		}
179 179
 
@@ -231,11 +231,11 @@  discard block
 block discarded – undo
231 231
 	 */
232 232
 	public function index($offset = 0, $limit = 10, $gid = '', $pattern = '', $backend = '') {
233 233
 		// Remove backends
234
-		if(!empty($backend)) {
234
+		if (!empty($backend)) {
235 235
 			$activeBackends = $this->userManager->getBackends();
236 236
 			$this->userManager->clearBackends();
237
-			foreach($activeBackends as $singleActiveBackend) {
238
-				if($backend === get_class($singleActiveBackend)) {
237
+			foreach ($activeBackends as $singleActiveBackend) {
238
+				if ($backend === get_class($singleActiveBackend)) {
239 239
 					$this->userManager->registerBackend($singleActiveBackend);
240 240
 					break;
241 241
 				}
@@ -244,14 +244,14 @@  discard block
 block discarded – undo
244 244
 
245 245
 		$users = [];
246 246
 		if ($this->isAdmin) {
247
-			if($gid !== '' && $gid !== '_disabledUsers') {
247
+			if ($gid !== '' && $gid !== '_disabledUsers') {
248 248
 				$batch = $this->getUsersForUID($this->groupManager->displayNamesInGroup($gid, $pattern, $limit, $offset));
249 249
 			} else {
250 250
 				$batch = $this->userManager->search($pattern, $limit, $offset);
251 251
 			}
252 252
 
253 253
 			foreach ($batch as $user) {
254
-				if( ($gid !== '_disabledUsers' && $user->isEnabled()) ||
254
+				if (($gid !== '_disabledUsers' && $user->isEnabled()) ||
255 255
 					($gid === '_disabledUsers' && !$user->isEnabled())
256 256
 				) {
257 257
 					$users[] = $this->formatUserForIndex($user);
@@ -268,17 +268,17 @@  discard block
 block discarded – undo
268 268
 			$subAdminOfGroups = $gids;
269 269
 
270 270
 			// Set the $gid parameter to an empty value if the subadmin has no rights to access a specific group
271
-			if($gid !== '' && $gid !== '_disabledUsers' && !in_array($gid, $subAdminOfGroups)) {
271
+			if ($gid !== '' && $gid !== '_disabledUsers' && !in_array($gid, $subAdminOfGroups)) {
272 272
 				$gid = '';
273 273
 			}
274 274
 
275 275
 			// Batch all groups the user is subadmin of when a group is specified
276 276
 			$batch = [];
277
-			if($gid === '') {
278
-				foreach($subAdminOfGroups as $group) {
277
+			if ($gid === '') {
278
+				foreach ($subAdminOfGroups as $group) {
279 279
 					$groupUsers = $this->groupManager->displayNamesInGroup($group, $pattern, $limit, $offset);
280 280
 
281
-					foreach($groupUsers as $uid => $displayName) {
281
+					foreach ($groupUsers as $uid => $displayName) {
282 282
 						$batch[$uid] = $displayName;
283 283
 					}
284 284
 				}
@@ -293,7 +293,7 @@  discard block
 block discarded – undo
293 293
 					$this->groupManager->getUserGroupIds($user),
294 294
 					$subAdminOfGroups
295 295
 				));
296
-				if( ($gid !== '_disabledUsers' && $user->isEnabled()) ||
296
+				if (($gid !== '_disabledUsers' && $user->isEnabled()) ||
297 297
 					($gid === '_disabledUsers' && !$user->isEnabled())
298 298
 				) {
299 299
 					$users[] = $this->formatUserForIndex($user, $userGroups);
@@ -314,11 +314,11 @@  discard block
 block discarded – undo
314 314
 	 * @param string $email
315 315
 	 * @return DataResponse
316 316
 	 */
317
-	public function create($username, $password, array $groups=[], $email='') {
318
-		if($email !== '' && !$this->mailer->validateMailAddress($email)) {
317
+	public function create($username, $password, array $groups = [], $email = '') {
318
+		if ($email !== '' && !$this->mailer->validateMailAddress($email)) {
319 319
 			return new DataResponse(
320 320
 				[
321
-					'message' => (string)$this->l10n->t('Invalid mail address')
321
+					'message' => (string) $this->l10n->t('Invalid mail address')
322 322
 				],
323 323
 				Http::STATUS_UNPROCESSABLE_ENTITY
324 324
 			);
@@ -330,7 +330,7 @@  discard block
 block discarded – undo
330 330
 			if (!empty($groups)) {
331 331
 				foreach ($groups as $key => $group) {
332 332
 					$groupObject = $this->groupManager->get($group);
333
-					if($groupObject === null) {
333
+					if ($groupObject === null) {
334 334
 						unset($groups[$key]);
335 335
 						continue;
336 336
 					}
@@ -354,7 +354,7 @@  discard block
 block discarded – undo
354 354
 		if ($this->userManager->userExists($username)) {
355 355
 			return new DataResponse(
356 356
 				[
357
-					'message' => (string)$this->l10n->t('A user with that name already exists.')
357
+					'message' => (string) $this->l10n->t('A user with that name already exists.')
358 358
 				],
359 359
 				Http::STATUS_CONFLICT
360 360
 			);
@@ -365,7 +365,7 @@  discard block
 block discarded – undo
365 365
 			if ($email === '') {
366 366
 				return new DataResponse(
367 367
 					[
368
-						'message' => (string)$this->l10n->t('To send a password link to the user an email address is required.')
368
+						'message' => (string) $this->l10n->t('To send a password link to the user an email address is required.')
369 369
 					],
370 370
 					Http::STATUS_UNPROCESSABLE_ENTITY
371 371
 				);
@@ -390,12 +390,12 @@  discard block
 block discarded – undo
390 390
 			);
391 391
 		}
392 392
 
393
-		if($user instanceof IUser) {
394
-			if($groups !== null) {
395
-				foreach($groups as $groupName) {
393
+		if ($user instanceof IUser) {
394
+			if ($groups !== null) {
395
+				foreach ($groups as $groupName) {
396 396
 					$group = $this->groupManager->get($groupName);
397 397
 
398
-					if(empty($group)) {
398
+					if (empty($group)) {
399 399
 						$group = $this->groupManager->createGroup($groupName);
400 400
 					}
401 401
 					$group->addUser($user);
@@ -404,13 +404,13 @@  discard block
 block discarded – undo
404 404
 			/**
405 405
 			 * Send new user mail only if a mail is set
406 406
 			 */
407
-			if($email !== '') {
407
+			if ($email !== '') {
408 408
 				$user->setEMailAddress($email);
409 409
 				try {
410 410
 					$emailTemplate = $this->newUserMailHelper->generateTemplate($user, $generatePasswordResetToken);
411 411
 					$this->newUserMailHelper->sendMail($user, $emailTemplate);
412
-				} catch(\Exception $e) {
413
-					$this->log->error("Can't send new user mail to $email: " . $e->getMessage(), ['app' => 'settings']);
412
+				} catch (\Exception $e) {
413
+					$this->log->error("Can't send new user mail to $email: ".$e->getMessage(), ['app' => 'settings']);
414 414
 				}
415 415
 			}
416 416
 			// fetch users groups
@@ -442,7 +442,7 @@  discard block
 block discarded – undo
442 442
 		$userId = $this->userSession->getUser()->getUID();
443 443
 		$user = $this->userManager->get($id);
444 444
 
445
-		if($userId === $id) {
445
+		if ($userId === $id) {
446 446
 			return new DataResponse(
447 447
 				[
448 448
 					'status' => 'error',
@@ -454,20 +454,20 @@  discard block
 block discarded – undo
454 454
 			);
455 455
 		}
456 456
 
457
-		if(!$this->isAdmin && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)) {
457
+		if (!$this->isAdmin && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)) {
458 458
 			return new DataResponse(
459 459
 				[
460 460
 					'status' => 'error',
461 461
 					'data' => [
462
-						'message' => (string)$this->l10n->t('Authentication error')
462
+						'message' => (string) $this->l10n->t('Authentication error')
463 463
 					]
464 464
 				],
465 465
 				Http::STATUS_FORBIDDEN
466 466
 			);
467 467
 		}
468 468
 
469
-		if($user) {
470
-			if($user->delete()) {
469
+		if ($user) {
470
+			if ($user->delete()) {
471 471
 				return new DataResponse(
472 472
 					[
473 473
 						'status' => 'success',
@@ -484,7 +484,7 @@  discard block
 block discarded – undo
484 484
 			[
485 485
 				'status' => 'error',
486 486
 				'data' => [
487
-					'message' => (string)$this->l10n->t('Unable to delete user.')
487
+					'message' => (string) $this->l10n->t('Unable to delete user.')
488 488
 				]
489 489
 			],
490 490
 			Http::STATUS_FORBIDDEN
@@ -513,7 +513,7 @@  discard block
 block discarded – undo
513 513
 		}
514 514
 
515 515
 		if ($user) {
516
-			if(!$this->isAdmin && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)) {
516
+			if (!$this->isAdmin && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)) {
517 517
 				return new DataResponse(
518 518
 					[
519 519
 						'status' => 'error',
@@ -570,7 +570,7 @@  discard block
 block discarded – undo
570 570
 			);
571 571
 		}
572 572
 
573
-		if($user) {
573
+		if ($user) {
574 574
 			if (!$this->isAdmin && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)) {
575 575
 				return new DataResponse(
576 576
 					[
@@ -775,7 +775,7 @@  discard block
 block discarded – undo
775 775
 
776 776
 			$uniqueUsers = [];
777 777
 			foreach ($groups as $group) {
778
-				foreach($group->getUsers() as $uid => $displayName) {
778
+				foreach ($group->getUsers() as $uid => $displayName) {
779 779
 					$uniqueUsers[$uid] = true;
780 780
 				}
781 781
 			}
@@ -876,7 +876,7 @@  discard block
 block discarded – undo
876 876
 			);
877 877
 		}
878 878
 
879
-		if($mailAddress !== '' && !$this->mailer->validateMailAddress($mailAddress)) {
879
+		if ($mailAddress !== '' && !$this->mailer->validateMailAddress($mailAddress)) {
880 880
 			return new DataResponse(
881 881
 				[
882 882
 					'status' => 'error',
Please login to merge, or discard this patch.