Completed
Push — master ( 5aaa8a...afaee6 )
by Morris
12:26
created
settings/Application.php 1 patch
Indentation   +92 added lines, -92 removed lines patch added patch discarded remove patch
@@ -50,106 +50,106 @@
 block discarded – undo
50 50
 class Application extends App {
51 51
 
52 52
 
53
-	/**
54
-	 * @param array $urlParams
55
-	 */
56
-	public function __construct(array $urlParams=[]){
57
-		parent::__construct('settings', $urlParams);
53
+    /**
54
+     * @param array $urlParams
55
+     */
56
+    public function __construct(array $urlParams=[]){
57
+        parent::__construct('settings', $urlParams);
58 58
 
59
-		$container = $this->getContainer();
59
+        $container = $this->getContainer();
60 60
 
61
-		// Register Middleware
62
-		$container->registerAlias('SubadminMiddleware', SubadminMiddleware::class);
63
-		$container->registerMiddleWare('SubadminMiddleware');
61
+        // Register Middleware
62
+        $container->registerAlias('SubadminMiddleware', SubadminMiddleware::class);
63
+        $container->registerMiddleWare('SubadminMiddleware');
64 64
 
65
-		/**
66
-		 * Core class wrappers
67
-		 */
68
-		/** FIXME: Remove once OC_User is non-static and mockable */
69
-		$container->registerService('isAdmin', function() {
70
-			return \OC_User::isAdminUser(\OC_User::getUser());
71
-		});
72
-		/** FIXME: Remove once OC_SubAdmin is non-static and mockable */
73
-		$container->registerService('isSubAdmin', function(IContainer $c) {
74
-			$userObject = \OC::$server->getUserSession()->getUser();
75
-			$isSubAdmin = false;
76
-			if($userObject !== null) {
77
-				$isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
78
-			}
79
-			return $isSubAdmin;
80
-		});
81
-		$container->registerService('userCertificateManager', function(IContainer $c) {
82
-			return $c->query('ServerContainer')->getCertificateManager();
83
-		}, false);
84
-		$container->registerService('systemCertificateManager', function (IContainer $c) {
85
-			return $c->query('ServerContainer')->getCertificateManager(null);
86
-		}, false);
87
-		$container->registerService(IProvider::class, function (IContainer $c) {
88
-			return $c->query('ServerContainer')->query(IProvider::class);
89
-		});
90
-		$container->registerService(IManager::class, function (IContainer $c) {
91
-			return $c->query('ServerContainer')->getSettingsManager();
92
-		});
65
+        /**
66
+         * Core class wrappers
67
+         */
68
+        /** FIXME: Remove once OC_User is non-static and mockable */
69
+        $container->registerService('isAdmin', function() {
70
+            return \OC_User::isAdminUser(\OC_User::getUser());
71
+        });
72
+        /** FIXME: Remove once OC_SubAdmin is non-static and mockable */
73
+        $container->registerService('isSubAdmin', function(IContainer $c) {
74
+            $userObject = \OC::$server->getUserSession()->getUser();
75
+            $isSubAdmin = false;
76
+            if($userObject !== null) {
77
+                $isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
78
+            }
79
+            return $isSubAdmin;
80
+        });
81
+        $container->registerService('userCertificateManager', function(IContainer $c) {
82
+            return $c->query('ServerContainer')->getCertificateManager();
83
+        }, false);
84
+        $container->registerService('systemCertificateManager', function (IContainer $c) {
85
+            return $c->query('ServerContainer')->getCertificateManager(null);
86
+        }, false);
87
+        $container->registerService(IProvider::class, function (IContainer $c) {
88
+            return $c->query('ServerContainer')->query(IProvider::class);
89
+        });
90
+        $container->registerService(IManager::class, function (IContainer $c) {
91
+            return $c->query('ServerContainer')->getSettingsManager();
92
+        });
93 93
 
94
-		$container->registerService(NewUserMailHelper::class, function (IContainer $c) {
95
-			/** @var Server $server */
96
-			$server = $c->query('ServerContainer');
97
-			/** @var Defaults $defaults */
98
-			$defaults = $server->query(Defaults::class);
94
+        $container->registerService(NewUserMailHelper::class, function (IContainer $c) {
95
+            /** @var Server $server */
96
+            $server = $c->query('ServerContainer');
97
+            /** @var Defaults $defaults */
98
+            $defaults = $server->query(Defaults::class);
99 99
 
100
-			return new NewUserMailHelper(
101
-				$defaults,
102
-				$server->getURLGenerator(),
103
-				$server->getL10NFactory(),
104
-				$server->getMailer(),
105
-				$server->getSecureRandom(),
106
-				new TimeFactory(),
107
-				$server->getConfig(),
108
-				$server->getCrypto(),
109
-				Util::getDefaultEmailAddress('no-reply')
110
-			);
111
-		});
112
-	}
100
+            return new NewUserMailHelper(
101
+                $defaults,
102
+                $server->getURLGenerator(),
103
+                $server->getL10NFactory(),
104
+                $server->getMailer(),
105
+                $server->getSecureRandom(),
106
+                new TimeFactory(),
107
+                $server->getConfig(),
108
+                $server->getCrypto(),
109
+                Util::getDefaultEmailAddress('no-reply')
110
+            );
111
+        });
112
+    }
113 113
 
114
-	public function register() {
115
-		$activityManager = $this->getContainer()->getServer()->getActivityManager();
116
-		$activityManager->registerSetting(Setting::class); // FIXME move to info.xml
117
-		$activityManager->registerProvider(Provider::class); // FIXME move to info.xml
118
-		$activityManager->registerFilter(SecurityFilter::class); // FIXME move to info.xml
119
-		$activityManager->registerSetting(SecuritySetting::class); // FIXME move to info.xml
120
-		$activityManager->registerProvider(SecurityProvider::class); // FIXME move to info.xml
114
+    public function register() {
115
+        $activityManager = $this->getContainer()->getServer()->getActivityManager();
116
+        $activityManager->registerSetting(Setting::class); // FIXME move to info.xml
117
+        $activityManager->registerProvider(Provider::class); // FIXME move to info.xml
118
+        $activityManager->registerFilter(SecurityFilter::class); // FIXME move to info.xml
119
+        $activityManager->registerSetting(SecuritySetting::class); // FIXME move to info.xml
120
+        $activityManager->registerProvider(SecurityProvider::class); // FIXME move to info.xml
121 121
 
122
-		Util::connectHook('OC_User', 'post_setPassword', $this, 'onChangePassword');
123
-		Util::connectHook('OC_User', 'changeUser', $this, 'onChangeInfo');
124
-	}
122
+        Util::connectHook('OC_User', 'post_setPassword', $this, 'onChangePassword');
123
+        Util::connectHook('OC_User', 'changeUser', $this, 'onChangeInfo');
124
+    }
125 125
 
126
-	/**
127
-	 * @param array $parameters
128
-	 * @throws \InvalidArgumentException
129
-	 * @throws \BadMethodCallException
130
-	 * @throws \Exception
131
-	 * @throws \OCP\AppFramework\QueryException
132
-	 */
133
-	public function onChangePassword(array $parameters) {
134
-		/** @var Hooks $hooks */
135
-		$hooks = $this->getContainer()->query(Hooks::class);
136
-		$hooks->onChangePassword($parameters['uid']);
137
-	}
126
+    /**
127
+     * @param array $parameters
128
+     * @throws \InvalidArgumentException
129
+     * @throws \BadMethodCallException
130
+     * @throws \Exception
131
+     * @throws \OCP\AppFramework\QueryException
132
+     */
133
+    public function onChangePassword(array $parameters) {
134
+        /** @var Hooks $hooks */
135
+        $hooks = $this->getContainer()->query(Hooks::class);
136
+        $hooks->onChangePassword($parameters['uid']);
137
+    }
138 138
 
139
-	/**
140
-	 * @param array $parameters
141
-	 * @throws \InvalidArgumentException
142
-	 * @throws \BadMethodCallException
143
-	 * @throws \Exception
144
-	 * @throws \OCP\AppFramework\QueryException
145
-	 */
146
-	public function onChangeInfo(array $parameters) {
147
-		if ($parameters['feature'] !== 'eMailAddress') {
148
-			return;
149
-		}
139
+    /**
140
+     * @param array $parameters
141
+     * @throws \InvalidArgumentException
142
+     * @throws \BadMethodCallException
143
+     * @throws \Exception
144
+     * @throws \OCP\AppFramework\QueryException
145
+     */
146
+    public function onChangeInfo(array $parameters) {
147
+        if ($parameters['feature'] !== 'eMailAddress') {
148
+            return;
149
+        }
150 150
 
151
-		/** @var Hooks $hooks */
152
-		$hooks = $this->getContainer()->query(Hooks::class);
153
-		$hooks->onChangeEmail($parameters['user'], $parameters['old_value']);
154
-	}
151
+        /** @var Hooks $hooks */
152
+        $hooks = $this->getContainer()->query(Hooks::class);
153
+        $hooks->onChangeEmail($parameters['user'], $parameters['old_value']);
154
+    }
155 155
 }
Please login to merge, or discard this patch.
settings/Mailer/NewUserMailHelper.php 1 patch
Indentation   +121 added lines, -121 removed lines patch added patch discarded remove patch
@@ -39,133 +39,133 @@
 block discarded – undo
39 39
 use OCP\Security\ISecureRandom;
40 40
 
