Completed
Pull Request — master (#8336)
by Morris
32:25 queued 13:49
created
lib/private/AppFramework/DependencyInjection/DIContainer.php 2 patches
Indentation   +379 added lines, -379 removed lines patch added patch discarded remove patch
@@ -67,383 +67,383 @@
 block discarded – undo
67 67
 
68 68
 class DIContainer extends SimpleContainer implements IAppContainer {
69 69
 
70
-	/**
71
-	 * @var array
72
-	 */
73
-	private $middleWares = array();
74
-
75
-	/** @var ServerContainer */
76
-	private $server;
77
-
78
-	/**
79
-	 * Put your class dependencies in here
80
-	 * @param string $appName the name of the app
81
-	 * @param array $urlParams
82
-	 * @param ServerContainer|null $server
83
-	 */
84
-	public function __construct($appName, $urlParams = array(), ServerContainer $server = null){
85
-		parent::__construct();
86
-		$this['AppName'] = $appName;
87
-		$this['urlParams'] = $urlParams;
88
-
89
-		/** @var \OC\ServerContainer $server */
90
-		if ($server === null) {
91
-			$server = \OC::$server;
92
-		}
93
-		$this->server = $server;
94
-		$this->server->registerAppContainer($appName, $this);
95
-
96
-		// aliases
97
-		$this->registerAlias('appName', 'AppName');
98
-		$this->registerAlias('webRoot', 'WebRoot');
99
-		$this->registerAlias('userId', 'UserId');
100
-
101
-		/**
102
-		 * Core services
103
-		 */
104
-		$this->registerService(IOutput::class, function($c){
105
-			return new Output($this->getServer()->getWebRoot());
106
-		});
107
-
108
-		$this->registerService(Folder::class, function() {
109
-			return $this->getServer()->getUserFolder();
110
-		});
111
-
112
-		$this->registerService(IAppData::class, function (SimpleContainer $c) {
113
-			return $this->getServer()->getAppDataDir($c->query('AppName'));
114
-		});
115
-
116
-		$this->registerService(IL10N::class, function($c) {
117
-			return $this->getServer()->getL10N($c->query('AppName'));
118
-		});
119
-
120
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
121
-		$this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
122
-
123
-		$this->registerService(IRequest::class, function() {
124
-			return $this->getServer()->query(IRequest::class);
125
-		});
126
-		$this->registerAlias('Request', IRequest::class);
127
-
128
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
129
-		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
130
-
131
-		$this->registerAlias(\OC\User\Session::class, \OCP\IUserSession::class);
132
-
133
-		$this->registerService(IServerContainer::class, function ($c) {
134
-			return $this->getServer();
135
-		});
136
-		$this->registerAlias('ServerContainer', IServerContainer::class);
137
-
138
-		$this->registerService(\OCP\WorkflowEngine\IManager::class, function ($c) {
139
-			return $c->query(Manager::class);
140
-		});
141
-
142
-		$this->registerService(\OCP\AppFramework\IAppContainer::class, function ($c) {
143
-			return $c;
144
-		});
145
-
146
-		// commonly used attributes
147
-		$this->registerService('UserId', function ($c) {
148
-			return $c->query(IUserSession::class)->getSession()->get('user_id');
149
-		});
150
-
151
-		$this->registerService('WebRoot', function ($c) {
152
-			return $c->query('ServerContainer')->getWebRoot();
153
-		});
154
-
155
-		$this->registerService('OC_Defaults', function ($c) {
156
-			return $c->getServer()->getThemingDefaults();
157
-		});
158
-
159
-		$this->registerService(IManager::class, function ($c) {
160
-			return $this->getServer()->getEncryptionManager();
161
-		});
162
-
163
-		$this->registerService(IConfig::class, function ($c) {
164
-			return $c->query(OC\GlobalScale\Config::class);
165
-		});
166
-
167
-		$this->registerService(IValidator::class, function($c) {
168
-			return $c->query(Validator::class);
169
-		});
170
-
171
-		$this->registerService(\OC\Security\IdentityProof\Manager::class, function ($c) {
172
-			return new \OC\Security\IdentityProof\Manager(
173
-				$this->getServer()->query(\OC\Files\AppData\Factory::class),
174
-				$this->getServer()->getCrypto(),
175
-				$this->getServer()->getConfig()
176
-			);
177
-		});
178
-
179
-		$this->registerService('Protocol', function($c){
180
-			/** @var \OC\Server $server */
181
-			$server = $c->query('ServerContainer');
182
-			$protocol = $server->getRequest()->getHttpProtocol();
183
-			return new Http($_SERVER, $protocol);
184
-		});
185
-
186
-		$this->registerService('Dispatcher', function($c) {
187
-			return new Dispatcher(
188
-				$c['Protocol'],
189
-				$c['MiddlewareDispatcher'],
190
-				$c['ControllerMethodReflector'],
191
-				$c['Request']
192
-			);
193
-		});
194
-
195
-		/**
196
-		 * App Framework default arguments
197
-		 */
198
-		$this->registerParameter('corsMethods', 'PUT, POST, GET, DELETE, PATCH');
199
-		$this->registerParameter('corsAllowedHeaders', 'Authorization, Content-Type, Accept');
200
-		$this->registerParameter('corsMaxAge', 1728000);
201
-
202
-		/**
203
-		 * Middleware
204
-		 */
205
-		$app = $this;
206
-		$this->registerService('SecurityMiddleware', function($c) use ($app){
207
-			/** @var \OC\Server $server */
208
-			$server = $app->getServer();
209
-
210
-			return new SecurityMiddleware(
211
-				$c['Request'],
212
-				$c['ControllerMethodReflector'],
213
-				$server->getNavigationManager(),
214
-				$server->getURLGenerator(),
215
-				$server->getLogger(),
216
-				$c['AppName'],
217
-				$server->getUserSession()->isLoggedIn(),
218
-				$server->getGroupManager()->isAdmin($this->getUserId()),
219
-				$server->getContentSecurityPolicyManager(),
220
-				$server->getCsrfTokenManager(),
221
-				$server->getContentSecurityPolicyNonceManager(),
222
-				$server->getAppManager()
223
-			);
224
-		});
225
-
226
-		$this->registerService(OC\AppFramework\Middleware\Security\PasswordConfirmationMiddleware::class, function ($c) use ($app) {
227
-			/** @var \OC\Server $server */
228
-			$server = $app->getServer();
229
-
230
-			return new OC\AppFramework\Middleware\Security\PasswordConfirmationMiddleware(
231
-				$c['ControllerMethodReflector'],
232
-				$server->getSession(),
233
-				$server->getUserSession(),
234
-				$server->query(ITimeFactory::class)
235
-			);
236
-		});
237
-
238
-		$this->registerService('BruteForceMiddleware', function($c) use ($app) {
239
-			/** @var \OC\Server $server */
240
-			$server = $app->getServer();
241
-
242
-			return new OC\AppFramework\Middleware\Security\BruteForceMiddleware(
243
-				$c['ControllerMethodReflector'],
244
-				$server->getBruteForceThrottler(),
245
-				$server->getRequest()
246
-			);
247
-		});
248
-
249
-		$this->registerService('RateLimitingMiddleware', function($c) use ($app) {
250
-			/** @var \OC\Server $server */
251
-			$server = $app->getServer();
252
-
253
-			return new RateLimitingMiddleware(
254
-				$server->getRequest(),
255
-				$server->getUserSession(),
256
-				$c['ControllerMethodReflector'],
257
-				$c->query(OC\Security\RateLimiting\Limiter::class)
258
-			);
259
-		});
260
-
261
-		$this->registerService('CORSMiddleware', function($c) {
262
-			return new CORSMiddleware(
263
-				$c['Request'],
264
-				$c['ControllerMethodReflector'],
265
-				$c->query(IUserSession::class),
266
-				$c->getServer()->getBruteForceThrottler()
267
-			);
268
-		});
269
-
270
-		$this->registerService('SessionMiddleware', function($c) use ($app) {
271
-			return new SessionMiddleware(
272
-				$c['Request'],
273
-				$c['ControllerMethodReflector'],
274
-				$app->getServer()->getSession()
275
-			);
276
-		});
277
-
278
-		$this->registerService('TwoFactorMiddleware', function (SimpleContainer $c) use ($app) {
279
-			$twoFactorManager = $c->getServer()->getTwoFactorAuthManager();
280
-			$userSession = $app->getServer()->getUserSession();
281
-			$session = $app->getServer()->getSession();
282
-			$urlGenerator = $app->getServer()->getURLGenerator();
283
-			$reflector = $c['ControllerMethodReflector'];
284
-			$request = $app->getServer()->getRequest();
285
-			return new TwoFactorMiddleware($twoFactorManager, $userSession, $session, $urlGenerator, $reflector, $request);
286
-		});
287
-
288
-		$this->registerService('OCSMiddleware', function (SimpleContainer $c) {
289
-			return new OCSMiddleware(
290
-				$c['Request']
291
-			);
292
-		});
293
-
294
-		$this->registerService(OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware::class, function (SimpleContainer $c) {
295
-			return new OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware(
296
-				$c['Request'],
297
-				$c['ControllerMethodReflector']
298
-			);
299
-		});
300
-
301
-		$middleWares = &$this->middleWares;
302
-		$this->registerService('MiddlewareDispatcher', function($c) use (&$middleWares) {
303
-			$dispatcher = new MiddlewareDispatcher();
304
-			$dispatcher->registerMiddleware($c[OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware::class]);
305
-			$dispatcher->registerMiddleware($c['CORSMiddleware']);
306
-			$dispatcher->registerMiddleware($c['OCSMiddleware']);
307
-			$dispatcher->registerMiddleware($c['SecurityMiddleware']);
308
-			$dispatcher->registerMiddleware($c[OC\AppFramework\Middleware\Security\PasswordConfirmationMiddleware::class]);
309
-			$dispatcher->registerMiddleware($c['TwoFactorMiddleware']);
310
-			$dispatcher->registerMiddleware($c['BruteForceMiddleware']);
311
-			$dispatcher->registerMiddleware($c['RateLimitingMiddleware']);
312
-
313
-			foreach($middleWares as $middleWare) {
314
-				$dispatcher->registerMiddleware($c[$middleWare]);
315
-			}
316
-
317
-			$dispatcher->registerMiddleware($c['SessionMiddleware']);
318
-			return $dispatcher;
319
-		});
320
-
321
-	}
322
-
323
-	/**
324
-	 * @return \OCP\IServerContainer
325
-	 */
326
-	public function getServer()
327
-	{
328
-		return $this->server;
329
-	}
330
-
331
-	/**
332
-	 * @param string $middleWare
333
-	 * @return boolean|null
334
-	 */
335
-	public function registerMiddleWare($middleWare) {
336
-		$this->middleWares[] = $middleWare;
337
-	}
338
-
339
-	/**
340
-	 * used to return the appname of the set application
341
-	 * @return string the name of your application
342
-	 */
343
-	public function getAppName() {
344
-		return $this->query('AppName');
345
-	}
346
-
347
-	/**
348
-	 * @deprecated use IUserSession->isLoggedIn()
349
-	 * @return boolean
350
-	 */
351
-	public function isLoggedIn() {
352
-		return \OC::$server->getUserSession()->isLoggedIn();
353
-	}
354
-
355
-	/**
356
-	 * @deprecated use IGroupManager->isAdmin($userId)
357
-	 * @return boolean
358
-	 */
359
-	public function isAdminUser() {
360
-		$uid = $this->getUserId();
361
-		return \OC_User::isAdminUser($uid);
362
-	}
363
-
364
-	private function getUserId() {
365
-		return $this->getServer()->getSession()->get('user_id');
366
-	}
367
-
368
-	/**
369
-	 * @deprecated use the ILogger instead
370
-	 * @param string $message
371
-	 * @param string $level
372
-	 * @return mixed
373
-	 */
374
-	public function log($message, $level) {
375
-		switch($level){
376
-			case 'debug':
377
-				$level = \OCP\Util::DEBUG;
378
-				break;
379
-			case 'info':
380
-				$level = \OCP\Util::INFO;
381
-				break;
382
-			case 'warn':
383
-				$level = \OCP\Util::WARN;
384
-				break;
385
-			case 'fatal':
386
-				$level = \OCP\Util::FATAL;
387
-				break;
388
-			default:
389
-				$level = \OCP\Util::ERROR;
390
-				break;
391
-		}
392
-		\OCP\Util::writeLog($this->getAppName(), $message, $level);
393
-	}
394
-
395
-	/**
396
-	 * Register a capability
397
-	 *
398
-	 * @param string $serviceName e.g. 'OCA\Files\Capabilities'
399
-	 */
400
-	public function registerCapability($serviceName) {
401
-		$this->query('OC\CapabilitiesManager')->registerCapability(function() use ($serviceName) {
402
-			return $this->query($serviceName);
403
-		});
404
-	}
405
-
406
-	/**
407
-	 * @param string $name
408
-	 * @return mixed
409
-	 * @throws QueryException if the query could not be resolved
410
-	 */
411
-	public function query($name) {
412
-		try {
413
-			return $this->queryNoFallback($name);
414
-		} catch (QueryException $firstException) {
415
-			try {
416
-				return $this->getServer()->query($name);
417
-			} catch (QueryException $secondException) {
418
-				if ($firstException->getCode() === 1) {
419
-					throw $secondException;
420
-				}
421
-				throw $firstException;
422
-			}
423
-		}
424
-	}
425
-
426
-	/**
427
-	 * @param string $name
428
-	 * @return mixed
429
-	 * @throws QueryException if the query could not be resolved
430
-	 */
431
-	public function queryNoFallback($name) {
432
-		$name = $this->sanitizeName($name);
433
-
434
-		if ($this->offsetExists($name)) {
435
-			return parent::query($name);
436
-		} else {
437
-			if ($this['AppName'] === 'settings' && strpos($name, 'OC\\Settings\\') === 0) {
438
-				return parent::query($name);
439
-			} else if ($this['AppName'] === 'core' && strpos($name, 'OC\\Core\\') === 0) {
440
-				return parent::query($name);
441
-			} else if (strpos($name, \OC\AppFramework\App::buildAppNamespace($this['AppName']) . '\\') === 0) {
442
-				return parent::query($name);
443
-			}
444
-		}
445
-
446
-		throw new QueryException('Could not resolve ' . $name . '!' .
447
-			' Class can not be instantiated', 1);
448
-	}
70
+    /**
71
+     * @var array
72
+     */
73
+    private $middleWares = array();
74
+
75
+    /** @var ServerContainer */
76
+    private $server;
77
+
78
+    /**
79
+     * Put your class dependencies in here
80
+     * @param string $appName the name of the app
81
+     * @param array $urlParams
82
+     * @param ServerContainer|null $server
83
+     */
84
+    public function __construct($appName, $urlParams = array(), ServerContainer $server = null){
85
+        parent::__construct();
86
+        $this['AppName'] = $appName;
87
+        $this['urlParams'] = $urlParams;
88
+
89
+        /** @var \OC\ServerContainer $server */
90
+        if ($server === null) {
91
+            $server = \OC::$server;
92
+        }
93
+        $this->server = $server;
94
+        $this->server->registerAppContainer($appName, $this);
95
+
96
+        // aliases
97
+        $this->registerAlias('appName', 'AppName');
98
+        $this->registerAlias('webRoot', 'WebRoot');
99
+        $this->registerAlias('userId', 'UserId');
100
+
101
+        /**
102
+         * Core services
103
+         */
104
+        $this->registerService(IOutput::class, function($c){
105
+            return new Output($this->getServer()->getWebRoot());
106
+        });
107
+
108
+        $this->registerService(Folder::class, function() {
109
+            return $this->getServer()->getUserFolder();
110
+        });
111
+
112
+        $this->registerService(IAppData::class, function (SimpleContainer $c) {
113
+            return $this->getServer()->getAppDataDir($c->query('AppName'));
114
+        });
115
+
116
+        $this->registerService(IL10N::class, function($c) {
117
+            return $this->getServer()->getL10N($c->query('AppName'));
118
+        });
119
+
120
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
121
+        $this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
122
+
123
+        $this->registerService(IRequest::class, function() {
124
+            return $this->getServer()->query(IRequest::class);
125
+        });
126
+        $this->registerAlias('Request', IRequest::class);
127
+
128
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
129
+        $this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
130
+
131
+        $this->registerAlias(\OC\User\Session::class, \OCP\IUserSession::class);
132
+
133
+        $this->registerService(IServerContainer::class, function ($c) {
134
+            return $this->getServer();
135
+        });
136
+        $this->registerAlias('ServerContainer', IServerContainer::class);
137
+
138
+        $this->registerService(\OCP\WorkflowEngine\IManager::class, function ($c) {
139
+            return $c->query(Manager::class);
140
+        });
141
+
142
+        $this->registerService(\OCP\AppFramework\IAppContainer::class, function ($c) {
143
+            return $c;
144
+        });
145
+
146
+        // commonly used attributes
147
+        $this->registerService('UserId', function ($c) {
148
+            return $c->query(IUserSession::class)->getSession()->get('user_id');
149
+        });
150
+
151
+        $this->registerService('WebRoot', function ($c) {
152
+            return $c->query('ServerContainer')->getWebRoot();
153
+        });
154
+
155
+        $this->registerService('OC_Defaults', function ($c) {
156
+            return $c->getServer()->getThemingDefaults();
157
+        });
158
+
159
+        $this->registerService(IManager::class, function ($c) {
160
+            return $this->getServer()->getEncryptionManager();
161
+        });
162
+
163
+        $this->registerService(IConfig::class, function ($c) {
164
+            return $c->query(OC\GlobalScale\Config::class);
165
+        });
166
+
167
+        $this->registerService(IValidator::class, function($c) {
168
+            return $c->query(Validator::class);
169
+        });
170
+
171
+        $this->registerService(\OC\Security\IdentityProof\Manager::class, function ($c) {
172
+            return new \OC\Security\IdentityProof\Manager(
173
+                $this->getServer()->query(\OC\Files\AppData\Factory::class),
174
+                $this->getServer()->getCrypto(),
175
+                $this->getServer()->getConfig()
176
+            );
177
+        });
178
+
179
+        $this->registerService('Protocol', function($c){
180
+            /** @var \OC\Server $server */
181
+            $server = $c->query('ServerContainer');
182
+            $protocol = $server->getRequest()->getHttpProtocol();
183
+            return new Http($_SERVER, $protocol);
184
+        });
185
+
186
+        $this->registerService('Dispatcher', function($c) {
187
+            return new Dispatcher(
188
+                $c['Protocol'],
189
+                $c['MiddlewareDispatcher'],
190
+                $c['ControllerMethodReflector'],
191
+                $c['Request']
192
+            );
193
+        });
194
+
195
+        /**
196
+         * App Framework default arguments
197
+         */
198
+        $this->registerParameter('corsMethods', 'PUT, POST, GET, DELETE, PATCH');
199
+        $this->registerParameter('corsAllowedHeaders', 'Authorization, Content-Type, Accept');
200
+        $this->registerParameter('corsMaxAge', 1728000);
201
+
202
+        /**
203
+         * Middleware
204
+         */
205
+        $app = $this;
206
+        $this->registerService('SecurityMiddleware', function($c) use ($app){
207
+            /** @var \OC\Server $server */
208
+            $server = $app->getServer();
209
+
210
+            return new SecurityMiddleware(
211
+                $c['Request'],
212
+                $c['ControllerMethodReflector'],
213
+                $server->getNavigationManager(),
214
+                $server->getURLGenerator(),
215
+                $server->getLogger(),
216
+                $c['AppName'],
217
+                $server->getUserSession()->isLoggedIn(),
218
+                $server->getGroupManager()->isAdmin($this->getUserId()),
219
+                $server->getContentSecurityPolicyManager(),
220
+                $server->getCsrfTokenManager(),
221
+                $server->getContentSecurityPolicyNonceManager(),
222
+                $server->getAppManager()
223
+            );
224
+        });
225
+
226
+        $this->registerService(OC\AppFramework\Middleware\Security\PasswordConfirmationMiddleware::class, function ($c) use ($app) {
227
+            /** @var \OC\Server $server */
228
+            $server = $app->getServer();
229
+
230
+            return new OC\AppFramework\Middleware\Security\PasswordConfirmationMiddleware(
231
+                $c['ControllerMethodReflector'],
232
+                $server->getSession(),
233
+                $server->getUserSession(),
234
+                $server->query(ITimeFactory::class)
235
+            );
236
+        });
237
+
238
+        $this->registerService('BruteForceMiddleware', function($c) use ($app) {
239
+            /** @var \OC\Server $server */
240
+            $server = $app->getServer();
241
+
242
+            return new OC\AppFramework\Middleware\Security\BruteForceMiddleware(
243
+                $c['ControllerMethodReflector'],
244
+                $server->getBruteForceThrottler(),
245
+                $server->getRequest()
246
+            );
247
+        });
248
+
249
+        $this->registerService('RateLimitingMiddleware', function($c) use ($app) {
250
+            /** @var \OC\Server $server */
251
+            $server = $app->getServer();
252
+
253
+            return new RateLimitingMiddleware(
254
+                $server->getRequest(),
255
+                $server->getUserSession(),
256
+                $c['ControllerMethodReflector'],
257
+                $c->query(OC\Security\RateLimiting\Limiter::class)
258
+            );
259
+        });
260
+
261
+        $this->registerService('CORSMiddleware', function($c) {
262
+            return new CORSMiddleware(
263
+                $c['Request'],
264
+                $c['ControllerMethodReflector'],
265
+                $c->query(IUserSession::class),
266
+                $c->getServer()->getBruteForceThrottler()
267
+            );
268
+        });
269
+
270
+        $this->registerService('SessionMiddleware', function($c) use ($app) {
271
+            return new SessionMiddleware(
272
+                $c['Request'],
273
+                $c['ControllerMethodReflector'],
274
+                $app->getServer()->getSession()
275
+            );
276
+        });
277
+
278
+        $this->registerService('TwoFactorMiddleware', function (SimpleContainer $c) use ($app) {
279
+            $twoFactorManager = $c->getServer()->getTwoFactorAuthManager();
280
+            $userSession = $app->getServer()->getUserSession();
281
+            $session = $app->getServer()->getSession();
282
+            $urlGenerator = $app->getServer()->getURLGenerator();
283
+            $reflector = $c['ControllerMethodReflector'];
284
+            $request = $app->getServer()->getRequest();
285
+            return new TwoFactorMiddleware($twoFactorManager, $userSession, $session, $urlGenerator, $reflector, $request);
286
+        });
287
+
288
+        $this->registerService('OCSMiddleware', function (SimpleContainer $c) {
289
+            return new OCSMiddleware(
290
+                $c['Request']
291
+            );
292
+        });
293
+
294
+        $this->registerService(OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware::class, function (SimpleContainer $c) {
295
+            return new OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware(
296
+                $c['Request'],
297
+                $c['ControllerMethodReflector']
298
+            );
299
+        });
300
+
301
+        $middleWares = &$this->middleWares;
302
+        $this->registerService('MiddlewareDispatcher', function($c) use (&$middleWares) {
303
+            $dispatcher = new MiddlewareDispatcher();
304
+            $dispatcher->registerMiddleware($c[OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware::class]);
305
+            $dispatcher->registerMiddleware($c['CORSMiddleware']);
306
+            $dispatcher->registerMiddleware($c['OCSMiddleware']);
307
+            $dispatcher->registerMiddleware($c['SecurityMiddleware']);
308
+            $dispatcher->registerMiddleware($c[OC\AppFramework\Middleware\Security\PasswordConfirmationMiddleware::class]);
309
+            $dispatcher->registerMiddleware($c['TwoFactorMiddleware']);
310
+            $dispatcher->registerMiddleware($c['BruteForceMiddleware']);
311
+            $dispatcher->registerMiddleware($c['RateLimitingMiddleware']);
312
+
313
+            foreach($middleWares as $middleWare) {
314
+                $dispatcher->registerMiddleware($c[$middleWare]);
315
+            }
316
+
317
+            $dispatcher->registerMiddleware($c['SessionMiddleware']);
318
+            return $dispatcher;
319
+        });
320
+
321
+    }
322
+
323
+    /**
324
+     * @return \OCP\IServerContainer
325
+     */
326
+    public function getServer()
327
+    {
328
+        return $this->server;
329
+    }
330
+
331
+    /**
332
+     * @param string $middleWare
333
+     * @return boolean|null
334
+     */
335
+    public function registerMiddleWare($middleWare) {
336
+        $this->middleWares[] = $middleWare;
337
+    }
338
+
339
+    /**
340
+     * used to return the appname of the set application
341
+     * @return string the name of your application
342
+     */
343
+    public function getAppName() {
344
+        return $this->query('AppName');
345
+    }
346
+
347
+    /**
348
+     * @deprecated use IUserSession->isLoggedIn()
349
+     * @return boolean
350
+     */
351
+    public function isLoggedIn() {
352
+        return \OC::$server->getUserSession()->isLoggedIn();
353
+    }
354
+
355
+    /**
356
+     * @deprecated use IGroupManager->isAdmin($userId)
357
+     * @return boolean
358
+     */
359
+    public function isAdminUser() {
360
+        $uid = $this->getUserId();
361
+        return \OC_User::isAdminUser($uid);
362
+    }
363
+
364
+    private function getUserId() {
365
+        return $this->getServer()->getSession()->get('user_id');
366
+    }
367
+
368
+    /**
369
+     * @deprecated use the ILogger instead
370
+     * @param string $message
371
+     * @param string $level
372
+     * @return mixed
373
+     */
374
+    public function log($message, $level) {
375
+        switch($level){
376
+            case 'debug':
377
+                $level = \OCP\Util::DEBUG;
378
+                break;
379
+            case 'info':
380
+                $level = \OCP\Util::INFO;
381
+                break;
382
+            case 'warn':
383
+                $level = \OCP\Util::WARN;
384
+                break;
385
+            case 'fatal':
386
+                $level = \OCP\Util::FATAL;
387
+                break;
388
+            default:
389
+                $level = \OCP\Util::ERROR;
390
+                break;
391
+        }
392
+        \OCP\Util::writeLog($this->getAppName(), $message, $level);
393
+    }
394
+
395
+    /**
396
+     * Register a capability
397
+     *
398
+     * @param string $serviceName e.g. 'OCA\Files\Capabilities'
399
+     */
400
+    public function registerCapability($serviceName) {
401
+        $this->query('OC\CapabilitiesManager')->registerCapability(function() use ($serviceName) {
402
+            return $this->query($serviceName);
403
+        });
404
+    }
405
+
406
+    /**
407
+     * @param string $name
408
+     * @return mixed
409
+     * @throws QueryException if the query could not be resolved
410
+     */
411
+    public function query($name) {
412
+        try {
413
+            return $this->queryNoFallback($name);
414
+        } catch (QueryException $firstException) {
415
+            try {
416
+                return $this->getServer()->query($name);
417
+            } catch (QueryException $secondException) {
418
+                if ($firstException->getCode() === 1) {
419
+                    throw $secondException;
420
+                }
421
+                throw $firstException;
422
+            }
423
+        }
424
+    }
425
+
426
+    /**
427
+     * @param string $name
428
+     * @return mixed
429
+     * @throws QueryException if the query could not be resolved
430
+     */
431
+    public function queryNoFallback($name) {
432
+        $name = $this->sanitizeName($name);
433
+
434
+        if ($this->offsetExists($name)) {
435
+            return parent::query($name);
436
+        } else {
437
+            if ($this['AppName'] === 'settings' && strpos($name, 'OC\\Settings\\') === 0) {
438
+                return parent::query($name);
439
+            } else if ($this['AppName'] === 'core' && strpos($name, 'OC\\Core\\') === 0) {
440
+                return parent::query($name);
441
+            } else if (strpos($name, \OC\AppFramework\App::buildAppNamespace($this['AppName']) . '\\') === 0) {
442
+                return parent::query($name);
443
+            }
444
+        }
445
+
446
+        throw new QueryException('Could not resolve ' . $name . '!' .
447
+            ' Class can not be instantiated', 1);
448
+    }
449 449
 }
Please login to merge, or discard this patch.
Spacing   +21 added lines, -21 removed lines patch added patch discarded remove patch
@@ -81,7 +81,7 @@  discard block
 block discarded – undo
81 81
 	 * @param array $urlParams
82 82
 	 * @param ServerContainer|null $server
83 83
 	 */
84
-	public function __construct($appName, $urlParams = array(), ServerContainer $server = null){
84
+	public function __construct($appName, $urlParams = array(), ServerContainer $server = null) {
85 85
 		parent::__construct();
86 86
 		$this['AppName'] = $appName;
87 87
 		$this['urlParams'] = $urlParams;
@@ -101,7 +101,7 @@  discard block
 block discarded – undo
101 101
 		/**
102 102
 		 * Core services
103 103
 		 */
104
-		$this->registerService(IOutput::class, function($c){
104
+		$this->registerService(IOutput::class, function($c) {
105 105
 			return new Output($this->getServer()->getWebRoot());
106 106
 		});
107 107
 
@@ -109,7 +109,7 @@  discard block
 block discarded – undo
109 109
 			return $this->getServer()->getUserFolder();
110 110
 		});
111 111
 
112
-		$this->registerService(IAppData::class, function (SimpleContainer $c) {
112
+		$this->registerService(IAppData::class, function(SimpleContainer $c) {
113 113
 			return $this->getServer()->getAppDataDir($c->query('AppName'));
114 114
 		});
115 115
 
@@ -130,37 +130,37 @@  discard block
 block discarded – undo
130 130
 
131 131
 		$this->registerAlias(\OC\User\Session::class, \OCP\IUserSession::class);
132 132
 
133
-		$this->registerService(IServerContainer::class, function ($c) {
133
+		$this->registerService(IServerContainer::class, function($c) {
134 134
 			return $this->getServer();
135 135
 		});
136 136
 		$this->registerAlias('ServerContainer', IServerContainer::class);
137 137
 
138
-		$this->registerService(\OCP\WorkflowEngine\IManager::class, function ($c) {
138
+		$this->registerService(\OCP\WorkflowEngine\IManager::class, function($c) {
139 139
 			return $c->query(Manager::class);
140 140
 		});
141 141
 
142
-		$this->registerService(\OCP\AppFramework\IAppContainer::class, function ($c) {
142
+		$this->registerService(\OCP\AppFramework\IAppContainer::class, function($c) {
143 143
 			return $c;
144 144
 		});
145 145
 
146 146
 		// commonly used attributes
147
-		$this->registerService('UserId', function ($c) {
147
+		$this->registerService('UserId', function($c) {
148 148
 			return $c->query(IUserSession::class)->getSession()->get('user_id');
149 149
 		});
150 150
 
151
-		$this->registerService('WebRoot', function ($c) {
151
+		$this->registerService('WebRoot', function($c) {
152 152
 			return $c->query('ServerContainer')->getWebRoot();
153 153
 		});
154 154
 
155
-		$this->registerService('OC_Defaults', function ($c) {
155
+		$this->registerService('OC_Defaults', function($c) {
156 156
 			return $c->getServer()->getThemingDefaults();
157 157
 		});
158 158
 
159
-		$this->registerService(IManager::class, function ($c) {
159
+		$this->registerService(IManager::class, function($c) {
160 160
 			return $this->getServer()->getEncryptionManager();
161 161
 		});
162 162
 
163
-		$this->registerService(IConfig::class, function ($c) {
163
+		$this->registerService(IConfig::class, function($c) {
164 164
 			return $c->query(OC\GlobalScale\Config::class);
165 165
 		});
166 166
 
@@ -168,7 +168,7 @@  discard block
 block discarded – undo
168 168
 			return $c->query(Validator::class);
169 169
 		});
170 170
 
171
-		$this->registerService(\OC\Security\IdentityProof\Manager::class, function ($c) {
171
+		$this->registerService(\OC\Security\IdentityProof\Manager::class, function($c) {
172 172
 			return new \OC\Security\IdentityProof\Manager(
173 173
 				$this->getServer()->query(\OC\Files\AppData\Factory::class),
174 174
 				$this->getServer()->getCrypto(),
@@ -176,7 +176,7 @@  discard block
 block discarded – undo
176 176
 			);
177 177
 		});
178 178
 
179
-		$this->registerService('Protocol', function($c){
179
+		$this->registerService('Protocol', function($c) {
180 180
 			/** @var \OC\Server $server */
181 181
 			$server = $c->query('ServerContainer');
182 182
 			$protocol = $server->getRequest()->getHttpProtocol();
@@ -223,7 +223,7 @@  discard block
 block discarded – undo
223 223
 			);
224 224
 		});
225 225
 
226
-		$this->registerService(OC\AppFramework\Middleware\Security\PasswordConfirmationMiddleware::class, function ($c) use ($app) {
226
+		$this->registerService(OC\AppFramework\Middleware\Security\PasswordConfirmationMiddleware::class, function($c) use ($app) {
227 227
 			/** @var \OC\Server $server */
228 228
 			$server = $app->getServer();
229 229
 
@@ -275,7 +275,7 @@  discard block
 block discarded – undo
275 275
 			);
276 276
 		});
277 277
 
278
-		$this->registerService('TwoFactorMiddleware', function (SimpleContainer $c) use ($app) {
278
+		$this->registerService('TwoFactorMiddleware', function(SimpleContainer $c) use ($app) {
279 279
 			$twoFactorManager = $c->getServer()->getTwoFactorAuthManager();
280 280
 			$userSession = $app->getServer()->getUserSession();
281 281
 			$session = $app->getServer()->getSession();
@@ -285,13 +285,13 @@  discard block
 block discarded – undo
285 285
 			return new TwoFactorMiddleware($twoFactorManager, $userSession, $session, $urlGenerator, $reflector, $request);
286 286
 		});
287 287
 
288
-		$this->registerService('OCSMiddleware', function (SimpleContainer $c) {
288
+		$this->registerService('OCSMiddleware', function(SimpleContainer $c) {
289 289
 			return new OCSMiddleware(
290 290
 				$c['Request']
291 291
 			);
292 292
 		});
293 293
 
294
-		$this->registerService(OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware::class, function (SimpleContainer $c) {
294
+		$this->registerService(OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware::class, function(SimpleContainer $c) {
295 295
 			return new OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware(
296 296
 				$c['Request'],
297 297
 				$c['ControllerMethodReflector']
@@ -310,7 +310,7 @@  discard block
 block discarded – undo
310 310
 			$dispatcher->registerMiddleware($c['BruteForceMiddleware']);
311 311
 			$dispatcher->registerMiddleware($c['RateLimitingMiddleware']);
312 312
 
313
-			foreach($middleWares as $middleWare) {
313
+			foreach ($middleWares as $middleWare) {
314 314
 				$dispatcher->registerMiddleware($c[$middleWare]);
315 315
 			}
316 316
 
@@ -372,7 +372,7 @@  discard block
 block discarded – undo
372 372
 	 * @return mixed
373 373
 	 */
374 374
 	public function log($message, $level) {
375
-		switch($level){
375
+		switch ($level) {
376 376
 			case 'debug':
377 377
 				$level = \OCP\Util::DEBUG;
378 378
 				break;
@@ -438,12 +438,12 @@  discard block
 block discarded – undo
438 438
 				return parent::query($name);
439 439
 			} else if ($this['AppName'] === 'core' && strpos($name, 'OC\\Core\\') === 0) {
440 440
 				return parent::query($name);
441
-			} else if (strpos($name, \OC\AppFramework\App::buildAppNamespace($this['AppName']) . '\\') === 0) {
441
+			} else if (strpos($name, \OC\AppFramework\App::buildAppNamespace($this['AppName']).'\\') === 0) {
442 442
 				return parent::query($name);
443 443
 			}
444 444
 		}
445 445
 
446
-		throw new QueryException('Could not resolve ' . $name . '!' .
446
+		throw new QueryException('Could not resolve '.$name.'!'.
447 447
 			' Class can not be instantiated', 1);
448 448
 	}
449 449
 }
Please login to merge, or discard this patch.
core/Controller/AutoCompleteController.php 1 patch
Indentation   +56 added lines, -56 removed lines patch added patch discarded remove patch
@@ -31,69 +31,69 @@
 block discarded – undo
31 31
 use OCP\Share;
32 32
 
33 33
 class AutoCompleteController extends Controller {
34
-	/** @var ISearch */
35
-	private $collaboratorSearch;
36
-	/** @var IManager */
37
-	private $autoCompleteManager;
34
+    /** @var ISearch */
35
+    private $collaboratorSearch;
36
+    /** @var IManager */
37
+    private $autoCompleteManager;
38 38
 
39
-	public function __construct(
40
-		$appName,
41
-		IRequest $request,
42
-		ISearch $collaboratorSearch,
43
-		IManager $autoCompleteManager
44
-	) {
45
-		parent::__construct($appName, $request);
39
+    public function __construct(
40
+        $appName,
41
+        IRequest $request,
42
+        ISearch $collaboratorSearch,
43
+        IManager $autoCompleteManager
44
+    ) {
45
+        parent::__construct($appName, $request);
46 46
 
47
-		$this->collaboratorSearch = $collaboratorSearch;
48
-		$this->autoCompleteManager = $autoCompleteManager;
49
-	}
47
+        $this->collaboratorSearch = $collaboratorSearch;
48
+        $this->autoCompleteManager = $autoCompleteManager;
49
+    }
50 50
 
51
-	/**
52
-	 * @NoAdminRequired
53
-	 *
54
-	 * @param string $search
55
-	 * @param string $itemType
56
-	 * @param string $itemId
57
-	 * @param string|null $sorter can be piped, top prio first, e.g.: "commenters|share-recipients"
58
-	 * @param array $shareTypes
59
-	 * @param int $limit
60
-	 * @return DataResponse
61
-	 */
62
-	public function get($search, $itemType, $itemId, $sorter = null, $shareTypes = [Share::SHARE_TYPE_USER], $limit = 10) {
63
-		// if enumeration/user listings are disabled, we'll receive an empty
64
-		// result from search() – thus nothing else to do here.
65
-		list($results,) = $this->collaboratorSearch->search($search, $shareTypes, false, $limit, 0);
51
+    /**
52
+     * @NoAdminRequired
53
+     *
54
+     * @param string $search
55
+     * @param string $itemType
56
+     * @param string $itemId
57
+     * @param string|null $sorter can be piped, top prio first, e.g.: "commenters|share-recipients"
58
+     * @param array $shareTypes
59
+     * @param int $limit
60
+     * @return DataResponse
61
+     */
62
+    public function get($search, $itemType, $itemId, $sorter = null, $shareTypes = [Share::SHARE_TYPE_USER], $limit = 10) {
63
+        // if enumeration/user listings are disabled, we'll receive an empty
64
+        // result from search() – thus nothing else to do here.
65
+        list($results,) = $this->collaboratorSearch->search($search, $shareTypes, false, $limit, 0);
66 66
 
67
-		$exactMatches = $results['exact'];
68
-		unset($results['exact']);
69
-		$results = array_merge_recursive($exactMatches, $results);
67
+        $exactMatches = $results['exact'];
68
+        unset($results['exact']);
69
+        $results = array_merge_recursive($exactMatches, $results);
70 70
 
71
-		if($sorter !== null) {
72
-			$sorters = array_reverse(explode('|', $sorter));
73
-			$this->autoCompleteManager->runSorters($sorters, $results, [
74
-				'itemType' => $itemType,
75
-				'itemId' => $itemId,
76
-			]);
77
-		}
71
+        if($sorter !== null) {
72
+            $sorters = array_reverse(explode('|', $sorter));
73
+            $this->autoCompleteManager->runSorters($sorters, $results, [
74
+                'itemType' => $itemType,
75
+                'itemId' => $itemId,
76
+            ]);
77
+        }
78 78
 
79
-		// transform to expected format
80
-		$results = $this->prepareResultArray($results);
79
+        // transform to expected format
80
+        $results = $this->prepareResultArray($results);
81 81
 
82
-		return new DataResponse($results);
83
-	}
82
+        return new DataResponse($results);
83
+    }
84 84
 
85 85
 
86
-	protected function prepareResultArray(array $results) {
87
-		$output = [];
88
-		foreach ($results as $type => $subResult) {
89
-			foreach ($subResult as $result) {
90
-				$output[] = [
91
-					'id' => $result['value']['shareWith'],
92
-					'label' => $result['label'],
93
-					'source' => $type,
94
-				];
95
-			}
96
-		}
97
-		return $output;
98
-	}
86
+    protected function prepareResultArray(array $results) {
87
+        $output = [];
88
+        foreach ($results as $type => $subResult) {
89
+            foreach ($subResult as $result) {
90
+                $output[] = [
91
+                    'id' => $result['value']['shareWith'],
92
+                    'label' => $result['label'],
93
+                    'source' => $type,
94
+                ];
95
+            }
96
+        }
97
+        return $output;
98
+    }
99 99
 }
Please login to merge, or discard this patch.
settings/Controller/MailSettingsController.php 1 patch
Indentation   +128 added lines, -128 removed lines patch added patch discarded remove patch
@@ -39,133 +39,133 @@
 block discarded – undo
39 39
  */
40 40
 class MailSettingsController extends Controller {
41 41
 
42
-	/** @var IL10N */
43
-	private $l10n;
44
-	/** @var IConfig */
45
-	private $config;
46
-	/** @var IUserSession */
47
-	private $userSession;
48
-	/** @var IMailer */
49
-	private $mailer;
50
-
51
-	/**
52
-	 * @param string $appName
53
-	 * @param IRequest $request
54
-	 * @param IL10N $l10n
55
-	 * @param IConfig $config
56
-	 * @param IUserSession $userSession
57
-	 * @param IMailer $mailer
58
-	 */
59
-	public function __construct($appName,
60
-								IRequest $request,
61
-								IL10N $l10n,
62
-								IConfig $config,
63
-								IUserSession $userSession,
64
-								IMailer $mailer) {
65
-		parent::__construct($appName, $request);
66
-		$this->l10n = $l10n;
67
-		$this->config = $config;
68
-		$this->userSession = $userSession;
69
-		$this->mailer = $mailer;
70
-	}
71
-
72
-	/**
73
-	 * Sets the email settings
74
-	 *
75
-	 * @PasswordConfirmationRequired
76
-	 *
77
-	 * @param string $mail_domain
78
-	 * @param string $mail_from_address
79
-	 * @param string $mail_smtpmode
80
-	 * @param string $mail_smtpsecure
81
-	 * @param string $mail_smtphost
82
-	 * @param string $mail_smtpauthtype
83
-	 * @param int $mail_smtpauth
84
-	 * @param string $mail_smtpport
85
-	 * @return DataResponse
86
-	 */
87
-	public function setMailSettings($mail_domain,
88
-									$mail_from_address,
89
-									$mail_smtpmode,
90
-									$mail_smtpsecure,
91
-									$mail_smtphost,
92
-									$mail_smtpauthtype,
93
-									$mail_smtpauth,
94
-									$mail_smtpport) {
95
-
96
-		$params = get_defined_vars();
97
-		$configs = [];
98
-		foreach($params as $key => $value) {
99
-			$configs[$key] = empty($value) ? null : $value;
100
-		}
101
-
102
-		// Delete passwords from config in case no auth is specified
103
-		if ($params['mail_smtpauth'] !== 1) {
104
-			$configs['mail_smtpname'] = null;
105
-			$configs['mail_smtppassword'] = null;
106
-		}
107
-
108
-		$this->config->setSystemValues($configs);
109
-
110
-		return new DataResponse();
111
-	}
112
-
113
-	/**
114
-	 * Store the credentials used for SMTP in the config
115
-	 *
116
-	 * @PasswordConfirmationRequired
117
-	 *
118
-	 * @param string $mail_smtpname
119
-	 * @param string $mail_smtppassword
120
-	 * @return DataResponse
121
-	 */
122
-	public function storeCredentials($mail_smtpname, $mail_smtppassword) {
123
-		if ($mail_smtppassword === '********') {
124
-			return new DataResponse($this->l10n->t('Invalid SMTP password.'), Http::STATUS_BAD_REQUEST);
125
-		}
126
-
127
-		$this->config->setSystemValues([
128
-			'mail_smtpname'		=> $mail_smtpname,
129
-			'mail_smtppassword'	=> $mail_smtppassword,
130
-		]);
131
-
132
-		return new DataResponse();
133
-	}
134
-
135
-	/**
136
-	 * Send a mail to test the settings
137
-	 * @return DataResponse
138
-	 */
139
-	public function sendTestMail() {
140
-		$email = $this->config->getUserValue($this->userSession->getUser()->getUID(), $this->appName, 'email', '');
141
-		if (!empty($email)) {
142
-			try {
143
-				$displayName = $this->userSession->getUser()->getDisplayName();
144
-
145
-				$template = $this->mailer->createEMailTemplate('settings.TestEmail', [
146
-					'displayname' => $displayName,
147
-				]);
148
-
149
-				$template->setSubject($this->l10n->t('Email setting test'));
150
-				$template->addHeader();
151
-				$template->addHeading($this->l10n->t('Well done, %s!', [$displayName]));
152
-				$template->addBodyText($this->l10n->t('If you received this email, the email configuration seems to be correct.'));
153
-				$template->addFooter();
154
-
155
-				$message = $this->mailer->createMessage();
156
-				$message->setTo([$email => $displayName]);
157
-				$message->useTemplate($template);
158
-				$errors = $this->mailer->send($message);
159
-				if (!empty($errors)) {
160
-					throw new \RuntimeException($this->l10n->t('Email could not be sent. Check your mail server log'));
161
-				}
162
-				return new DataResponse();
163
-			} catch (\Exception $e) {
164
-				return new DataResponse($this->l10n->t('A problem occurred while sending the email. Please revise your settings. (Error: %s)', [$e->getMessage()]), Http::STATUS_BAD_REQUEST);
165
-			}
166
-		}
167
-
168
-		return new DataResponse($this->l10n->t('You need to set your user email before being able to send test emails.'), Http::STATUS_BAD_REQUEST);
169
-	}
42
+    /** @var IL10N */
43
+    private $l10n;
44
+    /** @var IConfig */
45
+    private $config;
46
+    /** @var IUserSession */
47
+    private $userSession;
48
+    /** @var IMailer */
49
+    private $mailer;
50
+
51
+    /**
52
+     * @param string $appName
53
+     * @param IRequest $request
54
+     * @param IL10N $l10n
55
+     * @param IConfig $config
56
+     * @param IUserSession $userSession
57
+     * @param IMailer $mailer
58
+     */
59
+    public function __construct($appName,
60
+                                IRequest $request,
61
+                                IL10N $l10n,
62
+                                IConfig $config,
63
+                                IUserSession $userSession,
64
+                                IMailer $mailer) {
65
+        parent::__construct($appName, $request);
66
+        $this->l10n = $l10n;
67
+        $this->config = $config;
68
+        $this->userSession = $userSession;
69
+        $this->mailer = $mailer;
70
+    }
71
+
72
+    /**
73
+     * Sets the email settings
74
+     *
75
+     * @PasswordConfirmationRequired
76
+     *
77
+     * @param string $mail_domain
78
+     * @param string $mail_from_address
79
+     * @param string $mail_smtpmode
80
+     * @param string $mail_smtpsecure
81
+     * @param string $mail_smtphost
82
+     * @param string $mail_smtpauthtype
83
+     * @param int $mail_smtpauth
84
+     * @param string $mail_smtpport
85
+     * @return DataResponse
86
+     */
87
+    public function setMailSettings($mail_domain,
88
+                                    $mail_from_address,
89
+                                    $mail_smtpmode,
90
+                                    $mail_smtpsecure,
91
+                                    $mail_smtphost,
92
+                                    $mail_smtpauthtype,
93
+                                    $mail_smtpauth,
94
+                                    $mail_smtpport) {
95
+
96
+        $params = get_defined_vars();
97
+        $configs = [];
98
+        foreach($params as $key => $value) {
99
+            $configs[$key] = empty($value) ? null : $value;
100
+        }
101
+
102
+        // Delete passwords from config in case no auth is specified
103
+        if ($params['mail_smtpauth'] !== 1) {
104
+            $configs['mail_smtpname'] = null;
105
+            $configs['mail_smtppassword'] = null;
106
+        }
107
+
108
+        $this->config->setSystemValues($configs);
109
+
110
+        return new DataResponse();
111
+    }
112
+
113
+    /**
114
+     * Store the credentials used for SMTP in the config
115
+     *
116
+     * @PasswordConfirmationRequired
117
+     *
118
+     * @param string $mail_smtpname
119
+     * @param string $mail_smtppassword
120
+     * @return DataResponse
121
+     */
122
+    public function storeCredentials($mail_smtpname, $mail_smtppassword) {
123
+        if ($mail_smtppassword === '********') {
124
+            return new DataResponse($this->l10n->t('Invalid SMTP password.'), Http::STATUS_BAD_REQUEST);
125
+        }
126
+
127
+        $this->config->setSystemValues([
128
+            'mail_smtpname'		=> $mail_smtpname,
129
+            'mail_smtppassword'	=> $mail_smtppassword,
130
+        ]);
131
+
132
+        return new DataResponse();
133
+    }
134
+
135
+    /**
136
+     * Send a mail to test the settings
137
+     * @return DataResponse
138
+     */
139
+    public function sendTestMail() {
140
+        $email = $this->config->getUserValue($this->userSession->getUser()->getUID(), $this->appName, 'email', '');
141
+        if (!empty($email)) {
142
+            try {
143
+                $displayName = $this->userSession->getUser()->getDisplayName();
144
+
145
+                $template = $this->mailer->createEMailTemplate('settings.TestEmail', [
146
+                    'displayname' => $displayName,
147
+                ]);
148
+
149
+                $template->setSubject($this->l10n->t('Email setting test'));
150
+                $template->addHeader();
151
+                $template->addHeading($this->l10n->t('Well done, %s!', [$displayName]));
152
+                $template->addBodyText($this->l10n->t('If you received this email, the email configuration seems to be correct.'));
153
+                $template->addFooter();
154
+
155
+                $message = $this->mailer->createMessage();
156
+                $message->setTo([$email => $displayName]);
157
+                $message->useTemplate($template);
158
+                $errors = $this->mailer->send($message);
159
+                if (!empty($errors)) {
160
+                    throw new \RuntimeException($this->l10n->t('Email could not be sent. Check your mail server log'));
161
+                }
162
+                return new DataResponse();
163
+            } catch (\Exception $e) {
164
+                return new DataResponse($this->l10n->t('A problem occurred while sending the email. Please revise your settings. (Error: %s)', [$e->getMessage()]), Http::STATUS_BAD_REQUEST);
165
+            }
166
+        }
167
+
168
+        return new DataResponse($this->l10n->t('You need to set your user email before being able to send test emails.'), Http::STATUS_BAD_REQUEST);
169
+    }
170 170
 
171 171
 }
Please login to merge, or discard this patch.
settings/Controller/UsersController.php 1 patch
Indentation   +971 added lines, -971 removed lines patch added patch discarded remove patch
@@ -68,976 +68,976 @@
 block discarded – undo
68 68
  * @package OC\Settings\Controller
69 69
  */
70 70
 class UsersController extends Controller {
71
-	/** @var IL10N */
72
-	private $l10n;
73
-	/** @var IUserSession */
74
-	private $userSession;
75
-	/** @var bool */
76
-	private $isAdmin;
77
-	/** @var IUserManager */
78
-	private $userManager;
79
-	/** @var IGroupManager */
80
-	private $groupManager;
81
-	/** @var IConfig */
82
-	private $config;
83
-	/** @var ILogger */
84
-	private $log;
85
-	/** @var IMailer */
86
-	private $mailer;
87
-	/** @var bool contains the state of the encryption app */
88
-	private $isEncryptionAppEnabled;
89
-	/** @var bool contains the state of the admin recovery setting */
90
-	private $isRestoreEnabled = false;
91
-	/** @var IAppManager */
92
-	private $appManager;
93
-	/** @var IAvatarManager */
94
-	private $avatarManager;
95
-	/** @var AccountManager */
96
-	private $accountManager;
97
-	/** @var ISecureRandom */
98
-	private $secureRandom;
99
-	/** @var NewUserMailHelper */
100
-	private $newUserMailHelper;
101
-	/** @var Manager */
102
-	private $keyManager;
103
-	/** @var IJobList */
104
-	private $jobList;
105
-
106
-	/** @var IUserMountCache */
107
-	private $userMountCache;
108
-
109
-	/** @var IManager */
110
-	private $encryptionManager;
111
-
112
-
113
-	/**
114
-	 * @param string $appName
115
-	 * @param IRequest $request
116
-	 * @param IUserManager $userManager
117
-	 * @param IGroupManager $groupManager
118
-	 * @param IUserSession $userSession
119
-	 * @param IConfig $config
120
-	 * @param bool $isAdmin
121
-	 * @param IL10N $l10n
122
-	 * @param ILogger $log
123
-	 * @param IMailer $mailer
124
-	 * @param IURLGenerator $urlGenerator
125
-	 * @param IAppManager $appManager
126
-	 * @param IAvatarManager $avatarManager
127
-	 * @param AccountManager $accountManager
128
-	 * @param ISecureRandom $secureRandom
129
-	 * @param NewUserMailHelper $newUserMailHelper
130
-	 * @param Manager $keyManager
131
-	 * @param IJobList $jobList
132
-	 * @param IUserMountCache $userMountCache
133
-	 * @param IManager $encryptionManager
134
-	 */
135
-	public function __construct($appName,
136
-								IRequest $request,
137
-								IUserManager $userManager,
138
-								IGroupManager $groupManager,
139
-								IUserSession $userSession,
140
-								IConfig $config,
141
-								$isAdmin,
142
-								IL10N $l10n,
143
-								ILogger $log,
144
-								IMailer $mailer,
145
-								IURLGenerator $urlGenerator,
146
-								IAppManager $appManager,
147
-								IAvatarManager $avatarManager,
148
-								AccountManager $accountManager,
149
-								ISecureRandom $secureRandom,
150
-								NewUserMailHelper $newUserMailHelper,
151
-								Manager $keyManager,
152
-								IJobList $jobList,
153
-								IUserMountCache $userMountCache,
154
-								IManager $encryptionManager) {
155
-		parent::__construct($appName, $request);
156
-		$this->userManager = $userManager;
157
-		$this->groupManager = $groupManager;
158
-		$this->userSession = $userSession;
159
-		$this->config = $config;
160
-		$this->isAdmin = $isAdmin;
161
-		$this->l10n = $l10n;
162
-		$this->log = $log;
163
-		$this->mailer = $mailer;
164
-		$this->appManager = $appManager;
165
-		$this->avatarManager = $avatarManager;
166
-		$this->accountManager = $accountManager;
167
-		$this->secureRandom = $secureRandom;
168
-		$this->newUserMailHelper = $newUserMailHelper;
169
-		$this->keyManager = $keyManager;
170
-		$this->jobList = $jobList;
171
-		$this->userMountCache = $userMountCache;
172
-		$this->encryptionManager = $encryptionManager;
173
-
174
-		// check for encryption state - TODO see formatUserForIndex
175
-		$this->isEncryptionAppEnabled = $appManager->isEnabledForUser('encryption');
176
-		if ($this->isEncryptionAppEnabled) {
177
-			// putting this directly in empty is possible in PHP 5.5+
178
-			$result = $config->getAppValue('encryption', 'recoveryAdminEnabled', '0');
179
-			$this->isRestoreEnabled = !empty($result);
180
-		}
181
-	}
182
-
183
-	/**
184
-	 * @param IUser $user
185
-	 * @param array|null $userGroups
186
-	 * @return array
187
-	 */
188
-	private function formatUserForIndex(IUser $user, array $userGroups = null) {
189
-
190
-		// TODO: eliminate this encryption specific code below and somehow
191
-		// hook in additional user info from other apps
192
-
193
-		// recovery isn't possible if admin or user has it disabled and encryption
194
-		// is enabled - so we eliminate the else paths in the conditional tree
195
-		// below
196
-		$restorePossible = false;
197
-
198
-		if ($this->isEncryptionAppEnabled) {
199
-			if ($this->isRestoreEnabled) {
200
-				// check for the users recovery setting
201
-				$recoveryMode = $this->config->getUserValue($user->getUID(), 'encryption', 'recoveryEnabled', '0');
202
-				// method call inside empty is possible with PHP 5.5+
203
-				$recoveryModeEnabled = !empty($recoveryMode);
204
-				if ($recoveryModeEnabled) {
205
-					// user also has recovery mode enabled
206
-					$restorePossible = true;
207
-				}
208
-			} else {
209
-				$modules = $this->encryptionManager->getEncryptionModules();
210
-				$restorePossible = true;
211
-				foreach ($modules as $id => $module) {
212
-					/* @var IEncryptionModule $instance */
213
-					$instance = call_user_func($module['callback']);
214
-					if ($instance->needDetailedAccessList()) {
215
-						$restorePossible = false;
216
-						break;
217
-					}
218
-				}
219
-			}
220
-		} else {
221
-			// recovery is possible if encryption is disabled (plain files are
222
-			// available)
223
-			$restorePossible = true;
224
-		}
225
-
226
-		$subAdminGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($user);
227
-		foreach ($subAdminGroups as $key => $subAdminGroup) {
228
-			$subAdminGroups[$key] = $subAdminGroup->getGID();
229
-		}
230
-
231
-		$displayName = $user->getEMailAddress();
232
-		if (is_null($displayName)) {
233
-			$displayName = '';
234
-		}
235
-
236
-		$avatarAvailable = false;
237
-		try {
238
-			$avatarAvailable = $this->avatarManager->getAvatar($user->getUID())->exists();
239
-		} catch (\Exception $e) {
240
-			//No avatar yet
241
-		}
242
-
243
-		return [
244
-			'name' => $user->getUID(),
245
-			'displayname' => $user->getDisplayName(),
246
-			'groups' => empty($userGroups) ? $this->groupManager->getUserGroupIds($user) : $userGroups,
247
-			'subadmin' => $subAdminGroups,
248
-			'quota' => $user->getQuota(),
249
-			'quota_bytes' => Util::computerFileSize($user->getQuota()),
250
-			'storageLocation' => $user->getHome(),
251
-			'lastLogin' => $user->getLastLogin() * 1000,
252
-			'backend' => $user->getBackendClassName(),
253
-			'email' => $displayName,
254
-			'isRestoreDisabled' => !$restorePossible,
255
-			'isAvatarAvailable' => $avatarAvailable,
256
-			'isEnabled' => $user->isEnabled(),
257
-		];
258
-	}
259
-
260
-	/**
261
-	 * @param array $userIDs Array with schema [$uid => $displayName]
262
-	 * @return IUser[]
263
-	 */
264
-	private function getUsersForUID(array $userIDs) {
265
-		$users = [];
266
-		foreach ($userIDs as $uid => $displayName) {
267
-			$users[$uid] = $this->userManager->get($uid);
268
-		}
269
-		return $users;
270
-	}
271
-
272
-	/**
273
-	 * @NoAdminRequired
274
-	 *
275
-	 * @param int $offset
276
-	 * @param int $limit
277
-	 * @param string $gid GID to filter for
278
-	 * @param string $pattern Pattern to search for in the username
279
-	 * @param string $backend Backend to filter for (class-name)
280
-	 * @return DataResponse
281
-	 *
282
-	 * TODO: Tidy up and write unit tests - code is mainly static method calls
283
-	 */
284
-	public function index($offset = 0, $limit = 10, $gid = '', $pattern = '', $backend = '') {
285
-		// Remove backends
286
-		if (!empty($backend)) {
287
-			$activeBackends = $this->userManager->getBackends();
288
-			$this->userManager->clearBackends();
289
-			foreach ($activeBackends as $singleActiveBackend) {
290
-				if ($backend === get_class($singleActiveBackend)) {
291
-					$this->userManager->registerBackend($singleActiveBackend);
292
-					break;
293
-				}
294
-			}
295
-		}
296
-
297
-		$userObjects = [];
298
-		$users = [];
299
-		if ($this->isAdmin) {
300
-			if ($gid !== '' && $gid !== '_disabledUsers' && $gid !== '_everyone') {
301
-				$batch = $this->getUsersForUID($this->groupManager->displayNamesInGroup($gid, $pattern, $limit, $offset));
302
-			} else {
303
-				$batch = $this->userManager->search($pattern, $limit, $offset);
304
-			}
305
-
306
-			foreach ($batch as $user) {
307
-				if (($gid !== '_disabledUsers' && $user->isEnabled()) ||
308
-					($gid === '_disabledUsers' && !$user->isEnabled())
309
-				) {
310
-					$userObjects[] = $user;
311
-					$users[] = $this->formatUserForIndex($user);
312
-				}
313
-			}
314
-
315
-		} else {
316
-			$subAdminOfGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($this->userSession->getUser());
317
-			// New class returns IGroup[] so convert back
318
-			$gids = [];
319
-			foreach ($subAdminOfGroups as $group) {
320
-				$gids[] = $group->getGID();
321
-			}
322
-			$subAdminOfGroups = $gids;
323
-
324
-			// Set the $gid parameter to an empty value if the subadmin has no rights to access a specific group
325
-			if ($gid !== '' && $gid !== '_disabledUsers' && !in_array($gid, $subAdminOfGroups)) {
326
-				$gid = '';
327
-			}
328
-
329
-			// Batch all groups the user is subadmin of when a group is specified
330
-			$batch = [];
331
-			if ($gid !== '' && $gid !== '_disabledUsers' && $gid !== '_everyone') {
332
-				$batch = $this->groupManager->displayNamesInGroup($gid, $pattern, $limit, $offset);
333
-			} else {
334
-				foreach ($subAdminOfGroups as $group) {
335
-					$groupUsers = $this->groupManager->displayNamesInGroup($group, $pattern, $limit, $offset);
336
-
337
-					foreach ($groupUsers as $uid => $displayName) {
338
-						$batch[$uid] = $displayName;
339
-					}
340
-				}
341
-			}
342
-			$batch = $this->getUsersForUID($batch);
343
-
344
-			foreach ($batch as $user) {
345
-				// Only add the groups, this user is a subadmin of
346
-				$userGroups = array_values(array_intersect(
347
-					$this->groupManager->getUserGroupIds($user),
348
-					$subAdminOfGroups
349
-				));
350
-				if (($gid !== '_disabledUsers' && $user->isEnabled()) ||
351
-					($gid === '_disabledUsers' && !$user->isEnabled())
352
-				) {
353
-					$userObjects[] = $user;
354
-					$users[] = $this->formatUserForIndex($user, $userGroups);
355
-				}
356
-			}
357
-		}
358
-
359
-		$usedSpace = $this->userMountCache->getUsedSpaceForUsers($userObjects);
360
-
361
-		foreach ($users as &$userData) {
362
-			$userData['size'] = isset($usedSpace[$userData['name']]) ? $usedSpace[$userData['name']] : 0;
363
-		}
364
-
365
-		return new DataResponse($users);
366
-	}
367
-
368
-	/**
369
-	 * @NoAdminRequired
370
-	 * @PasswordConfirmationRequired
371
-	 *
372
-	 * @param string $username
373
-	 * @param string $password
374
-	 * @param array $groups
375
-	 * @param string $email
376
-	 * @return DataResponse
377
-	 */
378
-	public function create($username, $password, array $groups = [], $email = '') {
379
-		if ($email !== '' && !$this->mailer->validateMailAddress($email)) {
380
-			return new DataResponse(
381
-				[
382
-					'message' => (string)$this->l10n->t('Invalid mail address')
383
-				],
384
-				Http::STATUS_UNPROCESSABLE_ENTITY
385
-			);
386
-		}
387
-
388
-		$currentUser = $this->userSession->getUser();
389
-
390
-		if (!$this->isAdmin) {
391
-			if (!empty($groups)) {
392
-				foreach ($groups as $key => $group) {
393
-					$groupObject = $this->groupManager->get($group);
394
-					if ($groupObject === null) {
395
-						unset($groups[$key]);
396
-						continue;
397
-					}
398
-
399
-					if (!$this->groupManager->getSubAdmin()->isSubAdminofGroup($currentUser, $groupObject)) {
400
-						unset($groups[$key]);
401
-					}
402
-				}
403
-			}
404
-
405
-			if (empty($groups)) {
406
-				return new DataResponse(
407
-					[
408
-						'message' => $this->l10n->t('No valid group selected'),
409
-					],
410
-					Http::STATUS_FORBIDDEN
411
-				);
412
-			}
413
-		}
414
-
415
-		if ($this->userManager->userExists($username)) {
416
-			return new DataResponse(
417
-				[
418
-					'message' => (string)$this->l10n->t('A user with that name already exists.')
419
-				],
420
-				Http::STATUS_CONFLICT
421
-			);
422
-		}
423
-
424
-		$generatePasswordResetToken = false;
425
-		if ($password === '') {
426
-			if ($email === '') {
427
-				return new DataResponse(
428
-					[
429
-						'message' => (string)$this->l10n->t('To send a password link to the user an email address is required.')
430
-					],
431
-					Http::STATUS_UNPROCESSABLE_ENTITY
432
-				);
433
-			}
434
-
435
-			$password = $this->secureRandom->generate(30);
436
-			// Make sure we pass the password_policy
437
-			$password .= $this->secureRandom->generate(2, '$!.,;:-~+*[]{}()');
438
-			$generatePasswordResetToken = true;
439
-		}
440
-
441
-		try {
442
-			$user = $this->userManager->createUser($username, $password);
443
-		} catch (\Exception $exception) {
444
-			$message = $exception->getMessage();
445
-			if ($exception instanceof HintException && $exception->getHint()) {
446
-				$message = $exception->getHint();
447
-			}
448
-			if (!$message) {
449
-				$message = $this->l10n->t('Unable to create user.');
450
-			}
451
-			return new DataResponse(
452
-				[
453
-					'message' => (string)$message,
454
-				],
455
-				Http::STATUS_FORBIDDEN
456
-			);
457
-		}
458
-
459
-		if ($user instanceof IUser) {
460
-			if ($groups !== null) {
461
-				foreach ($groups as $groupName) {
462
-					$group = $this->groupManager->get($groupName);
463
-
464
-					if (empty($group)) {
465
-						$group = $this->groupManager->createGroup($groupName);
466
-					}
467
-					$group->addUser($user);
468
-				}
469
-			}
470
-			/**
471
-			 * Send new user mail only if a mail is set
472
-			 */
473
-			if ($email !== '') {
474
-				$user->setEMailAddress($email);
475
-				try {
476
-					$emailTemplate = $this->newUserMailHelper->generateTemplate($user, $generatePasswordResetToken);
477
-					$this->newUserMailHelper->sendMail($user, $emailTemplate);
478
-				} catch (\Exception $e) {
479
-					$this->log->logException($e, [
480
-						'message' => "Can't send new user mail to $email",
481
-						'level' => \OCP\Util::ERROR,
482
-						'app' => 'settings',
483
-					]);
484
-				}
485
-			}
486
-			// fetch users groups
487
-			$userGroups = $this->groupManager->getUserGroupIds($user);
488
-
489
-			return new DataResponse(
490
-				$this->formatUserForIndex($user, $userGroups),
491
-				Http::STATUS_CREATED
492
-			);
493
-		}
494
-
495
-		return new DataResponse(
496
-			[
497
-				'message' => (string)$this->l10n->t('Unable to create user.')
498
-			],
499
-			Http::STATUS_FORBIDDEN
500
-		);
501
-
502
-	}
503
-
504
-	/**
505
-	 * @NoAdminRequired
506
-	 * @PasswordConfirmationRequired
507
-	 *
508
-	 * @param string $id
509
-	 * @return DataResponse
510
-	 */
511
-	public function destroy($id) {
512
-		$userId = $this->userSession->getUser()->getUID();
513
-		$user = $this->userManager->get($id);
514
-
515
-		if ($userId === $id) {
516
-			return new DataResponse(
517
-				[
518
-					'status' => 'error',
519
-					'data' => [
520
-						'message' => (string)$this->l10n->t('Unable to delete user.')
521
-					]
522
-				],
523
-				Http::STATUS_FORBIDDEN
524
-			);
525
-		}
526
-
527
-		if (!$this->isAdmin && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)) {
528
-			return new DataResponse(
529
-				[
530
-					'status' => 'error',
531
-					'data' => [
532
-						'message' => (string)$this->l10n->t('Authentication error')
533
-					]
534
-				],
535
-				Http::STATUS_FORBIDDEN
536
-			);
537
-		}
538
-
539
-		if ($user) {
540
-			if ($user->delete()) {
541
-				return new DataResponse(
542
-					[
543
-						'status' => 'success',
544
-						'data' => [
545
-							'username' => $id
546
-						]
547
-					],
548
-					Http::STATUS_NO_CONTENT
549
-				);
550
-			}
551
-		}
552
-
553
-		return new DataResponse(
554
-			[
555
-				'status' => 'error',
556
-				'data' => [
557
-					'message' => (string)$this->l10n->t('Unable to delete user.')
558
-				]
559
-			],
560
-			Http::STATUS_FORBIDDEN
561
-		);
562
-	}
563
-
564
-	/**
565
-	 * @NoAdminRequired
566
-	 *
567
-	 * @param string $id
568
-	 * @param int $enabled
569
-	 * @return DataResponse
570
-	 */
571
-	public function setEnabled($id, $enabled) {
572
-		$enabled = (bool)$enabled;
573
-		if ($enabled) {
574
-			$errorMsgGeneral = (string)$this->l10n->t('Error while enabling user.');
575
-		} else {
576
-			$errorMsgGeneral = (string)$this->l10n->t('Error while disabling user.');
577
-		}
578
-
579
-		$userId = $this->userSession->getUser()->getUID();
580
-		$user = $this->userManager->get($id);
581
-
582
-		if ($userId === $id) {
583
-			return new DataResponse(
584
-				[
585
-					'status' => 'error',
586
-					'data' => [
587
-						'message' => $errorMsgGeneral
588
-					]
589
-				], Http::STATUS_FORBIDDEN
590
-			);
591
-		}
592
-
593
-		if ($user) {
594
-			if (!$this->isAdmin && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)) {
595
-				return new DataResponse(
596
-					[
597
-						'status' => 'error',
598
-						'data' => [
599
-							'message' => (string)$this->l10n->t('Authentication error')
600
-						]
601
-					],
602
-					Http::STATUS_FORBIDDEN
603
-				);
604
-			}
605
-
606
-			$user->setEnabled($enabled);
607
-			return new DataResponse(
608
-				[
609
-					'status' => 'success',
610
-					'data' => [
611
-						'username' => $id,
612
-						'enabled' => $enabled
613
-					]
614
-				]
615
-			);
616
-		} else {
617
-			return new DataResponse(
618
-				[
619
-					'status' => 'error',
620
-					'data' => [
621
-						'message' => $errorMsgGeneral
622
-					]
623
-				],
624
-				Http::STATUS_FORBIDDEN
625
-			);
626
-		}
627
-
628
-	}
629
-
630
-	/**
631
-	 * Set the mail address of a user
632
-	 *
633
-	 * @NoAdminRequired
634
-	 * @NoSubadminRequired
635
-	 * @PasswordConfirmationRequired
636
-	 *
637
-	 * @param string $account
638
-	 * @param bool $onlyVerificationCode only return verification code without updating the data
639
-	 * @return DataResponse
640
-	 */
641
-	public function getVerificationCode($account, $onlyVerificationCode) {
642
-
643
-		$user = $this->userSession->getUser();
644
-
645
-		if ($user === null) {
646
-			return new DataResponse([], Http::STATUS_BAD_REQUEST);
647
-		}
648
-
649
-		$accountData = $this->accountManager->getUser($user);
650
-		$cloudId = $user->getCloudId();
651
-		$message = "Use my Federated Cloud ID to share with me: " . $cloudId;
652
-		$signature = $this->signMessage($user, $message);
653
-
654
-		$code = $message . ' ' . $signature;
655
-		$codeMd5 = $message . ' ' . md5($signature);
656
-
657
-		switch ($account) {
658
-			case 'verify-twitter':
659
-				$accountData[AccountManager::PROPERTY_TWITTER]['verified'] = AccountManager::VERIFICATION_IN_PROGRESS;
660
-				$msg = $this->l10n->t('In order to verify your Twitter account, post the following tweet on Twitter (please make sure to post it without any line breaks):');
661
-				$code = $codeMd5;
662
-				$type = AccountManager::PROPERTY_TWITTER;
663
-				$data = $accountData[AccountManager::PROPERTY_TWITTER]['value'];
664
-				$accountData[AccountManager::PROPERTY_TWITTER]['signature'] = $signature;
665
-				break;
666
-			case 'verify-website':
667
-				$accountData[AccountManager::PROPERTY_WEBSITE]['verified'] = AccountManager::VERIFICATION_IN_PROGRESS;
668
-				$msg = $this->l10n->t('In order to verify your Website, store the following content in your web-root at \'.well-known/CloudIdVerificationCode.txt\' (please make sure that the complete text is in one line):');
669
-				$type = AccountManager::PROPERTY_WEBSITE;
670
-				$data = $accountData[AccountManager::PROPERTY_WEBSITE]['value'];
671
-				$accountData[AccountManager::PROPERTY_WEBSITE]['signature'] = $signature;
672
-				break;
673
-			default:
674
-				return new DataResponse([], Http::STATUS_BAD_REQUEST);
675
-		}
676
-
677
-		if ($onlyVerificationCode === false) {
678
-			$this->accountManager->updateUser($user, $accountData);
679
-
680
-			$this->jobList->add(VerifyUserData::class,
681
-				[
682
-					'verificationCode' => $code,
683
-					'data' => $data,
684
-					'type' => $type,
685
-					'uid' => $user->getUID(),
686
-					'try' => 0,
687
-					'lastRun' => $this->getCurrentTime()
688
-				]
689
-			);
690
-		}
691
-
692
-		return new DataResponse(['msg' => $msg, 'code' => $code]);
693
-	}
694
-
695
-	/**
696
-	 * get current timestamp
697
-	 *
698
-	 * @return int
699
-	 */
700
-	protected function getCurrentTime() {
701
-		return time();
702
-	}
703
-
704
-	/**
705
-	 * sign message with users private key
706
-	 *
707
-	 * @param IUser $user
708
-	 * @param string $message
709
-	 *
710
-	 * @return string base64 encoded signature
711
-	 */
712
-	protected function signMessage(IUser $user, $message) {
713
-		$privateKey = $this->keyManager->getKey($user)->getPrivate();
714
-		openssl_sign(json_encode($message), $signature, $privateKey, OPENSSL_ALGO_SHA512);
715
-		return base64_encode($signature);
716
-	}
717
-
718
-	/**
719
-	 * @NoAdminRequired
720
-	 * @NoSubadminRequired
721
-	 * @PasswordConfirmationRequired
722
-	 *
723
-	 * @param string $avatarScope
724
-	 * @param string $displayname
725
-	 * @param string $displaynameScope
726
-	 * @param string $phone
727
-	 * @param string $phoneScope
728
-	 * @param string $email
729
-	 * @param string $emailScope
730
-	 * @param string $website
731
-	 * @param string $websiteScope
732
-	 * @param string $address
733
-	 * @param string $addressScope
734
-	 * @param string $twitter
735
-	 * @param string $twitterScope
736
-	 * @return DataResponse
737
-	 */
738
-	public function setUserSettings($avatarScope,
739
-									$displayname,
740
-									$displaynameScope,
741
-									$phone,
742
-									$phoneScope,
743
-									$email,
744
-									$emailScope,
745
-									$website,
746
-									$websiteScope,
747
-									$address,
748
-									$addressScope,
749
-									$twitter,
750
-									$twitterScope
751
-	) {
752
-
753
-		if (!empty($email) && !$this->mailer->validateMailAddress($email)) {
754
-			return new DataResponse(
755
-				[
756
-					'status' => 'error',
757
-					'data' => [
758
-						'message' => (string)$this->l10n->t('Invalid mail address')
759
-					]
760
-				],
761
-				Http::STATUS_UNPROCESSABLE_ENTITY
762
-			);
763
-		}
764
-
765
-		$user = $this->userSession->getUser();
766
-
767
-		$data = $this->accountManager->getUser($user);
768
-
769
-		$data[AccountManager::PROPERTY_AVATAR] = ['scope' => $avatarScope];
770
-		if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
771
-			$data[AccountManager::PROPERTY_DISPLAYNAME] = ['value' => $displayname, 'scope' => $displaynameScope];
772
-			$data[AccountManager::PROPERTY_EMAIL] = ['value' => $email, 'scope' => $emailScope];
773
-		}
774
-
775
-		if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
776
-			$federatedFileSharing = new \OCA\FederatedFileSharing\AppInfo\Application();
777
-			$shareProvider = $federatedFileSharing->getFederatedShareProvider();
778
-			if ($shareProvider->isLookupServerUploadEnabled()) {
779
-				$data[AccountManager::PROPERTY_WEBSITE] = ['value' => $website, 'scope' => $websiteScope];
780
-				$data[AccountManager::PROPERTY_ADDRESS] = ['value' => $address, 'scope' => $addressScope];
781
-				$data[AccountManager::PROPERTY_PHONE] = ['value' => $phone, 'scope' => $phoneScope];
782
-				$data[AccountManager::PROPERTY_TWITTER] = ['value' => $twitter, 'scope' => $twitterScope];
783
-			}
784
-		}
785
-
786
-		try {
787
-			$this->saveUserSettings($user, $data);
788
-			return new DataResponse(
789
-				[
790
-					'status' => 'success',
791
-					'data' => [
792
-						'userId' => $user->getUID(),
793
-						'avatarScope' => $data[AccountManager::PROPERTY_AVATAR]['scope'],
794
-						'displayname' => $data[AccountManager::PROPERTY_DISPLAYNAME]['value'],
795
-						'displaynameScope' => $data[AccountManager::PROPERTY_DISPLAYNAME]['scope'],
796
-						'email' => $data[AccountManager::PROPERTY_EMAIL]['value'],
797
-						'emailScope' => $data[AccountManager::PROPERTY_EMAIL]['scope'],
798
-						'website' => $data[AccountManager::PROPERTY_WEBSITE]['value'],
799
-						'websiteScope' => $data[AccountManager::PROPERTY_WEBSITE]['scope'],
800
-						'address' => $data[AccountManager::PROPERTY_ADDRESS]['value'],
801
-						'addressScope' => $data[AccountManager::PROPERTY_ADDRESS]['scope'],
802
-						'message' => (string)$this->l10n->t('Settings saved')
803
-					]
804
-				],
805
-				Http::STATUS_OK
806
-			);
807
-		} catch (ForbiddenException $e) {
808
-			return new DataResponse([
809
-				'status' => 'error',
810
-				'data' => [
811
-					'message' => $e->getMessage()
812
-				],
813
-			]);
814
-		}
815
-
816
-	}
817
-
818
-
819
-	/**
820
-	 * update account manager with new user data
821
-	 *
822
-	 * @param IUser $user
823
-	 * @param array $data
824
-	 * @throws ForbiddenException
825
-	 */
826
-	protected function saveUserSettings(IUser $user, $data) {
827
-
828
-		// keep the user back-end up-to-date with the latest display name and email
829
-		// address
830
-		$oldDisplayName = $user->getDisplayName();
831
-		$oldDisplayName = is_null($oldDisplayName) ? '' : $oldDisplayName;
832
-		if (isset($data[AccountManager::PROPERTY_DISPLAYNAME]['value'])
833
-			&& $oldDisplayName !== $data[AccountManager::PROPERTY_DISPLAYNAME]['value']
834
-		) {
835
-			$result = $user->setDisplayName($data[AccountManager::PROPERTY_DISPLAYNAME]['value']);
836
-			if ($result === false) {
837
-				throw new ForbiddenException($this->l10n->t('Unable to change full name'));
838
-			}
839
-		}
840
-
841
-		$oldEmailAddress = $user->getEMailAddress();
842
-		$oldEmailAddress = is_null($oldEmailAddress) ? '' : $oldEmailAddress;
843
-		if (isset($data[AccountManager::PROPERTY_EMAIL]['value'])
844
-			&& $oldEmailAddress !== $data[AccountManager::PROPERTY_EMAIL]['value']
845
-		) {
846
-			// this is the only permission a backend provides and is also used
847
-			// for the permission of setting a email address
848
-			if (!$user->canChangeDisplayName()) {
849
-				throw new ForbiddenException($this->l10n->t('Unable to change email address'));
850
-			}
851
-			$user->setEMailAddress($data[AccountManager::PROPERTY_EMAIL]['value']);
852
-		}
853
-
854
-		$this->accountManager->updateUser($user, $data);
855
-	}
856
-
857
-	/**
858
-	 * Count all unique users visible for the current admin/subadmin.
859
-	 *
860
-	 * @NoAdminRequired
861
-	 *
862
-	 * @return DataResponse
863
-	 */
864
-	public function stats() {
865
-		$userCount = 0;
866
-		if ($this->isAdmin) {
867
-			$countByBackend = $this->userManager->countUsers();
868
-
869
-			if (!empty($countByBackend)) {
870
-				foreach ($countByBackend as $count) {
871
-					$userCount += $count;
872
-				}
873
-			}
874
-		} else {
875
-			$groups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($this->userSession->getUser());
876
-
877
-			$uniqueUsers = [];
878
-			foreach ($groups as $group) {
879
-				foreach ($group->getUsers() as $uid => $displayName) {
880
-					$uniqueUsers[$uid] = true;
881
-				}
882
-			}
883
-
884
-			$userCount = count($uniqueUsers);
885
-		}
886
-
887
-		return new DataResponse(
888
-			[
889
-				'totalUsers' => $userCount
890
-			]
891
-		);
892
-	}
893
-
894
-
895
-	/**
896
-	 * Set the displayName of a user
897
-	 *
898
-	 * @NoAdminRequired
899
-	 * @NoSubadminRequired
900
-	 * @PasswordConfirmationRequired
901
-	 * @todo merge into saveUserSettings
902
-	 *
903
-	 * @param string $username
904
-	 * @param string $displayName
905
-	 * @return DataResponse
906
-	 */
907
-	public function setDisplayName($username, $displayName) {
908
-		$currentUser = $this->userSession->getUser();
909
-		$user = $this->userManager->get($username);
910
-
911
-		if ($user === null ||
912
-			!$user->canChangeDisplayName() ||
913
-			(
914
-				!$this->groupManager->isAdmin($currentUser->getUID()) &&
915
-				!$this->groupManager->getSubAdmin()->isUserAccessible($currentUser, $user) &&
916
-				$currentUser->getUID() !== $username
917
-
918
-			)
919
-		) {
920
-			return new DataResponse([
921
-				'status' => 'error',
922
-				'data' => [
923
-					'message' => $this->l10n->t('Authentication error'),
924
-				],
925
-			]);
926
-		}
927
-
928
-		$userData = $this->accountManager->getUser($user);
929
-		$userData[AccountManager::PROPERTY_DISPLAYNAME]['value'] = $displayName;
930
-
931
-
932
-		try {
933
-			$this->saveUserSettings($user, $userData);
934
-			return new DataResponse([
935
-				'status' => 'success',
936
-				'data' => [
937
-					'message' => $this->l10n->t('Your full name has been changed.'),
938
-					'username' => $username,
939
-					'displayName' => $displayName,
940
-				],
941
-			]);
942
-		} catch (ForbiddenException $e) {
943
-			return new DataResponse([
944
-				'status' => 'error',
945
-				'data' => [
946
-					'message' => $e->getMessage(),
947
-					'displayName' => $user->getDisplayName(),
948
-				],
949
-			]);
950
-		}
951
-	}
952
-
953
-	/**
954
-	 * Set the mail address of a user
955
-	 *
956
-	 * @NoAdminRequired
957
-	 * @NoSubadminRequired
958
-	 * @PasswordConfirmationRequired
959
-	 *
960
-	 * @param string $id
961
-	 * @param string $mailAddress
962
-	 * @return DataResponse
963
-	 */
964
-	public function setEMailAddress($id, $mailAddress) {
965
-		$user = $this->userManager->get($id);
966
-		if (!$this->isAdmin
967
-			&& !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)
968
-		) {
969
-			return new DataResponse(
970
-				[
971
-					'status' => 'error',
972
-					'data' => [
973
-						'message' => (string)$this->l10n->t('Forbidden')
974
-					]
975
-				],
976
-				Http::STATUS_FORBIDDEN
977
-			);
978
-		}
979
-
980
-		if ($mailAddress !== '' && !$this->mailer->validateMailAddress($mailAddress)) {
981
-			return new DataResponse(
982
-				[
983
-					'status' => 'error',
984
-					'data' => [
985
-						'message' => (string)$this->l10n->t('Invalid mail address')
986
-					]
987
-				],
988
-				Http::STATUS_UNPROCESSABLE_ENTITY
989
-			);
990
-		}
991
-
992
-		if (!$user) {
993
-			return new DataResponse(
994
-				[
995
-					'status' => 'error',
996
-					'data' => [
997
-						'message' => (string)$this->l10n->t('Invalid user')
998
-					]
999
-				],
1000
-				Http::STATUS_UNPROCESSABLE_ENTITY
1001
-			);
1002
-		}
1003
-		// this is the only permission a backend provides and is also used
1004
-		// for the permission of setting a email address
1005
-		if (!$user->canChangeDisplayName()) {
1006
-			return new DataResponse(
1007
-				[
1008
-					'status' => 'error',
1009
-					'data' => [
1010
-						'message' => (string)$this->l10n->t('Unable to change mail address')
1011
-					]
1012
-				],
1013
-				Http::STATUS_FORBIDDEN
1014
-			);
1015
-		}
1016
-
1017
-		$userData = $this->accountManager->getUser($user);
1018
-		$userData[AccountManager::PROPERTY_EMAIL]['value'] = $mailAddress;
1019
-
1020
-		try {
1021
-			$this->saveUserSettings($user, $userData);
1022
-			return new DataResponse(
1023
-				[
1024
-					'status' => 'success',
1025
-					'data' => [
1026
-						'username' => $id,
1027
-						'mailAddress' => $mailAddress,
1028
-						'message' => (string)$this->l10n->t('Email saved')
1029
-					]
1030
-				],
1031
-				Http::STATUS_OK
1032
-			);
1033
-		} catch (ForbiddenException $e) {
1034
-			return new DataResponse([
1035
-				'status' => 'error',
1036
-				'data' => [
1037
-					'message' => $e->getMessage()
1038
-				],
1039
-			]);
1040
-		}
1041
-	}
71
+    /** @var IL10N */
72
+    private $l10n;
73
+    /** @var IUserSession */
74
+    private $userSession;
75
+    /** @var bool */
76
+    private $isAdmin;
77
+    /** @var IUserManager */
78
+    private $userManager;
79
+    /** @var IGroupManager */
80
+    private $groupManager;
81
+    /** @var IConfig */
82
+    private $config;
83
+    /** @var ILogger */
84
+    private $log;
85
+    /** @var IMailer */
86
+    private $mailer;
87
+    /** @var bool contains the state of the encryption app */
88
+    private $isEncryptionAppEnabled;
89
+    /** @var bool contains the state of the admin recovery setting */
90
+    private $isRestoreEnabled = false;
91
+    /** @var IAppManager */
92
+    private $appManager;
93
+    /** @var IAvatarManager */
94
+    private $avatarManager;
95
+    /** @var AccountManager */
96
+    private $accountManager;
97
+    /** @var ISecureRandom */
98
+    private $secureRandom;
99
+    /** @var NewUserMailHelper */
100
+    private $newUserMailHelper;
101
+    /** @var Manager */
102
+    private $keyManager;
103
+    /** @var IJobList */
104
+    private $jobList;
105
+
106
+    /** @var IUserMountCache */
107
+    private $userMountCache;
108
+
109
+    /** @var IManager */
110
+    private $encryptionManager;
111
+
112
+
113
+    /**
114
+     * @param string $appName
115
+     * @param IRequest $request
116
+     * @param IUserManager $userManager
117
+     * @param IGroupManager $groupManager
118
+     * @param IUserSession $userSession
119
+     * @param IConfig $config
120
+     * @param bool $isAdmin
121
+     * @param IL10N $l10n
122
+     * @param ILogger $log
123
+     * @param IMailer $mailer
124
+     * @param IURLGenerator $urlGenerator
125
+     * @param IAppManager $appManager
126
+     * @param IAvatarManager $avatarManager
127
+     * @param AccountManager $accountManager
128
+     * @param ISecureRandom $secureRandom
129
+     * @param NewUserMailHelper $newUserMailHelper
130
+     * @param Manager $keyManager
131
+     * @param IJobList $jobList
132
+     * @param IUserMountCache $userMountCache
133
+     * @param IManager $encryptionManager
134
+     */
135
+    public function __construct($appName,
136
+                                IRequest $request,
137
+                                IUserManager $userManager,
138
+                                IGroupManager $groupManager,
139
+                                IUserSession $userSession,
140
+                                IConfig $config,
141
+                                $isAdmin,
142
+                                IL10N $l10n,
143
+                                ILogger $log,
144
+                                IMailer $mailer,
145
+                                IURLGenerator $urlGenerator,
146
+                                IAppManager $appManager,
147
+                                IAvatarManager $avatarManager,
148
+                                AccountManager $accountManager,
149
+                                ISecureRandom $secureRandom,
150
+                                NewUserMailHelper $newUserMailHelper,
151
+                                Manager $keyManager,
152
+                                IJobList $jobList,
153
+                                IUserMountCache $userMountCache,
154
+                                IManager $encryptionManager) {
155
+        parent::__construct($appName, $request);
156
+        $this->userManager = $userManager;
157
+        $this->groupManager = $groupManager;
158
+        $this->userSession = $userSession;
159
+        $this->config = $config;
160
+        $this->isAdmin = $isAdmin;
161
+        $this->l10n = $l10n;
162
+        $this->log = $log;
163
+        $this->mailer = $mailer;
164
+        $this->appManager = $appManager;
165
+        $this->avatarManager = $avatarManager;
166
+        $this->accountManager = $accountManager;
167
+        $this->secureRandom = $secureRandom;
168
+        $this->newUserMailHelper = $newUserMailHelper;
169
+        $this->keyManager = $keyManager;
170
+        $this->jobList = $jobList;
171
+        $this->userMountCache = $userMountCache;
172
+        $this->encryptionManager = $encryptionManager;
173
+
174
+        // check for encryption state - TODO see formatUserForIndex
175
+        $this->isEncryptionAppEnabled = $appManager->isEnabledForUser('encryption');
176
+        if ($this->isEncryptionAppEnabled) {
177
+            // putting this directly in empty is possible in PHP 5.5+
178
+            $result = $config->getAppValue('encryption', 'recoveryAdminEnabled', '0');
179
+            $this->isRestoreEnabled = !empty($result);
180
+        }
181
+    }
182
+
183
+    /**
184
+     * @param IUser $user
185
+     * @param array|null $userGroups
186
+     * @return array
187
+     */
188
+    private function formatUserForIndex(IUser $user, array $userGroups = null) {
189
+
190
+        // TODO: eliminate this encryption specific code below and somehow
191
+        // hook in additional user info from other apps
192
+
193
+        // recovery isn't possible if admin or user has it disabled and encryption
194
+        // is enabled - so we eliminate the else paths in the conditional tree
195
+        // below
196
+        $restorePossible = false;
197
+
198
+        if ($this->isEncryptionAppEnabled) {
199
+            if ($this->isRestoreEnabled) {
200
+                // check for the users recovery setting
201
+                $recoveryMode = $this->config->getUserValue($user->getUID(), 'encryption', 'recoveryEnabled', '0');
202
+                // method call inside empty is possible with PHP 5.5+
203
+                $recoveryModeEnabled = !empty($recoveryMode);
204
+                if ($recoveryModeEnabled) {
205
+                    // user also has recovery mode enabled
206
+                    $restorePossible = true;
207
+                }
208
+            } else {
209
+                $modules = $this->encryptionManager->getEncryptionModules();
210
+                $restorePossible = true;
211
+                foreach ($modules as $id => $module) {
212
+                    /* @var IEncryptionModule $instance */
213
+                    $instance = call_user_func($module['callback']);
214
+                    if ($instance->needDetailedAccessList()) {
215
+                        $restorePossible = false;
216
+                        break;
217
+                    }
218
+                }
219
+            }
220
+        } else {
221
+            // recovery is possible if encryption is disabled (plain files are
222
+            // available)
223
+            $restorePossible = true;
224
+        }
225
+
226
+        $subAdminGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($user);
227
+        foreach ($subAdminGroups as $key => $subAdminGroup) {
228
+            $subAdminGroups[$key] = $subAdminGroup->getGID();
229
+        }
230
+
231
+        $displayName = $user->getEMailAddress();
232
+        if (is_null($displayName)) {
233
+            $displayName = '';
234
+        }
235
+
236
+        $avatarAvailable = false;
237
+        try {
238
+            $avatarAvailable = $this->avatarManager->getAvatar($user->getUID())->exists();
239
+        } catch (\Exception $e) {
240
+            //No avatar yet
241
+        }
242
+
243
+        return [
244
+            'name' => $user->getUID(),
245
+            'displayname' => $user->getDisplayName(),
246
+            'groups' => empty($userGroups) ? $this->groupManager->getUserGroupIds($user) : $userGroups,
247
+            'subadmin' => $subAdminGroups,
248
+            'quota' => $user->getQuota(),
249
+            'quota_bytes' => Util::computerFileSize($user->getQuota()),
250
+            'storageLocation' => $user->getHome(),
251
+            'lastLogin' => $user->getLastLogin() * 1000,
252
+            'backend' => $user->getBackendClassName(),
253
+            'email' => $displayName,
254
+            'isRestoreDisabled' => !$restorePossible,
255
+            'isAvatarAvailable' => $avatarAvailable,
256
+            'isEnabled' => $user->isEnabled(),
257
+        ];
258
+    }
259
+
260
+    /**
261
+     * @param array $userIDs Array with schema [$uid => $displayName]
262
+     * @return IUser[]
263
+     */
264
+    private function getUsersForUID(array $userIDs) {
265
+        $users = [];
266
+        foreach ($userIDs as $uid => $displayName) {
267
+            $users[$uid] = $this->userManager->get($uid);
268
+        }
269
+        return $users;
270
+    }
271
+
272
+    /**
273
+     * @NoAdminRequired
274
+     *
275
+     * @param int $offset
276
+     * @param int $limit
277
+     * @param string $gid GID to filter for
278
+     * @param string $pattern Pattern to search for in the username
279
+     * @param string $backend Backend to filter for (class-name)
280
+     * @return DataResponse
281
+     *
282
+     * TODO: Tidy up and write unit tests - code is mainly static method calls
283
+     */
284
+    public function index($offset = 0, $limit = 10, $gid = '', $pattern = '', $backend = '') {
285
+        // Remove backends
286
+        if (!empty($backend)) {
287
+            $activeBackends = $this->userManager->getBackends();
288
+            $this->userManager->clearBackends();
289
+            foreach ($activeBackends as $singleActiveBackend) {
290
+                if ($backend === get_class($singleActiveBackend)) {
291
+                    $this->userManager->registerBackend($singleActiveBackend);
292
+                    break;
293
+                }
294
+            }
295
+        }
296
+
297
+        $userObjects = [];
298
+        $users = [];
299
+        if ($this->isAdmin) {
300
+            if ($gid !== '' && $gid !== '_disabledUsers' && $gid !== '_everyone') {
301
+                $batch = $this->getUsersForUID($this->groupManager->displayNamesInGroup($gid, $pattern, $limit, $offset));
302
+            } else {
303
+                $batch = $this->userManager->search($pattern, $limit, $offset);
304
+            }
305
+
306
+            foreach ($batch as $user) {
307
+                if (($gid !== '_disabledUsers' && $user->isEnabled()) ||
308
+                    ($gid === '_disabledUsers' && !$user->isEnabled())
309
+                ) {
310
+                    $userObjects[] = $user;
311
+                    $users[] = $this->formatUserForIndex($user);
312
+                }
313
+            }
314
+
315
+        } else {
316
+            $subAdminOfGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($this->userSession->getUser());
317
+            // New class returns IGroup[] so convert back
318
+            $gids = [];
319
+            foreach ($subAdminOfGroups as $group) {
320
+                $gids[] = $group->getGID();
321
+            }
322
+            $subAdminOfGroups = $gids;
323
+
324
+            // Set the $gid parameter to an empty value if the subadmin has no rights to access a specific group
325
+            if ($gid !== '' && $gid !== '_disabledUsers' && !in_array($gid, $subAdminOfGroups)) {
326
+                $gid = '';
327
+            }
328
+
329
+            // Batch all groups the user is subadmin of when a group is specified
330
+            $batch = [];
331
+            if ($gid !== '' && $gid !== '_disabledUsers' && $gid !== '_everyone') {
332
+                $batch = $this->groupManager->displayNamesInGroup($gid, $pattern, $limit, $offset);
333
+            } else {
334
+                foreach ($subAdminOfGroups as $group) {
335
+                    $groupUsers = $this->groupManager->displayNamesInGroup($group, $pattern, $limit, $offset);
336
+
337
+                    foreach ($groupUsers as $uid => $displayName) {
338
+                        $batch[$uid] = $displayName;
339
+                    }
340
+                }
341
+            }
342
+            $batch = $this->getUsersForUID($batch);
343
+
344
+            foreach ($batch as $user) {
345
+                // Only add the groups, this user is a subadmin of
346
+                $userGroups = array_values(array_intersect(
347
+                    $this->groupManager->getUserGroupIds($user),
348
+                    $subAdminOfGroups
349
+                ));
350
+                if (($gid !== '_disabledUsers' && $user->isEnabled()) ||
351
+                    ($gid === '_disabledUsers' && !$user->isEnabled())
352
+                ) {
353
+                    $userObjects[] = $user;
354
+                    $users[] = $this->formatUserForIndex($user, $userGroups);
355
+                }
356
+            }
357
+        }
358
+
359
+        $usedSpace = $this->userMountCache->getUsedSpaceForUsers($userObjects);
360
+
361
+        foreach ($users as &$userData) {
362
+            $userData['size'] = isset($usedSpace[$userData['name']]) ? $usedSpace[$userData['name']] : 0;
363
+        }
364
+
365
+        return new DataResponse($users);
366
+    }
367
+
368
+    /**
369
+     * @NoAdminRequired
370
+     * @PasswordConfirmationRequired
371
+     *
372
+     * @param string $username
373
+     * @param string $password
374
+     * @param array $groups
375
+     * @param string $email
376
+     * @return DataResponse
377
+     */
378
+    public function create($username, $password, array $groups = [], $email = '') {
379
+        if ($email !== '' && !$this->mailer->validateMailAddress($email)) {
380
+            return new DataResponse(
381
+                [
382
+                    'message' => (string)$this->l10n->t('Invalid mail address')
383
+                ],
384
+                Http::STATUS_UNPROCESSABLE_ENTITY
385
+            );
386
+        }
387
+
388
+        $currentUser = $this->userSession->getUser();
389
+
390
+        if (!$this->isAdmin) {
391
+            if (!empty($groups)) {
392
+                foreach ($groups as $key => $group) {
393
+                    $groupObject = $this->groupManager->get($group);
394
+                    if ($groupObject === null) {
395
+                        unset($groups[$key]);
396
+                        continue;
397
+                    }
398
+
399
+                    if (!$this->groupManager->getSubAdmin()->isSubAdminofGroup($currentUser, $groupObject)) {
400
+                        unset($groups[$key]);
401
+                    }
402
+                }
403
+            }
404
+
405
+            if (empty($groups)) {
406
+                return new DataResponse(
407
+                    [
408
+                        'message' => $this->l10n->t('No valid group selected'),
409
+                    ],
410
+                    Http::STATUS_FORBIDDEN
411
+                );
412
+            }
413
+        }
414
+
415
+        if ($this->userManager->userExists($username)) {
416
+            return new DataResponse(
417
+                [
418
+                    'message' => (string)$this->l10n->t('A user with that name already exists.')
419
+                ],
420
+                Http::STATUS_CONFLICT
421
+            );
422
+        }
423
+
424
+        $generatePasswordResetToken = false;
425
+        if ($password === '') {
426
+            if ($email === '') {
427
+                return new DataResponse(
428
+                    [
429
+                        'message' => (string)$this->l10n->t('To send a password link to the user an email address is required.')
430
+                    ],
431
+                    Http::STATUS_UNPROCESSABLE_ENTITY
432
+                );
433
+            }
434
+
435
+            $password = $this->secureRandom->generate(30);
436
+            // Make sure we pass the password_policy
437
+            $password .= $this->secureRandom->generate(2, '$!.,;:-~+*[]{}()');
438
+            $generatePasswordResetToken = true;
439
+        }
440
+
441
+        try {
442
+            $user = $this->userManager->createUser($username, $password);
443
+        } catch (\Exception $exception) {
444
+            $message = $exception->getMessage();
445
+            if ($exception instanceof HintException && $exception->getHint()) {
446
+                $message = $exception->getHint();
447
+            }
448
+            if (!$message) {
449
+                $message = $this->l10n->t('Unable to create user.');
450
+            }
451
+            return new DataResponse(
452
+                [
453
+                    'message' => (string)$message,
454
+                ],
455
+                Http::STATUS_FORBIDDEN
456
+            );
457
+        }
458
+
459
+        if ($user instanceof IUser) {
460
+            if ($groups !== null) {
461
+                foreach ($groups as $groupName) {
462
+                    $group = $this->groupManager->get($groupName);
463
+
464
+                    if (empty($group)) {
465
+                        $group = $this->groupManager->createGroup($groupName);
466
+                    }
467
+                    $group->addUser($user);
468
+                }
469
+            }
470
+            /**
471
+             * Send new user mail only if a mail is set
472
+             */
473
+            if ($email !== '') {
474
+                $user->setEMailAddress($email);
475
+                try {
476
+                    $emailTemplate = $this->newUserMailHelper->generateTemplate($user, $generatePasswordResetToken);
477
+                    $this->newUserMailHelper->sendMail($user, $emailTemplate);
478
+                } catch (\Exception $e) {
479
+                    $this->log->logException($e, [
480
+                        'message' => "Can't send new user mail to $email",
481
+                        'level' => \OCP\Util::ERROR,
482
+                        'app' => 'settings',
483
+                    ]);
484
+                }
485
+            }
486
+            // fetch users groups
487
+            $userGroups = $this->groupManager->getUserGroupIds($user);
488
+
489
+            return new DataResponse(
490
+                $this->formatUserForIndex($user, $userGroups),
491
+                Http::STATUS_CREATED
492
+            );
493
+        }
494
+
495
+        return new DataResponse(
496
+            [
497
+                'message' => (string)$this->l10n->t('Unable to create user.')
498
+            ],
499
+            Http::STATUS_FORBIDDEN
500
+        );
501
+
502
+    }
503
+
504
+    /**
505
+     * @NoAdminRequired
506
+     * @PasswordConfirmationRequired
507
+     *
508
+     * @param string $id
509
+     * @return DataResponse
510
+     */
511
+    public function destroy($id) {
512
+        $userId = $this->userSession->getUser()->getUID();
513
+        $user = $this->userManager->get($id);
514
+
515
+        if ($userId === $id) {
516
+            return new DataResponse(
517
+                [
518
+                    'status' => 'error',
519
+                    'data' => [
520
+                        'message' => (string)$this->l10n->t('Unable to delete user.')
521
+                    ]
522
+                ],
523
+                Http::STATUS_FORBIDDEN
524
+            );
525
+        }
526
+
527
+        if (!$this->isAdmin && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)) {
528
+            return new DataResponse(
529
+                [
530
+                    'status' => 'error',
531
+                    'data' => [
532
+                        'message' => (string)$this->l10n->t('Authentication error')
533
+                    ]
534
+                ],
535
+                Http::STATUS_FORBIDDEN
536
+            );
537
+        }
538
+
539
+        if ($user) {
540
+            if ($user->delete()) {
541
+                return new DataResponse(
542
+                    [
543
+                        'status' => 'success',
544
+                        'data' => [
545
+                            'username' => $id
546
+                        ]
547
+                    ],
548
+                    Http::STATUS_NO_CONTENT
549
+                );
550
+            }
551
+        }
552
+
553
+        return new DataResponse(
554
+            [
555
+                'status' => 'error',
556
+                'data' => [
557
+                    'message' => (string)$this->l10n->t('Unable to delete user.')
558
+                ]
559
+            ],
560
+            Http::STATUS_FORBIDDEN
561
+        );
562
+    }
563
+
564
+    /**
565
+     * @NoAdminRequired
566
+     *
567
+     * @param string $id
568
+     * @param int $enabled
569
+     * @return DataResponse
570
+     */
571
+    public function setEnabled($id, $enabled) {
572
+        $enabled = (bool)$enabled;
573
+        if ($enabled) {
574
+            $errorMsgGeneral = (string)$this->l10n->t('Error while enabling user.');
575
+        } else {
576
+            $errorMsgGeneral = (string)$this->l10n->t('Error while disabling user.');
577
+        }
578
+
579
+        $userId = $this->userSession->getUser()->getUID();
580
+        $user = $this->userManager->get($id);
581
+
582
+        if ($userId === $id) {
583
+            return new DataResponse(
584
+                [
585
+                    'status' => 'error',
586
+                    'data' => [
587
+                        'message' => $errorMsgGeneral
588
+                    ]
589
+                ], Http::STATUS_FORBIDDEN
590
+            );
591
+        }
592
+
593
+        if ($user) {
594
+            if (!$this->isAdmin && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)) {
595
+                return new DataResponse(
596
+                    [
597
+                        'status' => 'error',
598
+                        'data' => [
599
+                            'message' => (string)$this->l10n->t('Authentication error')
600
+                        ]
601
+                    ],
602
+                    Http::STATUS_FORBIDDEN
603
+                );
604
+            }
605
+
606
+            $user->setEnabled($enabled);
607
+            return new DataResponse(
608
+                [
609
+                    'status' => 'success',
610
+                    'data' => [
611
+                        'username' => $id,
612
+                        'enabled' => $enabled
613
+                    ]
614
+                ]
615
+            );
616
+        } else {
617
+            return new DataResponse(
618
+                [
619
+                    'status' => 'error',
620
+                    'data' => [
621
+                        'message' => $errorMsgGeneral
622
+                    ]
623
+                ],
624
+                Http::STATUS_FORBIDDEN
625
+            );
626
+        }
627
+
628
+    }
629
+
630
+    /**
631
+     * Set the mail address of a user
632
+     *
633
+     * @NoAdminRequired
634
+     * @NoSubadminRequired
635
+     * @PasswordConfirmationRequired
636
+     *
637
+     * @param string $account
638
+     * @param bool $onlyVerificationCode only return verification code without updating the data
639
+     * @return DataResponse
640
+     */
641
+    public function getVerificationCode($account, $onlyVerificationCode) {
642
+
643
+        $user = $this->userSession->getUser();
644
+
645
+        if ($user === null) {
646
+            return new DataResponse([], Http::STATUS_BAD_REQUEST);
647
+        }
648
+
649
+        $accountData = $this->accountManager->getUser($user);
650
+        $cloudId = $user->getCloudId();
651
+        $message = "Use my Federated Cloud ID to share with me: " . $cloudId;
652
+        $signature = $this->signMessage($user, $message);
653
+
654
+        $code = $message . ' ' . $signature;
655
+        $codeMd5 = $message . ' ' . md5($signature);
656
+
657
+        switch ($account) {
658
+            case 'verify-twitter':
659
+                $accountData[AccountManager::PROPERTY_TWITTER]['verified'] = AccountManager::VERIFICATION_IN_PROGRESS;
660
+                $msg = $this->l10n->t('In order to verify your Twitter account, post the following tweet on Twitter (please make sure to post it without any line breaks):');
661
+                $code = $codeMd5;
662
+                $type = AccountManager::PROPERTY_TWITTER;
663
+                $data = $accountData[AccountManager::PROPERTY_TWITTER]['value'];
664
+                $accountData[AccountManager::PROPERTY_TWITTER]['signature'] = $signature;
665
+                break;
666
+            case 'verify-website':
667
+                $accountData[AccountManager::PROPERTY_WEBSITE]['verified'] = AccountManager::VERIFICATION_IN_PROGRESS;
668
+                $msg = $this->l10n->t('In order to verify your Website, store the following content in your web-root at \'.well-known/CloudIdVerificationCode.txt\' (please make sure that the complete text is in one line):');
669
+                $type = AccountManager::PROPERTY_WEBSITE;
670
+                $data = $accountData[AccountManager::PROPERTY_WEBSITE]['value'];
671
+                $accountData[AccountManager::PROPERTY_WEBSITE]['signature'] = $signature;
672
+                break;
673
+            default:
674
+                return new DataResponse([], Http::STATUS_BAD_REQUEST);
675
+        }
676
+
677
+        if ($onlyVerificationCode === false) {
678
+            $this->accountManager->updateUser($user, $accountData);
679
+
680
+            $this->jobList->add(VerifyUserData::class,
681
+                [
682
+                    'verificationCode' => $code,
683
+                    'data' => $data,
684
+                    'type' => $type,
685
+                    'uid' => $user->getUID(),
686
+                    'try' => 0,
687
+                    'lastRun' => $this->getCurrentTime()
688
+                ]
689
+            );
690
+        }
691
+
692
+        return new DataResponse(['msg' => $msg, 'code' => $code]);
693
+    }
694
+
695
+    /**
696
+     * get current timestamp
697
+     *
698
+     * @return int
699
+     */
700
+    protected function getCurrentTime() {
701
+        return time();
702
+    }
703
+
704
+    /**
705
+     * sign message with users private key
706
+     *
707
+     * @param IUser $user
708
+     * @param string $message
709
+     *
710
+     * @return string base64 encoded signature
711
+     */
712
+    protected function signMessage(IUser $user, $message) {
713
+        $privateKey = $this->keyManager->getKey($user)->getPrivate();
714
+        openssl_sign(json_encode($message), $signature, $privateKey, OPENSSL_ALGO_SHA512);
715
+        return base64_encode($signature);
716
+    }
717
+
718
+    /**
719
+     * @NoAdminRequired
720
+     * @NoSubadminRequired
721
+     * @PasswordConfirmationRequired
722
+     *
723
+     * @param string $avatarScope
724
+     * @param string $displayname
725
+     * @param string $displaynameScope
726
+     * @param string $phone
727
+     * @param string $phoneScope
728
+     * @param string $email
729
+     * @param string $emailScope
730
+     * @param string $website
731
+     * @param string $websiteScope
732
+     * @param string $address
733
+     * @param string $addressScope
734
+     * @param string $twitter
735
+     * @param string $twitterScope
736
+     * @return DataResponse
737
+     */
738
+    public function setUserSettings($avatarScope,
739
+                                    $displayname,
740
+                                    $displaynameScope,
741
+                                    $phone,
742
+                                    $phoneScope,
743
+                                    $email,
744
+                                    $emailScope,
745
+                                    $website,
746
+                                    $websiteScope,
747
+                                    $address,
748
+                                    $addressScope,
749
+                                    $twitter,
750
+                                    $twitterScope
751
+    ) {
752
+
753
+        if (!empty($email) && !$this->mailer->validateMailAddress($email)) {
754
+            return new DataResponse(
755
+                [
756
+                    'status' => 'error',
757
+                    'data' => [
758
+                        'message' => (string)$this->l10n->t('Invalid mail address')
759
+                    ]
760
+                ],
761
+                Http::STATUS_UNPROCESSABLE_ENTITY
762
+            );
763
+        }
764
+
765
+        $user = $this->userSession->getUser();
766
+
767
+        $data = $this->accountManager->getUser($user);
768
+
769
+        $data[AccountManager::PROPERTY_AVATAR] = ['scope' => $avatarScope];
770
+        if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
771
+            $data[AccountManager::PROPERTY_DISPLAYNAME] = ['value' => $displayname, 'scope' => $displaynameScope];
772
+            $data[AccountManager::PROPERTY_EMAIL] = ['value' => $email, 'scope' => $emailScope];
773
+        }
774
+
775
+        if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
776
+            $federatedFileSharing = new \OCA\FederatedFileSharing\AppInfo\Application();
777
+            $shareProvider = $federatedFileSharing->getFederatedShareProvider();
778
+            if ($shareProvider->isLookupServerUploadEnabled()) {
779
+                $data[AccountManager::PROPERTY_WEBSITE] = ['value' => $website, 'scope' => $websiteScope];
780
+                $data[AccountManager::PROPERTY_ADDRESS] = ['value' => $address, 'scope' => $addressScope];
781
+                $data[AccountManager::PROPERTY_PHONE] = ['value' => $phone, 'scope' => $phoneScope];
782
+                $data[AccountManager::PROPERTY_TWITTER] = ['value' => $twitter, 'scope' => $twitterScope];
783
+            }
784
+        }
785
+
786
+        try {
787
+            $this->saveUserSettings($user, $data);
788
+            return new DataResponse(
789
+                [
790
+                    'status' => 'success',
791
+                    'data' => [
792
+                        'userId' => $user->getUID(),
793
+                        'avatarScope' => $data[AccountManager::PROPERTY_AVATAR]['scope'],
794
+                        'displayname' => $data[AccountManager::PROPERTY_DISPLAYNAME]['value'],
795
+                        'displaynameScope' => $data[AccountManager::PROPERTY_DISPLAYNAME]['scope'],
796
+                        'email' => $data[AccountManager::PROPERTY_EMAIL]['value'],
797
+                        'emailScope' => $data[AccountManager::PROPERTY_EMAIL]['scope'],
798
+                        'website' => $data[AccountManager::PROPERTY_WEBSITE]['value'],
799
+                        'websiteScope' => $data[AccountManager::PROPERTY_WEBSITE]['scope'],
800
+                        'address' => $data[AccountManager::PROPERTY_ADDRESS]['value'],
801
+                        'addressScope' => $data[AccountManager::PROPERTY_ADDRESS]['scope'],
802
+                        'message' => (string)$this->l10n->t('Settings saved')
803
+                    ]
804
+                ],
805
+                Http::STATUS_OK
806
+            );
807
+        } catch (ForbiddenException $e) {
808
+            return new DataResponse([
809
+                'status' => 'error',
810
+                'data' => [
811
+                    'message' => $e->getMessage()
812
+                ],
813
+            ]);
814
+        }
815
+
816
+    }
817
+
818
+
819
+    /**
820
+     * update account manager with new user data
821
+     *
822
+     * @param IUser $user
823
+     * @param array $data
824
+     * @throws ForbiddenException
825
+     */
826
+    protected function saveUserSettings(IUser $user, $data) {
827
+
828
+        // keep the user back-end up-to-date with the latest display name and email
829
+        // address
830
+        $oldDisplayName = $user->getDisplayName();
831
+        $oldDisplayName = is_null($oldDisplayName) ? '' : $oldDisplayName;
832
+        if (isset($data[AccountManager::PROPERTY_DISPLAYNAME]['value'])
833
+            && $oldDisplayName !== $data[AccountManager::PROPERTY_DISPLAYNAME]['value']
834
+        ) {
835
+            $result = $user->setDisplayName($data[AccountManager::PROPERTY_DISPLAYNAME]['value']);
836
+            if ($result === false) {
837
+                throw new ForbiddenException($this->l10n->t('Unable to change full name'));
838
+            }
839
+        }
840
+
841
+        $oldEmailAddress = $user->getEMailAddress();
842
+        $oldEmailAddress = is_null($oldEmailAddress) ? '' : $oldEmailAddress;
843
+        if (isset($data[AccountManager::PROPERTY_EMAIL]['value'])
844
+            && $oldEmailAddress !== $data[AccountManager::PROPERTY_EMAIL]['value']
845
+        ) {
846
+            // this is the only permission a backend provides and is also used
847
+            // for the permission of setting a email address
848
+            if (!$user->canChangeDisplayName()) {
849
+                throw new ForbiddenException($this->l10n->t('Unable to change email address'));
850
+            }
851
+            $user->setEMailAddress($data[AccountManager::PROPERTY_EMAIL]['value']);
852
+        }
853
+
854
+        $this->accountManager->updateUser($user, $data);
855
+    }
856
+
857
+    /**
858
+     * Count all unique users visible for the current admin/subadmin.
859
+     *
860
+     * @NoAdminRequired
861
+     *
862
+     * @return DataResponse
863
+     */
864
+    public function stats() {
865
+        $userCount = 0;
866
+        if ($this->isAdmin) {
867
+            $countByBackend = $this->userManager->countUsers();
868
+
869
+            if (!empty($countByBackend)) {
870
+                foreach ($countByBackend as $count) {
871
+                    $userCount += $count;
872
+                }
873
+            }
874
+        } else {
875
+            $groups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($this->userSession->getUser());
876
+
877
+            $uniqueUsers = [];
878
+            foreach ($groups as $group) {
879
+                foreach ($group->getUsers() as $uid => $displayName) {
880
+                    $uniqueUsers[$uid] = true;
881
+                }
882
+            }
883
+
884
+            $userCount = count($uniqueUsers);
885
+        }
886
+
887
+        return new DataResponse(
888
+            [
889
+                'totalUsers' => $userCount
890
+            ]
891
+        );
892
+    }
893
+
894
+
895
+    /**
896
+     * Set the displayName of a user
897
+     *
898
+     * @NoAdminRequired
899
+     * @NoSubadminRequired
900
+     * @PasswordConfirmationRequired
901
+     * @todo merge into saveUserSettings
902
+     *
903
+     * @param string $username
904
+     * @param string $displayName
905
+     * @return DataResponse
906
+     */
907
+    public function setDisplayName($username, $displayName) {
908
+        $currentUser = $this->userSession->getUser();
909
+        $user = $this->userManager->get($username);
910
+
911
+        if ($user === null ||
912
+            !$user->canChangeDisplayName() ||
913
+            (
914
+                !$this->groupManager->isAdmin($currentUser->getUID()) &&
915
+                !$this->groupManager->getSubAdmin()->isUserAccessible($currentUser, $user) &&
916
+                $currentUser->getUID() !== $username
917
+
918
+            )
919
+        ) {
920
+            return new DataResponse([
921
+                'status' => 'error',
922
+                'data' => [
923
+                    'message' => $this->l10n->t('Authentication error'),
924
+                ],
925
+            ]);
926
+        }
927
+
928
+        $userData = $this->accountManager->getUser($user);
929
+        $userData[AccountManager::PROPERTY_DISPLAYNAME]['value'] = $displayName;
930
+
931
+
932
+        try {
933
+            $this->saveUserSettings($user, $userData);
934
+            return new DataResponse([
935
+                'status' => 'success',
936
+                'data' => [
937
+                    'message' => $this->l10n->t('Your full name has been changed.'),
938
+                    'username' => $username,
939
+                    'displayName' => $displayName,
940
+                ],
941
+            ]);
942
+        } catch (ForbiddenException $e) {
943
+            return new DataResponse([
944
+                'status' => 'error',
945
+                'data' => [
946
+                    'message' => $e->getMessage(),
947
+                    'displayName' => $user->getDisplayName(),
948
+                ],
949
+            ]);
950
+        }
951
+    }
952
+
953
+    /**
954
+     * Set the mail address of a user
955
+     *
956
+     * @NoAdminRequired
957
+     * @NoSubadminRequired
958
+     * @PasswordConfirmationRequired
959
+     *
960
+     * @param string $id
961
+     * @param string $mailAddress
962
+     * @return DataResponse
963
+     */
964
+    public function setEMailAddress($id, $mailAddress) {
965
+        $user = $this->userManager->get($id);
966
+        if (!$this->isAdmin
967
+            && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)
968
+        ) {
969
+            return new DataResponse(
970
+                [
971
+                    'status' => 'error',
972
+                    'data' => [
973
+                        'message' => (string)$this->l10n->t('Forbidden')
974
+                    ]
975
+                ],
976
+                Http::STATUS_FORBIDDEN
977
+            );
978
+        }
979
+
980
+        if ($mailAddress !== '' && !$this->mailer->validateMailAddress($mailAddress)) {
981
+            return new DataResponse(
982
+                [
983
+                    'status' => 'error',
984
+                    'data' => [
985
+                        'message' => (string)$this->l10n->t('Invalid mail address')
986
+                    ]
987
+                ],
988
+                Http::STATUS_UNPROCESSABLE_ENTITY
989
+            );
990
+        }
991
+
992
+        if (!$user) {
993
+            return new DataResponse(
994
+                [
995
+                    'status' => 'error',
996
+                    'data' => [
997
+                        'message' => (string)$this->l10n->t('Invalid user')
998
+                    ]
999
+                ],
1000
+                Http::STATUS_UNPROCESSABLE_ENTITY
1001
+            );
1002
+        }
1003
+        // this is the only permission a backend provides and is also used
1004
+        // for the permission of setting a email address
1005
+        if (!$user->canChangeDisplayName()) {
1006
+            return new DataResponse(
1007
+                [
1008
+                    'status' => 'error',
1009
+                    'data' => [
1010
+                        'message' => (string)$this->l10n->t('Unable to change mail address')
1011
+                    ]
1012
+                ],
1013
+                Http::STATUS_FORBIDDEN
1014
+            );
1015
+        }
1016
+
1017
+        $userData = $this->accountManager->getUser($user);
1018
+        $userData[AccountManager::PROPERTY_EMAIL]['value'] = $mailAddress;
1019
+
1020
+        try {
1021
+            $this->saveUserSettings($user, $userData);
1022
+            return new DataResponse(
1023
+                [
1024
+                    'status' => 'success',
1025
+                    'data' => [
1026
+                        'username' => $id,
1027
+                        'mailAddress' => $mailAddress,
1028
+                        'message' => (string)$this->l10n->t('Email saved')
1029
+                    ]
1030
+                ],
1031
+                Http::STATUS_OK
1032
+            );
1033
+        } catch (ForbiddenException $e) {
1034
+            return new DataResponse([
1035
+                'status' => 'error',
1036
+                'data' => [
1037
+                    'message' => $e->getMessage()
1038
+                ],
1039
+            ]);
1040
+        }
1041
+    }
1042 1042
 
1043 1043
 }
Please login to merge, or discard this patch.