Completed
Pull Request — master (#4330)
by Morris
12:38
created
lib/private/ServerContainer.php 1 patch
Indentation   +72 added lines, -72 removed lines patch added patch discarded remove patch
@@ -34,85 +34,85 @@
 block discarded – undo
34 34
  * @package OC
35 35
  */
36 36
 class ServerContainer extends SimpleContainer {
37
-	/** @var DIContainer[] */
38
-	protected $appContainers;
37
+    /** @var DIContainer[] */
38
+    protected $appContainers;
39 39
 
40
-	/** @var string[] */
41
-	protected $namespaces;
40
+    /** @var string[] */
41
+    protected $namespaces;
42 42
 
43
-	/**
44
-	 * ServerContainer constructor.
45
-	 */
46
-	public function __construct() {
47
-		parent::__construct();
48
-		$this->appContainers = [];
49
-		$this->namespaces = [];
50
-	}
43
+    /**
44
+     * ServerContainer constructor.
45
+     */
46
+    public function __construct() {
47
+        parent::__construct();
48
+        $this->appContainers = [];
49
+        $this->namespaces = [];
50
+    }
51 51
 
52
-	/**
53
-	 * @param string $appName
54
-	 * @param string $appNamespace
55
-	 */
56
-	public function registerNamespace($appName, $appNamespace) {
57
-		// Cut of OCA\ and lowercase
58
-		$appNamespace = strtolower(substr($appNamespace, strrpos($appNamespace, '\\') + 1));
59
-		$this->namespaces[$appNamespace] = $appName;
60
-	}
52
+    /**
53
+     * @param string $appName
54
+     * @param string $appNamespace
55
+     */
56
+    public function registerNamespace($appName, $appNamespace) {
57
+        // Cut of OCA\ and lowercase
58
+        $appNamespace = strtolower(substr($appNamespace, strrpos($appNamespace, '\\') + 1));
59
+        $this->namespaces[$appNamespace] = $appName;
60
+    }
61 61
 
62
-	/**
63
-	 * @param string $appName
64
-	 * @param DIContainer $container
65
-	 */
66
-	public function registerAppContainer($appName, DIContainer $container) {
67
-		$this->appContainers[strtolower(App::buildAppNamespace($appName, ''))] = $container;
68
-	}
62
+    /**
63
+     * @param string $appName
64
+     * @param DIContainer $container
65
+     */
66
+    public function registerAppContainer($appName, DIContainer $container) {
67
+        $this->appContainers[strtolower(App::buildAppNamespace($appName, ''))] = $container;
68
+    }
69 69
 
70
-	/**
71
-	 * @param string $namespace
72
-	 * @return DIContainer
73
-	 * @throws QueryException
74
-	 */
75
-	protected function getAppContainer($namespace) {
76
-		if (isset($this->appContainers[$namespace])) {
77
-			return $this->appContainers[$namespace];
78
-		}
70
+    /**
71
+     * @param string $namespace
72
+     * @return DIContainer
73
+     * @throws QueryException
74
+     */
75
+    protected function getAppContainer($namespace) {
76
+        if (isset($this->appContainers[$namespace])) {
77
+            return $this->appContainers[$namespace];
78
+        }
79 79
 
80
-		if (isset($this->namespaces[$namespace])) {
81
-			return new DIContainer($this->namespaces[$namespace]);
82
-		}
83
-		throw new QueryException();
84
-	}
80
+        if (isset($this->namespaces[$namespace])) {
81
+            return new DIContainer($this->namespaces[$namespace]);
82
+        }
83
+        throw new QueryException();
84
+    }
85 85
 
86
-	/**
87
-	 * @param string $name name of the service to query for
88
-	 * @return mixed registered service for the given $name
89
-	 * @throws QueryException if the query could not be resolved
90
-	 */
91
-	public function query($name) {
92
-		$name = $this->sanitizeName($name);
86
+    /**
87
+     * @param string $name name of the service to query for
88
+     * @return mixed registered service for the given $name
89
+     * @throws QueryException if the query could not be resolved
90
+     */
91
+    public function query($name) {
92
+        $name = $this->sanitizeName($name);
93 93
 
94
-		// In case the service starts with OCA\ we try to find the service in
95
-		// the apps container first.
96
-		if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
97
-			$segments = explode('\\', $name);
98
-			try {
99
-				$appContainer = $this->getAppContainer(strtolower($segments[1]));
100
-				return $appContainer->queryNoFallback($name);
101
-			} catch (QueryException $e) {
102
-				// Didn't find the service or the respective app container,
103
-				// ignore it and fall back to the core container.
104
-			}
105
-		} else if (strpos($name, 'OC\\Settings\\') === 0 && substr_count($name, '\\') >= 3) {
106
-			$segments = explode('\\', $name);
107
-			try {
108
-				$appContainer = $this->getAppContainer(strtolower($segments[1]));
109
-				return $appContainer->queryNoFallback($name);
110
-			} catch (QueryException $e) {
111
-				// Didn't find the service or the respective app container,
112
-				// ignore it and fall back to the core container.
113
-			}
114
-		}
94
+        // In case the service starts with OCA\ we try to find the service in
95
+        // the apps container first.
96
+        if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
97
+            $segments = explode('\\', $name);
98
+            try {
99
+                $appContainer = $this->getAppContainer(strtolower($segments[1]));
100
+                return $appContainer->queryNoFallback($name);
101
+            } catch (QueryException $e) {
102
+                // Didn't find the service or the respective app container,
103
+                // ignore it and fall back to the core container.
104
+            }
105
+        } else if (strpos($name, 'OC\\Settings\\') === 0 && substr_count($name, '\\') >= 3) {
106
+            $segments = explode('\\', $name);
107
+            try {
108
+                $appContainer = $this->getAppContainer(strtolower($segments[1]));
109
+                return $appContainer->queryNoFallback($name);
110
+            } catch (QueryException $e) {
111
+                // Didn't find the service or the respective app container,
112
+                // ignore it and fall back to the core container.
113
+            }
114
+        }
115 115
 
116
-		return parent::query($name);
117
-	}
116
+        return parent::query($name);
117
+    }
118 118
 }
Please login to merge, or discard this patch.
lib/base.php 1 patch
Indentation   +991 added lines, -991 removed lines patch added patch discarded remove patch
@@ -59,997 +59,997 @@
 block discarded – undo
59 59
  * OC_autoload!
60 60
  */