41 41
 class NewUserMailHelper {
42
-	/** @var Defaults */
43
-	private $themingDefaults;
44
-	/** @var IURLGenerator */
45
-	private $urlGenerator;
46
-	/** @var IFactory */
47
-	private $l10nFactory;
48
-	/** @var IMailer */
49
-	private $mailer;
50
-	/** @var ISecureRandom */
51
-	private $secureRandom;
52
-	/** @var ITimeFactory */
53
-	private $timeFactory;
54
-	/** @var IConfig */
55
-	private $config;
56
-	/** @var ICrypto */
57
-	private $crypto;
58
-	/** @var string */
59
-	private $fromAddress;
42
+    /** @var Defaults */
43
+    private $themingDefaults;
44
+    /** @var IURLGenerator */
45
+    private $urlGenerator;
46
+    /** @var IFactory */
47
+    private $l10nFactory;
48
+    /** @var IMailer */
49
+    private $mailer;
50
+    /** @var ISecureRandom */
51
+    private $secureRandom;
52
+    /** @var ITimeFactory */
53
+    private $timeFactory;
54
+    /** @var IConfig */
55
+    private $config;
56
+    /** @var ICrypto */
57
+    private $crypto;
58
+    /** @var string */
59
+    private $fromAddress;
60 60
 
61
-	/**
62
-	 * @param Defaults $themingDefaults
63
-	 * @param IURLGenerator $urlGenerator
64
-	 * @param IFactory $l10nFactory
65
-	 * @param IMailer $mailer
66
-	 * @param ISecureRandom $secureRandom
67
-	 * @param ITimeFactory $timeFactory
68
-	 * @param IConfig $config
69
-	 * @param ICrypto $crypto
70
-	 * @param string $fromAddress
71
-	 */
72
-	public function __construct(Defaults $themingDefaults,
73
-								IURLGenerator $urlGenerator,
74
-								IFactory $l10nFactory,
75
-								IMailer $mailer,
76
-								ISecureRandom $secureRandom,
77
-								ITimeFactory $timeFactory,
78
-								IConfig $config,
79
-								ICrypto $crypto,
80
-								$fromAddress) {
81
-		$this->themingDefaults = $themingDefaults;
82
-		$this->urlGenerator = $urlGenerator;
83
-		$this->l10nFactory = $l10nFactory;
84
-		$this->mailer = $mailer;
85
-		$this->secureRandom = $secureRandom;
86
-		$this->timeFactory = $timeFactory;
87
-		$this->config = $config;
88
-		$this->crypto = $crypto;
89
-		$this->fromAddress = $fromAddress;
90
-	}
61
+    /**
62
+     * @param Defaults $themingDefaults
63
+     * @param IURLGenerator $urlGenerator
64
+     * @param IFactory $l10nFactory
65
+     * @param IMailer $mailer
66
+     * @param ISecureRandom $secureRandom
67
+     * @param ITimeFactory $timeFactory
68
+     * @param IConfig $config
69
+     * @param ICrypto $crypto
70
+     * @param string $fromAddress
71
+     */
72
+    public function __construct(Defaults $themingDefaults,
73
+                                IURLGenerator $urlGenerator,
74
+                                IFactory $l10nFactory,
75
+                                IMailer $mailer,
76
+                                ISecureRandom $secureRandom,
77
+                                ITimeFactory $timeFactory,
78
+                                IConfig $config,
79
+                                ICrypto $crypto,
80
+                                $fromAddress) {
81
+        $this->themingDefaults = $themingDefaults;
82
+        $this->urlGenerator = $urlGenerator;
83
+        $this->l10nFactory = $l10nFactory;
84
+        $this->mailer = $mailer;
85
+        $this->secureRandom = $secureRandom;
86
+        $this->timeFactory = $timeFactory;
87
+        $this->config = $config;
88
+        $this->crypto = $crypto;
89
+        $this->fromAddress = $fromAddress;
90
+    }
91 91
 
92
-	/**
93
-	 * @param IUser $user
94
-	 * @param bool $generatePasswordResetToken
95
-	 * @return IEMailTemplate
96
-	 */
97
-	public function generateTemplate(IUser $user, $generatePasswordResetToken = false) {
98
-		$userId = $user->getUID();
99
-		$lang = $this->config->getUserValue($userId, 'core', 'lang', 'en');
100
-		if (!$this->l10nFactory->languageExists('settings', $lang)) {
101
-			$lang = 'en';
102
-		}
92
+    /**
93
+     * @param IUser $user
94
+     * @param bool $generatePasswordResetToken
95
+     * @return IEMailTemplate
96
+     */
97
+    public function generateTemplate(IUser $user, $generatePasswordResetToken = false) {
98
+        $userId = $user->getUID();
99
+        $lang = $this->config->getUserValue($userId, 'core', 'lang', 'en');
100
+        if (!$this->l10nFactory->languageExists('settings', $lang)) {
101
+            $lang = 'en';
102
+        }
103 103
 
104
-		$l10n = $this->l10nFactory->get('settings', $lang);
104
+        $l10n = $this->l10nFactory->get('settings', $lang);
105 105
 
106
-		if ($generatePasswordResetToken) {
107
-			$token = $this->secureRandom->generate(
108
-				21,
109
-				ISecureRandom::CHAR_DIGITS .
110
-				ISecureRandom::CHAR_LOWER .
111
-				ISecureRandom::CHAR_UPPER
112
-			);
113
-			$tokenValue = $this->timeFactory->getTime() . ':' . $token;
114
-			$mailAddress = (null !== $user->getEMailAddress()) ? $user->getEMailAddress() : '';
115
-			$encryptedValue = $this->crypto->encrypt($tokenValue, $mailAddress . $this->config->getSystemValue('secret'));
116
-			$this->config->setUserValue($user->getUID(), 'core', 'lostpassword', $encryptedValue);
117
-			$link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', ['userId' => $user->getUID(), 'token' => $token]);
118
-		} else {
119
-			$link = $this->urlGenerator->getAbsoluteURL('/');
120
-		}
121
-		$displayName = $user->getDisplayName();
106
+        if ($generatePasswordResetToken) {
107
+            $token = $this->secureRandom->generate(
108
+                21,
109
+                ISecureRandom::CHAR_DIGITS .
110
+                ISecureRandom::CHAR_LOWER .
111
+                ISecureRandom::CHAR_UPPER
112
+            );
113
+            $tokenValue = $this->timeFactory->getTime() . ':' . $token;
114
+            $mailAddress = (null !== $user->getEMailAddress()) ? $user->getEMailAddress() : '';
115
+            $encryptedValue = $this->crypto->encrypt($tokenValue, $mailAddress . $this->config->getSystemValue('secret'));
116
+            $this->config->setUserValue($user->getUID(), 'core', 'lostpassword', $encryptedValue);
117
+            $link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', ['userId' => $user->getUID(), 'token' => $token]);
118
+        } else {
119
+            $link = $this->urlGenerator->getAbsoluteURL('/');
120
+        }
121
+        $displayName = $user->getDisplayName();
122 122
 
123
-		$emailTemplate = $this->mailer->createEMailTemplate('settings.Welcome', [
124
-			'link' => $link,
125
-			'displayname' => $displayName,
126
-			'userid' => $userId,
127
-			'instancename' => $this->themingDefaults->getName(),
128
-			'resetTokenGenerated' => $generatePasswordResetToken,
129
-		]);
123
+        $emailTemplate = $this->mailer->createEMailTemplate('settings.Welcome', [
124
+            'link' => $link,
125
+            'displayname' => $displayName,
126
+            'userid' => $userId,
127
+            'instancename' => $this->themingDefaults->getName(),
128
+            'resetTokenGenerated' => $generatePasswordResetToken,
129
+        ]);
130 130
 
131
-		$emailTemplate->setSubject($l10n->t('Your %s account was created', [$this->themingDefaults->getName()]));
132
-		$emailTemplate->addHeader();
133
-		if ($displayName === $userId) {
134
-			$emailTemplate->addHeading($l10n->t('Welcome aboard'));
135
-		} else {
136
-			$emailTemplate->addHeading($l10n->t('Welcome aboard %s', [$displayName]));
137
-		}
138
-		$emailTemplate->addBodyText($l10n->t('Welcome to your %s account, you can add, protect, and share your data.', [$this->themingDefaults->getName()]));
139
-		$emailTemplate->addBodyText($l10n->t('Your username is: %s', [$userId]));
140
-		if ($generatePasswordResetToken) {
141
-			$leftButtonText = $l10n->t('Set your password');
142
-		} else {
143
-			$leftButtonText = $l10n->t('Go to %s', [$this->themingDefaults->getName()]);
144
-		}
145
-		$emailTemplate->addBodyButtonGroup(
146
-			$leftButtonText,
147
-			$link,
148
-			$l10n->t('Install Client'),
149
-			'https://nextcloud.com/install/#install-clients'
150
-		);
151
-		$emailTemplate->addFooter();
131
+        $emailTemplate->setSubject($l10n->t('Your %s account was created', [$this->themingDefaults->getName()]));
132
+        $emailTemplate->addHeader();
133
+        if ($displayName === $userId) {
134
+            $emailTemplate->addHeading($l10n->t('Welcome aboard'));
135
+        } else {
136
+            $emailTemplate->addHeading($l10n->t('Welcome aboard %s', [$displayName]));
137
+        }
138
+        $emailTemplate->addBodyText($l10n->t('Welcome to your %s account, you can add, protect, and share your data.', [$this->themingDefaults->getName()]));
139
+        $emailTemplate->addBodyText($l10n->t('Your username is: %s', [$userId]));
140
+        if ($generatePasswordResetToken) {
141
+            $leftButtonText = $l10n->t('Set your password');
142
+        } else {
143
+            $leftButtonText = $l10n->t('Go to %s', [$this->themingDefaults->getName()]);
144
+        }
145
+        $emailTemplate->addBodyButtonGroup(
146
+            $leftButtonText,
147
+            $link,
148
+            $l10n->t('Install Client'),
149
+            'https://nextcloud.com/install/#install-clients'
150
+        );
151
+        $emailTemplate->addFooter();
152 152
 
153
-		return $emailTemplate;
154
-	}
153
+        return $emailTemplate;
154
+    }
155 155
 
156
-	/**
157
-	 * Sends a welcome mail to $user
158
-	 *
159
-	 * @param IUser $user
160
-	 * @param IEmailTemplate $emailTemplate
161
-	 * @throws \Exception If mail could not be sent
162
-	 */
163
-	public function sendMail(IUser $user,
164
-							 IEMailTemplate $emailTemplate) {
165
-		$message = $this->mailer->createMessage();
166
-		$message->setTo([$user->getEMailAddress() => $user->getDisplayName()]);
167
-		$message->setFrom([$this->fromAddress => $this->themingDefaults->getName()]);
168
-		$message->useTemplate($emailTemplate);
169
-		$this->mailer->send($message);
170
-	}
156
+    /**
157
+     * Sends a welcome mail to $user
158
+     *
159
+     * @param IUser $user
160
+     * @param IEmailTemplate $emailTemplate
161
+     * @throws \Exception If mail could not be sent
162
+     */
163
+    public function sendMail(IUser $user,
164
+                                IEMailTemplate $emailTemplate) {
165
+        $message = $this->mailer->createMessage();
166
+        $message->setTo([$user->getEMailAddress() => $user->getDisplayName()]);
167
+        $message->setFrom([$this->fromAddress => $this->themingDefaults->getName()]);
168
+        $message->useTemplate($emailTemplate);
169
+        $this->mailer->send($message);
170
+    }
171 171
 }
Please login to merge, or discard this patch.
apps/provisioning_api/lib/Controller/UsersController.php 2 patches
Indentation   +855 added lines, -855 removed lines patch added patch discarded remove patch
@@ -54,859 +54,859 @@
 block discarded – undo
54 54
 
