Completed
Pull Request — master (#4256)
by Morris
22:14 queued 10:23
created
lib/base.php 1 patch
Indentation   +988 added lines, -988 removed lines patch added patch discarded remove patch
@@ -59,994 +59,994 @@
 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
-		//make sure temporary files are cleaned up
731
-		$tmpManager = \OC::$server->getTempManager();
732
-		register_shutdown_function(array($tmpManager, 'clean'));
733
-		$lockProvider = \OC::$server->getLockingProvider();
734
-		register_shutdown_function(array($lockProvider, 'releaseAll'));
735
-
736
-		// Check whether the sample configuration has been copied
737
-		if($systemConfig->getValue('copied_sample_config', false)) {
738
-			$l = \OC::$server->getL10N('lib');
739
-			header('HTTP/1.1 503 Service Temporarily Unavailable');
740
-			header('Status: 503 Service Temporarily Unavailable');
741
-			OC_Template::printErrorPage(
742
-				$l->t('Sample configuration detected'),
743
-				$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')
744
-			);
745
-			return;
746
-		}
747
-
748
-		$request = \OC::$server->getRequest();
749
-		$host = $request->getInsecureServerHost();
750
-		/**
751
-		 * if the host passed in headers isn't trusted
752
-		 * FIXME: Should not be in here at all :see_no_evil:
753
-		 */
754
-		if (!OC::$CLI
755
-			// overwritehost is always trusted, workaround to not have to make
756
-			// \OC\AppFramework\Http\Request::getOverwriteHost public
757
-			&& self::$server->getConfig()->getSystemValue('overwritehost') === ''
758
-			&& !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
759
-			&& self::$server->getConfig()->getSystemValue('installed', false)
760
-		) {
761
-			// Allow access to CSS resources
762
-			$isScssRequest = false;
763
-			if(strpos($request->getPathInfo(), '/css/') === 0) {
764
-				$isScssRequest = true;
765
-			}
766
-
767
-			if (!$isScssRequest) {
768
-				header('HTTP/1.1 400 Bad Request');
769
-				header('Status: 400 Bad Request');
770
-
771
-				\OC::$server->getLogger()->warning(
772
-					'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
773
-					[
774
-						'app' => 'core',
775
-						'remoteAddress' => $request->getRemoteAddress(),
776
-						'host' => $host,
777
-					]
778
-				);
779
-
780
-				$tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
781
-				$tmpl->assign('domain', $host);
782
-				$tmpl->printPage();
783
-
784
-				exit();
785
-			}
786
-		}
787
-		\OC::$server->getEventLogger()->end('boot');
788
-	}
789
-
790
-	/**
791
-	 * register hooks for the cache
792
-	 */
793
-	public static function registerCacheHooks() {
794
-		//don't try to do this before we are properly setup
795
-		if (\OC::$server->getSystemConfig()->getValue('installed', false) && !self::checkUpgrade(false)) {
796
-
797
-			// NOTE: This will be replaced to use OCP
798
-			$userSession = self::$server->getUserSession();
799
-			$userSession->listen('\OC\User', 'postLogin', function () {
800
-				try {
801
-					$cache = new \OC\Cache\File();
802
-					$cache->gc();
803
-				} catch (\OC\ServerNotAvailableException $e) {
804
-					// not a GC exception, pass it on
805
-					throw $e;
806
-				} catch (\Exception $e) {
807
-					// a GC exception should not prevent users from using OC,
808
-					// so log the exception
809
-					\OC::$server->getLogger()->warning('Exception when running cache gc: ' . $e->getMessage(), array('app' => 'core'));
810
-				}
811
-			});
812
-		}
813
-	}
814
-
815
-	public static function registerSettingsHooks() {
816
-		$dispatcher = \OC::$server->getEventDispatcher();
817
-		$dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_DISABLE, function($event) {
818
-			/** @var \OCP\App\ManagerEvent $event */
819
-			\OC::$server->getSettingsManager()->onAppDisabled($event->getAppID());
820
-		});
821
-		$dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_UPDATE, function($event) {
822
-			/** @var \OCP\App\ManagerEvent $event */
823
-			$jobList = \OC::$server->getJobList();
824
-			$job = 'OC\\Settings\\RemoveOrphaned';
825
-			if(!($jobList->has($job, null))) {
826
-				$jobList->add($job);
827
-			}
828
-		});
829
-	}
830
-
831
-	private static function registerEncryptionWrapper() {
832
-		$manager = self::$server->getEncryptionManager();
833
-		\OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
834
-	}
835
-
836
-	private static function registerEncryptionHooks() {
837
-		$enabled = self::$server->getEncryptionManager()->isEnabled();
838
-		if ($enabled) {
839
-			\OCP\Util::connectHook('OCP\Share', 'post_shared', 'OC\Encryption\HookManager', 'postShared');
840
-			\OCP\Util::connectHook('OCP\Share', 'post_unshare', 'OC\Encryption\HookManager', 'postUnshared');
841
-			\OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OC\Encryption\HookManager', 'postRename');
842
-			\OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', 'OC\Encryption\HookManager', 'postRestore');
843
-		}
844
-	}
845
-
846
-	private static function registerAccountHooks() {
847
-		$hookHandler = new \OC\Accounts\Hooks(\OC::$server->getLogger());
848
-		\OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
849
-	}
850
-
851
-	/**
852
-	 * register hooks for the cache
853
-	 */
854
-	public static function registerLogRotate() {
855
-		$systemConfig = \OC::$server->getSystemConfig();
856
-		if ($systemConfig->getValue('installed', false) && $systemConfig->getValue('log_rotate_size', false) && !self::checkUpgrade(false)) {
857
-			//don't try to do this before we are properly setup
858
-			//use custom logfile path if defined, otherwise use default of nextcloud.log in data directory
859
-			\OC::$server->getJobList()->add('OC\Log\Rotate');
860
-		}
861
-	}
862
-
863
-	/**
864
-	 * register hooks for the filesystem
865
-	 */
866
-	public static function registerFilesystemHooks() {
867
-		// Check for blacklisted files
868
-		OC_Hook::connect('OC_Filesystem', 'write', 'OC\Files\Filesystem', 'isBlacklisted');
869
-		OC_Hook::connect('OC_Filesystem', 'rename', 'OC\Files\Filesystem', 'isBlacklisted');
870
-	}
871
-
872
-	/**
873
-	 * register hooks for sharing
874
-	 */
875
-	public static function registerShareHooks() {
876
-		if (\OC::$server->getSystemConfig()->getValue('installed')) {
877
-			OC_Hook::connect('OC_User', 'post_deleteUser', 'OC\Share20\Hooks', 'post_deleteUser');
878
-			OC_Hook::connect('OC_User', 'post_removeFromGroup', 'OC\Share20\Hooks', 'post_removeFromGroup');
879
-			OC_Hook::connect('OC_User', 'post_deleteGroup', 'OC\Share20\Hooks', 'post_deleteGroup');
880
-		}
881
-	}
882
-
883
-	protected static function registerAutoloaderCache() {
884
-		// The class loader takes an optional low-latency cache, which MUST be
885
-		// namespaced. The instanceid is used for namespacing, but might be
886
-		// unavailable at this point. Furthermore, it might not be possible to
887
-		// generate an instanceid via \OC_Util::getInstanceId() because the
888
-		// config file may not be writable. As such, we only register a class
889
-		// loader cache if instanceid is available without trying to create one.
890
-		$instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
891
-		if ($instanceId) {
892
-			try {
893
-				$memcacheFactory = \OC::$server->getMemCacheFactory();
894
-				self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
895
-			} catch (\Exception $ex) {
896
-			}
897
-		}
898
-	}
899
-
900
-	/**
901
-	 * Handle the request
902
-	 */
903
-	public static function handleRequest() {
904
-
905
-		\OC::$server->getEventLogger()->start('handle_request', 'Handle request');
906
-		$systemConfig = \OC::$server->getSystemConfig();
907
-		// load all the classpaths from the enabled apps so they are available
908
-		// in the routing files of each app
909
-		OC::loadAppClassPaths();
910
-
911
-		// Check if Nextcloud is installed or in maintenance (update) mode
912
-		if (!$systemConfig->getValue('installed', false)) {
913
-			\OC::$server->getSession()->clear();
914
-			$setupHelper = new OC\Setup(\OC::$server->getSystemConfig(), \OC::$server->getIniWrapper(),
915
-				\OC::$server->getL10N('lib'), \OC::$server->getDefaults(), \OC::$server->getLogger(),
916
-				\OC::$server->getSecureRandom());
917
-			$controller = new OC\Core\Controller\SetupController($setupHelper);
918
-			$controller->run($_POST);
919
-			exit();
920
-		}
921
-
922
-		$request = \OC::$server->getRequest();
923
-		$requestPath = $request->getRawPathInfo();
924
-		if ($requestPath === '/heartbeat') {
925
-			return;
926
-		}
927
-		if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
928
-			self::checkMaintenanceMode();
929
-			self::checkUpgrade();
930
-		}
931
-
932
-		// emergency app disabling
933
-		if ($requestPath === '/disableapp'
934
-			&& $request->getMethod() === 'POST'
935
-			&& ((string)$request->getParam('appid')) !== ''
936
-		) {
937
-			\OCP\JSON::callCheck();
938
-			\OCP\JSON::checkAdminUser();
939
-			$appId = (string)$request->getParam('appid');
940
-			$appId = \OC_App::cleanAppId($appId);
941
-
942
-			\OC_App::disable($appId);
943
-			\OC_JSON::success();
944
-			exit();
945
-		}
946
-
947
-		// Always load authentication apps
948
-		OC_App::loadApps(['authentication']);
949
-
950
-		// Load minimum set of apps
951
-		if (!self::checkUpgrade(false)
952
-			&& !$systemConfig->getValue('maintenance', false)) {
953
-			// For logged-in users: Load everything
954
-			if(\OC::$server->getUserSession()->isLoggedIn()) {
955
-				OC_App::loadApps();
956
-			} else {
957
-				// For guests: Load only filesystem and logging
958
-				OC_App::loadApps(array('filesystem', 'logging'));
959
-				self::handleLogin($request);
960
-			}
961
-		}
962
-
963
-		if (!self::$CLI) {
964
-			try {
965
-				if (!$systemConfig->getValue('maintenance', false) && !self::checkUpgrade(false)) {
966
-					OC_App::loadApps(array('filesystem', 'logging'));
967
-					OC_App::loadApps();
968
-				}
969
-				OC_Util::setupFS();
970
-				OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
971
-				return;
972
-			} catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
973
-				//header('HTTP/1.0 404 Not Found');
974
-			} catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
975
-				OC_Response::setStatus(405);
976
-				return;
977
-			}
978
-		}
979
-
980
-		// Handle WebDAV
981
-		if ($_SERVER['REQUEST_METHOD'] == 'PROPFIND') {
982
-			// not allowed any more to prevent people
983
-			// mounting this root directly.
984
-			// Users need to mount remote.php/webdav instead.
985
-			header('HTTP/1.1 405 Method Not Allowed');
986
-			header('Status: 405 Method Not Allowed');
987
-			return;
988
-		}
989
-
990
-		// Someone is logged in
991
-		if (\OC::$server->getUserSession()->isLoggedIn()) {
992
-			OC_App::loadApps();
993
-			OC_User::setupBackends();
994
-			OC_Util::setupFS();
995
-			// FIXME
996
-			// Redirect to default application
997
-			OC_Util::redirectToDefaultPage();
998
-		} else {
999
-			// Not handled and not logged in
1000
-			header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1001
-		}
1002
-	}
1003
-
1004
-	/**
1005
-	 * Check login: apache auth, auth token, basic auth
1006
-	 *
1007
-	 * @param OCP\IRequest $request
1008
-	 * @return boolean
1009
-	 */
1010
-	static function handleLogin(OCP\IRequest $request) {
1011
-		$userSession = self::$server->getUserSession();
1012
-		if (OC_User::handleApacheAuth()) {
1013
-			return true;
1014
-		}
1015
-		if ($userSession->tryTokenLogin($request)) {
1016
-			return true;
1017
-		}
1018
-		if (isset($_COOKIE['nc_username'])
1019
-			&& isset($_COOKIE['nc_token'])
1020
-			&& isset($_COOKIE['nc_session_id'])
1021
-			&& $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1022
-			return true;
1023
-		}
1024
-		if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1025
-			return true;
1026
-		}
1027
-		return false;
1028
-	}
1029
-
1030
-	protected static function handleAuthHeaders() {
1031
-		//copy http auth headers for apache+php-fcgid work around
1032
-		if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1033
-			$_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1034
-		}
1035
-
1036
-		// Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1037
-		$vars = array(
1038
-			'HTTP_AUTHORIZATION', // apache+php-cgi work around
1039
-			'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1040
-		);
1041
-		foreach ($vars as $var) {
1042
-			if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1043
-				list($name, $password) = explode(':', base64_decode($matches[1]), 2);
1044
-				$_SERVER['PHP_AUTH_USER'] = $name;
1045
-				$_SERVER['PHP_AUTH_PW'] = $password;
1046
-				break;
1047
-			}
1048
-		}
1049
-	}
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
+        //make sure temporary files are cleaned up
731
+        $tmpManager = \OC::$server->getTempManager();
732
+        register_shutdown_function(array($tmpManager, 'clean'));
733
+        $lockProvider = \OC::$server->getLockingProvider();
734
+        register_shutdown_function(array($lockProvider, 'releaseAll'));
735
+
736
+        // Check whether the sample configuration has been copied
737
+        if($systemConfig->getValue('copied_sample_config', false)) {
738
+            $l = \OC::$server->getL10N('lib');
739
+            header('HTTP/1.1 503 Service Temporarily Unavailable');
740
+            header('Status: 503 Service Temporarily Unavailable');
741
+            OC_Template::printErrorPage(
742
+                $l->t('Sample configuration detected'),
743
+                $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')
744
+            );
745
+            return;
746
+        }
747
+
748
+        $request = \OC::$server->getRequest();
749
+        $host = $request->getInsecureServerHost();
750
+        /**
751
+         * if the host passed in headers isn't trusted
752
+         * FIXME: Should not be in here at all :see_no_evil:
753
+         */
754
+        if (!OC::$CLI
755
+            // overwritehost is always trusted, workaround to not have to make
756
+            // \OC\AppFramework\Http\Request::getOverwriteHost public
757
+            && self::$server->getConfig()->getSystemValue('overwritehost') === ''
758
+            && !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
759
+            && self::$server->getConfig()->getSystemValue('installed', false)
760
+        ) {
761
+            // Allow access to CSS resources
762
+            $isScssRequest = false;
763
+            if(strpos($request->getPathInfo(), '/css/') === 0) {
764
+                $isScssRequest = true;
765
+            }
766
+
767
+            if (!$isScssRequest) {
768
+                header('HTTP/1.1 400 Bad Request');
769
+                header('Status: 400 Bad Request');
770
+
771
+                \OC::$server->getLogger()->warning(
772
+                    'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
773
+                    [
774
+                        'app' => 'core',
775
+                        'remoteAddress' => $request->getRemoteAddress(),
776
+                        'host' => $host,
777
+                    ]
778
+                );
779
+
780
+                $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
781
+                $tmpl->assign('domain', $host);
782
+                $tmpl->printPage();
783
+
784
+                exit();
785
+            }
786
+        }
787
+        \OC::$server->getEventLogger()->end('boot');
788
+    }
789
+
790
+    /**
791
+     * register hooks for the cache
792
+     */
793
+    public static function registerCacheHooks() {
794
+        //don't try to do this before we are properly setup
795
+        if (\OC::$server->getSystemConfig()->getValue('installed', false) && !self::checkUpgrade(false)) {
796
+
797
+            // NOTE: This will be replaced to use OCP
798
+            $userSession = self::$server->getUserSession();
799
+            $userSession->listen('\OC\User', 'postLogin', function () {
800
+                try {
801
+                    $cache = new \OC\Cache\File();
802
+                    $cache->gc();
803
+                } catch (\OC\ServerNotAvailableException $e) {
804
+                    // not a GC exception, pass it on
805
+                    throw $e;
806
+                } catch (\Exception $e) {
807
+                    // a GC exception should not prevent users from using OC,
808
+                    // so log the exception
809
+                    \OC::$server->getLogger()->warning('Exception when running cache gc: ' . $e->getMessage(), array('app' => 'core'));
810
+                }
811
+            });
812
+        }
813
+    }
814
+
815
+    public static function registerSettingsHooks() {
816
+        $dispatcher = \OC::$server->getEventDispatcher();
817
+        $dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_DISABLE, function($event) {
818
+            /** @var \OCP\App\ManagerEvent $event */
819
+            \OC::$server->getSettingsManager()->onAppDisabled($event->getAppID());
820
+        });
821
+        $dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_UPDATE, function($event) {
822
+            /** @var \OCP\App\ManagerEvent $event */
823
+            $jobList = \OC::$server->getJobList();
824
+            $job = 'OC\\Settings\\RemoveOrphaned';
825
+            if(!($jobList->has($job, null))) {
826
+                $jobList->add($job);
827
+            }
828
+        });
829
+    }
830
+
831
+    private static function registerEncryptionWrapper() {
832
+        $manager = self::$server->getEncryptionManager();
833
+        \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
834
+    }
835
+
836
+    private static function registerEncryptionHooks() {
837
+        $enabled = self::$server->getEncryptionManager()->isEnabled();
838
+        if ($enabled) {
839
+            \OCP\Util::connectHook('OCP\Share', 'post_shared', 'OC\Encryption\HookManager', 'postShared');
840
+            \OCP\Util::connectHook('OCP\Share', 'post_unshare', 'OC\Encryption\HookManager', 'postUnshared');
841
+            \OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OC\Encryption\HookManager', 'postRename');
842
+            \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', 'OC\Encryption\HookManager', 'postRestore');
843
+        }
844
+    }
845
+
846
+    private static function registerAccountHooks() {
847
+        $hookHandler = new \OC\Accounts\Hooks(\OC::$server->getLogger());
848
+        \OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
849
+    }
850
+
851
+    /**
852
+     * register hooks for the cache
853
+     */
854
+    public static function registerLogRotate() {
855
+        $systemConfig = \OC::$server->getSystemConfig();
856
+        if ($systemConfig->getValue('installed', false) && $systemConfig->getValue('log_rotate_size', false) && !self::checkUpgrade(false)) {
857
+            //don't try to do this before we are properly setup
858
+            //use custom logfile path if defined, otherwise use default of nextcloud.log in data directory
859
+            \OC::$server->getJobList()->add('OC\Log\Rotate');
860
+        }
861
+    }
862
+
863
+    /**
864
+     * register hooks for the filesystem
865
+     */
866
+    public static function registerFilesystemHooks() {
867
+        // Check for blacklisted files
868
+        OC_Hook::connect('OC_Filesystem', 'write', 'OC\Files\Filesystem', 'isBlacklisted');
869
+        OC_Hook::connect('OC_Filesystem', 'rename', 'OC\Files\Filesystem', 'isBlacklisted');
870
+    }
871
+
872
+    /**
873
+     * register hooks for sharing
874
+     */
875
+    public static function registerShareHooks() {
876
+        if (\OC::$server->getSystemConfig()->getValue('installed')) {
877
+            OC_Hook::connect('OC_User', 'post_deleteUser', 'OC\Share20\Hooks', 'post_deleteUser');
878
+            OC_Hook::connect('OC_User', 'post_removeFromGroup', 'OC\Share20\Hooks', 'post_removeFromGroup');
879
+            OC_Hook::connect('OC_User', 'post_deleteGroup', 'OC\Share20\Hooks', 'post_deleteGroup');
880
+        }
881
+    }
882
+
883
+    protected static function registerAutoloaderCache() {
884
+        // The class loader takes an optional low-latency cache, which MUST be
885
+        // namespaced. The instanceid is used for namespacing, but might be
886
+        // unavailable at this point. Furthermore, it might not be possible to
887
+        // generate an instanceid via \OC_Util::getInstanceId() because the
888
+        // config file may not be writable. As such, we only register a class
889
+        // loader cache if instanceid is available without trying to create one.
890
+        $instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
891
+        if ($instanceId) {
892
+            try {
893
+                $memcacheFactory = \OC::$server->getMemCacheFactory();
894
+                self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
895
+            } catch (\Exception $ex) {
896
+            }
897
+        }
898
+    }
899
+
900
+    /**
901
+     * Handle the request
902
+     */
903
+    public static function handleRequest() {
904
+
905
+        \OC::$server->getEventLogger()->start('handle_request', 'Handle request');
906
+        $systemConfig = \OC::$server->getSystemConfig();
907
+        // load all the classpaths from the enabled apps so they are available
908
+        // in the routing files of each app
909
+        OC::loadAppClassPaths();
910
+
911
+        // Check if Nextcloud is installed or in maintenance (update) mode
912
+        if (!$systemConfig->getValue('installed', false)) {
913
+            \OC::$server->getSession()->clear();
914
+            $setupHelper = new OC\Setup(\OC::$server->getSystemConfig(), \OC::$server->getIniWrapper(),
915
+                \OC::$server->getL10N('lib'), \OC::$server->getDefaults(), \OC::$server->getLogger(),
916
+                \OC::$server->getSecureRandom());
917
+            $controller = new OC\Core\Controller\SetupController($setupHelper);
918
+            $controller->run($_POST);
919
+            exit();
920
+        }
921
+
922
+        $request = \OC::$server->getRequest();
923
+        $requestPath = $request->getRawPathInfo();
924
+        if ($requestPath === '/heartbeat') {
925
+            return;
926
+        }
927
+        if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
928
+            self::checkMaintenanceMode();
929
+            self::checkUpgrade();
930
+        }
931
+
932
+        // emergency app disabling
933
+        if ($requestPath === '/disableapp'
934
+            && $request->getMethod() === 'POST'
935
+            && ((string)$request->getParam('appid')) !== ''
936
+        ) {
937
+            \OCP\JSON::callCheck();
938
+            \OCP\JSON::checkAdminUser();
939
+            $appId = (string)$request->getParam('appid');
940
+            $appId = \OC_App::cleanAppId($appId);
941
+
942
+            \OC_App::disable($appId);
943
+            \OC_JSON::success();
944
+            exit();
945
+        }
946
+
947
+        // Always load authentication apps
948
+        OC_App::loadApps(['authentication']);
949
+
950
+        // Load minimum set of apps
951
+        if (!self::checkUpgrade(false)
952
+            && !$systemConfig->getValue('maintenance', false)) {
953
+            // For logged-in users: Load everything
954
+            if(\OC::$server->getUserSession()->isLoggedIn()) {
955
+                OC_App::loadApps();
956
+            } else {
957
+                // For guests: Load only filesystem and logging
958
+                OC_App::loadApps(array('filesystem', 'logging'));
959
+                self::handleLogin($request);
960
+            }
961
+        }
962
+
963
+        if (!self::$CLI) {
964
+            try {
965
+                if (!$systemConfig->getValue('maintenance', false) && !self::checkUpgrade(false)) {
966
+                    OC_App::loadApps(array('filesystem', 'logging'));
967
+                    OC_App::loadApps();
968
+                }
969
+                OC_Util::setupFS();
970
+                OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
971
+                return;
972
+            } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
973
+                //header('HTTP/1.0 404 Not Found');
974
+            } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
975
+                OC_Response::setStatus(405);
976
+                return;
977
+            }
978
+        }
979
+
980
+        // Handle WebDAV
981
+        if ($_SERVER['REQUEST_METHOD'] == 'PROPFIND') {
982
+            // not allowed any more to prevent people
983
+            // mounting this root directly.
984
+            // Users need to mount remote.php/webdav instead.
985
+            header('HTTP/1.1 405 Method Not Allowed');
986
+            header('Status: 405 Method Not Allowed');
987
+            return;
988
+        }
989
+
990
+        // Someone is logged in
991
+        if (\OC::$server->getUserSession()->isLoggedIn()) {
992
+            OC_App::loadApps();
993
+            OC_User::setupBackends();
994
+            OC_Util::setupFS();
995
+            // FIXME
996
+            // Redirect to default application
997
+            OC_Util::redirectToDefaultPage();
998
+        } else {
999
+            // Not handled and not logged in
1000
+            header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1001
+        }
1002
+    }
1003
+
1004
+    /**
1005
+     * Check login: apache auth, auth token, basic auth
1006
+     *
1007
+     * @param OCP\IRequest $request
1008
+     * @return boolean
1009
+     */
1010
+    static function handleLogin(OCP\IRequest $request) {
1011
+        $userSession = self::$server->getUserSession();
1012
+        if (OC_User::handleApacheAuth()) {
1013
+            return true;
1014
+        }
1015
+        if ($userSession->tryTokenLogin($request)) {
1016
+            return true;
1017
+        }
1018
+        if (isset($_COOKIE['nc_username'])
1019
+            && isset($_COOKIE['nc_token'])
1020
+            && isset($_COOKIE['nc_session_id'])
1021
+            && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1022
+            return true;
1023
+        }
1024
+        if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1025
+            return true;
1026
+        }
1027
+        return false;
1028
+    }
1029
+
1030
+    protected static function handleAuthHeaders() {
1031
+        //copy http auth headers for apache+php-fcgid work around
1032
+        if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1033
+            $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1034
+        }
1035
+
1036
+        // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1037
+        $vars = array(
1038
+            'HTTP_AUTHORIZATION', // apache+php-cgi work around
1039
+            'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1040
+        );
1041
+        foreach ($vars as $var) {
1042
+            if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1043
+                list($name, $password) = explode(':', base64_decode($matches[1]), 2);
1044
+                $_SERVER['PHP_AUTH_USER'] = $name;
1045
+                $_SERVER['PHP_AUTH_PW'] = $password;
1046
+                break;
1047
+            }
1048
+        }
1049
+    }
1050 1050
 }
1051 1051
 
1052 1052
 OC::init();
Please login to merge, or discard this patch.
lib/public/IServerContainer.php 1 patch
Indentation   +481 added lines, -481 removed lines patch added patch discarded remove patch
@@ -56,485 +56,485 @@
 block discarded – undo
56 56
  */
57 57
 interface IServerContainer extends IContainer {
58 58
 
59
-	/**
60
-	 * The contacts manager will act as a broker between consumers for contacts information and
61
-	 * providers which actual deliver the contact information.
62
-	 *
63
-	 * @return \OCP\Contacts\IManager
64
-	 * @since 6.0.0
65
-	 */
66
-	public function getContactsManager();
67
-
68
-	/**
69
-	 * The current request object holding all information about the request currently being processed
70
-	 * is returned from this method.
71
-	 * In case the current execution was not initiated by a web request null is returned
72
-	 *
73
-	 * @return \OCP\IRequest
74
-	 * @since 6.0.0
75
-	 */
76
-	public function getRequest();
77
-
78
-	/**
79
-	 * Returns the preview manager which can create preview images for a given file
80
-	 *
81
-	 * @return \OCP\IPreview
82
-	 * @since 6.0.0
83
-	 */
84
-	public function getPreviewManager();
85
-
86
-	/**
87
-	 * Returns the tag manager which can get and set tags for different object types
88
-	 *
89
-	 * @see \OCP\ITagManager::load()
90
-	 * @return \OCP\ITagManager
91
-	 * @since 6.0.0
92
-	 */
93
-	public function getTagManager();
94
-
95
-	/**
96
-	 * Returns the root folder of ownCloud's data directory
97
-	 *
98
-	 * @return \OCP\Files\IRootFolder
99
-	 * @since 6.0.0 - between 6.0.0 and 8.0.0 this returned \OCP\Files\Folder
100
-	 */
101
-	public function getRootFolder();
102
-
103
-	/**
104
-	 * Returns a view to ownCloud's files folder
105
-	 *
106
-	 * @param string $userId user ID
107
-	 * @return \OCP\Files\Folder
108
-	 * @since 6.0.0 - parameter $userId was added in 8.0.0
109
-	 * @see getUserFolder in \OCP\Files\IRootFolder
110
-	 */
111
-	public function getUserFolder($userId = null);
112
-
113
-	/**
114
-	 * Returns an app-specific view in ownClouds data directory
115
-	 *
116
-	 * @return \OCP\Files\Folder
117
-	 * @since 6.0.0
118
-	 * @deprecated since 9.2.0 use IAppData
119
-	 */
120
-	public function getAppFolder();
121
-
122
-	/**
123
-	 * Returns a user manager
124
-	 *
125
-	 * @return \OCP\IUserManager
126
-	 * @since 8.0.0
127
-	 */
128
-	public function getUserManager();
129
-
130
-	/**
131
-	 * Returns a group manager
132
-	 *
133
-	 * @return \OCP\IGroupManager
134
-	 * @since 8.0.0
135
-	 */
136
-	public function getGroupManager();
137
-
138
-	/**
139
-	 * Returns the user session
140
-	 *
141
-	 * @return \OCP\IUserSession
142
-	 * @since 6.0.0
143
-	 */
144
-	public function getUserSession();
145
-
146
-	/**
147
-	 * Returns the navigation manager
148
-	 *
149
-	 * @return \OCP\INavigationManager
150
-	 * @since 6.0.0
151
-	 */
152
-	public function getNavigationManager();
153
-
154
-	/**
155
-	 * Returns the config manager
156
-	 *
157
-	 * @return \OCP\IConfig
158
-	 * @since 6.0.0
159
-	 */
160
-	public function getConfig();
161
-
162
-	/**
163
-	 * Returns a Crypto instance
164
-	 *
165
-	 * @return \OCP\Security\ICrypto
166
-	 * @since 8.0.0
167
-	 */
168
-	public function getCrypto();
169
-
170
-	/**
171
-	 * Returns a Hasher instance
172
-	 *
173
-	 * @return \OCP\Security\IHasher
174
-	 * @since 8.0.0
175
-	 */
176
-	public function getHasher();
177
-
178
-	/**
179
-	 * Returns a SecureRandom instance
180
-	 *
181
-	 * @return \OCP\Security\ISecureRandom
182
-	 * @since 8.1.0
183
-	 */
184
-	public function getSecureRandom();
185
-
186
-	/**
187
-	 * Returns a CredentialsManager instance
188
-	 *
189
-	 * @return \OCP\Security\ICredentialsManager
190
-	 * @since 9.0.0
191
-	 */
192
-	public function getCredentialsManager();
193
-
194
-	/**
195
-	 * Returns the app config manager
196
-	 *
197
-	 * @return \OCP\IAppConfig
198
-	 * @since 7.0.0
199
-	 */
200
-	public function getAppConfig();
201
-
202
-	/**
203
-	 * @return \OCP\L10N\IFactory
204
-	 * @since 8.2.0
205
-	 */
206
-	public function getL10NFactory();
207
-
208
-	/**
209
-	 * get an L10N instance
210
-	 * @param string $app appid
211
-	 * @param string $lang
212
-	 * @return \OCP\IL10N
213
-	 * @since 6.0.0 - parameter $lang was added in 8.0.0
214
-	 */
215
-	public function getL10N($app, $lang = null);
216
-
217
-	/**
218
-	 * @return \OC\Encryption\Manager
219
-	 * @since 8.1.0
220
-	 */
221
-	public function getEncryptionManager();
222
-
223
-	/**
224
-	 * @return \OC\Encryption\File
225
-	 * @since 8.1.0
226
-	 */
227
-	public function getEncryptionFilesHelper();
228
-
229
-	/**
230
-	 * @return \OCP\Encryption\Keys\IStorage
231
-	 * @since 8.1.0
232
-	 */
233
-	public function getEncryptionKeyStorage();
234
-
235
-	/**
236
-	 * Returns the URL generator
237
-	 *
238
-	 * @return \OCP\IURLGenerator
239
-	 * @since 6.0.0
240
-	 */
241
-	public function getURLGenerator();
242
-
243
-	/**
244
-	 * Returns the Helper
245
-	 *
246
-	 * @return \OCP\IHelper
247
-	 * @since 6.0.0
248
-	 */
249
-	public function getHelper();
250
-
251
-	/**
252
-	 * Returns an ICache instance
253
-	 *
254
-	 * @return \OCP\ICache
255
-	 * @since 6.0.0
256
-	 */
257
-	public function getCache();
258
-
259
-	/**
260
-	 * Returns an \OCP\CacheFactory instance
261
-	 *
262
-	 * @return \OCP\ICacheFactory
263
-	 * @since 7.0.0
264
-	 */
265
-	public function getMemCacheFactory();
266
-
267
-	/**
268
-	 * Returns the current session
269
-	 *
270
-	 * @return \OCP\ISession
271
-	 * @since 6.0.0
272
-	 */
273
-	public function getSession();
274
-
275
-	/**
276
-	 * Returns the activity manager
277
-	 *
278
-	 * @return \OCP\Activity\IManager
279
-	 * @since 6.0.0
280
-	 */
281
-	public function getActivityManager();
282
-
283
-	/**
284
-	 * Returns the current session
285
-	 *
286
-	 * @return \OCP\IDBConnection
287
-	 * @since 6.0.0
288
-	 */
289
-	public function getDatabaseConnection();
290
-
291
-	/**
292
-	 * Returns an avatar manager, used for avatar functionality
293
-	 *
294
-	 * @return \OCP\IAvatarManager
295
-	 * @since 6.0.0
296
-	 */
297
-	public function getAvatarManager();
298
-
299
-	/**
300
-	 * Returns an job list for controlling background jobs
301
-	 *
302
-	 * @return \OCP\BackgroundJob\IJobList
303
-	 * @since 7.0.0
304
-	 */
305
-	public function getJobList();
306
-
307
-	/**
308
-	 * Returns a logger instance
309
-	 *
310
-	 * @return \OCP\ILogger
311
-	 * @since 8.0.0
312
-	 */
313
-	public function getLogger();
314
-
315
-	/**
316
-	 * Returns a router for generating and matching urls
317
-	 *
318
-	 * @return \OCP\Route\IRouter
319
-	 * @since 7.0.0
320
-	 */
321
-	public function getRouter();
322
-
323
-	/**
324
-	 * Returns a search instance
325
-	 *
326
-	 * @return \OCP\ISearch
327
-	 * @since 7.0.0
328
-	 */
329
-	public function getSearch();
330
-
331
-	/**
332
-	 * Get the certificate manager for the user
333
-	 *
334
-	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
335
-	 * @return \OCP\ICertificateManager | null if $userId is null and no user is logged in
336
-	 * @since 8.0.0
337
-	 */
338
-	public function getCertificateManager($userId = null);
339
-
340
-	/**
341
-	 * Create a new event source
342
-	 *
343
-	 * @return \OCP\IEventSource
344
-	 * @since 8.0.0
345
-	 */
346
-	public function createEventSource();
347
-
348
-	/**
349
-	 * Returns an instance of the HTTP helper class
350
-	 * @return \OC\HTTPHelper
351
-	 * @deprecated 8.1.0 Use \OCP\Http\Client\IClientService
352
-	 * @since 8.0.0
353
-	 */
354
-	public function getHTTPHelper();
355
-
356
-	/**
357
-	 * Returns an instance of the HTTP client service
358
-	 *
359
-	 * @return \OCP\Http\Client\IClientService
360
-	 * @since 8.1.0
361
-	 */
362
-	public function getHTTPClientService();
363
-
364
-	/**
365
-	 * Get the active event logger
366
-	 *
367
-	 * @return \OCP\Diagnostics\IEventLogger
368
-	 * @since 8.0.0
369
-	 */
370
-	public function getEventLogger();
371
-
372
-	/**
373
-	 * Get the active query logger
374
-	 *
375
-	 * The returned logger only logs data when debug mode is enabled
376
-	 *
377
-	 * @return \OCP\Diagnostics\IQueryLogger
378
-	 * @since 8.0.0
379
-	 */
380
-	public function getQueryLogger();
381
-
382
-	/**
383
-	 * Get the manager for temporary files and folders
384
-	 *
385
-	 * @return \OCP\ITempManager
386
-	 * @since 8.0.0
387
-	 */
388
-	public function getTempManager();
389
-
390
-	/**
391
-	 * Get the app manager
392
-	 *
393
-	 * @return \OCP\App\IAppManager
394
-	 * @since 8.0.0
395
-	 */
396
-	public function getAppManager();
397
-
398
-	/**
399
-	 * Get the webroot
400
-	 *
401
-	 * @return string
402
-	 * @since 8.0.0
403
-	 */
404
-	public function getWebRoot();
405
-
406
-	/**
407
-	 * @return \OCP\Files\Config\IMountProviderCollection
408
-	 * @since 8.0.0
409
-	 */
410
-	public function getMountProviderCollection();
411
-
412
-	/**
413
-	 * Get the IniWrapper
414
-	 *
415
-	 * @return \bantu\IniGetWrapper\IniGetWrapper
416
-	 * @since 8.0.0
417
-	 */
418
-	public function getIniWrapper();
419
-	/**
420
-	 * @return \OCP\Command\IBus
421
-	 * @since 8.1.0
422
-	 */
423
-	public function getCommandBus();
424
-
425
-	/**
426
-	 * Creates a new mailer
427
-	 *
428
-	 * @return \OCP\Mail\IMailer
429
-	 * @since 8.1.0
430
-	 */
431
-	public function getMailer();
432
-
433
-	/**
434
-	 * Get the locking provider
435
-	 *
436
-	 * @return \OCP\Lock\ILockingProvider
437
-	 * @since 8.1.0
438
-	 */
439
-	public function getLockingProvider();
440
-
441
-	/**
442
-	 * @return \OCP\Files\Mount\IMountManager
443
-	 * @since 8.2.0
444
-	 */
445
-	public function getMountManager();
446
-
447
-	/**
448
-	 * Get the MimeTypeDetector
449
-	 *
450
-	 * @return \OCP\Files\IMimeTypeDetector
451
-	 * @since 8.2.0
452
-	 */
453
-	public function getMimeTypeDetector();
454
-
455
-	/**
456
-	 * Get the MimeTypeLoader
457
-	 *
458
-	 * @return \OCP\Files\IMimeTypeLoader
459
-	 * @since 8.2.0
460
-	 */
461
-	public function getMimeTypeLoader();
462
-
463
-	/**
464
-	 * Get the EventDispatcher
465
-	 *
466
-	 * @return EventDispatcherInterface
467
-	 * @since 8.2.0
468
-	 */
469
-	public function getEventDispatcher();
470
-
471
-	/**
472
-	 * Get the Notification Manager
473
-	 *
474
-	 * @return \OCP\Notification\IManager
475
-	 * @since 9.0.0
476
-	 */
477
-	public function getNotificationManager();
478
-
479
-	/**
480
-	 * @return \OCP\Comments\ICommentsManager
481
-	 * @since 9.0.0
482
-	 */
483
-	public function getCommentsManager();
484
-
485
-	/**
486
-	 * Returns the system-tag manager
487
-	 *
488
-	 * @return \OCP\SystemTag\ISystemTagManager
489
-	 *
490
-	 * @since 9.0.0
491
-	 */
492
-	public function getSystemTagManager();
493
-
494
-	/**
495
-	 * Returns the system-tag object mapper
496
-	 *
497
-	 * @return \OCP\SystemTag\ISystemTagObjectMapper
498
-	 *
499
-	 * @since 9.0.0
500
-	 */
501
-	public function getSystemTagObjectMapper();
502
-
503
-	/**
504
-	 * Returns the share manager
505
-	 *
506
-	 * @return \OCP\Share\IManager
507
-	 * @since 9.0.0
508
-	 */
509
-	public function getShareManager();
510
-
511
-	/**
512
-	 * @return IContentSecurityPolicyManager
513
-	 * @since 9.0.0
514
-	 */
515
-	public function getContentSecurityPolicyManager();
516
-
517
-	/**
518
-	 * @return \OCP\IDateTimeZone
519
-	 * @since 8.0.0
520
-	 */
521
-	public function getDateTimeZone();
522
-
523
-	/**
524
-	 * @return \OCP\IDateTimeFormatter
525
-	 * @since 8.0.0
526
-	 */
527
-	public function getDateTimeFormatter();
528
-
529
-	/**
530
-	 * @return \OCP\Federation\ICloudIdManager
531
-	 * @since 12.0.0
532
-	 */
533
-	public function getCloudIdManager();
534
-
535
-	/**
536
-	 * @return \OCP\Defaults
537
-	 * @since 12.0.0
538
-	 */
539
-	public function getDefaults();
59
+    /**
60
+     * The contacts manager will act as a broker between consumers for contacts information and
61
+     * providers which actual deliver the contact information.
62
+     *
63
+     * @return \OCP\Contacts\IManager
64
+     * @since 6.0.0
65
+     */
66
+    public function getContactsManager();
67
+
68
+    /**
69
+     * The current request object holding all information about the request currently being processed
70
+     * is returned from this method.
71
+     * In case the current execution was not initiated by a web request null is returned
72
+     *
73
+     * @return \OCP\IRequest
74
+     * @since 6.0.0
75
+     */
76
+    public function getRequest();
77
+
78
+    /**
79
+     * Returns the preview manager which can create preview images for a given file
80
+     *
81
+     * @return \OCP\IPreview
82
+     * @since 6.0.0
83
+     */
84
+    public function getPreviewManager();
85
+
86
+    /**
87
+     * Returns the tag manager which can get and set tags for different object types
88
+     *
89
+     * @see \OCP\ITagManager::load()
90
+     * @return \OCP\ITagManager
91
+     * @since 6.0.0
92
+     */
93
+    public function getTagManager();
94
+
95
+    /**
96
+     * Returns the root folder of ownCloud's data directory
97
+     *
98
+     * @return \OCP\Files\IRootFolder
99
+     * @since 6.0.0 - between 6.0.0 and 8.0.0 this returned \OCP\Files\Folder
100
+     */
101
+    public function getRootFolder();
102
+
103
+    /**
104
+     * Returns a view to ownCloud's files folder
105
+     *
106
+     * @param string $userId user ID
107
+     * @return \OCP\Files\Folder
108
+     * @since 6.0.0 - parameter $userId was added in 8.0.0
109
+     * @see getUserFolder in \OCP\Files\IRootFolder
110
+     */
111
+    public function getUserFolder($userId = null);
112
+
113
+    /**
114
+     * Returns an app-specific view in ownClouds data directory
115
+     *
116
+     * @return \OCP\Files\Folder
117
+     * @since 6.0.0
118
+     * @deprecated since 9.2.0 use IAppData
119
+     */
120
+    public function getAppFolder();
121
+
122
+    /**
123
+     * Returns a user manager
124
+     *
125
+     * @return \OCP\IUserManager
126
+     * @since 8.0.0
127
+     */
128
+    public function getUserManager();
129
+
130
+    /**
131
+     * Returns a group manager
132
+     *
133
+     * @return \OCP\IGroupManager
134
+     * @since 8.0.0
135
+     */
136
+    public function getGroupManager();
137
+
138
+    /**
139
+     * Returns the user session
140
+     *
141
+     * @return \OCP\IUserSession
142
+     * @since 6.0.0
143
+     */
144
+    public function getUserSession();
145
+
146
+    /**
147
+     * Returns the navigation manager
148
+     *
149
+     * @return \OCP\INavigationManager
150
+     * @since 6.0.0
151
+     */
152
+    public function getNavigationManager();
153
+
154
+    /**
155
+     * Returns the config manager
156
+     *
157
+     * @return \OCP\IConfig
158
+     * @since 6.0.0
159
+     */
160
+    public function getConfig();
161
+
162
+    /**
163
+     * Returns a Crypto instance
164
+     *
165
+     * @return \OCP\Security\ICrypto
166
+     * @since 8.0.0
167
+     */
168
+    public function getCrypto();
169
+
170
+    /**
171
+     * Returns a Hasher instance
172
+     *
173
+     * @return \OCP\Security\IHasher
174
+     * @since 8.0.0
175
+     */
176
+    public function getHasher();
177
+
178
+    /**
179
+     * Returns a SecureRandom instance
180
+     *
181
+     * @return \OCP\Security\ISecureRandom
182
+     * @since 8.1.0
183
+     */
184
+    public function getSecureRandom();
185
+
186
+    /**
187
+     * Returns a CredentialsManager instance
188
+     *
189
+     * @return \OCP\Security\ICredentialsManager
190
+     * @since 9.0.0
191
+     */
192
+    public function getCredentialsManager();
193
+
194
+    /**
195
+     * Returns the app config manager
196
+     *
197
+     * @return \OCP\IAppConfig
198
+     * @since 7.0.0
199
+     */
200
+    public function getAppConfig();
201
+
202
+    /**
203
+     * @return \OCP\L10N\IFactory
204
+     * @since 8.2.0
205
+     */
206
+    public function getL10NFactory();
207
+
208
+    /**
209
+     * get an L10N instance
210
+     * @param string $app appid
211
+     * @param string $lang
212
+     * @return \OCP\IL10N
213
+     * @since 6.0.0 - parameter $lang was added in 8.0.0
214
+     */
215
+    public function getL10N($app, $lang = null);
216
+
217
+    /**
218
+     * @return \OC\Encryption\Manager
219
+     * @since 8.1.0
220
+     */
221
+    public function getEncryptionManager();
222
+
223
+    /**
224
+     * @return \OC\Encryption\File
225
+     * @since 8.1.0
226
+     */
227
+    public function getEncryptionFilesHelper();
228
+
229
+    /**
230
+     * @return \OCP\Encryption\Keys\IStorage
231
+     * @since 8.1.0
232
+     */
233
+    public function getEncryptionKeyStorage();
234
+
235
+    /**
236
+     * Returns the URL generator
237
+     *
238
+     * @return \OCP\IURLGenerator
239
+     * @since 6.0.0
240
+     */
241
+    public function getURLGenerator();
242
+
243
+    /**
244
+     * Returns the Helper
245
+     *
246
+     * @return \OCP\IHelper
247
+     * @since 6.0.0
248
+     */
249
+    public function getHelper();
250
+
251
+    /**
252
+     * Returns an ICache instance
253
+     *
254
+     * @return \OCP\ICache
255
+     * @since 6.0.0
256
+     */
257
+    public function getCache();
258
+
259
+    /**
260
+     * Returns an \OCP\CacheFactory instance
261
+     *
262
+     * @return \OCP\ICacheFactory
263
+     * @since 7.0.0
264
+     */
265
+    public function getMemCacheFactory();
266
+
267
+    /**
268
+     * Returns the current session
269
+     *
270
+     * @return \OCP\ISession
271
+     * @since 6.0.0
272
+     */
273
+    public function getSession();
274
+
275
+    /**
276
+     * Returns the activity manager
277
+     *
278
+     * @return \OCP\Activity\IManager
279
+     * @since 6.0.0
280
+     */
281
+    public function getActivityManager();
282
+
283
+    /**
284
+     * Returns the current session
285
+     *
286
+     * @return \OCP\IDBConnection
287
+     * @since 6.0.0
288
+     */
289
+    public function getDatabaseConnection();
290
+
291
+    /**
292
+     * Returns an avatar manager, used for avatar functionality
293
+     *
294
+     * @return \OCP\IAvatarManager
295
+     * @since 6.0.0
296
+     */
297
+    public function getAvatarManager();
298
+
299
+    /**
300
+     * Returns an job list for controlling background jobs
301
+     *
302
+     * @return \OCP\BackgroundJob\IJobList
303
+     * @since 7.0.0
304
+     */
305
+    public function getJobList();
306
+
307
+    /**
308
+     * Returns a logger instance
309
+     *
310
+     * @return \OCP\ILogger
311
+     * @since 8.0.0
312
+     */
313
+    public function getLogger();
314
+
315
+    /**
316
+     * Returns a router for generating and matching urls
317
+     *
318
+     * @return \OCP\Route\IRouter
319
+     * @since 7.0.0
320
+     */
321
+    public function getRouter();
322
+
323
+    /**
324
+     * Returns a search instance
325
+     *
326
+     * @return \OCP\ISearch
327
+     * @since 7.0.0
328
+     */
329
+    public function getSearch();
330
+
331
+    /**
332
+     * Get the certificate manager for the user
333
+     *
334
+     * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
335
+     * @return \OCP\ICertificateManager | null if $userId is null and no user is logged in
336
+     * @since 8.0.0
337
+     */
338
+    public function getCertificateManager($userId = null);
339
+
340
+    /**
341
+     * Create a new event source
342
+     *
343
+     * @return \OCP\IEventSource
344
+     * @since 8.0.0
345
+     */
346
+    public function createEventSource();
347
+
348
+    /**
349
+     * Returns an instance of the HTTP helper class
350
+     * @return \OC\HTTPHelper
351
+     * @deprecated 8.1.0 Use \OCP\Http\Client\IClientService
352
+     * @since 8.0.0
353
+     */
354
+    public function getHTTPHelper();
355
+
356
+    /**
357
+     * Returns an instance of the HTTP client service
358
+     *
359
+     * @return \OCP\Http\Client\IClientService
360
+     * @since 8.1.0
361
+     */
362
+    public function getHTTPClientService();
363
+
364
+    /**
365
+     * Get the active event logger
366
+     *
367
+     * @return \OCP\Diagnostics\IEventLogger
368
+     * @since 8.0.0
369
+     */
370
+    public function getEventLogger();
371
+
372
+    /**
373
+     * Get the active query logger
374
+     *
375
+     * The returned logger only logs data when debug mode is enabled
376
+     *
377
+     * @return \OCP\Diagnostics\IQueryLogger
378
+     * @since 8.0.0
379
+     */
380
+    public function getQueryLogger();
381
+
382
+    /**
383
+     * Get the manager for temporary files and folders
384
+     *
385
+     * @return \OCP\ITempManager
386
+     * @since 8.0.0
387
+     */
388
+    public function getTempManager();
389
+
390
+    /**
391
+     * Get the app manager
392
+     *
393
+     * @return \OCP\App\IAppManager
394
+     * @since 8.0.0
395
+     */
396
+    public function getAppManager();
397
+
398
+    /**
399
+     * Get the webroot
400
+     *
401
+     * @return string
402
+     * @since 8.0.0
403
+     */
404
+    public function getWebRoot();
405
+
406
+    /**
407
+     * @return \OCP\Files\Config\IMountProviderCollection
408
+     * @since 8.0.0
409
+     */
410
+    public function getMountProviderCollection();
411
+
412
+    /**
413
+     * Get the IniWrapper
414
+     *
415
+     * @return \bantu\IniGetWrapper\IniGetWrapper
416
+     * @since 8.0.0
417
+     */
418
+    public function getIniWrapper();
419
+    /**
420
+     * @return \OCP\Command\IBus
421
+     * @since 8.1.0
422
+     */
423
+    public function getCommandBus();
424
+
425
+    /**
426
+     * Creates a new mailer
427
+     *
428
+     * @return \OCP\Mail\IMailer
429
+     * @since 8.1.0
430
+     */
431
+    public function getMailer();
432
+
433
+    /**
434
+     * Get the locking provider
435
+     *
436
+     * @return \OCP\Lock\ILockingProvider
437
+     * @since 8.1.0
438
+     */
439
+    public function getLockingProvider();
440
+
441
+    /**
442
+     * @return \OCP\Files\Mount\IMountManager
443
+     * @since 8.2.0
444
+     */
445
+    public function getMountManager();
446
+
447
+    /**
448
+     * Get the MimeTypeDetector
449
+     *
450
+     * @return \OCP\Files\IMimeTypeDetector
451
+     * @since 8.2.0
452
+     */
453
+    public function getMimeTypeDetector();
454
+
455
+    /**
456
+     * Get the MimeTypeLoader
457
+     *
458
+     * @return \OCP\Files\IMimeTypeLoader
459
+     * @since 8.2.0
460
+     */
461
+    public function getMimeTypeLoader();
462
+
463
+    /**
464
+     * Get the EventDispatcher
465
+     *
466
+     * @return EventDispatcherInterface
467
+     * @since 8.2.0
468
+     */
469
+    public function getEventDispatcher();
470
+
471
+    /**
472
+     * Get the Notification Manager
473
+     *
474
+     * @return \OCP\Notification\IManager
475
+     * @since 9.0.0
476
+     */
477
+    public function getNotificationManager();
478
+
479
+    /**
480
+     * @return \OCP\Comments\ICommentsManager
481
+     * @since 9.0.0
482
+     */
483
+    public function getCommentsManager();
484
+
485
+    /**
486
+     * Returns the system-tag manager
487
+     *
488
+     * @return \OCP\SystemTag\ISystemTagManager
489
+     *
490
+     * @since 9.0.0
491
+     */
492
+    public function getSystemTagManager();
493
+
494
+    /**
495
+     * Returns the system-tag object mapper
496
+     *
497
+     * @return \OCP\SystemTag\ISystemTagObjectMapper
498
+     *
499
+     * @since 9.0.0
500
+     */
501
+    public function getSystemTagObjectMapper();
502
+
503
+    /**
504
+     * Returns the share manager
505
+     *
506
+     * @return \OCP\Share\IManager
507
+     * @since 9.0.0
508
+     */
509
+    public function getShareManager();
510
+
511
+    /**
512
+     * @return IContentSecurityPolicyManager
513
+     * @since 9.0.0
514
+     */
515
+    public function getContentSecurityPolicyManager();
516
+
517
+    /**
518
+     * @return \OCP\IDateTimeZone
519
+     * @since 8.0.0
520
+     */
521
+    public function getDateTimeZone();
522
+
523
+    /**
524
+     * @return \OCP\IDateTimeFormatter
525
+     * @since 8.0.0
526
+     */
527
+    public function getDateTimeFormatter();
528
+
529
+    /**
530
+     * @return \OCP\Federation\ICloudIdManager
531
+     * @since 12.0.0
532
+     */
533
+    public function getCloudIdManager();
534
+
535
+    /**
536
+     * @return \OCP\Defaults
537
+     * @since 12.0.0
538
+     */
539
+    public function getDefaults();
540 540
 }
Please login to merge, or discard this patch.
lib/public/Defaults.php 1 patch
Indentation   +181 added lines, -181 removed lines patch added patch discarded remove patch
@@ -40,185 +40,185 @@
 block discarded – undo
40 40
  */
41 41
 class Defaults {
42 42
 
43
-	/**
44
-	 * \OC_Defaults instance to retrieve the defaults
45
-	 * @since 6.0.0
46
-	 */
47
-	private $defaults;
48
-
49
-	/**
50
-	 * creates a \OC_Defaults instance which is used in all methods to retrieve the
51
-	 * actual defaults
52
-	 * @since 6.0.0
53
-	 */
54
-	function __construct(\OC_Defaults $defaults = null) {
55
-		if ($defaults === null) {
56
-			$defaults = \OC::$server->getThemingDefaults();
57
-		}
58
-		$this->defaults = $defaults;
59
-	}
60
-
61
-	/**
62
-	 * get base URL for the organisation behind your ownCloud instance
63
-	 * @return string
64
-	 * @since 6.0.0
65
-	 */
66
-	public function getBaseUrl() {
67
-		return $this->defaults->getBaseUrl();
68
-	}
69
-
70
-	/**
71
-	 * link to the desktop sync client
72
-	 * @return string
73
-	 * @since 6.0.0
74
-	 */
75
-	public function getSyncClientUrl() {
76
-		return $this->defaults->getSyncClientUrl();
77
-	}
78
-
79
-	/**
80
-	 * link to the iOS client
81
-	 * @return string
82
-	 * @since 8.0.0
83
-	 */
84
-	public function getiOSClientUrl() {
85
-		return $this->defaults->getiOSClientUrl();
86
-	}
87
-
88
-	/**
89
-	 * link to the Android client
90
-	 * @return string
91
-	 * @since 8.0.0
92
-	 */
93
-	public function getAndroidClientUrl() {
94
-		return $this->defaults->getAndroidClientUrl();
95
-	}
96
-
97
-	/**
98
-	 * base URL to the documentation of your ownCloud instance
99
-	 * @return string
100
-	 * @since 6.0.0
101
-	 */
102
-	public function getDocBaseUrl() {
103
-		return $this->defaults->getDocBaseUrl();
104
-	}
105
-
106
-	/**
107
-	 * name of your ownCloud instance
108
-	 * @return string
109
-	 * @since 6.0.0
110
-	 */
111
-	public function getName() {
112
-		return $this->defaults->getName();
113
-	}
114
-
115
-	/**
116
-	 * name of your ownCloud instance containing HTML styles
117
-	 * @return string
118
-	 * @since 8.0.0
119
-	 */
120
-	public function getHTMLName() {
121
-		return $this->defaults->getHTMLName();
122
-	}
123
-
124
-	/**
125
-	 * Entity behind your onwCloud instance
126
-	 * @return string
127
-	 * @since 6.0.0
128
-	 */
129
-	public function getEntity() {
130
-		return $this->defaults->getEntity();
131
-	}
132
-
133
-	/**
134
-	 * ownCloud slogan
135
-	 * @return string
136
-	 * @since 6.0.0
137
-	 */
138
-	public function getSlogan() {
139
-		return $this->defaults->getSlogan();
140
-	}
141
-
142
-	/**
143
-	 * logo claim
144
-	 * @return string
145
-	 * @since 6.0.0
146
-	 */
147
-	public function getLogoClaim() {
148
-		return $this->defaults->getLogoClaim();
149
-	}
150
-
151
-	/**
152
-	 * footer, short version
153
-	 * @return string
154
-	 * @since 6.0.0
155
-	 */
156
-	public function getShortFooter() {
157
-		return $this->defaults->getShortFooter();
158
-	}
159
-
160
-	/**
161
-	 * footer, long version
162
-	 * @return string
163
-	 * @since 6.0.0
164
-	 */
165
-	public function getLongFooter() {
166
-		return $this->defaults->getLongFooter();
167
-	}
168
-
169
-	/**
170
-	 * Returns the AppId for the App Store for the iOS Client
171
-	 * @return string AppId
172
-	 * @since 8.0.0
173
-	 */
174
-	public function getiTunesAppId() {
175
-		return $this->defaults->getiTunesAppId();
176
-	}
177
-
178
-	/**
179
-	 * Themed logo url
180
-	 *
181
-	 * @return string
182
-	 * @since 12.0.0
183
-	 */
184
-	public function getLogo() {
185
-		return $this->defaults->getLogo();
186
-	}
187
-
188
-	/**
189
-	 * Gets the current cache buster count
190
-	 *
191
-	 * @return string
192
-	 * @since 12.0.0
193
-	 */
194
-	public function getCacheBusterCounter() {
195
-		return $this->defaults->getCacheBusterCounter();
196
-	}
197
-
198
-	/**
199
-	 * Returns primary color
200
-	 * @return string
201
-	 * @since 12.0.0
202
-	 */
203
-	public function getColorPrimary() {
204
-		return $this->defaults->getColorPrimary();
205
-	}
206
-
207
-	/**
208
-	 * @param string $key
209
-	 * @return string URL to doc with key
210
-	 * @since 12.0.0
211
-	 */
212
-	public function buildDocLinkToKey($key) {
213
-		return $this->defaults->buildDocLinkToKey($key);
214
-	}
215
-
216
-	/**
217
-	 * Returns the title
218
-	 * @return string title
219
-	 * @since 12.0.0
220
-	 */
221
-	public function getTitle() {
222
-		return $this->defaults->getTitle();
223
-	}
43
+    /**
44
+     * \OC_Defaults instance to retrieve the defaults
45
+     * @since 6.0.0
46
+     */
47
+    private $defaults;
48
+
49
+    /**
50
+     * creates a \OC_Defaults instance which is used in all methods to retrieve the
51
+     * actual defaults
52
+     * @since 6.0.0
53
+     */
54
+    function __construct(\OC_Defaults $defaults = null) {
55
+        if ($defaults === null) {
56
+            $defaults = \OC::$server->getThemingDefaults();
57
+        }
58
+        $this->defaults = $defaults;
59
+    }
60
+
61
+    /**
62
+     * get base URL for the organisation behind your ownCloud instance
63
+     * @return string
64
+     * @since 6.0.0
65
+     */
66
+    public function getBaseUrl() {
67
+        return $this->defaults->getBaseUrl();
68
+    }
69
+
70
+    /**
71
+     * link to the desktop sync client
72
+     * @return string
73
+     * @since 6.0.0
74
+     */
75
+    public function getSyncClientUrl() {
76
+        return $this->defaults->getSyncClientUrl();
77
+    }
78
+
79
+    /**
80
+     * link to the iOS client
81
+     * @return string
82
+     * @since 8.0.0
83
+     */
84
+    public function getiOSClientUrl() {
85
+        return $this->defaults->getiOSClientUrl();
86
+    }
87
+
88
+    /**
89
+     * link to the Android client
90
+     * @return string
91
+     * @since 8.0.0
92
+     */
93
+    public function getAndroidClientUrl() {
94
+        return $this->defaults->getAndroidClientUrl();
95
+    }
96
+
97
+    /**
98
+     * base URL to the documentation of your ownCloud instance
99
+     * @return string
100
+     * @since 6.0.0
101
+     */
102
+    public function getDocBaseUrl() {
103
+        return $this->defaults->getDocBaseUrl();
104
+    }
105
+
106
+    /**
107
+     * name of your ownCloud instance
108
+     * @return string
109
+     * @since 6.0.0
110
+     */
111
+    public function getName() {
112
+        return $this->defaults->getName();
113
+    }
114
+
115
+    /**
116
+     * name of your ownCloud instance containing HTML styles
117
+     * @return string
118
+     * @since 8.0.0
119
+     */
120
+    public function getHTMLName() {
121
+        return $this->defaults->getHTMLName();
122
+    }
123
+
124
+    /**
125
+     * Entity behind your onwCloud instance
126
+     * @return string
127
+     * @since 6.0.0
128
+     */
129
+    public function getEntity() {
130
+        return $this->defaults->getEntity();
131
+    }
132
+
133
+    /**
134
+     * ownCloud slogan
135
+     * @return string
136
+     * @since 6.0.0
137
+     */
138
+    public function getSlogan() {
139
+        return $this->defaults->getSlogan();
140
+    }
141
+
142
+    /**
143
+     * logo claim
144
+     * @return string
145
+     * @since 6.0.0
146
+     */
147
+    public function getLogoClaim() {
148
+        return $this->defaults->getLogoClaim();
149
+    }
150
+
151
+    /**
152
+     * footer, short version
153
+     * @return string
154
+     * @since 6.0.0
155
+     */
156
+    public function getShortFooter() {
157
+        return $this->defaults->getShortFooter();
158
+    }
159
+
160
+    /**
161
+     * footer, long version
162
+     * @return string
163
+     * @since 6.0.0
164
+     */
165
+    public function getLongFooter() {
166
+        return $this->defaults->getLongFooter();
167
+    }
168
+
169
+    /**
170
+     * Returns the AppId for the App Store for the iOS Client
171
+     * @return string AppId
172
+     * @since 8.0.0
173
+     */
174
+    public function getiTunesAppId() {
175
+        return $this->defaults->getiTunesAppId();
176
+    }
177
+
178
+    /**
179
+     * Themed logo url
180
+     *
181
+     * @return string
182
+     * @since 12.0.0
183
+     */
184
+    public function getLogo() {
185
+        return $this->defaults->getLogo();
186
+    }
187
+
188
+    /**
189
+     * Gets the current cache buster count
190
+     *
191
+     * @return string
192
+     * @since 12.0.0
193
+     */
194
+    public function getCacheBusterCounter() {
195
+        return $this->defaults->getCacheBusterCounter();
196
+    }
197
+
198
+    /**
199
+     * Returns primary color
200
+     * @return string
201
+     * @since 12.0.0
202
+     */
203
+    public function getColorPrimary() {
204
+        return $this->defaults->getColorPrimary();
205
+    }
206
+
207
+    /**
208
+     * @param string $key
209
+     * @return string URL to doc with key
210
+     * @since 12.0.0
211
+     */
212
+    public function buildDocLinkToKey($key) {
213
+        return $this->defaults->buildDocLinkToKey($key);
214
+    }
215
+
216
+    /**
217
+     * Returns the title
218
+     * @return string title
219
+     * @since 12.0.0
220
+     */
221
+    public function getTitle() {
222
+        return $this->defaults->getTitle();
223
+    }
224 224
 }
Please login to merge, or discard this patch.
lib/private/Server.php 2 patches
Indentation   +1595 added lines, -1595 removed lines patch added patch discarded remove patch
@@ -116,1604 +116,1604 @@
 block discarded – undo
116 116
  * TODO: hookup all manager classes
117 117
  */
118 118
 class Server extends ServerContainer implements IServerContainer {
119
-	/** @var string */
120
-	private $webRoot;
121
-
122
-	/**
123
-	 * @param string $webRoot
124
-	 * @param \OC\Config $config
125
-	 */
126
-	public function __construct($webRoot, \OC\Config $config) {
127
-		parent::__construct();
128
-		$this->webRoot = $webRoot;
129
-
130
-		$this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
131
-		$this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
132
-
133
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
134
-			return new PreviewManager(
135
-				$c->getConfig(),
136
-				$c->getRootFolder(),
137
-				$c->getAppDataDir('preview'),
138
-				$c->getEventDispatcher(),
139
-				$c->getSession()->get('user_id')
140
-			);
141
-		});
142
-		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
143
-
144
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
145
-			return new \OC\Preview\Watcher(
146
-				$c->getAppDataDir('preview')
147
-			);
148
-		});
149
-
150
-		$this->registerService('EncryptionManager', function (Server $c) {
151
-			$view = new View();
152
-			$util = new Encryption\Util(
153
-				$view,
154
-				$c->getUserManager(),
155
-				$c->getGroupManager(),
156
-				$c->getConfig()
157
-			);
158
-			return new Encryption\Manager(
159
-				$c->getConfig(),
160
-				$c->getLogger(),
161
-				$c->getL10N('core'),
162
-				new View(),
163
-				$util,
164
-				new ArrayCache()
165
-			);
166
-		});
167
-
168
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
169
-			$util = new Encryption\Util(
170
-				new View(),
171
-				$c->getUserManager(),
172
-				$c->getGroupManager(),
173
-				$c->getConfig()
174
-			);
175
-			return new Encryption\File($util);
176
-		});
177
-
178
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
179
-			$view = new View();
180
-			$util = new Encryption\Util(
181
-				$view,
182
-				$c->getUserManager(),
183
-				$c->getGroupManager(),
184
-				$c->getConfig()
185
-			);
186
-
187
-			return new Encryption\Keys\Storage($view, $util);
188
-		});
189
-		$this->registerService('TagMapper', function (Server $c) {
190
-			return new TagMapper($c->getDatabaseConnection());
191
-		});
192
-
193
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
194
-			$tagMapper = $c->query('TagMapper');
195
-			return new TagManager($tagMapper, $c->getUserSession());
196
-		});
197
-		$this->registerAlias('TagManager', \OCP\ITagManager::class);
198
-
199
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
200
-			$config = $c->getConfig();
201
-			$factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
202
-			/** @var \OC\SystemTag\ManagerFactory $factory */
203
-			$factory = new $factoryClass($this);
204
-			return $factory;
205
-		});
206
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
207
-			return $c->query('SystemTagManagerFactory')->getManager();
208
-		});
209
-		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
210
-
211
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
212
-			return $c->query('SystemTagManagerFactory')->getObjectMapper();
213
-		});
214
-		$this->registerService('RootFolder', function (Server $c) {
215
-			$manager = \OC\Files\Filesystem::getMountManager(null);
216
-			$view = new View();
217
-			$root = new Root(
218
-				$manager,
219
-				$view,
220
-				null,
221
-				$c->getUserMountCache(),
222
-				$this->getLogger(),
223
-				$this->getUserManager()
224
-			);
225
-			$connector = new HookConnector($root, $view);
226
-			$connector->viewToNode();
227
-
228
-			$previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
229
-			$previewConnector->connectWatcher();
230
-
231
-			return $root;
232
-		});
233
-		$this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
234
-
235
-		$this->registerService(\OCP\Files\IRootFolder::class, function(Server $c) {
236
-			return new LazyRoot(function() use ($c) {
237
-				return $c->query('RootFolder');
238
-			});
239
-		});
240
-		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
241
-
242
-		$this->registerService(\OCP\IUserManager::class, function (Server $c) {
243
-			$config = $c->getConfig();
244
-			return new \OC\User\Manager($config);
245
-		});
246
-		$this->registerAlias('UserManager', \OCP\IUserManager::class);
247
-
248
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
249
-			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
250
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
251
-				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
252
-			});
253
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
254
-				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
255
-			});
256
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
257
-				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
258
-			});
259
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
260
-				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
261
-			});
262
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
263
-				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
264
-			});
265
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
266
-				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
267
-				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
268
-				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
269
-			});
270
-			return $groupManager;
271
-		});
272
-		$this->registerAlias('GroupManager', \OCP\IGroupManager::class);
273
-
274
-		$this->registerService(Store::class, function(Server $c) {
275
-			$session = $c->getSession();
276
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
277
-				$tokenProvider = $c->query('OC\Authentication\Token\IProvider');
278
-			} else {
279
-				$tokenProvider = null;
280
-			}
281
-			$logger = $c->getLogger();
282
-			return new Store($session, $logger, $tokenProvider);
283
-		});
284
-		$this->registerAlias(IStore::class, Store::class);
285
-		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
286
-			$dbConnection = $c->getDatabaseConnection();
287
-			return new Authentication\Token\DefaultTokenMapper($dbConnection);
288
-		});
289
-		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
290
-			$mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
291
-			$crypto = $c->getCrypto();
292
-			$config = $c->getConfig();
293
-			$logger = $c->getLogger();
294
-			$timeFactory = new TimeFactory();
295
-			return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
296
-		});
297
-		$this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
298
-
299
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
300
-			$manager = $c->getUserManager();
301
-			$session = new \OC\Session\Memory('');
302
-			$timeFactory = new TimeFactory();
303
-			// Token providers might require a working database. This code
304
-			// might however be called when ownCloud is not yet setup.
305
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
306
-				$defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
307
-			} else {
308
-				$defaultTokenProvider = null;
309
-			}
310
-
311
-			$userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom(), $c->getLockdownManager());
312
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
313
-				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
314
-			});
315
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
316
-				/** @var $user \OC\User\User */
317
-				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
318
-			});
319
-			$userSession->listen('\OC\User', 'preDelete', function ($user) {
320
-				/** @var $user \OC\User\User */
321
-				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
322
-			});
323
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
324
-				/** @var $user \OC\User\User */
325
-				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
326
-			});
327
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
328
-				/** @var $user \OC\User\User */
329
-				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
330
-			});
331
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
332
-				/** @var $user \OC\User\User */
333
-				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
334
-			});
335
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
336
-				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
337
-			});
338
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
339
-				/** @var $user \OC\User\User */
340
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
341
-			});
342
-			$userSession->listen('\OC\User', 'logout', function () {
343
-				\OC_Hook::emit('OC_User', 'logout', array());
344
-			});
345
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value) {
346
-				/** @var $user \OC\User\User */
347
-				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value));
348
-			});
349
-			return $userSession;
350
-		});
351
-		$this->registerAlias('UserSession', \OCP\IUserSession::class);
352
-
353
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
354
-			return new \OC\Authentication\TwoFactorAuth\Manager($c->getAppManager(), $c->getSession(), $c->getConfig(), $c->getActivityManager(), $c->getLogger());
355
-		});
356
-
357
-		$this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
358
-		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
359
-
360
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
361
-			return new \OC\AllConfig(
362
-				$c->getSystemConfig()
363
-			);
364
-		});
365
-		$this->registerAlias('AllConfig', \OC\AllConfig::class);
366
-		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
367
-
368
-		$this->registerService('SystemConfig', function ($c) use ($config) {
369
-			return new \OC\SystemConfig($config);
370
-		});
371
-
372
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
373
-			return new \OC\AppConfig($c->getDatabaseConnection());
374
-		});
375
-		$this->registerAlias('AppConfig', \OC\AppConfig::class);
376
-		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
377
-
378
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
379
-			return new \OC\L10N\Factory(
380
-				$c->getConfig(),
381
-				$c->getRequest(),
382
-				$c->getUserSession(),
383
-				\OC::$SERVERROOT
384
-			);
385
-		});
386
-		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
387
-
388
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
389
-			$config = $c->getConfig();
390
-			$cacheFactory = $c->getMemCacheFactory();
391
-			return new \OC\URLGenerator(
392
-				$config,
393
-				$cacheFactory
394
-			);
395
-		});
396
-		$this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
397
-
398
-		$this->registerService('AppHelper', function ($c) {
399
-			return new \OC\AppHelper();
400
-		});
401
-		$this->registerService('AppFetcher', function ($c) {
402
-			return new AppFetcher(
403
-				$this->getAppDataDir('appstore'),
404
-				$this->getHTTPClientService(),
405
-				$this->query(TimeFactory::class),
406
-				$this->getConfig()
407
-			);
408
-		});
409
-		$this->registerService('CategoryFetcher', function ($c) {
410
-			return new CategoryFetcher(
411
-				$this->getAppDataDir('appstore'),
412
-				$this->getHTTPClientService(),
413
-				$this->query(TimeFactory::class),
414
-				$this->getConfig()
415
-			);
416
-		});
417
-
418
-		$this->registerService(\OCP\ICache::class, function ($c) {
419
-			return new Cache\File();
420
-		});
421
-		$this->registerAlias('UserCache', \OCP\ICache::class);
422
-
423
-		$this->registerService(Factory::class, function (Server $c) {
424
-			$config = $c->getConfig();
425
-
426
-			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
427
-				$v = \OC_App::getAppVersions();
428
-				$v['core'] = md5(file_get_contents(\OC::$SERVERROOT . '/version.php'));
429
-				$version = implode(',', $v);
430
-				$instanceId = \OC_Util::getInstanceId();
431
-				$path = \OC::$SERVERROOT;
432
-				$prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . \OC::$WEBROOT);
433
-				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
434
-					$config->getSystemValue('memcache.local', null),
435
-					$config->getSystemValue('memcache.distributed', null),
436
-					$config->getSystemValue('memcache.locking', null)
437
-				);
438
-			}
439
-
440
-			return new \OC\Memcache\Factory('', $c->getLogger(),
441
-				'\\OC\\Memcache\\ArrayCache',
442
-				'\\OC\\Memcache\\ArrayCache',
443
-				'\\OC\\Memcache\\ArrayCache'
444
-			);
445
-		});
446
-		$this->registerAlias('MemCacheFactory', Factory::class);
447
-		$this->registerAlias(ICacheFactory::class, Factory::class);
448
-
449
-		$this->registerService('RedisFactory', function (Server $c) {
450
-			$systemConfig = $c->getSystemConfig();
451
-			return new RedisFactory($systemConfig);
452
-		});
453
-
454
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
455
-			return new \OC\Activity\Manager(
456
-				$c->getRequest(),
457
-				$c->getUserSession(),
458
-				$c->getConfig(),
459
-				$c->query(IValidator::class)
460
-			);
461
-		});
462
-		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
463
-
464
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
465
-			return new \OC\Activity\EventMerger(
466
-				$c->getL10N('lib')
467
-			);
468
-		});
469
-		$this->registerAlias(IValidator::class, Validator::class);
470
-
471
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
472
-			return new AvatarManager(
473
-				$c->getUserManager(),
474
-				$c->getAppDataDir('avatar'),
475
-				$c->getL10N('lib'),
476
-				$c->getLogger(),
477
-				$c->getConfig()
478
-			);
479
-		});
480
-		$this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
481
-
482
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
483
-			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
484
-			$logger = Log::getLogClass($logType);
485
-			call_user_func(array($logger, 'init'));
486
-
487
-			return new Log($logger);
488
-		});
489
-		$this->registerAlias('Logger', \OCP\ILogger::class);
490
-
491
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
492
-			$config = $c->getConfig();
493
-			return new \OC\BackgroundJob\JobList(
494
-				$c->getDatabaseConnection(),
495
-				$config,
496
-				new TimeFactory()
497
-			);
498
-		});
499
-		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
500
-
501
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
502
-			$cacheFactory = $c->getMemCacheFactory();
503
-			$logger = $c->getLogger();
504
-			if ($cacheFactory->isAvailable()) {
505
-				$router = new \OC\Route\CachingRouter($cacheFactory->create('route'), $logger);
506
-			} else {
507
-				$router = new \OC\Route\Router($logger);
508
-			}
509
-			return $router;
510
-		});
511
-		$this->registerAlias('Router', \OCP\Route\IRouter::class);
512
-
513
-		$this->registerService(\OCP\ISearch::class, function ($c) {
514
-			return new Search();
515
-		});
516
-		$this->registerAlias('Search', \OCP\ISearch::class);
517
-
518
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
519
-			return new SecureRandom();
520
-		});
521
-		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
522
-
523
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
524
-			return new Crypto($c->getConfig(), $c->getSecureRandom());
525
-		});
526
-		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
527
-
528
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
529
-			return new Hasher($c->getConfig());
530
-		});
531
-		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
532
-
533
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
534
-			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
535
-		});
536
-		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
537
-
538
-		$this->registerService(IDBConnection::class, function (Server $c) {
539
-			$systemConfig = $c->getSystemConfig();
540
-			$factory = new \OC\DB\ConnectionFactory($systemConfig);
541
-			$type = $systemConfig->getValue('dbtype', 'sqlite');
542
-			if (!$factory->isValidType($type)) {
543
-				throw new \OC\DatabaseException('Invalid database type');
544
-			}
545
-			$connectionParams = $factory->createConnectionParams();
546
-			$connection = $factory->getConnection($type, $connectionParams);
547
-			$connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
548
-			return $connection;
549
-		});
550
-		$this->registerAlias('DatabaseConnection', IDBConnection::class);
551
-
552
-		$this->registerService('HTTPHelper', function (Server $c) {
553
-			$config = $c->getConfig();
554
-			return new HTTPHelper(
555
-				$config,
556
-				$c->getHTTPClientService()
557
-			);
558
-		});
559
-
560
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
561
-			$user = \OC_User::getUser();
562
-			$uid = $user ? $user : null;
563
-			return new ClientService(
564
-				$c->getConfig(),
565
-				new \OC\Security\CertificateManager($uid, new View(), $c->getConfig(), $c->getLogger())
566
-			);
567
-		});
568
-		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
569
-
570
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
571
-			if ($c->getSystemConfig()->getValue('debug', false)) {
572
-				return new EventLogger();
573
-			} else {
574
-				return new NullEventLogger();
575
-			}
576
-		});
577
-		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
578
-
579
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
580
-			if ($c->getSystemConfig()->getValue('debug', false)) {
581
-				return new QueryLogger();
582
-			} else {
583
-				return new NullQueryLogger();
584
-			}
585
-		});
586
-		$this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
587
-
588
-		$this->registerService(TempManager::class, function (Server $c) {
589
-			return new TempManager(
590
-				$c->getLogger(),
591
-				$c->getConfig()
592
-			);
593
-		});
594
-		$this->registerAlias('TempManager', TempManager::class);
595
-		$this->registerAlias(ITempManager::class, TempManager::class);
596
-
597
-		$this->registerService(AppManager::class, function (Server $c) {
598
-			return new \OC\App\AppManager(
599
-				$c->getUserSession(),
600
-				$c->getAppConfig(),
601
-				$c->getGroupManager(),
602
-				$c->getMemCacheFactory(),
603
-				$c->getEventDispatcher()
604
-			);
605
-		});
606
-		$this->registerAlias('AppManager', AppManager::class);
607
-		$this->registerAlias(IAppManager::class, AppManager::class);
608
-
609
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
610
-			return new DateTimeZone(
611
-				$c->getConfig(),
612
-				$c->getSession()
613
-			);
614
-		});
615
-		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
616
-
617
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
618
-			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
619
-
620
-			return new DateTimeFormatter(
621
-				$c->getDateTimeZone()->getTimeZone(),
622
-				$c->getL10N('lib', $language)
623
-			);
624
-		});
625
-		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
626
-
627
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
628
-			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
629
-			$listener = new UserMountCacheListener($mountCache);
630
-			$listener->listen($c->getUserManager());
631
-			return $mountCache;
632
-		});
633
-		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
634
-
635
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
636
-			$loader = \OC\Files\Filesystem::getLoader();
637
-			$mountCache = $c->query('UserMountCache');
638
-			$manager =  new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
639
-
640
-			// builtin providers
641
-
642
-			$config = $c->getConfig();
643
-			$manager->registerProvider(new CacheMountProvider($config));
644
-			$manager->registerHomeProvider(new LocalHomeMountProvider());
645
-			$manager->registerHomeProvider(new ObjectHomeMountProvider($config));
646
-
647
-			return $manager;
648
-		});
649
-		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
650
-
651
-		$this->registerService('IniWrapper', function ($c) {
652
-			return new IniGetWrapper();
653
-		});
654
-		$this->registerService('AsyncCommandBus', function (Server $c) {
655
-			$jobList = $c->getJobList();
656
-			return new AsyncBus($jobList);
657
-		});
658
-		$this->registerService('TrustedDomainHelper', function ($c) {
659
-			return new TrustedDomainHelper($this->getConfig());
660
-		});
661
-		$this->registerService('Throttler', function(Server $c) {
662
-			return new Throttler(
663
-				$c->getDatabaseConnection(),
664
-				new TimeFactory(),
665
-				$c->getLogger(),
666
-				$c->getConfig()
667
-			);
668
-		});
669
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
670
-			// IConfig and IAppManager requires a working database. This code
671
-			// might however be called when ownCloud is not yet setup.
672
-			if(\OC::$server->getSystemConfig()->getValue('installed', false)) {
673
-				$config = $c->getConfig();
674
-				$appManager = $c->getAppManager();
675
-			} else {
676
-				$config = null;
677
-				$appManager = null;
678
-			}
679
-
680
-			return new Checker(
681
-					new EnvironmentHelper(),
682
-					new FileAccessHelper(),
683
-					new AppLocator(),
684
-					$config,
685
-					$c->getMemCacheFactory(),
686
-					$appManager,
687
-					$c->getTempManager()
688
-			);
689
-		});
690
-		$this->registerService(\OCP\IRequest::class, function ($c) {
691
-			if (isset($this['urlParams'])) {
692
-				$urlParams = $this['urlParams'];
693
-			} else {
694
-				$urlParams = [];
695
-			}
696
-
697
-			if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
698
-				&& in_array('fakeinput', stream_get_wrappers())
699
-			) {
700
-				$stream = 'fakeinput://data';
701
-			} else {
702
-				$stream = 'php://input';
703
-			}
704
-
705
-			return new Request(
706
-				[
707
-					'get' => $_GET,
708
-					'post' => $_POST,
709
-					'files' => $_FILES,
710
-					'server' => $_SERVER,
711
-					'env' => $_ENV,
712
-					'cookies' => $_COOKIE,
713
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
714
-						? $_SERVER['REQUEST_METHOD']
715
-						: null,
716
-					'urlParams' => $urlParams,
717
-				],
718
-				$this->getSecureRandom(),
719
-				$this->getConfig(),
720
-				$this->getCsrfTokenManager(),
721
-				$stream
722
-			);
723
-		});
724
-		$this->registerAlias('Request', \OCP\IRequest::class);
725
-
726
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
727
-			return new Mailer(
728
-				$c->getConfig(),
729
-				$c->getLogger(),
730
-				$c->getDefaults()
731
-			);
732
-		});
733
-		$this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
734
-
735
-		$this->registerService('LDAPProvider', function(Server $c) {
736
-			$config = $c->getConfig();
737
-			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
738
-			if(is_null($factoryClass)) {
739
-				throw new \Exception('ldapProviderFactory not set');
740
-			}
741
-			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
742
-			$factory = new $factoryClass($this);
743
-			return $factory->getLDAPProvider();
744
-		});
745
-		$this->registerService('LockingProvider', function (Server $c) {
746
-			$ini = $c->getIniWrapper();
747
-			$config = $c->getConfig();
748
-			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
749
-			if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
750
-				/** @var \OC\Memcache\Factory $memcacheFactory */
751
-				$memcacheFactory = $c->getMemCacheFactory();
752
-				$memcache = $memcacheFactory->createLocking('lock');
753
-				if (!($memcache instanceof \OC\Memcache\NullCache)) {
754
-					return new MemcacheLockingProvider($memcache, $ttl);
755
-				}
756
-				return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
757
-			}
758
-			return new NoopLockingProvider();
759
-		});
760
-
761
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
762
-			return new \OC\Files\Mount\Manager();
763
-		});
764
-		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
765
-
766
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
767
-			return new \OC\Files\Type\Detection(
768
-				$c->getURLGenerator(),
769
-				\OC::$configDir,
770
-				\OC::$SERVERROOT . '/resources/config/'
771
-			);
772
-		});
773
-		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
774
-
775
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
776
-			return new \OC\Files\Type\Loader(
777
-				$c->getDatabaseConnection()
778
-			);
779
-		});
780
-		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
781
-
782
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
783
-			return new Manager(
784
-				$c->query(IValidator::class)
785
-			);
786
-		});
787
-		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
788
-
789
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
790
-			$manager = new \OC\CapabilitiesManager($c->getLogger());
791
-			$manager->registerCapability(function () use ($c) {
792
-				return new \OC\OCS\CoreCapabilities($c->getConfig());
793
-			});
794
-			return $manager;
795
-		});
796
-		$this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
797
-
798
-		$this->registerService(\OCP\Comments\ICommentsManager::class, function(Server $c) {
799
-			$config = $c->getConfig();
800
-			$factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
801
-			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
802
-			$factory = new $factoryClass($this);
803
-			return $factory->getManager();
804
-		});
805
-		$this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
806
-
807
-		$this->registerService('ThemingDefaults', function(Server $c) {
808
-			/*
119
+    /** @var string */
120
+    private $webRoot;
121
+
122
+    /**
123
+     * @param string $webRoot
124
+     * @param \OC\Config $config
125
+     */
126
+    public function __construct($webRoot, \OC\Config $config) {
127
+        parent::__construct();
128
+        $this->webRoot = $webRoot;
129
+
130
+        $this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
131
+        $this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
132
+
133
+        $this->registerService(\OCP\IPreview::class, function (Server $c) {
134
+            return new PreviewManager(
135
+                $c->getConfig(),
136
+                $c->getRootFolder(),
137
+                $c->getAppDataDir('preview'),
138
+                $c->getEventDispatcher(),
139
+                $c->getSession()->get('user_id')
140
+            );
141
+        });
142
+        $this->registerAlias('PreviewManager', \OCP\IPreview::class);
143
+
144
+        $this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
145
+            return new \OC\Preview\Watcher(
146
+                $c->getAppDataDir('preview')
147
+            );
148
+        });
149
+
150
+        $this->registerService('EncryptionManager', function (Server $c) {
151
+            $view = new View();
152
+            $util = new Encryption\Util(
153
+                $view,
154
+                $c->getUserManager(),
155
+                $c->getGroupManager(),
156
+                $c->getConfig()
157
+            );
158
+            return new Encryption\Manager(
159
+                $c->getConfig(),
160
+                $c->getLogger(),
161
+                $c->getL10N('core'),
162
+                new View(),
163
+                $util,
164
+                new ArrayCache()
165
+            );
166
+        });
167
+
168
+        $this->registerService('EncryptionFileHelper', function (Server $c) {
169
+            $util = new Encryption\Util(
170
+                new View(),
171
+                $c->getUserManager(),
172
+                $c->getGroupManager(),
173
+                $c->getConfig()
174
+            );
175
+            return new Encryption\File($util);
176
+        });
177
+
178
+        $this->registerService('EncryptionKeyStorage', function (Server $c) {
179
+            $view = new View();
180
+            $util = new Encryption\Util(
181
+                $view,
182
+                $c->getUserManager(),
183
+                $c->getGroupManager(),
184
+                $c->getConfig()
185
+            );
186
+
187
+            return new Encryption\Keys\Storage($view, $util);
188
+        });
189
+        $this->registerService('TagMapper', function (Server $c) {
190
+            return new TagMapper($c->getDatabaseConnection());
191
+        });
192
+
193
+        $this->registerService(\OCP\ITagManager::class, function (Server $c) {
194
+            $tagMapper = $c->query('TagMapper');
195
+            return new TagManager($tagMapper, $c->getUserSession());
196
+        });
197
+        $this->registerAlias('TagManager', \OCP\ITagManager::class);
198
+
199
+        $this->registerService('SystemTagManagerFactory', function (Server $c) {
200
+            $config = $c->getConfig();
201
+            $factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
202
+            /** @var \OC\SystemTag\ManagerFactory $factory */
203
+            $factory = new $factoryClass($this);
204
+            return $factory;
205
+        });
206
+        $this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
207
+            return $c->query('SystemTagManagerFactory')->getManager();
208
+        });
209
+        $this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
210
+
211
+        $this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
212
+            return $c->query('SystemTagManagerFactory')->getObjectMapper();
213
+        });
214
+        $this->registerService('RootFolder', function (Server $c) {
215
+            $manager = \OC\Files\Filesystem::getMountManager(null);
216
+            $view = new View();
217
+            $root = new Root(
218
+                $manager,
219
+                $view,
220
+                null,
221
+                $c->getUserMountCache(),
222
+                $this->getLogger(),
223
+                $this->getUserManager()
224
+            );
225
+            $connector = new HookConnector($root, $view);
226
+            $connector->viewToNode();
227
+
228
+            $previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
229
+            $previewConnector->connectWatcher();
230
+
231
+            return $root;
232
+        });
233
+        $this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
234
+
235
+        $this->registerService(\OCP\Files\IRootFolder::class, function(Server $c) {
236
+            return new LazyRoot(function() use ($c) {
237
+                return $c->query('RootFolder');
238
+            });
239
+        });
240
+        $this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
241
+
242
+        $this->registerService(\OCP\IUserManager::class, function (Server $c) {
243
+            $config = $c->getConfig();
244
+            return new \OC\User\Manager($config);
245
+        });
246
+        $this->registerAlias('UserManager', \OCP\IUserManager::class);
247
+
248
+        $this->registerService(\OCP\IGroupManager::class, function (Server $c) {
249
+            $groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
250
+            $groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
251
+                \OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
252
+            });
253
+            $groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
254
+                \OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
255
+            });
256
+            $groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
257
+                \OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
258
+            });
259
+            $groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
260
+                \OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
261
+            });
262
+            $groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
263
+                \OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
264
+            });
265
+            $groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
266
+                \OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
267
+                //Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
268
+                \OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
269
+            });
270
+            return $groupManager;
271
+        });
272
+        $this->registerAlias('GroupManager', \OCP\IGroupManager::class);
273
+
274
+        $this->registerService(Store::class, function(Server $c) {
275
+            $session = $c->getSession();
276
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
277
+                $tokenProvider = $c->query('OC\Authentication\Token\IProvider');
278
+            } else {
279
+                $tokenProvider = null;
280
+            }
281
+            $logger = $c->getLogger();
282
+            return new Store($session, $logger, $tokenProvider);
283
+        });
284
+        $this->registerAlias(IStore::class, Store::class);
285
+        $this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
286
+            $dbConnection = $c->getDatabaseConnection();
287
+            return new Authentication\Token\DefaultTokenMapper($dbConnection);
288
+        });
289
+        $this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
290
+            $mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
291
+            $crypto = $c->getCrypto();
292
+            $config = $c->getConfig();
293
+            $logger = $c->getLogger();
294
+            $timeFactory = new TimeFactory();
295
+            return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
296
+        });
297
+        $this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
298
+
299
+        $this->registerService(\OCP\IUserSession::class, function (Server $c) {
300
+            $manager = $c->getUserManager();
301
+            $session = new \OC\Session\Memory('');
302
+            $timeFactory = new TimeFactory();
303
+            // Token providers might require a working database. This code
304
+            // might however be called when ownCloud is not yet setup.
305
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
306
+                $defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
307
+            } else {
308
+                $defaultTokenProvider = null;
309
+            }
310
+
311
+            $userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom(), $c->getLockdownManager());
312
+            $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
313
+                \OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
314
+            });
315
+            $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
316
+                /** @var $user \OC\User\User */
317
+                \OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
318
+            });
319
+            $userSession->listen('\OC\User', 'preDelete', function ($user) {
320
+                /** @var $user \OC\User\User */
321
+                \OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
322
+            });
323
+            $userSession->listen('\OC\User', 'postDelete', function ($user) {
324
+                /** @var $user \OC\User\User */
325
+                \OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
326
+            });
327
+            $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
328
+                /** @var $user \OC\User\User */
329
+                \OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
330
+            });
331
+            $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
332
+                /** @var $user \OC\User\User */
333
+                \OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
334
+            });
335
+            $userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
336
+                \OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
337
+            });
338
+            $userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
339
+                /** @var $user \OC\User\User */
340
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
341
+            });
342
+            $userSession->listen('\OC\User', 'logout', function () {
343
+                \OC_Hook::emit('OC_User', 'logout', array());
344
+            });
345
+            $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value) {
346
+                /** @var $user \OC\User\User */
347
+                \OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value));
348
+            });
349
+            return $userSession;
350
+        });
351
+        $this->registerAlias('UserSession', \OCP\IUserSession::class);
352
+
353
+        $this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
354
+            return new \OC\Authentication\TwoFactorAuth\Manager($c->getAppManager(), $c->getSession(), $c->getConfig(), $c->getActivityManager(), $c->getLogger());
355
+        });
356
+
357
+        $this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
358
+        $this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
359
+
360
+        $this->registerService(\OC\AllConfig::class, function (Server $c) {
361
+            return new \OC\AllConfig(
362
+                $c->getSystemConfig()
363
+            );
364
+        });
365
+        $this->registerAlias('AllConfig', \OC\AllConfig::class);
366
+        $this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
367
+
368
+        $this->registerService('SystemConfig', function ($c) use ($config) {
369
+            return new \OC\SystemConfig($config);
370
+        });
371
+
372
+        $this->registerService(\OC\AppConfig::class, function (Server $c) {
373
+            return new \OC\AppConfig($c->getDatabaseConnection());
374
+        });
375
+        $this->registerAlias('AppConfig', \OC\AppConfig::class);
376
+        $this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
377
+
378
+        $this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
379
+            return new \OC\L10N\Factory(
380
+                $c->getConfig(),
381
+                $c->getRequest(),
382
+                $c->getUserSession(),
383
+                \OC::$SERVERROOT
384
+            );
385
+        });
386
+        $this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
387
+
388
+        $this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
389
+            $config = $c->getConfig();
390
+            $cacheFactory = $c->getMemCacheFactory();
391
+            return new \OC\URLGenerator(
392
+                $config,
393
+                $cacheFactory
394
+            );
395
+        });
396
+        $this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
397
+
398
+        $this->registerService('AppHelper', function ($c) {
399
+            return new \OC\AppHelper();
400
+        });
401
+        $this->registerService('AppFetcher', function ($c) {
402
+            return new AppFetcher(
403
+                $this->getAppDataDir('appstore'),
404
+                $this->getHTTPClientService(),
405
+                $this->query(TimeFactory::class),
406
+                $this->getConfig()
407
+            );
408
+        });
409
+        $this->registerService('CategoryFetcher', function ($c) {
410
+            return new CategoryFetcher(
411
+                $this->getAppDataDir('appstore'),
412
+                $this->getHTTPClientService(),
413
+                $this->query(TimeFactory::class),
414
+                $this->getConfig()
415
+            );
416
+        });
417
+
418
+        $this->registerService(\OCP\ICache::class, function ($c) {
419
+            return new Cache\File();
420
+        });
421
+        $this->registerAlias('UserCache', \OCP\ICache::class);
422
+
423
+        $this->registerService(Factory::class, function (Server $c) {
424
+            $config = $c->getConfig();
425
+
426
+            if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
427
+                $v = \OC_App::getAppVersions();
428
+                $v['core'] = md5(file_get_contents(\OC::$SERVERROOT . '/version.php'));
429
+                $version = implode(',', $v);
430
+                $instanceId = \OC_Util::getInstanceId();
431
+                $path = \OC::$SERVERROOT;
432
+                $prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . \OC::$WEBROOT);
433
+                return new \OC\Memcache\Factory($prefix, $c->getLogger(),
434
+                    $config->getSystemValue('memcache.local', null),
435
+                    $config->getSystemValue('memcache.distributed', null),
436
+                    $config->getSystemValue('memcache.locking', null)
437
+                );
438
+            }
439
+
440
+            return new \OC\Memcache\Factory('', $c->getLogger(),
441
+                '\\OC\\Memcache\\ArrayCache',
442
+                '\\OC\\Memcache\\ArrayCache',
443
+                '\\OC\\Memcache\\ArrayCache'
444
+            );
445
+        });
446
+        $this->registerAlias('MemCacheFactory', Factory::class);
447
+        $this->registerAlias(ICacheFactory::class, Factory::class);
448
+
449
+        $this->registerService('RedisFactory', function (Server $c) {
450
+            $systemConfig = $c->getSystemConfig();
451
+            return new RedisFactory($systemConfig);
452
+        });
453
+
454
+        $this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
455
+            return new \OC\Activity\Manager(
456
+                $c->getRequest(),
457
+                $c->getUserSession(),
458
+                $c->getConfig(),
459
+                $c->query(IValidator::class)
460
+            );
461
+        });
462
+        $this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
463
+
464
+        $this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
465
+            return new \OC\Activity\EventMerger(
466
+                $c->getL10N('lib')
467
+            );
468
+        });
469
+        $this->registerAlias(IValidator::class, Validator::class);
470
+
471
+        $this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
472
+            return new AvatarManager(
473
+                $c->getUserManager(),
474
+                $c->getAppDataDir('avatar'),
475
+                $c->getL10N('lib'),
476
+                $c->getLogger(),
477
+                $c->getConfig()
478
+            );
479
+        });
480
+        $this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
481
+
482
+        $this->registerService(\OCP\ILogger::class, function (Server $c) {
483
+            $logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
484
+            $logger = Log::getLogClass($logType);
485
+            call_user_func(array($logger, 'init'));
486
+
487
+            return new Log($logger);
488
+        });
489
+        $this->registerAlias('Logger', \OCP\ILogger::class);
490
+
491
+        $this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
492
+            $config = $c->getConfig();
493
+            return new \OC\BackgroundJob\JobList(
494
+                $c->getDatabaseConnection(),
495
+                $config,
496
+                new TimeFactory()
497
+            );
498
+        });
499
+        $this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
500
+
501
+        $this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
502
+            $cacheFactory = $c->getMemCacheFactory();
503
+            $logger = $c->getLogger();
504
+            if ($cacheFactory->isAvailable()) {
505
+                $router = new \OC\Route\CachingRouter($cacheFactory->create('route'), $logger);
506
+            } else {
507
+                $router = new \OC\Route\Router($logger);
508
+            }
509
+            return $router;
510
+        });
511
+        $this->registerAlias('Router', \OCP\Route\IRouter::class);
512
+
513
+        $this->registerService(\OCP\ISearch::class, function ($c) {
514
+            return new Search();
515
+        });
516
+        $this->registerAlias('Search', \OCP\ISearch::class);
517
+
518
+        $this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
519
+            return new SecureRandom();
520
+        });
521
+        $this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
522
+
523
+        $this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
524
+            return new Crypto($c->getConfig(), $c->getSecureRandom());
525
+        });
526
+        $this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
527
+
528
+        $this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
529
+            return new Hasher($c->getConfig());
530
+        });
531
+        $this->registerAlias('Hasher', \OCP\Security\IHasher::class);
532
+
533
+        $this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
534
+            return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
535
+        });
536
+        $this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
537
+
538
+        $this->registerService(IDBConnection::class, function (Server $c) {
539
+            $systemConfig = $c->getSystemConfig();
540
+            $factory = new \OC\DB\ConnectionFactory($systemConfig);
541
+            $type = $systemConfig->getValue('dbtype', 'sqlite');
542
+            if (!$factory->isValidType($type)) {
543
+                throw new \OC\DatabaseException('Invalid database type');
544
+            }
545
+            $connectionParams = $factory->createConnectionParams();
546
+            $connection = $factory->getConnection($type, $connectionParams);
547
+            $connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
548
+            return $connection;
549
+        });
550
+        $this->registerAlias('DatabaseConnection', IDBConnection::class);
551
+
552
+        $this->registerService('HTTPHelper', function (Server $c) {
553
+            $config = $c->getConfig();
554
+            return new HTTPHelper(
555
+                $config,
556
+                $c->getHTTPClientService()
557
+            );
558
+        });
559
+
560
+        $this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
561
+            $user = \OC_User::getUser();
562
+            $uid = $user ? $user : null;
563
+            return new ClientService(
564
+                $c->getConfig(),
565
+                new \OC\Security\CertificateManager($uid, new View(), $c->getConfig(), $c->getLogger())
566
+            );
567
+        });
568
+        $this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
569
+
570
+        $this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
571
+            if ($c->getSystemConfig()->getValue('debug', false)) {
572
+                return new EventLogger();
573
+            } else {
574
+                return new NullEventLogger();
575
+            }
576
+        });
577
+        $this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
578
+
579
+        $this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
580
+            if ($c->getSystemConfig()->getValue('debug', false)) {
581
+                return new QueryLogger();
582
+            } else {
583
+                return new NullQueryLogger();
584
+            }
585
+        });
586
+        $this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
587
+
588
+        $this->registerService(TempManager::class, function (Server $c) {
589
+            return new TempManager(
590
+                $c->getLogger(),
591
+                $c->getConfig()
592
+            );
593
+        });
594
+        $this->registerAlias('TempManager', TempManager::class);
595
+        $this->registerAlias(ITempManager::class, TempManager::class);
596
+
597
+        $this->registerService(AppManager::class, function (Server $c) {
598
+            return new \OC\App\AppManager(
599
+                $c->getUserSession(),
600
+                $c->getAppConfig(),
601
+                $c->getGroupManager(),
602
+                $c->getMemCacheFactory(),
603
+                $c->getEventDispatcher()
604
+            );
605
+        });
606
+        $this->registerAlias('AppManager', AppManager::class);
607
+        $this->registerAlias(IAppManager::class, AppManager::class);
608
+
609
+        $this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
610
+            return new DateTimeZone(
611
+                $c->getConfig(),
612
+                $c->getSession()
613
+            );
614
+        });
615
+        $this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
616
+
617
+        $this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
618
+            $language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
619
+
620
+            return new DateTimeFormatter(
621
+                $c->getDateTimeZone()->getTimeZone(),
622
+                $c->getL10N('lib', $language)
623
+            );
624
+        });
625
+        $this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
626
+
627
+        $this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
628
+            $mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
629
+            $listener = new UserMountCacheListener($mountCache);
630
+            $listener->listen($c->getUserManager());
631
+            return $mountCache;
632
+        });
633
+        $this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
634
+
635
+        $this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
636
+            $loader = \OC\Files\Filesystem::getLoader();
637
+            $mountCache = $c->query('UserMountCache');
638
+            $manager =  new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
639
+
640
+            // builtin providers
641
+
642
+            $config = $c->getConfig();
643
+            $manager->registerProvider(new CacheMountProvider($config));
644
+            $manager->registerHomeProvider(new LocalHomeMountProvider());
645
+            $manager->registerHomeProvider(new ObjectHomeMountProvider($config));
646
+
647
+            return $manager;
648
+        });
649
+        $this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
650
+
651
+        $this->registerService('IniWrapper', function ($c) {
652
+            return new IniGetWrapper();
653
+        });
654
+        $this->registerService('AsyncCommandBus', function (Server $c) {
655
+            $jobList = $c->getJobList();
656
+            return new AsyncBus($jobList);
657
+        });
658
+        $this->registerService('TrustedDomainHelper', function ($c) {
659
+            return new TrustedDomainHelper($this->getConfig());
660
+        });
661
+        $this->registerService('Throttler', function(Server $c) {
662
+            return new Throttler(
663
+                $c->getDatabaseConnection(),
664
+                new TimeFactory(),
665
+                $c->getLogger(),
666
+                $c->getConfig()
667
+            );
668
+        });
669
+        $this->registerService('IntegrityCodeChecker', function (Server $c) {
670
+            // IConfig and IAppManager requires a working database. This code
671
+            // might however be called when ownCloud is not yet setup.
672
+            if(\OC::$server->getSystemConfig()->getValue('installed', false)) {
673
+                $config = $c->getConfig();
674
+                $appManager = $c->getAppManager();
675
+            } else {
676
+                $config = null;
677
+                $appManager = null;
678
+            }
679
+
680
+            return new Checker(
681
+                    new EnvironmentHelper(),
682
+                    new FileAccessHelper(),
683
+                    new AppLocator(),
684
+                    $config,
685
+                    $c->getMemCacheFactory(),
686
+                    $appManager,
687
+                    $c->getTempManager()
688
+            );
689
+        });
690
+        $this->registerService(\OCP\IRequest::class, function ($c) {
691
+            if (isset($this['urlParams'])) {
692
+                $urlParams = $this['urlParams'];
693
+            } else {
694
+                $urlParams = [];
695
+            }
696
+
697
+            if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
698
+                && in_array('fakeinput', stream_get_wrappers())
699
+            ) {
700
+                $stream = 'fakeinput://data';
701
+            } else {
702
+                $stream = 'php://input';
703
+            }
704
+
705
+            return new Request(
706
+                [
707
+                    'get' => $_GET,
708
+                    'post' => $_POST,
709
+                    'files' => $_FILES,
710
+                    'server' => $_SERVER,
711
+                    'env' => $_ENV,
712
+                    'cookies' => $_COOKIE,
713
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
714
+                        ? $_SERVER['REQUEST_METHOD']
715
+                        : null,
716
+                    'urlParams' => $urlParams,
717
+                ],
718
+                $this->getSecureRandom(),
719
+                $this->getConfig(),
720
+                $this->getCsrfTokenManager(),
721
+                $stream
722
+            );
723
+        });
724
+        $this->registerAlias('Request', \OCP\IRequest::class);
725
+
726
+        $this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
727
+            return new Mailer(
728
+                $c->getConfig(),
729
+                $c->getLogger(),
730
+                $c->getDefaults()
731
+            );
732
+        });
733
+        $this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
734
+
735
+        $this->registerService('LDAPProvider', function(Server $c) {
736
+            $config = $c->getConfig();
737
+            $factoryClass = $config->getSystemValue('ldapProviderFactory', null);
738
+            if(is_null($factoryClass)) {
739
+                throw new \Exception('ldapProviderFactory not set');
740
+            }
741
+            /** @var \OCP\LDAP\ILDAPProviderFactory $factory */
742
+            $factory = new $factoryClass($this);
743
+            return $factory->getLDAPProvider();
744
+        });
745
+        $this->registerService('LockingProvider', function (Server $c) {
746
+            $ini = $c->getIniWrapper();
747
+            $config = $c->getConfig();
748
+            $ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
749
+            if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
750
+                /** @var \OC\Memcache\Factory $memcacheFactory */
751
+                $memcacheFactory = $c->getMemCacheFactory();
752
+                $memcache = $memcacheFactory->createLocking('lock');
753
+                if (!($memcache instanceof \OC\Memcache\NullCache)) {
754
+                    return new MemcacheLockingProvider($memcache, $ttl);
755
+                }
756
+                return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
757
+            }
758
+            return new NoopLockingProvider();
759
+        });
760
+
761
+        $this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
762
+            return new \OC\Files\Mount\Manager();
763
+        });
764
+        $this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
765
+
766
+        $this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
767
+            return new \OC\Files\Type\Detection(
768
+                $c->getURLGenerator(),
769
+                \OC::$configDir,
770
+                \OC::$SERVERROOT . '/resources/config/'
771
+            );
772
+        });
773
+        $this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
774
+
775
+        $this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
776
+            return new \OC\Files\Type\Loader(
777
+                $c->getDatabaseConnection()
778
+            );
779
+        });
780
+        $this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
781
+
782
+        $this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
783
+            return new Manager(
784
+                $c->query(IValidator::class)
785
+            );
786
+        });
787
+        $this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
788
+
789
+        $this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
790
+            $manager = new \OC\CapabilitiesManager($c->getLogger());
791
+            $manager->registerCapability(function () use ($c) {
792
+                return new \OC\OCS\CoreCapabilities($c->getConfig());
793
+            });
794
+            return $manager;
795
+        });
796
+        $this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
797
+
798
+        $this->registerService(\OCP\Comments\ICommentsManager::class, function(Server $c) {
799
+            $config = $c->getConfig();
800
+            $factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
801
+            /** @var \OCP\Comments\ICommentsManagerFactory $factory */
802
+            $factory = new $factoryClass($this);
803
+            return $factory->getManager();
804
+        });
805
+        $this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
806
+
807
+        $this->registerService('ThemingDefaults', function(Server $c) {
808
+            /*
809 809
 			 * Dark magic for autoloader.
810 810
 			 * If we do a class_exists it will try to load the class which will
811 811
 			 * make composer cache the result. Resulting in errors when enabling
812 812
 			 * the theming app.
813 813
 			 */
814
-			$prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
815
-			if (isset($prefixes['OCA\\Theming\\'])) {
816
-				$classExists = true;
817
-			} else {
818
-				$classExists = false;
819
-			}
820
-
821
-			if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming')) {
822
-				return new ThemingDefaults(
823
-					$c->getConfig(),
824
-					$c->getL10N('theming'),
825
-					$c->getURLGenerator(),
826
-					new \OC_Defaults(),
827
-					$c->getAppDataDir('theming'),
828
-					$c->getMemCacheFactory()
829
-				);
830
-			}
831
-			return new \OC_Defaults();
832
-		});
833
-		$this->registerService(EventDispatcher::class, function () {
834
-			return new EventDispatcher();
835
-		});
836
-		$this->registerAlias('EventDispatcher', EventDispatcher::class);
837
-		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
838
-
839
-		$this->registerService('CryptoWrapper', function (Server $c) {
840
-			// FIXME: Instantiiated here due to cyclic dependency
841
-			$request = new Request(
842
-				[
843
-					'get' => $_GET,
844
-					'post' => $_POST,
845
-					'files' => $_FILES,
846
-					'server' => $_SERVER,
847
-					'env' => $_ENV,
848
-					'cookies' => $_COOKIE,
849
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
850
-						? $_SERVER['REQUEST_METHOD']
851
-						: null,
852
-				],
853
-				$c->getSecureRandom(),
854
-				$c->getConfig()
855
-			);
856
-
857
-			return new CryptoWrapper(
858
-				$c->getConfig(),
859
-				$c->getCrypto(),
860
-				$c->getSecureRandom(),
861
-				$request
862
-			);
863
-		});
864
-		$this->registerService('CsrfTokenManager', function (Server $c) {
865
-			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
866
-
867
-			return new CsrfTokenManager(
868
-				$tokenGenerator,
869
-				$c->query(SessionStorage::class)
870
-			);
871
-		});
872
-		$this->registerService(SessionStorage::class, function (Server $c) {
873
-			return new SessionStorage($c->getSession());
874
-		});
875
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
876
-			return new ContentSecurityPolicyManager();
877
-		});
878
-		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
879
-
880
-		$this->registerService('ContentSecurityPolicyNonceManager', function(Server $c) {
881
-			return new ContentSecurityPolicyNonceManager(
882
-				$c->getCsrfTokenManager(),
883
-				$c->getRequest()
884
-			);
885
-		});
886
-
887
-		$this->registerService(\OCP\Share\IManager::class, function(Server $c) {
888
-			$config = $c->getConfig();
889
-			$factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
890
-			/** @var \OCP\Share\IProviderFactory $factory */
891
-			$factory = new $factoryClass($this);
892
-
893
-			$manager = new \OC\Share20\Manager(
894
-				$c->getLogger(),
895
-				$c->getConfig(),
896
-				$c->getSecureRandom(),
897
-				$c->getHasher(),
898
-				$c->getMountManager(),
899
-				$c->getGroupManager(),
900
-				$c->getL10N('core'),
901
-				$factory,
902
-				$c->getUserManager(),
903
-				$c->getLazyRootFolder(),
904
-				$c->getEventDispatcher()
905
-			);
906
-
907
-			return $manager;
908
-		});
909
-		$this->registerAlias('ShareManager', \OCP\Share\IManager::class);
910
-
911
-		$this->registerService('SettingsManager', function(Server $c) {
912
-			$manager = new \OC\Settings\Manager(
913
-				$c->getLogger(),
914
-				$c->getDatabaseConnection(),
915
-				$c->getL10N('lib'),
916
-				$c->getConfig(),
917
-				$c->getEncryptionManager(),
918
-				$c->getUserManager(),
919
-				$c->getLockingProvider(),
920
-				$c->getRequest(),
921
-				new \OC\Settings\Mapper($c->getDatabaseConnection()),
922
-				$c->getURLGenerator()
923
-			);
924
-			return $manager;
925
-		});
926
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
927
-			return new \OC\Files\AppData\Factory(
928
-				$c->getRootFolder(),
929
-				$c->getSystemConfig()
930
-			);
931
-		});
932
-
933
-		$this->registerService('LockdownManager', function (Server $c) {
934
-			return new LockdownManager(function() use ($c) {
935
-				return $c->getSession();
936
-			});
937
-		});
938
-
939
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
940
-			return new CloudIdManager();
941
-		});
942
-
943
-		/* To trick DI since we don't extend the DIContainer here */
944
-		$this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
945
-			return new CleanPreviewsBackgroundJob(
946
-				$c->getRootFolder(),
947
-				$c->getLogger(),
948
-				$c->getJobList(),
949
-				new TimeFactory()
950
-			);
951
-		});
952
-
953
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
954
-		$this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
955
-
956
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
957
-		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
958
-
959
-		$this->registerService(Defaults::class, function (Server $c) {
960
-			return new Defaults(
961
-				$c->getThemingDefaults()
962
-			);
963
-		});
964
-		$this->registerAlias('Defaults', \OCP\Defaults::class);
965
-
966
-		$this->registerService(\OCP\ISession::class, function(SimpleContainer $c) {
967
-			return $c->query(\OCP\IUserSession::class)->getSession();
968
-		});
969
-	}
970
-
971
-	/**
972
-	 * @return \OCP\Contacts\IManager
973
-	 */
974
-	public function getContactsManager() {
975
-		return $this->query('ContactsManager');
976
-	}
977
-
978
-	/**
979
-	 * @return \OC\Encryption\Manager
980
-	 */
981
-	public function getEncryptionManager() {
982
-		return $this->query('EncryptionManager');
983
-	}
984
-
985
-	/**
986
-	 * @return \OC\Encryption\File
987
-	 */
988
-	public function getEncryptionFilesHelper() {
989
-		return $this->query('EncryptionFileHelper');
990
-	}
991
-
992
-	/**
993
-	 * @return \OCP\Encryption\Keys\IStorage
994
-	 */
995
-	public function getEncryptionKeyStorage() {
996
-		return $this->query('EncryptionKeyStorage');
997
-	}
998
-
999
-	/**
1000
-	 * The current request object holding all information about the request
1001
-	 * currently being processed is returned from this method.
1002
-	 * In case the current execution was not initiated by a web request null is returned
1003
-	 *
1004
-	 * @return \OCP\IRequest
1005
-	 */
1006
-	public function getRequest() {
1007
-		return $this->query('Request');
1008
-	}
1009
-
1010
-	/**
1011
-	 * Returns the preview manager which can create preview images for a given file
1012
-	 *
1013
-	 * @return \OCP\IPreview
1014
-	 */
1015
-	public function getPreviewManager() {
1016
-		return $this->query('PreviewManager');
1017
-	}
1018
-
1019
-	/**
1020
-	 * Returns the tag manager which can get and set tags for different object types
1021
-	 *
1022
-	 * @see \OCP\ITagManager::load()
1023
-	 * @return \OCP\ITagManager
1024
-	 */
1025
-	public function getTagManager() {
1026
-		return $this->query('TagManager');
1027
-	}
1028
-
1029
-	/**
1030
-	 * Returns the system-tag manager
1031
-	 *
1032
-	 * @return \OCP\SystemTag\ISystemTagManager
1033
-	 *
1034
-	 * @since 9.0.0
1035
-	 */
1036
-	public function getSystemTagManager() {
1037
-		return $this->query('SystemTagManager');
1038
-	}
1039
-
1040
-	/**
1041
-	 * Returns the system-tag object mapper
1042
-	 *
1043
-	 * @return \OCP\SystemTag\ISystemTagObjectMapper
1044
-	 *
1045
-	 * @since 9.0.0
1046
-	 */
1047
-	public function getSystemTagObjectMapper() {
1048
-		return $this->query('SystemTagObjectMapper');
1049
-	}
1050
-
1051
-	/**
1052
-	 * Returns the avatar manager, used for avatar functionality
1053
-	 *
1054
-	 * @return \OCP\IAvatarManager
1055
-	 */
1056
-	public function getAvatarManager() {
1057
-		return $this->query('AvatarManager');
1058
-	}
1059
-
1060
-	/**
1061
-	 * Returns the root folder of ownCloud's data directory
1062
-	 *
1063
-	 * @return \OCP\Files\IRootFolder
1064
-	 */
1065
-	public function getRootFolder() {
1066
-		return $this->query('LazyRootFolder');
1067
-	}
1068
-
1069
-	/**
1070
-	 * Returns the root folder of ownCloud's data directory
1071
-	 * This is the lazy variant so this gets only initialized once it
1072
-	 * is actually used.
1073
-	 *
1074
-	 * @return \OCP\Files\IRootFolder
1075
-	 */
1076
-	public function getLazyRootFolder() {
1077
-		return $this->query('LazyRootFolder');
1078
-	}
1079
-
1080
-	/**
1081
-	 * Returns a view to ownCloud's files folder
1082
-	 *
1083
-	 * @param string $userId user ID
1084
-	 * @return \OCP\Files\Folder|null
1085
-	 */
1086
-	public function getUserFolder($userId = null) {
1087
-		if ($userId === null) {
1088
-			$user = $this->getUserSession()->getUser();
1089
-			if (!$user) {
1090
-				return null;
1091
-			}
1092
-			$userId = $user->getUID();
1093
-		}
1094
-		$root = $this->getRootFolder();
1095
-		return $root->getUserFolder($userId);
1096
-	}
1097
-
1098
-	/**
1099
-	 * Returns an app-specific view in ownClouds data directory
1100
-	 *
1101
-	 * @return \OCP\Files\Folder
1102
-	 * @deprecated since 9.2.0 use IAppData
1103
-	 */
1104
-	public function getAppFolder() {
1105
-		$dir = '/' . \OC_App::getCurrentApp();
1106
-		$root = $this->getRootFolder();
1107
-		if (!$root->nodeExists($dir)) {
1108
-			$folder = $root->newFolder($dir);
1109
-		} else {
1110
-			$folder = $root->get($dir);
1111
-		}
1112
-		return $folder;
1113
-	}
1114
-
1115
-	/**
1116
-	 * @return \OC\User\Manager
1117
-	 */
1118
-	public function getUserManager() {
1119
-		return $this->query('UserManager');
1120
-	}
1121
-
1122
-	/**
1123
-	 * @return \OC\Group\Manager
1124
-	 */
1125
-	public function getGroupManager() {
1126
-		return $this->query('GroupManager');
1127
-	}
1128
-
1129
-	/**
1130
-	 * @return \OC\User\Session
1131
-	 */
1132
-	public function getUserSession() {
1133
-		return $this->query('UserSession');
1134
-	}
1135
-
1136
-	/**
1137
-	 * @return \OCP\ISession
1138
-	 */
1139
-	public function getSession() {
1140
-		return $this->query('UserSession')->getSession();
1141
-	}
1142
-
1143
-	/**
1144
-	 * @param \OCP\ISession $session
1145
-	 */
1146
-	public function setSession(\OCP\ISession $session) {
1147
-		$this->query(SessionStorage::class)->setSession($session);
1148
-		$this->query('UserSession')->setSession($session);
1149
-		$this->query(Store::class)->setSession($session);
1150
-	}
1151
-
1152
-	/**
1153
-	 * @return \OC\Authentication\TwoFactorAuth\Manager
1154
-	 */
1155
-	public function getTwoFactorAuthManager() {
1156
-		return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1157
-	}
1158
-
1159
-	/**
1160
-	 * @return \OC\NavigationManager
1161
-	 */
1162
-	public function getNavigationManager() {
1163
-		return $this->query('NavigationManager');
1164
-	}
1165
-
1166
-	/**
1167
-	 * @return \OCP\IConfig
1168
-	 */
1169
-	public function getConfig() {
1170
-		return $this->query('AllConfig');
1171
-	}
1172
-
1173
-	/**
1174
-	 * @internal For internal use only
1175
-	 * @return \OC\SystemConfig
1176
-	 */
1177
-	public function getSystemConfig() {
1178
-		return $this->query('SystemConfig');
1179
-	}
1180
-
1181
-	/**
1182
-	 * Returns the app config manager
1183
-	 *
1184
-	 * @return \OCP\IAppConfig
1185
-	 */
1186
-	public function getAppConfig() {
1187
-		return $this->query('AppConfig');
1188
-	}
1189
-
1190
-	/**
1191
-	 * @return \OCP\L10N\IFactory
1192
-	 */
1193
-	public function getL10NFactory() {
1194
-		return $this->query('L10NFactory');
1195
-	}
1196
-
1197
-	/**
1198
-	 * get an L10N instance
1199
-	 *
1200
-	 * @param string $app appid
1201
-	 * @param string $lang
1202
-	 * @return IL10N
1203
-	 */
1204
-	public function getL10N($app, $lang = null) {
1205
-		return $this->getL10NFactory()->get($app, $lang);
1206
-	}
1207
-
1208
-	/**
1209
-	 * @return \OCP\IURLGenerator
1210
-	 */
1211
-	public function getURLGenerator() {
1212
-		return $this->query('URLGenerator');
1213
-	}
1214
-
1215
-	/**
1216
-	 * @return \OCP\IHelper
1217
-	 */
1218
-	public function getHelper() {
1219
-		return $this->query('AppHelper');
1220
-	}
1221
-
1222
-	/**
1223
-	 * @return AppFetcher
1224
-	 */
1225
-	public function getAppFetcher() {
1226
-		return $this->query('AppFetcher');
1227
-	}
1228
-
1229
-	/**
1230
-	 * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1231
-	 * getMemCacheFactory() instead.
1232
-	 *
1233
-	 * @return \OCP\ICache
1234
-	 * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1235
-	 */
1236
-	public function getCache() {
1237
-		return $this->query('UserCache');
1238
-	}
1239
-
1240
-	/**
1241
-	 * Returns an \OCP\CacheFactory instance
1242
-	 *
1243
-	 * @return \OCP\ICacheFactory
1244
-	 */
1245
-	public function getMemCacheFactory() {
1246
-		return $this->query('MemCacheFactory');
1247
-	}
1248
-
1249
-	/**
1250
-	 * Returns an \OC\RedisFactory instance
1251
-	 *
1252
-	 * @return \OC\RedisFactory
1253
-	 */
1254
-	public function getGetRedisFactory() {
1255
-		return $this->query('RedisFactory');
1256
-	}
1257
-
1258
-
1259
-	/**
1260
-	 * Returns the current session
1261
-	 *
1262
-	 * @return \OCP\IDBConnection
1263
-	 */
1264
-	public function getDatabaseConnection() {
1265
-		return $this->query('DatabaseConnection');
1266
-	}
1267
-
1268
-	/**
1269
-	 * Returns the activity manager
1270
-	 *
1271
-	 * @return \OCP\Activity\IManager
1272
-	 */
1273
-	public function getActivityManager() {
1274
-		return $this->query('ActivityManager');
1275
-	}
1276
-
1277
-	/**
1278
-	 * Returns an job list for controlling background jobs
1279
-	 *
1280
-	 * @return \OCP\BackgroundJob\IJobList
1281
-	 */
1282
-	public function getJobList() {
1283
-		return $this->query('JobList');
1284
-	}
1285
-
1286
-	/**
1287
-	 * Returns a logger instance
1288
-	 *
1289
-	 * @return \OCP\ILogger
1290
-	 */
1291
-	public function getLogger() {
1292
-		return $this->query('Logger');
1293
-	}
1294
-
1295
-	/**
1296
-	 * Returns a router for generating and matching urls
1297
-	 *
1298
-	 * @return \OCP\Route\IRouter
1299
-	 */
1300
-	public function getRouter() {
1301
-		return $this->query('Router');
1302
-	}
1303
-
1304
-	/**
1305
-	 * Returns a search instance
1306
-	 *
1307
-	 * @return \OCP\ISearch
1308
-	 */
1309
-	public function getSearch() {
1310
-		return $this->query('Search');
1311
-	}
1312
-
1313
-	/**
1314
-	 * Returns a SecureRandom instance
1315
-	 *
1316
-	 * @return \OCP\Security\ISecureRandom
1317
-	 */
1318
-	public function getSecureRandom() {
1319
-		return $this->query('SecureRandom');
1320
-	}
1321
-
1322
-	/**
1323
-	 * Returns a Crypto instance
1324
-	 *
1325
-	 * @return \OCP\Security\ICrypto
1326
-	 */
1327
-	public function getCrypto() {
1328
-		return $this->query('Crypto');
1329
-	}
1330
-
1331
-	/**
1332
-	 * Returns a Hasher instance
1333
-	 *
1334
-	 * @return \OCP\Security\IHasher
1335
-	 */
1336
-	public function getHasher() {
1337
-		return $this->query('Hasher');
1338
-	}
1339
-
1340
-	/**
1341
-	 * Returns a CredentialsManager instance
1342
-	 *
1343
-	 * @return \OCP\Security\ICredentialsManager
1344
-	 */
1345
-	public function getCredentialsManager() {
1346
-		return $this->query('CredentialsManager');
1347
-	}
1348
-
1349
-	/**
1350
-	 * Returns an instance of the HTTP helper class
1351
-	 *
1352
-	 * @deprecated Use getHTTPClientService()
1353
-	 * @return \OC\HTTPHelper
1354
-	 */
1355
-	public function getHTTPHelper() {
1356
-		return $this->query('HTTPHelper');
1357
-	}
1358
-
1359
-	/**
1360
-	 * Get the certificate manager for the user
1361
-	 *
1362
-	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1363
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1364
-	 */
1365
-	public function getCertificateManager($userId = '') {
1366
-		if ($userId === '') {
1367
-			$userSession = $this->getUserSession();
1368
-			$user = $userSession->getUser();
1369
-			if (is_null($user)) {
1370
-				return null;
1371
-			}
1372
-			$userId = $user->getUID();
1373
-		}
1374
-		return new CertificateManager($userId, new View(), $this->getConfig(), $this->getLogger());
1375
-	}
1376
-
1377
-	/**
1378
-	 * Returns an instance of the HTTP client service
1379
-	 *
1380
-	 * @return \OCP\Http\Client\IClientService
1381
-	 */
1382
-	public function getHTTPClientService() {
1383
-		return $this->query('HttpClientService');
1384
-	}
1385
-
1386
-	/**
1387
-	 * Create a new event source
1388
-	 *
1389
-	 * @return \OCP\IEventSource
1390
-	 */
1391
-	public function createEventSource() {
1392
-		return new \OC_EventSource();
1393
-	}
1394
-
1395
-	/**
1396
-	 * Get the active event logger
1397
-	 *
1398
-	 * The returned logger only logs data when debug mode is enabled
1399
-	 *
1400
-	 * @return \OCP\Diagnostics\IEventLogger
1401
-	 */
1402
-	public function getEventLogger() {
1403
-		return $this->query('EventLogger');
1404
-	}
1405
-
1406
-	/**
1407
-	 * Get the active query logger
1408
-	 *
1409
-	 * The returned logger only logs data when debug mode is enabled
1410
-	 *
1411
-	 * @return \OCP\Diagnostics\IQueryLogger
1412
-	 */
1413
-	public function getQueryLogger() {
1414
-		return $this->query('QueryLogger');
1415
-	}
1416
-
1417
-	/**
1418
-	 * Get the manager for temporary files and folders
1419
-	 *
1420
-	 * @return \OCP\ITempManager
1421
-	 */
1422
-	public function getTempManager() {
1423
-		return $this->query('TempManager');
1424
-	}
1425
-
1426
-	/**
1427
-	 * Get the app manager
1428
-	 *
1429
-	 * @return \OCP\App\IAppManager
1430
-	 */
1431
-	public function getAppManager() {
1432
-		return $this->query('AppManager');
1433
-	}
1434
-
1435
-	/**
1436
-	 * Creates a new mailer
1437
-	 *
1438
-	 * @return \OCP\Mail\IMailer
1439
-	 */
1440
-	public function getMailer() {
1441
-		return $this->query('Mailer');
1442
-	}
1443
-
1444
-	/**
1445
-	 * Get the webroot
1446
-	 *
1447
-	 * @return string
1448
-	 */
1449
-	public function getWebRoot() {
1450
-		return $this->webRoot;
1451
-	}
1452
-
1453
-	/**
1454
-	 * @return \OC\OCSClient
1455
-	 */
1456
-	public function getOcsClient() {
1457
-		return $this->query('OcsClient');
1458
-	}
1459
-
1460
-	/**
1461
-	 * @return \OCP\IDateTimeZone
1462
-	 */
1463
-	public function getDateTimeZone() {
1464
-		return $this->query('DateTimeZone');
1465
-	}
1466
-
1467
-	/**
1468
-	 * @return \OCP\IDateTimeFormatter
1469
-	 */
1470
-	public function getDateTimeFormatter() {
1471
-		return $this->query('DateTimeFormatter');
1472
-	}
1473
-
1474
-	/**
1475
-	 * @return \OCP\Files\Config\IMountProviderCollection
1476
-	 */
1477
-	public function getMountProviderCollection() {
1478
-		return $this->query('MountConfigManager');
1479
-	}
1480
-
1481
-	/**
1482
-	 * Get the IniWrapper
1483
-	 *
1484
-	 * @return IniGetWrapper
1485
-	 */
1486
-	public function getIniWrapper() {
1487
-		return $this->query('IniWrapper');
1488
-	}
1489
-
1490
-	/**
1491
-	 * @return \OCP\Command\IBus
1492
-	 */
1493
-	public function getCommandBus() {
1494
-		return $this->query('AsyncCommandBus');
1495
-	}
1496
-
1497
-	/**
1498
-	 * Get the trusted domain helper
1499
-	 *
1500
-	 * @return TrustedDomainHelper
1501
-	 */
1502
-	public function getTrustedDomainHelper() {
1503
-		return $this->query('TrustedDomainHelper');
1504
-	}
1505
-
1506
-	/**
1507
-	 * Get the locking provider
1508
-	 *
1509
-	 * @return \OCP\Lock\ILockingProvider
1510
-	 * @since 8.1.0
1511
-	 */
1512
-	public function getLockingProvider() {
1513
-		return $this->query('LockingProvider');
1514
-	}
1515
-
1516
-	/**
1517
-	 * @return \OCP\Files\Mount\IMountManager
1518
-	 **/
1519
-	function getMountManager() {
1520
-		return $this->query('MountManager');
1521
-	}
1522
-
1523
-	/** @return \OCP\Files\Config\IUserMountCache */
1524
-	function getUserMountCache() {
1525
-		return $this->query('UserMountCache');
1526
-	}
1527
-
1528
-	/**
1529
-	 * Get the MimeTypeDetector
1530
-	 *
1531
-	 * @return \OCP\Files\IMimeTypeDetector
1532
-	 */
1533
-	public function getMimeTypeDetector() {
1534
-		return $this->query('MimeTypeDetector');
1535
-	}
1536
-
1537
-	/**
1538
-	 * Get the MimeTypeLoader
1539
-	 *
1540
-	 * @return \OCP\Files\IMimeTypeLoader
1541
-	 */
1542
-	public function getMimeTypeLoader() {
1543
-		return $this->query('MimeTypeLoader');
1544
-	}
1545
-
1546
-	/**
1547
-	 * Get the manager of all the capabilities
1548
-	 *
1549
-	 * @return \OC\CapabilitiesManager
1550
-	 */
1551
-	public function getCapabilitiesManager() {
1552
-		return $this->query('CapabilitiesManager');
1553
-	}
1554
-
1555
-	/**
1556
-	 * Get the EventDispatcher
1557
-	 *
1558
-	 * @return EventDispatcherInterface
1559
-	 * @since 8.2.0
1560
-	 */
1561
-	public function getEventDispatcher() {
1562
-		return $this->query('EventDispatcher');
1563
-	}
1564
-
1565
-	/**
1566
-	 * Get the Notification Manager
1567
-	 *
1568
-	 * @return \OCP\Notification\IManager
1569
-	 * @since 8.2.0
1570
-	 */
1571
-	public function getNotificationManager() {
1572
-		return $this->query('NotificationManager');
1573
-	}
1574
-
1575
-	/**
1576
-	 * @return \OCP\Comments\ICommentsManager
1577
-	 */
1578
-	public function getCommentsManager() {
1579
-		return $this->query('CommentsManager');
1580
-	}
1581
-
1582
-	/**
1583
-	 * @return \OCA\Theming\ThemingDefaults
1584
-	 */
1585
-	public function getThemingDefaults() {
1586
-		return $this->query('ThemingDefaults');
1587
-	}
1588
-
1589
-	/**
1590
-	 * @return \OC\IntegrityCheck\Checker
1591
-	 */
1592
-	public function getIntegrityCodeChecker() {
1593
-		return $this->query('IntegrityCodeChecker');
1594
-	}
1595
-
1596
-	/**
1597
-	 * @return \OC\Session\CryptoWrapper
1598
-	 */
1599
-	public function getSessionCryptoWrapper() {
1600
-		return $this->query('CryptoWrapper');
1601
-	}
1602
-
1603
-	/**
1604
-	 * @return CsrfTokenManager
1605
-	 */
1606
-	public function getCsrfTokenManager() {
1607
-		return $this->query('CsrfTokenManager');
1608
-	}
1609
-
1610
-	/**
1611
-	 * @return Throttler
1612
-	 */
1613
-	public function getBruteForceThrottler() {
1614
-		return $this->query('Throttler');
1615
-	}
1616
-
1617
-	/**
1618
-	 * @return IContentSecurityPolicyManager
1619
-	 */
1620
-	public function getContentSecurityPolicyManager() {
1621
-		return $this->query('ContentSecurityPolicyManager');
1622
-	}
1623
-
1624
-	/**
1625
-	 * @return ContentSecurityPolicyNonceManager
1626
-	 */
1627
-	public function getContentSecurityPolicyNonceManager() {
1628
-		return $this->query('ContentSecurityPolicyNonceManager');
1629
-	}
1630
-
1631
-	/**
1632
-	 * Not a public API as of 8.2, wait for 9.0
1633
-	 *
1634
-	 * @return \OCA\Files_External\Service\BackendService
1635
-	 */
1636
-	public function getStoragesBackendService() {
1637
-		return $this->query('OCA\\Files_External\\Service\\BackendService');
1638
-	}
1639
-
1640
-	/**
1641
-	 * Not a public API as of 8.2, wait for 9.0
1642
-	 *
1643
-	 * @return \OCA\Files_External\Service\GlobalStoragesService
1644
-	 */
1645
-	public function getGlobalStoragesService() {
1646
-		return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1647
-	}
1648
-
1649
-	/**
1650
-	 * Not a public API as of 8.2, wait for 9.0
1651
-	 *
1652
-	 * @return \OCA\Files_External\Service\UserGlobalStoragesService
1653
-	 */
1654
-	public function getUserGlobalStoragesService() {
1655
-		return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1656
-	}
1657
-
1658
-	/**
1659
-	 * Not a public API as of 8.2, wait for 9.0
1660
-	 *
1661
-	 * @return \OCA\Files_External\Service\UserStoragesService
1662
-	 */
1663
-	public function getUserStoragesService() {
1664
-		return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1665
-	}
1666
-
1667
-	/**
1668
-	 * @return \OCP\Share\IManager
1669
-	 */
1670
-	public function getShareManager() {
1671
-		return $this->query('ShareManager');
1672
-	}
1673
-
1674
-	/**
1675
-	 * Returns the LDAP Provider
1676
-	 *
1677
-	 * @return \OCP\LDAP\ILDAPProvider
1678
-	 */
1679
-	public function getLDAPProvider() {
1680
-		return $this->query('LDAPProvider');
1681
-	}
1682
-
1683
-	/**
1684
-	 * @return \OCP\Settings\IManager
1685
-	 */
1686
-	public function getSettingsManager() {
1687
-		return $this->query('SettingsManager');
1688
-	}
1689
-
1690
-	/**
1691
-	 * @return \OCP\Files\IAppData
1692
-	 */
1693
-	public function getAppDataDir($app) {
1694
-		/** @var \OC\Files\AppData\Factory $factory */
1695
-		$factory = $this->query(\OC\Files\AppData\Factory::class);
1696
-		return $factory->get($app);
1697
-	}
1698
-
1699
-	/**
1700
-	 * @return \OCP\Lockdown\ILockdownManager
1701
-	 */
1702
-	public function getLockdownManager() {
1703
-		return $this->query('LockdownManager');
1704
-	}
1705
-
1706
-	/**
1707
-	 * @return \OCP\Federation\ICloudIdManager
1708
-	 */
1709
-	public function getCloudIdManager() {
1710
-		return $this->query(ICloudIdManager::class);
1711
-	}
1712
-
1713
-	/**
1714
-	 * @return \OCP\Defaults
1715
-	 */
1716
-	public function getDefaults() {
1717
-		return $this->query(Defaults::class);
1718
-	}
814
+            $prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
815
+            if (isset($prefixes['OCA\\Theming\\'])) {
816
+                $classExists = true;
817
+            } else {
818
+                $classExists = false;
819
+            }
820
+
821
+            if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming')) {
822
+                return new ThemingDefaults(
823
+                    $c->getConfig(),
824
+                    $c->getL10N('theming'),
825
+                    $c->getURLGenerator(),
826
+                    new \OC_Defaults(),
827
+                    $c->getAppDataDir('theming'),
828
+                    $c->getMemCacheFactory()
829
+                );
830
+            }
831
+            return new \OC_Defaults();
832
+        });
833
+        $this->registerService(EventDispatcher::class, function () {
834
+            return new EventDispatcher();
835
+        });
836
+        $this->registerAlias('EventDispatcher', EventDispatcher::class);
837
+        $this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
838
+
839
+        $this->registerService('CryptoWrapper', function (Server $c) {
840
+            // FIXME: Instantiiated here due to cyclic dependency
841
+            $request = new Request(
842
+                [
843
+                    'get' => $_GET,
844
+                    'post' => $_POST,
845
+                    'files' => $_FILES,
846
+                    'server' => $_SERVER,
847
+                    'env' => $_ENV,
848
+                    'cookies' => $_COOKIE,
849
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
850
+                        ? $_SERVER['REQUEST_METHOD']
851
+                        : null,
852
+                ],
853
+                $c->getSecureRandom(),
854
+                $c->getConfig()
855
+            );
856
+
857
+            return new CryptoWrapper(
858
+                $c->getConfig(),
859
+                $c->getCrypto(),
860
+                $c->getSecureRandom(),
861
+                $request
862
+            );
863
+        });
864
+        $this->registerService('CsrfTokenManager', function (Server $c) {
865
+            $tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
866
+
867
+            return new CsrfTokenManager(
868
+                $tokenGenerator,
869
+                $c->query(SessionStorage::class)
870
+            );
871
+        });
872
+        $this->registerService(SessionStorage::class, function (Server $c) {
873
+            return new SessionStorage($c->getSession());
874
+        });
875
+        $this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
876
+            return new ContentSecurityPolicyManager();
877
+        });
878
+        $this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
879
+
880
+        $this->registerService('ContentSecurityPolicyNonceManager', function(Server $c) {
881
+            return new ContentSecurityPolicyNonceManager(
882
+                $c->getCsrfTokenManager(),
883
+                $c->getRequest()
884
+            );
885
+        });
886
+
887
+        $this->registerService(\OCP\Share\IManager::class, function(Server $c) {
888
+            $config = $c->getConfig();
889
+            $factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
890
+            /** @var \OCP\Share\IProviderFactory $factory */
891
+            $factory = new $factoryClass($this);
892
+
893
+            $manager = new \OC\Share20\Manager(
894
+                $c->getLogger(),
895
+                $c->getConfig(),
896
+                $c->getSecureRandom(),
897
+                $c->getHasher(),
898
+                $c->getMountManager(),
899
+                $c->getGroupManager(),
900
+                $c->getL10N('core'),
901
+                $factory,
902
+                $c->getUserManager(),
903
+                $c->getLazyRootFolder(),
904
+                $c->getEventDispatcher()
905
+            );
906
+
907
+            return $manager;
908
+        });
909
+        $this->registerAlias('ShareManager', \OCP\Share\IManager::class);
910
+
911
+        $this->registerService('SettingsManager', function(Server $c) {
912
+            $manager = new \OC\Settings\Manager(
913
+                $c->getLogger(),
914
+                $c->getDatabaseConnection(),
915
+                $c->getL10N('lib'),
916
+                $c->getConfig(),
917
+                $c->getEncryptionManager(),
918
+                $c->getUserManager(),
919
+                $c->getLockingProvider(),
920
+                $c->getRequest(),
921
+                new \OC\Settings\Mapper($c->getDatabaseConnection()),
922
+                $c->getURLGenerator()
923
+            );
924
+            return $manager;
925
+        });
926
+        $this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
927
+            return new \OC\Files\AppData\Factory(
928
+                $c->getRootFolder(),
929
+                $c->getSystemConfig()
930
+            );
931
+        });
932
+
933
+        $this->registerService('LockdownManager', function (Server $c) {
934
+            return new LockdownManager(function() use ($c) {
935
+                return $c->getSession();
936
+            });
937
+        });
938
+
939
+        $this->registerService(ICloudIdManager::class, function (Server $c) {
940
+            return new CloudIdManager();
941
+        });
942
+
943
+        /* To trick DI since we don't extend the DIContainer here */
944
+        $this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
945
+            return new CleanPreviewsBackgroundJob(
946
+                $c->getRootFolder(),
947
+                $c->getLogger(),
948
+                $c->getJobList(),
949
+                new TimeFactory()
950
+            );
951
+        });
952
+
953
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
954
+        $this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
955
+
956
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
957
+        $this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
958
+
959
+        $this->registerService(Defaults::class, function (Server $c) {
960
+            return new Defaults(
961
+                $c->getThemingDefaults()
962
+            );
963
+        });
964
+        $this->registerAlias('Defaults', \OCP\Defaults::class);
965
+
966
+        $this->registerService(\OCP\ISession::class, function(SimpleContainer $c) {
967
+            return $c->query(\OCP\IUserSession::class)->getSession();
968
+        });
969
+    }
970
+
971
+    /**
972
+     * @return \OCP\Contacts\IManager
973
+     */
974
+    public function getContactsManager() {
975
+        return $this->query('ContactsManager');
976
+    }
977
+
978
+    /**
979
+     * @return \OC\Encryption\Manager
980
+     */
981
+    public function getEncryptionManager() {
982
+        return $this->query('EncryptionManager');
983
+    }
984
+
985
+    /**
986
+     * @return \OC\Encryption\File
987
+     */
988
+    public function getEncryptionFilesHelper() {
989
+        return $this->query('EncryptionFileHelper');
990
+    }
991
+
992
+    /**
993
+     * @return \OCP\Encryption\Keys\IStorage
994
+     */
995
+    public function getEncryptionKeyStorage() {
996
+        return $this->query('EncryptionKeyStorage');
997
+    }
998
+
999
+    /**
1000
+     * The current request object holding all information about the request
1001
+     * currently being processed is returned from this method.
1002
+     * In case the current execution was not initiated by a web request null is returned
1003
+     *
1004
+     * @return \OCP\IRequest
1005
+     */
1006
+    public function getRequest() {
1007
+        return $this->query('Request');
1008
+    }
1009
+
1010
+    /**
1011
+     * Returns the preview manager which can create preview images for a given file
1012
+     *
1013
+     * @return \OCP\IPreview
1014
+     */
1015
+    public function getPreviewManager() {
1016
+        return $this->query('PreviewManager');
1017
+    }
1018
+
1019
+    /**
1020
+     * Returns the tag manager which can get and set tags for different object types
1021
+     *
1022
+     * @see \OCP\ITagManager::load()
1023
+     * @return \OCP\ITagManager
1024
+     */
1025
+    public function getTagManager() {
1026
+        return $this->query('TagManager');
1027
+    }
1028
+
1029
+    /**
1030
+     * Returns the system-tag manager
1031
+     *
1032
+     * @return \OCP\SystemTag\ISystemTagManager
1033
+     *
1034
+     * @since 9.0.0
1035
+     */
1036
+    public function getSystemTagManager() {
1037
+        return $this->query('SystemTagManager');
1038
+    }
1039
+
1040
+    /**
1041
+     * Returns the system-tag object mapper
1042
+     *
1043
+     * @return \OCP\SystemTag\ISystemTagObjectMapper
1044
+     *
1045
+     * @since 9.0.0
1046
+     */
1047
+    public function getSystemTagObjectMapper() {
1048
+        return $this->query('SystemTagObjectMapper');
1049
+    }
1050
+
1051
+    /**
1052
+     * Returns the avatar manager, used for avatar functionality
1053
+     *
1054
+     * @return \OCP\IAvatarManager
1055
+     */
1056
+    public function getAvatarManager() {
1057
+        return $this->query('AvatarManager');
1058
+    }
1059
+
1060
+    /**
1061
+     * Returns the root folder of ownCloud's data directory
1062
+     *
1063
+     * @return \OCP\Files\IRootFolder
1064
+     */
1065
+    public function getRootFolder() {
1066
+        return $this->query('LazyRootFolder');
1067
+    }
1068
+
1069
+    /**
1070
+     * Returns the root folder of ownCloud's data directory
1071
+     * This is the lazy variant so this gets only initialized once it
1072
+     * is actually used.
1073
+     *
1074
+     * @return \OCP\Files\IRootFolder
1075
+     */
1076
+    public function getLazyRootFolder() {
1077
+        return $this->query('LazyRootFolder');
1078
+    }
1079
+
1080
+    /**
1081
+     * Returns a view to ownCloud's files folder
1082
+     *
1083
+     * @param string $userId user ID
1084
+     * @return \OCP\Files\Folder|null
1085
+     */
1086
+    public function getUserFolder($userId = null) {
1087
+        if ($userId === null) {
1088
+            $user = $this->getUserSession()->getUser();
1089
+            if (!$user) {
1090
+                return null;
1091
+            }
1092
+            $userId = $user->getUID();
1093
+        }
1094
+        $root = $this->getRootFolder();
1095
+        return $root->getUserFolder($userId);
1096
+    }
1097
+
1098
+    /**
1099
+     * Returns an app-specific view in ownClouds data directory
1100
+     *
1101
+     * @return \OCP\Files\Folder
1102
+     * @deprecated since 9.2.0 use IAppData
1103
+     */
1104
+    public function getAppFolder() {
1105
+        $dir = '/' . \OC_App::getCurrentApp();
1106
+        $root = $this->getRootFolder();
1107
+        if (!$root->nodeExists($dir)) {
1108
+            $folder = $root->newFolder($dir);
1109
+        } else {
1110
+            $folder = $root->get($dir);
1111
+        }
1112
+        return $folder;
1113
+    }
1114
+
1115
+    /**
1116
+     * @return \OC\User\Manager
1117
+     */
1118
+    public function getUserManager() {
1119
+        return $this->query('UserManager');
1120
+    }
1121
+
1122
+    /**
1123
+     * @return \OC\Group\Manager
1124
+     */
1125
+    public function getGroupManager() {
1126
+        return $this->query('GroupManager');
1127
+    }
1128
+
1129
+    /**
1130
+     * @return \OC\User\Session
1131
+     */
1132
+    public function getUserSession() {
1133
+        return $this->query('UserSession');
1134
+    }
1135
+
1136
+    /**
1137
+     * @return \OCP\ISession
1138
+     */
1139
+    public function getSession() {
1140
+        return $this->query('UserSession')->getSession();
1141
+    }
1142
+
1143
+    /**
1144
+     * @param \OCP\ISession $session
1145
+     */
1146
+    public function setSession(\OCP\ISession $session) {
1147
+        $this->query(SessionStorage::class)->setSession($session);
1148
+        $this->query('UserSession')->setSession($session);
1149
+        $this->query(Store::class)->setSession($session);
1150
+    }
1151
+
1152
+    /**
1153
+     * @return \OC\Authentication\TwoFactorAuth\Manager
1154
+     */
1155
+    public function getTwoFactorAuthManager() {
1156
+        return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1157
+    }
1158
+
1159
+    /**
1160
+     * @return \OC\NavigationManager
1161
+     */
1162
+    public function getNavigationManager() {
1163
+        return $this->query('NavigationManager');
1164
+    }
1165
+
1166
+    /**
1167
+     * @return \OCP\IConfig
1168
+     */
1169
+    public function getConfig() {
1170
+        return $this->query('AllConfig');
1171
+    }
1172
+
1173
+    /**
1174
+     * @internal For internal use only
1175
+     * @return \OC\SystemConfig
1176
+     */
1177
+    public function getSystemConfig() {
1178
+        return $this->query('SystemConfig');
1179
+    }
1180
+
1181
+    /**
1182
+     * Returns the app config manager
1183
+     *
1184
+     * @return \OCP\IAppConfig
1185
+     */
1186
+    public function getAppConfig() {
1187
+        return $this->query('AppConfig');
1188
+    }
1189
+
1190
+    /**
1191
+     * @return \OCP\L10N\IFactory
1192
+     */
1193
+    public function getL10NFactory() {
1194
+        return $this->query('L10NFactory');
1195
+    }
1196
+
1197
+    /**
1198
+     * get an L10N instance
1199
+     *
1200
+     * @param string $app appid
1201
+     * @param string $lang
1202
+     * @return IL10N
1203
+     */
1204
+    public function getL10N($app, $lang = null) {
1205
+        return $this->getL10NFactory()->get($app, $lang);
1206
+    }
1207
+
1208
+    /**
1209
+     * @return \OCP\IURLGenerator
1210
+     */
1211
+    public function getURLGenerator() {
1212
+        return $this->query('URLGenerator');
1213
+    }
1214
+
1215
+    /**
1216
+     * @return \OCP\IHelper
1217
+     */
1218
+    public function getHelper() {
1219
+        return $this->query('AppHelper');
1220
+    }
1221
+
1222
+    /**
1223
+     * @return AppFetcher
1224
+     */
1225
+    public function getAppFetcher() {
1226
+        return $this->query('AppFetcher');
1227
+    }
1228
+
1229
+    /**
1230
+     * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1231
+     * getMemCacheFactory() instead.
1232
+     *
1233
+     * @return \OCP\ICache
1234
+     * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1235
+     */
1236
+    public function getCache() {
1237
+        return $this->query('UserCache');
1238
+    }
1239
+
1240
+    /**
1241
+     * Returns an \OCP\CacheFactory instance
1242
+     *
1243
+     * @return \OCP\ICacheFactory
1244
+     */
1245
+    public function getMemCacheFactory() {
1246
+        return $this->query('MemCacheFactory');
1247
+    }
1248
+
1249
+    /**
1250
+     * Returns an \OC\RedisFactory instance
1251
+     *
1252
+     * @return \OC\RedisFactory
1253
+     */
1254
+    public function getGetRedisFactory() {
1255
+        return $this->query('RedisFactory');
1256
+    }
1257
+
1258
+
1259
+    /**
1260
+     * Returns the current session
1261
+     *
1262
+     * @return \OCP\IDBConnection
1263
+     */
1264
+    public function getDatabaseConnection() {
1265
+        return $this->query('DatabaseConnection');
1266
+    }
1267
+
1268
+    /**
1269
+     * Returns the activity manager
1270
+     *
1271
+     * @return \OCP\Activity\IManager
1272
+     */
1273
+    public function getActivityManager() {
1274
+        return $this->query('ActivityManager');
1275
+    }
1276
+
1277
+    /**
1278
+     * Returns an job list for controlling background jobs
1279
+     *
1280
+     * @return \OCP\BackgroundJob\IJobList
1281
+     */
1282
+    public function getJobList() {
1283
+        return $this->query('JobList');
1284
+    }
1285
+
1286
+    /**
1287
+     * Returns a logger instance
1288
+     *
1289
+     * @return \OCP\ILogger
1290
+     */
1291
+    public function getLogger() {
1292
+        return $this->query('Logger');
1293
+    }
1294
+
1295
+    /**
1296
+     * Returns a router for generating and matching urls
1297
+     *
1298
+     * @return \OCP\Route\IRouter
1299
+     */
1300
+    public function getRouter() {
1301
+        return $this->query('Router');
1302
+    }
1303
+
1304
+    /**
1305
+     * Returns a search instance
1306
+     *
1307
+     * @return \OCP\ISearch
1308
+     */
1309
+    public function getSearch() {
1310
+        return $this->query('Search');
1311
+    }
1312
+
1313
+    /**
1314
+     * Returns a SecureRandom instance
1315
+     *
1316
+     * @return \OCP\Security\ISecureRandom
1317
+     */
1318
+    public function getSecureRandom() {
1319
+        return $this->query('SecureRandom');
1320
+    }
1321
+
1322
+    /**
1323
+     * Returns a Crypto instance
1324
+     *
1325
+     * @return \OCP\Security\ICrypto
1326
+     */
1327
+    public function getCrypto() {
1328
+        return $this->query('Crypto');
1329
+    }
1330
+
1331
+    /**
1332
+     * Returns a Hasher instance
1333
+     *
1334
+     * @return \OCP\Security\IHasher
1335
+     */
1336
+    public function getHasher() {
1337
+        return $this->query('Hasher');
1338
+    }
1339
+
1340
+    /**
1341
+     * Returns a CredentialsManager instance
1342
+     *
1343
+     * @return \OCP\Security\ICredentialsManager
1344
+     */
1345
+    public function getCredentialsManager() {
1346
+        return $this->query('CredentialsManager');
1347
+    }
1348
+
1349
+    /**
1350
+     * Returns an instance of the HTTP helper class
1351
+     *
1352
+     * @deprecated Use getHTTPClientService()
1353
+     * @return \OC\HTTPHelper
1354
+     */
1355
+    public function getHTTPHelper() {
1356
+        return $this->query('HTTPHelper');
1357
+    }
1358
+
1359
+    /**
1360
+     * Get the certificate manager for the user
1361
+     *
1362
+     * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1363
+     * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1364
+     */
1365
+    public function getCertificateManager($userId = '') {
1366
+        if ($userId === '') {
1367
+            $userSession = $this->getUserSession();
1368
+            $user = $userSession->getUser();
1369
+            if (is_null($user)) {
1370
+                return null;
1371
+            }
1372
+            $userId = $user->getUID();
1373
+        }
1374
+        return new CertificateManager($userId, new View(), $this->getConfig(), $this->getLogger());
1375
+    }
1376
+
1377
+    /**
1378
+     * Returns an instance of the HTTP client service
1379
+     *
1380
+     * @return \OCP\Http\Client\IClientService
1381
+     */
1382
+    public function getHTTPClientService() {
1383
+        return $this->query('HttpClientService');
1384
+    }
1385
+
1386
+    /**
1387
+     * Create a new event source
1388
+     *
1389
+     * @return \OCP\IEventSource
1390
+     */
1391
+    public function createEventSource() {
1392
+        return new \OC_EventSource();
1393
+    }
1394
+
1395
+    /**
1396
+     * Get the active event logger
1397
+     *
1398
+     * The returned logger only logs data when debug mode is enabled
1399
+     *
1400
+     * @return \OCP\Diagnostics\IEventLogger
1401
+     */
1402
+    public function getEventLogger() {
1403
+        return $this->query('EventLogger');
1404
+    }
1405
+
1406
+    /**
1407
+     * Get the active query logger
1408
+     *
1409
+     * The returned logger only logs data when debug mode is enabled
1410
+     *
1411
+     * @return \OCP\Diagnostics\IQueryLogger
1412
+     */
1413
+    public function getQueryLogger() {
1414
+        return $this->query('QueryLogger');
1415
+    }
1416
+
1417
+    /**
1418
+     * Get the manager for temporary files and folders
1419
+     *
1420
+     * @return \OCP\ITempManager
1421
+     */
1422
+    public function getTempManager() {
1423
+        return $this->query('TempManager');
1424
+    }
1425
+
1426
+    /**
1427
+     * Get the app manager
1428
+     *
1429
+     * @return \OCP\App\IAppManager
1430
+     */
1431
+    public function getAppManager() {
1432
+        return $this->query('AppManager');
1433
+    }
1434
+
1435
+    /**
1436
+     * Creates a new mailer
1437
+     *
1438
+     * @return \OCP\Mail\IMailer
1439
+     */
1440
+    public function getMailer() {
1441
+        return $this->query('Mailer');
1442
+    }
1443
+
1444
+    /**
1445
+     * Get the webroot
1446
+     *
1447
+     * @return string
1448
+     */
1449
+    public function getWebRoot() {
1450
+        return $this->webRoot;
1451
+    }
1452
+
1453
+    /**
1454
+     * @return \OC\OCSClient
1455
+     */
1456
+    public function getOcsClient() {
1457
+        return $this->query('OcsClient');
1458
+    }
1459
+
1460
+    /**
1461
+     * @return \OCP\IDateTimeZone
1462
+     */
1463
+    public function getDateTimeZone() {
1464
+        return $this->query('DateTimeZone');
1465
+    }
1466
+
1467
+    /**
1468
+     * @return \OCP\IDateTimeFormatter
1469
+     */
1470
+    public function getDateTimeFormatter() {
1471
+        return $this->query('DateTimeFormatter');
1472
+    }
1473
+
1474
+    /**
1475
+     * @return \OCP\Files\Config\IMountProviderCollection
1476
+     */
1477
+    public function getMountProviderCollection() {
1478
+        return $this->query('MountConfigManager');
1479
+    }
1480
+
1481
+    /**
1482
+     * Get the IniWrapper
1483
+     *
1484
+     * @return IniGetWrapper
1485
+     */
1486
+    public function getIniWrapper() {
1487
+        return $this->query('IniWrapper');
1488
+    }
1489
+
1490
+    /**
1491
+     * @return \OCP\Command\IBus
1492
+     */
1493
+    public function getCommandBus() {
1494
+        return $this->query('AsyncCommandBus');
1495
+    }
1496
+
1497
+    /**
1498
+     * Get the trusted domain helper
1499
+     *
1500
+     * @return TrustedDomainHelper
1501
+     */
1502
+    public function getTrustedDomainHelper() {
1503
+        return $this->query('TrustedDomainHelper');
1504
+    }
1505
+
1506
+    /**
1507
+     * Get the locking provider
1508
+     *
1509
+     * @return \OCP\Lock\ILockingProvider
1510
+     * @since 8.1.0
1511
+     */
1512
+    public function getLockingProvider() {
1513
+        return $this->query('LockingProvider');
1514
+    }
1515
+
1516
+    /**
1517
+     * @return \OCP\Files\Mount\IMountManager
1518
+     **/
1519
+    function getMountManager() {
1520
+        return $this->query('MountManager');
1521
+    }
1522
+
1523
+    /** @return \OCP\Files\Config\IUserMountCache */
1524
+    function getUserMountCache() {
1525
+        return $this->query('UserMountCache');
1526
+    }
1527
+
1528
+    /**
1529
+     * Get the MimeTypeDetector
1530
+     *
1531
+     * @return \OCP\Files\IMimeTypeDetector
1532
+     */
1533
+    public function getMimeTypeDetector() {
1534
+        return $this->query('MimeTypeDetector');
1535
+    }
1536
+
1537
+    /**
1538
+     * Get the MimeTypeLoader
1539
+     *
1540
+     * @return \OCP\Files\IMimeTypeLoader
1541
+     */
1542
+    public function getMimeTypeLoader() {
1543
+        return $this->query('MimeTypeLoader');
1544
+    }
1545
+
1546
+    /**
1547
+     * Get the manager of all the capabilities
1548
+     *
1549
+     * @return \OC\CapabilitiesManager
1550
+     */
1551
+    public function getCapabilitiesManager() {
1552
+        return $this->query('CapabilitiesManager');
1553
+    }
1554
+
1555
+    /**
1556
+     * Get the EventDispatcher
1557
+     *
1558
+     * @return EventDispatcherInterface
1559
+     * @since 8.2.0
1560
+     */
1561
+    public function getEventDispatcher() {
1562
+        return $this->query('EventDispatcher');
1563
+    }
1564
+
1565
+    /**
1566
+     * Get the Notification Manager
1567
+     *
1568
+     * @return \OCP\Notification\IManager
1569
+     * @since 8.2.0
1570
+     */
1571
+    public function getNotificationManager() {
1572
+        return $this->query('NotificationManager');
1573
+    }
1574
+
1575
+    /**
1576
+     * @return \OCP\Comments\ICommentsManager
1577
+     */
1578
+    public function getCommentsManager() {
1579
+        return $this->query('CommentsManager');
1580
+    }
1581
+
1582
+    /**
1583
+     * @return \OCA\Theming\ThemingDefaults
1584
+     */
1585
+    public function getThemingDefaults() {
1586
+        return $this->query('ThemingDefaults');
1587
+    }
1588
+
1589
+    /**
1590
+     * @return \OC\IntegrityCheck\Checker
1591
+     */
1592
+    public function getIntegrityCodeChecker() {
1593
+        return $this->query('IntegrityCodeChecker');
1594
+    }
1595
+
1596
+    /**
1597
+     * @return \OC\Session\CryptoWrapper
1598
+     */
1599
+    public function getSessionCryptoWrapper() {
1600
+        return $this->query('CryptoWrapper');
1601
+    }
1602
+
1603
+    /**
1604
+     * @return CsrfTokenManager
1605
+     */
1606
+    public function getCsrfTokenManager() {
1607
+        return $this->query('CsrfTokenManager');
1608
+    }
1609
+
1610
+    /**
1611
+     * @return Throttler
1612
+     */
1613
+    public function getBruteForceThrottler() {
1614
+        return $this->query('Throttler');
1615
+    }
1616
+
1617
+    /**
1618
+     * @return IContentSecurityPolicyManager
1619
+     */
1620
+    public function getContentSecurityPolicyManager() {
1621
+        return $this->query('ContentSecurityPolicyManager');
1622
+    }
1623
+
1624
+    /**
1625
+     * @return ContentSecurityPolicyNonceManager
1626
+     */
1627
+    public function getContentSecurityPolicyNonceManager() {
1628
+        return $this->query('ContentSecurityPolicyNonceManager');
1629
+    }
1630
+
1631
+    /**
1632
+     * Not a public API as of 8.2, wait for 9.0
1633
+     *
1634
+     * @return \OCA\Files_External\Service\BackendService
1635
+     */
1636
+    public function getStoragesBackendService() {
1637
+        return $this->query('OCA\\Files_External\\Service\\BackendService');
1638
+    }
1639
+
1640
+    /**
1641
+     * Not a public API as of 8.2, wait for 9.0
1642
+     *
1643
+     * @return \OCA\Files_External\Service\GlobalStoragesService
1644
+     */
1645
+    public function getGlobalStoragesService() {
1646
+        return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1647
+    }
1648
+
1649
+    /**
1650
+     * Not a public API as of 8.2, wait for 9.0
1651
+     *
1652
+     * @return \OCA\Files_External\Service\UserGlobalStoragesService
1653
+     */
1654
+    public function getUserGlobalStoragesService() {
1655
+        return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1656
+    }
1657
+
1658
+    /**
1659
+     * Not a public API as of 8.2, wait for 9.0
1660
+     *
1661
+     * @return \OCA\Files_External\Service\UserStoragesService
1662
+     */
1663
+    public function getUserStoragesService() {
1664
+        return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1665
+    }
1666
+
1667
+    /**
1668
+     * @return \OCP\Share\IManager
1669
+     */
1670
+    public function getShareManager() {
1671
+        return $this->query('ShareManager');
1672
+    }
1673
+
1674
+    /**
1675
+     * Returns the LDAP Provider
1676
+     *
1677
+     * @return \OCP\LDAP\ILDAPProvider
1678
+     */
1679
+    public function getLDAPProvider() {
1680
+        return $this->query('LDAPProvider');
1681
+    }
1682
+
1683
+    /**
1684
+     * @return \OCP\Settings\IManager
1685
+     */
1686
+    public function getSettingsManager() {
1687
+        return $this->query('SettingsManager');
1688
+    }
1689
+
1690
+    /**
1691
+     * @return \OCP\Files\IAppData
1692
+     */
1693
+    public function getAppDataDir($app) {
1694
+        /** @var \OC\Files\AppData\Factory $factory */
1695
+        $factory = $this->query(\OC\Files\AppData\Factory::class);
1696
+        return $factory->get($app);
1697
+    }
1698
+
1699
+    /**
1700
+     * @return \OCP\Lockdown\ILockdownManager
1701
+     */
1702
+    public function getLockdownManager() {
1703
+        return $this->query('LockdownManager');
1704
+    }
1705
+
1706
+    /**
1707
+     * @return \OCP\Federation\ICloudIdManager
1708
+     */
1709
+    public function getCloudIdManager() {
1710
+        return $this->query(ICloudIdManager::class);
1711
+    }
1712
+
1713
+    /**
1714
+     * @return \OCP\Defaults
1715
+     */
1716
+    public function getDefaults() {
1717
+        return $this->query(Defaults::class);
1718
+    }
1719 1719
 }
Please login to merge, or discard this patch.
Spacing   +96 added lines, -96 removed lines patch added patch discarded remove patch
@@ -130,7 +130,7 @@  discard block
 block discarded – undo
130 130
 		$this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
131 131
 		$this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
132 132
 
133
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
133
+		$this->registerService(\OCP\IPreview::class, function(Server $c) {
134 134
 			return new PreviewManager(
135 135
 				$c->getConfig(),
136 136
 				$c->getRootFolder(),
@@ -141,13 +141,13 @@  discard block
 block discarded – undo
141 141
 		});
142 142
 		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
143 143
 
144
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
144
+		$this->registerService(\OC\Preview\Watcher::class, function(Server $c) {
145 145
 			return new \OC\Preview\Watcher(
146 146
 				$c->getAppDataDir('preview')
147 147
 			);
148 148
 		});
149 149
 
150
-		$this->registerService('EncryptionManager', function (Server $c) {
150
+		$this->registerService('EncryptionManager', function(Server $c) {
151 151
 			$view = new View();
152 152
 			$util = new Encryption\Util(
153 153
 				$view,
@@ -165,7 +165,7 @@  discard block
 block discarded – undo
165 165
 			);
166 166
 		});
167 167
 
168
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
168
+		$this->registerService('EncryptionFileHelper', function(Server $c) {
169 169
 			$util = new Encryption\Util(
170 170
 				new View(),
171 171
 				$c->getUserManager(),
@@ -175,7 +175,7 @@  discard block
 block discarded – undo
175 175
 			return new Encryption\File($util);
176 176
 		});
177 177
 
178
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
178
+		$this->registerService('EncryptionKeyStorage', function(Server $c) {
179 179
 			$view = new View();
180 180
 			$util = new Encryption\Util(
181 181
 				$view,
@@ -186,32 +186,32 @@  discard block
 block discarded – undo
186 186
 
187 187
 			return new Encryption\Keys\Storage($view, $util);
188 188
 		});
189
-		$this->registerService('TagMapper', function (Server $c) {
189
+		$this->registerService('TagMapper', function(Server $c) {
190 190
 			return new TagMapper($c->getDatabaseConnection());
191 191
 		});
192 192
 
193
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
193
+		$this->registerService(\OCP\ITagManager::class, function(Server $c) {
194 194
 			$tagMapper = $c->query('TagMapper');
195 195
 			return new TagManager($tagMapper, $c->getUserSession());
196 196
 		});
197 197
 		$this->registerAlias('TagManager', \OCP\ITagManager::class);
198 198
 
199
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
199
+		$this->registerService('SystemTagManagerFactory', function(Server $c) {
200 200
 			$config = $c->getConfig();
201 201
 			$factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
202 202
 			/** @var \OC\SystemTag\ManagerFactory $factory */
203 203
 			$factory = new $factoryClass($this);
204 204
 			return $factory;
205 205
 		});
206
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
206
+		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function(Server $c) {
207 207
 			return $c->query('SystemTagManagerFactory')->getManager();
208 208
 		});
209 209
 		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
210 210
 
211
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
211
+		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function(Server $c) {
212 212
 			return $c->query('SystemTagManagerFactory')->getObjectMapper();
213 213
 		});
214
-		$this->registerService('RootFolder', function (Server $c) {
214
+		$this->registerService('RootFolder', function(Server $c) {
215 215
 			$manager = \OC\Files\Filesystem::getMountManager(null);
216 216
 			$view = new View();
217 217
 			$root = new Root(
@@ -239,30 +239,30 @@  discard block
 block discarded – undo
239 239
 		});
240 240
 		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
241 241
 
242
-		$this->registerService(\OCP\IUserManager::class, function (Server $c) {
242
+		$this->registerService(\OCP\IUserManager::class, function(Server $c) {
243 243
 			$config = $c->getConfig();
244 244
 			return new \OC\User\Manager($config);
245 245
 		});
246 246
 		$this->registerAlias('UserManager', \OCP\IUserManager::class);
247 247
 
248
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
248
+		$this->registerService(\OCP\IGroupManager::class, function(Server $c) {
249 249
 			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
250
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
250
+			$groupManager->listen('\OC\Group', 'preCreate', function($gid) {
251 251
 				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
252 252
 			});
253
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
253
+			$groupManager->listen('\OC\Group', 'postCreate', function(\OC\Group\Group $gid) {
254 254
 				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
255 255
 			});
256
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
256
+			$groupManager->listen('\OC\Group', 'preDelete', function(\OC\Group\Group $group) {
257 257
 				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
258 258
 			});
259
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
259
+			$groupManager->listen('\OC\Group', 'postDelete', function(\OC\Group\Group $group) {
260 260
 				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
261 261
 			});
262
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
262
+			$groupManager->listen('\OC\Group', 'preAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
263 263
 				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
264 264
 			});
265
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
265
+			$groupManager->listen('\OC\Group', 'postAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
266 266
 				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
267 267
 				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
268 268
 				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
@@ -282,11 +282,11 @@  discard block
 block discarded – undo
282 282
 			return new Store($session, $logger, $tokenProvider);
283 283
 		});
284 284
 		$this->registerAlias(IStore::class, Store::class);
285
-		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
285
+		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function(Server $c) {
286 286
 			$dbConnection = $c->getDatabaseConnection();
287 287
 			return new Authentication\Token\DefaultTokenMapper($dbConnection);
288 288
 		});
289
-		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
289
+		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function(Server $c) {
290 290
 			$mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
291 291
 			$crypto = $c->getCrypto();
292 292
 			$config = $c->getConfig();
@@ -296,7 +296,7 @@  discard block
 block discarded – undo
296 296
 		});
297 297
 		$this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
298 298
 
299
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
299
+		$this->registerService(\OCP\IUserSession::class, function(Server $c) {
300 300
 			$manager = $c->getUserManager();
301 301
 			$session = new \OC\Session\Memory('');
302 302
 			$timeFactory = new TimeFactory();
@@ -309,40 +309,40 @@  discard block
 block discarded – undo
309 309
 			}
310 310
 
311 311
 			$userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom(), $c->getLockdownManager());
312
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
312
+			$userSession->listen('\OC\User', 'preCreateUser', function($uid, $password) {
313 313
 				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
314 314
 			});
315
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
315
+			$userSession->listen('\OC\User', 'postCreateUser', function($user, $password) {
316 316
 				/** @var $user \OC\User\User */
317 317
 				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
318 318
 			});
319
-			$userSession->listen('\OC\User', 'preDelete', function ($user) {
319
+			$userSession->listen('\OC\User', 'preDelete', function($user) {
320 320
 				/** @var $user \OC\User\User */
321 321
 				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
322 322
 			});
323
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
323
+			$userSession->listen('\OC\User', 'postDelete', function($user) {
324 324
 				/** @var $user \OC\User\User */
325 325
 				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
326 326
 			});
327
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
327
+			$userSession->listen('\OC\User', 'preSetPassword', function($user, $password, $recoveryPassword) {
328 328
 				/** @var $user \OC\User\User */
329 329
 				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
330 330
 			});
331
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
331
+			$userSession->listen('\OC\User', 'postSetPassword', function($user, $password, $recoveryPassword) {
332 332
 				/** @var $user \OC\User\User */
333 333
 				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
334 334
 			});
335
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
335
+			$userSession->listen('\OC\User', 'preLogin', function($uid, $password) {
336 336
 				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
337 337
 			});
338
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
338
+			$userSession->listen('\OC\User', 'postLogin', function($user, $password) {
339 339
 				/** @var $user \OC\User\User */
340 340
 				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
341 341
 			});
342
-			$userSession->listen('\OC\User', 'logout', function () {
342
+			$userSession->listen('\OC\User', 'logout', function() {
343 343
 				\OC_Hook::emit('OC_User', 'logout', array());
344 344
 			});
345
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value) {
345
+			$userSession->listen('\OC\User', 'changeUser', function($user, $feature, $value) {
346 346
 				/** @var $user \OC\User\User */
347 347
 				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value));
348 348
 			});
@@ -350,14 +350,14 @@  discard block
 block discarded – undo
350 350
 		});
351 351
 		$this->registerAlias('UserSession', \OCP\IUserSession::class);
352 352
 
353
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
353
+		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function(Server $c) {
354 354
 			return new \OC\Authentication\TwoFactorAuth\Manager($c->getAppManager(), $c->getSession(), $c->getConfig(), $c->getActivityManager(), $c->getLogger());
355 355
 		});
356 356
 
357 357
 		$this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
358 358
 		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
359 359
 
360
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
360
+		$this->registerService(\OC\AllConfig::class, function(Server $c) {
361 361
 			return new \OC\AllConfig(
362 362
 				$c->getSystemConfig()
363 363
 			);
@@ -365,17 +365,17 @@  discard block
 block discarded – undo
365 365
 		$this->registerAlias('AllConfig', \OC\AllConfig::class);
366 366
 		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
367 367
 
368
-		$this->registerService('SystemConfig', function ($c) use ($config) {
368
+		$this->registerService('SystemConfig', function($c) use ($config) {
369 369
 			return new \OC\SystemConfig($config);
370 370
 		});
371 371
 
372
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
372
+		$this->registerService(\OC\AppConfig::class, function(Server $c) {
373 373
 			return new \OC\AppConfig($c->getDatabaseConnection());
374 374
 		});
375 375
 		$this->registerAlias('AppConfig', \OC\AppConfig::class);
376 376
 		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
377 377
 
378
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
378
+		$this->registerService(\OCP\L10N\IFactory::class, function(Server $c) {
379 379
 			return new \OC\L10N\Factory(
380 380
 				$c->getConfig(),
381 381
 				$c->getRequest(),
@@ -385,7 +385,7 @@  discard block
 block discarded – undo
385 385
 		});
386 386
 		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
387 387
 
388
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
388
+		$this->registerService(\OCP\IURLGenerator::class, function(Server $c) {
389 389
 			$config = $c->getConfig();
390 390
 			$cacheFactory = $c->getMemCacheFactory();
391 391
 			return new \OC\URLGenerator(
@@ -395,10 +395,10 @@  discard block
 block discarded – undo
395 395
 		});
396 396
 		$this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
397 397
 
398
-		$this->registerService('AppHelper', function ($c) {
398
+		$this->registerService('AppHelper', function($c) {
399 399
 			return new \OC\AppHelper();
400 400
 		});
401
-		$this->registerService('AppFetcher', function ($c) {
401
+		$this->registerService('AppFetcher', function($c) {
402 402
 			return new AppFetcher(
403 403
 				$this->getAppDataDir('appstore'),
404 404
 				$this->getHTTPClientService(),
@@ -406,7 +406,7 @@  discard block
 block discarded – undo
406 406
 				$this->getConfig()
407 407
 			);
408 408
 		});
409
-		$this->registerService('CategoryFetcher', function ($c) {
409
+		$this->registerService('CategoryFetcher', function($c) {
410 410
 			return new CategoryFetcher(
411 411
 				$this->getAppDataDir('appstore'),
412 412
 				$this->getHTTPClientService(),
@@ -415,21 +415,21 @@  discard block
 block discarded – undo
415 415
 			);
416 416
 		});
417 417
 
418
-		$this->registerService(\OCP\ICache::class, function ($c) {
418
+		$this->registerService(\OCP\ICache::class, function($c) {
419 419
 			return new Cache\File();
420 420
 		});
421 421
 		$this->registerAlias('UserCache', \OCP\ICache::class);
422 422
 
423
-		$this->registerService(Factory::class, function (Server $c) {
423
+		$this->registerService(Factory::class, function(Server $c) {
424 424
 			$config = $c->getConfig();
425 425
 
426 426
 			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
427 427
 				$v = \OC_App::getAppVersions();
428
-				$v['core'] = md5(file_get_contents(\OC::$SERVERROOT . '/version.php'));
428
+				$v['core'] = md5(file_get_contents(\OC::$SERVERROOT.'/version.php'));
429 429
 				$version = implode(',', $v);
430 430
 				$instanceId = \OC_Util::getInstanceId();
431 431
 				$path = \OC::$SERVERROOT;
432
-				$prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . \OC::$WEBROOT);
432
+				$prefix = md5($instanceId.'-'.$version.'-'.$path.'-'.\OC::$WEBROOT);
433 433
 				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
434 434
 					$config->getSystemValue('memcache.local', null),
435 435
 					$config->getSystemValue('memcache.distributed', null),
@@ -446,12 +446,12 @@  discard block
 block discarded – undo
446 446
 		$this->registerAlias('MemCacheFactory', Factory::class);
447 447
 		$this->registerAlias(ICacheFactory::class, Factory::class);
448 448
 
449
-		$this->registerService('RedisFactory', function (Server $c) {
449
+		$this->registerService('RedisFactory', function(Server $c) {
450 450
 			$systemConfig = $c->getSystemConfig();
451 451
 			return new RedisFactory($systemConfig);
452 452
 		});
453 453
 
454
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
454
+		$this->registerService(\OCP\Activity\IManager::class, function(Server $c) {
455 455
 			return new \OC\Activity\Manager(
456 456
 				$c->getRequest(),
457 457
 				$c->getUserSession(),
@@ -461,14 +461,14 @@  discard block
 block discarded – undo
461 461
 		});
462 462
 		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
463 463
 
464
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
464
+		$this->registerService(\OCP\Activity\IEventMerger::class, function(Server $c) {
465 465
 			return new \OC\Activity\EventMerger(
466 466
 				$c->getL10N('lib')
467 467
 			);
468 468
 		});
469 469
 		$this->registerAlias(IValidator::class, Validator::class);
470 470
 
471
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
471
+		$this->registerService(\OCP\IAvatarManager::class, function(Server $c) {
472 472
 			return new AvatarManager(
473 473
 				$c->getUserManager(),
474 474
 				$c->getAppDataDir('avatar'),
@@ -479,7 +479,7 @@  discard block
 block discarded – undo
479 479
 		});
480 480
 		$this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
481 481
 
482
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
482
+		$this->registerService(\OCP\ILogger::class, function(Server $c) {
483 483
 			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
484 484
 			$logger = Log::getLogClass($logType);
485 485
 			call_user_func(array($logger, 'init'));
@@ -488,7 +488,7 @@  discard block
 block discarded – undo
488 488
 		});
489 489
 		$this->registerAlias('Logger', \OCP\ILogger::class);
490 490
 
491
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
491
+		$this->registerService(\OCP\BackgroundJob\IJobList::class, function(Server $c) {
492 492
 			$config = $c->getConfig();
493 493
 			return new \OC\BackgroundJob\JobList(
494 494
 				$c->getDatabaseConnection(),
@@ -498,7 +498,7 @@  discard block
 block discarded – undo
498 498
 		});
499 499
 		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
500 500
 
501
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
501
+		$this->registerService(\OCP\Route\IRouter::class, function(Server $c) {
502 502
 			$cacheFactory = $c->getMemCacheFactory();
503 503
 			$logger = $c->getLogger();
504 504
 			if ($cacheFactory->isAvailable()) {
@@ -510,32 +510,32 @@  discard block
 block discarded – undo
510 510
 		});
511 511
 		$this->registerAlias('Router', \OCP\Route\IRouter::class);
512 512
 
513
-		$this->registerService(\OCP\ISearch::class, function ($c) {
513
+		$this->registerService(\OCP\ISearch::class, function($c) {
514 514
 			return new Search();
515 515
 		});
516 516
 		$this->registerAlias('Search', \OCP\ISearch::class);
517 517
 
518
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
518
+		$this->registerService(\OCP\Security\ISecureRandom::class, function($c) {
519 519
 			return new SecureRandom();
520 520
 		});
521 521
 		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
522 522
 
523
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
523
+		$this->registerService(\OCP\Security\ICrypto::class, function(Server $c) {
524 524
 			return new Crypto($c->getConfig(), $c->getSecureRandom());
525 525
 		});
526 526
 		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
527 527
 
528
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
528
+		$this->registerService(\OCP\Security\IHasher::class, function(Server $c) {
529 529
 			return new Hasher($c->getConfig());
530 530
 		});
531 531
 		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
532 532
 
533
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
533
+		$this->registerService(\OCP\Security\ICredentialsManager::class, function(Server $c) {
534 534
 			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
535 535
 		});
536 536
 		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
537 537
 
538
-		$this->registerService(IDBConnection::class, function (Server $c) {
538
+		$this->registerService(IDBConnection::class, function(Server $c) {
539 539
 			$systemConfig = $c->getSystemConfig();
540 540
 			$factory = new \OC\DB\ConnectionFactory($systemConfig);
541 541
 			$type = $systemConfig->getValue('dbtype', 'sqlite');
@@ -549,7 +549,7 @@  discard block
 block discarded – undo
549 549
 		});
550 550
 		$this->registerAlias('DatabaseConnection', IDBConnection::class);
551 551
 
552
-		$this->registerService('HTTPHelper', function (Server $c) {
552
+		$this->registerService('HTTPHelper', function(Server $c) {
553 553
 			$config = $c->getConfig();
554 554
 			return new HTTPHelper(
555 555
 				$config,
@@ -557,7 +557,7 @@  discard block
 block discarded – undo
557 557
 			);
558 558
 		});
559 559
 
560
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
560
+		$this->registerService(\OCP\Http\Client\IClientService::class, function(Server $c) {
561 561
 			$user = \OC_User::getUser();
562 562
 			$uid = $user ? $user : null;
563 563
 			return new ClientService(
@@ -567,7 +567,7 @@  discard block
 block discarded – undo
567 567
 		});
568 568
 		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
569 569
 
570
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
570
+		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function(Server $c) {
571 571
 			if ($c->getSystemConfig()->getValue('debug', false)) {
572 572
 				return new EventLogger();
573 573
 			} else {
@@ -576,7 +576,7 @@  discard block
 block discarded – undo
576 576
 		});
577 577
 		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
578 578
 
579
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
579
+		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function(Server $c) {
580 580
 			if ($c->getSystemConfig()->getValue('debug', false)) {
581 581
 				return new QueryLogger();
582 582
 			} else {
@@ -585,7 +585,7 @@  discard block
 block discarded – undo
585 585
 		});
586 586
 		$this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
587 587
 
588
-		$this->registerService(TempManager::class, function (Server $c) {
588
+		$this->registerService(TempManager::class, function(Server $c) {
589 589
 			return new TempManager(
590 590
 				$c->getLogger(),
591 591
 				$c->getConfig()
@@ -594,7 +594,7 @@  discard block
 block discarded – undo
594 594
 		$this->registerAlias('TempManager', TempManager::class);
595 595
 		$this->registerAlias(ITempManager::class, TempManager::class);
596 596
 
597
-		$this->registerService(AppManager::class, function (Server $c) {
597
+		$this->registerService(AppManager::class, function(Server $c) {
598 598
 			return new \OC\App\AppManager(
599 599
 				$c->getUserSession(),
600 600
 				$c->getAppConfig(),
@@ -606,7 +606,7 @@  discard block
 block discarded – undo
606 606
 		$this->registerAlias('AppManager', AppManager::class);
607 607
 		$this->registerAlias(IAppManager::class, AppManager::class);
608 608
 
609
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
609
+		$this->registerService(\OCP\IDateTimeZone::class, function(Server $c) {
610 610
 			return new DateTimeZone(
611 611
 				$c->getConfig(),
612 612
 				$c->getSession()
@@ -614,7 +614,7 @@  discard block
 block discarded – undo
614 614
 		});
615 615
 		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
616 616
 
617
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
617
+		$this->registerService(\OCP\IDateTimeFormatter::class, function(Server $c) {
618 618
 			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
619 619
 
620 620
 			return new DateTimeFormatter(
@@ -624,7 +624,7 @@  discard block
 block discarded – undo
624 624
 		});
625 625
 		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
626 626
 
627
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
627
+		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function(Server $c) {
628 628
 			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
629 629
 			$listener = new UserMountCacheListener($mountCache);
630 630
 			$listener->listen($c->getUserManager());
@@ -632,10 +632,10 @@  discard block
 block discarded – undo
632 632
 		});
633 633
 		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
634 634
 
635
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
635
+		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function(Server $c) {
636 636
 			$loader = \OC\Files\Filesystem::getLoader();
637 637
 			$mountCache = $c->query('UserMountCache');
638
-			$manager =  new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
638
+			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
639 639
 
640 640
 			// builtin providers
641 641
 
@@ -648,14 +648,14 @@  discard block
 block discarded – undo
648 648
 		});
649 649
 		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
650 650
 
651
-		$this->registerService('IniWrapper', function ($c) {
651
+		$this->registerService('IniWrapper', function($c) {
652 652
 			return new IniGetWrapper();
653 653
 		});
654
-		$this->registerService('AsyncCommandBus', function (Server $c) {
654
+		$this->registerService('AsyncCommandBus', function(Server $c) {
655 655
 			$jobList = $c->getJobList();
656 656
 			return new AsyncBus($jobList);
657 657
 		});
658
-		$this->registerService('TrustedDomainHelper', function ($c) {
658
+		$this->registerService('TrustedDomainHelper', function($c) {
659 659
 			return new TrustedDomainHelper($this->getConfig());
660 660
 		});
661 661
 		$this->registerService('Throttler', function(Server $c) {
@@ -666,10 +666,10 @@  discard block
 block discarded – undo
666 666
 				$c->getConfig()
667 667
 			);
668 668
 		});
669
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
669
+		$this->registerService('IntegrityCodeChecker', function(Server $c) {
670 670
 			// IConfig and IAppManager requires a working database. This code
671 671
 			// might however be called when ownCloud is not yet setup.
672
-			if(\OC::$server->getSystemConfig()->getValue('installed', false)) {
672
+			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
673 673
 				$config = $c->getConfig();
674 674
 				$appManager = $c->getAppManager();
675 675
 			} else {
@@ -687,7 +687,7 @@  discard block
 block discarded – undo
687 687
 					$c->getTempManager()
688 688
 			);
689 689
 		});
690
-		$this->registerService(\OCP\IRequest::class, function ($c) {
690
+		$this->registerService(\OCP\IRequest::class, function($c) {
691 691
 			if (isset($this['urlParams'])) {
692 692
 				$urlParams = $this['urlParams'];
693 693
 			} else {
@@ -723,7 +723,7 @@  discard block
 block discarded – undo
723 723
 		});
724 724
 		$this->registerAlias('Request', \OCP\IRequest::class);
725 725
 
726
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
726
+		$this->registerService(\OCP\Mail\IMailer::class, function(Server $c) {
727 727
 			return new Mailer(
728 728
 				$c->getConfig(),
729 729
 				$c->getLogger(),
@@ -735,14 +735,14 @@  discard block
 block discarded – undo
735 735
 		$this->registerService('LDAPProvider', function(Server $c) {
736 736
 			$config = $c->getConfig();
737 737
 			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
738
-			if(is_null($factoryClass)) {
738
+			if (is_null($factoryClass)) {
739 739
 				throw new \Exception('ldapProviderFactory not set');
740 740
 			}
741 741
 			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
742 742
 			$factory = new $factoryClass($this);
743 743
 			return $factory->getLDAPProvider();
744 744
 		});
745
-		$this->registerService('LockingProvider', function (Server $c) {
745
+		$this->registerService('LockingProvider', function(Server $c) {
746 746
 			$ini = $c->getIniWrapper();
747 747
 			$config = $c->getConfig();
748 748
 			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
@@ -758,37 +758,37 @@  discard block
 block discarded – undo
758 758
 			return new NoopLockingProvider();
759 759
 		});
760 760
 
761
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
761
+		$this->registerService(\OCP\Files\Mount\IMountManager::class, function() {
762 762
 			return new \OC\Files\Mount\Manager();
763 763
 		});
764 764
 		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
765 765
 
766
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
766
+		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function(Server $c) {
767 767
 			return new \OC\Files\Type\Detection(
768 768
 				$c->getURLGenerator(),
769 769
 				\OC::$configDir,
770
-				\OC::$SERVERROOT . '/resources/config/'
770
+				\OC::$SERVERROOT.'/resources/config/'
771 771
 			);
772 772
 		});
773 773
 		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
774 774
 
775
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
775
+		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function(Server $c) {
776 776
 			return new \OC\Files\Type\Loader(
777 777
 				$c->getDatabaseConnection()
778 778
 			);
779 779
 		});
780 780
 		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
781 781
 
782
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
782
+		$this->registerService(\OCP\Notification\IManager::class, function(Server $c) {
783 783
 			return new Manager(
784 784
 				$c->query(IValidator::class)
785 785
 			);
786 786
 		});
787 787
 		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
788 788
 
789
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
789
+		$this->registerService(\OC\CapabilitiesManager::class, function(Server $c) {
790 790
 			$manager = new \OC\CapabilitiesManager($c->getLogger());
791
-			$manager->registerCapability(function () use ($c) {
791
+			$manager->registerCapability(function() use ($c) {
792 792
 				return new \OC\OCS\CoreCapabilities($c->getConfig());
793 793
 			});
794 794
 			return $manager;
@@ -830,13 +830,13 @@  discard block
 block discarded – undo
830 830
 			}
831 831
 			return new \OC_Defaults();
832 832
 		});
833
-		$this->registerService(EventDispatcher::class, function () {
833
+		$this->registerService(EventDispatcher::class, function() {
834 834
 			return new EventDispatcher();
835 835
 		});
836 836
 		$this->registerAlias('EventDispatcher', EventDispatcher::class);
837 837
 		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
838 838
 
839
-		$this->registerService('CryptoWrapper', function (Server $c) {
839
+		$this->registerService('CryptoWrapper', function(Server $c) {
840 840
 			// FIXME: Instantiiated here due to cyclic dependency
841 841
 			$request = new Request(
842 842
 				[
@@ -861,7 +861,7 @@  discard block
 block discarded – undo
861 861
 				$request
862 862
 			);
863 863
 		});
864
-		$this->registerService('CsrfTokenManager', function (Server $c) {
864
+		$this->registerService('CsrfTokenManager', function(Server $c) {
865 865
 			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
866 866
 
867 867
 			return new CsrfTokenManager(
@@ -869,10 +869,10 @@  discard block
 block discarded – undo
869 869
 				$c->query(SessionStorage::class)
870 870
 			);
871 871
 		});
872
-		$this->registerService(SessionStorage::class, function (Server $c) {
872
+		$this->registerService(SessionStorage::class, function(Server $c) {
873 873
 			return new SessionStorage($c->getSession());
874 874
 		});
875
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
875
+		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function(Server $c) {
876 876
 			return new ContentSecurityPolicyManager();
877 877
 		});
878 878
 		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
@@ -923,25 +923,25 @@  discard block
 block discarded – undo
923 923
 			);
924 924
 			return $manager;
925 925
 		});
926
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
926
+		$this->registerService(\OC\Files\AppData\Factory::class, function(Server $c) {
927 927
 			return new \OC\Files\AppData\Factory(
928 928
 				$c->getRootFolder(),
929 929
 				$c->getSystemConfig()
930 930
 			);
931 931
 		});
932 932
 
933
-		$this->registerService('LockdownManager', function (Server $c) {
933
+		$this->registerService('LockdownManager', function(Server $c) {
934 934
 			return new LockdownManager(function() use ($c) {
935 935
 				return $c->getSession();
936 936
 			});
937 937
 		});
938 938
 
939
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
939
+		$this->registerService(ICloudIdManager::class, function(Server $c) {
940 940
 			return new CloudIdManager();
941 941
 		});
942 942
 
943 943
 		/* To trick DI since we don't extend the DIContainer here */
944
-		$this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
944
+		$this->registerService(CleanPreviewsBackgroundJob::class, function(Server $c) {
945 945
 			return new CleanPreviewsBackgroundJob(
946 946
 				$c->getRootFolder(),
947 947
 				$c->getLogger(),
@@ -956,7 +956,7 @@  discard block
 block discarded – undo
956 956
 		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
957 957
 		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
958 958
 
959
-		$this->registerService(Defaults::class, function (Server $c) {
959
+		$this->registerService(Defaults::class, function(Server $c) {
960 960
 			return new Defaults(
961 961
 				$c->getThemingDefaults()
962 962
 			);
@@ -1102,7 +1102,7 @@  discard block
 block discarded – undo
1102 1102
 	 * @deprecated since 9.2.0 use IAppData
1103 1103
 	 */
1104 1104
 	public function getAppFolder() {
1105
-		$dir = '/' . \OC_App::getCurrentApp();
1105
+		$dir = '/'.\OC_App::getCurrentApp();
1106 1106
 		$root = $this->getRootFolder();
1107 1107
 		if (!$root->nodeExists($dir)) {
1108 1108
 			$folder = $root->newFolder($dir);
Please login to merge, or discard this patch.
lib/private/Mail/EMailTemplate.php 1 patch
Indentation   +169 added lines, -169 removed lines patch added patch discarded remove patch
@@ -38,25 +38,25 @@  discard block
 block discarded – undo
38 38
  * @package OC\Mail
39 39
  */
40 40
 class EMailTemplate implements IEMailTemplate {
41
-	/** @var Defaults */
42
-	protected $themingDefaults;
43
-	/** @var IURLGenerator */
44
-	protected $urlGenerator;
45
-	/** @var IL10N */
46
-	protected $l10n;
47
-
48
-	/** @var string */
49
-	protected $htmlBody = '';
50
-	/** @var string */
51
-	protected $plainBody = '';
52
-	/** @var bool indicated if the footer is added */
53
-	protected $headerAdded = false;
54
-	/** @var bool indicated if the body is already opened */
55
-	protected $bodyOpened = false;
56
-	/** @var bool indicated if the footer is added */
57
-	protected $footerAdded = false;
58
-
59
-	protected $head = <<<EOF
41
+    /** @var Defaults */
42
+    protected $themingDefaults;
43
+    /** @var IURLGenerator */
44
+    protected $urlGenerator;
45
+    /** @var IL10N */
46
+    protected $l10n;
47
+
48
+    /** @var string */
49
+    protected $htmlBody = '';
50
+    /** @var string */
51
+    protected $plainBody = '';
52
+    /** @var bool indicated if the footer is added */
53
+    protected $headerAdded = false;
54
+    /** @var bool indicated if the body is already opened */
55
+    protected $bodyOpened = false;
56
+    /** @var bool indicated if the footer is added */
57
+    protected $footerAdded = false;
58
+
59
+    protected $head = <<<EOF
60 60
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
61 61
 <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en" style="-webkit-font-smoothing:antialiased;background:#f3f3f3!important">
62 62
 <head>
@@ -74,7 +74,7 @@  discard block
 block discarded – undo
74 74
 				<center data-parsed="" style="min-width:580px;width:100%">
75 75
 EOF;
76 76
 
77
-	protected $tail = <<<EOF
77
+    protected $tail = <<<EOF
78 78
 					</center>
79 79
 				</td>
80 80
 			</tr>
@@ -85,7 +85,7 @@  discard block
 block discarded – undo
85 85
 </html>
86 86
 EOF;
87 87
 
88
-	protected $header = <<<EOF
88
+    protected $header = <<<EOF
89 89
 <table align="center" class="wrapper header float-center" style="Margin:0 auto;background:#8a8a8a;background-color:%s;border-collapse:collapse;border-spacing:0;float:none;margin:0 auto;padding:0;text-align:center;vertical-align:top;width:100%%">
90 90
 	<tr style="padding:0;text-align:left;vertical-align:top">
91 91
 		<td class="wrapper-inner" style="-moz-hyphens:auto;-webkit-hyphens:auto;Margin:0;border-collapse:collapse!important;color:#0a0a0a;font-family:Lucida Grande,Geneva,Verdana,sans-serif;font-size:16px;font-weight:400;hyphens:auto;line-height:1.3;margin:0;padding:20px;text-align:left;vertical-align:top;word-wrap:break-word">
@@ -118,7 +118,7 @@  discard block
 block discarded – undo
118 118
 </table>
119 119
 EOF;
120 120
 
121
-	protected $heading = <<<EOF
121
+    protected $heading = <<<EOF
122 122
 <table align="center" class="container main-heading float-center" style="Margin:0 auto;background:0 0!important;border-collapse:collapse;border-spacing:0;float:none;margin:0 auto;padding:0;text-align:center;vertical-align:top;width:580px">
123 123
 	<tbody>
124 124
 	<tr style="padding:0;text-align:left;vertical-align:top">
@@ -137,7 +137,7 @@  discard block
 block discarded – undo
137 137
 </table>
138 138
 EOF;
139 139
 
140
-	protected $bodyBegin = <<<EOF
140
+    protected $bodyBegin = <<<EOF
141 141
 <table align="center" class="wrapper content float-center" style="Margin:0 auto;border-collapse:collapse;border-spacing:0;float:none;margin:0 auto;padding:0;text-align:center;vertical-align:top;width:100%">
142 142
 	<tr style="padding:0;text-align:left;vertical-align:top">
143 143
 		<td class="wrapper-inner" style="-moz-hyphens:auto;-webkit-hyphens:auto;Margin:0;border-collapse:collapse!important;color:#0a0a0a;font-family:Lucida Grande,Geneva,Verdana,sans-serif;font-size:16px;font-weight:400;hyphens:auto;line-height:1.3;margin:0;padding:0;text-align:left;vertical-align:top;word-wrap:break-word">
@@ -154,7 +154,7 @@  discard block
 block discarded – undo
154 154
 						</table>
155 155
 EOF;
156 156
 
157
-	protected $bodyText = <<<EOF
157
+    protected $bodyText = <<<EOF
158 158
 <table class="row description" style="border-collapse:collapse;border-spacing:0;display:table;padding:0;position:relative;text-align:left;vertical-align:top;width:100%%">
159 159
 	<tbody>
160 160
 	<tr style="padding:0;text-align:left;vertical-align:top">
@@ -173,7 +173,7 @@  discard block
 block discarded – undo
173 173
 </table>
174 174
 EOF;
175 175
 
176
-	protected $buttonGroup = <<<EOF
176
+    protected $buttonGroup = <<<EOF
177 177
 <table class="spacer" style="border-collapse:collapse;border-spacing:0;padding:0;text-align:left;vertical-align:top;width:100%%">
178 178
 	<tbody>
179 179
 	<tr style="padding:0;text-align:left;vertical-align:top">
@@ -226,7 +226,7 @@  discard block
 block discarded – undo
226 226
 </table>
227 227
 EOF;
228 228
 
229
-	protected $bodyEnd = <<<EOF
229
+    protected $bodyEnd = <<<EOF
230 230
 
231 231
 					</td>
232 232
 				</tr>
@@ -237,7 +237,7 @@  discard block
 block discarded – undo
237 237
 </table>
238 238
 EOF;
239 239
 
240
-	protected $footer = <<<EOF
240
+    protected $footer = <<<EOF
241 241
 <table class="spacer float-center" style="Margin:0 auto;border-collapse:collapse;border-spacing:0;float:none;margin:0 auto;padding:0;text-align:center;vertical-align:top;width:100%%">
242 242
 	<tbody>
243 243
 	<tr style="padding:0;text-align:left;vertical-align:top">
@@ -263,146 +263,146 @@  discard block
 block discarded – undo
263 263
 </table>
264 264
 EOF;
265 265
 
266
-	/**
267
-	 * @param Defaults $themingDefaults
268
-	 * @param IURLGenerator $urlGenerator
269
-	 * @param IL10N $l10n
270
-	 */
271
-	public function __construct(Defaults $themingDefaults,
272
-								IURLGenerator $urlGenerator,
273
-								IL10N $l10n) {
274
-		$this->themingDefaults = $themingDefaults;
275
-		$this->urlGenerator = $urlGenerator;
276
-		$this->l10n = $l10n;
277
-		$this->htmlBody .= $this->head;
278
-	}
279
-
280
-	/**
281
-	 * Adds a header to the email
282
-	 */
283
-	public function addHeader() {
284
-		if ($this->headerAdded) {
285
-			return;
286
-		}
287
-		$this->headerAdded = true;
288
-
289
-		$logoUrl = $this->urlGenerator->getAbsoluteURL($this->themingDefaults->getLogo()) . '?v='. $this->themingDefaults->getCacheBusterCounter();
290
-		$this->htmlBody .= vsprintf($this->header, [$this->themingDefaults->getColorPrimary(), $logoUrl]);
291
-	}
292
-
293
-	/**
294
-	 * Adds a heading to the email
295
-	 *
296
-	 * @param string $title
297
-	 */
298
-	public function addHeading($title) {
299
-		if ($this->footerAdded) {
300
-			return;
301
-		}
302
-
303
-		$this->htmlBody .= vsprintf($this->heading, [$title]);
304
-		$this->plainBody .= $title . PHP_EOL . PHP_EOL;
305
-	}
306
-
307
-	/**
308
-	 * Adds a paragraph to the body of the email
309
-	 *
310
-	 * @param string $text
311
-	 */
312
-	public function addBodyText($text) {
313
-		if ($this->footerAdded) {
314
-			return;
315
-		}
316
-
317
-		if (!$this->bodyOpened) {
318
-			$this->htmlBody .= $this->bodyBegin;
319
-			$this->bodyOpened = true;
320
-		}
321
-
322
-		$this->htmlBody .= vsprintf($this->bodyText, [$text]);
323
-		$this->plainBody .= $text . PHP_EOL . PHP_EOL;
324
-	}
325
-
326
-	/**
327
-	 * Adds a button group of two buttons to the body of the email
328
-	 *
329
-	 * @param string $textLeft Text of left button
330
-	 * @param string $urlLeft URL of left button
331
-	 * @param string $textRight Text of right button
332
-	 * @param string $urlRight URL of right button
333
-	 */
334
-	public function addBodyButtonGroup($textLeft, $urlLeft, $textRight, $urlRight) {
335
-		if ($this->footerAdded) {
336
-			return;
337
-		}
338
-
339
-		if (!$this->bodyOpened) {
340
-			$this->htmlBody .= $this->bodyBegin;
341
-			$this->bodyOpened = true;
342
-		}
343
-
344
-		$color = $this->themingDefaults->getColorPrimary();
345
-		$this->htmlBody .= vsprintf($this->buttonGroup, [$color, $color, $urlLeft, $color, $textLeft, $urlRight, $textRight]);
346
-		$this->plainBody .= $textLeft . ': ' . $urlLeft . PHP_EOL;
347
-		$this->plainBody .= $textRight . ': ' . $urlRight . PHP_EOL . PHP_EOL;
348
-
349
-	}
350
-
351
-	/**
352
-	 * Adds a logo and a text to the footer. <br> in the text will be replaced by new lines in the plain text email
353
-	 *
354
-	 * @param string $text
355
-	 */
356
-	public function addFooter($text = '') {
357
-		if($text === '') {
358
-			$text = $this->themingDefaults->getName() . ' - ' . $this->themingDefaults->getSlogan() . '<br>' . $this->l10n->t('This is an automatically generated email, please do not reply.');
359
-		}
360
-
361
-		if ($this->footerAdded) {
362
-			return;
363
-		}
364
-		$this->footerAdded = true;
365
-
366
-		if ($this->bodyOpened) {
367
-			$this->htmlBody .= $this->bodyEnd;
368
-			$this->bodyOpened = false;
369
-		}
370
-
371
-		$this->htmlBody .= vsprintf($this->footer, [$text]);
372
-		$this->htmlBody .= $this->tail;
373
-		$this->plainBody .= '--' . PHP_EOL;
374
-		$this->plainBody .= str_replace('<br>', PHP_EOL, $text);
375
-	}
376
-
377
-	/**
378
-	 * Returns the rendered HTML email as string
379
-	 *
380
-	 * @return string
381
-	 */
382
-	public function renderHTML() {
383
-		if (!$this->footerAdded) {
384
-			$this->footerAdded = true;
385
-			if ($this->bodyOpened) {
386
-				$this->htmlBody .= $this->bodyEnd;
387
-			}
388
-			$this->htmlBody .= $this->tail;
389
-		}
390
-		return $this->htmlBody;
391
-	}
392
-
393
-	/**
394
-	 * Returns the rendered plain text email as string
395
-	 *
396
-	 * @return string
397
-	 */
398
-	public function renderText() {
399
-		if (!$this->footerAdded) {
400
-			$this->footerAdded = true;
401
-			if ($this->bodyOpened) {
402
-				$this->htmlBody .= $this->bodyEnd;
403
-			}
404
-			$this->htmlBody .= $this->tail;
405
-		}
406
-		return $this->plainBody;
407
-	}
266
+    /**
267
+     * @param Defaults $themingDefaults
268
+     * @param IURLGenerator $urlGenerator
269
+     * @param IL10N $l10n
270
+     */
271
+    public function __construct(Defaults $themingDefaults,
272
+                                IURLGenerator $urlGenerator,
273
+                                IL10N $l10n) {
274
+        $this->themingDefaults = $themingDefaults;
275
+        $this->urlGenerator = $urlGenerator;
276
+        $this->l10n = $l10n;
277
+        $this->htmlBody .= $this->head;
278
+    }
279
+
280
+    /**
281
+     * Adds a header to the email
282
+     */
283
+    public function addHeader() {
284
+        if ($this->headerAdded) {
285
+            return;
286
+        }
287
+        $this->headerAdded = true;
288
+
289
+        $logoUrl = $this->urlGenerator->getAbsoluteURL($this->themingDefaults->getLogo()) . '?v='. $this->themingDefaults->getCacheBusterCounter();
290
+        $this->htmlBody .= vsprintf($this->header, [$this->themingDefaults->getColorPrimary(), $logoUrl]);
291
+    }
292
+
293
+    /**
294
+     * Adds a heading to the email
295
+     *
296
+     * @param string $title
297
+     */
298
+    public function addHeading($title) {
299
+        if ($this->footerAdded) {
300
+            return;
301
+        }
302
+
303
+        $this->htmlBody .= vsprintf($this->heading, [$title]);
304
+        $this->plainBody .= $title . PHP_EOL . PHP_EOL;
305
+    }
306
+
307
+    /**
308
+     * Adds a paragraph to the body of the email
309
+     *
310
+     * @param string $text
311
+     */
312
+    public function addBodyText($text) {
313
+        if ($this->footerAdded) {
314
+            return;
315
+        }
316
+
317
+        if (!$this->bodyOpened) {
318
+            $this->htmlBody .= $this->bodyBegin;
319
+            $this->bodyOpened = true;
320
+        }
321
+
322
+        $this->htmlBody .= vsprintf($this->bodyText, [$text]);
323
+        $this->plainBody .= $text . PHP_EOL . PHP_EOL;
324
+    }
325
+
326
+    /**
327
+     * Adds a button group of two buttons to the body of the email
328
+     *
329
+     * @param string $textLeft Text of left button
330
+     * @param string $urlLeft URL of left button
331
+     * @param string $textRight Text of right button
332
+     * @param string $urlRight URL of right button
333
+     */
334
+    public function addBodyButtonGroup($textLeft, $urlLeft, $textRight, $urlRight) {
335
+        if ($this->footerAdded) {
336
+            return;
337
+        }
338
+
339
+        if (!$this->bodyOpened) {
340
+            $this->htmlBody .= $this->bodyBegin;
341
+            $this->bodyOpened = true;
342
+        }
343
+
344
+        $color = $this->themingDefaults->getColorPrimary();
345
+        $this->htmlBody .= vsprintf($this->buttonGroup, [$color, $color, $urlLeft, $color, $textLeft, $urlRight, $textRight]);
346
+        $this->plainBody .= $textLeft . ': ' . $urlLeft . PHP_EOL;
347
+        $this->plainBody .= $textRight . ': ' . $urlRight . PHP_EOL . PHP_EOL;
348
+
349
+    }
350
+
351
+    /**
352
+     * Adds a logo and a text to the footer. <br> in the text will be replaced by new lines in the plain text email
353
+     *
354
+     * @param string $text
355
+     */
356
+    public function addFooter($text = '') {
357
+        if($text === '') {
358
+            $text = $this->themingDefaults->getName() . ' - ' . $this->themingDefaults->getSlogan() . '<br>' . $this->l10n->t('This is an automatically generated email, please do not reply.');
359
+        }
360
+
361
+        if ($this->footerAdded) {
362
+            return;
363
+        }
364
+        $this->footerAdded = true;
365
+
366
+        if ($this->bodyOpened) {
367
+            $this->htmlBody .= $this->bodyEnd;
368
+            $this->bodyOpened = false;
369
+        }
370
+
371
+        $this->htmlBody .= vsprintf($this->footer, [$text]);
372
+        $this->htmlBody .= $this->tail;
373
+        $this->plainBody .= '--' . PHP_EOL;
374
+        $this->plainBody .= str_replace('<br>', PHP_EOL, $text);
375
+    }
376
+
377
+    /**
378
+     * Returns the rendered HTML email as string
379
+     *
380
+     * @return string
381
+     */
382
+    public function renderHTML() {
383
+        if (!$this->footerAdded) {
384
+            $this->footerAdded = true;
385
+            if ($this->bodyOpened) {
386
+                $this->htmlBody .= $this->bodyEnd;
387
+            }
388
+            $this->htmlBody .= $this->tail;
389
+        }
390
+        return $this->htmlBody;
391
+    }
392
+
393
+    /**
394
+     * Returns the rendered plain text email as string
395
+     *
396
+     * @return string
397
+     */
398
+    public function renderText() {
399
+        if (!$this->footerAdded) {
400
+            $this->footerAdded = true;
401
+            if ($this->bodyOpened) {
402
+                $this->htmlBody .= $this->bodyEnd;
403
+            }
404
+            $this->htmlBody .= $this->tail;
405
+        }
406
+        return $this->plainBody;
407
+    }
408 408
 }
Please login to merge, or discard this patch.
lib/private/Mail/IEMailTemplate.php 1 patch
Indentation   +51 added lines, -51 removed lines patch added patch discarded remove patch
@@ -51,62 +51,62 @@
 block discarded – undo
51 51
  * $plainContent = $emailTemplate->renderText();
52 52
  */
53 53
 interface IEMailTemplate {
54
-	/**
55
-	 * @param Defaults $themingDefaults
56
-	 * @param \OCP\IURLGenerator $urlGenerator
57
-	 * @param \OCP\IL10N $l10n
58
-	 */
59
-	public function __construct(Defaults $themingDefaults,
60
-								\OCP\IURLGenerator $urlGenerator,
61
-								\OCP\IL10N $l10n);
54
+    /**
55
+     * @param Defaults $themingDefaults
56
+     * @param \OCP\IURLGenerator $urlGenerator
57
+     * @param \OCP\IL10N $l10n
58
+     */
59
+    public function __construct(Defaults $themingDefaults,
60
+                                \OCP\IURLGenerator $urlGenerator,
61
+                                \OCP\IL10N $l10n);
62 62
 
63
-	/**
64
-	 * Adds a header to the email
65
-	 */
66
-	public function addHeader();
63
+    /**
64
+     * Adds a header to the email
65
+     */
66
+    public function addHeader();
67 67
 
68
-	/**
69
-	 * Adds a heading to the email
70
-	 *
71
-	 * @param string $title
72
-	 */
73
-	public function addHeading($title);
68
+    /**
69
+     * Adds a heading to the email
70
+     *
71
+     * @param string $title
72
+     */
73
+    public function addHeading($title);
74 74
 
75
-	/**
76
-	 * Adds a paragraph to the body of the email
77
-	 *
78
-	 * @param string $text
79
-	 */
80
-	public function addBodyText($text);
75
+    /**
76
+     * Adds a paragraph to the body of the email
77
+     *
78
+     * @param string $text
79
+     */
80
+    public function addBodyText($text);
81 81
 
82
-	/**
83
-	 * Adds a button group of two buttons to the body of the email
84
-	 *
85
-	 * @param string $textLeft Text of left button
86
-	 * @param string $urlLeft URL of left button
87
-	 * @param string $textRight Text of right button
88
-	 * @param string $urlRight URL of right button
89
-	 */
90
-	public function addBodyButtonGroup($textLeft, $urlLeft, $textRight, $urlRight);
82
+    /**
83
+     * Adds a button group of two buttons to the body of the email
84
+     *
85
+     * @param string $textLeft Text of left button
86
+     * @param string $urlLeft URL of left button
87
+     * @param string $textRight Text of right button
88
+     * @param string $urlRight URL of right button
89
+     */
90
+    public function addBodyButtonGroup($textLeft, $urlLeft, $textRight, $urlRight);
91 91
 
92
-	/**
93
-	 * Adds a logo and a text to the footer. <br> in the text will be replaced by new lines in the plain text email
94
-	 *
95
-	 * @param string $text
96
-	 */
97
-	public function addFooter($text = '');
92
+    /**
93
+     * Adds a logo and a text to the footer. <br> in the text will be replaced by new lines in the plain text email
94
+     *
95
+     * @param string $text
96
+     */
97
+    public function addFooter($text = '');
98 98
 
99
-	/**
100
-	 * Returns the rendered HTML email as string
101
-	 *
102
-	 * @return string
103
-	 */
104
-	public function renderHTML();
99
+    /**
100
+     * Returns the rendered HTML email as string
101
+     *
102
+     * @return string
103
+     */
104
+    public function renderHTML();
105 105
 
106
-	/**
107
-	 * Returns the rendered plain text email as string
108
-	 *
109
-	 * @return string
110
-	 */
111
-	public function renderText();
106
+    /**
107
+     * Returns the rendered plain text email as string
108
+     *
109
+     * @return string
110
+     */
111
+    public function renderText();
112 112
 }
Please login to merge, or discard this patch.
lib/private/Mail/Mailer.php 1 patch
Indentation   +175 added lines, -175 removed lines patch added patch discarded remove patch
@@ -46,180 +46,180 @@
 block discarded – undo
46 46
  * @package OC\Mail
47 47
  */
48 48
 class Mailer implements IMailer {
49
-	/** @var \Swift_SmtpTransport|\Swift_SendmailTransport|\Swift_MailTransport Cached transport */
50
-	private $instance = null;
51
-	/** @var IConfig */
52
-	private $config;
53
-	/** @var ILogger */
54
-	private $logger;
55
-	/** @var Defaults */
56
-	private $defaults;
57
-
58
-	/**
59
-	 * @param IConfig $config
60
-	 * @param ILogger $logger
61
-	 * @param Defaults $defaults
62
-	 */
63
-	function __construct(IConfig $config,
64
-						 ILogger $logger,
65
-						 Defaults $defaults) {
66
-		$this->config = $config;
67
-		$this->logger = $logger;
68
-		$this->defaults = $defaults;
69
-	}
70
-
71
-	/**
72
-	 * Creates a new message object that can be passed to send()
73
-	 *
74
-	 * @return Message
75
-	 */
76
-	public function createMessage() {
77
-		return new Message(new \Swift_Message());
78
-	}
79
-
80
-	/**
81
-	 * Send the specified message. Also sets the from address to the value defined in config.php
82
-	 * if no-one has been passed.
83
-	 *
84
-	 * @param Message $message Message to send
85
-	 * @return string[] Array with failed recipients. Be aware that this depends on the used mail backend and
86
-	 * therefore should be considered
87
-	 * @throws \Exception In case it was not possible to send the message. (for example if an invalid mail address
88
-	 * has been supplied.)
89
-	 */
90
-	public function send(Message $message) {
91
-		$debugMode = $this->config->getSystemValue('mail_smtpdebug', false);
92
-
93
-		if (sizeof($message->getFrom()) === 0) {
94
-			$message->setFrom([\OCP\Util::getDefaultEmailAddress($this->defaults->getName())]);
95
-		}
96
-
97
-		$failedRecipients = [];
98
-
99
-		$mailer = $this->getInstance();
100
-
101
-		// Enable logger if debug mode is enabled
102
-		if($debugMode) {
103
-			$mailLogger = new \Swift_Plugins_Loggers_ArrayLogger();
104
-			$mailer->registerPlugin(new \Swift_Plugins_LoggerPlugin($mailLogger));
105
-		}
106
-
107
-		$mailer->send($message->getSwiftMessage(), $failedRecipients);
108
-
109
-		// Debugging logging
110
-		$logMessage = sprintf('Sent mail to "%s" with subject "%s"', print_r($message->getTo(), true), $message->getSubject());
111
-		$this->logger->debug($logMessage, ['app' => 'core']);
112
-		if($debugMode && isset($mailLogger)) {
113
-			$this->logger->debug($mailLogger->dump(), ['app' => 'core']);
114
-		}
115
-
116
-		return $failedRecipients;
117
-	}
118
-
119
-	/**
120
-	 * Checks if an e-mail address is valid
121
-	 *
122
-	 * @param string $email Email address to be validated
123
-	 * @return bool True if the mail address is valid, false otherwise
124
-	 */
125
-	public function validateMailAddress($email) {
126
-		return \Swift_Validate::email($this->convertEmail($email));
127
-	}
128
-
129
-	/**
130
-	 * SwiftMailer does currently not work with IDN domains, this function therefore converts the domains
131
-	 *
132
-	 * FIXME: Remove this once SwiftMailer supports IDN
133
-	 *
134
-	 * @param string $email
135
-	 * @return string Converted mail address if `idn_to_ascii` exists
136
-	 */
137
-	protected function convertEmail($email) {
138
-		if (!function_exists('idn_to_ascii') || strpos($email, '@') === false) {
139
-			return $email;
140
-		}
141
-
142
-		list($name, $domain) = explode('@', $email, 2);
143
-		$domain = idn_to_ascii($domain);
144
-		return $name.'@'.$domain;
145
-	}
146
-
147
-	/**
148
-	 * Returns whatever transport is configured within the config
149
-	 *
150
-	 * @return \Swift_SmtpTransport|\Swift_SendmailTransport|\Swift_MailTransport
151
-	 */
152
-	protected function getInstance() {
153
-		if (!is_null($this->instance)) {
154
-			return $this->instance;
155
-		}
156
-
157
-		switch ($this->config->getSystemValue('mail_smtpmode', 'php')) {
158
-			case 'smtp':
159
-				$this->instance = $this->getSMTPInstance();
160
-				break;
161
-			case 'sendmail':
162
-				// FIXME: Move into the return statement but requires proper testing
163
-				//       for SMTP and mail as well. Thus not really doable for a
164
-				//       minor release.
165
-				$this->instance = \Swift_Mailer::newInstance($this->getSendMailInstance());
166
-				break;
167
-			default:
168
-				$this->instance = $this->getMailInstance();
169
-				break;
170
-		}
171
-
172
-		return $this->instance;
173
-	}
174
-
175
-	/**
176
-	 * Returns the SMTP transport
177
-	 *
178
-	 * @return \Swift_SmtpTransport
179
-	 */
180
-	protected function getSmtpInstance() {
181
-		$transport = \Swift_SmtpTransport::newInstance();
182
-		$transport->setTimeout($this->config->getSystemValue('mail_smtptimeout', 10));
183
-		$transport->setHost($this->config->getSystemValue('mail_smtphost', '127.0.0.1'));
184
-		$transport->setPort($this->config->getSystemValue('mail_smtpport', 25));
185
-		if ($this->config->getSystemValue('mail_smtpauth', false)) {
186
-			$transport->setUsername($this->config->getSystemValue('mail_smtpname', ''));
187
-			$transport->setPassword($this->config->getSystemValue('mail_smtppassword', ''));
188
-			$transport->setAuthMode($this->config->getSystemValue('mail_smtpauthtype', 'LOGIN'));
189
-		}
190
-		$smtpSecurity = $this->config->getSystemValue('mail_smtpsecure', '');
191
-		if (!empty($smtpSecurity)) {
192
-			$transport->setEncryption($smtpSecurity);
193
-		}
194
-		$transport->start();
195
-		return $transport;
196
-	}
197
-
198
-	/**
199
-	 * Returns the sendmail transport
200
-	 *
201
-	 * @return \Swift_SendmailTransport
202
-	 */
203
-	protected function getSendMailInstance() {
204
-		switch ($this->config->getSystemValue('mail_smtpmode', 'php')) {
205
-			case 'qmail':
206
-				$binaryPath = '/var/qmail/bin/sendmail';
207
-				break;
208
-			default:
209
-				$binaryPath = '/usr/sbin/sendmail';
210
-				break;
211
-		}
212
-
213
-		return \Swift_SendmailTransport::newInstance($binaryPath . ' -bs');
214
-	}
215
-
216
-	/**
217
-	 * Returns the mail transport
218
-	 *
219
-	 * @return \Swift_MailTransport
220
-	 */
221
-	protected function getMailInstance() {
222
-		return \Swift_MailTransport::newInstance();
223
-	}
49
+    /** @var \Swift_SmtpTransport|\Swift_SendmailTransport|\Swift_MailTransport Cached transport */
50
+    private $instance = null;
51
+    /** @var IConfig */
52
+    private $config;
53
+    /** @var ILogger */
54
+    private $logger;
55
+    /** @var Defaults */
56
+    private $defaults;
57
+
58
+    /**
59
+     * @param IConfig $config
60
+     * @param ILogger $logger
61
+     * @param Defaults $defaults
62
+     */
63
+    function __construct(IConfig $config,
64
+                            ILogger $logger,
65
+                            Defaults $defaults) {
66
+        $this->config = $config;
67
+        $this->logger = $logger;
68
+        $this->defaults = $defaults;
69
+    }
70
+
71
+    /**
72
+     * Creates a new message object that can be passed to send()
73
+     *
74
+     * @return Message
75
+     */
76
+    public function createMessage() {
77
+        return new Message(new \Swift_Message());
78
+    }
79
+
80
+    /**
81
+     * Send the specified message. Also sets the from address to the value defined in config.php
82
+     * if no-one has been passed.
83
+     *
84
+     * @param Message $message Message to send
85
+     * @return string[] Array with failed recipients. Be aware that this depends on the used mail backend and
86
+     * therefore should be considered
87
+     * @throws \Exception In case it was not possible to send the message. (for example if an invalid mail address
88
+     * has been supplied.)
89
+     */
90
+    public function send(Message $message) {
91
+        $debugMode = $this->config->getSystemValue('mail_smtpdebug', false);
92
+
93
+        if (sizeof($message->getFrom()) === 0) {
94
+            $message->setFrom([\OCP\Util::getDefaultEmailAddress($this->defaults->getName())]);
95
+        }
96
+
97
+        $failedRecipients = [];
98
+
99
+        $mailer = $this->getInstance();
100
+
101
+        // Enable logger if debug mode is enabled
102
+        if($debugMode) {
103
+            $mailLogger = new \Swift_Plugins_Loggers_ArrayLogger();
104
+            $mailer->registerPlugin(new \Swift_Plugins_LoggerPlugin($mailLogger));
105
+        }
106
+
107
+        $mailer->send($message->getSwiftMessage(), $failedRecipients);
108
+
109
+        // Debugging logging
110
+        $logMessage = sprintf('Sent mail to "%s" with subject "%s"', print_r($message->getTo(), true), $message->getSubject());
111
+        $this->logger->debug($logMessage, ['app' => 'core']);
112
+        if($debugMode && isset($mailLogger)) {
113
+            $this->logger->debug($mailLogger->dump(), ['app' => 'core']);
114
+        }
115
+
116
+        return $failedRecipients;
117
+    }
118
+
119
+    /**
120
+     * Checks if an e-mail address is valid
121
+     *
122
+     * @param string $email Email address to be validated
123
+     * @return bool True if the mail address is valid, false otherwise
124
+     */
125
+    public function validateMailAddress($email) {
126
+        return \Swift_Validate::email($this->convertEmail($email));
127
+    }
128
+
129
+    /**
130
+     * SwiftMailer does currently not work with IDN domains, this function therefore converts the domains
131
+     *
132
+     * FIXME: Remove this once SwiftMailer supports IDN
133
+     *
134
+     * @param string $email
135
+     * @return string Converted mail address if `idn_to_ascii` exists
136
+     */
137
+    protected function convertEmail($email) {
138
+        if (!function_exists('idn_to_ascii') || strpos($email, '@') === false) {
139
+            return $email;
140
+        }
141
+
142
+        list($name, $domain) = explode('@', $email, 2);
143
+        $domain = idn_to_ascii($domain);
144
+        return $name.'@'.$domain;
145
+    }
146
+
147
+    /**
148
+     * Returns whatever transport is configured within the config
149
+     *
150
+     * @return \Swift_SmtpTransport|\Swift_SendmailTransport|\Swift_MailTransport
151
+     */
152
+    protected function getInstance() {
153
+        if (!is_null($this->instance)) {
154
+            return $this->instance;
155
+        }
156
+
157
+        switch ($this->config->getSystemValue('mail_smtpmode', 'php')) {
158
+            case 'smtp':
159
+                $this->instance = $this->getSMTPInstance();
160
+                break;
161
+            case 'sendmail':
162
+                // FIXME: Move into the return statement but requires proper testing
163
+                //       for SMTP and mail as well. Thus not really doable for a
164
+                //       minor release.
165
+                $this->instance = \Swift_Mailer::newInstance($this->getSendMailInstance());
166
+                break;
167
+            default:
168
+                $this->instance = $this->getMailInstance();
169
+                break;
170
+        }
171
+
172
+        return $this->instance;
173
+    }
174
+
175
+    /**
176
+     * Returns the SMTP transport
177
+     *
178
+     * @return \Swift_SmtpTransport
179
+     */
180
+    protected function getSmtpInstance() {
181
+        $transport = \Swift_SmtpTransport::newInstance();
182
+        $transport->setTimeout($this->config->getSystemValue('mail_smtptimeout', 10));
183
+        $transport->setHost($this->config->getSystemValue('mail_smtphost', '127.0.0.1'));
184
+        $transport->setPort($this->config->getSystemValue('mail_smtpport', 25));
185
+        if ($this->config->getSystemValue('mail_smtpauth', false)) {
186
+            $transport->setUsername($this->config->getSystemValue('mail_smtpname', ''));
187
+            $transport->setPassword($this->config->getSystemValue('mail_smtppassword', ''));
188
+            $transport->setAuthMode($this->config->getSystemValue('mail_smtpauthtype', 'LOGIN'));
189
+        }
190
+        $smtpSecurity = $this->config->getSystemValue('mail_smtpsecure', '');
191
+        if (!empty($smtpSecurity)) {
192
+            $transport->setEncryption($smtpSecurity);
193
+        }
194
+        $transport->start();
195
+        return $transport;
196
+    }
197
+
198
+    /**
199
+     * Returns the sendmail transport
200
+     *
201
+     * @return \Swift_SendmailTransport
202
+     */
203
+    protected function getSendMailInstance() {
204
+        switch ($this->config->getSystemValue('mail_smtpmode', 'php')) {
205
+            case 'qmail':
206
+                $binaryPath = '/var/qmail/bin/sendmail';
207
+                break;
208
+            default:
209
+                $binaryPath = '/usr/sbin/sendmail';
210
+                break;
211
+        }
212
+
213
+        return \Swift_SendmailTransport::newInstance($binaryPath . ' -bs');
214
+    }
215
+
216
+    /**
217
+     * Returns the mail transport
218
+     *
219
+     * @return \Swift_MailTransport
220
+     */
221
+    protected function getMailInstance() {
222
+        return \Swift_MailTransport::newInstance();
223
+    }
224 224
 
225 225
 }
Please login to merge, or discard this patch.
lib/private/Setup.php 1 patch
Indentation   +465 added lines, -465 removed lines patch added patch discarded remove patch
@@ -47,469 +47,469 @@
 block discarded – undo
47 47
 use OCP\Security\ISecureRandom;
48 48
 
49 49
 class Setup {
50
-	/** @var SystemConfig */
51
-	protected $config;
52
-	/** @var IniGetWrapper */
53
-	protected $iniWrapper;
54
-	/** @var IL10N */
55
-	protected $l10n;
56
-	/** @var Defaults */
57
-	protected $defaults;
58
-	/** @var ILogger */
59
-	protected $logger;
60
-	/** @var ISecureRandom */
61
-	protected $random;
62
-
63
-	/**
64
-	 * @param SystemConfig $config
65
-	 * @param IniGetWrapper $iniWrapper
66
-	 * @param Defaults $defaults
67
-	 * @param ILogger $logger
68
-	 * @param ISecureRandom $random
69
-	 */
70
-	function __construct(SystemConfig $config,
71
-						 IniGetWrapper $iniWrapper,
72
-						 IL10N $l10n,
73
-						 Defaults $defaults,
74
-						 ILogger $logger,
75
-						 ISecureRandom $random
76
-		) {
77
-		$this->config = $config;
78
-		$this->iniWrapper = $iniWrapper;
79
-		$this->l10n = $l10n;
80
-		$this->defaults = $defaults;
81
-		$this->logger = $logger;
82
-		$this->random = $random;
83
-	}
84
-
85
-	static $dbSetupClasses = [
86
-		'mysql' => \OC\Setup\MySQL::class,
87
-		'pgsql' => \OC\Setup\PostgreSQL::class,
88
-		'oci'   => \OC\Setup\OCI::class,
89
-		'sqlite' => \OC\Setup\Sqlite::class,
90
-		'sqlite3' => \OC\Setup\Sqlite::class,
91
-	];
92
-
93
-	/**
94
-	 * Wrapper around the "class_exists" PHP function to be able to mock it
95
-	 * @param string $name
96
-	 * @return bool
97
-	 */
98
-	protected function class_exists($name) {
99
-		return class_exists($name);
100
-	}
101
-
102
-	/**
103
-	 * Wrapper around the "is_callable" PHP function to be able to mock it
104
-	 * @param string $name
105
-	 * @return bool
106
-	 */
107
-	protected function is_callable($name) {
108
-		return is_callable($name);
109
-	}
110
-
111
-	/**
112
-	 * Wrapper around \PDO::getAvailableDrivers
113
-	 *
114
-	 * @return array
115
-	 */
116
-	protected function getAvailableDbDriversForPdo() {
117
-		return \PDO::getAvailableDrivers();
118
-	}
119
-
120
-	/**
121
-	 * Get the available and supported databases of this instance
122
-	 *
123
-	 * @param bool $allowAllDatabases
124
-	 * @return array
125
-	 * @throws Exception
126
-	 */
127
-	public function getSupportedDatabases($allowAllDatabases = false) {
128
-		$availableDatabases = array(
129
-			'sqlite' =>  array(
130
-				'type' => 'pdo',
131
-				'call' => 'sqlite',
132
-				'name' => 'SQLite'
133
-			),
134
-			'mysql' => array(
135
-				'type' => 'pdo',
136
-				'call' => 'mysql',
137
-				'name' => 'MySQL/MariaDB'
138
-			),
139
-			'pgsql' => array(
140
-				'type' => 'pdo',
141
-				'call' => 'pgsql',
142
-				'name' => 'PostgreSQL'
143
-			),
144
-			'oci' => array(
145
-				'type' => 'function',
146
-				'call' => 'oci_connect',
147
-				'name' => 'Oracle'
148
-			)
149
-		);
150
-		if ($allowAllDatabases) {
151
-			$configuredDatabases = array_keys($availableDatabases);
152
-		} else {
153
-			$configuredDatabases = $this->config->getValue('supportedDatabases',
154
-				array('sqlite', 'mysql', 'pgsql'));
155
-		}
156
-		if(!is_array($configuredDatabases)) {
157
-			throw new Exception('Supported databases are not properly configured.');
158
-		}
159
-
160
-		$supportedDatabases = array();
161
-
162
-		foreach($configuredDatabases as $database) {
163
-			if(array_key_exists($database, $availableDatabases)) {
164
-				$working = false;
165
-				$type = $availableDatabases[$database]['type'];
166
-				$call = $availableDatabases[$database]['call'];
167
-
168
-				if ($type === 'function') {
169
-					$working = $this->is_callable($call);
170
-				} elseif($type === 'pdo') {
171
-					$working = in_array($call, $this->getAvailableDbDriversForPdo(), TRUE);
172
-				}
173
-				if($working) {
174
-					$supportedDatabases[$database] = $availableDatabases[$database]['name'];
175
-				}
176
-			}
177
-		}
178
-
179
-		return $supportedDatabases;
180
-	}
181
-
182
-	/**
183
-	 * Gathers system information like database type and does
184
-	 * a few system checks.
185
-	 *
186
-	 * @return array of system info, including an "errors" value
187
-	 * in case of errors/warnings
188
-	 */
189
-	public function getSystemInfo($allowAllDatabases = false) {
190
-		$databases = $this->getSupportedDatabases($allowAllDatabases);
191
-
192
-		$dataDir = $this->config->getValue('datadirectory', \OC::$SERVERROOT.'/data');
193
-
194
-		$errors = array();
195
-
196
-		// Create data directory to test whether the .htaccess works
197
-		// Notice that this is not necessarily the same data directory as the one
198
-		// that will effectively be used.
199
-		if(!file_exists($dataDir)) {
200
-			@mkdir($dataDir);
201
-		}
202
-		$htAccessWorking = true;
203
-		if (is_dir($dataDir) && is_writable($dataDir)) {
204
-			// Protect data directory here, so we can test if the protection is working
205
-			\OC\Setup::protectDataDirectory();
206
-
207
-			try {
208
-				$util = new \OC_Util();
209
-				$htAccessWorking = $util->isHtaccessWorking(\OC::$server->getConfig());
210
-			} catch (\OC\HintException $e) {
211
-				$errors[] = array(
212
-					'error' => $e->getMessage(),
213
-					'hint' => $e->getHint()
214
-				);
215
-				$htAccessWorking = false;
216
-			}
217
-		}
218
-
219
-		if (\OC_Util::runningOnMac()) {
220
-			$errors[] = array(
221
-				'error' => $this->l10n->t(
222
-					'Mac OS X is not supported and %s will not work properly on this platform. ' .
223
-					'Use it at your own risk! ',
224
-					$this->defaults->getName()
225
-				),
226
-				'hint' => $this->l10n->t('For the best results, please consider using a GNU/Linux server instead.')
227
-			);
228
-		}
229
-
230
-		if($this->iniWrapper->getString('open_basedir') !== '' && PHP_INT_SIZE === 4) {
231
-			$errors[] = array(
232
-				'error' => $this->l10n->t(
233
-					'It seems that this %s instance is running on a 32-bit PHP environment and the open_basedir has been configured in php.ini. ' .
234
-					'This will lead to problems with files over 4 GB and is highly discouraged.',
235
-					$this->defaults->getName()
236
-				),
237
-				'hint' => $this->l10n->t('Please remove the open_basedir setting within your php.ini or switch to 64-bit PHP.')
238
-			);
239
-		}
240
-
241
-		return array(
242
-			'hasSQLite' => isset($databases['sqlite']),
243
-			'hasMySQL' => isset($databases['mysql']),
244
-			'hasPostgreSQL' => isset($databases['pgsql']),
245
-			'hasOracle' => isset($databases['oci']),
246
-			'databases' => $databases,
247
-			'directory' => $dataDir,
248
-			'htaccessWorking' => $htAccessWorking,
249
-			'errors' => $errors,
250
-		);
251
-	}
252
-
253
-	/**
254
-	 * @param $options
255
-	 * @return array
256
-	 */
257
-	public function install($options) {
258
-		$l = $this->l10n;
259
-
260
-		$error = array();
261
-		$dbType = $options['dbtype'];
262
-
263
-		if(empty($options['adminlogin'])) {
264
-			$error[] = $l->t('Set an admin username.');
265
-		}
266
-		if(empty($options['adminpass'])) {
267
-			$error[] = $l->t('Set an admin password.');
268
-		}
269
-		if(empty($options['directory'])) {
270
-			$options['directory'] = \OC::$SERVERROOT."/data";
271
-		}
272
-
273
-		if (!isset(self::$dbSetupClasses[$dbType])) {
274
-			$dbType = 'sqlite';
275
-		}
276
-
277
-		$username = htmlspecialchars_decode($options['adminlogin']);
278
-		$password = htmlspecialchars_decode($options['adminpass']);
279
-		$dataDir = htmlspecialchars_decode($options['directory']);
280
-
281
-		$class = self::$dbSetupClasses[$dbType];
282
-		/** @var \OC\Setup\AbstractDatabase $dbSetup */
283
-		$dbSetup = new $class($l, 'db_structure.xml', $this->config,
284
-			$this->logger, $this->random);
285
-		$error = array_merge($error, $dbSetup->validate($options));
286
-
287
-		// validate the data directory
288
-		if (
289
-			(!is_dir($dataDir) and !mkdir($dataDir)) or
290
-			!is_writable($dataDir)
291
-		) {
292
-			$error[] = $l->t("Can't create or write into the data directory %s", array($dataDir));
293
-		}
294
-
295
-		if(count($error) != 0) {
296
-			return $error;
297
-		}
298
-
299
-		$request = \OC::$server->getRequest();
300
-
301
-		//no errors, good
302
-		if(isset($options['trusted_domains'])
303
-		    && is_array($options['trusted_domains'])) {
304
-			$trustedDomains = $options['trusted_domains'];
305
-		} else {
306
-			$trustedDomains = [$request->getInsecureServerHost()];
307
-		}
308
-
309
-		//use sqlite3 when available, otherwise sqlite2 will be used.
310
-		if($dbType=='sqlite' and class_exists('SQLite3')) {
311
-			$dbType='sqlite3';
312
-		}
313
-
314
-		//generate a random salt that is used to salt the local user passwords
315
-		$salt = $this->random->generate(30);
316
-		// generate a secret
317
-		$secret = $this->random->generate(48);
318
-
319
-		//write the config file
320
-		$this->config->setValues([
321
-			'passwordsalt'		=> $salt,
322
-			'secret'			=> $secret,
323
-			'trusted_domains'	=> $trustedDomains,
324
-			'datadirectory'		=> $dataDir,
325
-			'overwrite.cli.url'	=> $request->getServerProtocol() . '://' . $request->getInsecureServerHost() . \OC::$WEBROOT,
326
-			'dbtype'			=> $dbType,
327
-			'version'			=> implode('.', \OCP\Util::getVersion()),
328
-		]);
329
-
330
-		try {
331
-			$dbSetup->initialize($options);
332
-			$dbSetup->setupDatabase($username);
333
-		} catch (\OC\DatabaseSetupException $e) {
334
-			$error[] = array(
335
-				'error' => $e->getMessage(),
336
-				'hint' => $e->getHint()
337
-			);
338
-			return($error);
339
-		} catch (Exception $e) {
340
-			$error[] = array(
341
-				'error' => 'Error while trying to create admin user: ' . $e->getMessage(),
342
-				'hint' => ''
343
-			);
344
-			return($error);
345
-		}
346
-
347
-		//create the user and group
348
-		$user =  null;
349
-		try {
350
-			$user = \OC::$server->getUserManager()->createUser($username, $password);
351
-			if (!$user) {
352
-				$error[] = "User <$username> could not be created.";
353
-			}
354
-		} catch(Exception $exception) {
355
-			$error[] = $exception->getMessage();
356
-		}
357
-
358
-		if(count($error) == 0) {
359
-			$config = \OC::$server->getConfig();
360
-			$config->setAppValue('core', 'installedat', microtime(true));
361
-			$config->setAppValue('core', 'lastupdatedat', microtime(true));
362
-			$config->setAppValue('core', 'vendor', $this->getVendor());
363
-
364
-			$group =\OC::$server->getGroupManager()->createGroup('admin');
365
-			$group->addUser($user);
366
-
367
-			//guess what this does
368
-			Installer::installShippedApps();
369
-
370
-			// create empty file in data dir, so we can later find
371
-			// out that this is indeed an ownCloud data directory
372
-			file_put_contents($config->getSystemValue('datadirectory', \OC::$SERVERROOT.'/data').'/.ocdata', '');
373
-
374
-			// Update .htaccess files
375
-			Setup::updateHtaccess();
376
-			Setup::protectDataDirectory();
377
-
378
-			self::installBackgroundJobs();
379
-
380
-			//and we are done
381
-			$config->setSystemValue('installed', true);
382
-
383
-			// Create a session token for the newly created user
384
-			// The token provider requires a working db, so it's not injected on setup
385
-			/* @var $userSession User\Session */
386
-			$userSession = \OC::$server->getUserSession();
387
-			$defaultTokenProvider = \OC::$server->query('OC\Authentication\Token\DefaultTokenProvider');
388
-			$userSession->setTokenProvider($defaultTokenProvider);
389
-			$userSession->login($username, $password);
390
-			$userSession->createSessionToken($request, $userSession->getUser()->getUID(), $username, $password);
391
-		}
392
-
393
-		return $error;
394
-	}
395
-
396
-	public static function installBackgroundJobs() {
397
-		\OC::$server->getJobList()->add('\OC\Authentication\Token\DefaultTokenCleanupJob');
398
-	}
399
-
400
-	/**
401
-	 * @return string Absolute path to htaccess
402
-	 */
403
-	private function pathToHtaccess() {
404
-		return \OC::$SERVERROOT.'/.htaccess';
405
-	}
406
-
407
-	/**
408
-	 * Append the correct ErrorDocument path for Apache hosts
409
-	 * @return bool True when success, False otherwise
410
-	 */
411
-	public static function updateHtaccess() {
412
-		$config = \OC::$server->getSystemConfig();
413
-
414
-		// For CLI read the value from overwrite.cli.url
415
-		if(\OC::$CLI) {
416
-			$webRoot = $config->getValue('overwrite.cli.url', '');
417
-			if($webRoot === '') {
418
-				return false;
419
-			}
420
-			$webRoot = parse_url($webRoot, PHP_URL_PATH);
421
-			$webRoot = rtrim($webRoot, '/');
422
-		} else {
423
-			$webRoot = !empty(\OC::$WEBROOT) ? \OC::$WEBROOT : '/';
424
-		}
425
-
426
-		$setupHelper = new \OC\Setup($config, \OC::$server->getIniWrapper(),
427
-			\OC::$server->getL10N('lib'), \OC::$server->getDefaults(), \OC::$server->getLogger(),
428
-			\OC::$server->getSecureRandom());
429
-
430
-		$htaccessContent = file_get_contents($setupHelper->pathToHtaccess());
431
-		$content = "#### DO NOT CHANGE ANYTHING ABOVE THIS LINE ####\n";
432
-		$htaccessContent = explode($content, $htaccessContent, 2)[0];
433
-
434
-		//custom 403 error page
435
-		$content.= "\nErrorDocument 403 ".$webRoot."/core/templates/403.php";
436
-
437
-		//custom 404 error page
438
-		$content.= "\nErrorDocument 404 ".$webRoot."/core/templates/404.php";
439
-
440
-		// Add rewrite rules if the RewriteBase is configured
441
-		$rewriteBase = $config->getValue('htaccess.RewriteBase', '');
442
-		if($rewriteBase !== '') {
443
-			$content .= "\n<IfModule mod_rewrite.c>";
444
-			$content .= "\n  Options -MultiViews";
445
-			$content .= "\n  RewriteRule ^core/js/oc.js$ index.php [PT,E=PATH_INFO:$1]";
446
-			$content .= "\n  RewriteRule ^core/preview.png$ index.php [PT,E=PATH_INFO:$1]";
447
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !\\.(css|js|svg|gif|png|html|ttf|woff|ico|jpg|jpeg)$";
448
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !core/img/favicon.ico$";
449
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/remote.php";
450
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/public.php";
451
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/cron.php";
452
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/core/ajax/update.php";
453
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/status.php";
454
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/ocs/v1.php";
455
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/ocs/v2.php";
456
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/robots.txt";
457
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/updater/";
458
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/ocs-provider/";
459
-			$content .= "\n  RewriteCond %{REQUEST_URI} !^/.well-known/acme-challenge/.*";
460
-			$content .= "\n  RewriteRule . index.php [PT,E=PATH_INFO:$1]";
461
-			$content .= "\n  RewriteBase " . $rewriteBase;
462
-			$content .= "\n  <IfModule mod_env.c>";
463
-			$content .= "\n    SetEnv front_controller_active true";
464
-			$content .= "\n    <IfModule mod_dir.c>";
465
-			$content .= "\n      DirectorySlash off";
466
-			$content .= "\n    </IfModule>";
467
-			$content .= "\n  </IfModule>";
468
-			$content .= "\n</IfModule>";
469
-		}
470
-
471
-		if ($content !== '') {
472
-			//suppress errors in case we don't have permissions for it
473
-			return (bool) @file_put_contents($setupHelper->pathToHtaccess(), $htaccessContent.$content . "\n");
474
-		}
475
-
476
-		return false;
477
-	}
478
-
479
-	public static function protectDataDirectory() {
480
-		//Require all denied
481
-		$now =  date('Y-m-d H:i:s');
482
-		$content = "# Generated by Nextcloud on $now\n";
483
-		$content.= "# line below if for Apache 2.4\n";
484
-		$content.= "<ifModule mod_authz_core.c>\n";
485
-		$content.= "Require all denied\n";
486
-		$content.= "</ifModule>\n\n";
487
-		$content.= "# line below if for Apache 2.2\n";
488
-		$content.= "<ifModule !mod_authz_core.c>\n";
489
-		$content.= "deny from all\n";
490
-		$content.= "Satisfy All\n";
491
-		$content.= "</ifModule>\n\n";
492
-		$content.= "# section for Apache 2.2 and 2.4\n";
493
-		$content.= "<ifModule mod_autoindex.c>\n";
494
-		$content.= "IndexIgnore *\n";
495
-		$content.= "</ifModule>\n";
496
-
497
-		$baseDir = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data');
498
-		file_put_contents($baseDir . '/.htaccess', $content);
499
-		file_put_contents($baseDir . '/index.html', '');
500
-	}
501
-
502
-	/**
503
-	 * Return vendor from which this version was published
504
-	 *
505
-	 * @return string Get the vendor
506
-	 *
507
-	 * Copy of \OC\Updater::getVendor()
508
-	 */
509
-	private function getVendor() {
510
-		// this should really be a JSON file
511
-		require \OC::$SERVERROOT . '/version.php';
512
-		/** @var string $vendor */
513
-		return (string) $vendor;
514
-	}
50
+    /** @var SystemConfig */
51
+    protected $config;
52
+    /** @var IniGetWrapper */
53
+    protected $iniWrapper;
54
+    /** @var IL10N */
55
+    protected $l10n;
56
+    /** @var Defaults */
57
+    protected $defaults;
58
+    /** @var ILogger */
59
+    protected $logger;
60
+    /** @var ISecureRandom */
61
+    protected $random;
62
+
63
+    /**
64
+     * @param SystemConfig $config
65
+     * @param IniGetWrapper $iniWrapper
66
+     * @param Defaults $defaults
67
+     * @param ILogger $logger
68
+     * @param ISecureRandom $random
69
+     */
70
+    function __construct(SystemConfig $config,
71
+                            IniGetWrapper $iniWrapper,
72
+                            IL10N $l10n,
73
+                            Defaults $defaults,
74
+                            ILogger $logger,
75
+                            ISecureRandom $random
76
+        ) {
77
+        $this->config = $config;
78
+        $this->iniWrapper = $iniWrapper;
79
+        $this->l10n = $l10n;
80
+        $this->defaults = $defaults;
81
+        $this->logger = $logger;
82
+        $this->random = $random;
83
+    }
84
+
85
+    static $dbSetupClasses = [
86
+        'mysql' => \OC\Setup\MySQL::class,
87
+        'pgsql' => \OC\Setup\PostgreSQL::class,
88
+        'oci'   => \OC\Setup\OCI::class,
89
+        'sqlite' => \OC\Setup\Sqlite::class,
90
+        'sqlite3' => \OC\Setup\Sqlite::class,
91
+    ];
92
+
93
+    /**
94
+     * Wrapper around the "class_exists" PHP function to be able to mock it
95
+     * @param string $name
96
+     * @return bool
97
+     */
98
+    protected function class_exists($name) {
99
+        return class_exists($name);
100
+    }
101
+
102
+    /**
103
+     * Wrapper around the "is_callable" PHP function to be able to mock it
104
+     * @param string $name
105
+     * @return bool
106
+     */
107
+    protected function is_callable($name) {
108
+        return is_callable($name);
109
+    }
110
+
111
+    /**
112
+     * Wrapper around \PDO::getAvailableDrivers
113
+     *
114
+     * @return array
115
+     */
116
+    protected function getAvailableDbDriversForPdo() {
117
+        return \PDO::getAvailableDrivers();
118
+    }
119
+
120
+    /**
121
+     * Get the available and supported databases of this instance
122
+     *
123
+     * @param bool $allowAllDatabases
124
+     * @return array
125
+     * @throws Exception
126
+     */
127
+    public function getSupportedDatabases($allowAllDatabases = false) {
128
+        $availableDatabases = array(
129
+            'sqlite' =>  array(
130
+                'type' => 'pdo',
131
+                'call' => 'sqlite',
132
+                'name' => 'SQLite'
133
+            ),
134
+            'mysql' => array(
135
+                'type' => 'pdo',
136
+                'call' => 'mysql',
137
+                'name' => 'MySQL/MariaDB'
138
+            ),
139
+            'pgsql' => array(
140
+                'type' => 'pdo',
141
+                'call' => 'pgsql',
142
+                'name' => 'PostgreSQL'
143
+            ),
144
+            'oci' => array(
145
+                'type' => 'function',
146
+                'call' => 'oci_connect',
147
+                'name' => 'Oracle'
148
+            )
149
+        );
150
+        if ($allowAllDatabases) {
151
+            $configuredDatabases = array_keys($availableDatabases);
152
+        } else {
153
+            $configuredDatabases = $this->config->getValue('supportedDatabases',
154
+                array('sqlite', 'mysql', 'pgsql'));
155
+        }
156
+        if(!is_array($configuredDatabases)) {
157
+            throw new Exception('Supported databases are not properly configured.');
158
+        }
159
+
160
+        $supportedDatabases = array();
161
+
162
+        foreach($configuredDatabases as $database) {
163
+            if(array_key_exists($database, $availableDatabases)) {
164
+                $working = false;
165
+                $type = $availableDatabases[$database]['type'];
166
+                $call = $availableDatabases[$database]['call'];
167
+
168
+                if ($type === 'function') {
169
+                    $working = $this->is_callable($call);
170
+                } elseif($type === 'pdo') {
171
+                    $working = in_array($call, $this->getAvailableDbDriversForPdo(), TRUE);
172
+                }
173
+                if($working) {
174
+                    $supportedDatabases[$database] = $availableDatabases[$database]['name'];
175
+                }
176
+            }
177
+        }
178
+
179
+        return $supportedDatabases;
180
+    }
181
+
182
+    /**
183
+     * Gathers system information like database type and does
184
+     * a few system checks.
185
+     *
186
+     * @return array of system info, including an "errors" value
187
+     * in case of errors/warnings
188
+     */
189
+    public function getSystemInfo($allowAllDatabases = false) {
190
+        $databases = $this->getSupportedDatabases($allowAllDatabases);
191
+
192
+        $dataDir = $this->config->getValue('datadirectory', \OC::$SERVERROOT.'/data');
193
+
194
+        $errors = array();
195
+
196
+        // Create data directory to test whether the .htaccess works
197
+        // Notice that this is not necessarily the same data directory as the one
198
+        // that will effectively be used.
199
+        if(!file_exists($dataDir)) {
200
+            @mkdir($dataDir);
201
+        }
202
+        $htAccessWorking = true;
203
+        if (is_dir($dataDir) && is_writable($dataDir)) {
204
+            // Protect data directory here, so we can test if the protection is working
205
+            \OC\Setup::protectDataDirectory();
206
+
207
+            try {
208
+                $util = new \OC_Util();
209
+                $htAccessWorking = $util->isHtaccessWorking(\OC::$server->getConfig());
210
+            } catch (\OC\HintException $e) {
211
+                $errors[] = array(
212
+                    'error' => $e->getMessage(),
213
+                    'hint' => $e->getHint()
214
+                );
215
+                $htAccessWorking = false;
216
+            }
217
+        }
218
+
219
+        if (\OC_Util::runningOnMac()) {
220
+            $errors[] = array(
221
+                'error' => $this->l10n->t(
222
+                    'Mac OS X is not supported and %s will not work properly on this platform. ' .
223
+                    'Use it at your own risk! ',
224
+                    $this->defaults->getName()
225
+                ),
226
+                'hint' => $this->l10n->t('For the best results, please consider using a GNU/Linux server instead.')
227
+            );
228
+        }
229
+
230
+        if($this->iniWrapper->getString('open_basedir') !== '' && PHP_INT_SIZE === 4) {
231
+            $errors[] = array(
232
+                'error' => $this->l10n->t(
233
+                    'It seems that this %s instance is running on a 32-bit PHP environment and the open_basedir has been configured in php.ini. ' .
234
+                    'This will lead to problems with files over 4 GB and is highly discouraged.',
235
+                    $this->defaults->getName()
236
+                ),
237
+                'hint' => $this->l10n->t('Please remove the open_basedir setting within your php.ini or switch to 64-bit PHP.')
238
+            );
239
+        }
240
+
241
+        return array(
242
+            'hasSQLite' => isset($databases['sqlite']),
243
+            'hasMySQL' => isset($databases['mysql']),
244
+            'hasPostgreSQL' => isset($databases['pgsql']),
245
+            'hasOracle' => isset($databases['oci']),
246
+            'databases' => $databases,
247
+            'directory' => $dataDir,
248
+            'htaccessWorking' => $htAccessWorking,
249
+            'errors' => $errors,
250
+        );
251
+    }
252
+
253
+    /**
254
+     * @param $options
255
+     * @return array
256
+     */
257
+    public function install($options) {
258
+        $l = $this->l10n;
259
+
260
+        $error = array();
261
+        $dbType = $options['dbtype'];
262
+
263
+        if(empty($options['adminlogin'])) {
264
+            $error[] = $l->t('Set an admin username.');
265
+        }
266
+        if(empty($options['adminpass'])) {
267
+            $error[] = $l->t('Set an admin password.');
268
+        }
269
+        if(empty($options['directory'])) {
270
+            $options['directory'] = \OC::$SERVERROOT."/data";
271
+        }
272
+
273
+        if (!isset(self::$dbSetupClasses[$dbType])) {
274
+            $dbType = 'sqlite';
275
+        }
276
+
277
+        $username = htmlspecialchars_decode($options['adminlogin']);
278
+        $password = htmlspecialchars_decode($options['adminpass']);
279
+        $dataDir = htmlspecialchars_decode($options['directory']);
280
+
281
+        $class = self::$dbSetupClasses[$dbType];
282
+        /** @var \OC\Setup\AbstractDatabase $dbSetup */
283
+        $dbSetup = new $class($l, 'db_structure.xml', $this->config,
284
+            $this->logger, $this->random);
285
+        $error = array_merge($error, $dbSetup->validate($options));
286
+
287
+        // validate the data directory
288
+        if (
289
+            (!is_dir($dataDir) and !mkdir($dataDir)) or
290
+            !is_writable($dataDir)
291
+        ) {
292
+            $error[] = $l->t("Can't create or write into the data directory %s", array($dataDir));
293
+        }
294
+
295
+        if(count($error) != 0) {
296
+            return $error;
297
+        }
298
+
299
+        $request = \OC::$server->getRequest();
300
+
301
+        //no errors, good
302
+        if(isset($options['trusted_domains'])
303
+            && is_array($options['trusted_domains'])) {
304
+            $trustedDomains = $options['trusted_domains'];
305
+        } else {
306
+            $trustedDomains = [$request->getInsecureServerHost()];
307
+        }
308
+
309
+        //use sqlite3 when available, otherwise sqlite2 will be used.
310
+        if($dbType=='sqlite' and class_exists('SQLite3')) {
311
+            $dbType='sqlite3';
312
+        }
313
+
314
+        //generate a random salt that is used to salt the local user passwords
315
+        $salt = $this->random->generate(30);
316
+        // generate a secret
317
+        $secret = $this->random->generate(48);
318
+
319
+        //write the config file
320
+        $this->config->setValues([
321
+            'passwordsalt'		=> $salt,
322
+            'secret'			=> $secret,
323
+            'trusted_domains'	=> $trustedDomains,
324
+            'datadirectory'		=> $dataDir,
325
+            'overwrite.cli.url'	=> $request->getServerProtocol() . '://' . $request->getInsecureServerHost() . \OC::$WEBROOT,
326
+            'dbtype'			=> $dbType,
327
+            'version'			=> implode('.', \OCP\Util::getVersion()),
328
+        ]);
329
+
330
+        try {
331
+            $dbSetup->initialize($options);
332
+            $dbSetup->setupDatabase($username);
333
+        } catch (\OC\DatabaseSetupException $e) {
334
+            $error[] = array(
335
+                'error' => $e->getMessage(),
336
+                'hint' => $e->getHint()
337
+            );
338
+            return($error);
339
+        } catch (Exception $e) {
340
+            $error[] = array(
341
+                'error' => 'Error while trying to create admin user: ' . $e->getMessage(),
342
+                'hint' => ''
343
+            );
344
+            return($error);
345
+        }
346
+
347
+        //create the user and group
348
+        $user =  null;
349
+        try {
350
+            $user = \OC::$server->getUserManager()->createUser($username, $password);
351
+            if (!$user) {
352
+                $error[] = "User <$username> could not be created.";
353
+            }
354
+        } catch(Exception $exception) {
355
+            $error[] = $exception->getMessage();
356
+        }
357
+
358
+        if(count($error) == 0) {
359
+            $config = \OC::$server->getConfig();
360
+            $config->setAppValue('core', 'installedat', microtime(true));
361
+            $config->setAppValue('core', 'lastupdatedat', microtime(true));
362
+            $config->setAppValue('core', 'vendor', $this->getVendor());
363
+
364
+            $group =\OC::$server->getGroupManager()->createGroup('admin');
365
+            $group->addUser($user);
366
+
367
+            //guess what this does
368
+            Installer::installShippedApps();
369
+
370
+            // create empty file in data dir, so we can later find
371
+            // out that this is indeed an ownCloud data directory
372
+            file_put_contents($config->getSystemValue('datadirectory', \OC::$SERVERROOT.'/data').'/.ocdata', '');
373
+
374
+            // Update .htaccess files
375
+            Setup::updateHtaccess();
376
+            Setup::protectDataDirectory();
377
+
378
+            self::installBackgroundJobs();
379
+
380
+            //and we are done
381
+            $config->setSystemValue('installed', true);
382
+
383
+            // Create a session token for the newly created user
384
+            // The token provider requires a working db, so it's not injected on setup
385
+            /* @var $userSession User\Session */
386
+            $userSession = \OC::$server->getUserSession();
387
+            $defaultTokenProvider = \OC::$server->query('OC\Authentication\Token\DefaultTokenProvider');
388
+            $userSession->setTokenProvider($defaultTokenProvider);
389
+            $userSession->login($username, $password);
390
+            $userSession->createSessionToken($request, $userSession->getUser()->getUID(), $username, $password);
391
+        }
392
+
393
+        return $error;
394
+    }
395
+
396
+    public static function installBackgroundJobs() {
397
+        \OC::$server->getJobList()->add('\OC\Authentication\Token\DefaultTokenCleanupJob');
398
+    }
399
+
400
+    /**
401
+     * @return string Absolute path to htaccess
402
+     */
403
+    private function pathToHtaccess() {
404
+        return \OC::$SERVERROOT.'/.htaccess';
405
+    }
406
+
407
+    /**
408
+     * Append the correct ErrorDocument path for Apache hosts
409
+     * @return bool True when success, False otherwise
410
+     */
411
+    public static function updateHtaccess() {
412
+        $config = \OC::$server->getSystemConfig();
413
+
414
+        // For CLI read the value from overwrite.cli.url
415
+        if(\OC::$CLI) {
416
+            $webRoot = $config->getValue('overwrite.cli.url', '');
417
+            if($webRoot === '') {
418
+                return false;
419
+            }
420
+            $webRoot = parse_url($webRoot, PHP_URL_PATH);
421
+            $webRoot = rtrim($webRoot, '/');
422
+        } else {
423
+            $webRoot = !empty(\OC::$WEBROOT) ? \OC::$WEBROOT : '/';
424
+        }
425
+
426
+        $setupHelper = new \OC\Setup($config, \OC::$server->getIniWrapper(),
427
+            \OC::$server->getL10N('lib'), \OC::$server->getDefaults(), \OC::$server->getLogger(),
428
+            \OC::$server->getSecureRandom());
429
+
430
+        $htaccessContent = file_get_contents($setupHelper->pathToHtaccess());
431
+        $content = "#### DO NOT CHANGE ANYTHING ABOVE THIS LINE ####\n";
432
+        $htaccessContent = explode($content, $htaccessContent, 2)[0];
433
+
434
+        //custom 403 error page
435
+        $content.= "\nErrorDocument 403 ".$webRoot."/core/templates/403.php";
436
+
437
+        //custom 404 error page
438
+        $content.= "\nErrorDocument 404 ".$webRoot."/core/templates/404.php";
439
+
440
+        // Add rewrite rules if the RewriteBase is configured
441
+        $rewriteBase = $config->getValue('htaccess.RewriteBase', '');
442
+        if($rewriteBase !== '') {
443
+            $content .= "\n<IfModule mod_rewrite.c>";
444
+            $content .= "\n  Options -MultiViews";
445
+            $content .= "\n  RewriteRule ^core/js/oc.js$ index.php [PT,E=PATH_INFO:$1]";
446
+            $content .= "\n  RewriteRule ^core/preview.png$ index.php [PT,E=PATH_INFO:$1]";
447
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !\\.(css|js|svg|gif|png|html|ttf|woff|ico|jpg|jpeg)$";
448
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !core/img/favicon.ico$";
449
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/remote.php";
450
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/public.php";
451
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/cron.php";
452
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/core/ajax/update.php";
453
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/status.php";
454
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/ocs/v1.php";
455
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/ocs/v2.php";
456
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/robots.txt";
457
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/updater/";
458
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/ocs-provider/";
459
+            $content .= "\n  RewriteCond %{REQUEST_URI} !^/.well-known/acme-challenge/.*";
460
+            $content .= "\n  RewriteRule . index.php [PT,E=PATH_INFO:$1]";
461
+            $content .= "\n  RewriteBase " . $rewriteBase;
462
+            $content .= "\n  <IfModule mod_env.c>";
463
+            $content .= "\n    SetEnv front_controller_active true";
464
+            $content .= "\n    <IfModule mod_dir.c>";
465
+            $content .= "\n      DirectorySlash off";
466
+            $content .= "\n    </IfModule>";
467
+            $content .= "\n  </IfModule>";
468
+            $content .= "\n</IfModule>";
469
+        }
470
+
471
+        if ($content !== '') {
472
+            //suppress errors in case we don't have permissions for it
473
+            return (bool) @file_put_contents($setupHelper->pathToHtaccess(), $htaccessContent.$content . "\n");
474
+        }
475
+
476
+        return false;
477
+    }
478
+
479
+    public static function protectDataDirectory() {
480
+        //Require all denied
481
+        $now =  date('Y-m-d H:i:s');
482
+        $content = "# Generated by Nextcloud on $now\n";
483
+        $content.= "# line below if for Apache 2.4\n";
484
+        $content.= "<ifModule mod_authz_core.c>\n";
485
+        $content.= "Require all denied\n";
486
+        $content.= "</ifModule>\n\n";
487
+        $content.= "# line below if for Apache 2.2\n";
488
+        $content.= "<ifModule !mod_authz_core.c>\n";
489
+        $content.= "deny from all\n";
490
+        $content.= "Satisfy All\n";
491
+        $content.= "</ifModule>\n\n";
492
+        $content.= "# section for Apache 2.2 and 2.4\n";
493
+        $content.= "<ifModule mod_autoindex.c>\n";
494
+        $content.= "IndexIgnore *\n";
495
+        $content.= "</ifModule>\n";
496
+
497
+        $baseDir = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data');
498
+        file_put_contents($baseDir . '/.htaccess', $content);
499
+        file_put_contents($baseDir . '/index.html', '');
500
+    }
501
+
502
+    /**
503
+     * Return vendor from which this version was published
504
+     *
505
+     * @return string Get the vendor
506
+     *
507
+     * Copy of \OC\Updater::getVendor()
508
+     */
509
+    private function getVendor() {
510
+        // this should really be a JSON file
511
+        require \OC::$SERVERROOT . '/version.php';
512
+        /** @var string $vendor */
513
+        return (string) $vendor;
514
+    }
515 515
 }
Please login to merge, or discard this patch.
lib/private/legacy/util.php 1 patch
Indentation   +1380 added lines, -1380 removed lines patch added patch discarded remove patch
@@ -61,1388 +61,1388 @@
 block discarded – undo
61 61
 use OCP\IUser;
62 62
 
63 63
 class OC_Util {
64
-	public static $scripts = array();
65
-	public static $styles = array();
66
-	public static $headers = array();
67
-	private static $rootMounted = false;
68
-	private static $fsSetup = false;
69
-
70
-	/** @var array Local cache of version.php */
71
-	private static $versionCache = null;
72
-
73
-	protected static function getAppManager() {
74
-		return \OC::$server->getAppManager();
75
-	}
76
-
77
-	private static function initLocalStorageRootFS() {
78
-		// mount local file backend as root
79
-		$configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data");
80
-		//first set up the local "root" storage
81
-		\OC\Files\Filesystem::initMountManager();
82
-		if (!self::$rootMounted) {
83
-			\OC\Files\Filesystem::mount('\OC\Files\Storage\Local', array('datadir' => $configDataDirectory), '/');
84
-			self::$rootMounted = true;
85
-		}
86
-	}
87
-
88
-	/**
89
-	 * mounting an object storage as the root fs will in essence remove the
90
-	 * necessity of a data folder being present.
91
-	 * TODO make home storage aware of this and use the object storage instead of local disk access
92
-	 *
93
-	 * @param array $config containing 'class' and optional 'arguments'
94
-	 */
95
-	private static function initObjectStoreRootFS($config) {
96
-		// check misconfiguration
97
-		if (empty($config['class'])) {
98
-			\OCP\Util::writeLog('files', 'No class given for objectstore', \OCP\Util::ERROR);
99
-		}
100
-		if (!isset($config['arguments'])) {
101
-			$config['arguments'] = array();
102
-		}
103
-
104
-		// instantiate object store implementation
105
-		$name = $config['class'];
106
-		if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
107
-			$segments = explode('\\', $name);
108
-			OC_App::loadApp(strtolower($segments[1]));
109
-		}
110
-		$config['arguments']['objectstore'] = new $config['class']($config['arguments']);
111
-		// mount with plain / root object store implementation
112
-		$config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
113
-
114
-		// mount object storage as root
115
-		\OC\Files\Filesystem::initMountManager();
116
-		if (!self::$rootMounted) {
117
-			\OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
118
-			self::$rootMounted = true;
119
-		}
120
-	}
121
-
122
-	/**
123
-	 * Can be set up
124
-	 *
125
-	 * @param string $user
126
-	 * @return boolean
127
-	 * @description configure the initial filesystem based on the configuration
128
-	 */
129
-	public static function setupFS($user = '') {
130
-		//setting up the filesystem twice can only lead to trouble
131
-		if (self::$fsSetup) {
132
-			return false;
133
-		}
134
-
135
-		\OC::$server->getEventLogger()->start('setup_fs', 'Setup filesystem');
136
-
137
-		// If we are not forced to load a specific user we load the one that is logged in
138
-		if ($user === null) {
139
-			$user = '';
140
-		} else if ($user == "" && \OC::$server->getUserSession()->isLoggedIn()) {
141
-			$user = OC_User::getUser();
142
-		}
143
-
144
-		// load all filesystem apps before, so no setup-hook gets lost
145
-		OC_App::loadApps(array('filesystem'));
146
-
147
-		// the filesystem will finish when $user is not empty,
148
-		// mark fs setup here to avoid doing the setup from loading
149
-		// OC_Filesystem
150
-		if ($user != '') {
151
-			self::$fsSetup = true;
152
-		}
153
-
154
-		\OC\Files\Filesystem::initMountManager();
155
-
156
-		\OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false);
157
-		\OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
158
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) {
159
-				/** @var \OC\Files\Storage\Common $storage */
160
-				$storage->setMountOptions($mount->getOptions());
161
-			}
162
-			return $storage;
163
-		});
164
-
165
-		\OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
166
-			if (!$mount->getOption('enable_sharing', true)) {
167
-				return new \OC\Files\Storage\Wrapper\PermissionsMask([
168
-					'storage' => $storage,
169
-					'mask' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_SHARE
170
-				]);
171
-			}
172
-			return $storage;
173
-		});
174
-
175
-		// install storage availability wrapper, before most other wrappers
176
-		\OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, $storage) {
177
-			if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
178
-				return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]);
179
-			}
180
-			return $storage;
181
-		});
182
-
183
-		\OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
184
-			if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
185
-				return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]);
186
-			}
187
-			return $storage;
188
-		});
189
-
190
-		\OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
191
-			// set up quota for home storages, even for other users
192
-			// which can happen when using sharing
193
-
194
-			/**
195
-			 * @var \OC\Files\Storage\Storage $storage
196
-			 */
197
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
198
-				|| $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
199
-			) {
200
-				/** @var \OC\Files\Storage\Home $storage */
201
-				if (is_object($storage->getUser())) {
202
-					$user = $storage->getUser()->getUID();
203
-					$quota = OC_Util::getUserQuota($user);
204
-					if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
205
-						return new \OC\Files\Storage\Wrapper\Quota(array('storage' => $storage, 'quota' => $quota, 'root' => 'files'));
206
-					}
207
-				}
208
-			}
209
-
210
-			return $storage;
211
-		});
212
-
213
-		OC_Hook::emit('OC_Filesystem', 'preSetup', array('user' => $user));
214
-		\OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(true);
215
-
216
-		//check if we are using an object storage
217
-		$objectStore = \OC::$server->getSystemConfig()->getValue('objectstore', null);
218
-		if (isset($objectStore)) {
219
-			self::initObjectStoreRootFS($objectStore);
220
-		} else {
221
-			self::initLocalStorageRootFS();
222
-		}
223
-
224
-		if ($user != '' && !OCP\User::userExists($user)) {
225
-			\OC::$server->getEventLogger()->end('setup_fs');
226
-			return false;
227
-		}
228
-
229
-		//if we aren't logged in, there is no use to set up the filesystem
230
-		if ($user != "") {
231
-
232
-			$userDir = '/' . $user . '/files';
233
-
234
-			//jail the user into his "home" directory
235
-			\OC\Files\Filesystem::init($user, $userDir);
236
-
237
-			OC_Hook::emit('OC_Filesystem', 'setup', array('user' => $user, 'user_dir' => $userDir));
238
-		}
239
-		\OC::$server->getEventLogger()->end('setup_fs');
240
-		return true;
241
-	}
242
-
243
-	/**
244
-	 * check if a password is required for each public link
245
-	 *
246
-	 * @return boolean
247
-	 */
248
-	public static function isPublicLinkPasswordRequired() {
249
-		$appConfig = \OC::$server->getAppConfig();
250
-		$enforcePassword = $appConfig->getValue('core', 'shareapi_enforce_links_password', 'no');
251
-		return ($enforcePassword === 'yes') ? true : false;
252
-	}
253
-
254
-	/**
255
-	 * check if sharing is disabled for the current user
256
-	 * @param IConfig $config
257
-	 * @param IGroupManager $groupManager
258
-	 * @param IUser|null $user
259
-	 * @return bool
260
-	 */
261
-	public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) {
262
-		if ($config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
263
-			$groupsList = $config->getAppValue('core', 'shareapi_exclude_groups_list', '');
264
-			$excludedGroups = json_decode($groupsList);
265
-			if (is_null($excludedGroups)) {
266
-				$excludedGroups = explode(',', $groupsList);
267
-				$newValue = json_encode($excludedGroups);
268
-				$config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
269
-			}
270
-			$usersGroups = $groupManager->getUserGroupIds($user);
271
-			if (!empty($usersGroups)) {
272
-				$remainingGroups = array_diff($usersGroups, $excludedGroups);
273
-				// if the user is only in groups which are disabled for sharing then
274
-				// sharing is also disabled for the user
275
-				if (empty($remainingGroups)) {
276
-					return true;
277
-				}
278
-			}
279
-		}
280
-		return false;
281
-	}
282
-
283
-	/**
284
-	 * check if share API enforces a default expire date
285
-	 *
286
-	 * @return boolean
287
-	 */
288
-	public static function isDefaultExpireDateEnforced() {
289
-		$isDefaultExpireDateEnabled = \OCP\Config::getAppValue('core', 'shareapi_default_expire_date', 'no');
290
-		$enforceDefaultExpireDate = false;
291
-		if ($isDefaultExpireDateEnabled === 'yes') {
292
-			$value = \OCP\Config::getAppValue('core', 'shareapi_enforce_expire_date', 'no');
293
-			$enforceDefaultExpireDate = ($value === 'yes') ? true : false;
294
-		}
295
-
296
-		return $enforceDefaultExpireDate;
297
-	}
298
-
299
-	/**
300
-	 * Get the quota of a user
301
-	 *
302
-	 * @param string $userId
303
-	 * @return int Quota bytes
304
-	 */
305
-	public static function getUserQuota($userId) {
306
-		$user = \OC::$server->getUserManager()->get($userId);
307
-		if (is_null($user)) {
308
-			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
309
-		}
310
-		$userQuota = $user->getQuota();
311
-		if($userQuota === 'none') {
312
-			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
313
-		}
314
-		return OC_Helper::computerFileSize($userQuota);
315
-	}
316
-
317
-	/**
318
-	 * copies the skeleton to the users /files
319
-	 *
320
-	 * @param String $userId
321
-	 * @param \OCP\Files\Folder $userDirectory
322
-	 * @throws \RuntimeException
323
-	 */
324
-	public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
325
-
326
-		$skeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
327
-		$instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', '');
328
-
329
-		if ($instanceId === null) {
330
-			throw new \RuntimeException('no instance id!');
331
-		}
332
-		$appdata = 'appdata_' . $instanceId;
333
-		if ($userId === $appdata) {
334
-			throw new \RuntimeException('username is reserved name: ' . $appdata);
335
-		}
336
-
337
-		if (!empty($skeletonDirectory)) {
338
-			\OCP\Util::writeLog(
339
-				'files_skeleton',
340
-				'copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'),
341
-				\OCP\Util::DEBUG
342
-			);
343
-			self::copyr($skeletonDirectory, $userDirectory);
344
-			// update the file cache
345
-			$userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
346
-		}
347
-	}
348
-
349
-	/**
350
-	 * copies a directory recursively by using streams
351
-	 *
352
-	 * @param string $source
353
-	 * @param \OCP\Files\Folder $target
354
-	 * @return void
355
-	 */
356
-	public static function copyr($source, \OCP\Files\Folder $target) {
357
-		$logger = \OC::$server->getLogger();
358
-
359
-		// Verify if folder exists
360
-		$dir = opendir($source);
361
-		if($dir === false) {
362
-			$logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
363
-			return;
364
-		}
365
-
366
-		// Copy the files
367
-		while (false !== ($file = readdir($dir))) {
368
-			if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
369
-				if (is_dir($source . '/' . $file)) {
370
-					$child = $target->newFolder($file);
371
-					self::copyr($source . '/' . $file, $child);
372
-				} else {
373
-					$child = $target->newFile($file);
374
-					$sourceStream = fopen($source . '/' . $file, 'r');
375
-					if($sourceStream === false) {
376
-						$logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
377
-						closedir($dir);
378
-						return;
379
-					}
380
-					stream_copy_to_stream($sourceStream, $child->fopen('w'));
381
-				}
382
-			}
383
-		}
384
-		closedir($dir);
385
-	}
386
-
387
-	/**
388
-	 * @return void
389
-	 */
390
-	public static function tearDownFS() {
391
-		\OC\Files\Filesystem::tearDown();
392
-		\OC::$server->getRootFolder()->clearCache();
393
-		self::$fsSetup = false;
394
-		self::$rootMounted = false;
395
-	}
396
-
397
-	/**
398
-	 * get the current installed version of ownCloud
399
-	 *
400
-	 * @return array
401
-	 */
402
-	public static function getVersion() {
403
-		OC_Util::loadVersion();
404
-		return self::$versionCache['OC_Version'];
405
-	}
406
-
407
-	/**
408
-	 * get the current installed version string of ownCloud
409
-	 *
410
-	 * @return string
411
-	 */
412
-	public static function getVersionString() {
413
-		OC_Util::loadVersion();
414
-		return self::$versionCache['OC_VersionString'];
415
-	}
416
-
417
-	/**
418
-	 * @deprecated the value is of no use anymore
419
-	 * @return string
420
-	 */
421
-	public static function getEditionString() {
422
-		return '';
423
-	}
424
-
425
-	/**
426
-	 * @description get the update channel of the current installed of ownCloud.
427
-	 * @return string
428
-	 */
429
-	public static function getChannel() {
430
-		OC_Util::loadVersion();
431
-		return \OC::$server->getConfig()->getSystemValue('updater.release.channel', self::$versionCache['OC_Channel']);
432
-	}
433
-
434
-	/**
435
-	 * @description get the build number of the current installed of ownCloud.
436
-	 * @return string
437
-	 */
438
-	public static function getBuild() {
439
-		OC_Util::loadVersion();
440
-		return self::$versionCache['OC_Build'];
441
-	}
442
-
443
-	/**
444
-	 * @description load the version.php into the session as cache
445
-	 */
446
-	private static function loadVersion() {
447
-		if (self::$versionCache !== null) {
448
-			return;
449
-		}
450
-
451
-		$timestamp = filemtime(OC::$SERVERROOT . '/version.php');
452
-		require OC::$SERVERROOT . '/version.php';
453
-		/** @var $timestamp int */
454
-		self::$versionCache['OC_Version_Timestamp'] = $timestamp;
455
-		/** @var $OC_Version string */
456
-		self::$versionCache['OC_Version'] = $OC_Version;
457
-		/** @var $OC_VersionString string */
458
-		self::$versionCache['OC_VersionString'] = $OC_VersionString;
459
-		/** @var $OC_Build string */
460
-		self::$versionCache['OC_Build'] = $OC_Build;
461
-
462
-		/** @var $OC_Channel string */
463
-		self::$versionCache['OC_Channel'] = $OC_Channel;
464
-	}
465
-
466
-	/**
467
-	 * generates a path for JS/CSS files. If no application is provided it will create the path for core.
468
-	 *
469
-	 * @param string $application application to get the files from
470
-	 * @param string $directory directory within this application (css, js, vendor, etc)
471
-	 * @param string $file the file inside of the above folder
472
-	 * @return string the path
473
-	 */
474
-	private static function generatePath($application, $directory, $file) {
475
-		if (is_null($file)) {
476
-			$file = $application;
477
-			$application = "";
478
-		}
479
-		if (!empty($application)) {
480
-			return "$application/$directory/$file";
481
-		} else {
482
-			return "$directory/$file";
483
-		}
484
-	}
485
-
486
-	/**
487
-	 * add a javascript file
488
-	 *
489
-	 * @param string $application application id
490
-	 * @param string|null $file filename
491
-	 * @param bool $prepend prepend the Script to the beginning of the list
492
-	 * @return void
493
-	 */
494
-	public static function addScript($application, $file = null, $prepend = false) {
495
-		$path = OC_Util::generatePath($application, 'js', $file);
496
-
497
-		// core js files need separate handling
498
-		if ($application !== 'core' && $file !== null) {
499
-			self::addTranslations ( $application );
500
-		}
501
-		self::addExternalResource($application, $prepend, $path, "script");
502
-	}
503
-
504
-	/**
505
-	 * add a javascript file from the vendor sub folder
506
-	 *
507
-	 * @param string $application application id
508
-	 * @param string|null $file filename
509
-	 * @param bool $prepend prepend the Script to the beginning of the list
510
-	 * @return void
511
-	 */
512
-	public static function addVendorScript($application, $file = null, $prepend = false) {
513
-		$path = OC_Util::generatePath($application, 'vendor', $file);
514
-		self::addExternalResource($application, $prepend, $path, "script");
515
-	}
516
-
517
-	/**
518
-	 * add a translation JS file
519
-	 *
520
-	 * @param string $application application id
521
-	 * @param string $languageCode language code, defaults to the current language
522
-	 * @param bool $prepend prepend the Script to the beginning of the list
523
-	 */
524
-	public static function addTranslations($application, $languageCode = null, $prepend = false) {
525
-		if (is_null($languageCode)) {
526
-			$languageCode = \OC::$server->getL10NFactory()->findLanguage($application);
527
-		}
528
-		if (!empty($application)) {
529
-			$path = "$application/l10n/$languageCode";
530
-		} else {
531
-			$path = "l10n/$languageCode";
532
-		}
533
-		self::addExternalResource($application, $prepend, $path, "script");
534
-	}
535
-
536
-	/**
537
-	 * add a css file
538
-	 *
539
-	 * @param string $application application id
540
-	 * @param string|null $file filename
541
-	 * @param bool $prepend prepend the Style to the beginning of the list
542
-	 * @return void
543
-	 */
544
-	public static function addStyle($application, $file = null, $prepend = false) {
545
-		$path = OC_Util::generatePath($application, 'css', $file);
546
-		self::addExternalResource($application, $prepend, $path, "style");
547
-	}
548
-
549
-	/**
550
-	 * add a css file from the vendor sub folder
551
-	 *
552
-	 * @param string $application application id
553
-	 * @param string|null $file filename
554
-	 * @param bool $prepend prepend the Style to the beginning of the list
555
-	 * @return void
556
-	 */
557
-	public static function addVendorStyle($application, $file = null, $prepend = false) {
558
-		$path = OC_Util::generatePath($application, 'vendor', $file);
559
-		self::addExternalResource($application, $prepend, $path, "style");
560
-	}
561
-
562
-	/**
563
-	 * add an external resource css/js file
564
-	 *
565
-	 * @param string $application application id
566
-	 * @param bool $prepend prepend the file to the beginning of the list
567
-	 * @param string $path
568
-	 * @param string $type (script or style)
569
-	 * @return void
570
-	 */
571
-	private static function addExternalResource($application, $prepend, $path, $type = "script") {
572
-
573
-		if ($type === "style") {
574
-			if (!in_array($path, self::$styles)) {
575
-				if ($prepend === true) {
576
-					array_unshift ( self::$styles, $path );
577
-				} else {
578
-					self::$styles[] = $path;
579
-				}
580
-			}
581
-		} elseif ($type === "script") {
582
-			if (!in_array($path, self::$scripts)) {
583
-				if ($prepend === true) {
584
-					array_unshift ( self::$scripts, $path );
585
-				} else {
586
-					self::$scripts [] = $path;
587
-				}
588
-			}
589
-		}
590
-	}
591
-
592
-	/**
593
-	 * Add a custom element to the header
594
-	 * If $text is null then the element will be written as empty element.
595
-	 * So use "" to get a closing tag.
596
-	 * @param string $tag tag name of the element
597
-	 * @param array $attributes array of attributes for the element
598
-	 * @param string $text the text content for the element
599
-	 */
600
-	public static function addHeader($tag, $attributes, $text=null) {
601
-		self::$headers[] = array(
602
-			'tag' => $tag,
603
-			'attributes' => $attributes,
604
-			'text' => $text
605
-		);
606
-	}
607
-
608
-	/**
609
-	 * formats a timestamp in the "right" way
610
-	 *
611
-	 * @param int $timestamp
612
-	 * @param bool $dateOnly option to omit time from the result
613
-	 * @param DateTimeZone|string $timeZone where the given timestamp shall be converted to
614
-	 * @return string timestamp
615
-	 *
616
-	 * @deprecated Use \OC::$server->query('DateTimeFormatter') instead
617
-	 */
618
-	public static function formatDate($timestamp, $dateOnly = false, $timeZone = null) {
619
-		if ($timeZone !== null && !$timeZone instanceof \DateTimeZone) {
620
-			$timeZone = new \DateTimeZone($timeZone);
621
-		}
622
-
623
-		/** @var \OC\DateTimeFormatter $formatter */
624
-		$formatter = \OC::$server->query('DateTimeFormatter');
625
-		if ($dateOnly) {
626
-			return $formatter->formatDate($timestamp, 'long', $timeZone);
627
-		}
628
-		return $formatter->formatDateTime($timestamp, 'long', 'long', $timeZone);
629
-	}
630
-
631
-	/**
632
-	 * check if the current server configuration is suitable for ownCloud
633
-	 *
634
-	 * @param \OC\SystemConfig $config
635
-	 * @return array arrays with error messages and hints
636
-	 */
637
-	public static function checkServer(\OC\SystemConfig $config) {
638
-		$l = \OC::$server->getL10N('lib');
639
-		$errors = array();
640
-		$CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
641
-
642
-		if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
643
-			// this check needs to be done every time
644
-			$errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
645
-		}
646
-
647
-		// Assume that if checkServer() succeeded before in this session, then all is fine.
648
-		if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
649
-			return $errors;
650
-		}
651
-
652
-		$webServerRestart = false;
653
-		$setup = new \OC\Setup($config, \OC::$server->getIniWrapper(), \OC::$server->getL10N('lib'),
654
-			\OC::$server->getDefaults(), \OC::$server->getLogger(), \OC::$server->getSecureRandom());
655
-
656
-		$urlGenerator = \OC::$server->getURLGenerator();
657
-
658
-		$availableDatabases = $setup->getSupportedDatabases();
659
-		if (empty($availableDatabases)) {
660
-			$errors[] = array(
661
-				'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
662
-				'hint' => '' //TODO: sane hint
663
-			);
664
-			$webServerRestart = true;
665
-		}
666
-
667
-		// Check if config folder is writable.
668
-		if(!OC_Helper::isReadOnlyConfigEnabled()) {
669
-			if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
670
-				$errors[] = array(
671
-					'error' => $l->t('Cannot write into "config" directory'),
672
-					'hint' => $l->t('This can usually be fixed by '
673
-						. '%sgiving the webserver write access to the config directory%s.',
674
-						array('<a href="' . $urlGenerator->linkToDocs('admin-dir_permissions') . '" target="_blank" rel="noreferrer">', '</a>'))
675
-				);
676
-			}
677
-		}
678
-
679
-		// Check if there is a writable install folder.
680
-		if ($config->getValue('appstoreenabled', true)) {
681
-			if (OC_App::getInstallPath() === null
682
-				|| !is_writable(OC_App::getInstallPath())
683
-				|| !is_readable(OC_App::getInstallPath())
684
-			) {
685
-				$errors[] = array(
686
-					'error' => $l->t('Cannot write into "apps" directory'),
687
-					'hint' => $l->t('This can usually be fixed by '
688
-						. '%sgiving the webserver write access to the apps directory%s'
689
-						. ' or disabling the appstore in the config file.',
690
-						array('<a href="' . $urlGenerator->linkToDocs('admin-dir_permissions') . '" target="_blank" rel="noreferrer">', '</a>'))
691
-				);
692
-			}
693
-		}
694
-		// Create root dir.
695
-		if ($config->getValue('installed', false)) {
696
-			if (!is_dir($CONFIG_DATADIRECTORY)) {
697
-				$success = @mkdir($CONFIG_DATADIRECTORY);
698
-				if ($success) {
699
-					$errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
700
-				} else {
701
-					$errors[] = array(
702
-						'error' => $l->t('Cannot create "data" directory (%s)', array($CONFIG_DATADIRECTORY)),
703
-						'hint' => $l->t('This can usually be fixed by '
704
-							. '<a href="%s" target="_blank" rel="noreferrer">giving the webserver write access to the root directory</a>.',
705
-							array($urlGenerator->linkToDocs('admin-dir_permissions')))
706
-					);
707
-				}
708
-			} else if (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
709
-				//common hint for all file permissions error messages
710
-				$permissionsHint = $l->t('Permissions can usually be fixed by '
711
-					. '%sgiving the webserver write access to the root directory%s.',
712
-					array('<a href="' . $urlGenerator->linkToDocs('admin-dir_permissions') . '" target="_blank" rel="noreferrer">', '</a>'));
713
-				$errors[] = array(
714
-					'error' => 'Data directory (' . $CONFIG_DATADIRECTORY . ') not writable',
715
-					'hint' => $permissionsHint
716
-				);
717
-			} else {
718
-				$errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
719
-			}
720
-		}
721
-
722
-		if (!OC_Util::isSetLocaleWorking()) {
723
-			$errors[] = array(
724
-				'error' => $l->t('Setting locale to %s failed',
725
-					array('en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
726
-						. 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8')),
727
-				'hint' => $l->t('Please install one of these locales on your system and restart your webserver.')
728
-			);
729
-		}
730
-
731
-		// Contains the dependencies that should be checked against
732
-		// classes = class_exists
733
-		// functions = function_exists
734
-		// defined = defined
735
-		// ini = ini_get
736
-		// If the dependency is not found the missing module name is shown to the EndUser
737
-		// When adding new checks always verify that they pass on Travis as well
738
-		// for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini
739
-		$dependencies = array(
740
-			'classes' => array(
741
-				'ZipArchive' => 'zip',
742
-				'DOMDocument' => 'dom',
743
-				'XMLWriter' => 'XMLWriter',
744
-				'XMLReader' => 'XMLReader',
745
-			),
746
-			'functions' => [
747
-				'xml_parser_create' => 'libxml',
748
-				'mb_strcut' => 'mb multibyte',
749
-				'ctype_digit' => 'ctype',
750
-				'json_encode' => 'JSON',
751
-				'gd_info' => 'GD',
752
-				'gzencode' => 'zlib',
753
-				'iconv' => 'iconv',
754
-				'simplexml_load_string' => 'SimpleXML',
755
-				'hash' => 'HASH Message Digest Framework',
756
-				'curl_init' => 'cURL',
757
-				'openssl_verify' => 'OpenSSL',
758
-			],
759
-			'defined' => array(
760
-				'PDO::ATTR_DRIVER_NAME' => 'PDO'
761
-			),
762
-			'ini' => [
763
-				'default_charset' => 'UTF-8',
764
-			],
765
-		);
766
-		$missingDependencies = array();
767
-		$invalidIniSettings = [];
768
-		$moduleHint = $l->t('Please ask your server administrator to install the module.');
769
-
770
-		/**
771
-		 * FIXME: The dependency check does not work properly on HHVM on the moment
772
-		 *        and prevents installation. Once HHVM is more compatible with our
773
-		 *        approach to check for these values we should re-enable those
774
-		 *        checks.
775
-		 */
776
-		$iniWrapper = \OC::$server->getIniWrapper();
777
-		if (!self::runningOnHhvm()) {
778
-			foreach ($dependencies['classes'] as $class => $module) {
779
-				if (!class_exists($class)) {
780
-					$missingDependencies[] = $module;
781
-				}
782
-			}
783
-			foreach ($dependencies['functions'] as $function => $module) {
784
-				if (!function_exists($function)) {
785
-					$missingDependencies[] = $module;
786
-				}
787
-			}
788
-			foreach ($dependencies['defined'] as $defined => $module) {
789
-				if (!defined($defined)) {
790
-					$missingDependencies[] = $module;
791
-				}
792
-			}
793
-			foreach ($dependencies['ini'] as $setting => $expected) {
794
-				if (is_bool($expected)) {
795
-					if ($iniWrapper->getBool($setting) !== $expected) {
796
-						$invalidIniSettings[] = [$setting, $expected];
797
-					}
798
-				}
799
-				if (is_int($expected)) {
800
-					if ($iniWrapper->getNumeric($setting) !== $expected) {
801
-						$invalidIniSettings[] = [$setting, $expected];
802
-					}
803
-				}
804
-				if (is_string($expected)) {
805
-					if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
806
-						$invalidIniSettings[] = [$setting, $expected];
807
-					}
808
-				}
809
-			}
810
-		}
811
-
812
-		foreach($missingDependencies as $missingDependency) {
813
-			$errors[] = array(
814
-				'error' => $l->t('PHP module %s not installed.', array($missingDependency)),
815
-				'hint' => $moduleHint
816
-			);
817
-			$webServerRestart = true;
818
-		}
819
-		foreach($invalidIniSettings as $setting) {
820
-			if(is_bool($setting[1])) {
821
-				$setting[1] = ($setting[1]) ? 'on' : 'off';
822
-			}
823
-			$errors[] = [
824
-				'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
825
-				'hint' =>  $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
826
-			];
827
-			$webServerRestart = true;
828
-		}
829
-
830
-		/**
831
-		 * The mbstring.func_overload check can only be performed if the mbstring
832
-		 * module is installed as it will return null if the checking setting is
833
-		 * not available and thus a check on the boolean value fails.
834
-		 *
835
-		 * TODO: Should probably be implemented in the above generic dependency
836
-		 *       check somehow in the long-term.
837
-		 */
838
-		if($iniWrapper->getBool('mbstring.func_overload') !== null &&
839
-			$iniWrapper->getBool('mbstring.func_overload') === true) {
840
-			$errors[] = array(
841
-				'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]),
842
-				'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini')
843
-			);
844
-		}
845
-
846
-		if(function_exists('xml_parser_create') &&
847
-			LIBXML_LOADED_VERSION < 20700 ) {
848
-			$version = LIBXML_LOADED_VERSION;
849
-			$major = floor($version/10000);
850
-			$version -= ($major * 10000);
851
-			$minor = floor($version/100);
852
-			$version -= ($minor * 100);
853
-			$patch = $version;
854
-			$errors[] = array(
855
-				'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
856
-				'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
857
-			);
858
-		}
859
-
860
-		if (!self::isAnnotationsWorking()) {
861
-			$errors[] = array(
862
-				'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
863
-				'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
864
-			);
865
-		}
866
-
867
-		if (!\OC::$CLI && $webServerRestart) {
868
-			$errors[] = array(
869
-				'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
870
-				'hint' => $l->t('Please ask your server administrator to restart the web server.')
871
-			);
872
-		}
873
-
874
-		$errors = array_merge($errors, self::checkDatabaseVersion());
875
-
876
-		// Cache the result of this function
877
-		\OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
878
-
879
-		return $errors;
880
-	}
881
-
882
-	/**
883
-	 * Check the database version
884
-	 *
885
-	 * @return array errors array
886
-	 */
887
-	public static function checkDatabaseVersion() {
888
-		$l = \OC::$server->getL10N('lib');
889
-		$errors = array();
890
-		$dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite');
891
-		if ($dbType === 'pgsql') {
892
-			// check PostgreSQL version
893
-			try {
894
-				$result = \OC_DB::executeAudited('SHOW SERVER_VERSION');
895
-				$data = $result->fetchRow();
896
-				if (isset($data['server_version'])) {
897
-					$version = $data['server_version'];
898
-					if (version_compare($version, '9.0.0', '<')) {
899
-						$errors[] = array(
900
-							'error' => $l->t('PostgreSQL >= 9 required'),
901
-							'hint' => $l->t('Please upgrade your database version')
902
-						);
903
-					}
904
-				}
905
-			} catch (\Doctrine\DBAL\DBALException $e) {
906
-				$logger = \OC::$server->getLogger();
907
-				$logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9');
908
-				$logger->logException($e);
909
-			}
910
-		}
911
-		return $errors;
912
-	}
913
-
914
-	/**
915
-	 * Check for correct file permissions of data directory
916
-	 *
917
-	 * @param string $dataDirectory
918
-	 * @return array arrays with error messages and hints
919
-	 */
920
-	public static function checkDataDirectoryPermissions($dataDirectory) {
921
-		$l = \OC::$server->getL10N('lib');
922
-		$errors = array();
923
-		$permissionsModHint = $l->t('Please change the permissions to 0770 so that the directory'
924
-			. ' cannot be listed by other users.');
925
-		$perms = substr(decoct(@fileperms($dataDirectory)), -3);
926
-		if (substr($perms, -1) != '0') {
927
-			chmod($dataDirectory, 0770);
928
-			clearstatcache();
929
-			$perms = substr(decoct(@fileperms($dataDirectory)), -3);
930
-			if (substr($perms, 2, 1) != '0') {
931
-				$errors[] = array(
932
-					'error' => $l->t('Data directory (%s) is readable by other users', array($dataDirectory)),
933
-					'hint' => $permissionsModHint
934
-				);
935
-			}
936
-		}
937
-		return $errors;
938
-	}
939
-
940
-	/**
941
-	 * Check that the data directory exists and is valid by
942
-	 * checking the existence of the ".ocdata" file.
943
-	 *
944
-	 * @param string $dataDirectory data directory path
945
-	 * @return array errors found
946
-	 */
947
-	public static function checkDataDirectoryValidity($dataDirectory) {
948
-		$l = \OC::$server->getL10N('lib');
949
-		$errors = [];
950
-		if ($dataDirectory[0] !== '/') {
951
-			$errors[] = [
952
-				'error' => $l->t('Data directory (%s) must be an absolute path', [$dataDirectory]),
953
-				'hint' => $l->t('Check the value of "datadirectory" in your configuration')
954
-			];
955
-		}
956
-		if (!file_exists($dataDirectory . '/.ocdata')) {
957
-			$errors[] = [
958
-				'error' => $l->t('Data directory (%s) is invalid', [$dataDirectory]),
959
-				'hint' => $l->t('Please check that the data directory contains a file' .
960
-					' ".ocdata" in its root.')
961
-			];
962
-		}
963
-		return $errors;
964
-	}
965
-
966
-	/**
967
-	 * Check if the user is logged in, redirects to home if not. With
968
-	 * redirect URL parameter to the request URI.
969
-	 *
970
-	 * @return void
971
-	 */
972
-	public static function checkLoggedIn() {
973
-		// Check if we are a user
974
-		if (!\OC::$server->getUserSession()->isLoggedIn()) {
975
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
976
-						'core.login.showLoginForm',
977
-						[
978
-							'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
979
-						]
980
-					)
981
-			);
982
-			exit();
983
-		}
984
-		// Redirect to 2FA challenge selection if 2FA challenge was not solved yet
985
-		if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
986
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
987
-			exit();
988
-		}
989
-	}
990
-
991
-	/**
992
-	 * Check if the user is a admin, redirects to home if not
993
-	 *
994
-	 * @return void
995
-	 */
996
-	public static function checkAdminUser() {
997
-		OC_Util::checkLoggedIn();
998
-		if (!OC_User::isAdminUser(OC_User::getUser())) {
999
-			header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1000
-			exit();
1001
-		}
1002
-	}
1003
-
1004
-	/**
1005
-	 * Check if the user is a subadmin, redirects to home if not
1006
-	 *
1007
-	 * @return null|boolean $groups where the current user is subadmin
1008
-	 */
1009
-	public static function checkSubAdminUser() {
1010
-		OC_Util::checkLoggedIn();
1011
-		$userObject = \OC::$server->getUserSession()->getUser();
1012
-		$isSubAdmin = false;
1013
-		if($userObject !== null) {
1014
-			$isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
1015
-		}
1016
-
1017
-		if (!$isSubAdmin) {
1018
-			header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1019
-			exit();
1020
-		}
1021
-		return true;
1022
-	}
1023
-
1024
-	/**
1025
-	 * Returns the URL of the default page
1026
-	 * based on the system configuration and
1027
-	 * the apps visible for the current user
1028
-	 *
1029
-	 * @return string URL
1030
-	 */
1031
-	public static function getDefaultPageUrl() {
1032
-		$urlGenerator = \OC::$server->getURLGenerator();
1033
-		// Deny the redirect if the URL contains a @
1034
-		// This prevents unvalidated redirects like ?redirect_url=:[email protected]
1035
-		if (isset($_REQUEST['redirect_url']) && strpos($_REQUEST['redirect_url'], '@') === false) {
1036
-			$location = $urlGenerator->getAbsoluteURL(urldecode($_REQUEST['redirect_url']));
1037
-		} else {
1038
-			$defaultPage = \OC::$server->getAppConfig()->getValue('core', 'defaultpage');
1039
-			if ($defaultPage) {
1040
-				$location = $urlGenerator->getAbsoluteURL($defaultPage);
1041
-			} else {
1042
-				$appId = 'files';
1043
-				$defaultApps = explode(',', \OCP\Config::getSystemValue('defaultapp', 'files'));
1044
-				// find the first app that is enabled for the current user
1045
-				foreach ($defaultApps as $defaultApp) {
1046
-					$defaultApp = OC_App::cleanAppId(strip_tags($defaultApp));
1047
-					if (static::getAppManager()->isEnabledForUser($defaultApp)) {
1048
-						$appId = $defaultApp;
1049
-						break;
1050
-					}
1051
-				}
1052
-
1053
-				if(\OC::$server->getConfig()->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') {
1054
-					$location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/');
1055
-				} else {
1056
-					$location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/');
1057
-				}
1058
-			}
1059
-		}
1060
-		return $location;
1061
-	}
1062
-
1063
-	/**
1064
-	 * Redirect to the user default page
1065
-	 *
1066
-	 * @return void
1067
-	 */
1068
-	public static function redirectToDefaultPage() {
1069
-		$location = self::getDefaultPageUrl();
1070
-		header('Location: ' . $location);
1071
-		exit();
1072
-	}
1073
-
1074
-	/**
1075
-	 * get an id unique for this instance
1076
-	 *
1077
-	 * @return string
1078
-	 */
1079
-	public static function getInstanceId() {
1080
-		$id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
1081
-		if (is_null($id)) {
1082
-			// We need to guarantee at least one letter in instanceid so it can be used as the session_name
1083
-			$id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1084
-			\OC::$server->getSystemConfig()->setValue('instanceid', $id);
1085
-		}
1086
-		return $id;
1087
-	}
1088
-
1089
-	/**
1090
-	 * Public function to sanitize HTML
1091
-	 *
1092
-	 * This function is used to sanitize HTML and should be applied on any
1093
-	 * string or array of strings before displaying it on a web page.
1094
-	 *
1095
-	 * @param string|array $value
1096
-	 * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
1097
-	 */
1098
-	public static function sanitizeHTML($value) {
1099
-		if (is_array($value)) {
1100
-			$value = array_map(function($value) {
1101
-				return self::sanitizeHTML($value);
1102
-			}, $value);
1103
-		} else {
1104
-			// Specify encoding for PHP<5.4
1105
-			$value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
1106
-		}
1107
-		return $value;
1108
-	}
1109
-
1110
-	/**
1111
-	 * Public function to encode url parameters
1112
-	 *
1113
-	 * This function is used to encode path to file before output.
1114
-	 * Encoding is done according to RFC 3986 with one exception:
1115
-	 * Character '/' is preserved as is.
1116
-	 *
1117
-	 * @param string $component part of URI to encode
1118
-	 * @return string
1119
-	 */
1120
-	public static function encodePath($component) {
1121
-		$encoded = rawurlencode($component);
1122
-		$encoded = str_replace('%2F', '/', $encoded);
1123
-		return $encoded;
1124
-	}
1125
-
1126
-
1127
-	public function createHtaccessTestFile(\OCP\IConfig $config) {
1128
-		// php dev server does not support htaccess
1129
-		if (php_sapi_name() === 'cli-server') {
1130
-			return false;
1131
-		}
1132
-
1133
-		// testdata
1134
-		$fileName = '/htaccesstest.txt';
1135
-		$testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
1136
-
1137
-		// creating a test file
1138
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1139
-
1140
-		if (file_exists($testFile)) {// already running this test, possible recursive call
1141
-			return false;
1142
-		}
1143
-
1144
-		$fp = @fopen($testFile, 'w');
1145
-		if (!$fp) {
1146
-			throw new OC\HintException('Can\'t create test file to check for working .htaccess file.',
1147
-				'Make sure it is possible for the webserver to write to ' . $testFile);
1148
-		}
1149
-		fwrite($fp, $testContent);
1150
-		fclose($fp);
1151
-
1152
-		return $testContent;
1153
-	}
1154
-
1155
-	/**
1156
-	 * Check if the .htaccess file is working
1157
-	 * @param \OCP\IConfig $config
1158
-	 * @return bool
1159
-	 * @throws Exception
1160
-	 * @throws \OC\HintException If the test file can't get written.
1161
-	 */
1162
-	public function isHtaccessWorking(\OCP\IConfig $config) {
1163
-
1164
-		if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) {
1165
-			return true;
1166
-		}
1167
-
1168
-		$testContent = $this->createHtaccessTestFile($config);
1169
-		if ($testContent === false) {
1170
-			return false;
1171
-		}
1172
-
1173
-		$fileName = '/htaccesstest.txt';
1174
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1175
-
1176
-		// accessing the file via http
1177
-		$url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
1178
-		try {
1179
-			$content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1180
-		} catch (\Exception $e) {
1181
-			$content = false;
1182
-		}
1183
-
1184
-		// cleanup
1185
-		@unlink($testFile);
1186
-
1187
-		/*
64
+    public static $scripts = array();
65
+    public static $styles = array();
66
+    public static $headers = array();
67
+    private static $rootMounted = false;
68
+    private static $fsSetup = false;
69
+
70
+    /** @var array Local cache of version.php */
71
+    private static $versionCache = null;
72
+
73
+    protected static function getAppManager() {
74
+        return \OC::$server->getAppManager();
75
+    }
76
+
77
+    private static function initLocalStorageRootFS() {
78
+        // mount local file backend as root
79
+        $configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data");
80
+        //first set up the local "root" storage
81
+        \OC\Files\Filesystem::initMountManager();
82
+        if (!self::$rootMounted) {
83
+            \OC\Files\Filesystem::mount('\OC\Files\Storage\Local', array('datadir' => $configDataDirectory), '/');
84
+            self::$rootMounted = true;
85
+        }
86
+    }
87
+
88
+    /**
89
+     * mounting an object storage as the root fs will in essence remove the
90
+     * necessity of a data folder being present.
91
+     * TODO make home storage aware of this and use the object storage instead of local disk access
92
+     *
93
+     * @param array $config containing 'class' and optional 'arguments'
94
+     */
95
+    private static function initObjectStoreRootFS($config) {
96
+        // check misconfiguration
97
+        if (empty($config['class'])) {
98
+            \OCP\Util::writeLog('files', 'No class given for objectstore', \OCP\Util::ERROR);
99
+        }
100
+        if (!isset($config['arguments'])) {
101
+            $config['arguments'] = array();
102
+        }
103
+
104
+        // instantiate object store implementation
105
+        $name = $config['class'];
106
+        if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
107
+            $segments = explode('\\', $name);
108
+            OC_App::loadApp(strtolower($segments[1]));
109
+        }
110
+        $config['arguments']['objectstore'] = new $config['class']($config['arguments']);
111
+        // mount with plain / root object store implementation
112
+        $config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
113
+
114
+        // mount object storage as root
115
+        \OC\Files\Filesystem::initMountManager();
116
+        if (!self::$rootMounted) {
117
+            \OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
118
+            self::$rootMounted = true;
119
+        }
120
+    }
121
+
122
+    /**
123
+     * Can be set up
124
+     *
125
+     * @param string $user
126
+     * @return boolean
127
+     * @description configure the initial filesystem based on the configuration
128
+     */
129
+    public static function setupFS($user = '') {
130
+        //setting up the filesystem twice can only lead to trouble
131
+        if (self::$fsSetup) {
132
+            return false;
133
+        }
134
+
135
+        \OC::$server->getEventLogger()->start('setup_fs', 'Setup filesystem');
136
+
137
+        // If we are not forced to load a specific user we load the one that is logged in
138
+        if ($user === null) {
139
+            $user = '';
140
+        } else if ($user == "" && \OC::$server->getUserSession()->isLoggedIn()) {
141
+            $user = OC_User::getUser();
142
+        }
143
+
144
+        // load all filesystem apps before, so no setup-hook gets lost
145
+        OC_App::loadApps(array('filesystem'));
146
+
147
+        // the filesystem will finish when $user is not empty,
148
+        // mark fs setup here to avoid doing the setup from loading
149
+        // OC_Filesystem
150
+        if ($user != '') {
151
+            self::$fsSetup = true;
152
+        }
153
+
154
+        \OC\Files\Filesystem::initMountManager();
155
+
156
+        \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false);
157
+        \OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
158
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) {
159
+                /** @var \OC\Files\Storage\Common $storage */
160
+                $storage->setMountOptions($mount->getOptions());
161
+            }
162
+            return $storage;
163
+        });
164
+
165
+        \OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
166
+            if (!$mount->getOption('enable_sharing', true)) {
167
+                return new \OC\Files\Storage\Wrapper\PermissionsMask([
168
+                    'storage' => $storage,
169
+                    'mask' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_SHARE
170
+                ]);
171
+            }
172
+            return $storage;
173
+        });
174
+
175
+        // install storage availability wrapper, before most other wrappers
176
+        \OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, $storage) {
177
+            if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
178
+                return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]);
179
+            }
180
+            return $storage;
181
+        });
182
+
183
+        \OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
184
+            if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
185
+                return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]);
186
+            }
187
+            return $storage;
188
+        });
189
+
190
+        \OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
191
+            // set up quota for home storages, even for other users
192
+            // which can happen when using sharing
193
+
194
+            /**
195
+             * @var \OC\Files\Storage\Storage $storage
196
+             */
197
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
198
+                || $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
199
+            ) {
200
+                /** @var \OC\Files\Storage\Home $storage */
201
+                if (is_object($storage->getUser())) {
202
+                    $user = $storage->getUser()->getUID();
203
+                    $quota = OC_Util::getUserQuota($user);
204
+                    if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
205
+                        return new \OC\Files\Storage\Wrapper\Quota(array('storage' => $storage, 'quota' => $quota, 'root' => 'files'));
206
+                    }
207
+                }
208
+            }
209
+
210
+            return $storage;
211
+        });
212
+
213
+        OC_Hook::emit('OC_Filesystem', 'preSetup', array('user' => $user));
214
+        \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(true);
215
+
216
+        //check if we are using an object storage
217
+        $objectStore = \OC::$server->getSystemConfig()->getValue('objectstore', null);
218
+        if (isset($objectStore)) {
219
+            self::initObjectStoreRootFS($objectStore);
220
+        } else {
221
+            self::initLocalStorageRootFS();
222
+        }
223
+
224
+        if ($user != '' && !OCP\User::userExists($user)) {
225
+            \OC::$server->getEventLogger()->end('setup_fs');
226
+            return false;
227
+        }
228
+
229
+        //if we aren't logged in, there is no use to set up the filesystem
230
+        if ($user != "") {
231
+
232
+            $userDir = '/' . $user . '/files';
233
+
234
+            //jail the user into his "home" directory
235
+            \OC\Files\Filesystem::init($user, $userDir);
236
+
237
+            OC_Hook::emit('OC_Filesystem', 'setup', array('user' => $user, 'user_dir' => $userDir));
238
+        }
239
+        \OC::$server->getEventLogger()->end('setup_fs');
240
+        return true;
241
+    }
242
+
243
+    /**
244
+     * check if a password is required for each public link
245
+     *
246
+     * @return boolean
247
+     */
248
+    public static function isPublicLinkPasswordRequired() {
249
+        $appConfig = \OC::$server->getAppConfig();
250
+        $enforcePassword = $appConfig->getValue('core', 'shareapi_enforce_links_password', 'no');
251
+        return ($enforcePassword === 'yes') ? true : false;
252
+    }
253
+
254
+    /**
255
+     * check if sharing is disabled for the current user
256
+     * @param IConfig $config
257
+     * @param IGroupManager $groupManager
258
+     * @param IUser|null $user
259
+     * @return bool
260
+     */
261
+    public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) {
262
+        if ($config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
263
+            $groupsList = $config->getAppValue('core', 'shareapi_exclude_groups_list', '');
264
+            $excludedGroups = json_decode($groupsList);
265
+            if (is_null($excludedGroups)) {
266
+                $excludedGroups = explode(',', $groupsList);
267
+                $newValue = json_encode($excludedGroups);
268
+                $config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
269
+            }
270
+            $usersGroups = $groupManager->getUserGroupIds($user);
271
+            if (!empty($usersGroups)) {
272
+                $remainingGroups = array_diff($usersGroups, $excludedGroups);
273
+                // if the user is only in groups which are disabled for sharing then
274
+                // sharing is also disabled for the user
275
+                if (empty($remainingGroups)) {
276
+                    return true;
277
+                }
278
+            }
279
+        }
280
+        return false;
281
+    }
282
+
283
+    /**
284
+     * check if share API enforces a default expire date
285
+     *
286
+     * @return boolean
287
+     */
288
+    public static function isDefaultExpireDateEnforced() {
289
+        $isDefaultExpireDateEnabled = \OCP\Config::getAppValue('core', 'shareapi_default_expire_date', 'no');
290
+        $enforceDefaultExpireDate = false;
291
+        if ($isDefaultExpireDateEnabled === 'yes') {
292
+            $value = \OCP\Config::getAppValue('core', 'shareapi_enforce_expire_date', 'no');
293
+            $enforceDefaultExpireDate = ($value === 'yes') ? true : false;
294
+        }
295
+
296
+        return $enforceDefaultExpireDate;
297
+    }
298
+
299
+    /**
300
+     * Get the quota of a user
301
+     *
302
+     * @param string $userId
303
+     * @return int Quota bytes
304
+     */
305
+    public static function getUserQuota($userId) {
306
+        $user = \OC::$server->getUserManager()->get($userId);
307
+        if (is_null($user)) {
308
+            return \OCP\Files\FileInfo::SPACE_UNLIMITED;
309
+        }
310
+        $userQuota = $user->getQuota();
311
+        if($userQuota === 'none') {
312
+            return \OCP\Files\FileInfo::SPACE_UNLIMITED;
313
+        }
314
+        return OC_Helper::computerFileSize($userQuota);
315
+    }
316
+
317
+    /**
318
+     * copies the skeleton to the users /files
319
+     *
320
+     * @param String $userId
321
+     * @param \OCP\Files\Folder $userDirectory
322
+     * @throws \RuntimeException
323
+     */
324
+    public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
325
+
326
+        $skeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
327
+        $instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', '');
328
+
329
+        if ($instanceId === null) {
330
+            throw new \RuntimeException('no instance id!');
331
+        }
332
+        $appdata = 'appdata_' . $instanceId;
333
+        if ($userId === $appdata) {
334
+            throw new \RuntimeException('username is reserved name: ' . $appdata);
335
+        }
336
+
337
+        if (!empty($skeletonDirectory)) {
338
+            \OCP\Util::writeLog(
339
+                'files_skeleton',
340
+                'copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'),
341
+                \OCP\Util::DEBUG
342
+            );
343
+            self::copyr($skeletonDirectory, $userDirectory);
344
+            // update the file cache
345
+            $userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
346
+        }
347
+    }
348
+
349
+    /**
350
+     * copies a directory recursively by using streams
351
+     *
352
+     * @param string $source
353
+     * @param \OCP\Files\Folder $target
354
+     * @return void
355
+     */
356
+    public static function copyr($source, \OCP\Files\Folder $target) {
357
+        $logger = \OC::$server->getLogger();
358
+
359
+        // Verify if folder exists
360
+        $dir = opendir($source);
361
+        if($dir === false) {
362
+            $logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
363
+            return;
364
+        }
365
+
366
+        // Copy the files
367
+        while (false !== ($file = readdir($dir))) {
368
+            if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
369
+                if (is_dir($source . '/' . $file)) {
370
+                    $child = $target->newFolder($file);
371
+                    self::copyr($source . '/' . $file, $child);
372
+                } else {
373
+                    $child = $target->newFile($file);
374
+                    $sourceStream = fopen($source . '/' . $file, 'r');
375
+                    if($sourceStream === false) {
376
+                        $logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
377
+                        closedir($dir);
378
+                        return;
379
+                    }
380
+                    stream_copy_to_stream($sourceStream, $child->fopen('w'));
381
+                }
382
+            }
383
+        }
384
+        closedir($dir);
385
+    }
386
+
387
+    /**
388
+     * @return void
389
+     */
390
+    public static function tearDownFS() {
391
+        \OC\Files\Filesystem::tearDown();
392
+        \OC::$server->getRootFolder()->clearCache();
393
+        self::$fsSetup = false;
394
+        self::$rootMounted = false;
395
+    }
396
+
397
+    /**
398
+     * get the current installed version of ownCloud
399
+     *
400
+     * @return array
401
+     */
402
+    public static function getVersion() {
403
+        OC_Util::loadVersion();
404
+        return self::$versionCache['OC_Version'];
405
+    }
406
+
407
+    /**
408
+     * get the current installed version string of ownCloud
409
+     *
410
+     * @return string
411
+     */
412
+    public static function getVersionString() {
413
+        OC_Util::loadVersion();
414
+        return self::$versionCache['OC_VersionString'];
415
+    }
416
+
417
+    /**
418
+     * @deprecated the value is of no use anymore
419
+     * @return string
420
+     */
421
+    public static function getEditionString() {
422
+        return '';
423
+    }
424
+
425
+    /**
426
+     * @description get the update channel of the current installed of ownCloud.
427
+     * @return string
428
+     */
429
+    public static function getChannel() {
430
+        OC_Util::loadVersion();
431
+        return \OC::$server->getConfig()->getSystemValue('updater.release.channel', self::$versionCache['OC_Channel']);
432
+    }
433
+
434
+    /**
435
+     * @description get the build number of the current installed of ownCloud.
436
+     * @return string
437
+     */
438
+    public static function getBuild() {
439
+        OC_Util::loadVersion();
440
+        return self::$versionCache['OC_Build'];
441
+    }
442
+
443
+    /**
444
+     * @description load the version.php into the session as cache
445
+     */
446
+    private static function loadVersion() {
447
+        if (self::$versionCache !== null) {
448
+            return;
449
+        }
450
+
451
+        $timestamp = filemtime(OC::$SERVERROOT . '/version.php');
452
+        require OC::$SERVERROOT . '/version.php';
453
+        /** @var $timestamp int */
454
+        self::$versionCache['OC_Version_Timestamp'] = $timestamp;
455
+        /** @var $OC_Version string */
456
+        self::$versionCache['OC_Version'] = $OC_Version;
457
+        /** @var $OC_VersionString string */
458
+        self::$versionCache['OC_VersionString'] = $OC_VersionString;
459
+        /** @var $OC_Build string */
460
+        self::$versionCache['OC_Build'] = $OC_Build;
461
+
462
+        /** @var $OC_Channel string */
463
+        self::$versionCache['OC_Channel'] = $OC_Channel;
464
+    }
465
+
466
+    /**
467
+     * generates a path for JS/CSS files. If no application is provided it will create the path for core.
468
+     *
469
+     * @param string $application application to get the files from
470
+     * @param string $directory directory within this application (css, js, vendor, etc)
471
+     * @param string $file the file inside of the above folder
472
+     * @return string the path
473
+     */
474
+    private static function generatePath($application, $directory, $file) {
475
+        if (is_null($file)) {
476
+            $file = $application;
477
+            $application = "";
478
+        }
479
+        if (!empty($application)) {
480
+            return "$application/$directory/$file";
481
+        } else {
482
+            return "$directory/$file";
483
+        }
484
+    }
485
+
486
+    /**
487
+     * add a javascript file
488
+     *
489
+     * @param string $application application id
490
+     * @param string|null $file filename
491
+     * @param bool $prepend prepend the Script to the beginning of the list
492
+     * @return void
493
+     */
494
+    public static function addScript($application, $file = null, $prepend = false) {
495
+        $path = OC_Util::generatePath($application, 'js', $file);
496
+
497
+        // core js files need separate handling
498
+        if ($application !== 'core' && $file !== null) {
499
+            self::addTranslations ( $application );
500
+        }
501
+        self::addExternalResource($application, $prepend, $path, "script");
502
+    }
503
+
504
+    /**
505
+     * add a javascript file from the vendor sub folder
506
+     *
507
+     * @param string $application application id
508
+     * @param string|null $file filename
509
+     * @param bool $prepend prepend the Script to the beginning of the list
510
+     * @return void
511
+     */
512
+    public static function addVendorScript($application, $file = null, $prepend = false) {
513
+        $path = OC_Util::generatePath($application, 'vendor', $file);
514
+        self::addExternalResource($application, $prepend, $path, "script");
515
+    }
516
+
517
+    /**
518
+     * add a translation JS file
519
+     *
520
+     * @param string $application application id
521
+     * @param string $languageCode language code, defaults to the current language
522
+     * @param bool $prepend prepend the Script to the beginning of the list
523
+     */
524
+    public static function addTranslations($application, $languageCode = null, $prepend = false) {
525
+        if (is_null($languageCode)) {
526
+            $languageCode = \OC::$server->getL10NFactory()->findLanguage($application);
527
+        }
528
+        if (!empty($application)) {
529
+            $path = "$application/l10n/$languageCode";
530
+        } else {
531
+            $path = "l10n/$languageCode";
532
+        }
533
+        self::addExternalResource($application, $prepend, $path, "script");
534
+    }
535
+
536
+    /**
537
+     * add a css file
538
+     *
539
+     * @param string $application application id
540
+     * @param string|null $file filename
541
+     * @param bool $prepend prepend the Style to the beginning of the list
542
+     * @return void
543
+     */
544
+    public static function addStyle($application, $file = null, $prepend = false) {
545
+        $path = OC_Util::generatePath($application, 'css', $file);
546
+        self::addExternalResource($application, $prepend, $path, "style");
547
+    }
548
+
549
+    /**
550
+     * add a css file from the vendor sub folder
551
+     *
552
+     * @param string $application application id
553
+     * @param string|null $file filename
554
+     * @param bool $prepend prepend the Style to the beginning of the list
555
+     * @return void
556
+     */
557
+    public static function addVendorStyle($application, $file = null, $prepend = false) {
558
+        $path = OC_Util::generatePath($application, 'vendor', $file);
559
+        self::addExternalResource($application, $prepend, $path, "style");
560
+    }
561
+
562
+    /**
563
+     * add an external resource css/js file
564
+     *
565
+     * @param string $application application id
566
+     * @param bool $prepend prepend the file to the beginning of the list
567
+     * @param string $path
568
+     * @param string $type (script or style)
569
+     * @return void
570
+     */
571
+    private static function addExternalResource($application, $prepend, $path, $type = "script") {
572
+
573
+        if ($type === "style") {
574
+            if (!in_array($path, self::$styles)) {
575
+                if ($prepend === true) {
576
+                    array_unshift ( self::$styles, $path );
577
+                } else {
578
+                    self::$styles[] = $path;
579
+                }
580
+            }
581
+        } elseif ($type === "script") {
582
+            if (!in_array($path, self::$scripts)) {
583
+                if ($prepend === true) {
584
+                    array_unshift ( self::$scripts, $path );
585
+                } else {
586
+                    self::$scripts [] = $path;
587
+                }
588
+            }
589
+        }
590
+    }
591
+
592
+    /**
593
+     * Add a custom element to the header
594
+     * If $text is null then the element will be written as empty element.
595
+     * So use "" to get a closing tag.
596
+     * @param string $tag tag name of the element
597
+     * @param array $attributes array of attributes for the element
598
+     * @param string $text the text content for the element
599
+     */
600
+    public static function addHeader($tag, $attributes, $text=null) {
601
+        self::$headers[] = array(
602
+            'tag' => $tag,
603
+            'attributes' => $attributes,
604
+            'text' => $text
605
+        );
606
+    }
607
+
608
+    /**
609
+     * formats a timestamp in the "right" way
610
+     *
611
+     * @param int $timestamp
612
+     * @param bool $dateOnly option to omit time from the result
613
+     * @param DateTimeZone|string $timeZone where the given timestamp shall be converted to
614
+     * @return string timestamp
615
+     *
616
+     * @deprecated Use \OC::$server->query('DateTimeFormatter') instead
617
+     */
618
+    public static function formatDate($timestamp, $dateOnly = false, $timeZone = null) {
619
+        if ($timeZone !== null && !$timeZone instanceof \DateTimeZone) {
620
+            $timeZone = new \DateTimeZone($timeZone);
621
+        }
622
+
623
+        /** @var \OC\DateTimeFormatter $formatter */
624
+        $formatter = \OC::$server->query('DateTimeFormatter');
625
+        if ($dateOnly) {
626
+            return $formatter->formatDate($timestamp, 'long', $timeZone);
627
+        }
628
+        return $formatter->formatDateTime($timestamp, 'long', 'long', $timeZone);
629
+    }
630
+
631
+    /**
632
+     * check if the current server configuration is suitable for ownCloud
633
+     *
634
+     * @param \OC\SystemConfig $config
635
+     * @return array arrays with error messages and hints
636
+     */
637
+    public static function checkServer(\OC\SystemConfig $config) {
638
+        $l = \OC::$server->getL10N('lib');
639
+        $errors = array();
640
+        $CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
641
+
642
+        if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
643
+            // this check needs to be done every time
644
+            $errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
645
+        }
646
+
647
+        // Assume that if checkServer() succeeded before in this session, then all is fine.
648
+        if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
649
+            return $errors;
650
+        }
651
+
652
+        $webServerRestart = false;
653
+        $setup = new \OC\Setup($config, \OC::$server->getIniWrapper(), \OC::$server->getL10N('lib'),
654
+            \OC::$server->getDefaults(), \OC::$server->getLogger(), \OC::$server->getSecureRandom());
655
+
656
+        $urlGenerator = \OC::$server->getURLGenerator();
657
+
658
+        $availableDatabases = $setup->getSupportedDatabases();
659
+        if (empty($availableDatabases)) {
660
+            $errors[] = array(
661
+                'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
662
+                'hint' => '' //TODO: sane hint
663
+            );
664
+            $webServerRestart = true;
665
+        }
666
+
667
+        // Check if config folder is writable.
668
+        if(!OC_Helper::isReadOnlyConfigEnabled()) {
669
+            if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
670
+                $errors[] = array(
671
+                    'error' => $l->t('Cannot write into "config" directory'),
672
+                    'hint' => $l->t('This can usually be fixed by '
673
+                        . '%sgiving the webserver write access to the config directory%s.',
674
+                        array('<a href="' . $urlGenerator->linkToDocs('admin-dir_permissions') . '" target="_blank" rel="noreferrer">', '</a>'))
675
+                );
676
+            }
677
+        }
678
+
679
+        // Check if there is a writable install folder.
680
+        if ($config->getValue('appstoreenabled', true)) {
681
+            if (OC_App::getInstallPath() === null
682
+                || !is_writable(OC_App::getInstallPath())
683
+                || !is_readable(OC_App::getInstallPath())
684
+            ) {
685
+                $errors[] = array(
686
+                    'error' => $l->t('Cannot write into "apps" directory'),
687
+                    'hint' => $l->t('This can usually be fixed by '
688
+                        . '%sgiving the webserver write access to the apps directory%s'
689
+                        . ' or disabling the appstore in the config file.',
690
+                        array('<a href="' . $urlGenerator->linkToDocs('admin-dir_permissions') . '" target="_blank" rel="noreferrer">', '</a>'))
691
+                );
692
+            }
693
+        }
694
+        // Create root dir.
695
+        if ($config->getValue('installed', false)) {
696
+            if (!is_dir($CONFIG_DATADIRECTORY)) {
697
+                $success = @mkdir($CONFIG_DATADIRECTORY);
698
+                if ($success) {
699
+                    $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
700
+                } else {
701
+                    $errors[] = array(
702
+                        'error' => $l->t('Cannot create "data" directory (%s)', array($CONFIG_DATADIRECTORY)),
703
+                        'hint' => $l->t('This can usually be fixed by '
704
+                            . '<a href="%s" target="_blank" rel="noreferrer">giving the webserver write access to the root directory</a>.',
705
+                            array($urlGenerator->linkToDocs('admin-dir_permissions')))
706
+                    );
707
+                }
708
+            } else if (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
709
+                //common hint for all file permissions error messages
710
+                $permissionsHint = $l->t('Permissions can usually be fixed by '
711
+                    . '%sgiving the webserver write access to the root directory%s.',
712
+                    array('<a href="' . $urlGenerator->linkToDocs('admin-dir_permissions') . '" target="_blank" rel="noreferrer">', '</a>'));
713
+                $errors[] = array(
714
+                    'error' => 'Data directory (' . $CONFIG_DATADIRECTORY . ') not writable',
715
+                    'hint' => $permissionsHint
716
+                );
717
+            } else {
718
+                $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
719
+            }
720
+        }
721
+
722
+        if (!OC_Util::isSetLocaleWorking()) {
723
+            $errors[] = array(
724
+                'error' => $l->t('Setting locale to %s failed',
725
+                    array('en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
726
+                        . 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8')),
727
+                'hint' => $l->t('Please install one of these locales on your system and restart your webserver.')
728
+            );
729
+        }
730
+
731
+        // Contains the dependencies that should be checked against
732
+        // classes = class_exists
733
+        // functions = function_exists
734
+        // defined = defined
735
+        // ini = ini_get
736
+        // If the dependency is not found the missing module name is shown to the EndUser
737
+        // When adding new checks always verify that they pass on Travis as well
738
+        // for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini
739
+        $dependencies = array(
740
+            'classes' => array(
741
+                'ZipArchive' => 'zip',
742
+                'DOMDocument' => 'dom',
743
+                'XMLWriter' => 'XMLWriter',
744
+                'XMLReader' => 'XMLReader',
745
+            ),
746
+            'functions' => [
747
+                'xml_parser_create' => 'libxml',
748
+                'mb_strcut' => 'mb multibyte',
749
+                'ctype_digit' => 'ctype',
750
+                'json_encode' => 'JSON',
751
+                'gd_info' => 'GD',
752
+                'gzencode' => 'zlib',
753
+                'iconv' => 'iconv',
754
+                'simplexml_load_string' => 'SimpleXML',
755
+                'hash' => 'HASH Message Digest Framework',
756
+                'curl_init' => 'cURL',
757
+                'openssl_verify' => 'OpenSSL',
758
+            ],
759
+            'defined' => array(
760
+                'PDO::ATTR_DRIVER_NAME' => 'PDO'
761
+            ),
762
+            'ini' => [
763
+                'default_charset' => 'UTF-8',
764
+            ],
765
+        );
766
+        $missingDependencies = array();
767
+        $invalidIniSettings = [];
768
+        $moduleHint = $l->t('Please ask your server administrator to install the module.');
769
+
770
+        /**
771
+         * FIXME: The dependency check does not work properly on HHVM on the moment
772
+         *        and prevents installation. Once HHVM is more compatible with our
773
+         *        approach to check for these values we should re-enable those
774
+         *        checks.
775
+         */
776
+        $iniWrapper = \OC::$server->getIniWrapper();
777
+        if (!self::runningOnHhvm()) {
778
+            foreach ($dependencies['classes'] as $class => $module) {
779
+                if (!class_exists($class)) {
780
+                    $missingDependencies[] = $module;
781
+                }
782
+            }
783
+            foreach ($dependencies['functions'] as $function => $module) {
784
+                if (!function_exists($function)) {
785
+                    $missingDependencies[] = $module;
786
+                }
787
+            }
788
+            foreach ($dependencies['defined'] as $defined => $module) {
789
+                if (!defined($defined)) {
790
+                    $missingDependencies[] = $module;
791
+                }
792
+            }
793
+            foreach ($dependencies['ini'] as $setting => $expected) {
794
+                if (is_bool($expected)) {
795
+                    if ($iniWrapper->getBool($setting) !== $expected) {
796
+                        $invalidIniSettings[] = [$setting, $expected];
797
+                    }
798
+                }
799
+                if (is_int($expected)) {
800
+                    if ($iniWrapper->getNumeric($setting) !== $expected) {
801
+                        $invalidIniSettings[] = [$setting, $expected];
802
+                    }
803
+                }
804
+                if (is_string($expected)) {
805
+                    if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
806
+                        $invalidIniSettings[] = [$setting, $expected];
807
+                    }
808
+                }
809
+            }
810
+        }
811
+
812
+        foreach($missingDependencies as $missingDependency) {
813
+            $errors[] = array(
814
+                'error' => $l->t('PHP module %s not installed.', array($missingDependency)),
815
+                'hint' => $moduleHint
816
+            );
817
+            $webServerRestart = true;
818
+        }
819
+        foreach($invalidIniSettings as $setting) {
820
+            if(is_bool($setting[1])) {
821
+                $setting[1] = ($setting[1]) ? 'on' : 'off';
822
+            }
823
+            $errors[] = [
824
+                'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
825
+                'hint' =>  $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
826
+            ];
827
+            $webServerRestart = true;
828
+        }
829
+
830
+        /**
831
+         * The mbstring.func_overload check can only be performed if the mbstring
832
+         * module is installed as it will return null if the checking setting is
833
+         * not available and thus a check on the boolean value fails.
834
+         *
835
+         * TODO: Should probably be implemented in the above generic dependency
836
+         *       check somehow in the long-term.
837
+         */
838
+        if($iniWrapper->getBool('mbstring.func_overload') !== null &&
839
+            $iniWrapper->getBool('mbstring.func_overload') === true) {
840
+            $errors[] = array(
841
+                'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]),
842
+                'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini')
843
+            );
844
+        }
845
+
846
+        if(function_exists('xml_parser_create') &&
847
+            LIBXML_LOADED_VERSION < 20700 ) {
848
+            $version = LIBXML_LOADED_VERSION;
849
+            $major = floor($version/10000);
850
+            $version -= ($major * 10000);
851
+            $minor = floor($version/100);
852
+            $version -= ($minor * 100);
853
+            $patch = $version;
854
+            $errors[] = array(
855
+                'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
856
+                'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
857
+            );
858
+        }
859
+
860
+        if (!self::isAnnotationsWorking()) {
861
+            $errors[] = array(
862
+                'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
863
+                'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
864
+            );
865
+        }
866
+
867
+        if (!\OC::$CLI && $webServerRestart) {
868
+            $errors[] = array(
869
+                'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
870
+                'hint' => $l->t('Please ask your server administrator to restart the web server.')
871
+            );
872
+        }
873
+
874
+        $errors = array_merge($errors, self::checkDatabaseVersion());
875
+
876
+        // Cache the result of this function
877
+        \OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
878
+
879
+        return $errors;
880
+    }
881
+
882
+    /**
883
+     * Check the database version
884
+     *
885
+     * @return array errors array
886
+     */
887
+    public static function checkDatabaseVersion() {
888
+        $l = \OC::$server->getL10N('lib');
889
+        $errors = array();
890
+        $dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite');
891
+        if ($dbType === 'pgsql') {
892
+            // check PostgreSQL version
893
+            try {
894
+                $result = \OC_DB::executeAudited('SHOW SERVER_VERSION');
895
+                $data = $result->fetchRow();
896
+                if (isset($data['server_version'])) {
897
+                    $version = $data['server_version'];
898
+                    if (version_compare($version, '9.0.0', '<')) {
899
+                        $errors[] = array(
900
+                            'error' => $l->t('PostgreSQL >= 9 required'),
901
+                            'hint' => $l->t('Please upgrade your database version')
902
+                        );
903
+                    }
904
+                }
905
+            } catch (\Doctrine\DBAL\DBALException $e) {
906
+                $logger = \OC::$server->getLogger();
907
+                $logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9');
908
+                $logger->logException($e);
909
+            }
910
+        }
911
+        return $errors;
912
+    }
913
+
914
+    /**
915
+     * Check for correct file permissions of data directory
916
+     *
917
+     * @param string $dataDirectory
918
+     * @return array arrays with error messages and hints
919
+     */
920
+    public static function checkDataDirectoryPermissions($dataDirectory) {
921
+        $l = \OC::$server->getL10N('lib');
922
+        $errors = array();
923
+        $permissionsModHint = $l->t('Please change the permissions to 0770 so that the directory'
924
+            . ' cannot be listed by other users.');
925
+        $perms = substr(decoct(@fileperms($dataDirectory)), -3);
926
+        if (substr($perms, -1) != '0') {
927
+            chmod($dataDirectory, 0770);
928
+            clearstatcache();
929
+            $perms = substr(decoct(@fileperms($dataDirectory)), -3);
930
+            if (substr($perms, 2, 1) != '0') {
931
+                $errors[] = array(
932
+                    'error' => $l->t('Data directory (%s) is readable by other users', array($dataDirectory)),
933
+                    'hint' => $permissionsModHint
934
+                );
935
+            }
936
+        }
937
+        return $errors;
938
+    }
939
+
940
+    /**
941
+     * Check that the data directory exists and is valid by
942
+     * checking the existence of the ".ocdata" file.
943
+     *
944
+     * @param string $dataDirectory data directory path
945
+     * @return array errors found
946
+     */
947
+    public static function checkDataDirectoryValidity($dataDirectory) {
948
+        $l = \OC::$server->getL10N('lib');
949
+        $errors = [];
950
+        if ($dataDirectory[0] !== '/') {
951
+            $errors[] = [
952
+                'error' => $l->t('Data directory (%s) must be an absolute path', [$dataDirectory]),
953
+                'hint' => $l->t('Check the value of "datadirectory" in your configuration')
954
+            ];
955
+        }
956
+        if (!file_exists($dataDirectory . '/.ocdata')) {
957
+            $errors[] = [
958
+                'error' => $l->t('Data directory (%s) is invalid', [$dataDirectory]),
959
+                'hint' => $l->t('Please check that the data directory contains a file' .
960
+                    ' ".ocdata" in its root.')
961
+            ];
962
+        }
963
+        return $errors;
964
+    }
965
+
966
+    /**
967
+     * Check if the user is logged in, redirects to home if not. With
968
+     * redirect URL parameter to the request URI.
969
+     *
970
+     * @return void
971
+     */
972
+    public static function checkLoggedIn() {
973
+        // Check if we are a user
974
+        if (!\OC::$server->getUserSession()->isLoggedIn()) {
975
+            header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
976
+                        'core.login.showLoginForm',
977
+                        [
978
+                            'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
979
+                        ]
980
+                    )
981
+            );
982
+            exit();
983
+        }
984
+        // Redirect to 2FA challenge selection if 2FA challenge was not solved yet
985
+        if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
986
+            header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
987
+            exit();
988
+        }
989
+    }
990
+
991
+    /**
992
+     * Check if the user is a admin, redirects to home if not
993
+     *
994
+     * @return void
995
+     */
996
+    public static function checkAdminUser() {
997
+        OC_Util::checkLoggedIn();
998
+        if (!OC_User::isAdminUser(OC_User::getUser())) {
999
+            header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1000
+            exit();
1001
+        }
1002
+    }
1003
+
1004
+    /**
1005
+     * Check if the user is a subadmin, redirects to home if not
1006
+     *
1007
+     * @return null|boolean $groups where the current user is subadmin
1008
+     */
1009
+    public static function checkSubAdminUser() {
1010
+        OC_Util::checkLoggedIn();
1011
+        $userObject = \OC::$server->getUserSession()->getUser();
1012
+        $isSubAdmin = false;
1013
+        if($userObject !== null) {
1014
+            $isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
1015
+        }
1016
+
1017
+        if (!$isSubAdmin) {
1018
+            header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1019
+            exit();
1020
+        }
1021
+        return true;
1022
+    }
1023
+
1024
+    /**
1025
+     * Returns the URL of the default page
1026
+     * based on the system configuration and
1027
+     * the apps visible for the current user
1028
+     *
1029
+     * @return string URL
1030
+     */
1031
+    public static function getDefaultPageUrl() {
1032
+        $urlGenerator = \OC::$server->getURLGenerator();
1033
+        // Deny the redirect if the URL contains a @
1034
+        // This prevents unvalidated redirects like ?redirect_url=:[email protected]
1035
+        if (isset($_REQUEST['redirect_url']) && strpos($_REQUEST['redirect_url'], '@') === false) {
1036
+            $location = $urlGenerator->getAbsoluteURL(urldecode($_REQUEST['redirect_url']));
1037
+        } else {
1038
+            $defaultPage = \OC::$server->getAppConfig()->getValue('core', 'defaultpage');
1039
+            if ($defaultPage) {
1040
+                $location = $urlGenerator->getAbsoluteURL($defaultPage);
1041
+            } else {
1042
+                $appId = 'files';
1043
+                $defaultApps = explode(',', \OCP\Config::getSystemValue('defaultapp', 'files'));
1044
+                // find the first app that is enabled for the current user
1045
+                foreach ($defaultApps as $defaultApp) {
1046
+                    $defaultApp = OC_App::cleanAppId(strip_tags($defaultApp));
1047
+                    if (static::getAppManager()->isEnabledForUser($defaultApp)) {
1048
+                        $appId = $defaultApp;
1049
+                        break;
1050
+                    }
1051
+                }
1052
+
1053
+                if(\OC::$server->getConfig()->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') {
1054
+                    $location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/');
1055
+                } else {
1056
+                    $location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/');
1057
+                }
1058
+            }
1059
+        }
1060
+        return $location;
1061
+    }
1062
+
1063
+    /**
1064
+     * Redirect to the user default page
1065
+     *
1066
+     * @return void
1067
+     */
1068
+    public static function redirectToDefaultPage() {
1069
+        $location = self::getDefaultPageUrl();
1070
+        header('Location: ' . $location);
1071
+        exit();
1072
+    }
1073
+
1074
+    /**
1075
+     * get an id unique for this instance
1076
+     *
1077
+     * @return string
1078
+     */
1079
+    public static function getInstanceId() {
1080
+        $id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
1081
+        if (is_null($id)) {
1082
+            // We need to guarantee at least one letter in instanceid so it can be used as the session_name
1083
+            $id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1084
+            \OC::$server->getSystemConfig()->setValue('instanceid', $id);
1085
+        }
1086
+        return $id;
1087
+    }
1088
+
1089
+    /**
1090
+     * Public function to sanitize HTML
1091
+     *
1092
+     * This function is used to sanitize HTML and should be applied on any
1093
+     * string or array of strings before displaying it on a web page.
1094
+     *
1095
+     * @param string|array $value
1096
+     * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
1097
+     */
1098
+    public static function sanitizeHTML($value) {
1099
+        if (is_array($value)) {
1100
+            $value = array_map(function($value) {
1101
+                return self::sanitizeHTML($value);
1102
+            }, $value);
1103
+        } else {
1104
+            // Specify encoding for PHP<5.4
1105
+            $value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
1106
+        }
1107
+        return $value;
1108
+    }
1109
+
1110
+    /**
1111
+     * Public function to encode url parameters
1112
+     *
1113
+     * This function is used to encode path to file before output.
1114
+     * Encoding is done according to RFC 3986 with one exception:
1115
+     * Character '/' is preserved as is.
1116
+     *
1117
+     * @param string $component part of URI to encode
1118
+     * @return string
1119
+     */
1120
+    public static function encodePath($component) {
1121
+        $encoded = rawurlencode($component);
1122
+        $encoded = str_replace('%2F', '/', $encoded);
1123
+        return $encoded;
1124
+    }
1125
+
1126
+
1127
+    public function createHtaccessTestFile(\OCP\IConfig $config) {
1128
+        // php dev server does not support htaccess
1129
+        if (php_sapi_name() === 'cli-server') {
1130
+            return false;
1131
+        }
1132
+
1133
+        // testdata
1134
+        $fileName = '/htaccesstest.txt';
1135
+        $testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
1136
+
1137
+        // creating a test file
1138
+        $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1139
+
1140
+        if (file_exists($testFile)) {// already running this test, possible recursive call
1141
+            return false;
1142
+        }
1143
+
1144
+        $fp = @fopen($testFile, 'w');
1145
+        if (!$fp) {
1146
+            throw new OC\HintException('Can\'t create test file to check for working .htaccess file.',
1147
+                'Make sure it is possible for the webserver to write to ' . $testFile);
1148
+        }
1149
+        fwrite($fp, $testContent);
1150
+        fclose($fp);
1151
+
1152
+        return $testContent;
1153
+    }
1154
+
1155
+    /**
1156
+     * Check if the .htaccess file is working
1157
+     * @param \OCP\IConfig $config
1158
+     * @return bool
1159
+     * @throws Exception
1160
+     * @throws \OC\HintException If the test file can't get written.
1161
+     */
1162
+    public function isHtaccessWorking(\OCP\IConfig $config) {
1163
+
1164
+        if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) {
1165
+            return true;
1166
+        }
1167
+
1168
+        $testContent = $this->createHtaccessTestFile($config);
1169
+        if ($testContent === false) {
1170
+            return false;
1171
+        }
1172
+
1173
+        $fileName = '/htaccesstest.txt';
1174
+        $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1175
+
1176
+        // accessing the file via http
1177
+        $url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
1178
+        try {
1179
+            $content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1180
+        } catch (\Exception $e) {
1181
+            $content = false;
1182
+        }
1183
+
1184
+        // cleanup
1185
+        @unlink($testFile);
1186
+
1187
+        /*
1188 1188
 		 * If the content is not equal to test content our .htaccess
1189 1189
 		 * is working as required
1190 1190
 		 */
1191
-		return $content !== $testContent;
1192
-	}
1193
-
1194
-	/**
1195
-	 * Check if the setlocal call does not work. This can happen if the right
1196
-	 * local packages are not available on the server.
1197
-	 *
1198
-	 * @return bool
1199
-	 */
1200
-	public static function isSetLocaleWorking() {
1201
-		\Patchwork\Utf8\Bootup::initLocale();
1202
-		if ('' === basename('§')) {
1203
-			return false;
1204
-		}
1205
-		return true;
1206
-	}
1207
-
1208
-	/**
1209
-	 * Check if it's possible to get the inline annotations
1210
-	 *
1211
-	 * @return bool
1212
-	 */
1213
-	public static function isAnnotationsWorking() {
1214
-		$reflection = new \ReflectionMethod(__METHOD__);
1215
-		$docs = $reflection->getDocComment();
1216
-
1217
-		return (is_string($docs) && strlen($docs) > 50);
1218
-	}
1219
-
1220
-	/**
1221
-	 * Check if the PHP module fileinfo is loaded.
1222
-	 *
1223
-	 * @return bool
1224
-	 */
1225
-	public static function fileInfoLoaded() {
1226
-		return function_exists('finfo_open');
1227
-	}
1228
-
1229
-	/**
1230
-	 * clear all levels of output buffering
1231
-	 *
1232
-	 * @return void
1233
-	 */
1234
-	public static function obEnd() {
1235
-		while (ob_get_level()) {
1236
-			ob_end_clean();
1237
-		}
1238
-	}
1239
-
1240
-	/**
1241
-	 * Checks whether the server is running on Mac OS X
1242
-	 *
1243
-	 * @return bool true if running on Mac OS X, false otherwise
1244
-	 */
1245
-	public static function runningOnMac() {
1246
-		return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
1247
-	}
1248
-
1249
-	/**
1250
-	 * Checks whether server is running on HHVM
1251
-	 *
1252
-	 * @return bool True if running on HHVM, false otherwise
1253
-	 */
1254
-	public static function runningOnHhvm() {
1255
-		return defined('HHVM_VERSION');
1256
-	}
1257
-
1258
-	/**
1259
-	 * Handles the case that there may not be a theme, then check if a "default"
1260
-	 * theme exists and take that one
1261
-	 *
1262
-	 * @return string the theme
1263
-	 */
1264
-	public static function getTheme() {
1265
-		$theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1266
-
1267
-		if ($theme === '') {
1268
-			if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1269
-				$theme = 'default';
1270
-			}
1271
-		}
1272
-
1273
-		return $theme;
1274
-	}
1275
-
1276
-	/**
1277
-	 * Clear a single file from the opcode cache
1278
-	 * This is useful for writing to the config file
1279
-	 * in case the opcode cache does not re-validate files
1280
-	 * Returns true if successful, false if unsuccessful:
1281
-	 * caller should fall back on clearing the entire cache
1282
-	 * with clearOpcodeCache() if unsuccessful
1283
-	 *
1284
-	 * @param string $path the path of the file to clear from the cache
1285
-	 * @return bool true if underlying function returns true, otherwise false
1286
-	 */
1287
-	public static function deleteFromOpcodeCache($path) {
1288
-		$ret = false;
1289
-		if ($path) {
1290
-			// APC >= 3.1.1
1291
-			if (function_exists('apc_delete_file')) {
1292
-				$ret = @apc_delete_file($path);
1293
-			}
1294
-			// Zend OpCache >= 7.0.0, PHP >= 5.5.0
1295
-			if (function_exists('opcache_invalidate')) {
1296
-				$ret = opcache_invalidate($path);
1297
-			}
1298
-		}
1299
-		return $ret;
1300
-	}
1301
-
1302
-	/**
1303
-	 * Clear the opcode cache if one exists
1304
-	 * This is necessary for writing to the config file
1305
-	 * in case the opcode cache does not re-validate files
1306
-	 *
1307
-	 * @return void
1308
-	 */
1309
-	public static function clearOpcodeCache() {
1310
-		// APC
1311
-		if (function_exists('apc_clear_cache')) {
1312
-			apc_clear_cache();
1313
-		}
1314
-		// Zend Opcache
1315
-		if (function_exists('accelerator_reset')) {
1316
-			accelerator_reset();
1317
-		}
1318
-		// XCache
1319
-		if (function_exists('xcache_clear_cache')) {
1320
-			if (\OC::$server->getIniWrapper()->getBool('xcache.admin.enable_auth')) {
1321
-				\OCP\Util::writeLog('core', 'XCache opcode cache will not be cleared because "xcache.admin.enable_auth" is enabled.', \OCP\Util::WARN);
1322
-			} else {
1323
-				@xcache_clear_cache(XC_TYPE_PHP, 0);
1324
-			}
1325
-		}
1326
-		// Opcache (PHP >= 5.5)
1327
-		if (function_exists('opcache_reset')) {
1328
-			opcache_reset();
1329
-		}
1330
-	}
1331
-
1332
-	/**
1333
-	 * Normalize a unicode string
1334
-	 *
1335
-	 * @param string $value a not normalized string
1336
-	 * @return bool|string
1337
-	 */
1338
-	public static function normalizeUnicode($value) {
1339
-		if(Normalizer::isNormalized($value)) {
1340
-			return $value;
1341
-		}
1342
-
1343
-		$normalizedValue = Normalizer::normalize($value);
1344
-		if ($normalizedValue === null || $normalizedValue === false) {
1345
-			\OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1346
-			return $value;
1347
-		}
1348
-
1349
-		return $normalizedValue;
1350
-	}
1351
-
1352
-	/**
1353
-	 * @param boolean|string $file
1354
-	 * @return string
1355
-	 */
1356
-	public static function basename($file) {
1357
-		$file = rtrim($file, '/');
1358
-		$t = explode('/', $file);
1359
-		return array_pop($t);
1360
-	}
1361
-
1362
-	/**
1363
-	 * A human readable string is generated based on version and build number
1364
-	 *
1365
-	 * @return string
1366
-	 */
1367
-	public static function getHumanVersion() {
1368
-		$version = OC_Util::getVersionString();
1369
-		$build = OC_Util::getBuild();
1370
-		if (!empty($build) and OC_Util::getChannel() === 'daily') {
1371
-			$version .= ' Build:' . $build;
1372
-		}
1373
-		return $version;
1374
-	}
1375
-
1376
-	/**
1377
-	 * Returns whether the given file name is valid
1378
-	 *
1379
-	 * @param string $file file name to check
1380
-	 * @return bool true if the file name is valid, false otherwise
1381
-	 * @deprecated use \OC\Files\View::verifyPath()
1382
-	 */
1383
-	public static function isValidFileName($file) {
1384
-		$trimmed = trim($file);
1385
-		if ($trimmed === '') {
1386
-			return false;
1387
-		}
1388
-		if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
1389
-			return false;
1390
-		}
1391
-		foreach (str_split($trimmed) as $char) {
1392
-			if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) {
1393
-				return false;
1394
-			}
1395
-		}
1396
-		return true;
1397
-	}
1398
-
1399
-	/**
1400
-	 * Check whether the instance needs to perform an upgrade,
1401
-	 * either when the core version is higher or any app requires
1402
-	 * an upgrade.
1403
-	 *
1404
-	 * @param \OC\SystemConfig $config
1405
-	 * @return bool whether the core or any app needs an upgrade
1406
-	 * @throws \OC\HintException When the upgrade from the given version is not allowed
1407
-	 */
1408
-	public static function needUpgrade(\OC\SystemConfig $config) {
1409
-		if ($config->getValue('installed', false)) {
1410
-			$installedVersion = $config->getValue('version', '0.0.0');
1411
-			$currentVersion = implode('.', \OCP\Util::getVersion());
1412
-			$versionDiff = version_compare($currentVersion, $installedVersion);
1413
-			if ($versionDiff > 0) {
1414
-				return true;
1415
-			} else if ($config->getValue('debug', false) && $versionDiff < 0) {
1416
-				// downgrade with debug
1417
-				$installedMajor = explode('.', $installedVersion);
1418
-				$installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1419
-				$currentMajor = explode('.', $currentVersion);
1420
-				$currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1421
-				if ($installedMajor === $currentMajor) {
1422
-					// Same major, allow downgrade for developers
1423
-					return true;
1424
-				} else {
1425
-					// downgrade attempt, throw exception
1426
-					throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1427
-				}
1428
-			} else if ($versionDiff < 0) {
1429
-				// downgrade attempt, throw exception
1430
-				throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1431
-			}
1432
-
1433
-			// also check for upgrades for apps (independently from the user)
1434
-			$apps = \OC_App::getEnabledApps(false, true);
1435
-			$shouldUpgrade = false;
1436
-			foreach ($apps as $app) {
1437
-				if (\OC_App::shouldUpgrade($app)) {
1438
-					$shouldUpgrade = true;
1439
-					break;
1440
-				}
1441
-			}
1442
-			return $shouldUpgrade;
1443
-		} else {
1444
-			return false;
1445
-		}
1446
-	}
1191
+        return $content !== $testContent;
1192
+    }
1193
+
1194
+    /**
1195
+     * Check if the setlocal call does not work. This can happen if the right
1196
+     * local packages are not available on the server.
1197
+     *
1198
+     * @return bool
1199
+     */
1200
+    public static function isSetLocaleWorking() {
1201
+        \Patchwork\Utf8\Bootup::initLocale();
1202
+        if ('' === basename('§')) {
1203
+            return false;
1204
+        }
1205
+        return true;
1206
+    }
1207
+
1208
+    /**
1209
+     * Check if it's possible to get the inline annotations
1210
+     *
1211
+     * @return bool
1212
+     */
1213
+    public static function isAnnotationsWorking() {
1214
+        $reflection = new \ReflectionMethod(__METHOD__);
1215
+        $docs = $reflection->getDocComment();
1216
+
1217
+        return (is_string($docs) && strlen($docs) > 50);
1218
+    }
1219
+
1220
+    /**
1221
+     * Check if the PHP module fileinfo is loaded.
1222
+     *
1223
+     * @return bool
1224
+     */
1225
+    public static function fileInfoLoaded() {
1226
+        return function_exists('finfo_open');
1227
+    }
1228
+
1229
+    /**
1230
+     * clear all levels of output buffering
1231
+     *
1232
+     * @return void
1233
+     */
1234
+    public static function obEnd() {
1235
+        while (ob_get_level()) {
1236
+            ob_end_clean();
1237
+        }
1238
+    }
1239
+
1240
+    /**
1241
+     * Checks whether the server is running on Mac OS X
1242
+     *
1243
+     * @return bool true if running on Mac OS X, false otherwise
1244
+     */
1245
+    public static function runningOnMac() {
1246
+        return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
1247
+    }
1248
+
1249
+    /**
1250
+     * Checks whether server is running on HHVM
1251
+     *
1252
+     * @return bool True if running on HHVM, false otherwise
1253
+     */
1254
+    public static function runningOnHhvm() {
1255
+        return defined('HHVM_VERSION');
1256
+    }
1257
+
1258
+    /**
1259
+     * Handles the case that there may not be a theme, then check if a "default"
1260
+     * theme exists and take that one
1261
+     *
1262
+     * @return string the theme
1263
+     */
1264
+    public static function getTheme() {
1265
+        $theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1266
+
1267
+        if ($theme === '') {
1268
+            if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1269
+                $theme = 'default';
1270
+            }
1271
+        }
1272
+
1273
+        return $theme;
1274
+    }
1275
+
1276
+    /**
1277
+     * Clear a single file from the opcode cache
1278
+     * This is useful for writing to the config file
1279
+     * in case the opcode cache does not re-validate files
1280
+     * Returns true if successful, false if unsuccessful:
1281
+     * caller should fall back on clearing the entire cache
1282
+     * with clearOpcodeCache() if unsuccessful
1283
+     *
1284
+     * @param string $path the path of the file to clear from the cache
1285
+     * @return bool true if underlying function returns true, otherwise false
1286
+     */
1287
+    public static function deleteFromOpcodeCache($path) {
1288
+        $ret = false;
1289
+        if ($path) {
1290
+            // APC >= 3.1.1
1291
+            if (function_exists('apc_delete_file')) {
1292
+                $ret = @apc_delete_file($path);
1293
+            }
1294
+            // Zend OpCache >= 7.0.0, PHP >= 5.5.0
1295
+            if (function_exists('opcache_invalidate')) {
1296
+                $ret = opcache_invalidate($path);
1297
+            }
1298
+        }
1299
+        return $ret;
1300
+    }
1301
+
1302
+    /**
1303
+     * Clear the opcode cache if one exists
1304
+     * This is necessary for writing to the config file
1305
+     * in case the opcode cache does not re-validate files
1306
+     *
1307
+     * @return void
1308
+     */
1309
+    public static function clearOpcodeCache() {
1310
+        // APC
1311
+        if (function_exists('apc_clear_cache')) {
1312
+            apc_clear_cache();
1313
+        }
1314
+        // Zend Opcache
1315
+        if (function_exists('accelerator_reset')) {
1316
+            accelerator_reset();
1317
+        }
1318
+        // XCache
1319
+        if (function_exists('xcache_clear_cache')) {
1320
+            if (\OC::$server->getIniWrapper()->getBool('xcache.admin.enable_auth')) {
1321
+                \OCP\Util::writeLog('core', 'XCache opcode cache will not be cleared because "xcache.admin.enable_auth" is enabled.', \OCP\Util::WARN);
1322
+            } else {
1323
+                @xcache_clear_cache(XC_TYPE_PHP, 0);
1324
+            }
1325
+        }
1326
+        // Opcache (PHP >= 5.5)
1327
+        if (function_exists('opcache_reset')) {
1328
+            opcache_reset();
1329
+        }
1330
+    }
1331
+
1332
+    /**
1333
+     * Normalize a unicode string
1334
+     *
1335
+     * @param string $value a not normalized string
1336
+     * @return bool|string
1337
+     */
1338
+    public static function normalizeUnicode($value) {
1339
+        if(Normalizer::isNormalized($value)) {
1340
+            return $value;
1341
+        }
1342
+
1343
+        $normalizedValue = Normalizer::normalize($value);
1344
+        if ($normalizedValue === null || $normalizedValue === false) {
1345
+            \OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1346
+            return $value;
1347
+        }
1348
+
1349
+        return $normalizedValue;
1350
+    }
1351
+
1352
+    /**
1353
+     * @param boolean|string $file
1354
+     * @return string
1355
+     */
1356
+    public static function basename($file) {
1357
+        $file = rtrim($file, '/');
1358
+        $t = explode('/', $file);
1359
+        return array_pop($t);
1360
+    }
1361
+
1362
+    /**
1363
+     * A human readable string is generated based on version and build number
1364
+     *
1365
+     * @return string
1366
+     */
1367
+    public static function getHumanVersion() {
1368
+        $version = OC_Util::getVersionString();
1369
+        $build = OC_Util::getBuild();
1370
+        if (!empty($build) and OC_Util::getChannel() === 'daily') {
1371
+            $version .= ' Build:' . $build;
1372
+        }
1373
+        return $version;
1374
+    }
1375
+
1376
+    /**
1377
+     * Returns whether the given file name is valid
1378
+     *
1379
+     * @param string $file file name to check
1380
+     * @return bool true if the file name is valid, false otherwise
1381
+     * @deprecated use \OC\Files\View::verifyPath()
1382
+     */
1383
+    public static function isValidFileName($file) {
1384
+        $trimmed = trim($file);
1385
+        if ($trimmed === '') {
1386
+            return false;
1387
+        }
1388
+        if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
1389
+            return false;
1390
+        }
1391
+        foreach (str_split($trimmed) as $char) {
1392
+            if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) {
1393
+                return false;
1394
+            }
1395
+        }
1396
+        return true;
1397
+    }
1398
+
1399
+    /**
1400
+     * Check whether the instance needs to perform an upgrade,
1401
+     * either when the core version is higher or any app requires
1402
+     * an upgrade.
1403
+     *
1404
+     * @param \OC\SystemConfig $config
1405
+     * @return bool whether the core or any app needs an upgrade
1406
+     * @throws \OC\HintException When the upgrade from the given version is not allowed
1407
+     */
1408
+    public static function needUpgrade(\OC\SystemConfig $config) {
1409
+        if ($config->getValue('installed', false)) {
1410
+            $installedVersion = $config->getValue('version', '0.0.0');
1411
+            $currentVersion = implode('.', \OCP\Util::getVersion());
1412
+            $versionDiff = version_compare($currentVersion, $installedVersion);
1413
+            if ($versionDiff > 0) {
1414
+                return true;
1415
+            } else if ($config->getValue('debug', false) && $versionDiff < 0) {
1416
+                // downgrade with debug
1417
+                $installedMajor = explode('.', $installedVersion);
1418
+                $installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1419
+                $currentMajor = explode('.', $currentVersion);
1420
+                $currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1421
+                if ($installedMajor === $currentMajor) {
1422
+                    // Same major, allow downgrade for developers
1423
+                    return true;
1424
+                } else {
1425
+                    // downgrade attempt, throw exception
1426
+                    throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1427
+                }
1428
+            } else if ($versionDiff < 0) {
1429
+                // downgrade attempt, throw exception
1430
+                throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1431
+            }
1432
+
1433
+            // also check for upgrades for apps (independently from the user)
1434
+            $apps = \OC_App::getEnabledApps(false, true);
1435
+            $shouldUpgrade = false;
1436
+            foreach ($apps as $app) {
1437
+                if (\OC_App::shouldUpgrade($app)) {
1438
+                    $shouldUpgrade = true;
1439
+                    break;
1440
+                }
1441
+            }
1442
+            return $shouldUpgrade;
1443
+        } else {
1444
+            return false;
1445
+        }
1446
+    }
1447 1447
 
1448 1448
 }
Please login to merge, or discard this patch.