61 61
 class OC {
62
-	/**
63
-	 * Associative array for autoloading. classname => filename
64
-	 */
65
-	public static $CLASSPATH = array();
66
-	/**
67
-	 * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
68
-	 */
69
-	public static $SERVERROOT = '';
70
-	/**
71
-	 * the current request path relative to the Nextcloud root (e.g. files/index.php)
72
-	 */
73
-	private static $SUBURI = '';
74
-	/**
75
-	 * the Nextcloud root path for http requests (e.g. nextcloud/)
76
-	 */
77
-	public static $WEBROOT = '';
78
-	/**
79
-	 * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
80
-	 * web path in 'url'
81
-	 */
82
-	public static $APPSROOTS = array();
83
-
84
-	/**
85
-	 * @var string
86
-	 */
87
-	public static $configDir;
88
-
89
-	/**
90
-	 * requested app
91
-	 */
92
-	public static $REQUESTEDAPP = '';
93
-
94
-	/**
95
-	 * check if Nextcloud runs in cli mode
96
-	 */
97
-	public static $CLI = false;
98
-
99
-	/**
100
-	 * @var \OC\Autoloader $loader
101
-	 */
102
-	public static $loader = null;
103
-
104
-	/** @var \Composer\Autoload\ClassLoader $composerAutoloader */
105
-	public static $composerAutoloader = null;
106
-
107
-	/**
108
-	 * @var \OC\Server
109
-	 */
110
-	public static $server = null;
111
-
112
-	/**
113
-	 * @var \OC\Config
114
-	 */
115
-	private static $config = null;
116
-
117
-	/**
118
-	 * @throws \RuntimeException when the 3rdparty directory is missing or
119
-	 * the app path list is empty or contains an invalid path
120
-	 */
121
-	public static function initPaths() {
122
-		if(defined('PHPUNIT_CONFIG_DIR')) {
123
-			self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
124
-		} elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
125
-			self::$configDir = OC::$SERVERROOT . '/tests/config/';
126
-		} elseif($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
127
-			self::$configDir = rtrim($dir, '/') . '/';
128
-		} else {
129
-			self::$configDir = OC::$SERVERROOT . '/config/';
130
-		}
131
-		self::$config = new \OC\Config(self::$configDir);
132
-
133
-		OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
134
-		/**
135
-		 * FIXME: The following lines are required because we can't yet instantiiate
136
-		 *        \OC::$server->getRequest() since \OC::$server does not yet exist.
137
-		 */
138
-		$params = [
139
-			'server' => [
140
-				'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
141
-				'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
142
-			],
143
-		];
144
-		$fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig(self::$config)));
145
-		$scriptName = $fakeRequest->getScriptName();
146
-		if (substr($scriptName, -1) == '/') {
147
-			$scriptName .= 'index.php';
148
-			//make sure suburi follows the same rules as scriptName
149
-			if (substr(OC::$SUBURI, -9) != 'index.php') {
150
-				if (substr(OC::$SUBURI, -1) != '/') {
151
-					OC::$SUBURI = OC::$SUBURI . '/';
152
-				}
153
-				OC::$SUBURI = OC::$SUBURI . 'index.php';
154
-			}
155
-		}
156
-
157
-
158
-		if (OC::$CLI) {
159
-			OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
160
-		} else {
161
-			if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
162
-				OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
163
-
164
-				if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
165
-					OC::$WEBROOT = '/' . OC::$WEBROOT;
166
-				}
167
-			} else {
168
-				// The scriptName is not ending with OC::$SUBURI
169
-				// This most likely means that we are calling from CLI.
170
-				// However some cron jobs still need to generate
171
-				// a web URL, so we use overwritewebroot as a fallback.
172
-				OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
173
-			}
174
-
175
-			// Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
176
-			// slash which is required by URL generation.
177
-			if($_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
178
-					substr($_SERVER['REQUEST_URI'], -1) !== '/') {
179
-				header('Location: '.\OC::$WEBROOT.'/');
180
-				exit();
181
-			}
182
-		}
183
-
184
-		// search the apps folder
185
-		$config_paths = self::$config->getValue('apps_paths', array());
186
-		if (!empty($config_paths)) {
187
-			foreach ($config_paths as $paths) {
188
-				if (isset($paths['url']) && isset($paths['path'])) {
189
-					$paths['url'] = rtrim($paths['url'], '/');
190
-					$paths['path'] = rtrim($paths['path'], '/');
191
-					OC::$APPSROOTS[] = $paths;
192
-				}
193
-			}
194
-		} elseif (file_exists(OC::$SERVERROOT . '/apps')) {
195
-			OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
196
-		} elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
197
-			OC::$APPSROOTS[] = array(
198
-				'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
199
-				'url' => '/apps',
200
-				'writable' => true
201
-			);
202
-		}
203
-
204
-		if (empty(OC::$APPSROOTS)) {
205
-			throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
206
-				. ' or the folder above. You can also configure the location in the config.php file.');
207
-		}
208
-		$paths = array();
209
-		foreach (OC::$APPSROOTS as $path) {
210
-			$paths[] = $path['path'];
211
-			if (!is_dir($path['path'])) {
212
-				throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
213
-					. ' Nextcloud folder or the folder above. You can also configure the location in the'
214
-					. ' config.php file.', $path['path']));
215
-			}
216
-		}
217
-
218
-		// set the right include path
219
-		set_include_path(
220
-			implode(PATH_SEPARATOR, $paths)
221
-		);
222
-	}
223
-
224
-	public static function checkConfig() {
225
-		$l = \OC::$server->getL10N('lib');
226
-
227
-		// Create config if it does not already exist
228
-		$configFilePath = self::$configDir .'/config.php';
229
-		if(!file_exists($configFilePath)) {
230
-			@touch($configFilePath);
231
-		}
232
-
233
-		// Check if config is writable
234
-		$configFileWritable = is_writable($configFilePath);
235
-		if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
236
-			|| !$configFileWritable && self::checkUpgrade(false)) {
237
-
238
-			$urlGenerator = \OC::$server->getURLGenerator();
239
-
240
-			if (self::$CLI) {
241
-				echo $l->t('Cannot write into "config" directory!')."\n";
242
-				echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
243
-				echo "\n";
244
-				echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-dir_permissions') ])."\n";
245
-				exit;
246
-			} else {
247
-				OC_Template::printErrorPage(
248
-					$l->t('Cannot write into "config" directory!'),
249
-					$l->t('This can usually be fixed by '
250
-					. '%sgiving the webserver write access to the config directory%s.',
251
-					 array('<a href="' . $urlGenerator->linkToDocs('admin-dir_permissions') . '" target="_blank" rel="noreferrer">', '</a>'))
252
-				);
253
-			}
254
-		}
255
-	}
256
-
257
-	public static function checkInstalled() {
258
-		if (defined('OC_CONSOLE')) {
259
-			return;
260
-		}
261
-		// Redirect to installer if not installed
262
-		if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
263
-			if (OC::$CLI) {
264
-				throw new Exception('Not installed');
265
-			} else {
266
-				$url = OC::$WEBROOT . '/index.php';
267
-				header('Location: ' . $url);
268
-			}
269
-			exit();
270
-		}
271
-	}
272
-
273
-	public static function checkMaintenanceMode() {
274
-		// Allow ajax update script to execute without being stopped
275
-		if (\OC::$server->getSystemConfig()->getValue('maintenance', false) && OC::$SUBURI != '/core/ajax/update.php') {
276
-			// send http status 503
277
-			header('HTTP/1.1 503 Service Temporarily Unavailable');
278
-			header('Status: 503 Service Temporarily Unavailable');
279
-			header('Retry-After: 120');
280
-
281
-			// render error page
282
-			$template = new OC_Template('', 'update.user', 'guest');
283
-			OC_Util::addScript('maintenance-check');
284
-			$template->printPage();
285
-			die();
286
-		}
287
-	}
288
-
289
-	/**
290
-	 * Checks if the version requires an update and shows
291
-	 * @param bool $showTemplate Whether an update screen should get shown
292
-	 * @return bool|void
293
-	 */
294
-	public static function checkUpgrade($showTemplate = true) {
295
-		if (\OCP\Util::needUpgrade()) {
296
-			$systemConfig = \OC::$server->getSystemConfig();
297
-			if ($showTemplate && !$systemConfig->getValue('maintenance', false)) {
298
-				self::printUpgradePage();
299
-				exit();
300
-			} else {
301
-				return true;
302
-			}
303
-		}
304
-		return false;
305
-	}
306
-
307
-	/**
308
-	 * Prints the upgrade page
309
-	 */
310
-	private static function printUpgradePage() {
311
-		$systemConfig = \OC::$server->getSystemConfig();
312
-
313
-		$disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
314
-		$tooBig = false;
315
-		if (!$disableWebUpdater) {
316
-			$apps = \OC::$server->getAppManager();
317
-			$tooBig = $apps->isInstalled('user_ldap') || $apps->isInstalled('user_shibboleth');
318
-			if (!$tooBig) {
319
-				// count users
320
-				$stats = \OC::$server->getUserManager()->countUsers();
321
-				$totalUsers = array_sum($stats);
322
-				$tooBig = ($totalUsers > 50);
323
-			}
324
-		}
325
-		if ($disableWebUpdater || $tooBig) {
326
-			// send http status 503
327
-			header('HTTP/1.1 503 Service Temporarily Unavailable');
328
-			header('Status: 503 Service Temporarily Unavailable');
329
-			header('Retry-After: 120');
330
-
331
-			// render error page
332
-			$template = new OC_Template('', 'update.use-cli', 'guest');
333
-			$template->assign('productName', 'nextcloud'); // for now
334
-			$template->assign('version', OC_Util::getVersionString());
335
-			$template->assign('tooBig', $tooBig);
336
-
337
-			$template->printPage();
338
-			die();
339
-		}
340
-
341
-		// check whether this is a core update or apps update
342
-		$installedVersion = $systemConfig->getValue('version', '0.0.0');
343
-		$currentVersion = implode('.', \OCP\Util::getVersion());
344
-
345
-		// if not a core upgrade, then it's apps upgrade
346
-		$isAppsOnlyUpgrade = (version_compare($currentVersion, $installedVersion, '='));
347
-
348
-		$oldTheme = $systemConfig->getValue('theme');
349
-		$systemConfig->setValue('theme', '');
350
-		OC_Util::addScript('config'); // needed for web root
351
-		OC_Util::addScript('update');
352
-
353
-		/** @var \OC\App\AppManager $appManager */
354
-		$appManager = \OC::$server->getAppManager();
355
-
356
-		$tmpl = new OC_Template('', 'update.admin', 'guest');
357
-		$tmpl->assign('version', OC_Util::getVersionString());
358
-		$tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
359
-
360
-		// get third party apps
361
-		$ocVersion = \OCP\Util::getVersion();
362
-		$incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
363
-		$incompatibleShippedApps = [];
364
-		foreach ($incompatibleApps as $appInfo) {
365
-			if ($appManager->isShipped($appInfo['id'])) {
366
-				$incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
367
-			}
368
-		}
369
-
370
-		if (!empty($incompatibleShippedApps)) {
371
-			$l = \OC::$server->getL10N('core');
372
-			$hint = $l->t('The files of the app %$1s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
373
-			throw new \OC\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
374
-		}
375
-
376
-		$tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
377
-		$tmpl->assign('incompatibleAppsList', $incompatibleApps);
378
-		$tmpl->assign('productName', 'Nextcloud'); // for now
379
-		$tmpl->assign('oldTheme', $oldTheme);
380
-		$tmpl->printPage();
381
-	}
382
-
383
-	public static function initSession() {
384
-		// prevents javascript from accessing php session cookies
385
-		ini_set('session.cookie_httponly', true);
386
-
387
-		// set the cookie path to the Nextcloud directory
388
-		$cookie_path = OC::$WEBROOT ? : '/';
389
-		ini_set('session.cookie_path', $cookie_path);
390
-
391
-		// Let the session name be changed in the initSession Hook
392
-		$sessionName = OC_Util::getInstanceId();
393
-
394
-		try {
395
-			// Allow session apps to create a custom session object
396
-			$useCustomSession = false;
397
-			$session = self::$server->getSession();
398
-			OC_Hook::emit('OC', 'initSession', array('session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession));
399
-			if (!$useCustomSession) {
400
-				// set the session name to the instance id - which is unique
401
-				$session = new \OC\Session\Internal($sessionName);
402
-			}
403
-
404
-			$cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
405
-			$session = $cryptoWrapper->wrapSession($session);
406
-			self::$server->setSession($session);
407
-
408
-			// if session can't be started break with http 500 error
409
-		} catch (Exception $e) {
410
-			\OCP\Util::logException('base', $e);
411
-			//show the user a detailed error page
412
-			OC_Response::setStatus(OC_Response::STATUS_INTERNAL_SERVER_ERROR);
413
-			OC_Template::printExceptionErrorPage($e);
414
-			die();
415
-		}
416
-
417
-		$sessionLifeTime = self::getSessionLifeTime();
418
-
419
-		// session timeout
420
-		if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
421
-			if (isset($_COOKIE[session_name()])) {
422
-				setcookie(session_name(), null, -1, self::$WEBROOT ? : '/');
423
-			}
424
-			\OC::$server->getUserSession()->logout();
425
-		}
426
-
427
-		$session->set('LAST_ACTIVITY', time());
428
-	}
429
-
430
-	/**
431
-	 * @return string
432
-	 */
433
-	private static function getSessionLifeTime() {
434
-		return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
435
-	}
436
-
437
-	public static function loadAppClassPaths() {
438
-		foreach (OC_App::getEnabledApps() as $app) {
439
-			$appPath = OC_App::getAppPath($app);
440
-			if ($appPath === false) {
441
-				continue;
442
-			}
443
-
444
-			$file = $appPath . '/appinfo/classpath.php';
445
-			if (file_exists($file)) {
446
-				require_once $file;
447
-			}
448
-		}
449
-	}
450
-
451
-	/**
452
-	 * Try to set some values to the required Nextcloud default
453
-	 */
454
-	public static function setRequiredIniValues() {
455
-		@ini_set('default_charset', 'UTF-8');
456
-		@ini_set('gd.jpeg_ignore_warning', 1);
457
-	}
458
-
459
-	/**
460
-	 * Send the same site cookies
461
-	 */
462
-	private static function sendSameSiteCookies() {
463
-		$cookieParams = session_get_cookie_params();
464
-		$secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
465
-		$policies = [
466
-			'lax',
467
-			'strict',
468
-		];
469
-
470
-		// Append __Host to the cookie if it meets the requirements
471
-		$cookiePrefix = '';
472
-		if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
473
-			$cookiePrefix = '__Host-';
474
-		}
475
-
476
-		foreach($policies as $policy) {
477
-			header(
478
-				sprintf(
479
-					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
480
-					$cookiePrefix,
481
-					$policy,
482
-					$cookieParams['path'],
483
-					$policy
484
-				),
485
-				false
486
-			);
487
-		}
488
-	}
489
-
490
-	/**
491
-	 * Same Site cookie to further mitigate CSRF attacks. This cookie has to
492
-	 * be set in every request if cookies are sent to add a second level of
493
-	 * defense against CSRF.
494
-	 *
495
-	 * If the cookie is not sent this will set the cookie and reload the page.
496
-	 * We use an additional cookie since we want to protect logout CSRF and
497
-	 * also we can't directly interfere with PHP's session mechanism.
498
-	 */
499
-	private static function performSameSiteCookieProtection() {
500
-		$request = \OC::$server->getRequest();
501
-
502
-		// Some user agents are notorious and don't really properly follow HTTP
503
-		// specifications. For those, have an automated opt-out. Since the protection
504
-		// for remote.php is applied in base.php as starting point we need to opt out
505
-		// here.
506
-		$incompatibleUserAgents = [
507
-			// OS X Finder
508
-			'/^WebDAVFS/',
509
-		];
510
-		if($request->isUserAgent($incompatibleUserAgents)) {
511
-			return;
512
-		}
513
-
514
-		if(count($_COOKIE) > 0) {
515
-			$requestUri = $request->getScriptName();
516
-			$processingScript = explode('/', $requestUri);
517
-			$processingScript = $processingScript[count($processingScript)-1];
518
-			// FIXME: In a SAML scenario we don't get any strict or lax cookie
519
-			// send for the ACS endpoint. Since we have some legacy code in Nextcloud
520
-			// (direct PHP files) the enforcement of lax cookies is performed here
521
-			// instead of the middleware.
522
-			//
523
-			// This means we cannot exclude some routes from the cookie validation,
524
-			// which normally is not a problem but is a little bit cumbersome for
525
-			// this use-case.
526
-			// Once the old legacy PHP endpoints have been removed we can move
527
-			// the verification into a middleware and also adds some exemptions.
528
-			//
529
-			// Questions about this code? Ask Lukas ;-)
530
-			$currentUrl = substr(explode('?',$request->getRequestUri(), 2)[0], strlen(\OC::$WEBROOT));
531
-			if($currentUrl === '/index.php/apps/user_saml/saml/acs' || $currentUrl === '/apps/user_saml/saml/acs') {
532
-				return;
533
-			}
534
-			// For the "index.php" endpoint only a lax cookie is required.
535
-			if($processingScript === 'index.php') {
536
-				if(!$request->passesLaxCookieCheck()) {
537
-					self::sendSameSiteCookies();
538
-					header('Location: '.$_SERVER['REQUEST_URI']);
539
-					exit();
540
-				}
541
-			} else {
542
-				// All other endpoints require the lax and the strict cookie
543
-				if(!$request->passesStrictCookieCheck()) {
544
-					self::sendSameSiteCookies();
545
-					// Debug mode gets access to the resources without strict cookie
546
-					// due to the fact that the SabreDAV browser also lives there.
547
-					if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
548
-						http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
549
-						exit();
550
-					}
551
-				}
552
-			}
553
-		} elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
554
-			self::sendSameSiteCookies();
555
-		}
556
-	}
557
-
558
-	public static function init() {
559
-		// calculate the root directories
560
-		OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
561
-
562
-		// register autoloader
563
-		$loaderStart = microtime(true);
564
-		require_once __DIR__ . '/autoloader.php';
565
-		self::$loader = new \OC\Autoloader([
566
-			OC::$SERVERROOT . '/lib/private/legacy',
567
-		]);
568
-		if (defined('PHPUNIT_RUN')) {
569
-			self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
570
-		}
571
-		spl_autoload_register(array(self::$loader, 'load'));
572
-		$loaderEnd = microtime(true);
573
-
574
-		self::$CLI = (php_sapi_name() == 'cli');
575
-
576
-		// Add default composer PSR-4 autoloader
577
-		self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
578
-
579
-		try {
580
-			self::initPaths();
581
-			// setup 3rdparty autoloader
582
-			$vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
583
-			if (!file_exists($vendorAutoLoad)) {
584
-				throw new \RuntimeException('Composer autoloader not found, unable to continue. Check the folder "3rdparty". Running "git submodule update --init" will initialize the git submodule that handles the subfolder "3rdparty".');
585
-			}
586
-			require_once $vendorAutoLoad;
587
-
588
-		} catch (\RuntimeException $e) {
589
-			if (!self::$CLI) {
590
-				$claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']);
591
-				$protocol = in_array($claimedProtocol, ['HTTP/1.0', 'HTTP/1.1', 'HTTP/2']) ? $claimedProtocol : 'HTTP/1.1';
592
-				header($protocol . ' ' . OC_Response::STATUS_SERVICE_UNAVAILABLE);
593
-			}
594
-			// we can't use the template error page here, because this needs the
595
-			// DI container which isn't available yet
596
-			print($e->getMessage());
597
-			exit();
598
-		}
599
-
600
-		// setup the basic server
601
-		self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
602
-		\OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
603
-		\OC::$server->getEventLogger()->start('boot', 'Initialize');
604
-
605
-		// Don't display errors and log them
606
-		error_reporting(E_ALL | E_STRICT);
607
-		@ini_set('display_errors', 0);
608
-		@ini_set('log_errors', 1);
609
-
610
-		if(!date_default_timezone_set('UTC')) {
611
-			throw new \RuntimeException('Could not set timezone to UTC');
612
-		};
613
-
614
-		//try to configure php to enable big file uploads.
615
-		//this doesn´t work always depending on the webserver and php configuration.
616
-		//Let´s try to overwrite some defaults anyway
617
-
618
-		//try to set the maximum execution time to 60min
619
-		if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
620
-			@set_time_limit(3600);
621
-		}
622
-		@ini_set('max_execution_time', 3600);
623
-		@ini_set('max_input_time', 3600);
624
-
625
-		//try to set the maximum filesize to 10G
626
-		@ini_set('upload_max_filesize', '10G');
627
-		@ini_set('post_max_size', '10G');
628
-		@ini_set('file_uploads', '50');
629
-
630
-		self::setRequiredIniValues();
631
-		self::handleAuthHeaders();
632
-		self::registerAutoloaderCache();
633
-
634
-		// initialize intl fallback is necessary
635
-		\Patchwork\Utf8\Bootup::initIntl();
636
-		OC_Util::isSetLocaleWorking();
637
-
638
-		if (!defined('PHPUNIT_RUN')) {
639
-			OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
640
-			$debug = \OC::$server->getConfig()->getSystemValue('debug', false);
641
-			OC\Log\ErrorHandler::register($debug);
642
-		}
643
-
644
-		\OC::$server->getEventLogger()->start('init_session', 'Initialize session');
645
-		OC_App::loadApps(array('session'));
646
-		if (!self::$CLI) {
647
-			self::initSession();
648
-		}
649
-		\OC::$server->getEventLogger()->end('init_session');
650
-		self::checkConfig();
651
-		self::checkInstalled();
652
-
653
-		OC_Response::addSecurityHeaders();
654
-		if(self::$server->getRequest()->getServerProtocol() === 'https') {
655
-			ini_set('session.cookie_secure', true);
656
-		}
657
-
658
-		self::performSameSiteCookieProtection();
659
-
660
-		if (!defined('OC_CONSOLE')) {
661
-			$errors = OC_Util::checkServer(\OC::$server->getSystemConfig());
662
-			if (count($errors) > 0) {
663
-				if (self::$CLI) {
664
-					// Convert l10n string into regular string for usage in database
665
-					$staticErrors = [];
666
-					foreach ($errors as $error) {
667
-						echo $error['error'] . "\n";
668
-						echo $error['hint'] . "\n\n";
669
-						$staticErrors[] = [
670
-							'error' => (string)$error['error'],
671
-							'hint' => (string)$error['hint'],
672
-						];
673
-					}
674
-
675
-					try {
676
-						\OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
677
-					} catch (\Exception $e) {
678
-						echo('Writing to database failed');
679
-					}
680
-					exit(1);
681
-				} else {
682
-					OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE);
683
-					OC_Util::addStyle('guest');
684
-					OC_Template::printGuestPage('', 'error', array('errors' => $errors));
685
-					exit;
686
-				}
687
-			} elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
688
-				\OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
689
-			}
690
-		}
691
-		//try to set the session lifetime
692
-		$sessionLifeTime = self::getSessionLifeTime();
693
-		@ini_set('gc_maxlifetime', (string)$sessionLifeTime);
694
-
695
-		$systemConfig = \OC::$server->getSystemConfig();
696
-
697
-		// User and Groups
698
-		if (!$systemConfig->getValue("installed", false)) {
699
-			self::$server->getSession()->set('user_id', '');
700
-		}
701
-
702
-		OC_User::useBackend(new \OC\User\Database());
703
-		\OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
704
-
705
-		// Subscribe to the hook
706
-		\OCP\Util::connectHook(
707
-			'\OCA\Files_Sharing\API\Server2Server',
708
-			'preLoginNameUsedAsUserName',
709
-			'\OC\User\Database',
710
-			'preLoginNameUsedAsUserName'
711
-		);
712
-
713
-		//setup extra user backends
714
-		if (!self::checkUpgrade(false)) {
715
-			OC_User::setupBackends();
716
-		} else {
717
-			// Run upgrades in incognito mode
718
-			OC_User::setIncognitoMode(true);
719
-		}
720
-
721
-		self::registerCacheHooks();
722
-		self::registerFilesystemHooks();
723
-		self::registerShareHooks();
724
-		self::registerLogRotate();
725
-		self::registerEncryptionWrapper();
726
-		self::registerEncryptionHooks();
727
-		self::registerAccountHooks();
728
-		self::registerSettingsHooks();
729
-
730
-		$settings = new \OC\Settings\Application();
731
-		$settings->register();
732
-
733
-		//make sure temporary files are cleaned up
734
-		$tmpManager = \OC::$server->getTempManager();
735
-		register_shutdown_function(array($tmpManager, 'clean'));
736
-		$lockProvider = \OC::$server->getLockingProvider();
737
-		register_shutdown_function(array($lockProvider, 'releaseAll'));
738
-
739
-		// Check whether the sample configuration has been copied
740
-		if($systemConfig->getValue('copied_sample_config', false)) {
741
-			$l = \OC::$server->getL10N('lib');
742
-			header('HTTP/1.1 503 Service Temporarily Unavailable');
743
-			header('Status: 503 Service Temporarily Unavailable');
744
-			OC_Template::printErrorPage(
745
-				$l->t('Sample configuration detected'),
746
-				$l->t('It has been detected that the sample configuration has been copied. This can break your installation and is unsupported. Please read the documentation before performing changes on config.php')
747
-			);
748
-			return;
749
-		}
750
-
751
-		$request = \OC::$server->getRequest();
752
-		$host = $request->getInsecureServerHost();
753
-		/**
754
-		 * if the host passed in headers isn't trusted
755
-		 * FIXME: Should not be in here at all :see_no_evil:
756
-		 */
757
-		if (!OC::$CLI
758
-			// overwritehost is always trusted, workaround to not have to make
759
-			// \OC\AppFramework\Http\Request::getOverwriteHost public
760
-			&& self::$server->getConfig()->getSystemValue('overwritehost') === ''
761
-			&& !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
762
-			&& self::$server->getConfig()->getSystemValue('installed', false)
763
-		) {
764
-			// Allow access to CSS resources
765
-			$isScssRequest = false;
766
-			if(strpos($request->getPathInfo(), '/css/') === 0) {
767
-				$isScssRequest = true;
768
-			}
769
-
770
-			if (!$isScssRequest) {
771
-				header('HTTP/1.1 400 Bad Request');
772
-				header('Status: 400 Bad Request');
773
-
774
-				\OC::$server->getLogger()->warning(
775
-					'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
776
-					[
777
-						'app' => 'core',
778
-						'remoteAddress' => $request->getRemoteAddress(),
779
-						'host' => $host,
780
-					]
781
-				);
782
-
783
-				$tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
784
-				$tmpl->assign('domain', $host);
785
-				$tmpl->printPage();
786
-
787
-				exit();
788
-			}
789
-		}
790
-		\OC::$server->getEventLogger()->end('boot');
791
-	}
792
-
793
-	/**
794
-	 * register hooks for the cache
795
-	 */
796
-	public static function registerCacheHooks() {
797
-		//don't try to do this before we are properly setup
798
-		if (\OC::$server->getSystemConfig()->getValue('installed', false) && !self::checkUpgrade(false)) {
799
-
800
-			// NOTE: This will be replaced to use OCP
801
-			$userSession = self::$server->getUserSession();
802
-			$userSession->listen('\OC\User', 'postLogin', function () {
803
-				try {
804
-					$cache = new \OC\Cache\File();
805
-					$cache->gc();
806
-				} catch (\OC\ServerNotAvailableException $e) {
807
-					// not a GC exception, pass it on
808
-					throw $e;
809
-				} catch (\Exception $e) {
810
-					// a GC exception should not prevent users from using OC,
811
-					// so log the exception
812
-					\OC::$server->getLogger()->warning('Exception when running cache gc: ' . $e->getMessage(), array('app' => 'core'));
813
-				}
814
-			});
815
-		}
816
-	}
817
-
818
-	public static function registerSettingsHooks() {
819
-		$dispatcher = \OC::$server->getEventDispatcher();
820
-		$dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_DISABLE, function($event) {
821
-			/** @var \OCP\App\ManagerEvent $event */
822
-			\OC::$server->getSettingsManager()->onAppDisabled($event->getAppID());
823
-		});
824
-		$dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_UPDATE, function($event) {
825
-			/** @var \OCP\App\ManagerEvent $event */
826
-			$jobList = \OC::$server->getJobList();
827
-			$job = 'OC\\Settings\\RemoveOrphaned';
828
-			if(!($jobList->has($job, null))) {
829
-				$jobList->add($job);
830
-			}
831
-		});
832
-	}
833
-
834
-	private static function registerEncryptionWrapper() {
835
-		$manager = self::$server->getEncryptionManager();
836
-		\OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
837
-	}
838
-
839
-	private static function registerEncryptionHooks() {
840
-		$enabled = self::$server->getEncryptionManager()->isEnabled();
841
-		if ($enabled) {
842
-			\OCP\Util::connectHook('OCP\Share', 'post_shared', 'OC\Encryption\HookManager', 'postShared');
843
-			\OCP\Util::connectHook('OCP\Share', 'post_unshare', 'OC\Encryption\HookManager', 'postUnshared');
844
-			\OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OC\Encryption\HookManager', 'postRename');
845
-			\OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', 'OC\Encryption\HookManager', 'postRestore');
846
-		}
847
-	}
848
-
849
-	private static function registerAccountHooks() {
850
-		$hookHandler = new \OC\Accounts\Hooks(\OC::$server->getLogger());
851
-		\OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
852
-	}
853
-
854
-	/**
855
-	 * register hooks for the cache
856
-	 */
857
-	public static function registerLogRotate() {
858
-		$systemConfig = \OC::$server->getSystemConfig();
859
-		if ($systemConfig->getValue('installed', false) && $systemConfig->getValue('log_rotate_size', false) && !self::checkUpgrade(false)) {
860
-			//don't try to do this before we are properly setup
861
-			//use custom logfile path if defined, otherwise use default of nextcloud.log in data directory
862
-			\OC::$server->getJobList()->add('OC\Log\Rotate');
863
-		}
864
-	}
865
-
866
-	/**
867
-	 * register hooks for the filesystem
868
-	 */
869
-	public static function registerFilesystemHooks() {
870
-		// Check for blacklisted files
871
-		OC_Hook::connect('OC_Filesystem', 'write', 'OC\Files\Filesystem', 'isBlacklisted');
872
-		OC_Hook::connect('OC_Filesystem', 'rename', 'OC\Files\Filesystem', 'isBlacklisted');
873
-	}
874
-
875
-	/**
876
-	 * register hooks for sharing
877
-	 */
878
-	public static function registerShareHooks() {
879
-		if (\OC::$server->getSystemConfig()->getValue('installed')) {
880
-			OC_Hook::connect('OC_User', 'post_deleteUser', 'OC\Share20\Hooks', 'post_deleteUser');
881
-			OC_Hook::connect('OC_User', 'post_removeFromGroup', 'OC\Share20\Hooks', 'post_removeFromGroup');
882
-			OC_Hook::connect('OC_User', 'post_deleteGroup', 'OC\Share20\Hooks', 'post_deleteGroup');
883
-		}
884
-	}
885
-
886
-	protected static function registerAutoloaderCache() {
887
-		// The class loader takes an optional low-latency cache, which MUST be
888
-		// namespaced. The instanceid is used for namespacing, but might be
889
-		// unavailable at this point. Furthermore, it might not be possible to
890
-		// generate an instanceid via \OC_Util::getInstanceId() because the
891
-		// config file may not be writable. As such, we only register a class
892
-		// loader cache if instanceid is available without trying to create one.
893
-		$instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
894
-		if ($instanceId) {
895
-			try {
896
-				$memcacheFactory = \OC::$server->getMemCacheFactory();
897
-				self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
898
-			} catch (\Exception $ex) {
899
-			}
900
-		}
901
-	}
902
-
903
-	/**
904
-	 * Handle the request
905
-	 */
906
-	public static function handleRequest() {
907
-
908
-		\OC::$server->getEventLogger()->start('handle_request', 'Handle request');
909
-		$systemConfig = \OC::$server->getSystemConfig();
910
-		// load all the classpaths from the enabled apps so they are available
911
-		// in the routing files of each app
912
-		OC::loadAppClassPaths();
913
-
914
-		// Check if Nextcloud is installed or in maintenance (update) mode
915
-		if (!$systemConfig->getValue('installed', false)) {
916
-			\OC::$server->getSession()->clear();
917
-			$setupHelper = new OC\Setup(\OC::$server->getSystemConfig(), \OC::$server->getIniWrapper(),
918
-				\OC::$server->getL10N('lib'), \OC::$server->query(\OCP\Defaults::class), \OC::$server->getLogger(),
919
-				\OC::$server->getSecureRandom());
920
-			$controller = new OC\Core\Controller\SetupController($setupHelper);
921
-			$controller->run($_POST);
922
-			exit();
923
-		}
924
-
925
-		$request = \OC::$server->getRequest();
926
-		$requestPath = $request->getRawPathInfo();
927
-		if ($requestPath === '/heartbeat') {
928
-			return;
929
-		}
930
-		if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
931
-			self::checkMaintenanceMode();
932
-			self::checkUpgrade();
933
-		}
934
-
935
-		// emergency app disabling
936
-		if ($requestPath === '/disableapp'
937
-			&& $request->getMethod() === 'POST'
938
-			&& ((string)$request->getParam('appid')) !== ''
939
-		) {
940
-			\OCP\JSON::callCheck();
941
-			\OCP\JSON::checkAdminUser();
942
-			$appId = (string)$request->getParam('appid');
943
-			$appId = \OC_App::cleanAppId($appId);
944
-
945
-			\OC_App::disable($appId);
946
-			\OC_JSON::success();
947
-			exit();
948
-		}
949
-
950
-		// Always load authentication apps
951
-		OC_App::loadApps(['authentication']);
952
-
953
-		// Load minimum set of apps
954
-		if (!self::checkUpgrade(false)
955
-			&& !$systemConfig->getValue('maintenance', false)) {
956
-			// For logged-in users: Load everything
957
-			if(\OC::$server->getUserSession()->isLoggedIn()) {
958
-				OC_App::loadApps();
959
-			} else {
960
-				// For guests: Load only filesystem and logging
961
-				OC_App::loadApps(array('filesystem', 'logging'));
962
-				self::handleLogin($request);
963
-			}
964
-		}
965
-
966
-		if (!self::$CLI) {
967
-			try {
968
-				if (!$systemConfig->getValue('maintenance', false) && !self::checkUpgrade(false)) {
969
-					OC_App::loadApps(array('filesystem', 'logging'));
970
-					OC_App::loadApps();
971
-				}
972
-				OC_Util::setupFS();
973
-				OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
974
-				return;
975
-			} catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
976
-				//header('HTTP/1.0 404 Not Found');
977
-			} catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
978
-				OC_Response::setStatus(405);
979
-				return;
980
-			}
981
-		}
982
-
983
-		// Handle WebDAV
984
-		if ($_SERVER['REQUEST_METHOD'] == 'PROPFIND') {
985
-			// not allowed any more to prevent people
986
-			// mounting this root directly.
987
-			// Users need to mount remote.php/webdav instead.
988
-			header('HTTP/1.1 405 Method Not Allowed');
989
-			header('Status: 405 Method Not Allowed');
990
-			return;
991
-		}
992
-
993
-		// Someone is logged in
994
-		if (\OC::$server->getUserSession()->isLoggedIn()) {
995
-			OC_App::loadApps();
996
-			OC_User::setupBackends();
997
-			OC_Util::setupFS();
998
-			// FIXME
999
-			// Redirect to default application
1000
-			OC_Util::redirectToDefaultPage();
1001
-		} else {
1002
-			// Not handled and not logged in
1003
-			header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1004
-		}
1005
-	}
1006
-
1007
-	/**
1008
-	 * Check login: apache auth, auth token, basic auth
1009
-	 *
1010
-	 * @param OCP\IRequest $request
1011
-	 * @return boolean
1012
-	 */
1013
-	static function handleLogin(OCP\IRequest $request) {
1014
-		$userSession = self::$server->getUserSession();
1015
-		if (OC_User::handleApacheAuth()) {
1016
-			return true;
1017
-		}
1018
-		if ($userSession->tryTokenLogin($request)) {
1019
-			return true;
1020
-		}
1021
-		if (isset($_COOKIE['nc_username'])
1022
-			&& isset($_COOKIE['nc_token'])
1023
-			&& isset($_COOKIE['nc_session_id'])
1024
-			&& $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1025
-			return true;
1026
-		}
1027
-		if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1028
-			return true;
1029
-		}
1030
-		return false;
1031
-	}
1032
-
1033
-	protected static function handleAuthHeaders() {
1034
-		//copy http auth headers for apache+php-fcgid work around
1035
-		if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1036
-			$_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1037
-		}
1038
-
1039
-		// Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1040
-		$vars = array(
1041
-			'HTTP_AUTHORIZATION', // apache+php-cgi work around
1042
-			'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1043
-		);
1044
-		foreach ($vars as $var) {
1045
-			if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1046
-				list($name, $password) = explode(':', base64_decode($matches[1]), 2);
1047
-				$_SERVER['PHP_AUTH_USER'] = $name;
1048
-				$_SERVER['PHP_AUTH_PW'] = $password;
1049
-				break;
1050
-			}
1051
-		}
1052
-	}
62
+    /**
63
+     * Associative array for autoloading. classname => filename
64
+     */
65
+    public static $CLASSPATH = array();
66
+    /**
67
+     * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
68
+     */
69
+    public static $SERVERROOT = '';
70
+    /**
71
+     * the current request path relative to the Nextcloud root (e.g. files/index.php)
72
+     */
73
+    private static $SUBURI = '';
74
+    /**
75
+     * the Nextcloud root path for http requests (e.g. nextcloud/)
76
+     */
77
+    public static $WEBROOT = '';
78
+    /**
79
+     * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
80
+     * web path in 'url'
81
+     */
82
+    public static $APPSROOTS = array();
83
+
84
+    /**
85
+     * @var string
86
+     */
87
+    public static $configDir;
88
+
89
+    /**
90
+     * requested app
91
+     */
92
+    public static $REQUESTEDAPP = '';
93
+
94
+    /**
95
+     * check if Nextcloud runs in cli mode
96
+     */
97
+    public static $CLI = false;
98
+
99
+    /**
100
+     * @var \OC\Autoloader $loader
101
+     */
102
+    public static $loader = null;
103
+
104
+    /** @var \Composer\Autoload\ClassLoader $composerAutoloader */
105
+    public static $composerAutoloader = null;
106
+
107
+    /**
108
+     * @var \OC\Server
109
+     */
110
+    public static $server = null;
111
+
112
+    /**
113
+     * @var \OC\Config
114
+     */
115
+    private static $config = null;
116
+
117
+    /**
118
+     * @throws \RuntimeException when the 3rdparty directory is missing or
119
+     * the app path list is empty or contains an invalid path
120
+     */
121
+    public static function initPaths() {
122
+        if(defined('PHPUNIT_CONFIG_DIR')) {
123
+            self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
124
+        } elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
125
+            self::$configDir = OC::$SERVERROOT . '/tests/config/';
126
+        } elseif($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
127
+            self::$configDir = rtrim($dir, '/') . '/';
128
+        } else {
129
+            self::$configDir = OC::$SERVERROOT . '/config/';
130
+        }
131
+        self::$config = new \OC\Config(self::$configDir);
132
+
133
+        OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
134
+        /**
135
+         * FIXME: The following lines are required because we can't yet instantiiate
136
+         *        \OC::$server->getRequest() since \OC::$server does not yet exist.
137
+         */
138
+        $params = [
139
+            'server' => [
140
+                'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
141
+                'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
142
+            ],
143
+        ];
144
+        $fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig(self::$config)));
145
+        $scriptName = $fakeRequest->getScriptName();
146
+        if (substr($scriptName, -1) == '/') {
147
+            $scriptName .= 'index.php';
148
+            //make sure suburi follows the same rules as scriptName
149
+            if (substr(OC::$SUBURI, -9) != 'index.php') {
150
+                if (substr(OC::$SUBURI, -1) != '/') {
151
+                    OC::$SUBURI = OC::$SUBURI . '/';
152
+                }
153
+                OC::$SUBURI = OC::$SUBURI . 'index.php';
154
+            }
155
+        }
156
+
157
+
158
+        if (OC::$CLI) {
159
+            OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
160
+        } else {
161
+            if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
162
+                OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
163
+
164
+                if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
165
+                    OC::$WEBROOT = '/' . OC::$WEBROOT;
166
+                }
167
+            } else {
168
+                // The scriptName is not ending with OC::$SUBURI
169
+                // This most likely means that we are calling from CLI.
170
+                // However some cron jobs still need to generate
171
+                // a web URL, so we use overwritewebroot as a fallback.
172
+                OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
173
+            }
174
+
175
+            // Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
176
+            // slash which is required by URL generation.
177
+            if($_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
178
+                    substr($_SERVER['REQUEST_URI'], -1) !== '/') {
179
+                header('Location: '.\OC::$WEBROOT.'/');
180
+                exit();
181
+            }
182
+        }
183
+
184
+        // search the apps folder
185
+        $config_paths = self::$config->getValue('apps_paths', array());
186
+        if (!empty($config_paths)) {
187
+            foreach ($config_paths as $paths) {
188
+                if (isset($paths['url']) && isset($paths['path'])) {
189
+                    $paths['url'] = rtrim($paths['url'], '/');
190
+                    $paths['path'] = rtrim($paths['path'], '/');
191
+                    OC::$APPSROOTS[] = $paths;
192
+                }
193
+            }
194
+        } elseif (file_exists(OC::$SERVERROOT . '/apps')) {
195
+            OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
196
+        } elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
197
+            OC::$APPSROOTS[] = array(
198
+                'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
199
+                'url' => '/apps',
200
+                'writable' => true
201
+            );
202
+        }
203
+
204
+        if (empty(OC::$APPSROOTS)) {
205
+            throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
206
+                . ' or the folder above. You can also configure the location in the config.php file.');
207
+        }
208
+        $paths = array();
209
+        foreach (OC::$APPSROOTS as $path) {
210
+            $paths[] = $path['path'];
211
+            if (!is_dir($path['path'])) {
212
+                throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
213
+                    . ' Nextcloud folder or the folder above. You can also configure the location in the'
214
+                    . ' config.php file.', $path['path']));
215
+            }
216
+        }
217
+
218
+        // set the right include path
219
+        set_include_path(
220
+            implode(PATH_SEPARATOR, $paths)
221
+        );
222
+    }
223
+
224
+    public static function checkConfig() {
225
+        $l = \OC::$server->getL10N('lib');
226
+
227
+        // Create config if it does not already exist
228
+        $configFilePath = self::$configDir .'/config.php';
229
+        if(!file_exists($configFilePath)) {
230
+            @touch($configFilePath);
231
+        }
232
+
233
+        // Check if config is writable
234
+        $configFileWritable = is_writable($configFilePath);
235
+        if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
236
+            || !$configFileWritable && self::checkUpgrade(false)) {
237
+
238
+            $urlGenerator = \OC::$server->getURLGenerator();
239
+
240
+            if (self::$CLI) {
241
+                echo $l->t('Cannot write into "config" directory!')."\n";
242
+                echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
243
+                echo "\n";
244
+                echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-dir_permissions') ])."\n";
245
+                exit;
246
+            } else {
247
+                OC_Template::printErrorPage(
248
+                    $l->t('Cannot write into "config" directory!'),
249
+                    $l->t('This can usually be fixed by '
250
+                    . '%sgiving the webserver write access to the config directory%s.',
251
+                        array('<a href="' . $urlGenerator->linkToDocs('admin-dir_permissions') . '" target="_blank" rel="noreferrer">', '</a>'))
252
+                );
253
+            }
254
+        }
255
+    }
256
+
257
+    public static function checkInstalled() {
258
+        if (defined('OC_CONSOLE')) {
259
+            return;
260
+        }
261
+        // Redirect to installer if not installed
262
+        if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
263
+            if (OC::$CLI) {
264
+                throw new Exception('Not installed');
265
+            } else {
266
+                $url = OC::$WEBROOT . '/index.php';
267
+                header('Location: ' . $url);
268
+            }
269
+            exit();
270
+        }
271
+    }
272
+
273
+    public static function checkMaintenanceMode() {
274
+        // Allow ajax update script to execute without being stopped
275
+        if (\OC::$server->getSystemConfig()->getValue('maintenance', false) && OC::$SUBURI != '/core/ajax/update.php') {
276
+            // send http status 503
277
+            header('HTTP/1.1 503 Service Temporarily Unavailable');
278
+            header('Status: 503 Service Temporarily Unavailable');
279
+            header('Retry-After: 120');
280
+
281
+            // render error page
282
+            $template = new OC_Template('', 'update.user', 'guest');
283
+            OC_Util::addScript('maintenance-check');
284
+            $template->printPage();
285
+            die();
286
+        }
287
+    }
288
+
289
+    /**
290
+     * Checks if the version requires an update and shows
291
+     * @param bool $showTemplate Whether an update screen should get shown
292
+     * @return bool|void
293
+     */
294
+    public static function checkUpgrade($showTemplate = true) {
295
+        if (\OCP\Util::needUpgrade()) {
296
+            $systemConfig = \OC::$server->getSystemConfig();
297
+            if ($showTemplate && !$systemConfig->getValue('maintenance', false)) {
298
+                self::printUpgradePage();
299
+                exit();
300
+            } else {
301
+                return true;
302
+            }
303
+        }
304
+        return false;
305
+    }
306
+
307
+    /**
308
+     * Prints the upgrade page
309
+     */
310
+    private static function printUpgradePage() {
311
+        $systemConfig = \OC::$server->getSystemConfig();
312
+
313
+        $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
314
+        $tooBig = false;
315
+        if (!$disableWebUpdater) {
316
+            $apps = \OC::$server->getAppManager();
317
+            $tooBig = $apps->isInstalled('user_ldap') || $apps->isInstalled('user_shibboleth');
318
+            if (!$tooBig) {
319
+                // count users
320
+                $stats = \OC::$server->getUserManager()->countUsers();
321
+                $totalUsers = array_sum($stats);
322
+                $tooBig = ($totalUsers > 50);
323
+            }
324
+        }
325
+        if ($disableWebUpdater || $tooBig) {
326
+            // send http status 503
327
+            header('HTTP/1.1 503 Service Temporarily Unavailable');
328
+            header('Status: 503 Service Temporarily Unavailable');
329
+            header('Retry-After: 120');
330
+
331
+            // render error page
332
+            $template = new OC_Template('', 'update.use-cli', 'guest');
333
+            $template->assign('productName', 'nextcloud'); // for now
334
+            $template->assign('version', OC_Util::getVersionString());
335
+            $template->assign('tooBig', $tooBig);
336
+
337
+            $template->printPage();
338
+            die();
339
+        }
340
+
341
+        // check whether this is a core update or apps update
342
+        $installedVersion = $systemConfig->getValue('version', '0.0.0');
343
+        $currentVersion = implode('.', \OCP\Util::getVersion());
344
+
345
+        // if not a core upgrade, then it's apps upgrade
346
+        $isAppsOnlyUpgrade = (version_compare($currentVersion, $installedVersion, '='));
347
+
348
+        $oldTheme = $systemConfig->getValue('theme');
349
+        $systemConfig->setValue('theme', '');
350
+        OC_Util::addScript('config'); // needed for web root
351
+        OC_Util::addScript('update');
352
+
353
+        /** @var \OC\App\AppManager $appManager */
354
+        $appManager = \OC::$server->getAppManager();
355
+
356
+        $tmpl = new OC_Template('', 'update.admin', 'guest');
357
+        $tmpl->assign('version', OC_Util::getVersionString());
358
+        $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
359
+
360
+        // get third party apps
361
+        $ocVersion = \OCP\Util::getVersion();
362
+        $incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
363
+        $incompatibleShippedApps = [];
364
+        foreach ($incompatibleApps as $appInfo) {
365
+            if ($appManager->isShipped($appInfo['id'])) {
366
+                $incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
367
+            }
368
+        }
369
+
370
+        if (!empty($incompatibleShippedApps)) {
371
+            $l = \OC::$server->getL10N('core');
372
+            $hint = $l->t('The files of the app %$1s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
373
+            throw new \OC\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
374
+        }
375
+
376
+        $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
377
+        $tmpl->assign('incompatibleAppsList', $incompatibleApps);
378
+        $tmpl->assign('productName', 'Nextcloud'); // for now
379
+        $tmpl->assign('oldTheme', $oldTheme);
380
+        $tmpl->printPage();
381
+    }
382
+
383
+    public static function initSession() {
384
+        // prevents javascript from accessing php session cookies
385
+        ini_set('session.cookie_httponly', true);
386
+
387
+        // set the cookie path to the Nextcloud directory
388
+        $cookie_path = OC::$WEBROOT ? : '/';
389
+        ini_set('session.cookie_path', $cookie_path);
390
+
391
+        // Let the session name be changed in the initSession Hook
392
+        $sessionName = OC_Util::getInstanceId();
393
+
394
+        try {
395
+            // Allow session apps to create a custom session object
396
+            $useCustomSession = false;
397
+            $session = self::$server->getSession();
398
+            OC_Hook::emit('OC', 'initSession', array('session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession));
399
+            if (!$useCustomSession) {
400
+                // set the session name to the instance id - which is unique
401
+                $session = new \OC\Session\Internal($sessionName);
402
+            }
403
+
404
+            $cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
405
+            $session = $cryptoWrapper->wrapSession($session);
406
+            self::$server->setSession($session);
407
+
408
+            // if session can't be started break with http 500 error
409
+        } catch (Exception $e) {
410
+            \OCP\Util::logException('base', $e);
411
+            //show the user a detailed error page
412
+            OC_Response::setStatus(OC_Response::STATUS_INTERNAL_SERVER_ERROR);
413
+            OC_Template::printExceptionErrorPage($e);
414
+            die();
415
+        }
416
+
417
+        $sessionLifeTime = self::getSessionLifeTime();
418
+
419
+        // session timeout
420
+        if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
421
+            if (isset($_COOKIE[session_name()])) {
422
+                setcookie(session_name(), null, -1, self::$WEBROOT ? : '/');
423
+            }
424
+            \OC::$server->getUserSession()->logout();
425
+        }
426
+
427
+        $session->set('LAST_ACTIVITY', time());
428
+    }
429
+
430
+    /**
431
+     * @return string
432
+     */
433
+    private static function getSessionLifeTime() {
434
+        return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
435
+    }
436
+
437
+    public static function loadAppClassPaths() {
438
+        foreach (OC_App::getEnabledApps() as $app) {
439
+            $appPath = OC_App::getAppPath($app);
440
+            if ($appPath === false) {
441
+                continue;
442
+            }
443
+
444
+            $file = $appPath . '/appinfo/classpath.php';
445
+            if (file_exists($file)) {
446
+                require_once $file;
447
+            }
448
+        }
449
+    }
450
+
451
+    /**
452
+     * Try to set some values to the required Nextcloud default
453
+     */
454
+    public static function setRequiredIniValues() {
455
+        @ini_set('default_charset', 'UTF-8');
456
+        @ini_set('gd.jpeg_ignore_warning', 1);
457
+    }
458
+
459
+    /**
460
+     * Send the same site cookies
461
+     */
462
+    private static function sendSameSiteCookies() {
463
+        $cookieParams = session_get_cookie_params();
464
+        $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
465
+        $policies = [
466
+            'lax',
467
+            'strict',
468
+        ];
469
+
470
+        // Append __Host to the cookie if it meets the requirements
471
+        $cookiePrefix = '';
472
+        if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
473
+            $cookiePrefix = '__Host-';
474
+        }
475
+
476
+        foreach($policies as $policy) {
477
+            header(
478
+                sprintf(
479
+                    'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
480
+                    $cookiePrefix,
481
+                    $policy,
482
+                    $cookieParams['path'],
483
+                    $policy
484
+                ),
485
+                false
486
+            );
487
+        }
488
+    }
489
+
490
+    /**
491
+     * Same Site cookie to further mitigate CSRF attacks. This cookie has to
492
+     * be set in every request if cookies are sent to add a second level of
493
+     * defense against CSRF.
494
+     *
495
+     * If the cookie is not sent this will set the cookie and reload the page.
496
+     * We use an additional cookie since we want to protect logout CSRF and
497
+     * also we can't directly interfere with PHP's session mechanism.
498
+     */
499
+    private static function performSameSiteCookieProtection() {
500
+        $request = \OC::$server->getRequest();
501
+
502
+        // Some user agents are notorious and don't really properly follow HTTP
503
+        // specifications. For those, have an automated opt-out. Since the protection
504
+        // for remote.php is applied in base.php as starting point we need to opt out
505
+        // here.
506
+        $incompatibleUserAgents = [
507
+            // OS X Finder
508
+            '/^WebDAVFS/',
509
+        ];
510
+        if($request->isUserAgent($incompatibleUserAgents)) {
511
+            return;
512
+        }
513
+
514
+        if(count($_COOKIE) > 0) {
515
+            $requestUri = $request->getScriptName();
516
+            $processingScript = explode('/', $requestUri);
517
+            $processingScript = $processingScript[count($processingScript)-1];
518
+            // FIXME: In a SAML scenario we don't get any strict or lax cookie
519
+            // send for the ACS endpoint. Since we have some legacy code in Nextcloud
520
+            // (direct PHP files) the enforcement of lax cookies is performed here
521
+            // instead of the middleware.
522
+            //
523
+            // This means we cannot exclude some routes from the cookie validation,
524
+            // which normally is not a problem but is a little bit cumbersome for
525
+            // this use-case.
526
+            // Once the old legacy PHP endpoints have been removed we can move
527
+            // the verification into a middleware and also adds some exemptions.
528
+            //
529
+            // Questions about this code? Ask Lukas ;-)
530
+            $currentUrl = substr(explode('?',$request->getRequestUri(), 2)[0], strlen(\OC::$WEBROOT));
531
+            if($currentUrl === '/index.php/apps/user_saml/saml/acs' || $currentUrl === '/apps/user_saml/saml/acs') {
532
+                return;
533
+            }
534
+            // For the "index.php" endpoint only a lax cookie is required.
535
+            if($processingScript === 'index.php') {
536
+                if(!$request->passesLaxCookieCheck()) {
537
+                    self::sendSameSiteCookies();
538
+                    header('Location: '.$_SERVER['REQUEST_URI']);
539
+                    exit();
540
+                }
541
+            } else {
542
+                // All other endpoints require the lax and the strict cookie
543
+                if(!$request->passesStrictCookieCheck()) {
544
+                    self::sendSameSiteCookies();
545
+                    // Debug mode gets access to the resources without strict cookie
546
+                    // due to the fact that the SabreDAV browser also lives there.
547
+                    if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
548
+                        http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
549
+                        exit();
550
+                    }
551
+                }
552
+            }
553
+        } elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
554
+            self::sendSameSiteCookies();
555
+        }
556
+    }
557
+
558
+    public static function init() {
559
+        // calculate the root directories
560
+        OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
561
+
562
+        // register autoloader
563
+        $loaderStart = microtime(true);
564
+        require_once __DIR__ . '/autoloader.php';
565
+        self::$loader = new \OC\Autoloader([
566
+            OC::$SERVERROOT . '/lib/private/legacy',
567
+        ]);
568
+        if (defined('PHPUNIT_RUN')) {
569
+            self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
570
+        }
571
+        spl_autoload_register(array(self::$loader, 'load'));
572
+        $loaderEnd = microtime(true);
573
+
574
+        self::$CLI = (php_sapi_name() == 'cli');
575
+
576
+        // Add default composer PSR-4 autoloader
577
+        self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
578
+
579
+        try {
580
+            self::initPaths();
581
+            // setup 3rdparty autoloader
582
+            $vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
583
+            if (!file_exists($vendorAutoLoad)) {
584
+                throw new \RuntimeException('Composer autoloader not found, unable to continue. Check the folder "3rdparty". Running "git submodule update --init" will initialize the git submodule that handles the subfolder "3rdparty".');
585
+            }
586
+            require_once $vendorAutoLoad;
587
+
588
+        } catch (\RuntimeException $e) {
589
+            if (!self::$CLI) {
590
+                $claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']);
591
+                $protocol = in_array($claimedProtocol, ['HTTP/1.0', 'HTTP/1.1', 'HTTP/2']) ? $claimedProtocol : 'HTTP/1.1';
592
+                header($protocol . ' ' . OC_Response::STATUS_SERVICE_UNAVAILABLE);
593
+            }
594
+            // we can't use the template error page here, because this needs the
595
+            // DI container which isn't available yet
596
+            print($e->getMessage());
597
+            exit();
598
+        }
599
+
600
+        // setup the basic server
601
+        self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
602
+        \OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
603
+        \OC::$server->getEventLogger()->start('boot', 'Initialize');
604
+
605
+        // Don't display errors and log them
606
+        error_reporting(E_ALL | E_STRICT);
607
+        @ini_set('display_errors', 0);
608
+        @ini_set('log_errors', 1);
609
+
610
+        if(!date_default_timezone_set('UTC')) {
611
+            throw new \RuntimeException('Could not set timezone to UTC');
612
+        };
613
+
614
+        //try to configure php to enable big file uploads.
615
+        //this doesn´t work always depending on the webserver and php configuration.
616
+        //Let´s try to overwrite some defaults anyway
617
+
618
+        //try to set the maximum execution time to 60min
619
+        if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
620
+            @set_time_limit(3600);
621
+        }
622
+        @ini_set('max_execution_time', 3600);
623
+        @ini_set('max_input_time', 3600);
624
+
625
+        //try to set the maximum filesize to 10G
626
+        @ini_set('upload_max_filesize', '10G');
627
+        @ini_set('post_max_size', '10G');
628
+        @ini_set('file_uploads', '50');
629
+
630
+        self::setRequiredIniValues();
631
+        self::handleAuthHeaders();
632
+        self::registerAutoloaderCache();
633
+
634
+        // initialize intl fallback is necessary
635
+        \Patchwork\Utf8\Bootup::initIntl();
636
+        OC_Util::isSetLocaleWorking();
637
+
638
+        if (!defined('PHPUNIT_RUN')) {
639
+            OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
640
+            $debug = \OC::$server->getConfig()->getSystemValue('debug', false);
641
+            OC\Log\ErrorHandler::register($debug);
642
+        }
643
+
644
+        \OC::$server->getEventLogger()->start('init_session', 'Initialize session');
645
+        OC_App::loadApps(array('session'));
646
+        if (!self::$CLI) {
647
+            self::initSession();
648
+        }
649
+        \OC::$server->getEventLogger()->end('init_session');
650
+        self::checkConfig();
651
+        self::checkInstalled();
652
+
653
+        OC_Response::addSecurityHeaders();
654
+        if(self::$server->getRequest()->getServerProtocol() === 'https') {
655
+            ini_set('session.cookie_secure', true);
656
+        }
657
+
658
+        self::performSameSiteCookieProtection();
659
+
660
+        if (!defined('OC_CONSOLE')) {
661
+            $errors = OC_Util::checkServer(\OC::$server->getSystemConfig());
662
+            if (count($errors) > 0) {
663
+                if (self::$CLI) {
664
+                    // Convert l10n string into regular string for usage in database
665
+                    $staticErrors = [];
666
+                    foreach ($errors as $error) {
667
+                        echo $error['error'] . "\n";
668
+                        echo $error['hint'] . "\n\n";
669
+                        $staticErrors[] = [
670
+                            'error' => (string)$error['error'],
671
+                            'hint' => (string)$error['hint'],
672
+                        ];
673
+                    }
674
+
675
+                    try {
676
+                        \OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
677
+                    } catch (\Exception $e) {
678
+                        echo('Writing to database failed');
679
+                    }
680
+                    exit(1);
681
+                } else {
682
+                    OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE);
683
+                    OC_Util::addStyle('guest');
684
+                    OC_Template::printGuestPage('', 'error', array('errors' => $errors));
685
+                    exit;
686
+                }
687
+            } elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
688
+                \OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
689
+            }
690
+        }
691
+        //try to set the session lifetime
692
+        $sessionLifeTime = self::getSessionLifeTime();
693
+        @ini_set('gc_maxlifetime', (string)$sessionLifeTime);
694
+
695
+        $systemConfig = \OC::$server->getSystemConfig();
696
+
697
+        // User and Groups
698
+        if (!$systemConfig->getValue("installed", false)) {
699
+            self::$server->getSession()->set('user_id', '');
700
+        }
701
+
702
+        OC_User::useBackend(new \OC\User\Database());
703
+        \OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
704
+
705
+        // Subscribe to the hook
706
+        \OCP\Util::connectHook(
707
+            '\OCA\Files_Sharing\API\Server2Server',
708
+            'preLoginNameUsedAsUserName',
709
+            '\OC\User\Database',
710
+            'preLoginNameUsedAsUserName'
711
+        );
712
+
713
+        //setup extra user backends
714
+        if (!self::checkUpgrade(false)) {
715
+            OC_User::setupBackends();
716
+        } else {
717
+            // Run upgrades in incognito mode
718
+            OC_User::setIncognitoMode(true);
719
+        }
720
+
721
+        self::registerCacheHooks();
722
+        self::registerFilesystemHooks();
723
+        self::registerShareHooks();
724
+        self::registerLogRotate();
725
+        self::registerEncryptionWrapper();
726
+        self::registerEncryptionHooks();
727
+        self::registerAccountHooks();
728
+        self::registerSettingsHooks();
729
+
730
+        $settings = new \OC\Settings\Application();
731
+        $settings->register();
732
+
733
+        //make sure temporary files are cleaned up
734
+        $tmpManager = \OC::$server->getTempManager();
735
+        register_shutdown_function(array($tmpManager, 'clean'));
736
+        $lockProvider = \OC::$server->getLockingProvider();
737
+        register_shutdown_function(array($lockProvider, 'releaseAll'));
738
+
739
+        // Check whether the sample configuration has been copied
740
+        if($systemConfig->getValue('copied_sample_config', false)) {
741
+            $l = \OC::$server->getL10N('lib');
742
+            header('HTTP/1.1 503 Service Temporarily Unavailable');
743
+            header('Status: 503 Service Temporarily Unavailable');
744
+            OC_Template::printErrorPage(
745
+                $l->t('Sample configuration detected'),
746
+                $l->t('It has been detected that the sample configuration has been copied. This can break your installation and is unsupported. Please read the documentation before performing changes on config.php')
747
+            );
748
+            return;
749
+        }
750
+
751
+        $request = \OC::$server->getRequest();
752
+        $host = $request->getInsecureServerHost();
753
+        /**
754
+         * if the host passed in headers isn't trusted
755
+         * FIXME: Should not be in here at all :see_no_evil:
756
+         */
757
+        if (!OC::$CLI
758
+            // overwritehost is always trusted, workaround to not have to make
759
+            // \OC\AppFramework\Http\Request::getOverwriteHost public
760
+            && self::$server->getConfig()->getSystemValue('overwritehost') === ''
761
+            && !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
762
+            && self::$server->getConfig()->getSystemValue('installed', false)
763
+        ) {
764
+            // Allow access to CSS resources
765
+            $isScssRequest = false;
766
+            if(strpos($request->getPathInfo(), '/css/') === 0) {
767
+                $isScssRequest = true;
768
+            }
769
+
770
+            if (!$isScssRequest) {
771
+                header('HTTP/1.1 400 Bad Request');
772
+                header('Status: 400 Bad Request');
773
+
774
+                \OC::$server->getLogger()->warning(
775
+                    'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
776
+                    [
777
+                        'app' => 'core',
778
+                        'remoteAddress' => $request->getRemoteAddress(),
779
+                        'host' => $host,
780
+                    ]
781
+                );
782
+
783
+                $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
784
+                $tmpl->assign('domain', $host);
785
+                $tmpl->printPage();
786
+
787
+                exit();
788
+            }
789
+        }
790
+        \OC::$server->getEventLogger()->end('boot');
791
+    }
792
+
793
+    /**
794
+     * register hooks for the cache
795
+     */
796
+    public static function registerCacheHooks() {
797
+        //don't try to do this before we are properly setup
798
+        if (\OC::$server->getSystemConfig()->getValue('installed', false) && !self::checkUpgrade(false)) {
799
+
800
+            // NOTE: This will be replaced to use OCP
801
+            $userSession = self::$server->getUserSession();
802
+            $userSession->listen('\OC\User', 'postLogin', function () {
803
+                try {
804
+                    $cache = new \OC\Cache\File();
805
+                    $cache->gc();
806
+                } catch (\OC\ServerNotAvailableException $e) {
807
+                    // not a GC exception, pass it on
808
+                    throw $e;
809
+                } catch (\Exception $e) {
810
+                    // a GC exception should not prevent users from using OC,
811
+                    // so log the exception
812
+                    \OC::$server->getLogger()->warning('Exception when running cache gc: ' . $e->getMessage(), array('app' => 'core'));
813
+                }
814
+            });
815
+        }
816
+    }
817
+
818
+    public static function registerSettingsHooks() {
819
+        $dispatcher = \OC::$server->getEventDispatcher();
820
+        $dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_DISABLE, function($event) {
821
+            /** @var \OCP\App\ManagerEvent $event */
822
+            \OC::$server->getSettingsManager()->onAppDisabled($event->getAppID());
823
+        });
824
+        $dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_UPDATE, function($event) {
825
+            /** @var \OCP\App\ManagerEvent $event */
826
+            $jobList = \OC::$server->getJobList();
827
+            $job = 'OC\\Settings\\RemoveOrphaned';
828
+            if(!($jobList->has($job, null))) {
829
+                $jobList->add($job);
830
+            }
831
+        });
832
+    }
833
+
834
+    private static function registerEncryptionWrapper() {
835
+        $manager = self::$server->getEncryptionManager();
836
+        \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
837
+    }
838
+
839
+    private static function registerEncryptionHooks() {
840
+        $enabled = self::$server->getEncryptionManager()->isEnabled();
841
+        if ($enabled) {
842
+            \OCP\Util::connectHook('OCP\Share', 'post_shared', 'OC\Encryption\HookManager', 'postShared');
843
+            \OCP\Util::connectHook('OCP\Share', 'post_unshare', 'OC\Encryption\HookManager', 'postUnshared');
844
+            \OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OC\Encryption\HookManager', 'postRename');
845
+            \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', 'OC\Encryption\HookManager', 'postRestore');
846
+        }
847
+    }
848
+
849
+    private static function registerAccountHooks() {
850
+        $hookHandler = new \OC\Accounts\Hooks(\OC::$server->getLogger());
851
+        \OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
852
+    }
853
+
854
+    /**
855
+     * register hooks for the cache
856
+     */
857
+    public static function registerLogRotate() {
858
+        $systemConfig = \OC::$server->getSystemConfig();
859
+        if ($systemConfig->getValue('installed', false) && $systemConfig->getValue('log_rotate_size', false) && !self::checkUpgrade(false)) {
860
+            //don't try to do this before we are properly setup
861
+            //use custom logfile path if defined, otherwise use default of nextcloud.log in data directory
862
+            \OC::$server->getJobList()->add('OC\Log\Rotate');
863
+        }
864
+    }
865
+
866
+    /**
867
+     * register hooks for the filesystem
868
+     */
869
+    public static function registerFilesystemHooks() {
870
+        // Check for blacklisted files
871
+        OC_Hook::connect('OC_Filesystem', 'write', 'OC\Files\Filesystem', 'isBlacklisted');
872
+        OC_Hook::connect('OC_Filesystem', 'rename', 'OC\Files\Filesystem', 'isBlacklisted');
873
+    }
874
+
875
+    /**
876
+     * register hooks for sharing
877
+     */
878
+    public static function registerShareHooks() {
879
+        if (\OC::$server->getSystemConfig()->getValue('installed')) {
880
+            OC_Hook::connect('OC_User', 'post_deleteUser', 'OC\Share20\Hooks', 'post_deleteUser');
881
+            OC_Hook::connect('OC_User', 'post_removeFromGroup', 'OC\Share20\Hooks', 'post_removeFromGroup');
882
+            OC_Hook::connect('OC_User', 'post_deleteGroup', 'OC\Share20\Hooks', 'post_deleteGroup');
883
+        }
884
+    }
885
+
886
+    protected static function registerAutoloaderCache() {
887
+        // The class loader takes an optional low-latency cache, which MUST be
888
+        // namespaced. The instanceid is used for namespacing, but might be
889
+        // unavailable at this point. Furthermore, it might not be possible to
890
+        // generate an instanceid via \OC_Util::getInstanceId() because the
891
+        // config file may not be writable. As such, we only register a class
892
+        // loader cache if instanceid is available without trying to create one.
893
+        $instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
894
+        if ($instanceId) {
895
+            try {
896
+                $memcacheFactory = \OC::$server->getMemCacheFactory();
897
+                self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
898
+            } catch (\Exception $ex) {
899
+            }
900
+        }
901
+    }
902
+
903
+    /**
904
+     * Handle the request
905
+     */
906
+    public static function handleRequest() {
907
+
908
+        \OC::$server->getEventLogger()->start('handle_request', 'Handle request');
909
+        $systemConfig = \OC::$server->getSystemConfig();
910
+        // load all the classpaths from the enabled apps so they are available
911
+        // in the routing files of each app
912
+        OC::loadAppClassPaths();
913
+
914
+        // Check if Nextcloud is installed or in maintenance (update) mode
915
+        if (!$systemConfig->getValue('installed', false)) {
916
+            \OC::$server->getSession()->clear();
917
+            $setupHelper = new OC\Setup(\OC::$server->getSystemConfig(), \OC::$server->getIniWrapper(),
918
+                \OC::$server->getL10N('lib'), \OC::$server->query(\OCP\Defaults::class), \OC::$server->getLogger(),
919
+                \OC::$server->getSecureRandom());
920
+            $controller = new OC\Core\Controller\SetupController($setupHelper);
921
+            $controller->run($_POST);
922
+            exit();
923
+        }
924
+
925
+        $request = \OC::$server->getRequest();
926
+        $requestPath = $request->getRawPathInfo();
927
+        if ($requestPath === '/heartbeat') {
928
+            return;
929
+        }
930
+        if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
931
+            self::checkMaintenanceMode();
932
+            self::checkUpgrade();
933
+        }
934
+
935
+        // emergency app disabling
936
+        if ($requestPath === '/disableapp'
937
+            && $request->getMethod() === 'POST'
938
+            && ((string)$request->getParam('appid')) !== ''
939
+        ) {
940
+            \OCP\JSON::callCheck();
941
+            \OCP\JSON::checkAdminUser();
942
+            $appId = (string)$request->getParam('appid');
943
+            $appId = \OC_App::cleanAppId($appId);
944
+
945
+            \OC_App::disable($appId);
946
+            \OC_JSON::success();
947
+            exit();
948
+        }
949
+
950
+        // Always load authentication apps
951
+        OC_App::loadApps(['authentication']);
952
+
953
+        // Load minimum set of apps
954
+        if (!self::checkUpgrade(false)
955
+            && !$systemConfig->getValue('maintenance', false)) {
956
+            // For logged-in users: Load everything
957
+            if(\OC::$server->getUserSession()->isLoggedIn()) {
958
+                OC_App::loadApps();
959
+            } else {
960
+                // For guests: Load only filesystem and logging
961
+                OC_App::loadApps(array('filesystem', 'logging'));
962
+                self::handleLogin($request);
963
+            }
964
+        }
965
+
966
+        if (!self::$CLI) {
967
+            try {
968
+                if (!$systemConfig->getValue('maintenance', false) && !self::checkUpgrade(false)) {
969
+                    OC_App::loadApps(array('filesystem', 'logging'));
970
+                    OC_App::loadApps();
971
+                }
972
+                OC_Util::setupFS();
973
+                OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
974
+                return;
975
+            } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
976
+                //header('HTTP/1.0 404 Not Found');
977
+            } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
978
+                OC_Response::setStatus(405);
979
+                return;
980
+            }
981
+        }
982
+
983
+        // Handle WebDAV
984
+        if ($_SERVER['REQUEST_METHOD'] == 'PROPFIND') {
985
+            // not allowed any more to prevent people
986
+            // mounting this root directly.
987
+            // Users need to mount remote.php/webdav instead.
988
+            header('HTTP/1.1 405 Method Not Allowed');
989
+            header('Status: 405 Method Not Allowed');
990
+            return;
991
+        }
992
+
993
+        // Someone is logged in
994
+        if (\OC::$server->getUserSession()->isLoggedIn()) {
995
+            OC_App::loadApps();
996
+            OC_User::setupBackends();
997
+            OC_Util::setupFS();
998
+            // FIXME
999
+            // Redirect to default application
1000
+            OC_Util::redirectToDefaultPage();
1001
+        } else {
1002
+            // Not handled and not logged in
1003
+            header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1004
+        }
1005
+    }
1006
+
1007
+    /**
1008
+     * Check login: apache auth, auth token, basic auth
1009
+     *
1010
+     * @param OCP\IRequest $request
1011
+     * @return boolean
1012
+     */
1013
+    static function handleLogin(OCP\IRequest $request) {
1014
+        $userSession = self::$server->getUserSession();
1015
+        if (OC_User::handleApacheAuth()) {
1016
+            return true;
1017
+        }
1018
+        if ($userSession->tryTokenLogin($request)) {
1019
+            return true;
1020
+        }
1021
+        if (isset($_COOKIE['nc_username'])
1022
+            && isset($_COOKIE['nc_token'])
1023
+            && isset($_COOKIE['nc_session_id'])
1024
+            && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1025
+            return true;
1026
+        }
1027
+        if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1028
+            return true;
1029
+        }
1030
+        return false;
1031
+    }
1032
+
1033
+    protected static function handleAuthHeaders() {
1034
+        //copy http auth headers for apache+php-fcgid work around
1035
+        if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1036
+            $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1037
+        }
1038
+
1039
+        // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1040
+        $vars = array(
1041
+            'HTTP_AUTHORIZATION', // apache+php-cgi work around
1042
+            'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1043
+        );
1044
+        foreach ($vars as $var) {
1045
+            if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1046
+                list($name, $password) = explode(':', base64_decode($matches[1]), 2);
1047
+                $_SERVER['PHP_AUTH_USER'] = $name;
1048
+                $_SERVER['PHP_AUTH_PW'] = $password;
1049
+                break;
1050
+            }
1051
+        }
1052
+    }
1053 1053
 }