55 55
 class UsersController extends AUserData {
56 56
 
57
-	/** @var IAppManager */
58
-	private $appManager;
59
-	/** @var ILogger */
60
-	private $logger;
61
-	/** @var IFactory */
62
-	private $l10nFactory;
63
-	/** @var NewUserMailHelper */
64
-	private $newUserMailHelper;
65
-	/** @var FederatedFileSharingFactory */
66
-	private $federatedFileSharingFactory;
67
-	/** @var ISecureRandom */
68
-	private $secureRandom;
69
-
70
-	/**
71
-	 * @param string $appName
72
-	 * @param IRequest $request
73
-	 * @param IUserManager $userManager
74
-	 * @param IConfig $config
75
-	 * @param IAppManager $appManager
76
-	 * @param IGroupManager $groupManager
77
-	 * @param IUserSession $userSession
78
-	 * @param AccountManager $accountManager
79
-	 * @param ILogger $logger
80
-	 * @param IFactory $l10nFactory
81
-	 * @param NewUserMailHelper $newUserMailHelper
82
-	 * @param FederatedFileSharingFactory $federatedFileSharingFactory
83
-	 * @param ISecureRandom $secureRandom
84
-	 */
85
-	public function __construct(string $appName,
86
-								IRequest $request,
87
-								IUserManager $userManager,
88
-								IConfig $config,
89
-								IAppManager $appManager,
90
-								IGroupManager $groupManager,
91
-								IUserSession $userSession,
92
-								AccountManager $accountManager,
93
-								ILogger $logger,
94
-								IFactory $l10nFactory,
95
-								NewUserMailHelper $newUserMailHelper,
96
-								FederatedFileSharingFactory $federatedFileSharingFactory,
97
-								ISecureRandom $secureRandom) {
98
-		parent::__construct($appName,
99
-							$request,
100
-							$userManager,
101
-							$config,
102
-							$groupManager,
103
-							$userSession,
104
-							$accountManager);
105
-
106
-		$this->appManager = $appManager;
107
-		$this->logger = $logger;
108
-		$this->l10nFactory = $l10nFactory;
109
-		$this->newUserMailHelper = $newUserMailHelper;
110
-		$this->federatedFileSharingFactory = $federatedFileSharingFactory;
111
-		$this->secureRandom = $secureRandom;
112
-	}
113
-
114
-	/**
115
-	 * @NoAdminRequired
116
-	 *
117
-	 * returns a list of users
118
-	 *
119
-	 * @param string $search
120
-	 * @param int $limit
121
-	 * @param int $offset
122
-	 * @return DataResponse
123
-	 */
124
-	public function getUsers(string $search = '', $limit = null, $offset = 0): DataResponse {
125
-		$user = $this->userSession->getUser();
126
-		$users = [];
127
-
128
-		// Admin? Or SubAdmin?
129
-		$uid = $user->getUID();
130
-		$subAdminManager = $this->groupManager->getSubAdmin();
131
-		if ($this->groupManager->isAdmin($uid)){
132
-			$users = $this->userManager->search($search, $limit, $offset);
133
-		} else if ($subAdminManager->isSubAdmin($user)) {
134
-			$subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
135
-			foreach ($subAdminOfGroups as $key => $group) {
136
-				$subAdminOfGroups[$key] = $group->getGID();
137
-			}
138
-
139
-			$users = [];
140
-			foreach ($subAdminOfGroups as $group) {
141
-				$users = array_merge($users, $this->groupManager->displayNamesInGroup($group, $search, $limit, $offset));
142
-			}
143
-		}
144
-
145
-		$users = array_keys($users);
146
-
147
-		return new DataResponse([
148
-			'users' => $users
149
-		]);
150
-	}
151
-
152
-	/**
153
-	 * @NoAdminRequired
154
-	 *
155
-	 * returns a list of users and their data
156
-	 */
157
-	public function getUsersDetails(string $search = '', $limit = null, $offset = 0): DataResponse {
158
-		$currentUser = $this->userSession->getUser();
159
-		$users = [];
160
-
161
-		// Admin? Or SubAdmin?
162
-		$uid = $currentUser->getUID();
163
-		$subAdminManager = $this->groupManager->getSubAdmin();
164
-		if ($this->groupManager->isAdmin($uid)){
165
-			$users = $this->userManager->search($search, $limit, $offset);
166
-			$users = array_keys($users);
167
-		} else if ($subAdminManager->isSubAdmin($currentUser)) {
168
-			$subAdminOfGroups = $subAdminManager->getSubAdminsGroups($currentUser);
169
-			foreach ($subAdminOfGroups as $key => $group) {
170
-				$subAdminOfGroups[$key] = $group->getGID();
171
-			}
172
-
173
-			$users = [];
174
-			foreach ($subAdminOfGroups as $group) {
175
-				$users[] = array_keys($this->groupManager->displayNamesInGroup($group, $search, $limit, $offset));
176
-			}
177
-			$users = array_merge(...$users);
178
-		}
179
-
180
-		$usersDetails = [];
181
-		foreach ($users as $userId) {
182
-			$userId = (string) $userId;
183
-			$userData = $this->getUserData($userId);
184
-			// Do not insert empty entry
185
-			if (!empty($userData)) {
186
-				$usersDetails[$userId] = $userData;
187
-			} else {
188
-				// Logged user does not have permissions to see this user
189
-				// only showing its id
190
-				$usersDetails[$userId] = ['id' => $userId];
191
-			}
192
-		}
193
-
194
-		return new DataResponse([
195
-			'users' => $usersDetails
196
-		]);
197
-	}
198
-
199
-	/**
200
-	 * @PasswordConfirmationRequired
201
-	 * @NoAdminRequired
202
-	 *
203
-	 * @param string $userid
204
-	 * @param string $password
205
-	 * @param string $displayName
206
-	 * @param string $email
207
-	 * @param array $groups
208
-	 * @param array $subadmins
209
-	 * @param string $quota
210
-	 * @param string $language
211
-	 * @return DataResponse
212
-	 * @throws OCSException
213
-	 */
214
-	public function addUser(string $userid,
215
-							string $password = '',
216
-							string $displayName = '',
217
-							string $email = '',
218
-							array $groups = [],
219
-							array $subadmin = [],
220
-							string $quota = '',
221
-							string $language = ''): DataResponse {
222
-		$user = $this->userSession->getUser();
223
-		$isAdmin = $this->groupManager->isAdmin($user->getUID());
224
-		$subAdminManager = $this->groupManager->getSubAdmin();
225
-
226
-		if ($this->userManager->userExists($userid)) {
227
-			$this->logger->error('Failed addUser attempt: User already exists.', ['app' => 'ocs_api']);
228
-			throw new OCSException('User already exists', 102);
229
-		}
230
-
231
-		if ($groups !== []) {
232
-			foreach ($groups as $group) {
233
-				if (!$this->groupManager->groupExists($group)) {
234
-					throw new OCSException('group '.$group.' does not exist', 104);
235
-				}
236
-				if (!$isAdmin && !$subAdminManager->isSubAdminOfGroup($user, $this->groupManager->get($group))) {
237
-					throw new OCSException('insufficient privileges for group '. $group, 105);
238
-				}
239
-			}
240
-		} else {
241
-			if (!$isAdmin) {
242
-				throw new OCSException('no group specified (required for subadmins)', 106);
243
-			}
244
-		}
245
-
246
-		$subadminGroups = [];
247
-		if ($subadmin !== []) {
248
-			foreach ($subadmin as $groupid) {
249
-				$group = $this->groupManager->get($groupid);
250
-				// Check if group exists
251
-				if ($group === null) {
252
-					throw new OCSException('Subadmin group does not exist',  102);
253
-				}
254
-				// Check if trying to make subadmin of admin group
255
-				if ($group->getGID() === 'admin') {
256
-					throw new OCSException('Cannot create subadmins for admin group', 103);
257
-				}
258
-				// Check if has permission to promote subadmins
259
-				if (!$subAdminManager->isSubAdminOfGroup($user, $group) && !$isAdmin) {
260
-					throw new OCSForbiddenException('No permissions to promote subadmins');
261
-				}
262
-				$subadminGroups[] = $group;
263
-			}
264
-		}
265
-
266
-		$generatePasswordResetToken = false;
267
-		if ($password === '') {
268
-			if ($email === '') {
269
-				throw new OCSException('To send a password link to the user an email address is required.', 108);
270
-			}
271
-
272
-			$password = $this->secureRandom->generate(10);
273
-			// Make sure we pass the password_policy
274
-			$password .= $this->secureRandom->generate(2, '$!.,;:-~+*[]{}()');
275
-			$generatePasswordResetToken = true;
276
-		}
277
-
278
-		try {
279
-			$newUser = $this->userManager->createUser($userid, $password);
280
-			$this->logger->info('Successful addUser call with userid: ' . $userid, ['app' => 'ocs_api']);
281
-
282
-			foreach ($groups as $group) {
283
-				$this->groupManager->get($group)->addUser($newUser);
284
-				$this->logger->info('Added userid ' . $userid . ' to group ' . $group, ['app' => 'ocs_api']);
285
-			}
286
-			foreach ($subadminGroups as $group) {
287
-				$subAdminManager->createSubAdmin($newUser, $group);
288
-			}
289
-
290
-			if ($displayName !== '') {
291
-				$this->editUser($userid, 'display', $displayName);
292
-			}
293
-
294
-			if ($quota !== '') {
295
-				$this->editUser($userid, 'quota', $quota);
296
-			}
297
-
298
-			if ($language !== '') {
299
-				$this->editUser($userid, 'language', $language);
300
-			}
301
-
302
-			// Send new user mail only if a mail is set
303
-			if ($email !== '') {
304
-				$newUser->setEMailAddress($email);
305
-				try {
306
-					$emailTemplate = $this->newUserMailHelper->generateTemplate($newUser, $generatePasswordResetToken);
307
-					$this->newUserMailHelper->sendMail($newUser, $emailTemplate);
308
-				} catch (\Exception $e) {
309
-					$this->logger->logException($e, [
310
-						'message' => "Can't send new user mail to $email",
311
-						'level' => ILogger::ERROR,
312
-						'app' => 'ocs_api',
313
-					]);
314
-					throw new OCSException('Unable to send the invitation mail', 109);
315
-				}
316
-			}
317
-
318
-			return new DataResponse();
319
-
320
-		} catch (HintException $e ) {
321
-			$this->logger->logException($e, [
322
-				'message' => 'Failed addUser attempt with hint exception.',
323
-				'level' => ILogger::WARN,
324
-				'app' => 'ocs_api',
325
-			]);
326
-			throw new OCSException($e->getHint(), 107);
327
-		} catch (\Exception $e) {
328
-			$this->logger->logException($e, [
329
-				'message' => 'Failed addUser attempt with exception.',
330
-				'level' => ILogger::ERROR,
331
-				'app' => 'ocs_api',
332
-			]);
333
-			throw new OCSException('Bad request', 101);
334
-		}
335
-	}
336
-
337
-	/**
338
-	 * @NoAdminRequired
339
-	 * @NoSubAdminRequired
340
-	 *
341
-	 * gets user info
342
-	 *
343
-	 * @param string $userId
344
-	 * @return DataResponse
345
-	 * @throws OCSException
346
-	 */
347
-	public function getUser(string $userId): DataResponse {
348
-		$data = $this->getUserData($userId);
349
-		// getUserData returns empty array if not enough permissions
350
-		if (empty($data)) {
351
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
352
-		}
353
-		return new DataResponse($data);
354
-	}
355
-
356
-	/**
357
-	 * @NoAdminRequired
358
-	 * @NoSubAdminRequired
359
-	 *
360
-	 * gets user info from the currently logged in user
361
-	 *
362
-	 * @return DataResponse
363
-	 * @throws OCSException
364
-	 */
365
-	public function getCurrentUser(): DataResponse {
366
-		$user = $this->userSession->getUser();
367
-		if ($user) {
368
-			$data =  $this->getUserData($user->getUID());
369
-			// rename "displayname" to "display-name" only for this call to keep
370
-			// the API stable.
371
-			$data['display-name'] = $data['displayname'];
372
-			unset($data['displayname']);
373
-			return new DataResponse($data);
374
-
375
-		}
376
-
377
-		throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
378
-	}
379
-
380
-	/**
381
-	 * @NoAdminRequired
382
-	 * @NoSubAdminRequired
383
-	 */
384
-	public function getEditableFields(): DataResponse {
385
-		$permittedFields = [];
386
-
387
-		// Editing self (display, email)
388
-		if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
389
-			$permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
390
-			$permittedFields[] = AccountManager::PROPERTY_EMAIL;
391
-		}
392
-
393
-		if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
394
-			$federatedFileSharing = $this->federatedFileSharingFactory->get();
395
-			$shareProvider = $federatedFileSharing->getFederatedShareProvider();
396
-			if ($shareProvider->isLookupServerUploadEnabled()) {
397
-				$permittedFields[] = AccountManager::PROPERTY_PHONE;
398
-				$permittedFields[] = AccountManager::PROPERTY_ADDRESS;
399
-				$permittedFields[] = AccountManager::PROPERTY_WEBSITE;
400
-				$permittedFields[] = AccountManager::PROPERTY_TWITTER;
401
-			}
402
-		}
403
-
404
-		return new DataResponse($permittedFields);
405
-	}
406
-
407
-	/**
408
-	 * @NoAdminRequired
409
-	 * @NoSubAdminRequired
410
-	 * @PasswordConfirmationRequired
411
-	 *
412
-	 * edit users
413
-	 *
414
-	 * @param string $userId
415
-	 * @param string $key
416
-	 * @param string $value
417
-	 * @return DataResponse
418
-	 * @throws OCSException
419
-	 */
420
-	public function editUser(string $userId, string $key, string $value): DataResponse {
421
-		$currentLoggedInUser = $this->userSession->getUser();
422
-
423
-		$targetUser = $this->userManager->get($userId);
424
-		if ($targetUser === null) {
425
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
426
-		}
427
-
428
-		$permittedFields = [];
429
-		if ($targetUser->getUID() === $currentLoggedInUser->getUID()) {
430
-			// Editing self (display, email)
431
-			if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
432
-				$permittedFields[] = 'display';
433
-				$permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
434
-				$permittedFields[] = AccountManager::PROPERTY_EMAIL;
435
-			}
436
-
437
-			$permittedFields[] = 'password';
438
-			if ($this->config->getSystemValue('force_language', false) === false ||
439
-				$this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
440
-				$permittedFields[] = 'language';
441
-			}
442
-
443
-			if ($this->config->getSystemValue('force_locale', false) === false ||
444
-				$this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
445
-				$permittedFields[] = 'locale';
446
-			}
447
-
448
-			if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
449
-				$federatedFileSharing = new \OCA\FederatedFileSharing\AppInfo\Application();
450
-				$shareProvider = $federatedFileSharing->getFederatedShareProvider();
451
-				if ($shareProvider->isLookupServerUploadEnabled()) {
452
-					$permittedFields[] = AccountManager::PROPERTY_PHONE;
453
-					$permittedFields[] = AccountManager::PROPERTY_ADDRESS;
454
-					$permittedFields[] = AccountManager::PROPERTY_WEBSITE;
455
-					$permittedFields[] = AccountManager::PROPERTY_TWITTER;
456
-				}
457
-			}
458
-
459
-			// If admin they can edit their own quota
460
-			if ($this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
461
-				$permittedFields[] = 'quota';
462
-			}
463
-		} else {
464
-			// Check if admin / subadmin
465
-			$subAdminManager = $this->groupManager->getSubAdmin();
466
-			if ($subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
467
-			|| $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
468
-				// They have permissions over the user
469
-				$permittedFields[] = 'display';
470
-				$permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
471
-				$permittedFields[] = AccountManager::PROPERTY_EMAIL;
472
-				$permittedFields[] = 'password';
473
-				$permittedFields[] = 'language';
474
-				$permittedFields[] = 'locale';
475
-				$permittedFields[] = AccountManager::PROPERTY_PHONE;
476
-				$permittedFields[] = AccountManager::PROPERTY_ADDRESS;
477
-				$permittedFields[] = AccountManager::PROPERTY_WEBSITE;
478
-				$permittedFields[] = AccountManager::PROPERTY_TWITTER;
479
-				$permittedFields[] = 'quota';
480
-			} else {
481
-				// No rights
482
-				throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
483
-			}
484
-		}
485
-		// Check if permitted to edit this field
486
-		if (!in_array($key, $permittedFields)) {
487
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
488
-		}
489
-		// Process the edit
490
-		switch($key) {
491
-			case 'display':
492
-			case AccountManager::PROPERTY_DISPLAYNAME:
493
-				$targetUser->setDisplayName($value);
494
-				break;
495
-			case 'quota':
496
-				$quota = $value;
497
-				if ($quota !== 'none' && $quota !== 'default') {
498
-					if (is_numeric($quota)) {
499
-						$quota = (float) $quota;
500
-					} else {
501
-						$quota = \OCP\Util::computerFileSize($quota);
502
-					}
503
-					if ($quota === false) {
504
-						throw new OCSException('Invalid quota value '.$value, 103);
505
-					}
506
-					if ($quota === -1) {
507
-						$quota = 'none';
508
-					} else {
509
-						$quota = \OCP\Util::humanFileSize($quota);
510
-					}
511
-				}
512
-				$targetUser->setQuota($quota);
513
-				break;
514
-			case 'password':
515
-				$targetUser->setPassword($value);
516
-				break;
517
-			case 'language':
518
-				$languagesCodes = $this->l10nFactory->findAvailableLanguages();
519
-				if (!in_array($value, $languagesCodes, true) && $value !== 'en') {
520
-					throw new OCSException('Invalid language', 102);
521
-				}
522
-				$this->config->setUserValue($targetUser->getUID(), 'core', 'lang', $value);
523
-				break;
524
-			case 'locale':
525
-				if (!$this->l10nFactory->localeExists($value)) {
526
-					throw new OCSException('Invalid locale', 102);
527
-				}
528
-				$this->config->setUserValue($targetUser->getUID(), 'core', 'locale', $value);
529
-				break;
530
-			case AccountManager::PROPERTY_EMAIL:
531
-				if (filter_var($value, FILTER_VALIDATE_EMAIL) || $value === '') {
532
-					$targetUser->setEMailAddress($value);
533
-				} else {
534
-					throw new OCSException('', 102);
535
-				}
536
-				break;
537
-			case AccountManager::PROPERTY_PHONE:
538
-			case AccountManager::PROPERTY_ADDRESS:
539
-			case AccountManager::PROPERTY_WEBSITE:
540
-			case AccountManager::PROPERTY_TWITTER:
541
-				$userAccount = $this->accountManager->getUser($targetUser);
542
-				if ($userAccount[$key]['value'] !== $value) {
543
-					$userAccount[$key]['value'] = $value;
544
-					$this->accountManager->updateUser($targetUser, $userAccount);
545
-				}
546
-				break;
547
-			default:
548
-				throw new OCSException('', 103);
549
-		}
550
-		return new DataResponse();
551
-	}
552
-
553
-	/**
554
-	 * @PasswordConfirmationRequired
555
-	 * @NoAdminRequired
556
-	 *
557
-	 * @param string $userId
558
-	 * @return DataResponse
559
-	 * @throws OCSException
560
-	 */
561
-	public function deleteUser(string $userId): DataResponse {
562
-		$currentLoggedInUser = $this->userSession->getUser();
563
-
564
-		$targetUser = $this->userManager->get($userId);
565
-
566
-		if ($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
567
-			throw new OCSException('', 101);
568
-		}
569
-
570
-		// If not permitted
571
-		$subAdminManager = $this->groupManager->getSubAdmin();
572
-		if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
573
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
574
-		}
575
-
576
-		// Go ahead with the delete
577
-		if ($targetUser->delete()) {
578
-			return new DataResponse();
579
-		} else {
580
-			throw new OCSException('', 101);
581
-		}
582
-	}
583
-
584
-	/**
585
-	 * @PasswordConfirmationRequired
586
-	 * @NoAdminRequired
587
-	 *
588
-	 * @param string $userId
589
-	 * @return DataResponse
590
-	 * @throws OCSException
591
-	 * @throws OCSForbiddenException
592
-	 */
593
-	public function disableUser(string $userId): DataResponse {
594
-		return $this->setEnabled($userId, false);
595
-	}
596
-
597
-	/**
598
-	 * @PasswordConfirmationRequired
599
-	 * @NoAdminRequired
600
-	 *
601
-	 * @param string $userId
602
-	 * @return DataResponse
603
-	 * @throws OCSException
604
-	 * @throws OCSForbiddenException
605
-	 */
606
-	public function enableUser(string $userId): DataResponse {
607
-		return $this->setEnabled($userId, true);
608
-	}
609
-
610
-	/**
611
-	 * @param string $userId
612
-	 * @param bool $value
613
-	 * @return DataResponse
614
-	 * @throws OCSException
615
-	 */
616
-	private function setEnabled(string $userId, bool $value): DataResponse {
617
-		$currentLoggedInUser = $this->userSession->getUser();
618
-
619
-		$targetUser = $this->userManager->get($userId);
620
-		if ($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
621
-			throw new OCSException('', 101);
622
-		}
623
-
624
-		// If not permitted
625
-		$subAdminManager = $this->groupManager->getSubAdmin();
626
-		if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
627
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
628
-		}
629
-
630
-		// enable/disable the user now
631
-		$targetUser->setEnabled($value);
632
-		return new DataResponse();
633
-	}
634
-
635
-	/**
636
-	 * @NoAdminRequired
637
-	 * @NoSubAdminRequired
638
-	 *
639
-	 * @param string $userId
640
-	 * @return DataResponse
641
-	 * @throws OCSException
642
-	 */
643
-	public function getUsersGroups(string $userId): DataResponse {
644
-		$loggedInUser = $this->userSession->getUser();
645
-
646
-		$targetUser = $this->userManager->get($userId);
647
-		if ($targetUser === null) {
648
-			throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
649
-		}
650
-
651
-		if ($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) {
652
-			// Self lookup or admin lookup
653
-			return new DataResponse([
654
-				'groups' => $this->groupManager->getUserGroupIds($targetUser)
655
-			]);
656
-		} else {
657
-			$subAdminManager = $this->groupManager->getSubAdmin();
658
-
659
-			// Looking up someone else
660
-			if ($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) {
661
-				// Return the group that the method caller is subadmin of for the user in question
662
-				/** @var IGroup[] $getSubAdminsGroups */
663
-				$getSubAdminsGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
664
-				foreach ($getSubAdminsGroups as $key => $group) {
665
-					$getSubAdminsGroups[$key] = $group->getGID();
666
-				}
667
-				$groups = array_intersect(
668
-					$getSubAdminsGroups,
669
-					$this->groupManager->getUserGroupIds($targetUser)
670
-				);
671
-				return new DataResponse(['groups' => $groups]);
672
-			} else {
673
-				// Not permitted
674
-				throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
675
-			}
676
-		}
677
-
678
-	}
679
-
680
-	/**
681
-	 * @PasswordConfirmationRequired
682
-	 * @NoAdminRequired
683
-	 *
684
-	 * @param string $userId
685
-	 * @param string $groupid
686
-	 * @return DataResponse
687
-	 * @throws OCSException
688
-	 */
689
-	public function addToGroup(string $userId, string $groupid = ''): DataResponse {
690
-		if ($groupid === '') {
691
-			throw new OCSException('', 101);
692
-		}
693
-
694
-		$group = $this->groupManager->get($groupid);
695
-		$targetUser = $this->userManager->get($userId);
696
-		if ($group === null) {
697
-			throw new OCSException('', 102);
698
-		}
699
-		if ($targetUser === null) {
700
-			throw new OCSException('', 103);
701
-		}
702
-
703
-		// If they're not an admin, check they are a subadmin of the group in question
704
-		$loggedInUser = $this->userSession->getUser();
705
-		$subAdminManager = $this->groupManager->getSubAdmin();
706
-		if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
707
-			throw new OCSException('', 104);
708
-		}
709
-
710
-		// Add user to group
711
-		$group->addUser($targetUser);
712
-		return new DataResponse();
713
-	}
714
-
715
-	/**
716
-	 * @PasswordConfirmationRequired
717
-	 * @NoAdminRequired
718
-	 *
719
-	 * @param string $userId
720
-	 * @param string $groupid
721
-	 * @return DataResponse
722
-	 * @throws OCSException
723
-	 */
724
-	public function removeFromGroup(string $userId, string $groupid): DataResponse {
725
-		$loggedInUser = $this->userSession->getUser();
726
-
727
-		if ($groupid === null || trim($groupid) === '') {
728
-			throw new OCSException('', 101);
729
-		}
730
-
731
-		$group = $this->groupManager->get($groupid);
732
-		if ($group === null) {
733
-			throw new OCSException('', 102);
734
-		}
735
-
736
-		$targetUser = $this->userManager->get($userId);
737
-		if ($targetUser === null) {
738
-			throw new OCSException('', 103);
739
-		}
740
-
741
-		// If they're not an admin, check they are a subadmin of the group in question
742
-		$subAdminManager = $this->groupManager->getSubAdmin();
743
-		if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
744
-			throw new OCSException('', 104);
745
-		}
746
-
747
-		// Check they aren't removing themselves from 'admin' or their 'subadmin; group
748
-		if ($targetUser->getUID() === $loggedInUser->getUID()) {
749
-			if ($this->groupManager->isAdmin($loggedInUser->getUID())) {
750
-				if ($group->getGID() === 'admin') {
751
-					throw new OCSException('Cannot remove yourself from the admin group', 105);
752
-				}
753
-			} else {
754
-				// Not an admin, so the user must be a subadmin of this group, but that is not allowed.
755
-				throw new OCSException('Cannot remove yourself from this group as you are a SubAdmin', 105);
756
-			}
757
-
758
-		} else if (!$this->groupManager->isAdmin($loggedInUser->getUID())) {
759
-			/** @var IGroup[] $subAdminGroups */
760
-			$subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
761
-			$subAdminGroups = array_map(function (IGroup $subAdminGroup) {
762
-				return $subAdminGroup->getGID();
763
-			}, $subAdminGroups);
764
-			$userGroups = $this->groupManager->getUserGroupIds($targetUser);
765
-			$userSubAdminGroups = array_intersect($subAdminGroups, $userGroups);
766
-
767
-			if (count($userSubAdminGroups) <= 1) {
768
-				// Subadmin must not be able to remove a user from all their subadmin groups.
769
-				throw new OCSException('Cannot remove user from this group as this is the only remaining group you are a SubAdmin of', 105);
770
-			}
771
-		}
772
-
773
-		// Remove user from group
774
-		$group->removeUser($targetUser);
775
-		return new DataResponse();
776
-	}
777
-
778
-	/**
779
-	 * Creates a subadmin
780
-	 *
781
-	 * @PasswordConfirmationRequired
782
-	 *
783
-	 * @param string $userId
784
-	 * @param string $groupid
785
-	 * @return DataResponse
786
-	 * @throws OCSException
787
-	 */
788
-	public function addSubAdmin(string $userId, string $groupid): DataResponse {
789
-		$group = $this->groupManager->get($groupid);
790
-		$user = $this->userManager->get($userId);
791
-
792
-		// Check if the user exists
793
-		if ($user === null) {
794
-			throw new OCSException('User does not exist', 101);
795
-		}
796
-		// Check if group exists
797
-		if ($group === null) {
798
-			throw new OCSException('Group does not exist',  102);
799
-		}
800
-		// Check if trying to make subadmin of admin group
801
-		if ($group->getGID() === 'admin') {
802
-			throw new OCSException('Cannot create subadmins for admin group', 103);
803
-		}
804
-
805
-		$subAdminManager = $this->groupManager->getSubAdmin();
806
-
807
-		// We cannot be subadmin twice
808
-		if ($subAdminManager->isSubAdminOfGroup($user, $group)) {
809
-			return new DataResponse();
810
-		}
811
-		// Go
812
-		if ($subAdminManager->createSubAdmin($user, $group)) {
813
-			return new DataResponse();
814
-		} else {
815
-			throw new OCSException('Unknown error occurred', 103);
816
-		}
817
-	}
818
-
819
-	/**
820
-	 * Removes a subadmin from a group
821
-	 *
822
-	 * @PasswordConfirmationRequired
823
-	 *
824
-	 * @param string $userId
825
-	 * @param string $groupid
826
-	 * @return DataResponse
827
-	 * @throws OCSException
828
-	 */
829
-	public function removeSubAdmin(string $userId, string $groupid): DataResponse {
830
-		$group = $this->groupManager->get($groupid);
831
-		$user = $this->userManager->get($userId);
832
-		$subAdminManager = $this->groupManager->getSubAdmin();
833
-
834
-		// Check if the user exists
835
-		if ($user === null) {
836
-			throw new OCSException('User does not exist', 101);
837
-		}
838
-		// Check if the group exists
839
-		if ($group === null) {
840
-			throw new OCSException('Group does not exist', 101);
841
-		}
842
-		// Check if they are a subadmin of this said group
843
-		if (!$subAdminManager->isSubAdminOfGroup($user, $group)) {
844
-			throw new OCSException('User is not a subadmin of this group', 102);
845
-		}
846
-
847
-		// Go
848
-		if ($subAdminManager->deleteSubAdmin($user, $group)) {
849
-			return new DataResponse();
850
-		} else {
851
-			throw new OCSException('Unknown error occurred', 103);
852
-		}
853
-	}
854
-
855
-	/**
856
-	 * Get the groups a user is a subadmin of
857
-	 *
858
-	 * @param string $userId
859
-	 * @return DataResponse
860
-	 * @throws OCSException
861
-	 */
862
-	public function getUserSubAdminGroups(string $userId): DataResponse {
863
-		$groups = $this->getUserSubAdminGroupsData($userId);
864
-		return new DataResponse($groups);
865
-	}
866
-
867
-	/**
868
-	 * @NoAdminRequired
869
-	 * @PasswordConfirmationRequired
870
-	 *
871
-	 * resend welcome message
872
-	 *
873
-	 * @param string $userId
874
-	 * @return DataResponse
875
-	 * @throws OCSException
876
-	 */
877
-	public function resendWelcomeMessage(string $userId): DataResponse {
878
-		$currentLoggedInUser = $this->userSession->getUser();
879
-
880
-		$targetUser = $this->userManager->get($userId);
881
-		if ($targetUser === null) {
882
-			throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
883
-		}
884
-
885
-		// Check if admin / subadmin
886
-		$subAdminManager = $this->groupManager->getSubAdmin();
887
-		if (!$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
888
-			&& !$this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
889
-			// No rights
890
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
891
-		}
892
-
893
-		$email = $targetUser->getEMailAddress();
894
-		if ($email === '' || $email === null) {
895
-			throw new OCSException('Email address not available', 101);
896
-		}
897
-
898
-		try {
899
-			$emailTemplate = $this->newUserMailHelper->generateTemplate($targetUser, false);
900
-			$this->newUserMailHelper->sendMail($targetUser, $emailTemplate);
901
-		} catch(\Exception $e) {
902
-			$this->logger->logException($e, [
903
-				'message' => "Can't send new user mail to $email",
904
-				'level' => ILogger::ERROR,
905
-				'app' => 'settings',
906
-			]);
907
-			throw new OCSException('Sending email failed', 102);
908
-		}
909
-
910
-		return new DataResponse();
911
-	}
57
+    /** @var IAppManager */
58
+    private $appManager;
59
+    /** @var ILogger */
60
+    private $logger;
61
+    /** @var IFactory */
62
+    private $l10nFactory;
63
+    /** @var NewUserMailHelper */
64
+    private $newUserMailHelper;
65
+    /** @var FederatedFileSharingFactory */
66
+    private $federatedFileSharingFactory;
67
+    /** @var ISecureRandom */
68
+    private $secureRandom;
69
+
70
+    /**
71
+     * @param string $appName
72
+     * @param IRequest $request
73
+     * @param IUserManager $userManager
74
+     * @param IConfig $config
75
+     * @param IAppManager $appManager
76
+     * @param IGroupManager $groupManager
77
+     * @param IUserSession $userSession
78
+     * @param AccountManager $accountManager
79
+     * @param ILogger $logger
80
+     * @param IFactory $l10nFactory
81
+     * @param NewUserMailHelper $newUserMailHelper
82
+     * @param FederatedFileSharingFactory $federatedFileSharingFactory
83
+     * @param ISecureRandom $secureRandom
84
+     */
85
+    public function __construct(string $appName,
86
+                                IRequest $request,
87
+                                IUserManager $userManager,
88
+                                IConfig $config,
89
+                                IAppManager $appManager,
90
+                                IGroupManager $groupManager,
91
+                                IUserSession $userSession,
92
+                                AccountManager $accountManager,
93
+                                ILogger $logger,
94
+                                IFactory $l10nFactory,
95
+                                NewUserMailHelper $newUserMailHelper,
96
+                                FederatedFileSharingFactory $federatedFileSharingFactory,
97
+                                ISecureRandom $secureRandom) {
98
+        parent::__construct($appName,
99
+                            $request,
100
+                            $userManager,
101
+                            $config,
102
+                            $groupManager,
103
+                            $userSession,
104
+                            $accountManager);
105
+
106
+        $this->appManager = $appManager;
107
+        $this->logger = $logger;
108
+        $this->l10nFactory = $l10nFactory;
109
+        $this->newUserMailHelper = $newUserMailHelper;
110
+        $this->federatedFileSharingFactory = $federatedFileSharingFactory;
111
+        $this->secureRandom = $secureRandom;
112
+    }
113
+
114
+    /**
115
+     * @NoAdminRequired
116
+     *
117
+     * returns a list of users
118
+     *
119
+     * @param string $search
120
+     * @param int $limit
121
+     * @param int $offset
122
+     * @return DataResponse
123
+     */
124
+    public function getUsers(string $search = '', $limit = null, $offset = 0): DataResponse {
125
+        $user = $this->userSession->getUser();
126
+        $users = [];
127
+
128
+        // Admin? Or SubAdmin?
129
+        $uid = $user->getUID();
130
+        $subAdminManager = $this->groupManager->getSubAdmin();
131
+        if ($this->groupManager->isAdmin($uid)){
132
+            $users = $this->userManager->search($search, $limit, $offset);
133
+        } else if ($subAdminManager->isSubAdmin($user)) {
134
+            $subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
135
+            foreach ($subAdminOfGroups as $key => $group) {
136
+                $subAdminOfGroups[$key] = $group->getGID();
137
+            }
138
+
139
+            $users = [];
140
+            foreach ($subAdminOfGroups as $group) {
141
+                $users = array_merge($users, $this->groupManager->displayNamesInGroup($group, $search, $limit, $offset));
142
+            }
143
+        }
144
+
145
+        $users = array_keys($users);
146
+
147
+        return new DataResponse([
148
+            'users' => $users
149
+        ]);
150
+    }
151
+
152
+    /**
153
+     * @NoAdminRequired
154
+     *
155
+     * returns a list of users and their data
156
+     */
157
+    public function getUsersDetails(string $search = '', $limit = null, $offset = 0): DataResponse {
158
+        $currentUser = $this->userSession->getUser();
159
+        $users = [];
160
+
161
+        // Admin? Or SubAdmin?
162
+        $uid = $currentUser->getUID();
163
+        $subAdminManager = $this->groupManager->getSubAdmin();
164
+        if ($this->groupManager->isAdmin($uid)){
165
+            $users = $this->userManager->search($search, $limit, $offset);
166
+            $users = array_keys($users);
167
+        } else if ($subAdminManager->isSubAdmin($currentUser)) {
168
+            $subAdminOfGroups = $subAdminManager->getSubAdminsGroups($currentUser);
169
+            foreach ($subAdminOfGroups as $key => $group) {
170
+                $subAdminOfGroups[$key] = $group->getGID();
171
+            }
172
+
173
+            $users = [];
174
+            foreach ($subAdminOfGroups as $group) {
175
+                $users[] = array_keys($this->groupManager->displayNamesInGroup($group, $search, $limit, $offset));
176
+            }
177
+            $users = array_merge(...$users);
178
+        }
179
+
180
+        $usersDetails = [];
181
+        foreach ($users as $userId) {
182
+            $userId = (string) $userId;
183
+            $userData = $this->getUserData($userId);
184
+            // Do not insert empty entry
185
+            if (!empty($userData)) {
186
+                $usersDetails[$userId] = $userData;
187
+            } else {
188
+                // Logged user does not have permissions to see this user
189
+                // only showing its id
190
+                $usersDetails[$userId] = ['id' => $userId];
191
+            }
192
+        }
193
+
194
+        return new DataResponse([
195
+            'users' => $usersDetails
196
+        ]);
197
+    }
198
+
199
+    /**
200
+     * @PasswordConfirmationRequired
201
+     * @NoAdminRequired
202
+     *
203
+     * @param string $userid
204
+     * @param string $password
205
+     * @param string $displayName
206
+     * @param string $email
207
+     * @param array $groups
208
+     * @param array $subadmins
209
+     * @param string $quota
210
+     * @param string $language
211
+     * @return DataResponse
212
+     * @throws OCSException
213
+     */
214
+    public function addUser(string $userid,
215
+                            string $password = '',
216
+                            string $displayName = '',
217
+                            string $email = '',
218
+                            array $groups = [],
219
+                            array $subadmin = [],
220
+                            string $quota = '',
221
+                            string $language = ''): DataResponse {
222
+        $user = $this->userSession->getUser();
223
+        $isAdmin = $this->groupManager->isAdmin($user->getUID());
224
+        $subAdminManager = $this->groupManager->getSubAdmin();
225
+
226
+        if ($this->userManager->userExists($userid)) {
227
+            $this->logger->error('Failed addUser attempt: User already exists.', ['app' => 'ocs_api']);
228
+            throw new OCSException('User already exists', 102);
229
+        }
230
+
231
+        if ($groups !== []) {
232
+            foreach ($groups as $group) {
233
+                if (!$this->groupManager->groupExists($group)) {
234
+                    throw new OCSException('group '.$group.' does not exist', 104);
235
+                }
236
+                if (!$isAdmin && !$subAdminManager->isSubAdminOfGroup($user, $this->groupManager->get($group))) {
237
+                    throw new OCSException('insufficient privileges for group '. $group, 105);
238
+                }
239
+            }
240
+        } else {
241
+            if (!$isAdmin) {
242
+                throw new OCSException('no group specified (required for subadmins)', 106);
243
+            }
244
+        }
245
+
246
+        $subadminGroups = [];
247
+        if ($subadmin !== []) {
248
+            foreach ($subadmin as $groupid) {
249
+                $group = $this->groupManager->get($groupid);
250
+                // Check if group exists
251
+                if ($group === null) {
252
+                    throw new OCSException('Subadmin group does not exist',  102);
253
+                }
254
+                // Check if trying to make subadmin of admin group
255
+                if ($group->getGID() === 'admin') {
256
+                    throw new OCSException('Cannot create subadmins for admin group', 103);
257
+                }
258
+                // Check if has permission to promote subadmins
259
+                if (!$subAdminManager->isSubAdminOfGroup($user, $group) && !$isAdmin) {
260
+                    throw new OCSForbiddenException('No permissions to promote subadmins');
261
+                }
262
+                $subadminGroups[] = $group;
263
+            }
264
+        }
265
+
266
+        $generatePasswordResetToken = false;
267
+        if ($password === '') {
268
+            if ($email === '') {
269
+                throw new OCSException('To send a password link to the user an email address is required.', 108);
270
+            }
271
+
272
+            $password = $this->secureRandom->generate(10);
273
+            // Make sure we pass the password_policy
274
+            $password .= $this->secureRandom->generate(2, '$!.,;:-~+*[]{}()');
275
+            $generatePasswordResetToken = true;
276
+        }
277
+
278
+        try {
279
+            $newUser = $this->userManager->createUser($userid, $password);
280
+            $this->logger->info('Successful addUser call with userid: ' . $userid, ['app' => 'ocs_api']);
281
+
282
+            foreach ($groups as $group) {
283
+                $this->groupManager->get($group)->addUser($newUser);
284
+                $this->logger->info('Added userid ' . $userid . ' to group ' . $group, ['app' => 'ocs_api']);
285
+            }
286
+            foreach ($subadminGroups as $group) {
287
+                $subAdminManager->createSubAdmin($newUser, $group);
288
+            }
289
+
290
+            if ($displayName !== '') {
291
+                $this->editUser($userid, 'display', $displayName);
292
+            }
293
+
294
+            if ($quota !== '') {
295
+                $this->editUser($userid, 'quota', $quota);
296
+            }
297
+
298
+            if ($language !== '') {
299
+                $this->editUser($userid, 'language', $language);
300
+            }
301
+
302
+            // Send new user mail only if a mail is set
303
+            if ($email !== '') {
304
+                $newUser->setEMailAddress($email);
305
+                try {
306
+                    $emailTemplate = $this->newUserMailHelper->generateTemplate($newUser, $generatePasswordResetToken);
307
+                    $this->newUserMailHelper->sendMail($newUser, $emailTemplate);
308
+                } catch (\Exception $e) {
309
+                    $this->logger->logException($e, [
310
+                        'message' => "Can't send new user mail to $email",
311
+                        'level' => ILogger::ERROR,
312
+                        'app' => 'ocs_api',
313
+                    ]);
314
+                    throw new OCSException('Unable to send the invitation mail', 109);
315
+                }
316
+            }
317
+
318
+            return new DataResponse();
319
+
320
+        } catch (HintException $e ) {
321
+            $this->logger->logException($e, [
322
+                'message' => 'Failed addUser attempt with hint exception.',
323
+                'level' => ILogger::WARN,
324
+                'app' => 'ocs_api',
325
+            ]);
326
+            throw new OCSException($e->getHint(), 107);
327
+        } catch (\Exception $e) {
328
+            $this->logger->logException($e, [
329
+                'message' => 'Failed addUser attempt with exception.',
330
+                'level' => ILogger::ERROR,
331
+                'app' => 'ocs_api',
332
+            ]);
333
+            throw new OCSException('Bad request', 101);
334
+        }
335
+    }
336
+
337
+    /**
338
+     * @NoAdminRequired
339
+     * @NoSubAdminRequired
340
+     *
341
+     * gets user info
342
+     *
343
+     * @param string $userId
344
+     * @return DataResponse
345
+     * @throws OCSException
346
+     */
347
+    public function getUser(string $userId): DataResponse {
348
+        $data = $this->getUserData($userId);
349
+        // getUserData returns empty array if not enough permissions
350
+        if (empty($data)) {
351
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
352
+        }
353
+        return new DataResponse($data);
354
+    }
355
+
356
+    /**
357
+     * @NoAdminRequired
358
+     * @NoSubAdminRequired
359
+     *
360
+     * gets user info from the currently logged in user
361
+     *
362
+     * @return DataResponse
363
+     * @throws OCSException
364
+     */
365
+    public function getCurrentUser(): DataResponse {
366
+        $user = $this->userSession->getUser();
367
+        if ($user) {
368
+            $data =  $this->getUserData($user->getUID());
369
+            // rename "displayname" to "display-name" only for this call to keep
370
+            // the API stable.
371
+            $data['display-name'] = $data['displayname'];
372
+            unset($data['displayname']);
373
+            return new DataResponse($data);
374
+
375
+        }
376
+
377
+        throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
378
+    }
379
+
380
+    /**
381
+     * @NoAdminRequired
382
+     * @NoSubAdminRequired
383
+     */
384
+    public function getEditableFields(): DataResponse {
385
+        $permittedFields = [];
386
+
387
+        // Editing self (display, email)
388
+        if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
389
+            $permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
390
+            $permittedFields[] = AccountManager::PROPERTY_EMAIL;
391
+        }
392
+
393
+        if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
394
+            $federatedFileSharing = $this->federatedFileSharingFactory->get();
395
+            $shareProvider = $federatedFileSharing->getFederatedShareProvider();
396
+            if ($shareProvider->isLookupServerUploadEnabled()) {
397
+                $permittedFields[] = AccountManager::PROPERTY_PHONE;
398
+                $permittedFields[] = AccountManager::PROPERTY_ADDRESS;
399
+                $permittedFields[] = AccountManager::PROPERTY_WEBSITE;
400
+                $permittedFields[] = AccountManager::PROPERTY_TWITTER;
401
+            }
402
+        }
403
+
404
+        return new DataResponse($permittedFields);
405
+    }
406
+
407
+    /**
408
+     * @NoAdminRequired
409
+     * @NoSubAdminRequired
410
+     * @PasswordConfirmationRequired
411
+     *
412
+     * edit users
413
+     *
414
+     * @param string $userId
415
+     * @param string $key
416
+     * @param string $value
417
+     * @return DataResponse
418
+     * @throws OCSException
419
+     */
420
+    public function editUser(string $userId, string $key, string $value): DataResponse {
421
+        $currentLoggedInUser = $this->userSession->getUser();
422
+
423
+        $targetUser = $this->userManager->get($userId);
424
+        if ($targetUser === null) {
425
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
426
+        }
427
+
428
+        $permittedFields = [];
429
+        if ($targetUser->getUID() === $currentLoggedInUser->getUID()) {
430
+            // Editing self (display, email)
431
+            if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
432
+                $permittedFields[] = 'display';
433
+                $permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
434
+                $permittedFields[] = AccountManager::PROPERTY_EMAIL;
435
+            }
436
+
437
+            $permittedFields[] = 'password';
438
+            if ($this->config->getSystemValue('force_language', false) === false ||
439
+                $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
440
+                $permittedFields[] = 'language';
441
+            }
442
+
443
+            if ($this->config->getSystemValue('force_locale', false) === false ||
444
+                $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
445
+                $permittedFields[] = 'locale';
446
+            }
447
+
448
+            if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
449
+                $federatedFileSharing = new \OCA\FederatedFileSharing\AppInfo\Application();
450
+                $shareProvider = $federatedFileSharing->getFederatedShareProvider();
451
+                if ($shareProvider->isLookupServerUploadEnabled()) {
452
+                    $permittedFields[] = AccountManager::PROPERTY_PHONE;
453
+                    $permittedFields[] = AccountManager::PROPERTY_ADDRESS;
454
+                    $permittedFields[] = AccountManager::PROPERTY_WEBSITE;
455
+                    $permittedFields[] = AccountManager::PROPERTY_TWITTER;
456
+                }
457
+            }
458
+
459
+            // If admin they can edit their own quota
460
+            if ($this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
461
+                $permittedFields[] = 'quota';
462
+            }
463
+        } else {
464
+            // Check if admin / subadmin
465
+            $subAdminManager = $this->groupManager->getSubAdmin();
466
+            if ($subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
467
+            || $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
468
+                // They have permissions over the user
469
+                $permittedFields[] = 'display';
470
+                $permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
471
+                $permittedFields[] = AccountManager::PROPERTY_EMAIL;
472
+                $permittedFields[] = 'password';
473
+                $permittedFields[] = 'language';
474
+                $permittedFields[] = 'locale';
475
+                $permittedFields[] = AccountManager::PROPERTY_PHONE;
476
+                $permittedFields[] = AccountManager::PROPERTY_ADDRESS;
477
+                $permittedFields[] = AccountManager::PROPERTY_WEBSITE;
478
+                $permittedFields[] = AccountManager::PROPERTY_TWITTER;
479
+                $permittedFields[] = 'quota';
480
+            } else {
481
+                // No rights
482
+                throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
483
+            }
484
+        }
485
+        // Check if permitted to edit this field
486
+        if (!in_array($key, $permittedFields)) {
487
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
488
+        }
489
+        // Process the edit
490
+        switch($key) {
491
+            case 'display':
492
+            case AccountManager::PROPERTY_DISPLAYNAME:
493
+                $targetUser->setDisplayName($value);
494
+                break;
495
+            case 'quota':
496
+                $quota = $value;
497
+                if ($quota !== 'none' && $quota !== 'default') {
498
+                    if (is_numeric($quota)) {
499
+                        $quota = (float) $quota;
500
+                    } else {
501
+                        $quota = \OCP\Util::computerFileSize($quota);
502
+                    }
503
+                    if ($quota === false) {
504
+                        throw new OCSException('Invalid quota value '.$value, 103);
505
+                    }
506
+                    if ($quota === -1) {
507
+                        $quota = 'none';
508
+                    } else {
509
+                        $quota = \OCP\Util::humanFileSize($quota);
510
+                    }
511
+                }
512
+                $targetUser->setQuota($quota);
513
+                break;
514
+            case 'password':
515
+                $targetUser->setPassword($value);
516
+                break;
517
+            case 'language':
518
+                $languagesCodes = $this->l10nFactory->findAvailableLanguages();
519
+                if (!in_array($value, $languagesCodes, true) && $value !== 'en') {
520
+                    throw new OCSException('Invalid language', 102);
521
+                }
522
+                $this->config->setUserValue($targetUser->getUID(), 'core', 'lang', $value);
523
+                break;
524
+            case 'locale':
525
+                if (!$this->l10nFactory->localeExists($value)) {
526
+                    throw new OCSException('Invalid locale', 102);
527
+                }
528
+                $this->config->setUserValue($targetUser->getUID(), 'core', 'locale', $value);
529
+                break;
530
+            case AccountManager::PROPERTY_EMAIL:
531
+                if (filter_var($value, FILTER_VALIDATE_EMAIL) || $value === '') {
532
+                    $targetUser->setEMailAddress($value);
533
+                } else {
534
+                    throw new OCSException('', 102);
535
+                }
536
+                break;
537
+            case AccountManager::PROPERTY_PHONE:
538
+            case AccountManager::PROPERTY_ADDRESS:
539
+            case AccountManager::PROPERTY_WEBSITE:
540
+            case AccountManager::PROPERTY_TWITTER:
541
+                $userAccount = $this->accountManager->getUser($targetUser);
542
+                if ($userAccount[$key]['value'] !== $value) {
543
+                    $userAccount[$key]['value'] = $value;
544
+                    $this->accountManager->updateUser($targetUser, $userAccount);
545
+                }
546
+                break;
547
+            default:
548
+                throw new OCSException('', 103);
549
+        }
550
+        return new DataResponse();
551
+    }
552
+
553
+    /**
554
+     * @PasswordConfirmationRequired
555
+     * @NoAdminRequired
556
+     *
557
+     * @param string $userId
558
+     * @return DataResponse
559
+     * @throws OCSException
560
+     */
561
+    public function deleteUser(string $userId): DataResponse {
562
+        $currentLoggedInUser = $this->userSession->getUser();
563
+
564
+        $targetUser = $this->userManager->get($userId);
565
+
566
+        if ($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
567
+            throw new OCSException('', 101);
568
+        }
569
+
570
+        // If not permitted
571
+        $subAdminManager = $this->groupManager->getSubAdmin();
572
+        if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
573
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
574
+        }
575
+
576
+        // Go ahead with the delete
577
+        if ($targetUser->delete()) {
578
+            return new DataResponse();
579
+        } else {
580
+            throw new OCSException('', 101);
581
+        }
582
+    }
583
+
584
+    /**
585
+     * @PasswordConfirmationRequired
586
+     * @NoAdminRequired
587
+     *
588
+     * @param string $userId
589
+     * @return DataResponse
590
+     * @throws OCSException
591
+     * @throws OCSForbiddenException
592
+     */
593
+    public function disableUser(string $userId): DataResponse {
594
+        return $this->setEnabled($userId, false);
595
+    }
596
+
597
+    /**
598
+     * @PasswordConfirmationRequired
599
+     * @NoAdminRequired
600
+     *
601
+     * @param string $userId
602
+     * @return DataResponse
603
+     * @throws OCSException
604
+     * @throws OCSForbiddenException
605
+     */
606
+    public function enableUser(string $userId): DataResponse {
607
+        return $this->setEnabled($userId, true);
608
+    }
609
+
610
+    /**
611
+     * @param string $userId
612
+     * @param bool $value
613
+     * @return DataResponse
614
+     * @throws OCSException
615
+     */
616
+    private function setEnabled(string $userId, bool $value): DataResponse {
617
+        $currentLoggedInUser = $this->userSession->getUser();
618
+
619
+        $targetUser = $this->userManager->get($userId);
620
+        if ($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
621
+            throw new OCSException('', 101);
622
+        }
623
+
624
+        // If not permitted
625
+        $subAdminManager = $this->groupManager->getSubAdmin();
626
+        if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
627
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
628
+        }
629
+
630
+        // enable/disable the user now
631
+        $targetUser->setEnabled($value);
632
+        return new DataResponse();
633
+    }
634
+
635
+    /**
636
+     * @NoAdminRequired
637
+     * @NoSubAdminRequired
638
+     *
639
+     * @param string $userId
640
+     * @return DataResponse
641
+     * @throws OCSException
642
+     */
643
+    public function getUsersGroups(string $userId): DataResponse {
644
+        $loggedInUser = $this->userSession->getUser();
645
+
646
+        $targetUser = $this->userManager->get($userId);
647
+        if ($targetUser === null) {
648
+            throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
649
+        }
650
+
651
+        if ($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) {
652
+            // Self lookup or admin lookup
653
+            return new DataResponse([
654
+                'groups' => $this->groupManager->getUserGroupIds($targetUser)
655
+            ]);
656
+        } else {
657
+            $subAdminManager = $this->groupManager->getSubAdmin();
658
+
659
+            // Looking up someone else
660
+            if ($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) {
661
+                // Return the group that the method caller is subadmin of for the user in question
662
+                /** @var IGroup[] $getSubAdminsGroups */
663
+                $getSubAdminsGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
664
+                foreach ($getSubAdminsGroups as $key => $group) {
665
+                    $getSubAdminsGroups[$key] = $group->getGID();
666
+                }
667
+                $groups = array_intersect(
668
+                    $getSubAdminsGroups,
669
+                    $this->groupManager->getUserGroupIds($targetUser)
670
+                );
671
+                return new DataResponse(['groups' => $groups]);
672
+            } else {
673
+                // Not permitted
674
+                throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
675
+            }
676
+        }
677
+
678
+    }
679
+
680
+    /**
681
+     * @PasswordConfirmationRequired
682
+     * @NoAdminRequired
683
+     *
684
+     * @param string $userId
685
+     * @param string $groupid
686
+     * @return DataResponse
687
+     * @throws OCSException
688
+     */
689
+    public function addToGroup(string $userId, string $groupid = ''): DataResponse {
690
+        if ($groupid === '') {
691
+            throw new OCSException('', 101);
692
+        }
693
+
694
+        $group = $this->groupManager->get($groupid);
695
+        $targetUser = $this->userManager->get($userId);
696
+        if ($group === null) {
697
+            throw new OCSException('', 102);
698
+        }
699
+        if ($targetUser === null) {
700
+            throw new OCSException('', 103);
701
+        }
702
+
703
+        // If they're not an admin, check they are a subadmin of the group in question
704
+        $loggedInUser = $this->userSession->getUser();
705
+        $subAdminManager = $this->groupManager->getSubAdmin();
706
+        if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
707
+            throw new OCSException('', 104);
708
+        }
709
+
710
+        // Add user to group
711
+        $group->addUser($targetUser);
712
+        return new DataResponse();
713
+    }
714
+
715
+    /**
716
+     * @PasswordConfirmationRequired
717
+     * @NoAdminRequired
718
+     *
719
+     * @param string $userId
720
+     * @param string $groupid
721
+     * @return DataResponse
722
+     * @throws OCSException
723
+     */
724
+    public function removeFromGroup(string $userId, string $groupid): DataResponse {
725
+        $loggedInUser = $this->userSession->getUser();
726
+
727
+        if ($groupid === null || trim($groupid) === '') {
728
+            throw new OCSException('', 101);
729
+        }
730
+
731
+        $group = $this->groupManager->get($groupid);
732
+        if ($group === null) {
733
+            throw new OCSException('', 102);
734
+        }
735
+
736
+        $targetUser = $this->userManager->get($userId);
737
+        if ($targetUser === null) {
738
+            throw new OCSException('', 103);
739
+        }
740
+
741
+        // If they're not an admin, check they are a subadmin of the group in question
742
+        $subAdminManager = $this->groupManager->getSubAdmin();
743
+        if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
744
+            throw new OCSException('', 104);
745
+        }
746
+
747
+        // Check they aren't removing themselves from 'admin' or their 'subadmin; group
748
+        if ($targetUser->getUID() === $loggedInUser->getUID()) {
749
+            if ($this->groupManager->isAdmin($loggedInUser->getUID())) {
750
+                if ($group->getGID() === 'admin') {
751
+                    throw new OCSException('Cannot remove yourself from the admin group', 105);
752
+                }
753
+            } else {
754
+                // Not an admin, so the user must be a subadmin of this group, but that is not allowed.
755
+                throw new OCSException('Cannot remove yourself from this group as you are a SubAdmin', 105);
756
+            }
757
+
758
+        } else if (!$this->groupManager->isAdmin($loggedInUser->getUID())) {
759
+            /** @var IGroup[] $subAdminGroups */
760
+            $subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
761
+            $subAdminGroups = array_map(function (IGroup $subAdminGroup) {
762
+                return $subAdminGroup->getGID();
763
+            }, $subAdminGroups);
764
+            $userGroups = $this->groupManager->getUserGroupIds($targetUser);
765
+            $userSubAdminGroups = array_intersect($subAdminGroups, $userGroups);
766
+
767
+            if (count($userSubAdminGroups) <= 1) {
768
+                // Subadmin must not be able to remove a user from all their subadmin groups.
769
+                throw new OCSException('Cannot remove user from this group as this is the only remaining group you are a SubAdmin of', 105);
770
+            }
771
+        }
772
+
773
+        // Remove user from group
774
+        $group->removeUser($targetUser);
775
+        return new DataResponse();
776
+    }
777
+
778
+    /**
779
+     * Creates a subadmin
780
+     *
781
+     * @PasswordConfirmationRequired
782
+     *
783
+     * @param string $userId
784
+     * @param string $groupid
785
+     * @return DataResponse
786
+     * @throws OCSException
787
+     */
788
+    public function addSubAdmin(string $userId, string $groupid): DataResponse {
789
+        $group = $this->groupManager->get($groupid);
790
+        $user = $this->userManager->get($userId);
791
+
792
+        // Check if the user exists
793
+        if ($user === null) {
794
+            throw new OCSException('User does not exist', 101);
795
+        }
796
+        // Check if group exists
797
+        if ($group === null) {
798
+            throw new OCSException('Group does not exist',  102);
799
+        }
800
+        // Check if trying to make subadmin of admin group
801
+        if ($group->getGID() === 'admin') {
802
+            throw new OCSException('Cannot create subadmins for admin group', 103);
803
+        }
804
+
805
+        $subAdminManager = $this->groupManager->getSubAdmin();
806
+
807
+        // We cannot be subadmin twice
808
+        if ($subAdminManager->isSubAdminOfGroup($user, $group)) {
809
+            return new DataResponse();
810
+        }
811
+        // Go
812
+        if ($subAdminManager->createSubAdmin($user, $group)) {
813
+            return new DataResponse();
814
+        } else {
815
+            throw new OCSException('Unknown error occurred', 103);
816
+        }
817
+    }
818
+
819
+    /**
820
+     * Removes a subadmin from a group
821
+     *
822
+     * @PasswordConfirmationRequired
823
+     *
824
+     * @param string $userId
825
+     * @param string $groupid
826
+     * @return DataResponse
827
+     * @throws OCSException
828
+     */
829
+    public function removeSubAdmin(string $userId, string $groupid): DataResponse {
830
+        $group = $this->groupManager->get($groupid);
831
+        $user = $this->userManager->get($userId);
832
+        $subAdminManager = $this->groupManager->getSubAdmin();
833
+
834
+        // Check if the user exists
835
+        if ($user === null) {
836
+            throw new OCSException('User does not exist', 101);
837
+        }
838
+        // Check if the group exists
839
+        if ($group === null) {
840
+            throw new OCSException('Group does not exist', 101);
841
+        }
842
+        // Check if they are a subadmin of this said group
843
+        if (!$subAdminManager->isSubAdminOfGroup($user, $group)) {
844
+            throw new OCSException('User is not a subadmin of this group', 102);
845
+        }
846
+
847
+        // Go
848
+        if ($subAdminManager->deleteSubAdmin($user, $group)) {
849
+            return new DataResponse();
850
+        } else {
851
+            throw new OCSException('Unknown error occurred', 103);
852
+        }
853
+    }
854
+
855
+    /**
856
+     * Get the groups a user is a subadmin of
857
+     *
858
+     * @param string $userId
859
+     * @return DataResponse
860
+     * @throws OCSException
861
+     */
862
+    public function getUserSubAdminGroups(string $userId): DataResponse {
863
+        $groups = $this->getUserSubAdminGroupsData($userId);
864
+        return new DataResponse($groups);
865
+    }
866
+
867
+    /**
868
+     * @NoAdminRequired
869
+     * @PasswordConfirmationRequired
870
+     *
871
+     * resend welcome message
872
+     *
873
+     * @param string $userId
874
+     * @return DataResponse
875
+     * @throws OCSException
876
+     */
877
+    public function resendWelcomeMessage(string $userId): DataResponse {
878
+        $currentLoggedInUser = $this->userSession->getUser();
879
+
880
+        $targetUser = $this->userManager->get($userId);
881
+        if ($targetUser === null) {
882
+            throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
883
+        }
884
+
885
+        // Check if admin / subadmin
886
+        $subAdminManager = $this->groupManager->getSubAdmin();
887
+        if (!$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
888
+            && !$this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
889
+            // No rights
890
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
891
+        }
892
+
893
+        $email = $targetUser->getEMailAddress();
894
+        if ($email === '' || $email === null) {
895
+            throw new OCSException('Email address not available', 101);
896
+        }
897
+
898
+        try {
899
+            $emailTemplate = $this->newUserMailHelper->generateTemplate($targetUser, false);
900
+            $this->newUserMailHelper->sendMail($targetUser, $emailTemplate);
901
+        } catch(\Exception $e) {
902
+            $this->logger->logException($e, [
903
+                'message' => "Can't send new user mail to $email",
904
+                'level' => ILogger::ERROR,
905
+                'app' => 'settings',
906
+            ]);
907
+            throw new OCSException('Sending email failed', 102);
908
+        }
909
+
910
+        return new DataResponse();
911
+    }
912 912
 }
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -128,7 +128,7 @@  discard block
 block discarded – undo