1054 1054
 
1055 1055
 OC::init();
Please login to merge, or discard this patch.
settings/Activity/Provider.php 2 patches
Indentation   +144 added lines, -144 removed lines patch added patch discarded remove patch
@@ -31,148 +31,148 @@
 block discarded – undo
31 31
 
32 32
 class Provider implements IProvider {
33 33
 
34
-	const PASSWORD_CHANGED_BY = 'password_changed_by';
35
-	const PASSWORD_CHANGED_SELF = 'password_changed_self';
36
-	const PASSWORD_RESET = 'password_changed';
37
-	const EMAIL_CHANGED_BY = 'email_changed_by';
38
-	const EMAIL_CHANGED_SELF = 'email_changed_self';
39
-	const EMAIL_CHANGED = 'email_changed';
40
-
41
-	/** @var IFactory */
42
-	protected $languageFactory;
43
-
44
-	/** @var IL10N */
45
-	protected $l;
46
-
47
-	/** @var IURLGenerator */
48
-	protected $url;
49
-
50
-	/** @var IUserManager */
51
-	protected $userManager;
52
-
53
-	/** @var string[] cached displayNames - key is the UID and value the displayname */
54
-	protected $displayNames = [];
55
-
56
-	/**
57
-	 * @param IFactory $languageFactory
58
-	 * @param IURLGenerator $url
59
-	 * @param IUserManager $userManager
60
-	 */
61
-	public function __construct(IFactory $languageFactory, IURLGenerator $url, IUserManager $userManager) {
62
-		$this->languageFactory = $languageFactory;
63
-		$this->url = $url;
64
-		$this->userManager = $userManager;
65
-	}
66
-
67
-	/**
68
-	 * @param string $language
69
-	 * @param IEvent $event
70
-	 * @param IEvent|null $previousEvent
71
-	 * @return IEvent
72
-	 * @throws \InvalidArgumentException
73
-	 * @since 11.0.0
74
-	 */
75
-	public function parse($language, IEvent $event, IEvent $previousEvent = null) {
76
-		if ($event->getApp() !== 'settings') {
77
-			throw new \InvalidArgumentException();
78
-		}
79
-
80
-		$this->l = $this->languageFactory->get('settings', $language);
81
-
82
-		$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('settings', 'personal.svg')));
83
-
84
-		if ($event->getSubject() === self::PASSWORD_CHANGED_BY) {
85
-			$subject = $this->l->t('{actor} changed your password');
86
-		} else if ($event->getSubject() === self::PASSWORD_CHANGED_SELF) {
87
-			$subject = $this->l->t('You changed your password');
88
-		} else if ($event->getSubject() === self::PASSWORD_RESET) {
89
-			$subject = $this->l->t('Your password was reset by an administrator');
90
-
91
-		} else if ($event->getSubject() === self::EMAIL_CHANGED_BY) {
92
-			$subject = $this->l->t('{actor} changed your email');
93
-		} else if ($event->getSubject() === self::EMAIL_CHANGED_SELF) {
94
-			$subject = $this->l->t('You changed your email');
95
-		} else if ($event->getSubject() === self::EMAIL_CHANGED) {
96
-			$subject = $this->l->t('Your email was changed by an administrator');
97
-
98
-		} else {
99
-			throw new \InvalidArgumentException();
100
-		}
101
-
102
-		$parsedParameters = $this->getParameters($event);
103
-		$this->setSubjects($event, $subject, $parsedParameters);
104
-
105
-		return $event;
106
-	}
107
-
108
-	/**
109
-	 * @param IEvent $event
110
-	 * @return array
111
-	 * @throws \InvalidArgumentException
112
-	 */
113
-	protected function getParameters(IEvent $event) {
114
-		$subject = $event->getSubject();
115
-		$parameters = $event->getSubjectParameters();
116
-
117
-		switch ($subject) {
118
-			case self::PASSWORD_CHANGED_SELF:
119
-			case self::PASSWORD_RESET:
120
-			case self::EMAIL_CHANGED_SELF:
121
-			case self::EMAIL_CHANGED:
122
-				return [];
123
-			case self::PASSWORD_CHANGED_BY:
124
-			case self::EMAIL_CHANGED_BY:
125
-				return [
126
-					'actor' => $this->generateUserParameter($parameters[0]),
127
-				];
128
-		}
129
-
130
-		throw new \InvalidArgumentException();
131
-	}
132
-
133
-	/**
134
-	 * @param IEvent $event
135
-	 * @param string $subject
136
-	 * @param array $parameters
137
-	 * @throws \InvalidArgumentException
138
-	 */
139
-	protected function setSubjects(IEvent $event, $subject, array $parameters) {
140
-		$placeholders = $replacements = [];
141
-		foreach ($parameters as $placeholder => $parameter) {
142
-			$placeholders[] = '{' . $placeholder . '}';
143
-			$replacements[] = $parameter['name'];
144
-		}
145
-
146
-		$event->setParsedSubject(str_replace($placeholders, $replacements, $subject))
147
-			->setRichSubject($subject, $parameters);
148
-	}
149
-
150
-	/**
151
-	 * @param string $uid
152
-	 * @return array
153
-	 */
154
-	protected function generateUserParameter($uid) {
155
-		if (!isset($this->displayNames[$uid])) {
156
-			$this->displayNames[$uid] = $this->getDisplayName($uid);
157
-		}
158
-
159
-		return [
160
-			'type' => 'user',
161
-			'id' => $uid,
162
-			'name' => $this->displayNames[$uid],
163
-		];
164
-	}
165
-
166
-	/**
167
-	 * @param string $uid
168
-	 * @return string
169
-	 */
170
-	protected function getDisplayName($uid) {
171
-		$user = $this->userManager->get($uid);
172
-		if ($user instanceof IUser) {
173
-			return $user->getDisplayName();
174
-		}
175
-
176
-		return $uid;
177
-	}
34
+    const PASSWORD_CHANGED_BY = 'password_changed_by';
35
+    const PASSWORD_CHANGED_SELF = 'password_changed_self';
36
+    const PASSWORD_RESET = 'password_changed';
37
+    const EMAIL_CHANGED_BY = 'email_changed_by';
38
+    const EMAIL_CHANGED_SELF = 'email_changed_self';
39
+    const EMAIL_CHANGED = 'email_changed';
40
+
41
+    /** @var IFactory */
42
+    protected $languageFactory;
43
+
44
+    /** @var IL10N */
45
+    protected $l;
46
+
47
+    /** @var IURLGenerator */
48
+    protected $url;
49
+
50
+    /** @var IUserManager */
51
+    protected $userManager;
52
+
53
+    /** @var string[] cached displayNames - key is the UID and value the displayname */
54
+    protected $displayNames = [];
55
+
56
+    /**
57
+     * @param IFactory $languageFactory
58
+     * @param IURLGenerator $url
59
+     * @param IUserManager $userManager
60
+     */
61
+    public function __construct(IFactory $languageFactory, IURLGenerator $url, IUserManager $userManager) {
62
+        $this->languageFactory = $languageFactory;
63
+        $this->url = $url;
64
+        $this->userManager = $userManager;
65
+    }
66
+
67
+    /**
68
+     * @param string $language
69
+     * @param IEvent $event
70
+     * @param IEvent|null $previousEvent
71
+     * @return IEvent
72
+     * @throws \InvalidArgumentException
73
+     * @since 11.0.0
74
+     */
75
+    public function parse($language, IEvent $event, IEvent $previousEvent = null) {
76
+        if ($event->getApp() !== 'settings') {
77
+            throw new \InvalidArgumentException();
78
+        }
79
+
80
+        $this->l = $this->languageFactory->get('settings', $language);
81
+
82
+        $event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('settings', 'personal.svg')));
83
+
84
+        if ($event->getSubject() === self::PASSWORD_CHANGED_BY) {
85
+            $subject = $this->l->t('{actor} changed your password');
86
+        } else if ($event->getSubject() === self::PASSWORD_CHANGED_SELF) {
87
+            $subject = $this->l->t('You changed your password');
88
+        } else if ($event->getSubject() === self::PASSWORD_RESET) {
89
+            $subject = $this->l->t('Your password was reset by an administrator');
90
+
91
+        } else if ($event->getSubject() === self::EMAIL_CHANGED_BY) {
92
+            $subject = $this->l->t('{actor} changed your email');
93
+        } else if ($event->getSubject() === self::EMAIL_CHANGED_SELF) {
94
+            $subject = $this->l->t('You changed your email');
95
+        } else if ($event->getSubject() === self::EMAIL_CHANGED) {
96
+            $subject = $this->l->t('Your email was changed by an administrator');
97
+
98
+        } else {
99
+            throw new \InvalidArgumentException();
100
+        }
101
+
102
+        $parsedParameters = $this->getParameters($event);
103
+        $this->setSubjects($event, $subject, $parsedParameters);
104
+
105
+        return $event;
106
+    }
107
+
108
+    /**
109
+     * @param IEvent $event
110
+     * @return array
111
+     * @throws \InvalidArgumentException
112
+     */
113
+    protected function getParameters(IEvent $event) {
114
+        $subject = $event->getSubject();
115
+        $parameters = $event->getSubjectParameters();
116
+
117
+        switch ($subject) {
118
+            case self::PASSWORD_CHANGED_SELF:
119
+            case self::PASSWORD_RESET:
120
+            case self::EMAIL_CHANGED_SELF:
121
+            case self::EMAIL_CHANGED:
122
+                return [];
123
+            case self::PASSWORD_CHANGED_BY:
124
+            case self::EMAIL_CHANGED_BY:
125
+                return [
126
+                    'actor' => $this->generateUserParameter($parameters[0]),
127
+                ];
128
+        }
129
+
130
+        throw new \InvalidArgumentException();
131
+    }
132
+
133
+    /**
134
+     * @param IEvent $event
135
+     * @param string $subject
136
+     * @param array $parameters
137
+     * @throws \InvalidArgumentException
138
+     */
139
+    protected function setSubjects(IEvent $event, $subject, array $parameters) {
140
+        $placeholders = $replacements = [];
141
+        foreach ($parameters as $placeholder => $parameter) {
142
+            $placeholders[] = '{' . $placeholder . '}';
143
+            $replacements[] = $parameter['name'];
144
+        }
145
+
146
+        $event->setParsedSubject(str_replace($placeholders, $replacements, $subject))
147
+            ->setRichSubject($subject, $parameters);
148
+    }
149
+
150
+    /**
151
+     * @param string $uid
152
+     * @return array
153
+     */
154
+    protected function generateUserParameter($uid) {
155
+        if (!isset($this->displayNames[$uid])) {
156
+            $this->displayNames[$uid] = $this->getDisplayName($uid);
157
+        }
158
+
159
+        return [
160
+            'type' => 'user',
161
+            'id' => $uid,
162
+            'name' => $this->displayNames[$uid],
163
+        ];
164
+    }
165
+
166
+    /**
167
+     * @param string $uid
168
+     * @return string
169
+     */
170
+    protected function getDisplayName($uid) {
171
+        $user = $this->userManager->get($uid);
172
+        if ($user instanceof IUser) {
173
+            return $user->getDisplayName();
174
+        }
175
+
176
+        return $uid;
177
+    }
178 178
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -49,7 +49,7 @@
 block discarded – undo
49 49
 	protected function setSubjects(IEvent $event, $subject, array $parameters) {
50 50
 		$placeholders = $replacements = [];
51 51
 		foreach ($parameters as $placeholder => $parameter) {
52
-			$placeholders[] = '{' . $placeholder . '}';
52
+			$placeholders[] = '{'.$placeholder.'}';
53 53
 			$replacements[] = $parameter['name'];
54 54
 		}
55 55
 
Please login to merge, or discard this patch.
lib/private/User/User.php 3 patches
Doc Comments   +5 added lines patch added patch discarded remove patch
@@ -436,6 +436,11 @@
 block discarded – undo
436 436
 		return $url;
437 437
 	}
438 438
 
439
+	/**
440
+	 * @param string $feature
441
+	 * @param string $value
442
+	 * @param string $oldValue
443
+	 */
439 444
 	public function triggerChange($feature, $value = null, $oldValue = null) {
440 445
 		if ($this->emitter) {
441 446
 			$this->emitter->emit('\OC\User', 'changeUser', array($this, $feature, $value, $oldValue));
Please login to merge, or discard this patch.
Indentation   +399 added lines, -399 removed lines patch added patch discarded remove patch
@@ -42,403 +42,403 @@
 block discarded – undo
42 42
 use \OCP\IUserBackend;
43 43
 
44 44
 class User implements IUser {
45
-	/** @var string $uid */
46
-	private $uid;
47
-
48
-	/** @var string $displayName */
49
-	private $displayName;
50
-
51
-	/** @var UserInterface $backend */
52
-	private $backend;
53
-
54
-	/** @var bool $enabled */
55
-	private $enabled;
56
-
57
-	/** @var Emitter|Manager $emitter */
58
-	private $emitter;
59
-
60
-	/** @var string $home */
61
-	private $home;
62
-
63
-	/** @var int $lastLogin */
64
-	private $lastLogin;
65
-
66
-	/** @var \OCP\IConfig $config */
67
-	private $config;
68
-
69
-	/** @var IAvatarManager */
70
-	private $avatarManager;
71
-
72
-	/** @var IURLGenerator */
73
-	private $urlGenerator;
74
-
75
-	/**
76
-	 * @param string $uid
77
-	 * @param UserInterface $backend
78
-	 * @param \OC\Hooks\Emitter $emitter
79
-	 * @param IConfig|null $config
80
-	 * @param IURLGenerator $urlGenerator
81
-	 */
82
-	public function __construct($uid, $backend, $emitter = null, IConfig $config = null, $urlGenerator = null) {
83
-		$this->uid = $uid;
84
-		$this->backend = $backend;
85
-		$this->emitter = $emitter;
86
-		if(is_null($config)) {
87
-			$config = \OC::$server->getConfig();
88
-		}
89
-		$this->config = $config;
90
-		$this->urlGenerator = $urlGenerator;
91
-		$enabled = $this->config->getUserValue($uid, 'core', 'enabled', 'true');
92
-		$this->enabled = ($enabled === 'true');
93
-		$this->lastLogin = $this->config->getUserValue($uid, 'login', 'lastLogin', 0);
94
-		if (is_null($this->urlGenerator)) {
95
-			$this->urlGenerator = \OC::$server->getURLGenerator();
96
-		}
97
-	}
98
-
99
-	/**
100
-	 * get the user id
101
-	 *
102
-	 * @return string
103
-	 */
104
-	public function getUID() {
105
-		return $this->uid;
106
-	}
107
-
108
-	/**
109
-	 * get the display name for the user, if no specific display name is set it will fallback to the user id
110
-	 *
111
-	 * @return string
112
-	 */
113
-	public function getDisplayName() {
114
-		if (!isset($this->displayName)) {
115
-			$displayName = '';
116
-			if ($this->backend and $this->backend->implementsActions(Backend::GET_DISPLAYNAME)) {
117
-				// get display name and strip whitespace from the beginning and end of it
118
-				$backendDisplayName = $this->backend->getDisplayName($this->uid);
119
-				if (is_string($backendDisplayName)) {
120
-					$displayName = trim($backendDisplayName);
121
-				}
122
-			}
123
-
124
-			if (!empty($displayName)) {
125
-				$this->displayName = $displayName;
126
-			} else {
127
-				$this->displayName = $this->uid;
128
-			}
129
-		}
130
-		return $this->displayName;
131
-	}
132
-
133
-	/**
134
-	 * set the displayname for the user
135
-	 *
136
-	 * @param string $displayName
137
-	 * @return bool
138
-	 */
139
-	public function setDisplayName($displayName) {
140
-		$displayName = trim($displayName);
141
-		if ($this->backend->implementsActions(Backend::SET_DISPLAYNAME) && !empty($displayName)) {
142
-			$result = $this->backend->setDisplayName($this->uid, $displayName);
143
-			if ($result) {
144
-				$this->displayName = $displayName;
145
-				$this->triggerChange('displayName', $displayName);
146
-			}
147
-			return $result !== false;
148
-		} else {
149
-			return false;
150
-		}
151
-	}
152
-
153
-	/**
154
-	 * set the email address of the user
155
-	 *
156
-	 * @param string|null $mailAddress
157
-	 * @return void
158
-	 * @since 9.0.0
159
-	 */
160
-	public function setEMailAddress($mailAddress) {
161
-		$oldMailAddress = $this->getEMailAddress();
162
-		if($mailAddress === '') {
163
-			$this->config->deleteUserValue($this->uid, 'settings', 'email');
164
-		} else {
165
-			$this->config->setUserValue($this->uid, 'settings', 'email', $mailAddress);
166
-		}
167
-		$this->triggerChange('eMailAddress', $mailAddress, $oldMailAddress);
168
-	}
169
-
170
-	/**
171
-	 * returns the timestamp of the user's last login or 0 if the user did never
172
-	 * login
173
-	 *
174
-	 * @return int
175
-	 */
176
-	public function getLastLogin() {
177
-		return $this->lastLogin;
178
-	}
179
-
180
-	/**
181
-	 * updates the timestamp of the most recent login of this user
182
-	 */
183
-	public function updateLastLoginTimestamp() {
184
-		$firstTimeLogin = ($this->lastLogin === 0);
185
-		$this->lastLogin = time();
186
-		$this->config->setUserValue(
187
-			$this->uid, 'login', 'lastLogin', $this->lastLogin);
188
-
189
-		return $firstTimeLogin;
190
-	}
191
-
192
-	/**
193
-	 * Delete the user
194
-	 *
195
-	 * @return bool
196
-	 */
197
-	public function delete() {
198
-		if ($this->emitter) {
199
-			$this->emitter->emit('\OC\User', 'preDelete', array($this));
200
-		}
201
-		// get the home now because it won't return it after user deletion
202
-		$homePath = $this->getHome();
203
-		$result = $this->backend->deleteUser($this->uid);
204
-		if ($result) {
205
-
206
-			// FIXME: Feels like an hack - suggestions?
207
-
208
-			$groupManager = \OC::$server->getGroupManager();
209
-			// We have to delete the user from all groups
210
-			foreach ($groupManager->getUserGroupIds($this) as $groupId) {
211
-				$group = $groupManager->get($groupId);
212
-				if ($group) {
213
-					\OC_Hook::emit("OC_Group", "pre_removeFromGroup", ["run" => true, "uid" => $this->uid, "gid" => $groupId]);
214
-					$group->removeUser($this);
215
-					\OC_Hook::emit("OC_User", "post_removeFromGroup", ["uid" => $this->uid, "gid" => $groupId]);
216
-				}
217
-			}
218
-			// Delete the user's keys in preferences
219
-			\OC::$server->getConfig()->deleteAllUserValues($this->uid);
220
-
221
-			// Delete user files in /data/
222
-			if ($homePath !== false) {
223
-				// FIXME: this operates directly on FS, should use View instead...
224
-				// also this is not testable/mockable...
225
-				\OC_Helper::rmdirr($homePath);
226
-			}
227
-
228
-			// Delete the users entry in the storage table
229
-			Storage::remove('home::' . $this->uid);
230
-
231
-			\OC::$server->getCommentsManager()->deleteReferencesOfActor('users', $this->uid);
232
-			\OC::$server->getCommentsManager()->deleteReadMarksFromUser($this);
233
-
234
-			$notification = \OC::$server->getNotificationManager()->createNotification();
235
-			$notification->setUser($this->uid);
236
-			\OC::$server->getNotificationManager()->markProcessed($notification);
237
-
238
-			if ($this->emitter) {
239
-				$this->emitter->emit('\OC\User', 'postDelete', array($this));
240
-			}
241
-		}
242
-		return !($result === false);
243
-	}
244
-
245
-	/**
246
-	 * Set the password of the user
247
-	 *
248
-	 * @param string $password
249
-	 * @param string $recoveryPassword for the encryption app to reset encryption keys
250
-	 * @return bool
251
-	 */
252
-	public function setPassword($password, $recoveryPassword = null) {
253
-		if ($this->emitter) {
254
-			$this->emitter->emit('\OC\User', 'preSetPassword', array($this, $password, $recoveryPassword));
255
-		}
256
-		if ($this->backend->implementsActions(Backend::SET_PASSWORD)) {
257
-			$result = $this->backend->setPassword($this->uid, $password);
258
-			if ($this->emitter) {
259
-				$this->emitter->emit('\OC\User', 'postSetPassword', array($this, $password, $recoveryPassword));
260
-			}
261
-			return !($result === false);
262
-		} else {
263
-			return false;
264
-		}
265
-	}
266
-
267
-	/**
268
-	 * get the users home folder to mount
269
-	 *
270
-	 * @return string
271
-	 */
272
-	public function getHome() {
273
-		if (!$this->home) {
274
-			if ($this->backend->implementsActions(Backend::GET_HOME) and $home = $this->backend->getHome($this->uid)) {
275
-				$this->home = $home;
276
-			} elseif ($this->config) {
277
-				$this->home = $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/' . $this->uid;
278
-			} else {
279
-				$this->home = \OC::$SERVERROOT . '/data/' . $this->uid;
280
-			}
281
-		}
282
-		return $this->home;
283
-	}
284
-
285
-	/**
286
-	 * Get the name of the backend class the user is connected with
287
-	 *
288
-	 * @return string
289
-	 */
290
-	public function getBackendClassName() {
291
-		if($this->backend instanceof IUserBackend) {
292
-			return $this->backend->getBackendName();
293
-		}
294
-		return get_class($this->backend);
295
-	}
296
-
297
-	/**
298
-	 * check if the backend allows the user to change his avatar on Personal page
299
-	 *
300
-	 * @return bool
301
-	 */
302
-	public function canChangeAvatar() {
303
-		if ($this->backend->implementsActions(Backend::PROVIDE_AVATAR)) {
304
-			return $this->backend->canChangeAvatar($this->uid);
305
-		}
306
-		return true;
307
-	}
308
-
309
-	/**
310
-	 * check if the backend supports changing passwords
311
-	 *
312
-	 * @return bool
313
-	 */
314
-	public function canChangePassword() {
315
-		return $this->backend->implementsActions(Backend::SET_PASSWORD);
316
-	}
317
-
318
-	/**
319
-	 * check if the backend supports changing display names
320
-	 *
321
-	 * @return bool
322
-	 */
323
-	public function canChangeDisplayName() {
324
-		if ($this->config->getSystemValue('allow_user_to_change_display_name') === false) {
325
-			return false;
326
-		}
327
-		return $this->backend->implementsActions(Backend::SET_DISPLAYNAME);
328
-	}
329
-
330
-	/**
331
-	 * check if the user is enabled
332
-	 *
333
-	 * @return bool
334
-	 */
335
-	public function isEnabled() {
336
-		return $this->enabled;
337
-	}
338
-
339
-	/**
340
-	 * set the enabled status for the user
341
-	 *
342
-	 * @param bool $enabled
343
-	 */
344
-	public function setEnabled($enabled) {
345
-		$this->enabled = $enabled;
346
-		$enabled = ($enabled) ? 'true' : 'false';
347
-		$this->config->setUserValue($this->uid, 'core', 'enabled', $enabled);
348
-	}
349
-
350
-	/**
351
-	 * get the users email address
352
-	 *
353
-	 * @return string|null
354
-	 * @since 9.0.0
355
-	 */
356
-	public function getEMailAddress() {
357
-		return $this->config->getUserValue($this->uid, 'settings', 'email', null);
358
-	}
359
-
360
-	/**
361
-	 * get the users' quota
362
-	 *
363
-	 * @return string
364
-	 * @since 9.0.0
365
-	 */
366
-	public function getQuota() {
367
-		$quota = $this->config->getUserValue($this->uid, 'files', 'quota', 'default');
368
-		if($quota === 'default') {
369
-			$quota = $this->config->getAppValue('files', 'default_quota', 'none');
370
-		}
371
-		return $quota;
372
-	}
373
-
374
-	/**
375
-	 * set the users' quota
376
-	 *
377
-	 * @param string $quota
378
-	 * @return void
379
-	 * @since 9.0.0
380
-	 */
381
-	public function setQuota($quota) {
382
-		if($quota !== 'none' and $quota !== 'default') {
383
-			$quota = OC_Helper::computerFileSize($quota);
384
-			$quota = OC_Helper::humanFileSize($quota);
385
-		}
386
-		$this->config->setUserValue($this->uid, 'files', 'quota', $quota);
387
-		$this->triggerChange('quota', $quota);
388
-	}
389
-
390
-	/**
391
-	 * get the avatar image if it exists
392
-	 *
393
-	 * @param int $size
394
-	 * @return IImage|null
395
-	 * @since 9.0.0
396
-	 */
397
-	public function getAvatarImage($size) {
398
-		// delay the initialization
399
-		if (is_null($this->avatarManager)) {
400
-			$this->avatarManager = \OC::$server->getAvatarManager();
401
-		}
402
-
403
-		$avatar = $this->avatarManager->getAvatar($this->uid);
404
-		$image = $avatar->get(-1);
405
-		if ($image) {
406
-			return $image;
407
-		}
408
-
409
-		return null;
410
-	}
411
-
412
-	/**
413
-	 * get the federation cloud id
414
-	 *
415
-	 * @return string
416
-	 * @since 9.0.0
417
-	 */
418
-	public function getCloudId() {
419
-		$uid = $this->getUID();
420
-		$server = $this->urlGenerator->getAbsoluteURL('/');
421
-		$server =  rtrim( $this->removeProtocolFromUrl($server), '/');
422
-		return \OC::$server->getCloudIdManager()->getCloudId($uid, $server)->getId();
423
-	}
424
-
425
-	/**
426
-	 * @param string $url
427
-	 * @return string
428
-	 */
429
-	private function removeProtocolFromUrl($url) {
430
-		if (strpos($url, 'https://') === 0) {
431
-			return substr($url, strlen('https://'));
432
-		} else if (strpos($url, 'http://') === 0) {
433
-			return substr($url, strlen('http://'));
434
-		}
435
-
436
-		return $url;
437
-	}
438
-
439
-	public function triggerChange($feature, $value = null, $oldValue = null) {
440
-		if ($this->emitter) {
441
-			$this->emitter->emit('\OC\User', 'changeUser', array($this, $feature, $value, $oldValue));
442
-		}
443
-	}
45
+    /** @var string $uid */
46
+    private $uid;
47
+
48
+    /** @var string $displayName */
49
+    private $displayName;
50
+
51
+    /** @var UserInterface $backend */
52
+    private $backend;
53
+
54
+    /** @var bool $enabled */
55
+    private $enabled;
56
+
57
+    /** @var Emitter|Manager $emitter */
58
+    private $emitter;
59
+
60
+    /** @var string $home */
61
+    private $home;
62
+
63
+    /** @var int $lastLogin */
64
+    private $lastLogin;
65
+
66
+    /** @var \OCP\IConfig $config */
67
+    private $config;
68
+
69
+    /** @var IAvatarManager */
70
+    private $avatarManager;
71
+
72
+    /** @var IURLGenerator */
73
+    private $urlGenerator;
74
+
75
+    /**
76
+     * @param string $uid
77
+     * @param UserInterface $backend
78
+     * @param \OC\Hooks\Emitter $emitter
79
+     * @param IConfig|null $config
80
+     * @param IURLGenerator $urlGenerator
81
+     */
82
+    public function __construct($uid, $backend, $emitter = null, IConfig $config = null, $urlGenerator = null) {
83
+        $this->uid = $uid;
84
+        $this->backend = $backend;
85
+        $this->emitter = $emitter;
86
+        if(is_null($config)) {
87
+            $config = \OC::$server->getConfig();
88
+        }
89
+        $this->config = $config;
90
+        $this->urlGenerator = $urlGenerator;
91
+        $enabled = $this->config->getUserValue($uid, 'core', 'enabled', 'true');
92
+        $this->enabled = ($enabled === 'true');
93
+        $this->lastLogin = $this->config->getUserValue($uid, 'login', 'lastLogin', 0);
94
+        if (is_null($this->urlGenerator)) {
95
+            $this->urlGenerator = \OC::$server->getURLGenerator();
96
+        }
97
+    }
98
+
99
+    /**
100
+     * get the user id
101
+     *
102
+     * @return string
103
+     */
104
+    public function getUID() {
105
+        return $this->uid;
106
+    }
107
+
108
+    /**
109
+     * get the display name for the user, if no specific display name is set it will fallback to the user id
110
+     *
111
+     * @return string
112
+     */
113
+    public function getDisplayName() {
114
+        if (!isset($this->displayName)) {
115
+            $displayName = '';
116
+            if ($this->backend and $this->backend->implementsActions(Backend::GET_DISPLAYNAME)) {
117
+                // get display name and strip whitespace from the beginning and end of it
118
+                $backendDisplayName = $this->backend->getDisplayName($this->uid);
119
+                if (is_string($backendDisplayName)) {
120
+                    $displayName = trim($backendDisplayName);
121
+                }
122
+            }
123
+
124
+            if (!empty($displayName)) {
125
+                $this->displayName = $displayName;
126
+            } else {
127
+                $this->displayName = $this->uid;
128
+            }
129
+        }
130
+        return $this->displayName;
131
+    }
132
+
133
+    /**
134
+     * set the displayname for the user
135
+     *
136
+     * @param string $displayName
137
+     * @return bool
138
+     */
139
+    public function setDisplayName($displayName) {
140
+        $displayName = trim($displayName);
141
+        if ($this->backend->implementsActions(Backend::SET_DISPLAYNAME) && !empty($displayName)) {
142
+            $result = $this->backend->setDisplayName($this->uid, $displayName);
143
+            if ($result) {
144
+                $this->displayName = $displayName;
145
+                $this->triggerChange('displayName', $displayName);
146
+            }
147
+            return $result !== false;
148
+        } else {
149
+            return false;
150
+        }
151
+    }
152
+
153
+    /**
154
+     * set the email address of the user
155
+     *
156
+     * @param string|null $mailAddress
157
+     * @return void
158
+     * @since 9.0.0
159
+     */
160
+    public function setEMailAddress($mailAddress) {
161
+        $oldMailAddress = $this->getEMailAddress();
162
+        if($mailAddress === '') {
163
+            $this->config->deleteUserValue($this->uid, 'settings', 'email');
164
+        } else {
165
+            $this->config->setUserValue($this->uid, 'settings', 'email', $mailAddress);
166
+        }
167
+        $this->triggerChange('eMailAddress', $mailAddress, $oldMailAddress);
168
+    }
169
+
170
+    /**
171
+     * returns the timestamp of the user's last login or 0 if the user did never
172
+     * login
173
+     *
174
+     * @return int
175
+     */
176
+    public function getLastLogin() {
177
+        return $this->lastLogin;
178
+    }
179
+
180
+    /**
181
+     * updates the timestamp of the most recent login of this user
182
+     */
183
+    public function updateLastLoginTimestamp() {
184
+        $firstTimeLogin = ($this->lastLogin === 0);
185
+        $this->lastLogin = time();
186
+        $this->config->setUserValue(
187
+            $this->uid, 'login', 'lastLogin', $this->lastLogin);
188
+
189
+        return $firstTimeLogin;
190
+    }
191
+
192
+    /**
193
+     * Delete the user
194
+     *
195
+     * @return bool
196
+     */
197
+    public function delete() {
198
+        if ($this->emitter) {
199
+            $this->emitter->emit('\OC\User', 'preDelete', array($this));
200
+        }
201
+        // get the home now because it won't return it after user deletion
202
+        $homePath = $this->getHome();
203
+        $result = $this->backend->deleteUser($this->uid);
204
+        if ($result) {
205
+
206
+            // FIXME: Feels like an hack - suggestions?
207
+
208
+            $groupManager = \OC::$server->getGroupManager();
209
+            // We have to delete the user from all groups
210
+            foreach ($groupManager->getUserGroupIds($this) as $groupId) {
211
+                $group = $groupManager->get($groupId);
212
+                if ($group) {
213
+                    \OC_Hook::emit("OC_Group", "pre_removeFromGroup", ["run" => true, "uid" => $this->uid, "gid" => $groupId]);
214
+                    $group->removeUser($this);
215
+                    \OC_Hook::emit("OC_User", "post_removeFromGroup", ["uid" => $this->uid, "gid" => $groupId]);
216
+                }
217
+            }
218
+            // Delete the user's keys in preferences
219
+            \OC::$server->getConfig()->deleteAllUserValues($this->uid);
220
+
221
+            // Delete user files in /data/
222
+            if ($homePath !== false) {
223
+                // FIXME: this operates directly on FS, should use View instead...
224
+                // also this is not testable/mockable...
225
+                \OC_Helper::rmdirr($homePath);
226
+            }
227
+
228
+            // Delete the users entry in the storage table
229
+            Storage::remove('home::' . $this->uid);
230
+
231
+            \OC::$server->getCommentsManager()->deleteReferencesOfActor('users', $this->uid);
232
+            \OC::$server->getCommentsManager()->deleteReadMarksFromUser($this);
233
+
234
+            $notification = \OC::$server->getNotificationManager()->createNotification();
235
+            $notification->setUser($this->uid);
236
+            \OC::$server->getNotificationManager()->markProcessed($notification);
237
+
238
+            if ($this->emitter) {
239
+                $this->emitter->emit('\OC\User', 'postDelete', array($this));
240
+            }
241
+        }
242
+        return !($result === false);
243
+    }
244
+
245
+    /**
246
+     * Set the password of the user
247
+     *
248
+     * @param string $password
249
+     * @param string $recoveryPassword for the encryption app to reset encryption keys
250
+     * @return bool
251
+     */
252
+    public function setPassword($password, $recoveryPassword = null) {
253
+        if ($this->emitter) {
254
+            $this->emitter->emit('\OC\User', 'preSetPassword', array($this, $password, $recoveryPassword));
255
+        }
256
+        if ($this->backend->implementsActions(Backend::SET_PASSWORD)) {
257
+            $result = $this->backend->setPassword($this->uid, $password);
258
+            if ($this->emitter) {
259
+                $this->emitter->emit('\OC\User', 'postSetPassword', array($this, $password, $recoveryPassword));
260
+            }
261
+            return !($result === false);
262
+        } else {
263
+            return false;
264
+        }
265
+    }
266
+
267
+    /**
268
+     * get the users home folder to mount
269
+     *
270
+     * @return string
271
+     */
272
+    public function getHome() {
273
+        if (!$this->home) {
274
+            if ($this->backend->implementsActions(Backend::GET_HOME) and $home = $this->backend->getHome($this->uid)) {
275
+                $this->home = $home;
276
+            } elseif ($this->config) {
277
+                $this->home = $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/' . $this->uid;
278
+            } else {
279
+                $this->home = \OC::$SERVERROOT . '/data/' . $this->uid;
280
+            }
281
+        }
282
+        return $this->home;
283
+    }
284
+
285
+    /**
286
+     * Get the name of the backend class the user is connected with
287
+     *
288
+     * @return string
289
+     */
290
+    public function getBackendClassName() {
291
+        if($this->backend instanceof IUserBackend) {
292
+            return $this->backend->getBackendName();
293
+        }
294
+        return get_class($this->backend);
295
+    }
296
+
297
+    /**
298
+     * check if the backend allows the user to change his avatar on Personal page
299
+     *
300
+     * @return bool
301
+     */
302
+    public function canChangeAvatar() {
303
+        if ($this->backend->implementsActions(Backend::PROVIDE_AVATAR)) {
304
+            return $this->backend->canChangeAvatar($this->uid);
305
+        }
306
+        return true;
307
+    }
308
+
309
+    /**
310
+     * check if the backend supports changing passwords
311
+     *
312
+     * @return bool
313
+     */
314
+    public function canChangePassword() {
315
+        return $this->backend->implementsActions(Backend::SET_PASSWORD);
316
+    }
317
+
318
+    /**
319
+     * check if the backend supports changing display names
320
+     *
321
+     * @return bool
322
+     */
323
+    public function canChangeDisplayName() {
324
+        if ($this->config->getSystemValue('allow_user_to_change_display_name') === false) {
325
+            return false;
326
+        }
327
+        return $this->backend->implementsActions(Backend::SET_DISPLAYNAME);
328
+    }
329
+
330
+    /**
331
+     * check if the user is enabled
332
+     *
333
+     * @return bool
334
+     */
335
+    public function isEnabled() {
336
+        return $this->enabled;
337
+    }
338
+
339
+    /**
340
+     * set the enabled status for the user
341
+     *
342
+     * @param bool $enabled
343
+     */
344
+    public function setEnabled($enabled) {
345
+        $this->enabled = $enabled;
346
+        $enabled = ($enabled) ? 'true' : 'false';
347
+        $this->config->setUserValue($this->uid, 'core', 'enabled', $enabled);
348
+    }
349
+
350
+    /**
351
+     * get the users email address
352
+     *
353
+     * @return string|null
354
+     * @since 9.0.0
355
+     */
356
+    public function getEMailAddress() {
357
+        return $this->config->getUserValue($this->uid, 'settings', 'email', null);
358
+    }
359
+
360
+    /**
361
+     * get the users' quota
362
+     *
363
+     * @return string
364
+     * @since 9.0.0
365
+     */
366
+    public function getQuota() {
367
+        $quota = $this->config->getUserValue($this->uid, 'files', 'quota', 'default');
368
+        if($quota === 'default') {
369
+            $quota = $this->config->getAppValue('files', 'default_quota', 'none');
370
+        }
371
+        return $quota;
372
+    }
373
+
374
+    /**
375
+     * set the users' quota
376
+     *
377
+     * @param string $quota
378
+     * @return void
379
+     * @since 9.0.0
380
+     */
381
+    public function setQuota($quota) {
382
+        if($quota !== 'none' and $quota !== 'default') {
383
+            $quota = OC_Helper::computerFileSize($quota);
384
+            $quota = OC_Helper::humanFileSize($quota);
385
+        }
386
+        $this->config->setUserValue($this->uid, 'files', 'quota', $quota);
387
+        $this->triggerChange('quota', $quota);
388
+    }
389
+
390
+    /**
391
+     * get the avatar image if it exists
392
+     *
393
+     * @param int $size
394
+     * @return IImage|null
395
+     * @since 9.0.0
396
+     */
397
+    public function getAvatarImage($size) {
398
+        // delay the initialization
399
+        if (is_null($this->avatarManager)) {
400
+            $this->avatarManager = \OC::$server->getAvatarManager();
401
+        }
402
+
403
+        $avatar = $this->avatarManager->getAvatar($this->uid);
404
+        $image = $avatar->get(-1);
405
+        if ($image) {
406
+            return $image;
407
+        }
408
+
409
+        return null;
410
+    }
411
+
412
+    /**
413
+     * get the federation cloud id
414
+     *
415
+     * @return string
416
+     * @since 9.0.0
417
+     */
418
+    public function getCloudId() {
419
+        $uid = $this->getUID();
420
+        $server = $this->urlGenerator->getAbsoluteURL('/');
421
+        $server =  rtrim( $this->removeProtocolFromUrl($server), '/');
422
+        return \OC::$server->getCloudIdManager()->getCloudId($uid, $server)->getId();
423
+    }
424
+
425
+    /**
426
+     * @param string $url
427
+     * @return string
428
+     */
429
+    private function removeProtocolFromUrl($url) {
430
+        if (strpos($url, 'https://') === 0) {
431
+            return substr($url, strlen('https://'));
432
+        } else if (strpos($url, 'http://') === 0) {
433
+            return substr($url, strlen('http://'));
434
+        }
435
+
436
+        return $url;
437
+    }
438
+
439
+    public function triggerChange($feature, $value = null, $oldValue = null) {
440
+        if ($this->emitter) {
441
+            $this->emitter->emit('\OC\User', 'changeUser', array($this, $feature, $value, $oldValue));
442
+        }
443
+    }
444 444
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -83,7 +83,7 @@  discard block
 block discarded – undo
83 83
 		$this->uid = $uid;
84 84
 		$this->backend = $backend;
85 85
 		$this->emitter = $emitter;
86
-		if(is_null($config)) {
86
+		if (is_null($config)) {
87 87
 			$config = \OC::$server->getConfig();
88 88
 		}
89 89
 		$this->config = $config;
@@ -159,7 +159,7 @@  discard block
 block discarded – undo
159 159
 	 */
160 160
 	public function setEMailAddress($mailAddress) {
161 161
 		$oldMailAddress = $this->getEMailAddress();
162
-		if($mailAddress === '') {
162
+		if ($mailAddress === '') {
163 163
 			$this->config->deleteUserValue($this->uid, 'settings', 'email');
164 164
 		} else {
165 165
 			$this->config->setUserValue($this->uid, 'settings', 'email', $mailAddress);
@@ -226,7 +226,7 @@  discard block
 block discarded – undo
226 226
 			}
227 227
 
228 228
 			// Delete the users entry in the storage table
229
-			Storage::remove('home::' . $this->uid);
229
+			Storage::remove('home::'.$this->uid);
230 230
 
231 231
 			\OC::$server->getCommentsManager()->deleteReferencesOfActor('users', $this->uid);
232 232
 			\OC::$server->getCommentsManager()->deleteReadMarksFromUser($this);
@@ -274,9 +274,9 @@  discard block
 block discarded – undo
274 274
 			if ($this->backend->implementsActions(Backend::GET_HOME) and $home = $this->backend->getHome($this->uid)) {
275 275
 				$this->home = $home;
276 276
 			} elseif ($this->config) {
277
-				$this->home = $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/' . $this->uid;
277
+				$this->home = $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT.'/data').'/'.$this->uid;
278 278
 			} else {
279
-				$this->home = \OC::$SERVERROOT . '/data/' . $this->uid;
279
+				$this->home = \OC::$SERVERROOT.'/data/'.$this->uid;
280 280
 			}
281 281
 		}
282 282
 		return $this->home;
@@ -288,7 +288,7 @@  discard block
 block discarded – undo
288 288
 	 * @return string
289 289
 	 */
290 290
 	public function getBackendClassName() {
291
-		if($this->backend instanceof IUserBackend) {
291
+		if ($this->backend instanceof IUserBackend) {
292 292
 			return $this->backend->getBackendName();
293 293
 		}
294 294
 		return get_class($this->backend);
@@ -365,7 +365,7 @@  discard block
 block discarded – undo
365 365
 	 */
366 366
 	public function getQuota() {
367 367
 		$quota = $this->config->getUserValue($this->uid, 'files', 'quota', 'default');
368
-		if($quota === 'default') {
368
+		if ($quota === 'default') {
369 369
 			$quota = $this->config->getAppValue('files', 'default_quota', 'none');
370 370
 		}
371 371
 		return $quota;
@@ -379,7 +379,7 @@  discard block
 block discarded – undo
379 379
 	 * @since 9.0.0
380 380
 	 */
381 381
 	public function setQuota($quota) {
382
-		if($quota !== 'none' and $quota !== 'default') {
382
+		if ($quota !== 'none' and $quota !== 'default') {
383 383
 			$quota = OC_Helper::computerFileSize($quota);
384 384
 			$quota = OC_Helper::humanFileSize($quota);
385 385
 		}
@@ -418,7 +418,7 @@  discard block
 block discarded – undo
418 418
 	public function getCloudId() {
419 419
 		$uid = $this->getUID();
420 420
 		$server = $this->urlGenerator->getAbsoluteURL('/');
421
-		$server =  rtrim( $this->removeProtocolFromUrl($server), '/');
421
+		$server = rtrim($this->removeProtocolFromUrl($server), '/');
422 422
 		return \OC::$server->getCloudIdManager()->getCloudId($uid, $server)->getId();
423 423
 	}
424 424
 
Please login to merge, or discard this patch.
settings/Activity/Setting.php 1 patch
Indentation   +59 added lines, -59 removed lines patch added patch discarded remove patch
@@ -26,71 +26,71 @@
 block discarded – undo
26 26
 
27 27
 class Setting implements ISetting {
28 28
 
29
-	/** @var IL10N */
30
-	protected $l;
29
+    /** @var IL10N */
30
+    protected $l;
31 31
 
32
-	/**
33
-	 * @param IL10N $l10n
34
-	 */
35
-	public function __construct(IL10N $l10n) {
36
-		$this->l = $l10n;
37
-	}
32
+    /**
33
+     * @param IL10N $l10n
34
+     */
35
+    public function __construct(IL10N $l10n) {
36
+        $this->l = $l10n;
37
+    }
38 38
 
39
-	/**
40
-	 * @return string Lowercase a-z and underscore only identifier
41
-	 * @since 11.0.0
42
-	 */
43
-	public function getIdentifier() {
44
-		return 'personal_settings';
45
-	}
39
+    /**
40
+     * @return string Lowercase a-z and underscore only identifier
41
+     * @since 11.0.0
42
+     */
43
+    public function getIdentifier() {
44
+        return 'personal_settings';
45
+    }
46 46
 
47
-	/**
48
-	 * @return string A translated string
49
-	 * @since 11.0.0
50
-	 */
51
-	public function getName() {
52
-		return $this->l->t('Your <strong>password</strong> or <strong>email</strong> was modified');
53
-	}
47
+    /**
48
+     * @return string A translated string
49
+     * @since 11.0.0
50
+     */
51
+    public function getName() {
52
+        return $this->l->t('Your <strong>password</strong> or <strong>email</strong> was modified');
53
+    }
54 54
 
55
-	/**
56
-	 * @return int whether the filter should be rather on the top or bottom of
57
-	 * the admin section. The filters are arranged in ascending order of the
58
-	 * priority values. It is required to return a value between 0 and 100.
59
-	 * @since 11.0.0
60
-	 */
61
-	public function getPriority() {
62
-		return 0;
63
-	}
55
+    /**
56
+     * @return int whether the filter should be rather on the top or bottom of
57
+     * the admin section. The filters are arranged in ascending order of the
58
+     * priority values. It is required to return a value between 0 and 100.
59
+     * @since 11.0.0
60
+     */
61
+    public function getPriority() {
62
+        return 0;
63
+    }
64 64
 
65
-	/**
66
-	 * @return bool True when the option can be changed for the stream
67
-	 * @since 11.0.0
68
-	 */
69
-	public function canChangeStream() {
70
-		return false;
71
-	}
65
+    /**
66
+     * @return bool True when the option can be changed for the stream
67
+     * @since 11.0.0
68
+     */
69
+    public function canChangeStream() {
70
+        return false;
71
+    }
72 72
 
73
-	/**
74
-	 * @return bool True when the option can be changed for the stream
75
-	 * @since 11.0.0
76
-	 */
77
-	public function isDefaultEnabledStream() {
78
-		return true;
79
-	}
73
+    /**
74
+     * @return bool True when the option can be changed for the stream
75
+     * @since 11.0.0
76
+     */
77
+    public function isDefaultEnabledStream() {
78
+        return true;
79
+    }
80 80
 
81
-	/**
82
-	 * @return bool True when the option can be changed for the mail
83
-	 * @since 11.0.0
84
-	 */
85
-	public function canChangeMail() {
86
-		return false;
87
-	}
81
+    /**
82
+     * @return bool True when the option can be changed for the mail
83
+     * @since 11.0.0
84
+     */
85
+    public function canChangeMail() {
86
+        return false;
87
+    }
88 88
 
89
-	/**
90
-	 * @return bool True when the option can be changed for the stream
91
-	 * @since 11.0.0
92
-	 */
93
-	public function isDefaultEnabledMail() {
94
-		return false;
95
-	}
89
+    /**
90
+     * @return bool True when the option can be changed for the stream
91
+     * @since 11.0.0
92
+     */
93
+    public function isDefaultEnabledMail() {
94
+        return false;
95
+    }
96 96
 }
Please login to merge, or discard this patch.
settings/Hooks.php 2 patches
Indentation   +130 added lines, -130 removed lines patch added patch discarded remove patch
@@ -32,134 +32,134 @@
 block discarded – undo
32 32
 
33 33
 class Hooks {
34 34
 
35
-	/** @var IActivityManager */
36
-	protected $activityManager;
37
-	/** @var IUserManager */
38
-	protected $userManager;
39
-	/** @var IUserSession */
40
-	protected $userSession;
41
-	/** @var IURLGenerator */
42
-	protected $urlGenerator;
43
-	/** @var IMailer */
44
-	protected $mailer;
45
-	/** @var IL10N */
46
-	protected $l;
47
-
48
-	public function __construct(IActivityManager $activityManager, IUserManager $userManager, IUserSession $userSession, IURLGenerator $urlGenerator, IMailer $mailer, IL10N $l) {
49
-		$this->activityManager = $activityManager;
50
-		$this->userManager = $userManager;
51
-		$this->userSession = $userSession;
52
-		$this->urlGenerator = $urlGenerator;
53
-		$this->mailer = $mailer;
54
-		$this->l = $l;
55
-	}
56
-
57
-	/**
58
-	 * @param string $uid
59
-	 * @throws \InvalidArgumentException
60
-	 * @throws \BadMethodCallException
61
-	 * @throws \Exception
62
-	 */
63
-	public function onChangePassword($uid) {
64
-		$user = $this->userManager->get($uid);
65
-
66
-		if (!$user instanceof IUser || $user->getEMailAddress() === null) {
67
-			return;
68
-		}
69
-
70
-		$event = $this->activityManager->generateEvent();
71
-		$event->setApp('settings')
72
-			->setType('personal_settings')
73
-			->setAffectedUser($user->getUID());
74
-
75
-		$instanceUrl = $this->urlGenerator->getAbsoluteURL('/');
76
-
77
-		$actor = $this->userSession->getUser();
78
-		if ($actor instanceof IUser) {
79
-			if ($actor->getUID() !== $user->getUID()) {
80
-				$text = $this->l->t('%1$s changed your password on %2$s.', [$actor->getDisplayName(), $instanceUrl]);
81
-				$event->setAuthor($actor->getUID())
82
-					->setSubject(Provider::PASSWORD_CHANGED_BY, [$actor->getUID()]);
83
-			} else {
84
-				$text = $this->l->t('Your password on %s was changed.', [$instanceUrl]);
85
-				$event->setAuthor($actor->getUID())
86
-					->setSubject(Provider::PASSWORD_CHANGED_SELF);
87
-			}
88
-		} else {
89
-			$text = $this->l->t('Your password on %s was reset by an administrator.', [$instanceUrl]);
90
-			$event->setSubject(Provider::PASSWORD_RESET);
91
-		}
92
-
93
-		$this->activityManager->publish($event);
94
-
95
-		if ($user->getEMailAddress() !== null) {
96
-			$template = $this->mailer->createEMailTemplate();
97
-			$template->addHeader();
98
-			$template->addHeading($this->l->t('Password changed for %s', $user->getDisplayName()), false);
99
-			$template->addBodyText($text . ' ' . $this->l->t('If you did not request this, please contact an administrator.'));
100
-			$template->addFooter();
101
-
102
-
103
-			$message = $this->mailer->createMessage();
104
-			$message->setTo([$user->getEMailAddress() => $user->getDisplayName()]);
105
-			$message->setSubject($this->l->t('Password for %1$s changed on %2$s', [$user->getDisplayName(), $instanceUrl]));
106
-			$message->setBody($template->renderText(), 'text/plain');
107
-			$message->setHtmlBody($template->renderHTML());
108
-
109
-			$this->mailer->send($message);
110
-		}
111
-	}
112
-
113
-	/**
114
-	 * @param IUser $user
115
-	 * @param string|null $oldMailAddress
116
-	 * @throws \InvalidArgumentException
117
-	 * @throws \BadMethodCallException
118
-	 */
119
-	public function onChangeEmail(IUser $user, $oldMailAddress) {
120
-		$event = $this->activityManager->generateEvent();
121
-		$event->setApp('settings')
122
-			->setType('personal_settings')
123
-			->setAffectedUser($user->getUID());
124
-
125
-		$instanceUrl = $this->urlGenerator->getAbsoluteURL('/');
126
-
127
-		$actor = $this->userSession->getUser();
128
-		if ($actor instanceof IUser) {
129
-			if ($actor->getUID() !== $user->getUID()) {
130
-				$text = $this->l->t('%1$s changed your email address on %2$s.', [$actor->getDisplayName(), $instanceUrl]);
131
-				$event->setAuthor($actor->getUID())
132
-					->setSubject(Provider::EMAIL_CHANGED_BY, [$actor->getUID()]);
133
-			} else {
134
-				$text = $this->l->t('Your email address on %s was changed.', [$instanceUrl]);
135
-				$event->setAuthor($actor->getUID())
136
-					->setSubject(Provider::EMAIL_CHANGED_SELF);
137
-			}
138
-		} else {
139
-			$text = $this->l->t('Your email address on %s was changed by an administrator.', [$instanceUrl]);
140
-			$event->setSubject(Provider::EMAIL_CHANGED);
141
-		}
142
-		$this->activityManager->publish($event);
143
-
144
-
145
-		if ($oldMailAddress !== null) {
146
-			$template = $this->mailer->createEMailTemplate();
147
-			$template->addHeader();
148
-			$template->addHeading($this->l->t('Email address changed for %s', $user->getDisplayName()), false);
149
-			$template->addBodyText($text . ' ' . $this->l->t('If you did not request this, please contact an administrator.'));
150
-			if ($user->getEMailAddress()) {
151
-				$template->addBodyText($this->l->t('The new email address is %s', $user->getEMailAddress()));
152
-			}
153
-			$template->addFooter();
154
-
155
-
156
-			$message = $this->mailer->createMessage();
157
-			$message->setTo([$oldMailAddress => $user->getDisplayName()]);
158
-			$message->setSubject($this->l->t('Email address for %1$s changed on %2$s', [$user->getDisplayName(), $instanceUrl]));
159
-			$message->setBody($template->renderText(), 'text/plain');
160
-			$message->setHtmlBody($template->renderHTML());
161
-
162
-			$this->mailer->send($message);
163
-		}
164
-	}
35
+    /** @var IActivityManager */
36
+    protected $activityManager;
37
+    /** @var IUserManager */
38
+    protected $userManager;
39
+    /** @var IUserSession */
40
+    protected $userSession;
41
+    /** @var IURLGenerator */
42
+    protected $urlGenerator;
43
+    /** @var IMailer */
44
+    protected $mailer;
45
+    /** @var IL10N */
46
+    protected $l;
47
+
48
+    public function __construct(IActivityManager $activityManager, IUserManager $userManager, IUserSession $userSession, IURLGenerator $urlGenerator, IMailer $mailer, IL10N $l) {
49
+        $this->activityManager = $activityManager;
50
+        $this->userManager = $userManager;
51
+        $this->userSession = $userSession;
52
+        $this->urlGenerator = $urlGenerator;
53
+        $this->mailer = $mailer;
54
+        $this->l = $l;
55
+    }
56
+
57
+    /**
58
+     * @param string $uid
59
+     * @throws \InvalidArgumentException
60
+     * @throws \BadMethodCallException
61
+     * @throws \Exception
62
+     */
63
+    public function onChangePassword($uid) {
64
+        $user = $this->userManager->get($uid);
65
+
66
+        if (!$user instanceof IUser || $user->getEMailAddress() === null) {
67
+            return;
68
+        }
69
+
70
+        $event = $this->activityManager->generateEvent();
71
+        $event->setApp('settings')
72
+            ->setType('personal_settings')
73
+            ->setAffectedUser($user->getUID());
74
+
75
+        $instanceUrl = $this->urlGenerator->getAbsoluteURL('/');
76
+
77
+        $actor = $this->userSession->getUser();
78
+        if ($actor instanceof IUser) {
79
+            if ($actor->getUID() !== $user->getUID()) {
80
+                $text = $this->l->t('%1$s changed your password on %2$s.', [$actor->getDisplayName(), $instanceUrl]);
81
+                $event->setAuthor($actor->getUID())
82
+                    ->setSubject(Provider::PASSWORD_CHANGED_BY, [$actor->getUID()]);
83
+            } else {
84
+                $text = $this->l->t('Your password on %s was changed.', [$instanceUrl]);
85
+                $event->setAuthor($actor->getUID())
86
+                    ->setSubject(Provider::PASSWORD_CHANGED_SELF);
87
+            }
88
+        } else {
89
+            $text = $this->l->t('Your password on %s was reset by an administrator.', [$instanceUrl]);
90
+            $event->setSubject(Provider::PASSWORD_RESET);
91
+        }
92
+
93
+        $this->activityManager->publish($event);
94
+
95
+        if ($user->getEMailAddress() !== null) {
96
+            $template = $this->mailer->createEMailTemplate();
97
+            $template->addHeader();
98
+            $template->addHeading($this->l->t('Password changed for %s', $user->getDisplayName()), false);
99
+            $template->addBodyText($text . ' ' . $this->l->t('If you did not request this, please contact an administrator.'));
100
+            $template->addFooter();
101
+
102
+
103
+            $message = $this->mailer->createMessage();
104
+            $message->setTo([$user->getEMailAddress() => $user->getDisplayName()]);
105
+            $message->setSubject($this->l->t('Password for %1$s changed on %2$s', [$user->getDisplayName(), $instanceUrl]));
106
+            $message->setBody($template->renderText(), 'text/plain');
107
+            $message->setHtmlBody($template->renderHTML());
108
+
109
+            $this->mailer->send($message);
110
+        }
111
+    }
112
+
113
+    /**
114
+     * @param IUser $user
115
+     * @param string|null $oldMailAddress
116
+     * @throws \InvalidArgumentException
117
+     * @throws \BadMethodCallException
118
+     */
119
+    public function onChangeEmail(IUser $user, $oldMailAddress) {
120
+        $event = $this->activityManager->generateEvent();
121
+        $event->setApp('settings')
122
+            ->setType('personal_settings')
123
+            ->setAffectedUser($user->getUID());
124
+
125
+        $instanceUrl = $this->urlGenerator->getAbsoluteURL('/');
126
+
127
+        $actor = $this->userSession->getUser();
128
+        if ($actor instanceof IUser) {
129
+            if ($actor->getUID() !== $user->getUID()) {
130
+                $text = $this->l->t('%1$s changed your email address on %2$s.', [$actor->getDisplayName(), $instanceUrl]);
131
+                $event->setAuthor($actor->getUID())
132
+                    ->setSubject(Provider::EMAIL_CHANGED_BY, [$actor->getUID()]);
133
+            } else {
134
+                $text = $this->l->t('Your email address on %s was changed.', [$instanceUrl]);
135
+                $event->setAuthor($actor->getUID())
136
+                    ->setSubject(Provider::EMAIL_CHANGED_SELF);
137
+            }
138
+        } else {
139
+            $text = $this->l->t('Your email address on %s was changed by an administrator.', [$instanceUrl]);
140
+            $event->setSubject(Provider::EMAIL_CHANGED);
141
+        }
142
+        $this->activityManager->publish($event);
143
+
144
+
145
+        if ($oldMailAddress !== null) {
146
+            $template = $this->mailer->createEMailTemplate();
147
+            $template->addHeader();
148
+            $template->addHeading($this->l->t('Email address changed for %s', $user->getDisplayName()), false);
149
+            $template->addBodyText($text . ' ' . $this->l->t('If you did not request this, please contact an administrator.'));
150
+            if ($user->getEMailAddress()) {
151
+                $template->addBodyText($this->l->t('The new email address is %s', $user->getEMailAddress()));
152
+            }
153
+            $template->addFooter();
154
+
155
+
156
+            $message = $this->mailer->createMessage();
157
+            $message->setTo([$oldMailAddress => $user->getDisplayName()]);
158
+            $message->setSubject($this->l->t('Email address for %1$s changed on %2$s', [$user->getDisplayName(), $instanceUrl]));
159
+            $message->setBody($template->renderText(), 'text/plain');
160
+            $message->setHtmlBody($template->renderHTML());
161
+
162
+            $this->mailer->send($message);
163
+        }
164
+    }
165 165
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -96,7 +96,7 @@  discard block
 block discarded – undo
96 96
 			$template = $this->mailer->createEMailTemplate();
97 97
 			$template->addHeader();
98 98
 			$template->addHeading($this->l->t('Password changed for %s', $user->getDisplayName()), false);
99
-			$template->addBodyText($text . ' ' . $this->l->t('If you did not request this, please contact an administrator.'));
99
+			$template->addBodyText($text.' '.$this->l->t('If you did not request this, please contact an administrator.'));
100 100
 			$template->addFooter();
101 101
 
102 102
 
@@ -146,7 +146,7 @@  discard block
 block discarded – undo
146 146
 			$template = $this->mailer->createEMailTemplate();
147 147
 			$template->addHeader();
148 148
 			$template->addHeading($this->l->t('Email address changed for %s', $user->getDisplayName()), false);
149
-			$template->addBodyText($text . ' ' . $this->l->t('If you did not request this, please contact an administrator.'));
149
+			$template->addBodyText($text.' '.$this->l->t('If you did not request this, please contact an administrator.'));
150 150
 			if ($user->getEMailAddress()) {
151 151
 				$template->addBodyText($this->l->t('The new email address is %s', $user->getEMailAddress()));
152 152
 			}
Please login to merge, or discard this patch.
settings/Application.php 1 patch
Indentation   +109 added lines, -109 removed lines patch added patch discarded remove patch
@@ -51,123 +51,123 @@
 block discarded – undo
51 51
 class Application extends App {
52 52
 
53 53
 
54
-	/**
55
-	 * @param array $urlParams
56
-	 */
57
-	public function __construct(array $urlParams=[]){
58
-		parent::__construct('settings', $urlParams);
54
+    /**
55
+     * @param array $urlParams
56
+     */
57
+    public function __construct(array $urlParams=[]){
58
+        parent::__construct('settings', $urlParams);
59 59
 
60
-		$container = $this->getContainer();
60
+        $container = $this->getContainer();
61 61
 
62
-		// Register Middleware
63
-		$container->registerAlias('SubadminMiddleware', SubadminMiddleware::class);
64
-		$container->registerMiddleWare('SubadminMiddleware');
62
+        // Register Middleware
63
+        $container->registerAlias('SubadminMiddleware', SubadminMiddleware::class);
64
+        $container->registerMiddleWare('SubadminMiddleware');
65 65
 
66
-		/**
67
-		 * Core class wrappers
68
-		 */
69
-		/** FIXME: Remove once OC_User is non-static and mockable */
70
-		$container->registerService('isAdmin', function() {
71
-			return \OC_User::isAdminUser(\OC_User::getUser());
72
-		});
73
-		/** FIXME: Remove once OC_SubAdmin is non-static and mockable */
74
-		$container->registerService('isSubAdmin', function(IContainer $c) {
75
-			$userObject = \OC::$server->getUserSession()->getUser();
76
-			$isSubAdmin = false;
77
-			if($userObject !== null) {
78
-				$isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
79
-			}
80
-			return $isSubAdmin;
81
-		});
82
-		$container->registerService('userCertificateManager', function(IContainer $c) {
83
-			return $c->query('ServerContainer')->getCertificateManager();
84
-		}, false);
85
-		$container->registerService('systemCertificateManager', function (IContainer $c) {
86
-			return $c->query('ServerContainer')->getCertificateManager(null);
87
-		}, false);
88
-		$container->registerService(IProvider::class, function (IContainer $c) {
89
-			return $c->query('ServerContainer')->query(IProvider::class);
90
-		});
91
-		$container->registerService(IManager::class, function (IContainer $c) {
92
-			return $c->query('ServerContainer')->getSettingsManager();
93
-		});
66
+        /**
67
+         * Core class wrappers
68
+         */
69
+        /** FIXME: Remove once OC_User is non-static and mockable */
70
+        $container->registerService('isAdmin', function() {
71
+            return \OC_User::isAdminUser(\OC_User::getUser());
72
+        });
73
+        /** FIXME: Remove once OC_SubAdmin is non-static and mockable */
74
+        $container->registerService('isSubAdmin', function(IContainer $c) {
75
+            $userObject = \OC::$server->getUserSession()->getUser();
76
+            $isSubAdmin = false;
77
+            if($userObject !== null) {
78
+                $isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
79
+            }
80
+            return $isSubAdmin;
81
+        });
82
+        $container->registerService('userCertificateManager', function(IContainer $c) {
83
+            return $c->query('ServerContainer')->getCertificateManager();
84
+        }, false);
85
+        $container->registerService('systemCertificateManager', function (IContainer $c) {
86
+            return $c->query('ServerContainer')->getCertificateManager(null);
87
+        }, false);
88
+        $container->registerService(IProvider::class, function (IContainer $c) {
89
+            return $c->query('ServerContainer')->query(IProvider::class);
90
+        });
91
+        $container->registerService(IManager::class, function (IContainer $c) {
92
+            return $c->query('ServerContainer')->getSettingsManager();
93
+        });
94 94
 
95
-		$container->registerService(NewUserMailHelper::class, function (IContainer $c) {
96
-			/** @var Server $server */
97
-			$server = $c->query('ServerContainer');
98
-			/** @var Defaults $defaults */
99
-			$defaults = $server->query(Defaults::class);
95
+        $container->registerService(NewUserMailHelper::class, function (IContainer $c) {
96
+            /** @var Server $server */
97
+            $server = $c->query('ServerContainer');
98
+            /** @var Defaults $defaults */
99
+            $defaults = $server->query(Defaults::class);
100 100
 
101
-			return new NewUserMailHelper(
102
-				$defaults,
103
-				$server->getURLGenerator(),
104
-				$server->getL10N('settings'),
105
-				$server->getMailer(),
106
-				$server->getSecureRandom(),
107
-				new TimeFactory(),
108
-				$server->getConfig(),
109
-				$server->getCrypto(),
110
-				Util::getDefaultEmailAddress('no-reply')
111
-			);
112
-		});
113
-		$container->registerService(AppFetcher::class, function (IContainer $c) {
114
-			/** @var Server $server */
115
-			$server = $c->query('ServerContainer');
116
-			return new AppFetcher(
117
-				$server->getAppDataDir('appstore'),
118
-				$server->getHTTPClientService(),
119
-				$server->query(TimeFactory::class),
120
-				$server->getConfig()
121
-			);
122
-		});
123
-		$container->registerService(CategoryFetcher::class, function (IContainer $c) {
124
-			/** @var Server $server */
125
-			$server = $c->query('ServerContainer');
126
-			return new CategoryFetcher(
127
-				$server->getAppDataDir('appstore'),
128
-				$server->getHTTPClientService(),
129
-				$server->query(TimeFactory::class),
130
-				$server->getConfig()
131
-			);
132
-		});
133
-	}
101
+            return new NewUserMailHelper(
102
+                $defaults,
103
+                $server->getURLGenerator(),
104
+                $server->getL10N('settings'),
105
+                $server->getMailer(),
106
+                $server->getSecureRandom(),
107
+                new TimeFactory(),
108
+                $server->getConfig(),
109
+                $server->getCrypto(),
110
+                Util::getDefaultEmailAddress('no-reply')
111
+            );
112
+        });
113
+        $container->registerService(AppFetcher::class, function (IContainer $c) {
114
+            /** @var Server $server */
115
+            $server = $c->query('ServerContainer');
116
+            return new AppFetcher(
117
+                $server->getAppDataDir('appstore'),
118
+                $server->getHTTPClientService(),
119
+                $server->query(TimeFactory::class),
120
+                $server->getConfig()
121
+            );
122
+        });
123
+        $container->registerService(CategoryFetcher::class, function (IContainer $c) {
124
+            /** @var Server $server */
125
+            $server = $c->query('ServerContainer');
126
+            return new CategoryFetcher(
127
+                $server->getAppDataDir('appstore'),
128
+                $server->getHTTPClientService(),
129
+                $server->query(TimeFactory::class),
130
+                $server->getConfig()
131
+            );
132
+        });
133
+    }
134 134
 
135
-	public function register() {
136
-		$activityManager = $this->getContainer()->getServer()->getActivityManager();
137
-		$activityManager->registerSetting(Setting::class); // FIXME move to info.xml
138
-		$activityManager->registerProvider(Provider::class); // FIXME move to info.xml
135
+    public function register() {
136
+        $activityManager = $this->getContainer()->getServer()->getActivityManager();
137
+        $activityManager->registerSetting(Setting::class); // FIXME move to info.xml
138
+        $activityManager->registerProvider(Provider::class); // FIXME move to info.xml
139 139
 
140
-		Util::connectHook('OC_User', 'post_setPassword', $this, 'onChangePassword');
141
-		Util::connectHook('OC_User', 'changeUser', $this, 'onChangeInfo');
142
-	}
140
+        Util::connectHook('OC_User', 'post_setPassword', $this, 'onChangePassword');
141
+        Util::connectHook('OC_User', 'changeUser', $this, 'onChangeInfo');
142
+    }
143 143
 
144
-	/**
145
-	 * @param array $parameters
146
-	 * @throws \InvalidArgumentException
147
-	 * @throws \BadMethodCallException
148
-	 * @throws \Exception
149
-	 * @throws \OCP\AppFramework\QueryException
150
-	 */
151
-	public function onChangePassword(array $parameters) {
152
-		/** @var Hooks $hooks */
153
-		$hooks = $this->getContainer()->query(Hooks::class);
154
-		$hooks->onChangePassword($parameters['uid']);
155
-	}
144
+    /**
145
+     * @param array $parameters
146
+     * @throws \InvalidArgumentException
147
+     * @throws \BadMethodCallException
148
+     * @throws \Exception
149
+     * @throws \OCP\AppFramework\QueryException
150
+     */
151
+    public function onChangePassword(array $parameters) {
152
+        /** @var Hooks $hooks */
153
+        $hooks = $this->getContainer()->query(Hooks::class);
154
+        $hooks->onChangePassword($parameters['uid']);
155
+    }
156 156
 
157
-	/**
158
-	 * @param array $parameters
159
-	 * @throws \InvalidArgumentException
160
-	 * @throws \BadMethodCallException
161
-	 * @throws \Exception
162
-	 * @throws \OCP\AppFramework\QueryException
163
-	 */
164
-	public function onChangeInfo(array $parameters) {
165
-		if ($parameters['feature'] !== 'eMailAddress') {
166
-			return;
167
-		}
157
+    /**
158
+     * @param array $parameters
159
+     * @throws \InvalidArgumentException
160
+     * @throws \BadMethodCallException
161
+     * @throws \Exception
162
+     * @throws \OCP\AppFramework\QueryException
163
+     */
164
+    public function onChangeInfo(array $parameters) {
165
+        if ($parameters['feature'] !== 'eMailAddress') {
166
+            return;
167
+        }
168 168
 
169
-		/** @var Hooks $hooks */
170
-		$hooks = $this->getContainer()->query(Hooks::class);
171
-		$hooks->onChangeEmail($parameters['user'], $parameters['old_value']);
172
-	}
169
+        /** @var Hooks $hooks */
170
+        $hooks = $this->getContainer()->query(Hooks::class);
171
+        $hooks->onChangeEmail($parameters['user'], $parameters['old_value']);
172
+    }
173 173
 }
Please login to merge, or discard this patch.
lib/private/Server.php 2 patches
Indentation   +1609 added lines, -1609 removed lines patch added patch discarded remove patch
@@ -117,1618 +117,1618 @@
 block discarded – undo
117 117
  * TODO: hookup all manager classes
118 118
  */
119 119
 class Server extends ServerContainer implements IServerContainer {
120
-	/** @var string */
121
-	private $webRoot;
122
-
123
-	/**
124
-	 * @param string $webRoot
125
-	 * @param \OC\Config $config
126
-	 */
127
-	public function __construct($webRoot, \OC\Config $config) {
128
-		parent::__construct();
129
-		$this->webRoot = $webRoot;
130
-
131
-		$this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
132
-		$this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
133
-
134
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
135
-			return new PreviewManager(
136
-				$c->getConfig(),
137
-				$c->getRootFolder(),
138
-				$c->getAppDataDir('preview'),
139
-				$c->getEventDispatcher(),
140
-				$c->getSession()->get('user_id')
141
-			);
142
-		});
143
-		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
144
-
145
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
146
-			return new \OC\Preview\Watcher(
147
-				$c->getAppDataDir('preview')
148
-			);
149
-		});
150
-
151
-		$this->registerService('EncryptionManager', function (Server $c) {
152
-			$view = new View();
153
-			$util = new Encryption\Util(
154
-				$view,
155
-				$c->getUserManager(),
156
-				$c->getGroupManager(),
157
-				$c->getConfig()
158
-			);
159
-			return new Encryption\Manager(
160
-				$c->getConfig(),
161
-				$c->getLogger(),
162
-				$c->getL10N('core'),
163
-				new View(),
164
-				$util,
165
-				new ArrayCache()
166
-			);
167
-		});
168
-
169
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
170
-			$util = new Encryption\Util(
171
-				new View(),
172
-				$c->getUserManager(),
173
-				$c->getGroupManager(),
174
-				$c->getConfig()
175
-			);
176
-			return new Encryption\File($util);
177
-		});
178
-
179
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
180
-			$view = new View();
181
-			$util = new Encryption\Util(
182
-				$view,
183
-				$c->getUserManager(),
184
-				$c->getGroupManager(),
185
-				$c->getConfig()
186
-			);
187
-
188
-			return new Encryption\Keys\Storage($view, $util);
189
-		});
190
-		$this->registerService('TagMapper', function (Server $c) {
191
-			return new TagMapper($c->getDatabaseConnection());
192
-		});
193
-
194
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
195
-			$tagMapper = $c->query('TagMapper');
196
-			return new TagManager($tagMapper, $c->getUserSession());
197
-		});
198
-		$this->registerAlias('TagManager', \OCP\ITagManager::class);
199
-
200
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
201
-			$config = $c->getConfig();
202
-			$factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
203
-			/** @var \OC\SystemTag\ManagerFactory $factory */
204
-			$factory = new $factoryClass($this);
205
-			return $factory;
206
-		});
207
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
208
-			return $c->query('SystemTagManagerFactory')->getManager();
209
-		});
210
-		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
211
-
212
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
213
-			return $c->query('SystemTagManagerFactory')->getObjectMapper();
214
-		});
215
-		$this->registerService('RootFolder', function (Server $c) {
216
-			$manager = \OC\Files\Filesystem::getMountManager(null);
217
-			$view = new View();
218
-			$root = new Root(
219
-				$manager,
220
-				$view,
221
-				null,
222
-				$c->getUserMountCache(),
223
-				$this->getLogger(),
224
-				$this->getUserManager()
225
-			);
226
-			$connector = new HookConnector($root, $view);
227
-			$connector->viewToNode();
228
-
229
-			$previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
230
-			$previewConnector->connectWatcher();
231
-
232
-			return $root;
233
-		});
234
-		$this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
235
-
236
-		$this->registerService(\OCP\Files\IRootFolder::class, function(Server $c) {
237
-			return new LazyRoot(function() use ($c) {
238
-				return $c->query('RootFolder');
239
-			});
240
-		});
241
-		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
242
-
243
-		$this->registerService(\OCP\IUserManager::class, function (Server $c) {
244
-			$config = $c->getConfig();
245
-			return new \OC\User\Manager($config);
246
-		});
247
-		$this->registerAlias('UserManager', \OCP\IUserManager::class);
248
-
249
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
250
-			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
251
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
252
-				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
253
-			});
254
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
255
-				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
256
-			});
257
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
258
-				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
259
-			});
260
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
261
-				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
262
-			});
263
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
264
-				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
265
-			});
266
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
267
-				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
268
-				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
269
-				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
270
-			});
271
-			return $groupManager;
272
-		});
273
-		$this->registerAlias('GroupManager', \OCP\IGroupManager::class);
274
-
275
-		$this->registerService(Store::class, function(Server $c) {
276
-			$session = $c->getSession();
277
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
278
-				$tokenProvider = $c->query('OC\Authentication\Token\IProvider');
279
-			} else {
280
-				$tokenProvider = null;
281
-			}
282
-			$logger = $c->getLogger();
283
-			return new Store($session, $logger, $tokenProvider);
284
-		});
285
-		$this->registerAlias(IStore::class, Store::class);
286
-		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
287
-			$dbConnection = $c->getDatabaseConnection();
288
-			return new Authentication\Token\DefaultTokenMapper($dbConnection);
289
-		});
290
-		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
291
-			$mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
292
-			$crypto = $c->getCrypto();
293
-			$config = $c->getConfig();
294
-			$logger = $c->getLogger();
295
-			$timeFactory = new TimeFactory();
296
-			return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
297
-		});
298
-		$this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
299
-
300
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
301
-			$manager = $c->getUserManager();
302
-			$session = new \OC\Session\Memory('');
303
-			$timeFactory = new TimeFactory();
304
-			// Token providers might require a working database. This code
305
-			// might however be called when ownCloud is not yet setup.
306
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
307
-				$defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
308
-			} else {
309
-				$defaultTokenProvider = null;
310
-			}
311
-
312
-			$userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom(), $c->getLockdownManager());
313
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
314
-				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
315
-			});
316
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
317
-				/** @var $user \OC\User\User */
318
-				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
319
-			});
320
-			$userSession->listen('\OC\User', 'preDelete', function ($user) {
321
-				/** @var $user \OC\User\User */
322
-				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
323
-			});
324
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
325
-				/** @var $user \OC\User\User */
326
-				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
327
-			});
328
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
329
-				/** @var $user \OC\User\User */
330
-				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
331
-			});
332
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
333
-				/** @var $user \OC\User\User */
334
-				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
335
-			});
336
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
337
-				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
338
-			});
339
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
340
-				/** @var $user \OC\User\User */
341
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
342
-			});
343
-			$userSession->listen('\OC\User', 'logout', function () {
344
-				\OC_Hook::emit('OC_User', 'logout', array());
345
-			});
346
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
347
-				/** @var $user \OC\User\User */
348
-				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
349
-			});
350
-			return $userSession;
351
-		});
352
-		$this->registerAlias('UserSession', \OCP\IUserSession::class);
353
-
354
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
355
-			return new \OC\Authentication\TwoFactorAuth\Manager($c->getAppManager(), $c->getSession(), $c->getConfig(), $c->getActivityManager(), $c->getLogger());
356
-		});
357
-
358
-		$this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
359
-		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
360
-
361
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
362
-			return new \OC\AllConfig(
363
-				$c->getSystemConfig()
364
-			);
365
-		});
366
-		$this->registerAlias('AllConfig', \OC\AllConfig::class);
367
-		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
368
-
369
-		$this->registerService('SystemConfig', function ($c) use ($config) {
370
-			return new \OC\SystemConfig($config);
371
-		});
372
-
373
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
374
-			return new \OC\AppConfig($c->getDatabaseConnection());
375
-		});
376
-		$this->registerAlias('AppConfig', \OC\AppConfig::class);
377
-		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
378
-
379
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
380
-			return new \OC\L10N\Factory(
381
-				$c->getConfig(),
382
-				$c->getRequest(),
383
-				$c->getUserSession(),
384
-				\OC::$SERVERROOT
385
-			);
386
-		});
387
-		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
388
-
389
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
390
-			$config = $c->getConfig();
391
-			$cacheFactory = $c->getMemCacheFactory();
392
-			return new \OC\URLGenerator(
393
-				$config,
394
-				$cacheFactory
395
-			);
396
-		});
397
-		$this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
398
-
399
-		$this->registerService('AppHelper', function ($c) {
400
-			return new \OC\AppHelper();
401
-		});
402
-		$this->registerService('AppFetcher', function ($c) {
403
-			return new AppFetcher(
404
-				$this->getAppDataDir('appstore'),
405
-				$this->getHTTPClientService(),
406
-				$this->query(TimeFactory::class),
407
-				$this->getConfig()
408
-			);
409
-		});
410
-		$this->registerService('CategoryFetcher', function ($c) {
411
-			return new CategoryFetcher(
412
-				$this->getAppDataDir('appstore'),
413
-				$this->getHTTPClientService(),
414
-				$this->query(TimeFactory::class),
415
-				$this->getConfig()
416
-			);
417
-		});
418
-
419
-		$this->registerService(\OCP\ICache::class, function ($c) {
420
-			return new Cache\File();
421
-		});
422
-		$this->registerAlias('UserCache', \OCP\ICache::class);
423
-
424
-		$this->registerService(Factory::class, function (Server $c) {
425
-			$config = $c->getConfig();
426
-
427
-			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
428
-				$v = \OC_App::getAppVersions();
429
-				$v['core'] = md5(file_get_contents(\OC::$SERVERROOT . '/version.php'));
430
-				$version = implode(',', $v);
431
-				$instanceId = \OC_Util::getInstanceId();
432
-				$path = \OC::$SERVERROOT;
433
-				$prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . \OC::$WEBROOT);
434
-				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
435
-					$config->getSystemValue('memcache.local', null),
436
-					$config->getSystemValue('memcache.distributed', null),
437
-					$config->getSystemValue('memcache.locking', null)
438
-				);
439
-			}
440
-
441
-			return new \OC\Memcache\Factory('', $c->getLogger(),
442
-				'\\OC\\Memcache\\ArrayCache',
443
-				'\\OC\\Memcache\\ArrayCache',
444
-				'\\OC\\Memcache\\ArrayCache'
445
-			);
446
-		});
447
-		$this->registerAlias('MemCacheFactory', Factory::class);
448
-		$this->registerAlias(ICacheFactory::class, Factory::class);
449
-
450
-		$this->registerService('RedisFactory', function (Server $c) {
451
-			$systemConfig = $c->getSystemConfig();
452
-			return new RedisFactory($systemConfig);
453
-		});
454
-
455
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
456
-			return new \OC\Activity\Manager(
457
-				$c->getRequest(),
458
-				$c->getUserSession(),
459
-				$c->getConfig(),
460
-				$c->query(IValidator::class)
461
-			);
462
-		});
463
-		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
464
-
465
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
466
-			return new \OC\Activity\EventMerger(
467
-				$c->getL10N('lib')
468
-			);
469
-		});
470
-		$this->registerAlias(IValidator::class, Validator::class);
471
-
472
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
473
-			return new AvatarManager(
474
-				$c->getUserManager(),
475
-				$c->getAppDataDir('avatar'),
476
-				$c->getL10N('lib'),
477
-				$c->getLogger(),
478
-				$c->getConfig()
479
-			);
480
-		});
481
-		$this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
482
-
483
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
484
-			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
485
-			$logger = Log::getLogClass($logType);
486
-			call_user_func(array($logger, 'init'));
487
-
488
-			return new Log($logger);
489
-		});
490
-		$this->registerAlias('Logger', \OCP\ILogger::class);
491
-
492
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
493
-			$config = $c->getConfig();
494
-			return new \OC\BackgroundJob\JobList(
495
-				$c->getDatabaseConnection(),
496
-				$config,
497
-				new TimeFactory()
498
-			);
499
-		});
500
-		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
501
-
502
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
503
-			$cacheFactory = $c->getMemCacheFactory();
504
-			$logger = $c->getLogger();
505
-			if ($cacheFactory->isAvailable()) {
506
-				$router = new \OC\Route\CachingRouter($cacheFactory->create('route'), $logger);
507
-			} else {
508
-				$router = new \OC\Route\Router($logger);
509
-			}
510
-			return $router;
511
-		});
512
-		$this->registerAlias('Router', \OCP\Route\IRouter::class);
513
-
514
-		$this->registerService(\OCP\ISearch::class, function ($c) {
515
-			return new Search();
516
-		});
517
-		$this->registerAlias('Search', \OCP\ISearch::class);
518
-
519
-		$this->registerService(\OC\Security\RateLimiting\Limiter::class, function($c) {
520
-			return new \OC\Security\RateLimiting\Limiter(
521
-				$this->getUserSession(),
522
-				$this->getRequest(),
523
-				new \OC\AppFramework\Utility\TimeFactory(),
524
-				$c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
525
-			);
526
-		});
527
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function($c) {
528
-			return new \OC\Security\RateLimiting\Backend\MemoryCache(
529
-				$this->getMemCacheFactory(),
530
-				new \OC\AppFramework\Utility\TimeFactory()
531
-			);
532
-		});
533
-
534
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
535
-			return new SecureRandom();
536
-		});
537
-		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
538
-
539
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
540
-			return new Crypto($c->getConfig(), $c->getSecureRandom());
541
-		});
542
-		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
543
-
544
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
545
-			return new Hasher($c->getConfig());
546
-		});
547
-		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
548
-
549
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
550
-			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
551
-		});
552
-		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
553
-
554
-		$this->registerService(IDBConnection::class, function (Server $c) {
555
-			$systemConfig = $c->getSystemConfig();
556
-			$factory = new \OC\DB\ConnectionFactory($systemConfig);
557
-			$type = $systemConfig->getValue('dbtype', 'sqlite');
558
-			if (!$factory->isValidType($type)) {
559
-				throw new \OC\DatabaseException('Invalid database type');
560
-			}
561
-			$connectionParams = $factory->createConnectionParams();
562
-			$connection = $factory->getConnection($type, $connectionParams);
563
-			$connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
564
-			return $connection;
565
-		});
566
-		$this->registerAlias('DatabaseConnection', IDBConnection::class);
567
-
568
-		$this->registerService('HTTPHelper', function (Server $c) {
569
-			$config = $c->getConfig();
570
-			return new HTTPHelper(
571
-				$config,
572
-				$c->getHTTPClientService()
573
-			);
574
-		});
575
-
576
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
577
-			$user = \OC_User::getUser();
578
-			$uid = $user ? $user : null;
579
-			return new ClientService(
580
-				$c->getConfig(),
581
-				new \OC\Security\CertificateManager($uid, new View(), $c->getConfig(), $c->getLogger())
582
-			);
583
-		});
584
-		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
585
-
586
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
587
-			if ($c->getSystemConfig()->getValue('debug', false)) {
588
-				return new EventLogger();
589
-			} else {
590
-				return new NullEventLogger();
591
-			}
592
-		});
593
-		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
594
-
595
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
596
-			if ($c->getSystemConfig()->getValue('debug', false)) {
597
-				return new QueryLogger();
598
-			} else {
599
-				return new NullQueryLogger();
600
-			}
601
-		});
602
-		$this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
603
-
604
-		$this->registerService(TempManager::class, function (Server $c) {
605
-			return new TempManager(
606
-				$c->getLogger(),
607
-				$c->getConfig()
608
-			);
609
-		});
610
-		$this->registerAlias('TempManager', TempManager::class);
611
-		$this->registerAlias(ITempManager::class, TempManager::class);
612
-
613
-		$this->registerService(AppManager::class, function (Server $c) {
614
-			return new \OC\App\AppManager(
615
-				$c->getUserSession(),
616
-				$c->getAppConfig(),
617
-				$c->getGroupManager(),
618
-				$c->getMemCacheFactory(),
619
-				$c->getEventDispatcher()
620
-			);
621
-		});
622
-		$this->registerAlias('AppManager', AppManager::class);
623
-		$this->registerAlias(IAppManager::class, AppManager::class);
624
-
625
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
626
-			return new DateTimeZone(
627
-				$c->getConfig(),
628
-				$c->getSession()
629
-			);
630
-		});
631
-		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
632
-
633
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
634
-			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
635
-
636
-			return new DateTimeFormatter(
637
-				$c->getDateTimeZone()->getTimeZone(),
638
-				$c->getL10N('lib', $language)
639
-			);
640
-		});
641
-		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
642
-
643
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
644
-			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
645
-			$listener = new UserMountCacheListener($mountCache);
646
-			$listener->listen($c->getUserManager());
647
-			return $mountCache;
648
-		});
649
-		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
650
-
651
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
652
-			$loader = \OC\Files\Filesystem::getLoader();
653
-			$mountCache = $c->query('UserMountCache');
654
-			$manager =  new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
655
-
656
-			// builtin providers
657
-
658
-			$config = $c->getConfig();
659
-			$manager->registerProvider(new CacheMountProvider($config));
660
-			$manager->registerHomeProvider(new LocalHomeMountProvider());
661
-			$manager->registerHomeProvider(new ObjectHomeMountProvider($config));
662
-
663
-			return $manager;
664
-		});
665
-		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
666
-
667
-		$this->registerService('IniWrapper', function ($c) {
668
-			return new IniGetWrapper();
669
-		});
670
-		$this->registerService('AsyncCommandBus', function (Server $c) {
671
-			$jobList = $c->getJobList();
672
-			return new AsyncBus($jobList);
673
-		});
674
-		$this->registerService('TrustedDomainHelper', function ($c) {
675
-			return new TrustedDomainHelper($this->getConfig());
676
-		});
677
-		$this->registerService('Throttler', function(Server $c) {
678
-			return new Throttler(
679
-				$c->getDatabaseConnection(),
680
-				new TimeFactory(),
681
-				$c->getLogger(),
682
-				$c->getConfig()
683
-			);
684
-		});
685
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
686
-			// IConfig and IAppManager requires a working database. This code
687
-			// might however be called when ownCloud is not yet setup.
688
-			if(\OC::$server->getSystemConfig()->getValue('installed', false)) {
689
-				$config = $c->getConfig();
690
-				$appManager = $c->getAppManager();
691
-			} else {
692
-				$config = null;
693
-				$appManager = null;
694
-			}
695
-
696
-			return new Checker(
697
-					new EnvironmentHelper(),
698
-					new FileAccessHelper(),
699
-					new AppLocator(),
700
-					$config,
701
-					$c->getMemCacheFactory(),
702
-					$appManager,
703
-					$c->getTempManager()
704
-			);
705
-		});
706
-		$this->registerService(\OCP\IRequest::class, function ($c) {
707
-			if (isset($this['urlParams'])) {
708
-				$urlParams = $this['urlParams'];
709
-			} else {
710
-				$urlParams = [];
711
-			}
712
-
713
-			if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
714
-				&& in_array('fakeinput', stream_get_wrappers())
715
-			) {
716
-				$stream = 'fakeinput://data';
717
-			} else {
718
-				$stream = 'php://input';
719
-			}
720
-
721
-			return new Request(
722
-				[
723
-					'get' => $_GET,
724
-					'post' => $_POST,
725
-					'files' => $_FILES,
726
-					'server' => $_SERVER,
727
-					'env' => $_ENV,
728
-					'cookies' => $_COOKIE,
729
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
730
-						? $_SERVER['REQUEST_METHOD']
731
-						: null,
732
-					'urlParams' => $urlParams,
733
-				],
734
-				$this->getSecureRandom(),
735
-				$this->getConfig(),
736
-				$this->getCsrfTokenManager(),
737
-				$stream
738
-			);
739
-		});
740
-		$this->registerAlias('Request', \OCP\IRequest::class);
741
-
742
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
743
-			return new Mailer(
744
-				$c->getConfig(),
745
-				$c->getLogger(),
746
-				$c->query(Defaults::class),
747
-				$c->getURLGenerator(),
748
-				$c->getL10N('lib')
749
-			);
750
-		});
751
-		$this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
752
-
753
-		$this->registerService('LDAPProvider', function(Server $c) {
754
-			$config = $c->getConfig();
755
-			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
756
-			if(is_null($factoryClass)) {
757
-				throw new \Exception('ldapProviderFactory not set');
758
-			}
759
-			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
760
-			$factory = new $factoryClass($this);
761
-			return $factory->getLDAPProvider();
762
-		});
763
-		$this->registerService('LockingProvider', function (Server $c) {
764
-			$ini = $c->getIniWrapper();
765
-			$config = $c->getConfig();
766
-			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
767
-			if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
768
-				/** @var \OC\Memcache\Factory $memcacheFactory */
769
-				$memcacheFactory = $c->getMemCacheFactory();
770
-				$memcache = $memcacheFactory->createLocking('lock');
771
-				if (!($memcache instanceof \OC\Memcache\NullCache)) {
772
-					return new MemcacheLockingProvider($memcache, $ttl);
773
-				}
774
-				return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
775
-			}
776
-			return new NoopLockingProvider();
777
-		});
778
-
779
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
780
-			return new \OC\Files\Mount\Manager();
781
-		});
782
-		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
783
-
784
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
785
-			return new \OC\Files\Type\Detection(
786
-				$c->getURLGenerator(),
787
-				\OC::$configDir,
788
-				\OC::$SERVERROOT . '/resources/config/'
789
-			);
790
-		});
791
-		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
792
-
793
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
794
-			return new \OC\Files\Type\Loader(
795
-				$c->getDatabaseConnection()
796
-			);
797
-		});
798
-		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
799
-
800
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
801
-			return new Manager(
802
-				$c->query(IValidator::class)
803
-			);
804
-		});
805
-		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
806
-
807
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
808
-			$manager = new \OC\CapabilitiesManager($c->getLogger());
809
-			$manager->registerCapability(function () use ($c) {
810
-				return new \OC\OCS\CoreCapabilities($c->getConfig());
811
-			});
812
-			return $manager;
813
-		});
814
-		$this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
815
-
816
-		$this->registerService(\OCP\Comments\ICommentsManager::class, function(Server $c) {
817
-			$config = $c->getConfig();
818
-			$factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
819
-			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
820
-			$factory = new $factoryClass($this);
821
-			return $factory->getManager();
822
-		});
823
-		$this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
824
-
825
-		$this->registerService('ThemingDefaults', function(Server $c) {
826
-			/*
120
+    /** @var string */
121
+    private $webRoot;
122
+
123
+    /**
124
+     * @param string $webRoot
125
+     * @param \OC\Config $config
126
+     */
127
+    public function __construct($webRoot, \OC\Config $config) {
128
+        parent::__construct();
129
+        $this->webRoot = $webRoot;
130
+
131
+        $this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
132
+        $this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
133
+
134
+        $this->registerService(\OCP\IPreview::class, function (Server $c) {
135
+            return new PreviewManager(
136
+                $c->getConfig(),
137
+                $c->getRootFolder(),
138
+                $c->getAppDataDir('preview'),
139
+                $c->getEventDispatcher(),
140
+                $c->getSession()->get('user_id')
141
+            );
142
+        });
143
+        $this->registerAlias('PreviewManager', \OCP\IPreview::class);
144
+
145
+        $this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
146
+            return new \OC\Preview\Watcher(
147
+                $c->getAppDataDir('preview')
148
+            );
149
+        });
150
+
151
+        $this->registerService('EncryptionManager', function (Server $c) {
152
+            $view = new View();
153
+            $util = new Encryption\Util(
154
+                $view,
155
+                $c->getUserManager(),
156
+                $c->getGroupManager(),
157
+                $c->getConfig()
158
+            );
159
+            return new Encryption\Manager(
160
+                $c->getConfig(),
161
+                $c->getLogger(),
162
+                $c->getL10N('core'),
163
+                new View(),
164
+                $util,
165
+                new ArrayCache()
166
+            );
167
+        });
168
+
169
+        $this->registerService('EncryptionFileHelper', function (Server $c) {
170
+            $util = new Encryption\Util(
171
+                new View(),
172
+                $c->getUserManager(),
173
+                $c->getGroupManager(),
174
+                $c->getConfig()
175
+            );
176
+            return new Encryption\File($util);
177
+        });
178
+
179
+        $this->registerService('EncryptionKeyStorage', function (Server $c) {
180
+            $view = new View();
181
+            $util = new Encryption\Util(
182
+                $view,
183
+                $c->getUserManager(),
184
+                $c->getGroupManager(),
185
+                $c->getConfig()
186
+            );
187
+
188
+            return new Encryption\Keys\Storage($view, $util);
189
+        });
190
+        $this->registerService('TagMapper', function (Server $c) {
191
+            return new TagMapper($c->getDatabaseConnection());
192
+        });
193
+
194
+        $this->registerService(\OCP\ITagManager::class, function (Server $c) {
195
+            $tagMapper = $c->query('TagMapper');
196
+            return new TagManager($tagMapper, $c->getUserSession());
197
+        });
198
+        $this->registerAlias('TagManager', \OCP\ITagManager::class);
199
+
200
+        $this->registerService('SystemTagManagerFactory', function (Server $c) {
201
+            $config = $c->getConfig();
202
+            $factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
203
+            /** @var \OC\SystemTag\ManagerFactory $factory */
204
+            $factory = new $factoryClass($this);
205
+            return $factory;
206
+        });
207
+        $this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
208
+            return $c->query('SystemTagManagerFactory')->getManager();
209
+        });
210
+        $this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
211
+
212
+        $this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
213
+            return $c->query('SystemTagManagerFactory')->getObjectMapper();
214
+        });
215
+        $this->registerService('RootFolder', function (Server $c) {
216
+            $manager = \OC\Files\Filesystem::getMountManager(null);
217
+            $view = new View();
218
+            $root = new Root(
219
+                $manager,
220
+                $view,
221
+                null,
222
+                $c->getUserMountCache(),
223
+                $this->getLogger(),
224
+                $this->getUserManager()
225
+            );
226
+            $connector = new HookConnector($root, $view);
227
+            $connector->viewToNode();
228
+
229
+            $previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
230
+            $previewConnector->connectWatcher();
231
+
232
+            return $root;
233
+        });
234
+        $this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
235
+
236
+        $this->registerService(\OCP\Files\IRootFolder::class, function(Server $c) {
237
+            return new LazyRoot(function() use ($c) {
238
+                return $c->query('RootFolder');
239
+            });
240
+        });
241
+        $this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
242
+
243
+        $this->registerService(\OCP\IUserManager::class, function (Server $c) {
244
+            $config = $c->getConfig();
245
+            return new \OC\User\Manager($config);
246
+        });
247
+        $this->registerAlias('UserManager', \OCP\IUserManager::class);
248
+
249
+        $this->registerService(\OCP\IGroupManager::class, function (Server $c) {
250
+            $groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
251
+            $groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
252
+                \OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
253
+            });
254
+            $groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
255
+                \OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
256
+            });
257
+            $groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
258
+                \OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
259
+            });
260
+            $groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
261
+                \OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
262
+            });
263
+            $groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
264
+                \OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
265
+            });
266
+            $groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
267
+                \OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
268
+                //Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
269
+                \OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
270
+            });
271
+            return $groupManager;
272
+        });
273
+        $this->registerAlias('GroupManager', \OCP\IGroupManager::class);
274
+
275
+        $this->registerService(Store::class, function(Server $c) {
276
+            $session = $c->getSession();
277
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
278
+                $tokenProvider = $c->query('OC\Authentication\Token\IProvider');
279
+            } else {
280
+                $tokenProvider = null;
281
+            }
282
+            $logger = $c->getLogger();
283
+            return new Store($session, $logger, $tokenProvider);
284
+        });
285
+        $this->registerAlias(IStore::class, Store::class);
286
+        $this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
287
+            $dbConnection = $c->getDatabaseConnection();
288
+            return new Authentication\Token\DefaultTokenMapper($dbConnection);
289
+        });
290
+        $this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
291
+            $mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
292
+            $crypto = $c->getCrypto();
293
+            $config = $c->getConfig();
294
+            $logger = $c->getLogger();
295
+            $timeFactory = new TimeFactory();
296
+            return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
297
+        });
298
+        $this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
299
+
300
+        $this->registerService(\OCP\IUserSession::class, function (Server $c) {
301
+            $manager = $c->getUserManager();
302
+            $session = new \OC\Session\Memory('');
303
+            $timeFactory = new TimeFactory();
304
+            // Token providers might require a working database. This code
305
+            // might however be called when ownCloud is not yet setup.
306
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
307
+                $defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
308
+            } else {
309
+                $defaultTokenProvider = null;
310
+            }
311
+
312
+            $userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom(), $c->getLockdownManager());
313
+            $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
314
+                \OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
315
+            });
316
+            $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
317
+                /** @var $user \OC\User\User */
318
+                \OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
319
+            });
320
+            $userSession->listen('\OC\User', 'preDelete', function ($user) {
321
+                /** @var $user \OC\User\User */
322
+                \OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
323
+            });
324
+            $userSession->listen('\OC\User', 'postDelete', function ($user) {
325
+                /** @var $user \OC\User\User */
326
+                \OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
327
+            });
328
+            $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
329
+                /** @var $user \OC\User\User */
330
+                \OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
331
+            });
332
+            $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
333
+                /** @var $user \OC\User\User */
334
+                \OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
335
+            });
336
+            $userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
337
+                \OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
338
+            });
339
+            $userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
340
+                /** @var $user \OC\User\User */
341
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
342
+            });
343
+            $userSession->listen('\OC\User', 'logout', function () {
344
+                \OC_Hook::emit('OC_User', 'logout', array());
345
+            });
346
+            $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
347
+                /** @var $user \OC\User\User */
348
+                \OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
349
+            });
350
+            return $userSession;
351
+        });
352
+        $this->registerAlias('UserSession', \OCP\IUserSession::class);
353
+
354
+        $this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
355
+            return new \OC\Authentication\TwoFactorAuth\Manager($c->getAppManager(), $c->getSession(), $c->getConfig(), $c->getActivityManager(), $c->getLogger());
356
+        });
357
+
358
+        $this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
359
+        $this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
360
+
361
+        $this->registerService(\OC\AllConfig::class, function (Server $c) {
362
+            return new \OC\AllConfig(
363
+                $c->getSystemConfig()
364
+            );
365
+        });
366
+        $this->registerAlias('AllConfig', \OC\AllConfig::class);
367
+        $this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
368
+
369
+        $this->registerService('SystemConfig', function ($c) use ($config) {
370
+            return new \OC\SystemConfig($config);
371
+        });
372
+
373
+        $this->registerService(\OC\AppConfig::class, function (Server $c) {
374
+            return new \OC\AppConfig($c->getDatabaseConnection());
375
+        });
376
+        $this->registerAlias('AppConfig', \OC\AppConfig::class);
377
+        $this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
378
+
379
+        $this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
380
+            return new \OC\L10N\Factory(
381
+                $c->getConfig(),
382
+                $c->getRequest(),
383
+                $c->getUserSession(),
384
+                \OC::$SERVERROOT
385
+            );
386
+        });
387
+        $this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
388
+
389
+        $this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
390
+            $config = $c->getConfig();
391
+            $cacheFactory = $c->getMemCacheFactory();
392
+            return new \OC\URLGenerator(
393
+                $config,
394
+                $cacheFactory
395
+            );
396
+        });
397
+        $this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
398
+
399
+        $this->registerService('AppHelper', function ($c) {
400
+            return new \OC\AppHelper();
401
+        });
402
+        $this->registerService('AppFetcher', function ($c) {
403
+            return new AppFetcher(
404
+                $this->getAppDataDir('appstore'),
405
+                $this->getHTTPClientService(),
406
+                $this->query(TimeFactory::class),
407
+                $this->getConfig()
408
+            );
409
+        });
410
+        $this->registerService('CategoryFetcher', function ($c) {
411
+            return new CategoryFetcher(
412
+                $this->getAppDataDir('appstore'),
413
+                $this->getHTTPClientService(),
414
+                $this->query(TimeFactory::class),
415
+                $this->getConfig()
416
+            );
417
+        });
418
+
419
+        $this->registerService(\OCP\ICache::class, function ($c) {
420
+            return new Cache\File();
421
+        });
422
+        $this->registerAlias('UserCache', \OCP\ICache::class);
423
+
424
+        $this->registerService(Factory::class, function (Server $c) {
425
+            $config = $c->getConfig();
426
+
427
+            if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
428
+                $v = \OC_App::getAppVersions();
429
+                $v['core'] = md5(file_get_contents(\OC::$SERVERROOT . '/version.php'));
430
+                $version = implode(',', $v);
431
+                $instanceId = \OC_Util::getInstanceId();
432
+                $path = \OC::$SERVERROOT;
433
+                $prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . \OC::$WEBROOT);
434
+                return new \OC\Memcache\Factory($prefix, $c->getLogger(),
435
+                    $config->getSystemValue('memcache.local', null),
436
+                    $config->getSystemValue('memcache.distributed', null),
437
+                    $config->getSystemValue('memcache.locking', null)
438
+                );
439
+            }
440
+
441
+            return new \OC\Memcache\Factory('', $c->getLogger(),
442
+                '\\OC\\Memcache\\ArrayCache',
443
+                '\\OC\\Memcache\\ArrayCache',
444
+                '\\OC\\Memcache\\ArrayCache'
445
+            );
446
+        });
447
+        $this->registerAlias('MemCacheFactory', Factory::class);
448
+        $this->registerAlias(ICacheFactory::class, Factory::class);
449
+
450
+        $this->registerService('RedisFactory', function (Server $c) {
451
+            $systemConfig = $c->getSystemConfig();
452
+            return new RedisFactory($systemConfig);
453
+        });
454
+
455
+        $this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
456
+            return new \OC\Activity\Manager(
457
+                $c->getRequest(),
458
+                $c->getUserSession(),
459
+                $c->getConfig(),
460
+                $c->query(IValidator::class)
461
+            );
462
+        });
463
+        $this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
464
+
465
+        $this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
466
+            return new \OC\Activity\EventMerger(
467
+                $c->getL10N('lib')
468
+            );
469
+        });
470
+        $this->registerAlias(IValidator::class, Validator::class);
471
+
472
+        $this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
473
+            return new AvatarManager(
474
+                $c->getUserManager(),
475
+                $c->getAppDataDir('avatar'),
476
+                $c->getL10N('lib'),
477
+                $c->getLogger(),
478
+                $c->getConfig()
479
+            );
480
+        });
481
+        $this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
482
+
483
+        $this->registerService(\OCP\ILogger::class, function (Server $c) {
484
+            $logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
485
+            $logger = Log::getLogClass($logType);
486
+            call_user_func(array($logger, 'init'));
487
+
488
+            return new Log($logger);
489
+        });
490
+        $this->registerAlias('Logger', \OCP\ILogger::class);
491
+
492
+        $this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
493
+            $config = $c->getConfig();
494
+            return new \OC\BackgroundJob\JobList(
495
+                $c->getDatabaseConnection(),
496
+                $config,
497
+                new TimeFactory()
498
+            );
499
+        });
500
+        $this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
501
+
502
+        $this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
503
+            $cacheFactory = $c->getMemCacheFactory();
504
+            $logger = $c->getLogger();
505
+            if ($cacheFactory->isAvailable()) {
506
+                $router = new \OC\Route\CachingRouter($cacheFactory->create('route'), $logger);
507
+            } else {
508
+                $router = new \OC\Route\Router($logger);
509
+            }
510
+            return $router;
511
+        });
512
+        $this->registerAlias('Router', \OCP\Route\IRouter::class);
513
+
514
+        $this->registerService(\OCP\ISearch::class, function ($c) {
515
+            return new Search();
516
+        });
517
+        $this->registerAlias('Search', \OCP\ISearch::class);
518
+
519
+        $this->registerService(\OC\Security\RateLimiting\Limiter::class, function($c) {
520
+            return new \OC\Security\RateLimiting\Limiter(
521
+                $this->getUserSession(),
522
+                $this->getRequest(),
523
+                new \OC\AppFramework\Utility\TimeFactory(),
524
+                $c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
525
+            );
526
+        });
527
+        $this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function($c) {
528
+            return new \OC\Security\RateLimiting\Backend\MemoryCache(
529
+                $this->getMemCacheFactory(),
530
+                new \OC\AppFramework\Utility\TimeFactory()
531
+            );
532
+        });
533
+
534
+        $this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
535
+            return new SecureRandom();
536
+        });
537
+        $this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
538
+
539
+        $this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
540
+            return new Crypto($c->getConfig(), $c->getSecureRandom());
541
+        });
542
+        $this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
543
+
544
+        $this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
545
+            return new Hasher($c->getConfig());
546
+        });
547
+        $this->registerAlias('Hasher', \OCP\Security\IHasher::class);
548
+
549
+        $this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
550
+            return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
551
+        });
552
+        $this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
553
+
554
+        $this->registerService(IDBConnection::class, function (Server $c) {
555
+            $systemConfig = $c->getSystemConfig();
556
+            $factory = new \OC\DB\ConnectionFactory($systemConfig);
557
+            $type = $systemConfig->getValue('dbtype', 'sqlite');
558
+            if (!$factory->isValidType($type)) {
559
+                throw new \OC\DatabaseException('Invalid database type');
560
+            }
561
+            $connectionParams = $factory->createConnectionParams();
562
+            $connection = $factory->getConnection($type, $connectionParams);
563
+            $connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
564
+            return $connection;
565
+        });
566
+        $this->registerAlias('DatabaseConnection', IDBConnection::class);
567
+
568
+        $this->registerService('HTTPHelper', function (Server $c) {
569
+            $config = $c->getConfig();
570
+            return new HTTPHelper(
571
+                $config,
572
+                $c->getHTTPClientService()
573
+            );
574
+        });
575
+
576
+        $this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
577
+            $user = \OC_User::getUser();
578
+            $uid = $user ? $user : null;
579
+            return new ClientService(
580
+                $c->getConfig(),
581
+                new \OC\Security\CertificateManager($uid, new View(), $c->getConfig(), $c->getLogger())
582
+            );
583
+        });
584
+        $this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
585
+
586
+        $this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
587
+            if ($c->getSystemConfig()->getValue('debug', false)) {
588
+                return new EventLogger();
589
+            } else {
590
+                return new NullEventLogger();
591
+            }
592
+        });
593
+        $this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
594
+
595
+        $this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
596
+            if ($c->getSystemConfig()->getValue('debug', false)) {
597
+                return new QueryLogger();
598
+            } else {
599
+                return new NullQueryLogger();
600
+            }
601
+        });
602
+        $this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
603
+
604
+        $this->registerService(TempManager::class, function (Server $c) {
605
+            return new TempManager(
606
+                $c->getLogger(),
607
+                $c->getConfig()
608
+            );
609
+        });
610
+        $this->registerAlias('TempManager', TempManager::class);
611
+        $this->registerAlias(ITempManager::class, TempManager::class);
612
+
613
+        $this->registerService(AppManager::class, function (Server $c) {
614
+            return new \OC\App\AppManager(
615
+                $c->getUserSession(),
616
+                $c->getAppConfig(),
617
+                $c->getGroupManager(),
618
+                $c->getMemCacheFactory(),
619
+                $c->getEventDispatcher()
620
+            );
621
+        });
622
+        $this->registerAlias('AppManager', AppManager::class);
623
+        $this->registerAlias(IAppManager::class, AppManager::class);
624
+
625
+        $this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
626
+            return new DateTimeZone(
627
+                $c->getConfig(),
628
+                $c->getSession()
629
+            );
630
+        });
631
+        $this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
632
+
633
+        $this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
634
+            $language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
635
+
636
+            return new DateTimeFormatter(
637
+                $c->getDateTimeZone()->getTimeZone(),
638
+                $c->getL10N('lib', $language)
639
+            );
640
+        });
641
+        $this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
642
+
643
+        $this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
644
+            $mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
645
+            $listener = new UserMountCacheListener($mountCache);
646
+            $listener->listen($c->getUserManager());
647
+            return $mountCache;
648
+        });
649
+        $this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
650
+
651
+        $this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
652
+            $loader = \OC\Files\Filesystem::getLoader();
653
+            $mountCache = $c->query('UserMountCache');
654
+            $manager =  new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
655
+
656
+            // builtin providers
657
+
658
+            $config = $c->getConfig();
659
+            $manager->registerProvider(new CacheMountProvider($config));
660
+            $manager->registerHomeProvider(new LocalHomeMountProvider());
661
+            $manager->registerHomeProvider(new ObjectHomeMountProvider($config));
662
+
663
+            return $manager;
664
+        });
665
+        $this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
666
+
667
+        $this->registerService('IniWrapper', function ($c) {
668
+            return new IniGetWrapper();
669
+        });
670
+        $this->registerService('AsyncCommandBus', function (Server $c) {
671
+            $jobList = $c->getJobList();
672
+            return new AsyncBus($jobList);
673
+        });
674
+        $this->registerService('TrustedDomainHelper', function ($c) {
675
+            return new TrustedDomainHelper($this->getConfig());
676
+        });
677
+        $this->registerService('Throttler', function(Server $c) {
678
+            return new Throttler(
679
+                $c->getDatabaseConnection(),
680
+                new TimeFactory(),
681
+                $c->getLogger(),
682
+                $c->getConfig()
683
+            );
684
+        });
685
+        $this->registerService('IntegrityCodeChecker', function (Server $c) {
686
+            // IConfig and IAppManager requires a working database. This code
687
+            // might however be called when ownCloud is not yet setup.
688
+            if(\OC::$server->getSystemConfig()->getValue('installed', false)) {
689
+                $config = $c->getConfig();
690
+                $appManager = $c->getAppManager();
691
+            } else {
692
+                $config = null;
693
+                $appManager = null;
694
+            }
695
+
696
+            return new Checker(
697
+                    new EnvironmentHelper(),
698
+                    new FileAccessHelper(),
699
+                    new AppLocator(),
700
+                    $config,
701
+                    $c->getMemCacheFactory(),
702
+                    $appManager,
703
+                    $c->getTempManager()
704
+            );
705
+        });
706
+        $this->registerService(\OCP\IRequest::class, function ($c) {
707
+            if (isset($this['urlParams'])) {
708
+                $urlParams = $this['urlParams'];
709
+            } else {
710
+                $urlParams = [];
711
+            }
712
+
713
+            if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
714
+                && in_array('fakeinput', stream_get_wrappers())
715
+            ) {
716
+                $stream = 'fakeinput://data';
717
+            } else {
718
+                $stream = 'php://input';
719
+            }
720
+
721
+            return new Request(
722
+                [
723
+                    'get' => $_GET,
724
+                    'post' => $_POST,
725
+                    'files' => $_FILES,
726
+                    'server' => $_SERVER,
727
+                    'env' => $_ENV,
728
+                    'cookies' => $_COOKIE,
729
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
730
+                        ? $_SERVER['REQUEST_METHOD']
731
+                        : null,
732
+                    'urlParams' => $urlParams,
733
+                ],
734
+                $this->getSecureRandom(),
735
+                $this->getConfig(),
736
+                $this->getCsrfTokenManager(),
737
+                $stream
738
+            );
739
+        });
740
+        $this->registerAlias('Request', \OCP\IRequest::class);
741
+
742
+        $this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
743
+            return new Mailer(
744
+                $c->getConfig(),
745
+                $c->getLogger(),
746
+                $c->query(Defaults::class),
747
+                $c->getURLGenerator(),
748
+                $c->getL10N('lib')
749
+            );
750
+        });
751
+        $this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
752
+
753
+        $this->registerService('LDAPProvider', function(Server $c) {
754
+            $config = $c->getConfig();
755
+            $factoryClass = $config->getSystemValue('ldapProviderFactory', null);
756
+            if(is_null($factoryClass)) {
757
+                throw new \Exception('ldapProviderFactory not set');
758
+            }
759
+            /** @var \OCP\LDAP\ILDAPProviderFactory $factory */
760
+            $factory = new $factoryClass($this);
761
+            return $factory->getLDAPProvider();
762
+        });
763
+        $this->registerService('LockingProvider', function (Server $c) {
764
+            $ini = $c->getIniWrapper();
765
+            $config = $c->getConfig();
766
+            $ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
767
+            if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
768
+                /** @var \OC\Memcache\Factory $memcacheFactory */
769
+                $memcacheFactory = $c->getMemCacheFactory();
770
+                $memcache = $memcacheFactory->createLocking('lock');
771
+                if (!($memcache instanceof \OC\Memcache\NullCache)) {
772
+                    return new MemcacheLockingProvider($memcache, $ttl);
773
+                }
774
+                return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
775
+            }
776
+            return new NoopLockingProvider();
777
+        });
778
+
779
+        $this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
780
+            return new \OC\Files\Mount\Manager();
781
+        });
782
+        $this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
783
+
784
+        $this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
785
+            return new \OC\Files\Type\Detection(
786
+                $c->getURLGenerator(),
787
+                \OC::$configDir,
788
+                \OC::$SERVERROOT . '/resources/config/'
789
+            );
790
+        });
791
+        $this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
792
+
793
+        $this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
794
+            return new \OC\Files\Type\Loader(
795
+                $c->getDatabaseConnection()
796
+            );
797
+        });
798
+        $this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
799
+
800
+        $this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
801
+            return new Manager(
802
+                $c->query(IValidator::class)
803
+            );
804
+        });
805
+        $this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
806
+
807
+        $this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
808
+            $manager = new \OC\CapabilitiesManager($c->getLogger());
809
+            $manager->registerCapability(function () use ($c) {
810
+                return new \OC\OCS\CoreCapabilities($c->getConfig());
811
+            });
812
+            return $manager;
813
+        });
814
+        $this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
815
+
816
+        $this->registerService(\OCP\Comments\ICommentsManager::class, function(Server $c) {
817
+            $config = $c->getConfig();
818
+            $factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
819
+            /** @var \OCP\Comments\ICommentsManagerFactory $factory */
820
+            $factory = new $factoryClass($this);
821
+            return $factory->getManager();
822
+        });
823
+        $this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
824
+
825
+        $this->registerService('ThemingDefaults', function(Server $c) {
826
+            /*
827 827
 			 * Dark magic for autoloader.
828 828
 			 * If we do a class_exists it will try to load the class which will
829 829
 			 * make composer cache the result. Resulting in errors when enabling
830 830
 			 * the theming app.
831 831
 			 */
832
-			$prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
833
-			if (isset($prefixes['OCA\\Theming\\'])) {
834
-				$classExists = true;
835
-			} else {
836
-				$classExists = false;
837
-			}
838
-
839
-			if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming')) {
840
-				return new ThemingDefaults(
841
-					$c->getConfig(),
842
-					$c->getL10N('theming'),
843
-					$c->getURLGenerator(),
844
-					new \OC_Defaults(),
845
-					$c->getAppDataDir('theming'),
846
-					$c->getMemCacheFactory()
847
-				);
848
-			}
849
-			return new \OC_Defaults();
850
-		});
851
-		$this->registerService(EventDispatcher::class, function () {
852
-			return new EventDispatcher();
853
-		});
854
-		$this->registerAlias('EventDispatcher', EventDispatcher::class);
855
-		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
856
-
857
-		$this->registerService('CryptoWrapper', function (Server $c) {
858
-			// FIXME: Instantiiated here due to cyclic dependency
859
-			$request = new Request(
860
-				[
861
-					'get' => $_GET,
862
-					'post' => $_POST,
863
-					'files' => $_FILES,
864
-					'server' => $_SERVER,
865
-					'env' => $_ENV,
866
-					'cookies' => $_COOKIE,
867
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
868
-						? $_SERVER['REQUEST_METHOD']
869
-						: null,
870
-				],
871
-				$c->getSecureRandom(),
872
-				$c->getConfig()
873
-			);
874
-
875
-			return new CryptoWrapper(
876
-				$c->getConfig(),
877
-				$c->getCrypto(),
878
-				$c->getSecureRandom(),
879
-				$request
880
-			);
881
-		});
882
-		$this->registerService('CsrfTokenManager', function (Server $c) {
883
-			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
884
-
885
-			return new CsrfTokenManager(
886
-				$tokenGenerator,
887
-				$c->query(SessionStorage::class)
888
-			);
889
-		});
890
-		$this->registerService(SessionStorage::class, function (Server $c) {
891
-			return new SessionStorage($c->getSession());
892
-		});
893
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
894
-			return new ContentSecurityPolicyManager();
895
-		});
896
-		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
897
-
898
-		$this->registerService('ContentSecurityPolicyNonceManager', function(Server $c) {
899
-			return new ContentSecurityPolicyNonceManager(
900
-				$c->getCsrfTokenManager(),
901
-				$c->getRequest()
902
-			);
903
-		});
904
-
905
-		$this->registerService(\OCP\Share\IManager::class, function(Server $c) {
906
-			$config = $c->getConfig();
907
-			$factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
908
-			/** @var \OCP\Share\IProviderFactory $factory */
909
-			$factory = new $factoryClass($this);
910
-
911
-			$manager = new \OC\Share20\Manager(
912
-				$c->getLogger(),
913
-				$c->getConfig(),
914
-				$c->getSecureRandom(),
915
-				$c->getHasher(),
916
-				$c->getMountManager(),
917
-				$c->getGroupManager(),
918
-				$c->getL10N('core'),
919
-				$factory,
920
-				$c->getUserManager(),
921
-				$c->getLazyRootFolder(),
922
-				$c->getEventDispatcher()
923
-			);
924
-
925
-			return $manager;
926
-		});
927
-		$this->registerAlias('ShareManager', \OCP\Share\IManager::class);
928
-
929
-		$this->registerService('SettingsManager', function(Server $c) {
930
-			$manager = new \OC\Settings\Manager(
931
-				$c->getLogger(),
932
-				$c->getDatabaseConnection(),
933
-				$c->getL10N('lib'),
934
-				$c->getConfig(),
935
-				$c->getEncryptionManager(),
936
-				$c->getUserManager(),
937
-				$c->getLockingProvider(),
938
-				$c->getRequest(),
939
-				new \OC\Settings\Mapper($c->getDatabaseConnection()),
940
-				$c->getURLGenerator()
941
-			);
942
-			return $manager;
943
-		});
944
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
945
-			return new \OC\Files\AppData\Factory(
946
-				$c->getRootFolder(),
947
-				$c->getSystemConfig()
948
-			);
949
-		});
950
-
951
-		$this->registerService('LockdownManager', function (Server $c) {
952
-			return new LockdownManager(function() use ($c) {
953
-				return $c->getSession();
954
-			});
955
-		});
956
-
957
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
958
-			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
959
-		});
960
-
961
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
962
-			return new CloudIdManager();
963
-		});
964
-
965
-		/* To trick DI since we don't extend the DIContainer here */
966
-		$this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
967
-			return new CleanPreviewsBackgroundJob(
968
-				$c->getRootFolder(),
969
-				$c->getLogger(),
970
-				$c->getJobList(),
971
-				new TimeFactory()
972
-			);
973
-		});
974
-
975
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
976
-		$this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
977
-
978
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
979
-		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
980
-
981
-		$this->registerService(Defaults::class, function (Server $c) {
982
-			return new Defaults(
983
-				$c->getThemingDefaults()
984
-			);
985
-		});
986
-		$this->registerAlias('Defaults', \OCP\Defaults::class);
987
-
988
-		$this->registerService(\OCP\ISession::class, function(SimpleContainer $c) {
989
-			return $c->query(\OCP\IUserSession::class)->getSession();
990
-		});
991
-	}
992
-
993
-	/**
994
-	 * @return \OCP\Contacts\IManager
995
-	 */
996
-	public function getContactsManager() {
997
-		return $this->query('ContactsManager');
998
-	}
999
-
1000
-	/**
1001
-	 * @return \OC\Encryption\Manager
1002
-	 */
1003
-	public function getEncryptionManager() {
1004
-		return $this->query('EncryptionManager');
1005
-	}
1006
-
1007
-	/**
1008
-	 * @return \OC\Encryption\File
1009
-	 */
1010
-	public function getEncryptionFilesHelper() {
1011
-		return $this->query('EncryptionFileHelper');
1012
-	}
1013
-
1014
-	/**
1015
-	 * @return \OCP\Encryption\Keys\IStorage
1016
-	 */
1017
-	public function getEncryptionKeyStorage() {
1018
-		return $this->query('EncryptionKeyStorage');
1019
-	}
1020
-
1021
-	/**
1022
-	 * The current request object holding all information about the request
1023
-	 * currently being processed is returned from this method.
1024
-	 * In case the current execution was not initiated by a web request null is returned
1025
-	 *
1026
-	 * @return \OCP\IRequest
1027
-	 */
1028
-	public function getRequest() {
1029
-		return $this->query('Request');
1030
-	}
1031
-
1032
-	/**
1033
-	 * Returns the preview manager which can create preview images for a given file
1034
-	 *
1035
-	 * @return \OCP\IPreview
1036
-	 */
1037
-	public function getPreviewManager() {
1038
-		return $this->query('PreviewManager');
1039
-	}
1040
-
1041
-	/**
1042
-	 * Returns the tag manager which can get and set tags for different object types
1043
-	 *
1044
-	 * @see \OCP\ITagManager::load()
1045
-	 * @return \OCP\ITagManager
1046
-	 */
1047
-	public function getTagManager() {
1048
-		return $this->query('TagManager');
1049
-	}
1050
-
1051
-	/**
1052
-	 * Returns the system-tag manager
1053
-	 *
1054
-	 * @return \OCP\SystemTag\ISystemTagManager
1055
-	 *
1056
-	 * @since 9.0.0
1057
-	 */
1058
-	public function getSystemTagManager() {
1059
-		return $this->query('SystemTagManager');
1060
-	}
1061
-
1062
-	/**
1063
-	 * Returns the system-tag object mapper
1064
-	 *
1065
-	 * @return \OCP\SystemTag\ISystemTagObjectMapper
1066
-	 *
1067
-	 * @since 9.0.0
1068
-	 */
1069
-	public function getSystemTagObjectMapper() {
1070
-		return $this->query('SystemTagObjectMapper');
1071
-	}
1072
-
1073
-	/**
1074
-	 * Returns the avatar manager, used for avatar functionality
1075
-	 *
1076
-	 * @return \OCP\IAvatarManager
1077
-	 */
1078
-	public function getAvatarManager() {
1079
-		return $this->query('AvatarManager');
1080
-	}
1081
-
1082
-	/**
1083
-	 * Returns the root folder of ownCloud's data directory
1084
-	 *
1085
-	 * @return \OCP\Files\IRootFolder
1086
-	 */
1087
-	public function getRootFolder() {
1088
-		return $this->query('LazyRootFolder');
1089
-	}
1090
-
1091
-	/**
1092
-	 * Returns the root folder of ownCloud's data directory
1093
-	 * This is the lazy variant so this gets only initialized once it
1094
-	 * is actually used.
1095
-	 *
1096
-	 * @return \OCP\Files\IRootFolder
1097
-	 */
1098
-	public function getLazyRootFolder() {
1099
-		return $this->query('LazyRootFolder');
1100
-	}
1101
-
1102
-	/**
1103
-	 * Returns a view to ownCloud's files folder
1104
-	 *
1105
-	 * @param string $userId user ID
1106
-	 * @return \OCP\Files\Folder|null
1107
-	 */
1108
-	public function getUserFolder($userId = null) {
1109
-		if ($userId === null) {
1110
-			$user = $this->getUserSession()->getUser();
1111
-			if (!$user) {
1112
-				return null;
1113
-			}
1114
-			$userId = $user->getUID();
1115
-		}
1116
-		$root = $this->getRootFolder();
1117
-		return $root->getUserFolder($userId);
1118
-	}
1119
-
1120
-	/**
1121
-	 * Returns an app-specific view in ownClouds data directory
1122
-	 *
1123
-	 * @return \OCP\Files\Folder
1124
-	 * @deprecated since 9.2.0 use IAppData
1125
-	 */
1126
-	public function getAppFolder() {
1127
-		$dir = '/' . \OC_App::getCurrentApp();
1128
-		$root = $this->getRootFolder();
1129
-		if (!$root->nodeExists($dir)) {
1130
-			$folder = $root->newFolder($dir);
1131
-		} else {
1132
-			$folder = $root->get($dir);
1133
-		}
1134
-		return $folder;
1135
-	}
1136
-
1137
-	/**
1138
-	 * @return \OC\User\Manager
1139
-	 */
1140
-	public function getUserManager() {
1141
-		return $this->query('UserManager');
1142
-	}
1143
-
1144
-	/**
1145
-	 * @return \OC\Group\Manager
1146
-	 */
1147
-	public function getGroupManager() {
1148
-		return $this->query('GroupManager');
1149
-	}
1150
-
1151
-	/**
1152
-	 * @return \OC\User\Session
1153
-	 */
1154
-	public function getUserSession() {
1155
-		return $this->query('UserSession');
1156
-	}
1157
-
1158
-	/**
1159
-	 * @return \OCP\ISession
1160
-	 */
1161
-	public function getSession() {
1162
-		return $this->query('UserSession')->getSession();
1163
-	}
1164
-
1165
-	/**
1166
-	 * @param \OCP\ISession $session
1167
-	 */
1168
-	public function setSession(\OCP\ISession $session) {
1169
-		$this->query(SessionStorage::class)->setSession($session);
1170
-		$this->query('UserSession')->setSession($session);
1171
-		$this->query(Store::class)->setSession($session);
1172
-	}
1173
-
1174
-	/**
1175
-	 * @return \OC\Authentication\TwoFactorAuth\Manager
1176
-	 */
1177
-	public function getTwoFactorAuthManager() {
1178
-		return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1179
-	}
1180
-
1181
-	/**
1182
-	 * @return \OC\NavigationManager
1183
-	 */
1184
-	public function getNavigationManager() {
1185
-		return $this->query('NavigationManager');
1186
-	}
1187
-
1188
-	/**
1189
-	 * @return \OCP\IConfig
1190
-	 */
1191
-	public function getConfig() {
1192
-		return $this->query('AllConfig');
1193
-	}
1194
-
1195
-	/**
1196
-	 * @internal For internal use only
1197
-	 * @return \OC\SystemConfig
1198
-	 */
1199
-	public function getSystemConfig() {
1200
-		return $this->query('SystemConfig');
1201
-	}
1202
-
1203
-	/**
1204
-	 * Returns the app config manager
1205
-	 *
1206
-	 * @return \OCP\IAppConfig
1207
-	 */
1208
-	public function getAppConfig() {
1209
-		return $this->query('AppConfig');
1210
-	}
1211
-
1212
-	/**
1213
-	 * @return \OCP\L10N\IFactory
1214
-	 */
1215
-	public function getL10NFactory() {
1216
-		return $this->query('L10NFactory');
1217
-	}
1218
-
1219
-	/**
1220
-	 * get an L10N instance
1221
-	 *
1222
-	 * @param string $app appid
1223
-	 * @param string $lang
1224
-	 * @return IL10N
1225
-	 */
1226
-	public function getL10N($app, $lang = null) {
1227
-		return $this->getL10NFactory()->get($app, $lang);
1228
-	}
1229
-
1230
-	/**
1231
-	 * @return \OCP\IURLGenerator
1232
-	 */
1233
-	public function getURLGenerator() {
1234
-		return $this->query('URLGenerator');
1235
-	}
1236
-
1237
-	/**
1238
-	 * @return \OCP\IHelper
1239
-	 */
1240
-	public function getHelper() {
1241
-		return $this->query('AppHelper');
1242
-	}
1243
-
1244
-	/**
1245
-	 * @return AppFetcher
1246
-	 */
1247
-	public function getAppFetcher() {
1248
-		return $this->query('AppFetcher');
1249
-	}
1250
-
1251
-	/**
1252
-	 * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1253
-	 * getMemCacheFactory() instead.
1254
-	 *
1255
-	 * @return \OCP\ICache
1256
-	 * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1257
-	 */
1258
-	public function getCache() {
1259
-		return $this->query('UserCache');
1260
-	}
1261
-
1262
-	/**
1263
-	 * Returns an \OCP\CacheFactory instance
1264
-	 *
1265
-	 * @return \OCP\ICacheFactory
1266
-	 */
1267
-	public function getMemCacheFactory() {
1268
-		return $this->query('MemCacheFactory');
1269
-	}
1270
-
1271
-	/**
1272
-	 * Returns an \OC\RedisFactory instance
1273
-	 *
1274
-	 * @return \OC\RedisFactory
1275
-	 */
1276
-	public function getGetRedisFactory() {
1277
-		return $this->query('RedisFactory');
1278
-	}
1279
-
1280
-
1281
-	/**
1282
-	 * Returns the current session
1283
-	 *
1284
-	 * @return \OCP\IDBConnection
1285
-	 */
1286
-	public function getDatabaseConnection() {
1287
-		return $this->query('DatabaseConnection');
1288
-	}
1289
-
1290
-	/**
1291
-	 * Returns the activity manager
1292
-	 *
1293
-	 * @return \OCP\Activity\IManager
1294
-	 */
1295
-	public function getActivityManager() {
1296
-		return $this->query('ActivityManager');
1297
-	}
1298
-
1299
-	/**
1300
-	 * Returns an job list for controlling background jobs
1301
-	 *
1302
-	 * @return \OCP\BackgroundJob\IJobList
1303
-	 */
1304
-	public function getJobList() {
1305
-		return $this->query('JobList');
1306
-	}
1307
-
1308
-	/**
1309
-	 * Returns a logger instance
1310
-	 *
1311
-	 * @return \OCP\ILogger
1312
-	 */
1313
-	public function getLogger() {
1314
-		return $this->query('Logger');
1315
-	}
1316
-
1317
-	/**
1318
-	 * Returns a router for generating and matching urls
1319
-	 *
1320
-	 * @return \OCP\Route\IRouter
1321
-	 */
1322
-	public function getRouter() {
1323
-		return $this->query('Router');
1324
-	}
1325
-
1326
-	/**
1327
-	 * Returns a search instance
1328
-	 *
1329
-	 * @return \OCP\ISearch
1330
-	 */
1331
-	public function getSearch() {
1332
-		return $this->query('Search');
1333
-	}
1334
-
1335
-	/**
1336
-	 * Returns a SecureRandom instance
1337
-	 *
1338
-	 * @return \OCP\Security\ISecureRandom
1339
-	 */
1340
-	public function getSecureRandom() {
1341
-		return $this->query('SecureRandom');
1342
-	}
1343
-
1344
-	/**
1345
-	 * Returns a Crypto instance
1346
-	 *
1347
-	 * @return \OCP\Security\ICrypto
1348
-	 */
1349
-	public function getCrypto() {
1350
-		return $this->query('Crypto');
1351
-	}
1352
-
1353
-	/**
1354
-	 * Returns a Hasher instance
1355
-	 *
1356
-	 * @return \OCP\Security\IHasher
1357
-	 */
1358
-	public function getHasher() {
1359
-		return $this->query('Hasher');
1360
-	}
1361
-
1362
-	/**
1363
-	 * Returns a CredentialsManager instance
1364
-	 *
1365
-	 * @return \OCP\Security\ICredentialsManager
1366
-	 */
1367
-	public function getCredentialsManager() {
1368
-		return $this->query('CredentialsManager');
1369
-	}
1370
-
1371
-	/**
1372
-	 * Returns an instance of the HTTP helper class
1373
-	 *
1374
-	 * @deprecated Use getHTTPClientService()
1375
-	 * @return \OC\HTTPHelper
1376
-	 */
1377
-	public function getHTTPHelper() {
1378
-		return $this->query('HTTPHelper');
1379
-	}
1380
-
1381
-	/**
1382
-	 * Get the certificate manager for the user
1383
-	 *
1384
-	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1385
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1386
-	 */
1387
-	public function getCertificateManager($userId = '') {
1388
-		if ($userId === '') {
1389
-			$userSession = $this->getUserSession();
1390
-			$user = $userSession->getUser();
1391
-			if (is_null($user)) {
1392
-				return null;
1393
-			}
1394
-			$userId = $user->getUID();
1395
-		}
1396
-		return new CertificateManager($userId, new View(), $this->getConfig(), $this->getLogger());
1397
-	}
1398
-
1399
-	/**
1400
-	 * Returns an instance of the HTTP client service
1401
-	 *
1402
-	 * @return \OCP\Http\Client\IClientService
1403
-	 */
1404
-	public function getHTTPClientService() {
1405
-		return $this->query('HttpClientService');
1406
-	}
1407
-
1408
-	/**
1409
-	 * Create a new event source
1410
-	 *
1411
-	 * @return \OCP\IEventSource
1412
-	 */
1413
-	public function createEventSource() {
1414
-		return new \OC_EventSource();
1415
-	}
1416
-
1417
-	/**
1418
-	 * Get the active event logger
1419
-	 *
1420
-	 * The returned logger only logs data when debug mode is enabled
1421
-	 *
1422
-	 * @return \OCP\Diagnostics\IEventLogger
1423
-	 */
1424
-	public function getEventLogger() {
1425
-		return $this->query('EventLogger');
1426
-	}
1427
-
1428
-	/**
1429
-	 * Get the active query logger
1430
-	 *
1431
-	 * The returned logger only logs data when debug mode is enabled
1432
-	 *
1433
-	 * @return \OCP\Diagnostics\IQueryLogger
1434
-	 */
1435
-	public function getQueryLogger() {
1436
-		return $this->query('QueryLogger');
1437
-	}
1438
-
1439
-	/**
1440
-	 * Get the manager for temporary files and folders
1441
-	 *
1442
-	 * @return \OCP\ITempManager
1443
-	 */
1444
-	public function getTempManager() {
1445
-		return $this->query('TempManager');
1446
-	}
1447
-
1448
-	/**
1449
-	 * Get the app manager
1450
-	 *
1451
-	 * @return \OCP\App\IAppManager
1452
-	 */
1453
-	public function getAppManager() {
1454
-		return $this->query('AppManager');
1455
-	}
1456
-
1457
-	/**
1458
-	 * Creates a new mailer
1459
-	 *
1460
-	 * @return \OCP\Mail\IMailer
1461
-	 */
1462
-	public function getMailer() {
1463
-		return $this->query('Mailer');
1464
-	}
1465
-
1466
-	/**
1467
-	 * Get the webroot
1468
-	 *
1469
-	 * @return string
1470
-	 */
1471
-	public function getWebRoot() {
1472
-		return $this->webRoot;
1473
-	}
1474
-
1475
-	/**
1476
-	 * @return \OC\OCSClient
1477
-	 */
1478
-	public function getOcsClient() {
1479
-		return $this->query('OcsClient');
1480
-	}
1481
-
1482
-	/**
1483
-	 * @return \OCP\IDateTimeZone
1484
-	 */
1485
-	public function getDateTimeZone() {
1486
-		return $this->query('DateTimeZone');
1487
-	}
1488
-
1489
-	/**
1490
-	 * @return \OCP\IDateTimeFormatter
1491
-	 */
1492
-	public function getDateTimeFormatter() {
1493
-		return $this->query('DateTimeFormatter');
1494
-	}
1495
-
1496
-	/**
1497
-	 * @return \OCP\Files\Config\IMountProviderCollection
1498
-	 */
1499
-	public function getMountProviderCollection() {
1500
-		return $this->query('MountConfigManager');
1501
-	}
1502
-
1503
-	/**
1504
-	 * Get the IniWrapper
1505
-	 *
1506
-	 * @return IniGetWrapper
1507
-	 */
1508
-	public function getIniWrapper() {
1509
-		return $this->query('IniWrapper');
1510
-	}
1511
-
1512
-	/**
1513
-	 * @return \OCP\Command\IBus
1514
-	 */
1515
-	public function getCommandBus() {
1516
-		return $this->query('AsyncCommandBus');
1517
-	}
1518
-
1519
-	/**
1520
-	 * Get the trusted domain helper
1521
-	 *
1522
-	 * @return TrustedDomainHelper
1523
-	 */
1524
-	public function getTrustedDomainHelper() {
1525
-		return $this->query('TrustedDomainHelper');
1526
-	}
1527
-
1528
-	/**
1529
-	 * Get the locking provider
1530
-	 *
1531
-	 * @return \OCP\Lock\ILockingProvider
1532
-	 * @since 8.1.0
1533
-	 */
1534
-	public function getLockingProvider() {
1535
-		return $this->query('LockingProvider');
1536
-	}
1537
-
1538
-	/**
1539
-	 * @return \OCP\Files\Mount\IMountManager
1540
-	 **/
1541
-	function getMountManager() {
1542
-		return $this->query('MountManager');
1543
-	}
1544
-
1545
-	/** @return \OCP\Files\Config\IUserMountCache */
1546
-	function getUserMountCache() {
1547
-		return $this->query('UserMountCache');
1548
-	}
1549
-
1550
-	/**
1551
-	 * Get the MimeTypeDetector
1552
-	 *
1553
-	 * @return \OCP\Files\IMimeTypeDetector
1554
-	 */
1555
-	public function getMimeTypeDetector() {
1556
-		return $this->query('MimeTypeDetector');
1557
-	}
1558
-
1559
-	/**
1560
-	 * Get the MimeTypeLoader
1561
-	 *
1562
-	 * @return \OCP\Files\IMimeTypeLoader
1563
-	 */
1564
-	public function getMimeTypeLoader() {
1565
-		return $this->query('MimeTypeLoader');
1566
-	}
1567
-
1568
-	/**
1569
-	 * Get the manager of all the capabilities
1570
-	 *
1571
-	 * @return \OC\CapabilitiesManager
1572
-	 */
1573
-	public function getCapabilitiesManager() {
1574
-		return $this->query('CapabilitiesManager');
1575
-	}
1576
-
1577
-	/**
1578
-	 * Get the EventDispatcher
1579
-	 *
1580
-	 * @return EventDispatcherInterface
1581
-	 * @since 8.2.0
1582
-	 */
1583
-	public function getEventDispatcher() {
1584
-		return $this->query('EventDispatcher');
1585
-	}
1586
-
1587
-	/**
1588
-	 * Get the Notification Manager
1589
-	 *
1590
-	 * @return \OCP\Notification\IManager
1591
-	 * @since 8.2.0
1592
-	 */
1593
-	public function getNotificationManager() {
1594
-		return $this->query('NotificationManager');
1595
-	}
1596
-
1597
-	/**
1598
-	 * @return \OCP\Comments\ICommentsManager
1599
-	 */
1600
-	public function getCommentsManager() {
1601
-		return $this->query('CommentsManager');
1602
-	}
1603
-
1604
-	/**
1605
-	 * @return \OCA\Theming\ThemingDefaults
1606
-	 */
1607
-	public function getThemingDefaults() {
1608
-		return $this->query('ThemingDefaults');
1609
-	}
1610
-
1611
-	/**
1612
-	 * @return \OC\IntegrityCheck\Checker
1613
-	 */
1614
-	public function getIntegrityCodeChecker() {
1615
-		return $this->query('IntegrityCodeChecker');
1616
-	}
1617
-
1618
-	/**
1619
-	 * @return \OC\Session\CryptoWrapper
1620
-	 */
1621
-	public function getSessionCryptoWrapper() {
1622
-		return $this->query('CryptoWrapper');
1623
-	}
1624
-
1625
-	/**
1626
-	 * @return CsrfTokenManager
1627
-	 */
1628
-	public function getCsrfTokenManager() {
1629
-		return $this->query('CsrfTokenManager');
1630
-	}
1631
-
1632
-	/**
1633
-	 * @return Throttler
1634
-	 */
1635
-	public function getBruteForceThrottler() {
1636
-		return $this->query('Throttler');
1637
-	}
1638
-
1639
-	/**
1640
-	 * @return IContentSecurityPolicyManager
1641
-	 */
1642
-	public function getContentSecurityPolicyManager() {
1643
-		return $this->query('ContentSecurityPolicyManager');
1644
-	}
1645
-
1646
-	/**
1647
-	 * @return ContentSecurityPolicyNonceManager
1648
-	 */
1649
-	public function getContentSecurityPolicyNonceManager() {
1650
-		return $this->query('ContentSecurityPolicyNonceManager');
1651
-	}
1652
-
1653
-	/**
1654
-	 * Not a public API as of 8.2, wait for 9.0
1655
-	 *
1656
-	 * @return \OCA\Files_External\Service\BackendService
1657
-	 */
1658
-	public function getStoragesBackendService() {
1659
-		return $this->query('OCA\\Files_External\\Service\\BackendService');
1660
-	}
1661
-
1662
-	/**
1663
-	 * Not a public API as of 8.2, wait for 9.0
1664
-	 *
1665
-	 * @return \OCA\Files_External\Service\GlobalStoragesService
1666
-	 */
1667
-	public function getGlobalStoragesService() {
1668
-		return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1669
-	}
1670
-
1671
-	/**
1672
-	 * Not a public API as of 8.2, wait for 9.0
1673
-	 *
1674
-	 * @return \OCA\Files_External\Service\UserGlobalStoragesService
1675
-	 */
1676
-	public function getUserGlobalStoragesService() {
1677
-		return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1678
-	}
1679
-
1680
-	/**
1681
-	 * Not a public API as of 8.2, wait for 9.0
1682
-	 *
1683
-	 * @return \OCA\Files_External\Service\UserStoragesService
1684
-	 */
1685
-	public function getUserStoragesService() {
1686
-		return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1687
-	}
1688
-
1689
-	/**
1690
-	 * @return \OCP\Share\IManager
1691
-	 */
1692
-	public function getShareManager() {
1693
-		return $this->query('ShareManager');
1694
-	}
1695
-
1696
-	/**
1697
-	 * Returns the LDAP Provider
1698
-	 *
1699
-	 * @return \OCP\LDAP\ILDAPProvider
1700
-	 */
1701
-	public function getLDAPProvider() {
1702
-		return $this->query('LDAPProvider');
1703
-	}
1704
-
1705
-	/**
1706
-	 * @return \OCP\Settings\IManager
1707
-	 */
1708
-	public function getSettingsManager() {
1709
-		return $this->query('SettingsManager');
1710
-	}
1711
-
1712
-	/**
1713
-	 * @return \OCP\Files\IAppData
1714
-	 */
1715
-	public function getAppDataDir($app) {
1716
-		/** @var \OC\Files\AppData\Factory $factory */
1717
-		$factory = $this->query(\OC\Files\AppData\Factory::class);
1718
-		return $factory->get($app);
1719
-	}
1720
-
1721
-	/**
1722
-	 * @return \OCP\Lockdown\ILockdownManager
1723
-	 */
1724
-	public function getLockdownManager() {
1725
-		return $this->query('LockdownManager');
1726
-	}
1727
-
1728
-	/**
1729
-	 * @return \OCP\Federation\ICloudIdManager
1730
-	 */
1731
-	public function getCloudIdManager() {
1732
-		return $this->query(ICloudIdManager::class);
1733
-	}
832
+            $prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
833
+            if (isset($prefixes['OCA\\Theming\\'])) {
834
+                $classExists = true;
835
+            } else {
836
+                $classExists = false;
837
+            }
838
+
839
+            if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming')) {
840
+                return new ThemingDefaults(
841
+                    $c->getConfig(),
842
+                    $c->getL10N('theming'),
843
+                    $c->getURLGenerator(),
844
+                    new \OC_Defaults(),
845
+                    $c->getAppDataDir('theming'),
846
+                    $c->getMemCacheFactory()
847
+                );
848
+            }
849
+            return new \OC_Defaults();
850
+        });
851
+        $this->registerService(EventDispatcher::class, function () {
852
+            return new EventDispatcher();
853
+        });
854
+        $this->registerAlias('EventDispatcher', EventDispatcher::class);
855
+        $this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
856
+
857
+        $this->registerService('CryptoWrapper', function (Server $c) {
858
+            // FIXME: Instantiiated here due to cyclic dependency
859
+            $request = new Request(
860
+                [
861
+                    'get' => $_GET,
862
+                    'post' => $_POST,
863
+                    'files' => $_FILES,
864
+                    'server' => $_SERVER,
865
+                    'env' => $_ENV,
866
+                    'cookies' => $_COOKIE,
867
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
868
+                        ? $_SERVER['REQUEST_METHOD']
869
+                        : null,
870
+                ],
871
+                $c->getSecureRandom(),
872
+                $c->getConfig()
873
+            );
874
+
875
+            return new CryptoWrapper(
876
+                $c->getConfig(),
877
+                $c->getCrypto(),
878
+                $c->getSecureRandom(),
879
+                $request
880
+            );
881
+        });
882
+        $this->registerService('CsrfTokenManager', function (Server $c) {
883
+            $tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
884
+
885
+            return new CsrfTokenManager(
886
+                $tokenGenerator,
887
+                $c->query(SessionStorage::class)
888
+            );
889
+        });
890
+        $this->registerService(SessionStorage::class, function (Server $c) {
891
+            return new SessionStorage($c->getSession());
892
+        });
893
+        $this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
894
+            return new ContentSecurityPolicyManager();
895
+        });
896
+        $this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
897
+
898
+        $this->registerService('ContentSecurityPolicyNonceManager', function(Server $c) {
899
+            return new ContentSecurityPolicyNonceManager(
900
+                $c->getCsrfTokenManager(),
901
+                $c->getRequest()
902
+            );
903
+        });
904
+
905
+        $this->registerService(\OCP\Share\IManager::class, function(Server $c) {
906
+            $config = $c->getConfig();
907
+            $factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
908
+            /** @var \OCP\Share\IProviderFactory $factory */
909
+            $factory = new $factoryClass($this);
910
+
911
+            $manager = new \OC\Share20\Manager(
912
+                $c->getLogger(),
913
+                $c->getConfig(),
914
+                $c->getSecureRandom(),
915
+                $c->getHasher(),
916
+                $c->getMountManager(),
917
+                $c->getGroupManager(),
918
+                $c->getL10N('core'),
919
+                $factory,
920
+                $c->getUserManager(),
921
+                $c->getLazyRootFolder(),
922
+                $c->getEventDispatcher()
923
+            );
924
+
925
+            return $manager;
926
+        });
927
+        $this->registerAlias('ShareManager', \OCP\Share\IManager::class);
928
+
929
+        $this->registerService('SettingsManager', function(Server $c) {
930
+            $manager = new \OC\Settings\Manager(
931
+                $c->getLogger(),
932
+                $c->getDatabaseConnection(),
933
+                $c->getL10N('lib'),
934
+                $c->getConfig(),
935
+                $c->getEncryptionManager(),
936
+                $c->getUserManager(),
937
+                $c->getLockingProvider(),
938
+                $c->getRequest(),
939
+                new \OC\Settings\Mapper($c->getDatabaseConnection()),
940
+                $c->getURLGenerator()
941
+            );
942
+            return $manager;
943
+        });
944
+        $this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
945
+            return new \OC\Files\AppData\Factory(
946
+                $c->getRootFolder(),
947
+                $c->getSystemConfig()
948
+            );
949
+        });
950
+
951
+        $this->registerService('LockdownManager', function (Server $c) {
952
+            return new LockdownManager(function() use ($c) {
953
+                return $c->getSession();
954
+            });
955
+        });
956
+
957
+        $this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
958
+            return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
959
+        });
960
+
961
+        $this->registerService(ICloudIdManager::class, function (Server $c) {
962
+            return new CloudIdManager();
963
+        });
964
+
965
+        /* To trick DI since we don't extend the DIContainer here */
966
+        $this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
967
+            return new CleanPreviewsBackgroundJob(
968
+                $c->getRootFolder(),
969
+                $c->getLogger(),
970
+                $c->getJobList(),
971
+                new TimeFactory()
972
+            );
973
+        });
974
+
975
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
976
+        $this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
977
+
978
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
979
+        $this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
980
+
981
+        $this->registerService(Defaults::class, function (Server $c) {
982
+            return new Defaults(
983
+                $c->getThemingDefaults()
984
+            );
985
+        });
986
+        $this->registerAlias('Defaults', \OCP\Defaults::class);
987
+
988
+        $this->registerService(\OCP\ISession::class, function(SimpleContainer $c) {
989
+            return $c->query(\OCP\IUserSession::class)->getSession();
990
+        });
991
+    }
992
+
993
+    /**
994
+     * @return \OCP\Contacts\IManager
995
+     */
996
+    public function getContactsManager() {
997
+        return $this->query('ContactsManager');
998
+    }
999
+
1000
+    /**
1001
+     * @return \OC\Encryption\Manager
1002
+     */
1003
+    public function getEncryptionManager() {
1004
+        return $this->query('EncryptionManager');
1005
+    }
1006
+
1007
+    /**
1008
+     * @return \OC\Encryption\File
1009
+     */
1010
+    public function getEncryptionFilesHelper() {
1011
+        return $this->query('EncryptionFileHelper');
1012
+    }
1013
+
1014
+    /**
1015
+     * @return \OCP\Encryption\Keys\IStorage
1016
+     */
1017
+    public function getEncryptionKeyStorage() {
1018
+        return $this->query('EncryptionKeyStorage');
1019
+    }
1020
+
1021
+    /**
1022
+     * The current request object holding all information about the request
1023
+     * currently being processed is returned from this method.
1024
+     * In case the current execution was not initiated by a web request null is returned
1025
+     *
1026
+     * @return \OCP\IRequest
1027
+     */
1028
+    public function getRequest() {
1029
+        return $this->query('Request');
1030
+    }
1031
+
1032
+    /**
1033
+     * Returns the preview manager which can create preview images for a given file
1034
+     *
1035
+     * @return \OCP\IPreview
1036
+     */
1037
+    public function getPreviewManager() {
1038
+        return $this->query('PreviewManager');
1039
+    }
1040
+
1041
+    /**
1042
+     * Returns the tag manager which can get and set tags for different object types
1043
+     *
1044
+     * @see \OCP\ITagManager::load()
1045
+     * @return \OCP\ITagManager
1046
+     */
1047
+    public function getTagManager() {
1048
+        return $this->query('TagManager');
1049
+    }
1050
+
1051
+    /**
1052
+     * Returns the system-tag manager
1053
+     *
1054
+     * @return \OCP\SystemTag\ISystemTagManager
1055
+     *
1056
+     * @since 9.0.0
1057
+     */
1058
+    public function getSystemTagManager() {
1059
+        return $this->query('SystemTagManager');
1060
+    }
1061
+
1062
+    /**
1063
+     * Returns the system-tag object mapper
1064
+     *
1065
+     * @return \OCP\SystemTag\ISystemTagObjectMapper
1066
+     *
1067
+     * @since 9.0.0
1068
+     */
1069
+    public function getSystemTagObjectMapper() {
1070
+        return $this->query('SystemTagObjectMapper');
1071
+    }
1072
+
1073
+    /**
1074
+     * Returns the avatar manager, used for avatar functionality
1075
+     *
1076
+     * @return \OCP\IAvatarManager
1077
+     */
1078
+    public function getAvatarManager() {
1079
+        return $this->query('AvatarManager');
1080
+    }
1081
+
1082
+    /**
1083
+     * Returns the root folder of ownCloud's data directory
1084
+     *
1085
+     * @return \OCP\Files\IRootFolder
1086
+     */
1087
+    public function getRootFolder() {
1088
+        return $this->query('LazyRootFolder');
1089
+    }
1090
+
1091
+    /**
1092
+     * Returns the root folder of ownCloud's data directory
1093
+     * This is the lazy variant so this gets only initialized once it
1094
+     * is actually used.
1095
+     *
1096
+     * @return \OCP\Files\IRootFolder
1097
+     */
1098
+    public function getLazyRootFolder() {
1099
+        return $this->query('LazyRootFolder');
1100
+    }
1101
+
1102
+    /**
1103
+     * Returns a view to ownCloud's files folder
1104
+     *
1105
+     * @param string $userId user ID
1106
+     * @return \OCP\Files\Folder|null
1107
+     */
1108
+    public function getUserFolder($userId = null) {
1109
+        if ($userId === null) {
1110
+            $user = $this->getUserSession()->getUser();
1111
+            if (!$user) {
1112
+                return null;
1113
+            }
1114
+            $userId = $user->getUID();
1115
+        }
1116
+        $root = $this->getRootFolder();
1117
+        return $root->getUserFolder($userId);
1118
+    }
1119
+
1120
+    /**
1121
+     * Returns an app-specific view in ownClouds data directory
1122
+     *
1123
+     * @return \OCP\Files\Folder
1124
+     * @deprecated since 9.2.0 use IAppData
1125
+     */
1126
+    public function getAppFolder() {
1127
+        $dir = '/' . \OC_App::getCurrentApp();
1128
+        $root = $this->getRootFolder();
1129
+        if (!$root->nodeExists($dir)) {
1130
+            $folder = $root->newFolder($dir);
1131
+        } else {
1132
+            $folder = $root->get($dir);
1133
+        }
1134
+        return $folder;
1135
+    }
1136
+
1137
+    /**
1138
+     * @return \OC\User\Manager
1139
+     */
1140
+    public function getUserManager() {
1141
+        return $this->query('UserManager');
1142
+    }
1143
+
1144
+    /**
1145
+     * @return \OC\Group\Manager
1146
+     */
1147
+    public function getGroupManager() {
1148
+        return $this->query('GroupManager');
1149
+    }
1150
+
1151
+    /**
1152
+     * @return \OC\User\Session
1153
+     */
1154
+    public function getUserSession() {
1155
+        return $this->query('UserSession');
1156
+    }
1157
+
1158
+    /**
1159
+     * @return \OCP\ISession
1160
+     */
1161
+    public function getSession() {
1162
+        return $this->query('UserSession')->getSession();
1163
+    }
1164
+
1165
+    /**
1166
+     * @param \OCP\ISession $session
1167
+     */
1168
+    public function setSession(\OCP\ISession $session) {
1169
+        $this->query(SessionStorage::class)->setSession($session);
1170
+        $this->query('UserSession')->setSession($session);
1171
+        $this->query(Store::class)->setSession($session);
1172
+    }
1173
+
1174
+    /**
1175
+     * @return \OC\Authentication\TwoFactorAuth\Manager
1176
+     */
1177
+    public function getTwoFactorAuthManager() {
1178
+        return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1179
+    }
1180
+
1181
+    /**
1182
+     * @return \OC\NavigationManager
1183
+     */
1184
+    public function getNavigationManager() {
1185
+        return $this->query('NavigationManager');
1186
+    }
1187
+
1188
+    /**
1189
+     * @return \OCP\IConfig
1190
+     */
1191
+    public function getConfig() {
1192
+        return $this->query('AllConfig');
1193
+    }
1194
+
1195
+    /**
1196
+     * @internal For internal use only
1197
+     * @return \OC\SystemConfig
1198
+     */
1199
+    public function getSystemConfig() {
1200
+        return $this->query('SystemConfig');
1201
+    }
1202
+
1203
+    /**
1204
+     * Returns the app config manager
1205
+     *
1206
+     * @return \OCP\IAppConfig
1207
+     */
1208
+    public function getAppConfig() {
1209
+        return $this->query('AppConfig');
1210
+    }
1211
+
1212
+    /**
1213
+     * @return \OCP\L10N\IFactory
1214
+     */
1215
+    public function getL10NFactory() {
1216
+        return $this->query('L10NFactory');
1217
+    }
1218
+
1219
+    /**
1220
+     * get an L10N instance
1221
+     *
1222
+     * @param string $app appid
1223
+     * @param string $lang
1224
+     * @return IL10N
1225
+     */
1226
+    public function getL10N($app, $lang = null) {
1227
+        return $this->getL10NFactory()->get($app, $lang);
1228
+    }
1229
+
1230
+    /**
1231
+     * @return \OCP\IURLGenerator
1232
+     */
1233
+    public function getURLGenerator() {
1234
+        return $this->query('URLGenerator');
1235
+    }
1236
+
1237
+    /**
1238
+     * @return \OCP\IHelper
1239
+     */
1240
+    public function getHelper() {
1241
+        return $this->query('AppHelper');
1242
+    }
1243
+
1244
+    /**
1245
+     * @return AppFetcher
1246
+     */
1247
+    public function getAppFetcher() {
1248
+        return $this->query('AppFetcher');
1249
+    }
1250
+
1251
+    /**
1252
+     * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1253
+     * getMemCacheFactory() instead.
1254
+     *
1255
+     * @return \OCP\ICache
1256
+     * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1257
+     */
1258
+    public function getCache() {
1259
+        return $this->query('UserCache');
1260
+    }
1261
+
1262
+    /**
1263
+     * Returns an \OCP\CacheFactory instance
1264
+     *
1265
+     * @return \OCP\ICacheFactory
1266
+     */
1267
+    public function getMemCacheFactory() {
1268
+        return $this->query('MemCacheFactory');
1269
+    }
1270
+
1271
+    /**
1272
+     * Returns an \OC\RedisFactory instance
1273
+     *
1274
+     * @return \OC\RedisFactory
1275
+     */
1276
+    public function getGetRedisFactory() {
1277
+        return $this->query('RedisFactory');
1278
+    }
1279
+
1280
+
1281
+    /**
1282
+     * Returns the current session
1283
+     *
1284
+     * @return \OCP\IDBConnection
1285
+     */
1286
+    public function getDatabaseConnection() {
1287
+        return $this->query('DatabaseConnection');
1288
+    }
1289
+
1290
+    /**
1291
+     * Returns the activity manager
1292
+     *
1293
+     * @return \OCP\Activity\IManager
1294
+     */
1295
+    public function getActivityManager() {
1296
+        return $this->query('ActivityManager');
1297
+    }
1298
+
1299
+    /**
1300
+     * Returns an job list for controlling background jobs
1301
+     *
1302
+     * @return \OCP\BackgroundJob\IJobList
1303
+     */
1304
+    public function getJobList() {
1305
+        return $this->query('JobList');
1306
+    }
1307
+
1308
+    /**
1309
+     * Returns a logger instance
1310
+     *
1311
+     * @return \OCP\ILogger
1312
+     */
1313
+    public function getLogger() {
1314
+        return $this->query('Logger');
1315
+    }
1316
+
1317
+    /**
1318
+     * Returns a router for generating and matching urls
1319
+     *
1320
+     * @return \OCP\Route\IRouter
1321
+     */
1322
+    public function getRouter() {
1323
+        return $this->query('Router');
1324
+    }
1325
+
1326
+    /**
1327
+     * Returns a search instance
1328
+     *
1329
+     * @return \OCP\ISearch
1330
+     */
1331
+    public function getSearch() {
1332
+        return $this->query('Search');
1333
+    }
1334
+
1335
+    /**
1336
+     * Returns a SecureRandom instance
1337
+     *
1338
+     * @return \OCP\Security\ISecureRandom
1339
+     */
1340
+    public function getSecureRandom() {
1341
+        return $this->query('SecureRandom');
1342
+    }
1343
+
1344
+    /**
1345
+     * Returns a Crypto instance
1346
+     *
1347
+     * @return \OCP\Security\ICrypto
1348
+     */
1349
+    public function getCrypto() {
1350
+        return $this->query('Crypto');
1351
+    }
1352
+
1353
+    /**
1354
+     * Returns a Hasher instance
1355
+     *
1356
+     * @return \OCP\Security\IHasher
1357
+     */
1358
+    public function getHasher() {
1359
+        return $this->query('Hasher');
1360
+    }
1361
+
1362
+    /**
1363
+     * Returns a CredentialsManager instance
1364
+     *
1365
+     * @return \OCP\Security\ICredentialsManager
1366
+     */
1367
+    public function getCredentialsManager() {
1368
+        return $this->query('CredentialsManager');
1369
+    }
1370
+
1371
+    /**
1372
+     * Returns an instance of the HTTP helper class
1373
+     *
1374
+     * @deprecated Use getHTTPClientService()
1375
+     * @return \OC\HTTPHelper
1376
+     */
1377
+    public function getHTTPHelper() {
1378
+        return $this->query('HTTPHelper');
1379
+    }
1380
+
1381
+    /**
1382
+     * Get the certificate manager for the user
1383
+     *
1384
+     * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1385
+     * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1386
+     */
1387
+    public function getCertificateManager($userId = '') {
1388
+        if ($userId === '') {
1389
+            $userSession = $this->getUserSession();
1390
+            $user = $userSession->getUser();
1391
+            if (is_null($user)) {
1392
+                return null;
1393
+            }
1394
+            $userId = $user->getUID();
1395
+        }
1396
+        return new CertificateManager($userId, new View(), $this->getConfig(), $this->getLogger());
1397
+    }
1398
+
1399
+    /**
1400
+     * Returns an instance of the HTTP client service
1401
+     *
1402
+     * @return \OCP\Http\Client\IClientService
1403
+     */
1404
+    public function getHTTPClientService() {
1405
+        return $this->query('HttpClientService');
1406
+    }
1407
+
1408
+    /**
1409
+     * Create a new event source
1410
+     *
1411
+     * @return \OCP\IEventSource
1412
+     */
1413
+    public function createEventSource() {
1414
+        return new \OC_EventSource();
1415
+    }
1416
+
1417
+    /**
1418
+     * Get the active event logger
1419
+     *
1420
+     * The returned logger only logs data when debug mode is enabled
1421
+     *
1422
+     * @return \OCP\Diagnostics\IEventLogger
1423
+     */
1424
+    public function getEventLogger() {
1425
+        return $this->query('EventLogger');
1426
+    }
1427
+
1428
+    /**
1429
+     * Get the active query logger
1430
+     *
1431
+     * The returned logger only logs data when debug mode is enabled
1432
+     *
1433
+     * @return \OCP\Diagnostics\IQueryLogger
1434
+     */
1435
+    public function getQueryLogger() {
1436
+        return $this->query('QueryLogger');
1437
+    }
1438
+
1439
+    /**
1440
+     * Get the manager for temporary files and folders
1441
+     *
1442
+     * @return \OCP\ITempManager
1443
+     */
1444
+    public function getTempManager() {
1445
+        return $this->query('TempManager');
1446
+    }
1447
+
1448
+    /**
1449
+     * Get the app manager
1450
+     *
1451
+     * @return \OCP\App\IAppManager
1452
+     */
1453
+    public function getAppManager() {
1454
+        return $this->query('AppManager');
1455
+    }
1456
+
1457
+    /**
1458
+     * Creates a new mailer
1459
+     *
1460
+     * @return \OCP\Mail\IMailer
1461
+     */
1462
+    public function getMailer() {
1463
+        return $this->query('Mailer');
1464
+    }
1465
+
1466
+    /**
1467
+     * Get the webroot
1468
+     *
1469
+     * @return string
1470
+     */
1471
+    public function getWebRoot() {
1472
+        return $this->webRoot;
1473
+    }
1474
+
1475
+    /**
1476
+     * @return \OC\OCSClient
1477
+     */
1478
+    public function getOcsClient() {
1479
+        return $this->query('OcsClient');
1480
+    }
1481
+
1482
+    /**
1483
+     * @return \OCP\IDateTimeZone
1484
+     */
1485
+    public function getDateTimeZone() {
1486
+        return $this->query('DateTimeZone');
1487
+    }
1488
+
1489
+    /**
1490
+     * @return \OCP\IDateTimeFormatter
1491
+     */
1492
+    public function getDateTimeFormatter() {
1493
+        return $this->query('DateTimeFormatter');
1494
+    }
1495
+
1496
+    /**
1497
+     * @return \OCP\Files\Config\IMountProviderCollection
1498
+     */
1499
+    public function getMountProviderCollection() {
1500
+        return $this->query('MountConfigManager');
1501
+    }
1502
+
1503
+    /**
1504
+     * Get the IniWrapper
1505
+     *
1506
+     * @return IniGetWrapper
1507
+     */
1508
+    public function getIniWrapper() {
1509
+        return $this->query('IniWrapper');
1510
+    }
1511
+
1512
+    /**
1513
+     * @return \OCP\Command\IBus
1514
+     */
1515
+    public function getCommandBus() {
1516
+        return $this->query('AsyncCommandBus');
1517
+    }
1518
+
1519
+    /**
1520
+     * Get the trusted domain helper
1521
+     *
1522
+     * @return TrustedDomainHelper
1523
+     */
1524
+    public function getTrustedDomainHelper() {
1525
+        return $this->query('TrustedDomainHelper');
1526
+    }
1527
+
1528
+    /**
1529
+     * Get the locking provider
1530
+     *
1531
+     * @return \OCP\Lock\ILockingProvider
1532
+     * @since 8.1.0
1533
+     */
1534
+    public function getLockingProvider() {
1535
+        return $this->query('LockingProvider');
1536
+    }
1537
+
1538
+    /**
1539
+     * @return \OCP\Files\Mount\IMountManager
1540
+     **/
1541
+    function getMountManager() {
1542
+        return $this->query('MountManager');
1543
+    }
1544
+
1545
+    /** @return \OCP\Files\Config\IUserMountCache */
1546
+    function getUserMountCache() {
1547
+        return $this->query('UserMountCache');
1548
+    }
1549
+
1550
+    /**
1551
+     * Get the MimeTypeDetector
1552
+     *
1553
+     * @return \OCP\Files\IMimeTypeDetector
1554
+     */
1555
+    public function getMimeTypeDetector() {
1556
+        return $this->query('MimeTypeDetector');
1557
+    }
1558
+
1559
+    /**
1560
+     * Get the MimeTypeLoader
1561
+     *
1562
+     * @return \OCP\Files\IMimeTypeLoader
1563
+     */
1564
+    public function getMimeTypeLoader() {
1565
+        return $this->query('MimeTypeLoader');
1566
+    }
1567
+
1568
+    /**
1569
+     * Get the manager of all the capabilities
1570
+     *
1571
+     * @return \OC\CapabilitiesManager
1572
+     */
1573
+    public function getCapabilitiesManager() {
1574
+        return $this->query('CapabilitiesManager');
1575
+    }
1576
+
1577
+    /**
1578
+     * Get the EventDispatcher
1579
+     *
1580
+     * @return EventDispatcherInterface
1581
+     * @since 8.2.0
1582
+     */
1583
+    public function getEventDispatcher() {
1584
+        return $this->query('EventDispatcher');
1585
+    }
1586
+
1587
+    /**
1588
+     * Get the Notification Manager
1589
+     *
1590
+     * @return \OCP\Notification\IManager
1591
+     * @since 8.2.0
1592
+     */
1593
+    public function getNotificationManager() {
1594
+        return $this->query('NotificationManager');
1595
+    }
1596
+
1597
+    /**
1598
+     * @return \OCP\Comments\ICommentsManager
1599
+     */
1600
+    public function getCommentsManager() {
1601
+        return $this->query('CommentsManager');
1602
+    }
1603
+
1604
+    /**
1605
+     * @return \OCA\Theming\ThemingDefaults
1606
+     */
1607
+    public function getThemingDefaults() {
1608
+        return $this->query('ThemingDefaults');
1609
+    }
1610
+
1611
+    /**
1612
+     * @return \OC\IntegrityCheck\Checker
1613
+     */
1614
+    public function getIntegrityCodeChecker() {
1615
+        return $this->query('IntegrityCodeChecker');
1616
+    }
1617
+
1618
+    /**
1619
+     * @return \OC\Session\CryptoWrapper
1620
+     */
1621
+    public function getSessionCryptoWrapper() {
1622
+        return $this->query('CryptoWrapper');
1623
+    }
1624
+
1625
+    /**
1626
+     * @return CsrfTokenManager
1627
+     */
1628
+    public function getCsrfTokenManager() {
1629
+        return $this->query('CsrfTokenManager');
1630
+    }
1631
+
1632
+    /**
1633
+     * @return Throttler
1634
+     */
1635
+    public function getBruteForceThrottler() {
1636
+        return $this->query('Throttler');
1637
+    }
1638
+
1639
+    /**
1640
+     * @return IContentSecurityPolicyManager
1641
+     */
1642
+    public function getContentSecurityPolicyManager() {
1643
+        return $this->query('ContentSecurityPolicyManager');
1644
+    }
1645
+
1646
+    /**
1647
+     * @return ContentSecurityPolicyNonceManager
1648
+     */
1649
+    public function getContentSecurityPolicyNonceManager() {
1650
+        return $this->query('ContentSecurityPolicyNonceManager');
1651
+    }
1652
+
1653
+    /**
1654
+     * Not a public API as of 8.2, wait for 9.0
1655
+     *
1656
+     * @return \OCA\Files_External\Service\BackendService
1657
+     */
1658
+    public function getStoragesBackendService() {
1659
+        return $this->query('OCA\\Files_External\\Service\\BackendService');
1660
+    }
1661
+
1662
+    /**
1663
+     * Not a public API as of 8.2, wait for 9.0
1664
+     *
1665
+     * @return \OCA\Files_External\Service\GlobalStoragesService
1666
+     */
1667
+    public function getGlobalStoragesService() {
1668
+        return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1669
+    }
1670
+
1671
+    /**
1672
+     * Not a public API as of 8.2, wait for 9.0
1673
+     *
1674
+     * @return \OCA\Files_External\Service\UserGlobalStoragesService
1675
+     */
1676
+    public function getUserGlobalStoragesService() {
1677
+        return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1678
+    }
1679
+
1680
+    /**
1681
+     * Not a public API as of 8.2, wait for 9.0
1682
+     *
1683
+     * @return \OCA\Files_External\Service\UserStoragesService
1684
+     */
1685
+    public function getUserStoragesService() {
1686
+        return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1687
+    }
1688
+
1689
+    /**
1690
+     * @return \OCP\Share\IManager
1691
+     */
1692
+    public function getShareManager() {
1693
+        return $this->query('ShareManager');
1694
+    }
1695
+
1696
+    /**
1697
+     * Returns the LDAP Provider
1698
+     *
1699
+     * @return \OCP\LDAP\ILDAPProvider
1700
+     */
1701
+    public function getLDAPProvider() {
1702
+        return $this->query('LDAPProvider');
1703
+    }
1704
+
1705
+    /**
1706
+     * @return \OCP\Settings\IManager
1707
+     */
1708
+    public function getSettingsManager() {
1709
+        return $this->query('SettingsManager');
1710
+    }
1711
+
1712
+    /**
1713
+     * @return \OCP\Files\IAppData
1714
+     */
1715
+    public function getAppDataDir($app) {
1716
+        /** @var \OC\Files\AppData\Factory $factory */
1717
+        $factory = $this->query(\OC\Files\AppData\Factory::class);
1718
+        return $factory->get($app);
1719
+    }
1720
+
1721
+    /**
1722
+     * @return \OCP\Lockdown\ILockdownManager
1723
+     */
1724
+    public function getLockdownManager() {
1725
+        return $this->query('LockdownManager');
1726
+    }
1727
+
1728
+    /**
1729
+     * @return \OCP\Federation\ICloudIdManager
1730
+     */
1731
+    public function getCloudIdManager() {
1732
+        return $this->query(ICloudIdManager::class);
1733
+    }
1734 1734
 }