128 128
 		// Admin? Or SubAdmin?
129 129
 		$uid = $user->getUID();
130 130
 		$subAdminManager = $this->groupManager->getSubAdmin();
131
-		if ($this->groupManager->isAdmin($uid)){
131
+		if ($this->groupManager->isAdmin($uid)) {
132 132
 			$users = $this->userManager->search($search, $limit, $offset);
133 133
 		} else if ($subAdminManager->isSubAdmin($user)) {
134 134
 			$subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
@@ -161,7 +161,7 @@  discard block
 block discarded – undo
161 161
 		// Admin? Or SubAdmin?
162 162
 		$uid = $currentUser->getUID();
163 163
 		$subAdminManager = $this->groupManager->getSubAdmin();
164
-		if ($this->groupManager->isAdmin($uid)){
164
+		if ($this->groupManager->isAdmin($uid)) {
165 165
 			$users = $this->userManager->search($search, $limit, $offset);
166 166
 			$users = array_keys($users);
167 167
 		} else if ($subAdminManager->isSubAdmin($currentUser)) {
@@ -234,7 +234,7 @@  discard block
 block discarded – undo
234 234
 					throw new OCSException('group '.$group.' does not exist', 104);
235 235
 				}
236 236
 				if (!$isAdmin && !$subAdminManager->isSubAdminOfGroup($user, $this->groupManager->get($group))) {
237
-					throw new OCSException('insufficient privileges for group '. $group, 105);
237
+					throw new OCSException('insufficient privileges for group '.$group, 105);
238 238
 				}
239 239
 			}
240 240
 		} else {
@@ -249,7 +249,7 @@  discard block
 block discarded – undo
249 249
 				$group = $this->groupManager->get($groupid);
250 250
 				// Check if group exists
251 251
 				if ($group === null) {
252
-					throw new OCSException('Subadmin group does not exist',  102);
252
+					throw new OCSException('Subadmin group does not exist', 102);
253 253
 				}
254 254
 				// Check if trying to make subadmin of admin group
255 255
 				if ($group->getGID() === 'admin') {
@@ -277,11 +277,11 @@  discard block
 block discarded – undo
277 277
 
278 278
 		try {
279 279
 			$newUser = $this->userManager->createUser($userid, $password);
280
-			$this->logger->info('Successful addUser call with userid: ' . $userid, ['app' => 'ocs_api']);
280
+			$this->logger->info('Successful addUser call with userid: '.$userid, ['app' => 'ocs_api']);
281 281
 
282 282
 			foreach ($groups as $group) {
283 283
 				$this->groupManager->get($group)->addUser($newUser);
284
-				$this->logger->info('Added userid ' . $userid . ' to group ' . $group, ['app' => 'ocs_api']);
284
+				$this->logger->info('Added userid '.$userid.' to group '.$group, ['app' => 'ocs_api']);
285 285
 			}
286 286
 			foreach ($subadminGroups as $group) {
287 287
 				$subAdminManager->createSubAdmin($newUser, $group);
@@ -317,7 +317,7 @@  discard block
 block discarded – undo
317 317
 
318 318
 			return new DataResponse();
319 319
 
320
-		} catch (HintException $e ) {
320
+		} catch (HintException $e) {
321 321
 			$this->logger->logException($e, [
322 322
 				'message' => 'Failed addUser attempt with hint exception.',
323 323
 				'level' => ILogger::WARN,
@@ -365,7 +365,7 @@  discard block
 block discarded – undo
365 365
 	public function getCurrentUser(): DataResponse {
366 366
 		$user = $this->userSession->getUser();
367 367
 		if ($user) {
368
-			$data =  $this->getUserData($user->getUID());
368
+			$data = $this->getUserData($user->getUID());
369 369
 			// rename "displayname" to "display-name" only for this call to keep
370 370
 			// the API stable.
371 371
 			$data['display-name'] = $data['displayname'];
@@ -487,7 +487,7 @@  discard block
 block discarded – undo
487 487
 			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
488 488
 		}
489 489
 		// Process the edit
490
-		switch($key) {
490
+		switch ($key) {
491 491
 			case 'display':
492 492
 			case AccountManager::PROPERTY_DISPLAYNAME:
493 493
 				$targetUser->setDisplayName($value);
@@ -758,7 +758,7 @@  discard block
 block discarded – undo
758 758
 		} else if (!$this->groupManager->isAdmin($loggedInUser->getUID())) {
759 759
 			/** @var IGroup[] $subAdminGroups */
760 760
 			$subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
761
-			$subAdminGroups = array_map(function (IGroup $subAdminGroup) {
761
+			$subAdminGroups = array_map(function(IGroup $subAdminGroup) {
762 762
 				return $subAdminGroup->getGID();
763 763
 			}, $subAdminGroups);
764 764
 			$userGroups = $this->groupManager->getUserGroupIds($targetUser);
@@ -795,7 +795,7 @@  discard block
 block discarded – undo
795 795
 		}
796 796
 		// Check if group exists
797 797
 		if ($group === null) {
798
-			throw new OCSException('Group does not exist',  102);
798
+			throw new OCSException('Group does not exist', 102);
799 799
 		}
800 800
 		// Check if trying to make subadmin of admin group
801 801
 		if ($group->getGID() === 'admin') {
@@ -898,7 +898,7 @@  discard block
 block discarded – undo
898 898
 		try {
899 899
 			$emailTemplate = $this->newUserMailHelper->generateTemplate($targetUser, false);
900 900
 			$this->newUserMailHelper->sendMail($targetUser, $emailTemplate);
901
-		} catch(\Exception $e) {
901
+		} catch (\Exception $e) {
902 902
 			$this->logger->logException($e, [
903 903
 				'message' => "Can't send new user mail to $email",
904 904
 				'level' => ILogger::ERROR,
Please login to merge, or discard this patch.
apps/provisioning_api/lib/AppInfo/Application.php 1 patch
Indentation   +29 added lines, -29 removed lines patch added patch discarded remove patch
@@ -33,35 +33,35 @@
 block discarded – undo
33 33
 use OCP\Util;
34 34
 
35 35
 class Application extends App {
36
-	public function __construct(array $urlParams = array()) {
37
-		parent::__construct('provisioning_api', $urlParams);
36
+    public function __construct(array $urlParams = array()) {
37
+        parent::__construct('provisioning_api', $urlParams);
38 38
 
39
-		$container = $this->getContainer();
40
-		$server = $container->getServer();
39
+        $container = $this->getContainer();
40
+        $server = $container->getServer();
41 41
 
42
-		$container->registerService(NewUserMailHelper::class, function(SimpleContainer $c) use ($server) {
43
-			return new NewUserMailHelper(
44
-				$server->query(Defaults::class),
45
-				$server->getURLGenerator(),
46
-				$server->getL10NFactory(),
47
-				$server->getMailer(),
48
-				$server->getSecureRandom(),
49
-				new TimeFactory(),
50
-				$server->getConfig(),
51
-				$server->getCrypto(),
52
-				Util::getDefaultEmailAddress('no-reply')
53
-			);
54
-		});
55
-		$container->registerService('ProvisioningApiMiddleware', function(SimpleContainer $c) use ($server) {
56
-			$user = $server->getUserManager()->get($c['UserId']);
57
-			$isAdmin = $user !== null ? $server->getGroupManager()->isAdmin($user->getUID()) : false;
58
-			$isSubAdmin = $user !== null ? $server->getGroupManager()->getSubAdmin()->isSubAdmin($user) : false;
59
-			return new ProvisioningApiMiddleware(
60
-				$c['ControllerMethodReflector'],
61
-				$isAdmin,
62
-				$isSubAdmin
63
-			);
64
-		});
65
-		$container->registerMiddleWare('ProvisioningApiMiddleware');
66
-	}
42
+        $container->registerService(NewUserMailHelper::class, function(SimpleContainer $c) use ($server) {
43
+            return new NewUserMailHelper(
44
+                $server->query(Defaults::class),
45
+                $server->getURLGenerator(),
46
+                $server->getL10NFactory(),
47
+                $server->getMailer(),
48
+                $server->getSecureRandom(),
49
+                new TimeFactory(),
50
+                $server->getConfig(),
51
+                $server->getCrypto(),
52
+                Util::getDefaultEmailAddress('no-reply')
53
+            );
54
+        });
55
+        $container->registerService('ProvisioningApiMiddleware', function(SimpleContainer $c) use ($server) {
56
+            $user = $server->getUserManager()->get($c['UserId']);
57
+            $isAdmin = $user !== null ? $server->getGroupManager()->isAdmin($user->getUID()) : false;
58
+            $isSubAdmin = $user !== null ? $server->getGroupManager()->getSubAdmin()->isSubAdmin($user) : false;
59
+            return new ProvisioningApiMiddleware(
60
+                $c['ControllerMethodReflector'],
61
+                $isAdmin,
62
+                $isSubAdmin
63
+            );
64
+        });
65
+        $container->registerMiddleWare('ProvisioningApiMiddleware');
66
+    }
67 67
 }
Please login to merge, or discard this patch.