Please login to merge, or discard this patch.
Spacing   +97 added lines, -97 removed lines patch added patch discarded remove patch
@@ -131,7 +131,7 @@  discard block
 block discarded – undo
131 131
 		$this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
132 132
 		$this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
133 133
 
134
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
134
+		$this->registerService(\OCP\IPreview::class, function(Server $c) {
135 135
 			return new PreviewManager(
136 136
 				$c->getConfig(),
137 137
 				$c->getRootFolder(),
@@ -142,13 +142,13 @@  discard block
 block discarded – undo
142 142
 		});
143 143
 		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
144 144
 
145
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
145
+		$this->registerService(\OC\Preview\Watcher::class, function(Server $c) {
146 146
 			return new \OC\Preview\Watcher(
147 147
 				$c->getAppDataDir('preview')
148 148
 			);
149 149
 		});
150 150
 
151
-		$this->registerService('EncryptionManager', function (Server $c) {
151
+		$this->registerService('EncryptionManager', function(Server $c) {
152 152
 			$view = new View();
153 153
 			$util = new Encryption\Util(
154 154
 				$view,
@@ -166,7 +166,7 @@  discard block
 block discarded – undo
166 166
 			);
167 167
 		});
168 168
 
169
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
169
+		$this->registerService('EncryptionFileHelper', function(Server $c) {
170 170
 			$util = new Encryption\Util(
171 171
 				new View(),
172 172
 				$c->getUserManager(),
@@ -176,7 +176,7 @@  discard block
 block discarded – undo
176 176
 			return new Encryption\File($util);
177 177
 		});
178 178
 
179
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
179
+		$this->registerService('EncryptionKeyStorage', function(Server $c) {
180 180
 			$view = new View();
181 181
 			$util = new Encryption\Util(
182 182
 				$view,
@@ -187,32 +187,32 @@  discard block
 block discarded – undo
187 187
 
188 188
 			return new Encryption\Keys\Storage($view, $util);
189 189
 		});
190
-		$this->registerService('TagMapper', function (Server $c) {
190
+		$this->registerService('TagMapper', function(Server $c) {
191 191
 			return new TagMapper($c->getDatabaseConnection());
192 192
 		});
193 193
 
194
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
194
+		$this->registerService(\OCP\ITagManager::class, function(Server $c) {
195 195
 			$tagMapper = $c->query('TagMapper');
196 196
 			return new TagManager($tagMapper, $c->getUserSession());
197 197
 		});
198 198
 		$this->registerAlias('TagManager', \OCP\ITagManager::class);
199 199
 
200
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
200
+		$this->registerService('SystemTagManagerFactory', function(Server $c) {
201 201
 			$config = $c->getConfig();
202 202
 			$factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
203 203
 			/** @var \OC\SystemTag\ManagerFactory $factory */
204 204
 			$factory = new $factoryClass($this);
205 205
 			return $factory;
206 206
 		});
207
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
207
+		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function(Server $c) {
208 208
 			return $c->query('SystemTagManagerFactory')->getManager();
209 209
 		});
210 210
 		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
211 211
 
212
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
212
+		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function(Server $c) {
213 213
 			return $c->query('SystemTagManagerFactory')->getObjectMapper();
214 214
 		});
215
-		$this->registerService('RootFolder', function (Server $c) {
215
+		$this->registerService('RootFolder', function(Server $c) {
216 216
 			$manager = \OC\Files\Filesystem::getMountManager(null);
217 217
 			$view = new View();
218 218
 			$root = new Root(
@@ -240,30 +240,30 @@  discard block
 block discarded – undo
240 240
 		});
241 241
 		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
242 242
 
243
-		$this->registerService(\OCP\IUserManager::class, function (Server $c) {
243
+		$this->registerService(\OCP\IUserManager::class, function(Server $c) {
244 244
 			$config = $c->getConfig();
245 245
 			return new \OC\User\Manager($config);
246 246
 		});
247 247
 		$this->registerAlias('UserManager', \OCP\IUserManager::class);
248 248
 
249
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
249
+		$this->registerService(\OCP\IGroupManager::class, function(Server $c) {
250 250
 			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
251
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
251
+			$groupManager->listen('\OC\Group', 'preCreate', function($gid) {
252 252
 				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
253 253
 			});
254
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
254
+			$groupManager->listen('\OC\Group', 'postCreate', function(\OC\Group\Group $gid) {
255 255
 				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
256 256
 			});
257
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
257
+			$groupManager->listen('\OC\Group', 'preDelete', function(\OC\Group\Group $group) {
258 258
 				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
259 259
 			});
260
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
260
+			$groupManager->listen('\OC\Group', 'postDelete', function(\OC\Group\Group $group) {
261 261
 				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
262 262
 			});
263
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
263
+			$groupManager->listen('\OC\Group', 'preAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
264 264
 				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
265 265
 			});
266
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
266
+			$groupManager->listen('\OC\Group', 'postAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
267 267
 				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
268 268
 				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
269 269
 				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
@@ -283,11 +283,11 @@  discard block
 block discarded – undo
283 283
 			return new Store($session, $logger, $tokenProvider);
284 284
 		});
285 285
 		$this->registerAlias(IStore::class, Store::class);
286
-		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
286
+		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function(Server $c) {
287 287
 			$dbConnection = $c->getDatabaseConnection();
288 288
 			return new Authentication\Token\DefaultTokenMapper($dbConnection);
289 289
 		});
290
-		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
290
+		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function(Server $c) {
291 291
 			$mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
292 292
 			$crypto = $c->getCrypto();
293 293
 			$config = $c->getConfig();
@@ -297,7 +297,7 @@  discard block
 block discarded – undo
297 297
 		});
298 298
 		$this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
299 299
 
300
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
300
+		$this->registerService(\OCP\IUserSession::class, function(Server $c) {
301 301
 			$manager = $c->getUserManager();
302 302
 			$session = new \OC\Session\Memory('');
303 303
 			$timeFactory = new TimeFactory();
@@ -310,40 +310,40 @@  discard block
 block discarded – undo
310 310
 			}
311 311
 
312 312
 			$userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom(), $c->getLockdownManager());
313
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
313
+			$userSession->listen('\OC\User', 'preCreateUser', function($uid, $password) {
314 314
 				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
315 315
 			});
316
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
316
+			$userSession->listen('\OC\User', 'postCreateUser', function($user, $password) {
317 317
 				/** @var $user \OC\User\User */
318 318
 				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
319 319
 			});
320
-			$userSession->listen('\OC\User', 'preDelete', function ($user) {
320
+			$userSession->listen('\OC\User', 'preDelete', function($user) {
321 321
 				/** @var $user \OC\User\User */
322 322
 				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
323 323
 			});
324
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
324
+			$userSession->listen('\OC\User', 'postDelete', function($user) {
325 325
 				/** @var $user \OC\User\User */
326 326
 				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
327 327
 			});
328
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
328
+			$userSession->listen('\OC\User', 'preSetPassword', function($user, $password, $recoveryPassword) {
329 329
 				/** @var $user \OC\User\User */
330 330
 				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
331 331
 			});
332
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
332
+			$userSession->listen('\OC\User', 'postSetPassword', function($user, $password, $recoveryPassword) {
333 333
 				/** @var $user \OC\User\User */
334 334
 				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
335 335
 			});
336
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
336
+			$userSession->listen('\OC\User', 'preLogin', function($uid, $password) {
337 337
 				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
338 338
 			});
339
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
339
+			$userSession->listen('\OC\User', 'postLogin', function($user, $password) {
340 340
 				/** @var $user \OC\User\User */
341 341
 				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
342 342
 			});
343
-			$userSession->listen('\OC\User', 'logout', function () {
343
+			$userSession->listen('\OC\User', 'logout', function() {
344 344
 				\OC_Hook::emit('OC_User', 'logout', array());
345 345
 			});
346
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
346
+			$userSession->listen('\OC\User', 'changeUser', function($user, $feature, $value, $oldValue) {
347 347
 				/** @var $user \OC\User\User */
348 348
 				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
349 349
 			});
@@ -351,14 +351,14 @@  discard block
 block discarded – undo
351 351
 		});
352 352
 		$this->registerAlias('UserSession', \OCP\IUserSession::class);
353 353
 
354
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
354
+		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function(Server $c) {
355 355
 			return new \OC\Authentication\TwoFactorAuth\Manager($c->getAppManager(), $c->getSession(), $c->getConfig(), $c->getActivityManager(), $c->getLogger());
356 356
 		});
357 357
 
358 358
 		$this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
359 359
 		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
360 360
 
361
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
361
+		$this->registerService(\OC\AllConfig::class, function(Server $c) {
362 362
 			return new \OC\AllConfig(
363 363
 				$c->getSystemConfig()
364 364
 			);
@@ -366,17 +366,17 @@  discard block
 block discarded – undo
366 366
 		$this->registerAlias('AllConfig', \OC\AllConfig::class);
367 367
 		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
368 368
 
369
-		$this->registerService('SystemConfig', function ($c) use ($config) {
369
+		$this->registerService('SystemConfig', function($c) use ($config) {
370 370
 			return new \OC\SystemConfig($config);
371 371
 		});
372 372
 
373
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
373
+		$this->registerService(\OC\AppConfig::class, function(Server $c) {
374 374
 			return new \OC\AppConfig($c->getDatabaseConnection());
375 375
 		});
376 376
 		$this->registerAlias('AppConfig', \OC\AppConfig::class);
377 377
 		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
378 378
 
379
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
379
+		$this->registerService(\OCP\L10N\IFactory::class, function(Server $c) {
380 380
 			return new \OC\L10N\Factory(
381 381
 				$c->getConfig(),
382 382
 				$c->getRequest(),
@@ -386,7 +386,7 @@  discard block
 block discarded – undo
386 386
 		});
387 387
 		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
388 388
 
389
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
389
+		$this->registerService(\OCP\IURLGenerator::class, function(Server $c) {
390 390
 			$config = $c->getConfig();
391 391
 			$cacheFactory = $c->getMemCacheFactory();
392 392
 			return new \OC\URLGenerator(
@@ -396,10 +396,10 @@  discard block
 block discarded – undo
396 396
 		});
397 397
 		$this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
398 398
 
399
-		$this->registerService('AppHelper', function ($c) {
399
+		$this->registerService('AppHelper', function($c) {
400 400
 			return new \OC\AppHelper();
401 401
 		});
402
-		$this->registerService('AppFetcher', function ($c) {
402
+		$this->registerService('AppFetcher', function($c) {
403 403
 			return new AppFetcher(
404 404
 				$this->getAppDataDir('appstore'),
405 405
 				$this->getHTTPClientService(),
@@ -407,7 +407,7 @@  discard block
 block discarded – undo
407 407
 				$this->getConfig()
408 408
 			);
409 409
 		});
410
-		$this->registerService('CategoryFetcher', function ($c) {
410
+		$this->registerService('CategoryFetcher', function($c) {
411 411
 			return new CategoryFetcher(
412 412
 				$this->getAppDataDir('appstore'),
413 413
 				$this->getHTTPClientService(),
@@ -416,21 +416,21 @@  discard block
 block discarded – undo
416 416
 			);
417 417
 		});
418 418
 
419
-		$this->registerService(\OCP\ICache::class, function ($c) {
419
+		$this->registerService(\OCP\ICache::class, function($c) {
420 420
 			return new Cache\File();
421 421
 		});
422 422
 		$this->registerAlias('UserCache', \OCP\ICache::class);
423 423
 
424
-		$this->registerService(Factory::class, function (Server $c) {
424
+		$this->registerService(Factory::class, function(Server $c) {
425 425
 			$config = $c->getConfig();
426 426
 
427 427
 			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
428 428
 				$v = \OC_App::getAppVersions();
429
-				$v['core'] = md5(file_get_contents(\OC::$SERVERROOT . '/version.php'));
429
+				$v['core'] = md5(file_get_contents(\OC::$SERVERROOT.'/version.php'));
430 430
 				$version = implode(',', $v);
431 431
 				$instanceId = \OC_Util::getInstanceId();
432 432
 				$path = \OC::$SERVERROOT;
433
-				$prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . \OC::$WEBROOT);
433
+				$prefix = md5($instanceId.'-'.$version.'-'.$path.'-'.\OC::$WEBROOT);
434 434
 				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
435 435
 					$config->getSystemValue('memcache.local', null),
436 436
 					$config->getSystemValue('memcache.distributed', null),
@@ -447,12 +447,12 @@  discard block
 block discarded – undo
447 447
 		$this->registerAlias('MemCacheFactory', Factory::class);
448 448
 		$this->registerAlias(ICacheFactory::class, Factory::class);
449 449
 
450
-		$this->registerService('RedisFactory', function (Server $c) {
450
+		$this->registerService('RedisFactory', function(Server $c) {
451 451
 			$systemConfig = $c->getSystemConfig();
452 452
 			return new RedisFactory($systemConfig);
453 453
 		});
454 454
 
455
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
455
+		$this->registerService(\OCP\Activity\IManager::class, function(Server $c) {
456 456
 			return new \OC\Activity\Manager(
457 457
 				$c->getRequest(),
458 458
 				$c->getUserSession(),
@@ -462,14 +462,14 @@  discard block
 block discarded – undo
462 462
 		});
463 463
 		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
464 464
 
465
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
465
+		$this->registerService(\OCP\Activity\IEventMerger::class, function(Server $c) {
466 466
 			return new \OC\Activity\EventMerger(
467 467
 				$c->getL10N('lib')
468 468
 			);
469 469
 		});
470 470
 		$this->registerAlias(IValidator::class, Validator::class);
471 471
 
472
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
472
+		$this->registerService(\OCP\IAvatarManager::class, function(Server $c) {
473 473
 			return new AvatarManager(
474 474
 				$c->getUserManager(),
475 475
 				$c->getAppDataDir('avatar'),
@@ -480,7 +480,7 @@  discard block
 block discarded – undo
480 480
 		});
481 481
 		$this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
482 482
 
483
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
483
+		$this->registerService(\OCP\ILogger::class, function(Server $c) {
484 484
 			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
485 485
 			$logger = Log::getLogClass($logType);
486 486
 			call_user_func(array($logger, 'init'));
@@ -489,7 +489,7 @@  discard block
 block discarded – undo
489 489
 		});
490 490
 		$this->registerAlias('Logger', \OCP\ILogger::class);
491 491
 
492
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
492
+		$this->registerService(\OCP\BackgroundJob\IJobList::class, function(Server $c) {
493 493
 			$config = $c->getConfig();
494 494
 			return new \OC\BackgroundJob\JobList(
495 495
 				$c->getDatabaseConnection(),
@@ -499,7 +499,7 @@  discard block
 block discarded – undo
499 499
 		});
500 500
 		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
501 501
 
502
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
502
+		$this->registerService(\OCP\Route\IRouter::class, function(Server $c) {
503 503
 			$cacheFactory = $c->getMemCacheFactory();
504 504
 			$logger = $c->getLogger();
505 505
 			if ($cacheFactory->isAvailable()) {
@@ -511,7 +511,7 @@  discard block
 block discarded – undo
511 511
 		});
512 512
 		$this->registerAlias('Router', \OCP\Route\IRouter::class);
513 513
 
514
-		$this->registerService(\OCP\ISearch::class, function ($c) {
514
+		$this->registerService(\OCP\ISearch::class, function($c) {
515 515
 			return new Search();
516 516
 		});
517 517
 		$this->registerAlias('Search', \OCP\ISearch::class);
@@ -531,27 +531,27 @@  discard block
 block discarded – undo
531 531
 			);
532 532
 		});
533 533
 
534
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
534
+		$this->registerService(\OCP\Security\ISecureRandom::class, function($c) {
535 535
 			return new SecureRandom();
536 536
 		});
537 537
 		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
538 538
 
539
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
539
+		$this->registerService(\OCP\Security\ICrypto::class, function(Server $c) {
540 540
 			return new Crypto($c->getConfig(), $c->getSecureRandom());
541 541
 		});
542 542
 		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
543 543
 
544
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
544
+		$this->registerService(\OCP\Security\IHasher::class, function(Server $c) {
545 545
 			return new Hasher($c->getConfig());
546 546
 		});
547 547
 		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
548 548
 
549
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
549
+		$this->registerService(\OCP\Security\ICredentialsManager::class, function(Server $c) {
550 550
 			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
551 551
 		});
552 552
 		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
553 553
 
554
-		$this->registerService(IDBConnection::class, function (Server $c) {
554
+		$this->registerService(IDBConnection::class, function(Server $c) {
555 555
 			$systemConfig = $c->getSystemConfig();
556 556
 			$factory = new \OC\DB\ConnectionFactory($systemConfig);
557 557
 			$type = $systemConfig->getValue('dbtype', 'sqlite');
@@ -565,7 +565,7 @@  discard block
 block discarded – undo
565 565
 		});
566 566
 		$this->registerAlias('DatabaseConnection', IDBConnection::class);
567 567
 
568
-		$this->registerService('HTTPHelper', function (Server $c) {
568
+		$this->registerService('HTTPHelper', function(Server $c) {
569 569
 			$config = $c->getConfig();
570 570
 			return new HTTPHelper(
571 571
 				$config,
@@ -573,7 +573,7 @@  discard block
 block discarded – undo
573 573
 			);
574 574
 		});
575 575
 
576
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
576
+		$this->registerService(\OCP\Http\Client\IClientService::class, function(Server $c) {
577 577
 			$user = \OC_User::getUser();
578 578
 			$uid = $user ? $user : null;
579 579
 			return new ClientService(
@@ -583,7 +583,7 @@  discard block
 block discarded – undo
583 583
 		});
584 584
 		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
585 585
 
586
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
586
+		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function(Server $c) {
587 587
 			if ($c->getSystemConfig()->getValue('debug', false)) {
588 588
 				return new EventLogger();
589 589
 			} else {
@@ -592,7 +592,7 @@  discard block
 block discarded – undo
592 592
 		});
593 593
 		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
594 594
 
595
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
595
+		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function(Server $c) {
596 596
 			if ($c->getSystemConfig()->getValue('debug', false)) {
597 597
 				return new QueryLogger();
598 598
 			} else {
@@ -601,7 +601,7 @@  discard block
 block discarded – undo
601 601
 		});
602 602
 		$this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
603 603
 
604
-		$this->registerService(TempManager::class, function (Server $c) {
604
+		$this->registerService(TempManager::class, function(Server $c) {
605 605
 			return new TempManager(
606 606
 				$c->getLogger(),
607 607
 				$c->getConfig()
@@ -610,7 +610,7 @@  discard block
 block discarded – undo
610 610
 		$this->registerAlias('TempManager', TempManager::class);
611 611
 		$this->registerAlias(ITempManager::class, TempManager::class);
612 612
 
613
-		$this->registerService(AppManager::class, function (Server $c) {
613
+		$this->registerService(AppManager::class, function(Server $c) {
614 614
 			return new \OC\App\AppManager(
615 615
 				$c->getUserSession(),
616 616
 				$c->getAppConfig(),
@@ -622,7 +622,7 @@  discard block
 block discarded – undo
622 622
 		$this->registerAlias('AppManager', AppManager::class);
623 623
 		$this->registerAlias(IAppManager::class, AppManager::class);
624 624
 
625
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
625
+		$this->registerService(\OCP\IDateTimeZone::class, function(Server $c) {
626 626
 			return new DateTimeZone(
627 627
 				$c->getConfig(),
628 628
 				$c->getSession()
@@ -630,7 +630,7 @@  discard block
 block discarded – undo
630 630
 		});
631 631
 		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
632 632
 
633
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
633
+		$this->registerService(\OCP\IDateTimeFormatter::class, function(Server $c) {
634 634
 			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
635 635
 
636 636
 			return new DateTimeFormatter(
@@ -640,7 +640,7 @@  discard block
 block discarded – undo
640 640
 		});
641 641
 		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
642 642
 
643
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
643
+		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function(Server $c) {
644 644
 			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
645 645
 			$listener = new UserMountCacheListener($mountCache);
646 646
 			$listener->listen($c->getUserManager());
@@ -648,10 +648,10 @@  discard block
 block discarded – undo
648 648
 		});
649 649
 		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
650 650
 
651
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
651
+		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function(Server $c) {
652 652
 			$loader = \OC\Files\Filesystem::getLoader();
653 653
 			$mountCache = $c->query('UserMountCache');
654
-			$manager =  new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
654
+			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
655 655
 
656 656
 			// builtin providers
657 657
 
@@ -664,14 +664,14 @@  discard block
 block discarded – undo
664 664
 		});
665 665
 		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
666 666
 
667
-		$this->registerService('IniWrapper', function ($c) {
667
+		$this->registerService('IniWrapper', function($c) {
668 668
 			return new IniGetWrapper();
669 669
 		});
670
-		$this->registerService('AsyncCommandBus', function (Server $c) {
670
+		$this->registerService('AsyncCommandBus', function(Server $c) {
671 671
 			$jobList = $c->getJobList();
672 672
 			return new AsyncBus($jobList);
673 673
 		});
674
-		$this->registerService('TrustedDomainHelper', function ($c) {
674
+		$this->registerService('TrustedDomainHelper', function($c) {
675 675
 			return new TrustedDomainHelper($this->getConfig());
676 676
 		});
677 677
 		$this->registerService('Throttler', function(Server $c) {
@@ -682,10 +682,10 @@  discard block
 block discarded – undo
682 682
 				$c->getConfig()
683 683
 			);
684 684
 		});
685
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
685
+		$this->registerService('IntegrityCodeChecker', function(Server $c) {
686 686
 			// IConfig and IAppManager requires a working database. This code
687 687
 			// might however be called when ownCloud is not yet setup.
688
-			if(\OC::$server->getSystemConfig()->getValue('installed', false)) {
688
+			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
689 689
 				$config = $c->getConfig();
690 690
 				$appManager = $c->getAppManager();
691 691
 			} else {
@@ -703,7 +703,7 @@  discard block
 block discarded – undo
703 703
 					$c->getTempManager()
704 704
 			);
705 705
 		});
706
-		$this->registerService(\OCP\IRequest::class, function ($c) {
706
+		$this->registerService(\OCP\IRequest::class, function($c) {
707 707
 			if (isset($this['urlParams'])) {
708 708
 				$urlParams = $this['urlParams'];
709 709
 			} else {
@@ -739,7 +739,7 @@  discard block
 block discarded – undo
739 739
 		});
740 740
 		$this->registerAlias('Request', \OCP\IRequest::class);
741 741
 
742
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
742
+		$this->registerService(\OCP\Mail\IMailer::class, function(Server $c) {
743 743
 			return new Mailer(
744 744
 				$c->getConfig(),
745 745
 				$c->getLogger(),
@@ -753,14 +753,14 @@  discard block
 block discarded – undo
753 753
 		$this->registerService('LDAPProvider', function(Server $c) {
754 754
 			$config = $c->getConfig();
755 755
 			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
756
-			if(is_null($factoryClass)) {
756
+			if (is_null($factoryClass)) {
757 757
 				throw new \Exception('ldapProviderFactory not set');
758 758
 			}
759 759
 			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
760 760
 			$factory = new $factoryClass($this);
761 761
 			return $factory->getLDAPProvider();
762 762
 		});
763
-		$this->registerService('LockingProvider', function (Server $c) {
763
+		$this->registerService('LockingProvider', function(Server $c) {
764 764
 			$ini = $c->getIniWrapper();
765 765
 			$config = $c->getConfig();
766 766
 			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
@@ -776,37 +776,37 @@  discard block
 block discarded – undo
776 776
 			return new NoopLockingProvider();
777 777
 		});
778 778
 
779
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
779
+		$this->registerService(\OCP\Files\Mount\IMountManager::class, function() {
780 780
 			return new \OC\Files\Mount\Manager();
781 781
 		});
782 782
 		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
783 783
 
784
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
784
+		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function(Server $c) {
785 785
 			return new \OC\Files\Type\Detection(
786 786
 				$c->getURLGenerator(),
787 787
 				\OC::$configDir,
788
-				\OC::$SERVERROOT . '/resources/config/'
788
+				\OC::$SERVERROOT.'/resources/config/'
789 789
 			);
790 790
 		});
791 791
 		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
792 792
 
793
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
793
+		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function(Server $c) {
794 794
 			return new \OC\Files\Type\Loader(
795 795
 				$c->getDatabaseConnection()
796 796
 			);
797 797
 		});
798 798
 		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
799 799
 
800
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
800
+		$this->registerService(\OCP\Notification\IManager::class, function(Server $c) {
801 801
 			return new Manager(
802 802
 				$c->query(IValidator::class)
803 803
 			);
804 804
 		});
805 805
 		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
806 806
 
807
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
807
+		$this->registerService(\OC\CapabilitiesManager::class, function(Server $c) {
808 808
 			$manager = new \OC\CapabilitiesManager($c->getLogger());
809
-			$manager->registerCapability(function () use ($c) {
809
+			$manager->registerCapability(function() use ($c) {
810 810
 				return new \OC\OCS\CoreCapabilities($c->getConfig());
811 811
 			});
812 812
 			return $manager;
@@ -848,13 +848,13 @@  discard block
 block discarded – undo
848 848
 			}
849 849
 			return new \OC_Defaults();
850 850
 		});
851
-		$this->registerService(EventDispatcher::class, function () {
851
+		$this->registerService(EventDispatcher::class, function() {
852 852
 			return new EventDispatcher();
853 853
 		});
854 854
 		$this->registerAlias('EventDispatcher', EventDispatcher::class);
855 855
 		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
856 856
 
857
-		$this->registerService('CryptoWrapper', function (Server $c) {
857
+		$this->registerService('CryptoWrapper', function(Server $c) {
858 858
 			// FIXME: Instantiiated here due to cyclic dependency
859 859
 			$request = new Request(
860 860
 				[
@@ -879,7 +879,7 @@  discard block
 block discarded – undo
879 879
 				$request
880 880
 			);
881 881
 		});
882
-		$this->registerService('CsrfTokenManager', function (Server $c) {
882
+		$this->registerService('CsrfTokenManager', function(Server $c) {
883 883
 			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
884 884
 
885 885
 			return new CsrfTokenManager(
@@ -887,10 +887,10 @@  discard block
 block discarded – undo
887 887
 				$c->query(SessionStorage::class)
888 888
 			);
889 889
 		});
890
-		$this->registerService(SessionStorage::class, function (Server $c) {
890
+		$this->registerService(SessionStorage::class, function(Server $c) {
891 891
 			return new SessionStorage($c->getSession());
892 892
 		});
893
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
893
+		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function(Server $c) {
894 894
 			return new ContentSecurityPolicyManager();
895 895
 		});
896 896
 		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
@@ -941,29 +941,29 @@  discard block
 block discarded – undo
941 941
 			);
942 942
 			return $manager;
943 943
 		});
944
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
944
+		$this->registerService(\OC\Files\AppData\Factory::class, function(Server $c) {
945 945
 			return new \OC\Files\AppData\Factory(
946 946
 				$c->getRootFolder(),
947 947
 				$c->getSystemConfig()
948 948
 			);
949 949
 		});
950 950
 
951
-		$this->registerService('LockdownManager', function (Server $c) {
951
+		$this->registerService('LockdownManager', function(Server $c) {
952 952
 			return new LockdownManager(function() use ($c) {
953 953
 				return $c->getSession();
954 954
 			});
955 955
 		});
956 956
 
957
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
957
+		$this->registerService(\OCP\OCS\IDiscoveryService::class, function(Server $c) {
958 958
 			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
959 959
 		});
960 960
 
961
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
961
+		$this->registerService(ICloudIdManager::class, function(Server $c) {
962 962
 			return new CloudIdManager();
963 963
 		});
964 964
 
965 965
 		/* To trick DI since we don't extend the DIContainer here */
966
-		$this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
966
+		$this->registerService(CleanPreviewsBackgroundJob::class, function(Server $c) {
967 967
 			return new CleanPreviewsBackgroundJob(
968 968
 				$c->getRootFolder(),
969 969
 				$c->getLogger(),
@@ -978,7 +978,7 @@  discard block
 block discarded – undo
978 978
 		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
979 979
 		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
980 980
 
981
-		$this->registerService(Defaults::class, function (Server $c) {
981
+		$this->registerService(Defaults::class, function(Server $c) {
982 982
 			return new Defaults(
983 983
 				$c->getThemingDefaults()
984 984
 			);
@@ -1124,7 +1124,7 @@  discard block
 block discarded – undo
1124 1124
 	 * @deprecated since 9.2.0 use IAppData
1125 1125
 	 */
1126 1126
 	public function getAppFolder() {
1127
-		$dir = '/' . \OC_App::getCurrentApp();
1127
+		$dir = '/'.\OC_App::getCurrentApp();
1128 1128
 		$root = $this->getRootFolder();
1129 1129
 		if (!$root->nodeExists($dir)) {
1130 1130
 			$folder = $root->newFolder($dir);
Please login to merge, or discard this patch.