Passed
Push — master ( 15b0e4...d4d33e )
by Roeland
14:38 queued 01:38
created
lib/base.php 2 patches
Indentation   +994 added lines, -994 removed lines patch added patch discarded remove patch
@@ -77,1000 +77,1000 @@
 block discarded – undo
77 77
  * OC_autoload!
78 78
  */
79 79
 class OC {
80
-	/**
81
-	 * Associative array for autoloading. classname => filename
82
-	 */
83
-	public static $CLASSPATH = [];
84
-	/**
85
-	 * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
86
-	 */
87
-	public static $SERVERROOT = '';
88
-	/**
89
-	 * the current request path relative to the Nextcloud root (e.g. files/index.php)
90
-	 */
91
-	private static $SUBURI = '';
92
-	/**
93
-	 * the Nextcloud root path for http requests (e.g. nextcloud/)
94
-	 */
95
-	public static $WEBROOT = '';
96
-	/**
97
-	 * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
98
-	 * web path in 'url'
99
-	 */
100
-	public static $APPSROOTS = [];
101
-
102
-	/**
103
-	 * @var string
104
-	 */
105
-	public static $configDir;
106
-
107
-	/**
108
-	 * requested app
109
-	 */
110
-	public static $REQUESTEDAPP = '';
111
-
112
-	/**
113
-	 * check if Nextcloud runs in cli mode
114
-	 */
115
-	public static $CLI = false;
116
-
117
-	/**
118
-	 * @var \OC\Autoloader $loader
119
-	 */
120
-	public static $loader = null;
121
-
122
-	/** @var \Composer\Autoload\ClassLoader $composerAutoloader */
123
-	public static $composerAutoloader = null;
124
-
125
-	/**
126
-	 * @var \OC\Server
127
-	 */
128
-	public static $server = null;
129
-
130
-	/**
131
-	 * @var \OC\Config
132
-	 */
133
-	private static $config = null;
134
-
135
-	/**
136
-	 * @throws \RuntimeException when the 3rdparty directory is missing or
137
-	 * the app path list is empty or contains an invalid path
138
-	 */
139
-	public static function initPaths() {
140
-		if (defined('PHPUNIT_CONFIG_DIR')) {
141
-			self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
142
-		} elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
143
-			self::$configDir = OC::$SERVERROOT . '/tests/config/';
144
-		} elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
145
-			self::$configDir = rtrim($dir, '/') . '/';
146
-		} else {
147
-			self::$configDir = OC::$SERVERROOT . '/config/';
148
-		}
149
-		self::$config = new \OC\Config(self::$configDir);
150
-
151
-		OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
152
-		/**
153
-		 * FIXME: The following lines are required because we can't yet instantiate
154
-		 *        \OC::$server->getRequest() since \OC::$server does not yet exist.
155
-		 */
156
-		$params = [
157
-			'server' => [
158
-				'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
159
-				'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
160
-			],
161
-		];
162
-		$fakeRequest = new \OC\AppFramework\Http\Request($params, new \OC\Security\SecureRandom(), new \OC\AllConfig(new \OC\SystemConfig(self::$config)));
163
-		$scriptName = $fakeRequest->getScriptName();
164
-		if (substr($scriptName, -1) == '/') {
165
-			$scriptName .= 'index.php';
166
-			//make sure suburi follows the same rules as scriptName
167
-			if (substr(OC::$SUBURI, -9) != 'index.php') {
168
-				if (substr(OC::$SUBURI, -1) != '/') {
169
-					OC::$SUBURI = OC::$SUBURI . '/';
170
-				}
171
-				OC::$SUBURI = OC::$SUBURI . 'index.php';
172
-			}
173
-		}
174
-
175
-
176
-		if (OC::$CLI) {
177
-			OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
178
-		} else {
179
-			if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
180
-				OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
181
-
182
-				if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
183
-					OC::$WEBROOT = '/' . OC::$WEBROOT;
184
-				}
185
-			} else {
186
-				// The scriptName is not ending with OC::$SUBURI
187
-				// This most likely means that we are calling from CLI.
188
-				// However some cron jobs still need to generate
189
-				// a web URL, so we use overwritewebroot as a fallback.
190
-				OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
191
-			}
192
-
193
-			// Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
194
-			// slash which is required by URL generation.
195
-			if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
196
-					substr($_SERVER['REQUEST_URI'], -1) !== '/') {
197
-				header('Location: '.\OC::$WEBROOT.'/');
198
-				exit();
199
-			}
200
-		}
201
-
202
-		// search the apps folder
203
-		$config_paths = self::$config->getValue('apps_paths', []);
204
-		if (!empty($config_paths)) {
205
-			foreach ($config_paths as $paths) {
206
-				if (isset($paths['url']) && isset($paths['path'])) {
207
-					$paths['url'] = rtrim($paths['url'], '/');
208
-					$paths['path'] = rtrim($paths['path'], '/');
209
-					OC::$APPSROOTS[] = $paths;
210
-				}
211
-			}
212
-		} elseif (file_exists(OC::$SERVERROOT . '/apps')) {
213
-			OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true];
214
-		}
215
-
216
-		if (empty(OC::$APPSROOTS)) {
217
-			throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
218
-				. '. You can also configure the location in the config.php file.');
219
-		}
220
-		$paths = [];
221
-		foreach (OC::$APPSROOTS as $path) {
222
-			$paths[] = $path['path'];
223
-			if (!is_dir($path['path'])) {
224
-				throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
225
-					. ' Nextcloud folder. You can also configure the location in the config.php file.', $path['path']));
226
-			}
227
-		}
228
-
229
-		// set the right include path
230
-		set_include_path(
231
-			implode(PATH_SEPARATOR, $paths)
232
-		);
233
-	}
234
-
235
-	public static function checkConfig() {
236
-		$l = \OC::$server->getL10N('lib');
237
-
238
-		// Create config if it does not already exist
239
-		$configFilePath = self::$configDir .'/config.php';
240
-		if (!file_exists($configFilePath)) {
241
-			@touch($configFilePath);
242
-		}
243
-
244
-		// Check if config is writable
245
-		$configFileWritable = is_writable($configFilePath);
246
-		if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
247
-			|| !$configFileWritable && \OCP\Util::needUpgrade()) {
248
-			$urlGenerator = \OC::$server->getURLGenerator();
249
-
250
-			if (self::$CLI) {
251
-				echo $l->t('Cannot write into "config" directory!')."\n";
252
-				echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
253
-				echo "\n";
254
-				echo $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.')."\n";
255
-				echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ])."\n";
256
-				exit;
257
-			} else {
258
-				OC_Template::printErrorPage(
259
-					$l->t('Cannot write into "config" directory!'),
260
-					$l->t('This can usually be fixed by giving the webserver write access to the config directory.') . '. '
261
-					. $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
262
-					[ $urlGenerator->linkToDocs('admin-config') ]),
263
-					503
264
-				);
265
-			}
266
-		}
267
-	}
268
-
269
-	public static function checkInstalled(\OC\SystemConfig $systemConfig) {
270
-		if (defined('OC_CONSOLE')) {
271
-			return;
272
-		}
273
-		// Redirect to installer if not installed
274
-		if (!$systemConfig->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
275
-			if (OC::$CLI) {
276
-				throw new Exception('Not installed');
277
-			} else {
278
-				$url = OC::$WEBROOT . '/index.php';
279
-				header('Location: ' . $url);
280
-			}
281
-			exit();
282
-		}
283
-	}
284
-
285
-	public static function checkMaintenanceMode(\OC\SystemConfig $systemConfig) {
286
-		// Allow ajax update script to execute without being stopped
287
-		if (((bool) $systemConfig->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') {
288
-			// send http status 503
289
-			http_response_code(503);
290
-			header('Retry-After: 120');
291
-
292
-			// render error page
293
-			$template = new OC_Template('', 'update.user', 'guest');
294
-			OC_Util::addScript('dist/maintenance');
295
-			OC_Util::addStyle('core', 'guest');
296
-			$template->printPage();
297
-			die();
298
-		}
299
-	}
300
-
301
-	/**
302
-	 * Prints the upgrade page
303
-	 *
304
-	 * @param \OC\SystemConfig $systemConfig
305
-	 */
306
-	private static function printUpgradePage(\OC\SystemConfig $systemConfig) {
307
-		$disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
308
-		$tooBig = false;
309
-		if (!$disableWebUpdater) {
310
-			$apps = \OC::$server->getAppManager();
311
-			if ($apps->isInstalled('user_ldap')) {
312
-				$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
313
-
314
-				$result = $qb->select($qb->func()->count('*', 'user_count'))
315
-					->from('ldap_user_mapping')
316
-					->execute();
317
-				$row = $result->fetch();
318
-				$result->closeCursor();
319
-
320
-				$tooBig = ($row['user_count'] > 50);
321
-			}
322
-			if (!$tooBig && $apps->isInstalled('user_saml')) {
323
-				$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
324
-
325
-				$result = $qb->select($qb->func()->count('*', 'user_count'))
326
-					->from('user_saml_users')
327
-					->execute();
328
-				$row = $result->fetch();
329
-				$result->closeCursor();
330
-
331
-				$tooBig = ($row['user_count'] > 50);
332
-			}
333
-			if (!$tooBig) {
334
-				// count users
335
-				$stats = \OC::$server->getUserManager()->countUsers();
336
-				$totalUsers = array_sum($stats);
337
-				$tooBig = ($totalUsers > 50);
338
-			}
339
-		}
340
-		$ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
341
-			$_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
342
-
343
-		if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
344
-			// send http status 503
345
-			http_response_code(503);
346
-			header('Retry-After: 120');
347
-
348
-			// render error page
349
-			$template = new OC_Template('', 'update.use-cli', 'guest');
350
-			$template->assign('productName', 'nextcloud'); // for now
351
-			$template->assign('version', OC_Util::getVersionString());
352
-			$template->assign('tooBig', $tooBig);
353
-
354
-			$template->printPage();
355
-			die();
356
-		}
357
-
358
-		// check whether this is a core update or apps update
359
-		$installedVersion = $systemConfig->getValue('version', '0.0.0');
360
-		$currentVersion = implode('.', \OCP\Util::getVersion());
361
-
362
-		// if not a core upgrade, then it's apps upgrade
363
-		$isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '=');
364
-
365
-		$oldTheme = $systemConfig->getValue('theme');
366
-		$systemConfig->setValue('theme', '');
367
-		OC_Util::addScript('update');
368
-
369
-		/** @var \OC\App\AppManager $appManager */
370
-		$appManager = \OC::$server->getAppManager();
371
-
372
-		$tmpl = new OC_Template('', 'update.admin', 'guest');
373
-		$tmpl->assign('version', OC_Util::getVersionString());
374
-		$tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
375
-
376
-		// get third party apps
377
-		$ocVersion = \OCP\Util::getVersion();
378
-		$ocVersion = implode('.', $ocVersion);
379
-		$incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
380
-		$incompatibleShippedApps = [];
381
-		foreach ($incompatibleApps as $appInfo) {
382
-			if ($appManager->isShipped($appInfo['id'])) {
383
-				$incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
384
-			}
385
-		}
386
-
387
-		if (!empty($incompatibleShippedApps)) {
388
-			$l = \OC::$server->getL10N('core');
389
-			$hint = $l->t('The files of the app %1$s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
390
-			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);
391
-		}
392
-
393
-		$tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
394
-		$tmpl->assign('incompatibleAppsList', $incompatibleApps);
395
-		$tmpl->assign('productName', 'Nextcloud'); // for now
396
-		$tmpl->assign('oldTheme', $oldTheme);
397
-		$tmpl->printPage();
398
-	}
399
-
400
-	public static function initSession() {
401
-		if (self::$server->getRequest()->getServerProtocol() === 'https') {
402
-			ini_set('session.cookie_secure', true);
403
-		}
404
-
405
-		// prevents javascript from accessing php session cookies
406
-		ini_set('session.cookie_httponly', 'true');
407
-
408
-		// set the cookie path to the Nextcloud directory
409
-		$cookie_path = OC::$WEBROOT ? : '/';
410
-		ini_set('session.cookie_path', $cookie_path);
411
-
412
-		// Let the session name be changed in the initSession Hook
413
-		$sessionName = OC_Util::getInstanceId();
414
-
415
-		try {
416
-			// set the session name to the instance id - which is unique
417
-			$session = new \OC\Session\Internal($sessionName);
418
-
419
-			$cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
420
-			$session = $cryptoWrapper->wrapSession($session);
421
-			self::$server->setSession($session);
422
-
423
-			// if session can't be started break with http 500 error
424
-		} catch (Exception $e) {
425
-			\OC::$server->getLogger()->logException($e, ['app' => 'base']);
426
-			//show the user a detailed error page
427
-			OC_Template::printExceptionErrorPage($e, 500);
428
-			die();
429
-		}
430
-
431
-		$sessionLifeTime = self::getSessionLifeTime();
432
-
433
-		// session timeout
434
-		if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
435
-			if (isset($_COOKIE[session_name()])) {
436
-				setcookie(session_name(), '', -1, self::$WEBROOT ? : '/');
437
-			}
438
-			\OC::$server->getUserSession()->logout();
439
-		}
440
-
441
-		$session->set('LAST_ACTIVITY', time());
442
-	}
443
-
444
-	/**
445
-	 * @return string
446
-	 */
447
-	private static function getSessionLifeTime() {
448
-		return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
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(\OCP\IConfig $config) {
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 = $config->getSystemValue('csrf.optout');
507
-
508
-		// Fallback, if csrf.optout is unset
509
-		if (!is_array($incompatibleUserAgents)) {
510
-			$incompatibleUserAgents = [
511
-				// OS X Finder
512
-				'/^WebDAVFS/',
513
-				// Windows webdav drive
514
-				'/^Microsoft-WebDAV-MiniRedir/',
515
-			];
516
-		}
517
-
518
-		if ($request->isUserAgent($incompatibleUserAgents)) {
519
-			return;
520
-		}
521
-
522
-		if (count($_COOKIE) > 0) {
523
-			$requestUri = $request->getScriptName();
524
-			$processingScript = explode('/', $requestUri);
525
-			$processingScript = $processingScript[count($processingScript) - 1];
526
-
527
-			// index.php routes are handled in the middleware
528
-			if ($processingScript === 'index.php') {
529
-				return;
530
-			}
531
-
532
-			// All other endpoints require the lax and the strict cookie
533
-			if (!$request->passesStrictCookieCheck()) {
534
-				self::sendSameSiteCookies();
535
-				// Debug mode gets access to the resources without strict cookie
536
-				// due to the fact that the SabreDAV browser also lives there.
537
-				if (!$config->getSystemValue('debug', false)) {
538
-					http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
539
-					exit();
540
-				}
541
-			}
542
-		} elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
543
-			self::sendSameSiteCookies();
544
-		}
545
-	}
546
-
547
-	public static function init() {
548
-		// calculate the root directories
549
-		OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
550
-
551
-		// register autoloader
552
-		$loaderStart = microtime(true);
553
-		require_once __DIR__ . '/autoloader.php';
554
-		self::$loader = new \OC\Autoloader([
555
-			OC::$SERVERROOT . '/lib/private/legacy',
556
-		]);
557
-		if (defined('PHPUNIT_RUN')) {
558
-			self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
559
-		}
560
-		spl_autoload_register([self::$loader, 'load']);
561
-		$loaderEnd = microtime(true);
562
-
563
-		self::$CLI = (php_sapi_name() == 'cli');
564
-
565
-		// Add default composer PSR-4 autoloader
566
-		self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
567
-
568
-		try {
569
-			self::initPaths();
570
-			// setup 3rdparty autoloader
571
-			$vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
572
-			if (!file_exists($vendorAutoLoad)) {
573
-				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".');
574
-			}
575
-			require_once $vendorAutoLoad;
576
-		} catch (\RuntimeException $e) {
577
-			if (!self::$CLI) {
578
-				http_response_code(503);
579
-			}
580
-			// we can't use the template error page here, because this needs the
581
-			// DI container which isn't available yet
582
-			print($e->getMessage());
583
-			exit();
584
-		}
585
-
586
-		// setup the basic server
587
-		self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
588
-		self::$server->boot();
589
-		$eventLogger = \OC::$server->getEventLogger();
590
-		$eventLogger->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
591
-		$eventLogger->start('boot', 'Initialize');
592
-
593
-		// Override php.ini and log everything if we're troubleshooting
594
-		if (self::$config->getValue('loglevel') === ILogger::DEBUG) {
595
-			error_reporting(E_ALL);
596
-		}
597
-
598
-		// Don't display errors and log them
599
-		@ini_set('display_errors', '0');
600
-		@ini_set('log_errors', '1');
601
-
602
-		if (!date_default_timezone_set('UTC')) {
603
-			throw new \RuntimeException('Could not set timezone to UTC');
604
-		}
605
-
606
-		//try to configure php to enable big file uploads.
607
-		//this doesn´t work always depending on the webserver and php configuration.
608
-		//Let´s try to overwrite some defaults anyway
609
-
610
-		//try to set the maximum execution time to 60min
611
-		if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
612
-			@set_time_limit(3600);
613
-		}
614
-		@ini_set('max_execution_time', '3600');
615
-		@ini_set('max_input_time', '3600');
616
-
617
-		self::setRequiredIniValues();
618
-		self::handleAuthHeaders();
619
-		$systemConfig = \OC::$server->get(\OC\SystemConfig::class);
620
-		self::registerAutoloaderCache($systemConfig);
621
-
622
-		// initialize intl fallback if necessary
623
-		OC_Util::isSetLocaleWorking();
624
-
625
-		$config = \OC::$server->get(\OCP\IConfig::class);
626
-		if (!defined('PHPUNIT_RUN')) {
627
-			OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
628
-			$debug = $config->getSystemValue('debug', false);
629
-			OC\Log\ErrorHandler::register($debug);
630
-		}
631
-
632
-		/** @var \OC\AppFramework\Bootstrap\Coordinator $bootstrapCoordinator */
633
-		$bootstrapCoordinator = \OC::$server->query(\OC\AppFramework\Bootstrap\Coordinator::class);
634
-		$bootstrapCoordinator->runInitialRegistration();
635
-
636
-		$eventLogger->start('init_session', 'Initialize session');
637
-		OC_App::loadApps(['session']);
638
-		if (!self::$CLI) {
639
-			self::initSession();
640
-		}
641
-		$eventLogger->end('init_session');
642
-		self::checkConfig();
643
-		self::checkInstalled($systemConfig);
644
-
645
-		OC_Response::addSecurityHeaders();
646
-
647
-		self::performSameSiteCookieProtection($config);
648
-
649
-		if (!defined('OC_CONSOLE')) {
650
-			$errors = OC_Util::checkServer($systemConfig);
651
-			if (count($errors) > 0) {
652
-				if (!self::$CLI) {
653
-					http_response_code(503);
654
-					OC_Util::addStyle('guest');
655
-					try {
656
-						OC_Template::printGuestPage('', 'error', ['errors' => $errors]);
657
-						exit;
658
-					} catch (\Exception $e) {
659
-						// In case any error happens when showing the error page, we simply fall back to posting the text.
660
-						// This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it.
661
-					}
662
-				}
663
-
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
-					$config->setAppValue('core', 'cronErrors', json_encode($staticErrors));
677
-				} catch (\Exception $e) {
678
-					echo('Writing to database failed');
679
-				}
680
-				exit(1);
681
-			} elseif (self::$CLI && $config->getSystemValue('installed', false)) {
682
-				$config->deleteAppValue('core', 'cronErrors');
683
-			}
684
-		}
685
-		//try to set the session lifetime
686
-		$sessionLifeTime = self::getSessionLifeTime();
687
-		@ini_set('gc_maxlifetime', (string)$sessionLifeTime);
688
-
689
-		// User and Groups
690
-		if (!$systemConfig->getValue("installed", false)) {
691
-			self::$server->getSession()->set('user_id', '');
692
-		}
693
-
694
-		OC_User::useBackend(new \OC\User\Database());
695
-		\OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
696
-
697
-		// Subscribe to the hook
698
-		\OCP\Util::connectHook(
699
-			'\OCA\Files_Sharing\API\Server2Server',
700
-			'preLoginNameUsedAsUserName',
701
-			'\OC\User\Database',
702
-			'preLoginNameUsedAsUserName'
703
-		);
704
-
705
-		//setup extra user backends
706
-		if (!\OCP\Util::needUpgrade()) {
707
-			OC_User::setupBackends();
708
-		} else {
709
-			// Run upgrades in incognito mode
710
-			OC_User::setIncognitoMode(true);
711
-		}
712
-
713
-		self::registerCleanupHooks($systemConfig);
714
-		self::registerFilesystemHooks();
715
-		self::registerShareHooks($systemConfig);
716
-		self::registerEncryptionWrapperAndHooks();
717
-		self::registerAccountHooks();
718
-		self::registerResourceCollectionHooks();
719
-		self::registerAppRestrictionsHooks();
720
-
721
-		// Make sure that the application class is not loaded before the database is setup
722
-		if ($systemConfig->getValue("installed", false)) {
723
-			OC_App::loadApp('settings');
724
-		}
725
-
726
-		//make sure temporary files are cleaned up
727
-		$tmpManager = \OC::$server->getTempManager();
728
-		register_shutdown_function([$tmpManager, 'clean']);
729
-		$lockProvider = \OC::$server->getLockingProvider();
730
-		register_shutdown_function([$lockProvider, 'releaseAll']);
731
-
732
-		// Check whether the sample configuration has been copied
733
-		if ($systemConfig->getValue('copied_sample_config', false)) {
734
-			$l = \OC::$server->getL10N('lib');
735
-			OC_Template::printErrorPage(
736
-				$l->t('Sample configuration detected'),
737
-				$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'),
738
-				503
739
-			);
740
-			return;
741
-		}
742
-
743
-		$request = \OC::$server->getRequest();
744
-		$host = $request->getInsecureServerHost();
745
-		/**
746
-		 * if the host passed in headers isn't trusted
747
-		 * FIXME: Should not be in here at all :see_no_evil:
748
-		 */
749
-		if (!OC::$CLI
750
-			&& !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
751
-			&& $config->getSystemValue('installed', false)
752
-		) {
753
-			// Allow access to CSS resources
754
-			$isScssRequest = false;
755
-			if (strpos($request->getPathInfo(), '/css/') === 0) {
756
-				$isScssRequest = true;
757
-			}
758
-
759
-			if (substr($request->getRequestUri(), -11) === '/status.php') {
760
-				http_response_code(400);
761
-				header('Content-Type: application/json');
762
-				echo '{"error": "Trusted domain error.", "code": 15}';
763
-				exit();
764
-			}
765
-
766
-			if (!$isScssRequest) {
767
-				http_response_code(400);
768
-
769
-				\OC::$server->getLogger()->info(
770
-					'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
771
-					[
772
-						'app' => 'core',
773
-						'remoteAddress' => $request->getRemoteAddress(),
774
-						'host' => $host,
775
-					]
776
-				);
777
-
778
-				$tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
779
-				$tmpl->assign('docUrl', \OC::$server->getURLGenerator()->linkToDocs('admin-trusted-domains'));
780
-				$tmpl->printPage();
781
-
782
-				exit();
783
-			}
784
-		}
785
-		$eventLogger->end('boot');
786
-	}
787
-
788
-	/**
789
-	 * register hooks for the cleanup of cache and bruteforce protection
790
-	 */
791
-	public static function registerCleanupHooks(\OC\SystemConfig $systemConfig) {
792
-		//don't try to do this before we are properly setup
793
-		if ($systemConfig->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
794
-
795
-			// NOTE: This will be replaced to use OCP
796
-			$userSession = self::$server->getUserSession();
797
-			$userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
798
-				if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) {
799
-					// reset brute force delay for this IP address and username
800
-					$uid = \OC::$server->getUserSession()->getUser()->getUID();
801
-					$request = \OC::$server->getRequest();
802
-					$throttler = \OC::$server->getBruteForceThrottler();
803
-					$throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
804
-				}
805
-
806
-				try {
807
-					$cache = new \OC\Cache\File();
808
-					$cache->gc();
809
-				} catch (\OC\ServerNotAvailableException $e) {
810
-					// not a GC exception, pass it on
811
-					throw $e;
812
-				} catch (\OC\ForbiddenException $e) {
813
-					// filesystem blocked for this request, ignore
814
-				} catch (\Exception $e) {
815
-					// a GC exception should not prevent users from using OC,
816
-					// so log the exception
817
-					\OC::$server->getLogger()->logException($e, [
818
-						'message' => 'Exception when running cache gc.',
819
-						'level' => ILogger::WARN,
820
-						'app' => 'core',
821
-					]);
822
-				}
823
-			});
824
-		}
825
-	}
826
-
827
-	private static function registerEncryptionWrapperAndHooks() {
828
-		$manager = self::$server->getEncryptionManager();
829
-		\OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
830
-
831
-		$enabled = $manager->isEnabled();
832
-		if ($enabled) {
833
-			\OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared');
834
-			\OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared');
835
-			\OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename');
836
-			\OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore');
837
-		}
838
-	}
839
-
840
-	private static function registerAccountHooks() {
841
-		$hookHandler = \OC::$server->get(\OC\Accounts\Hooks::class);
842
-		\OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
843
-	}
844
-
845
-	private static function registerAppRestrictionsHooks() {
846
-		/** @var \OC\Group\Manager $groupManager */
847
-		$groupManager = self::$server->query(\OCP\IGroupManager::class);
848
-		$groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) {
849
-			$appManager = self::$server->getAppManager();
850
-			$apps = $appManager->getEnabledAppsForGroup($group);
851
-			foreach ($apps as $appId) {
852
-				$restrictions = $appManager->getAppRestriction($appId);
853
-				if (empty($restrictions)) {
854
-					continue;
855
-				}
856
-				$key = array_search($group->getGID(), $restrictions);
857
-				unset($restrictions[$key]);
858
-				$restrictions = array_values($restrictions);
859
-				if (empty($restrictions)) {
860
-					$appManager->disableApp($appId);
861
-				} else {
862
-					$appManager->enableAppForGroups($appId, $restrictions);
863
-				}
864
-			}
865
-		});
866
-	}
867
-
868
-	private static function registerResourceCollectionHooks() {
869
-		\OC\Collaboration\Resources\Listener::register(\OC::$server->getEventDispatcher());
870
-	}
871
-
872
-	/**
873
-	 * register hooks for the filesystem
874
-	 */
875
-	public static function registerFilesystemHooks() {
876
-		// Check for blacklisted files
877
-		OC_Hook::connect('OC_Filesystem', 'write', Filesystem::class, 'isBlacklisted');
878
-		OC_Hook::connect('OC_Filesystem', 'rename', Filesystem::class, 'isBlacklisted');
879
-	}
880
-
881
-	/**
882
-	 * register hooks for sharing
883
-	 */
884
-	public static function registerShareHooks(\OC\SystemConfig $systemConfig) {
885
-		if ($systemConfig->getValue('installed')) {
886
-			OC_Hook::connect('OC_User', 'post_deleteUser', Hooks::class, 'post_deleteUser');
887
-			OC_Hook::connect('OC_User', 'post_deleteGroup', Hooks::class, 'post_deleteGroup');
888
-
889
-			/** @var IEventDispatcher $dispatcher */
890
-			$dispatcher = \OC::$server->get(IEventDispatcher::class);
891
-			$dispatcher->addServiceListener(UserRemovedEvent::class, \OC\Share20\UserRemovedListener::class);
892
-		}
893
-	}
894
-
895
-	protected static function registerAutoloaderCache(\OC\SystemConfig $systemConfig) {
896
-		// The class loader takes an optional low-latency cache, which MUST be
897
-		// namespaced. The instanceid is used for namespacing, but might be
898
-		// unavailable at this point. Furthermore, it might not be possible to
899
-		// generate an instanceid via \OC_Util::getInstanceId() because the
900
-		// config file may not be writable. As such, we only register a class
901
-		// loader cache if instanceid is available without trying to create one.
902
-		$instanceId = $systemConfig->getValue('instanceid', null);
903
-		if ($instanceId) {
904
-			try {
905
-				$memcacheFactory = \OC::$server->getMemCacheFactory();
906
-				self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
907
-			} catch (\Exception $ex) {
908
-			}
909
-		}
910
-	}
911
-
912
-	/**
913
-	 * Handle the request
914
-	 */
915
-	public static function handleRequest() {
916
-		\OC::$server->getEventLogger()->start('handle_request', 'Handle request');
917
-		$systemConfig = \OC::$server->getSystemConfig();
918
-
919
-		// Check if Nextcloud is installed or in maintenance (update) mode
920
-		if (!$systemConfig->getValue('installed', false)) {
921
-			\OC::$server->getSession()->clear();
922
-			$setupHelper = new OC\Setup(
923
-				$systemConfig,
924
-				\OC::$server->get(\bantu\IniGetWrapper\IniGetWrapper::class),
925
-				\OC::$server->getL10N('lib'),
926
-				\OC::$server->query(\OCP\Defaults::class),
927
-				\OC::$server->getLogger(),
928
-				\OC::$server->getSecureRandom(),
929
-				\OC::$server->query(\OC\Installer::class)
930
-			);
931
-			$controller = new OC\Core\Controller\SetupController($setupHelper);
932
-			$controller->run($_POST);
933
-			exit();
934
-		}
935
-
936
-		$request = \OC::$server->getRequest();
937
-		$requestPath = $request->getRawPathInfo();
938
-		if ($requestPath === '/heartbeat') {
939
-			return;
940
-		}
941
-		if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
942
-			self::checkMaintenanceMode($systemConfig);
943
-
944
-			if (\OCP\Util::needUpgrade()) {
945
-				if (function_exists('opcache_reset')) {
946
-					opcache_reset();
947
-				}
948
-				if (!((bool) $systemConfig->getValue('maintenance', false))) {
949
-					self::printUpgradePage($systemConfig);
950
-					exit();
951
-				}
952
-			}
953
-		}
954
-
955
-		// emergency app disabling
956
-		if ($requestPath === '/disableapp'
957
-			&& $request->getMethod() === 'POST'
958
-			&& ((array)$request->getParam('appid')) !== ''
959
-		) {
960
-			\OC_JSON::callCheck();
961
-			\OC_JSON::checkAdminUser();
962
-			$appIds = (array)$request->getParam('appid');
963
-			foreach ($appIds as $appId) {
964
-				$appId = \OC_App::cleanAppId($appId);
965
-				\OC::$server->getAppManager()->disableApp($appId);
966
-			}
967
-			\OC_JSON::success();
968
-			exit();
969
-		}
970
-
971
-		// Always load authentication apps
972
-		OC_App::loadApps(['authentication']);
973
-
974
-		// Load minimum set of apps
975
-		if (!\OCP\Util::needUpgrade()
976
-			&& !((bool) $systemConfig->getValue('maintenance', false))) {
977
-			// For logged-in users: Load everything
978
-			if (\OC::$server->getUserSession()->isLoggedIn()) {
979
-				OC_App::loadApps();
980
-			} else {
981
-				// For guests: Load only filesystem and logging
982
-				OC_App::loadApps(['filesystem', 'logging']);
983
-				self::handleLogin($request);
984
-			}
985
-		}
986
-
987
-		if (!self::$CLI) {
988
-			try {
989
-				if (!((bool) $systemConfig->getValue('maintenance', false)) && !\OCP\Util::needUpgrade()) {
990
-					OC_App::loadApps(['filesystem', 'logging']);
991
-					OC_App::loadApps();
992
-				}
993
-				OC::$server->get(\OC\Route\Router::class)->match($request->getRawPathInfo());
994
-				return;
995
-			} catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
996
-				//header('HTTP/1.0 404 Not Found');
997
-			} catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
998
-				http_response_code(405);
999
-				return;
1000
-			}
1001
-		}
1002
-
1003
-		// Handle WebDAV
1004
-		if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
1005
-			// not allowed any more to prevent people
1006
-			// mounting this root directly.
1007
-			// Users need to mount remote.php/webdav instead.
1008
-			http_response_code(405);
1009
-			return;
1010
-		}
1011
-
1012
-		// Someone is logged in
1013
-		if (\OC::$server->getUserSession()->isLoggedIn()) {
1014
-			OC_App::loadApps();
1015
-			OC_User::setupBackends();
1016
-			OC_Util::setupFS();
1017
-			// FIXME
1018
-			// Redirect to default application
1019
-			OC_Util::redirectToDefaultPage();
1020
-		} else {
1021
-			// Not handled and not logged in
1022
-			header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1023
-		}
1024
-	}
1025
-
1026
-	/**
1027
-	 * Check login: apache auth, auth token, basic auth
1028
-	 *
1029
-	 * @param OCP\IRequest $request
1030
-	 * @return boolean
1031
-	 */
1032
-	public static function handleLogin(OCP\IRequest $request) {
1033
-		$userSession = self::$server->getUserSession();
1034
-		if (OC_User::handleApacheAuth()) {
1035
-			return true;
1036
-		}
1037
-		if ($userSession->tryTokenLogin($request)) {
1038
-			return true;
1039
-		}
1040
-		if (isset($_COOKIE['nc_username'])
1041
-			&& isset($_COOKIE['nc_token'])
1042
-			&& isset($_COOKIE['nc_session_id'])
1043
-			&& $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1044
-			return true;
1045
-		}
1046
-		if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1047
-			return true;
1048
-		}
1049
-		return false;
1050
-	}
1051
-
1052
-	protected static function handleAuthHeaders() {
1053
-		//copy http auth headers for apache+php-fcgid work around
1054
-		if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1055
-			$_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1056
-		}
1057
-
1058
-		// Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1059
-		$vars = [
1060
-			'HTTP_AUTHORIZATION', // apache+php-cgi work around
1061
-			'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1062
-		];
1063
-		foreach ($vars as $var) {
1064
-			if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1065
-				$credentials = explode(':', base64_decode($matches[1]), 2);
1066
-				if (count($credentials) === 2) {
1067
-					$_SERVER['PHP_AUTH_USER'] = $credentials[0];
1068
-					$_SERVER['PHP_AUTH_PW'] = $credentials[1];
1069
-					break;
1070
-				}
1071
-			}
1072
-		}
1073
-	}
80
+    /**
81
+     * Associative array for autoloading. classname => filename
82
+     */
83
+    public static $CLASSPATH = [];
84
+    /**
85
+     * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
86
+     */
87
+    public static $SERVERROOT = '';
88
+    /**
89
+     * the current request path relative to the Nextcloud root (e.g. files/index.php)
90
+     */
91
+    private static $SUBURI = '';
92
+    /**
93
+     * the Nextcloud root path for http requests (e.g. nextcloud/)
94
+     */
95
+    public static $WEBROOT = '';
96
+    /**
97
+     * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
98
+     * web path in 'url'
99
+     */
100
+    public static $APPSROOTS = [];
101
+
102
+    /**
103
+     * @var string
104
+     */
105
+    public static $configDir;
106
+
107
+    /**
108
+     * requested app
109
+     */
110
+    public static $REQUESTEDAPP = '';
111
+
112
+    /**
113
+     * check if Nextcloud runs in cli mode
114
+     */
115
+    public static $CLI = false;
116
+
117
+    /**
118
+     * @var \OC\Autoloader $loader
119
+     */
120
+    public static $loader = null;
121
+
122
+    /** @var \Composer\Autoload\ClassLoader $composerAutoloader */
123
+    public static $composerAutoloader = null;
124
+
125
+    /**
126
+     * @var \OC\Server
127
+     */
128
+    public static $server = null;
129
+
130
+    /**
131
+     * @var \OC\Config
132
+     */
133
+    private static $config = null;
134
+
135
+    /**
136
+     * @throws \RuntimeException when the 3rdparty directory is missing or
137
+     * the app path list is empty or contains an invalid path
138
+     */
139
+    public static function initPaths() {
140
+        if (defined('PHPUNIT_CONFIG_DIR')) {
141
+            self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
142
+        } elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
143
+            self::$configDir = OC::$SERVERROOT . '/tests/config/';
144
+        } elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
145
+            self::$configDir = rtrim($dir, '/') . '/';
146
+        } else {
147
+            self::$configDir = OC::$SERVERROOT . '/config/';
148
+        }
149
+        self::$config = new \OC\Config(self::$configDir);
150
+
151
+        OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
152
+        /**
153
+         * FIXME: The following lines are required because we can't yet instantiate
154
+         *        \OC::$server->getRequest() since \OC::$server does not yet exist.
155
+         */
156
+        $params = [
157
+            'server' => [
158
+                'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
159
+                'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
160
+            ],
161
+        ];
162
+        $fakeRequest = new \OC\AppFramework\Http\Request($params, new \OC\Security\SecureRandom(), new \OC\AllConfig(new \OC\SystemConfig(self::$config)));
163
+        $scriptName = $fakeRequest->getScriptName();
164
+        if (substr($scriptName, -1) == '/') {
165
+            $scriptName .= 'index.php';
166
+            //make sure suburi follows the same rules as scriptName
167
+            if (substr(OC::$SUBURI, -9) != 'index.php') {
168
+                if (substr(OC::$SUBURI, -1) != '/') {
169
+                    OC::$SUBURI = OC::$SUBURI . '/';
170
+                }
171
+                OC::$SUBURI = OC::$SUBURI . 'index.php';
172
+            }
173
+        }
174
+
175
+
176
+        if (OC::$CLI) {
177
+            OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
178
+        } else {
179
+            if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
180
+                OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
181
+
182
+                if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
183
+                    OC::$WEBROOT = '/' . OC::$WEBROOT;
184
+                }
185
+            } else {
186
+                // The scriptName is not ending with OC::$SUBURI
187
+                // This most likely means that we are calling from CLI.
188
+                // However some cron jobs still need to generate
189
+                // a web URL, so we use overwritewebroot as a fallback.
190
+                OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
191
+            }
192
+
193
+            // Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
194
+            // slash which is required by URL generation.
195
+            if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
196
+                    substr($_SERVER['REQUEST_URI'], -1) !== '/') {
197
+                header('Location: '.\OC::$WEBROOT.'/');
198
+                exit();
199
+            }
200
+        }
201
+
202
+        // search the apps folder
203
+        $config_paths = self::$config->getValue('apps_paths', []);
204
+        if (!empty($config_paths)) {
205
+            foreach ($config_paths as $paths) {
206
+                if (isset($paths['url']) && isset($paths['path'])) {
207
+                    $paths['url'] = rtrim($paths['url'], '/');
208
+                    $paths['path'] = rtrim($paths['path'], '/');
209
+                    OC::$APPSROOTS[] = $paths;
210
+                }
211
+            }
212
+        } elseif (file_exists(OC::$SERVERROOT . '/apps')) {
213
+            OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true];
214
+        }
215
+
216
+        if (empty(OC::$APPSROOTS)) {
217
+            throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
218
+                . '. You can also configure the location in the config.php file.');
219
+        }
220
+        $paths = [];
221
+        foreach (OC::$APPSROOTS as $path) {
222
+            $paths[] = $path['path'];
223
+            if (!is_dir($path['path'])) {
224
+                throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
225
+                    . ' Nextcloud folder. You can also configure the location in the config.php file.', $path['path']));
226
+            }
227
+        }
228
+
229
+        // set the right include path
230
+        set_include_path(
231
+            implode(PATH_SEPARATOR, $paths)
232
+        );
233
+    }
234
+
235
+    public static function checkConfig() {
236
+        $l = \OC::$server->getL10N('lib');
237
+
238
+        // Create config if it does not already exist
239
+        $configFilePath = self::$configDir .'/config.php';
240
+        if (!file_exists($configFilePath)) {
241
+            @touch($configFilePath);
242
+        }
243
+
244
+        // Check if config is writable
245
+        $configFileWritable = is_writable($configFilePath);
246
+        if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
247
+            || !$configFileWritable && \OCP\Util::needUpgrade()) {
248
+            $urlGenerator = \OC::$server->getURLGenerator();
249
+
250
+            if (self::$CLI) {
251
+                echo $l->t('Cannot write into "config" directory!')."\n";
252
+                echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
253
+                echo "\n";
254
+                echo $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.')."\n";
255
+                echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ])."\n";
256
+                exit;
257
+            } else {
258
+                OC_Template::printErrorPage(
259
+                    $l->t('Cannot write into "config" directory!'),
260
+                    $l->t('This can usually be fixed by giving the webserver write access to the config directory.') . '. '
261
+                    . $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
262
+                    [ $urlGenerator->linkToDocs('admin-config') ]),
263
+                    503
264
+                );
265
+            }
266
+        }
267
+    }
268
+
269
+    public static function checkInstalled(\OC\SystemConfig $systemConfig) {
270
+        if (defined('OC_CONSOLE')) {
271
+            return;
272
+        }
273
+        // Redirect to installer if not installed
274
+        if (!$systemConfig->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
275
+            if (OC::$CLI) {
276
+                throw new Exception('Not installed');
277
+            } else {
278
+                $url = OC::$WEBROOT . '/index.php';
279
+                header('Location: ' . $url);
280
+            }
281
+            exit();
282
+        }
283
+    }
284
+
285
+    public static function checkMaintenanceMode(\OC\SystemConfig $systemConfig) {
286
+        // Allow ajax update script to execute without being stopped
287
+        if (((bool) $systemConfig->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') {
288
+            // send http status 503
289
+            http_response_code(503);
290
+            header('Retry-After: 120');
291
+
292
+            // render error page
293
+            $template = new OC_Template('', 'update.user', 'guest');
294
+            OC_Util::addScript('dist/maintenance');
295
+            OC_Util::addStyle('core', 'guest');
296
+            $template->printPage();
297
+            die();
298
+        }
299
+    }
300
+
301
+    /**
302
+     * Prints the upgrade page
303
+     *
304
+     * @param \OC\SystemConfig $systemConfig
305
+     */
306
+    private static function printUpgradePage(\OC\SystemConfig $systemConfig) {
307
+        $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
308
+        $tooBig = false;
309
+        if (!$disableWebUpdater) {
310
+            $apps = \OC::$server->getAppManager();
311
+            if ($apps->isInstalled('user_ldap')) {
312
+                $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
313
+
314
+                $result = $qb->select($qb->func()->count('*', 'user_count'))
315
+                    ->from('ldap_user_mapping')
316
+                    ->execute();
317
+                $row = $result->fetch();
318
+                $result->closeCursor();
319
+
320
+                $tooBig = ($row['user_count'] > 50);
321
+            }
322
+            if (!$tooBig && $apps->isInstalled('user_saml')) {
323
+                $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
324
+
325
+                $result = $qb->select($qb->func()->count('*', 'user_count'))
326
+                    ->from('user_saml_users')
327
+                    ->execute();
328
+                $row = $result->fetch();
329
+                $result->closeCursor();
330
+
331
+                $tooBig = ($row['user_count'] > 50);
332
+            }
333
+            if (!$tooBig) {
334
+                // count users
335
+                $stats = \OC::$server->getUserManager()->countUsers();
336
+                $totalUsers = array_sum($stats);
337
+                $tooBig = ($totalUsers > 50);
338
+            }
339
+        }
340
+        $ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
341
+            $_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
342
+
343
+        if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
344
+            // send http status 503
345
+            http_response_code(503);
346
+            header('Retry-After: 120');
347
+
348
+            // render error page
349
+            $template = new OC_Template('', 'update.use-cli', 'guest');
350
+            $template->assign('productName', 'nextcloud'); // for now
351
+            $template->assign('version', OC_Util::getVersionString());
352
+            $template->assign('tooBig', $tooBig);
353
+
354
+            $template->printPage();
355
+            die();
356
+        }
357
+
358
+        // check whether this is a core update or apps update
359
+        $installedVersion = $systemConfig->getValue('version', '0.0.0');
360
+        $currentVersion = implode('.', \OCP\Util::getVersion());
361
+
362
+        // if not a core upgrade, then it's apps upgrade
363
+        $isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '=');
364
+
365
+        $oldTheme = $systemConfig->getValue('theme');
366
+        $systemConfig->setValue('theme', '');
367
+        OC_Util::addScript('update');
368
+
369
+        /** @var \OC\App\AppManager $appManager */
370
+        $appManager = \OC::$server->getAppManager();
371
+
372
+        $tmpl = new OC_Template('', 'update.admin', 'guest');
373
+        $tmpl->assign('version', OC_Util::getVersionString());
374
+        $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
375
+
376
+        // get third party apps
377
+        $ocVersion = \OCP\Util::getVersion();
378
+        $ocVersion = implode('.', $ocVersion);
379
+        $incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
380
+        $incompatibleShippedApps = [];
381
+        foreach ($incompatibleApps as $appInfo) {
382
+            if ($appManager->isShipped($appInfo['id'])) {
383
+                $incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
384
+            }
385
+        }
386
+
387
+        if (!empty($incompatibleShippedApps)) {
388
+            $l = \OC::$server->getL10N('core');
389
+            $hint = $l->t('The files of the app %1$s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
390
+            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);
391
+        }
392
+
393
+        $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
394
+        $tmpl->assign('incompatibleAppsList', $incompatibleApps);
395
+        $tmpl->assign('productName', 'Nextcloud'); // for now
396
+        $tmpl->assign('oldTheme', $oldTheme);
397
+        $tmpl->printPage();
398
+    }
399
+
400
+    public static function initSession() {
401
+        if (self::$server->getRequest()->getServerProtocol() === 'https') {
402
+            ini_set('session.cookie_secure', true);
403
+        }
404
+
405
+        // prevents javascript from accessing php session cookies
406
+        ini_set('session.cookie_httponly', 'true');
407
+
408
+        // set the cookie path to the Nextcloud directory
409
+        $cookie_path = OC::$WEBROOT ? : '/';
410
+        ini_set('session.cookie_path', $cookie_path);
411
+
412
+        // Let the session name be changed in the initSession Hook
413
+        $sessionName = OC_Util::getInstanceId();
414
+
415
+        try {
416
+            // set the session name to the instance id - which is unique
417
+            $session = new \OC\Session\Internal($sessionName);
418
+
419
+            $cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
420
+            $session = $cryptoWrapper->wrapSession($session);
421
+            self::$server->setSession($session);
422
+
423
+            // if session can't be started break with http 500 error
424
+        } catch (Exception $e) {
425
+            \OC::$server->getLogger()->logException($e, ['app' => 'base']);
426
+            //show the user a detailed error page
427
+            OC_Template::printExceptionErrorPage($e, 500);
428
+            die();
429
+        }
430
+
431
+        $sessionLifeTime = self::getSessionLifeTime();
432
+
433
+        // session timeout
434
+        if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
435
+            if (isset($_COOKIE[session_name()])) {
436
+                setcookie(session_name(), '', -1, self::$WEBROOT ? : '/');
437
+            }
438
+            \OC::$server->getUserSession()->logout();
439
+        }
440
+
441
+        $session->set('LAST_ACTIVITY', time());
442
+    }
443
+
444
+    /**
445
+     * @return string
446
+     */
447
+    private static function getSessionLifeTime() {
448
+        return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
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(\OCP\IConfig $config) {
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 = $config->getSystemValue('csrf.optout');
507
+
508
+        // Fallback, if csrf.optout is unset
509
+        if (!is_array($incompatibleUserAgents)) {
510
+            $incompatibleUserAgents = [
511
+                // OS X Finder
512
+                '/^WebDAVFS/',
513
+                // Windows webdav drive
514
+                '/^Microsoft-WebDAV-MiniRedir/',
515
+            ];
516
+        }
517
+
518
+        if ($request->isUserAgent($incompatibleUserAgents)) {
519
+            return;
520
+        }
521
+
522
+        if (count($_COOKIE) > 0) {
523
+            $requestUri = $request->getScriptName();
524
+            $processingScript = explode('/', $requestUri);
525
+            $processingScript = $processingScript[count($processingScript) - 1];
526
+
527
+            // index.php routes are handled in the middleware
528
+            if ($processingScript === 'index.php') {
529
+                return;
530
+            }
531
+
532
+            // All other endpoints require the lax and the strict cookie
533
+            if (!$request->passesStrictCookieCheck()) {
534
+                self::sendSameSiteCookies();
535
+                // Debug mode gets access to the resources without strict cookie
536
+                // due to the fact that the SabreDAV browser also lives there.
537
+                if (!$config->getSystemValue('debug', false)) {
538
+                    http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
539
+                    exit();
540
+                }
541
+            }
542
+        } elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
543
+            self::sendSameSiteCookies();
544
+        }
545
+    }
546
+
547
+    public static function init() {
548
+        // calculate the root directories
549
+        OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
550
+
551
+        // register autoloader
552
+        $loaderStart = microtime(true);
553
+        require_once __DIR__ . '/autoloader.php';
554
+        self::$loader = new \OC\Autoloader([
555
+            OC::$SERVERROOT . '/lib/private/legacy',
556
+        ]);
557
+        if (defined('PHPUNIT_RUN')) {
558
+            self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
559
+        }
560
+        spl_autoload_register([self::$loader, 'load']);
561
+        $loaderEnd = microtime(true);
562
+
563
+        self::$CLI = (php_sapi_name() == 'cli');
564
+
565
+        // Add default composer PSR-4 autoloader
566
+        self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
567
+
568
+        try {
569
+            self::initPaths();
570
+            // setup 3rdparty autoloader
571
+            $vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
572
+            if (!file_exists($vendorAutoLoad)) {
573
+                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".');
574
+            }
575
+            require_once $vendorAutoLoad;
576
+        } catch (\RuntimeException $e) {
577
+            if (!self::$CLI) {
578
+                http_response_code(503);
579
+            }
580
+            // we can't use the template error page here, because this needs the
581
+            // DI container which isn't available yet
582
+            print($e->getMessage());
583
+            exit();
584
+        }
585
+
586
+        // setup the basic server
587
+        self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
588
+        self::$server->boot();
589
+        $eventLogger = \OC::$server->getEventLogger();
590
+        $eventLogger->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
591
+        $eventLogger->start('boot', 'Initialize');
592
+
593
+        // Override php.ini and log everything if we're troubleshooting
594
+        if (self::$config->getValue('loglevel') === ILogger::DEBUG) {
595
+            error_reporting(E_ALL);
596
+        }
597
+
598
+        // Don't display errors and log them
599
+        @ini_set('display_errors', '0');
600
+        @ini_set('log_errors', '1');
601
+
602
+        if (!date_default_timezone_set('UTC')) {
603
+            throw new \RuntimeException('Could not set timezone to UTC');
604
+        }
605
+
606
+        //try to configure php to enable big file uploads.
607
+        //this doesn´t work always depending on the webserver and php configuration.
608
+        //Let´s try to overwrite some defaults anyway
609
+
610
+        //try to set the maximum execution time to 60min
611
+        if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
612
+            @set_time_limit(3600);
613
+        }
614
+        @ini_set('max_execution_time', '3600');
615
+        @ini_set('max_input_time', '3600');
616
+
617
+        self::setRequiredIniValues();
618
+        self::handleAuthHeaders();
619
+        $systemConfig = \OC::$server->get(\OC\SystemConfig::class);
620
+        self::registerAutoloaderCache($systemConfig);
621
+
622
+        // initialize intl fallback if necessary
623
+        OC_Util::isSetLocaleWorking();
624
+
625
+        $config = \OC::$server->get(\OCP\IConfig::class);
626
+        if (!defined('PHPUNIT_RUN')) {
627
+            OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
628
+            $debug = $config->getSystemValue('debug', false);
629
+            OC\Log\ErrorHandler::register($debug);
630
+        }
631
+
632
+        /** @var \OC\AppFramework\Bootstrap\Coordinator $bootstrapCoordinator */
633
+        $bootstrapCoordinator = \OC::$server->query(\OC\AppFramework\Bootstrap\Coordinator::class);
634
+        $bootstrapCoordinator->runInitialRegistration();
635
+
636
+        $eventLogger->start('init_session', 'Initialize session');
637
+        OC_App::loadApps(['session']);
638
+        if (!self::$CLI) {
639
+            self::initSession();
640
+        }
641
+        $eventLogger->end('init_session');
642
+        self::checkConfig();
643
+        self::checkInstalled($systemConfig);
644
+
645
+        OC_Response::addSecurityHeaders();
646
+
647
+        self::performSameSiteCookieProtection($config);
648
+
649
+        if (!defined('OC_CONSOLE')) {
650
+            $errors = OC_Util::checkServer($systemConfig);
651
+            if (count($errors) > 0) {
652
+                if (!self::$CLI) {
653
+                    http_response_code(503);
654
+                    OC_Util::addStyle('guest');
655
+                    try {
656
+                        OC_Template::printGuestPage('', 'error', ['errors' => $errors]);
657
+                        exit;
658
+                    } catch (\Exception $e) {
659
+                        // In case any error happens when showing the error page, we simply fall back to posting the text.
660
+                        // This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it.
661
+                    }
662
+                }
663
+
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
+                    $config->setAppValue('core', 'cronErrors', json_encode($staticErrors));
677
+                } catch (\Exception $e) {
678
+                    echo('Writing to database failed');
679
+                }
680
+                exit(1);
681
+            } elseif (self::$CLI && $config->getSystemValue('installed', false)) {
682
+                $config->deleteAppValue('core', 'cronErrors');
683
+            }
684
+        }
685
+        //try to set the session lifetime
686
+        $sessionLifeTime = self::getSessionLifeTime();
687
+        @ini_set('gc_maxlifetime', (string)$sessionLifeTime);
688
+
689
+        // User and Groups
690
+        if (!$systemConfig->getValue("installed", false)) {
691
+            self::$server->getSession()->set('user_id', '');
692
+        }
693
+
694
+        OC_User::useBackend(new \OC\User\Database());
695
+        \OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
696
+
697
+        // Subscribe to the hook
698
+        \OCP\Util::connectHook(
699
+            '\OCA\Files_Sharing\API\Server2Server',
700
+            'preLoginNameUsedAsUserName',
701
+            '\OC\User\Database',
702
+            'preLoginNameUsedAsUserName'
703
+        );
704
+
705
+        //setup extra user backends
706
+        if (!\OCP\Util::needUpgrade()) {
707
+            OC_User::setupBackends();
708
+        } else {
709
+            // Run upgrades in incognito mode
710
+            OC_User::setIncognitoMode(true);
711
+        }
712
+
713
+        self::registerCleanupHooks($systemConfig);
714
+        self::registerFilesystemHooks();
715
+        self::registerShareHooks($systemConfig);
716
+        self::registerEncryptionWrapperAndHooks();
717
+        self::registerAccountHooks();
718
+        self::registerResourceCollectionHooks();
719
+        self::registerAppRestrictionsHooks();
720
+
721
+        // Make sure that the application class is not loaded before the database is setup
722
+        if ($systemConfig->getValue("installed", false)) {
723
+            OC_App::loadApp('settings');
724
+        }
725
+
726
+        //make sure temporary files are cleaned up
727
+        $tmpManager = \OC::$server->getTempManager();
728
+        register_shutdown_function([$tmpManager, 'clean']);
729
+        $lockProvider = \OC::$server->getLockingProvider();
730
+        register_shutdown_function([$lockProvider, 'releaseAll']);
731
+
732
+        // Check whether the sample configuration has been copied
733
+        if ($systemConfig->getValue('copied_sample_config', false)) {
734
+            $l = \OC::$server->getL10N('lib');
735
+            OC_Template::printErrorPage(
736
+                $l->t('Sample configuration detected'),
737
+                $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'),
738
+                503
739
+            );
740
+            return;
741
+        }
742
+
743
+        $request = \OC::$server->getRequest();
744
+        $host = $request->getInsecureServerHost();
745
+        /**
746
+         * if the host passed in headers isn't trusted
747
+         * FIXME: Should not be in here at all :see_no_evil:
748
+         */
749
+        if (!OC::$CLI
750
+            && !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
751
+            && $config->getSystemValue('installed', false)
752
+        ) {
753
+            // Allow access to CSS resources
754
+            $isScssRequest = false;
755
+            if (strpos($request->getPathInfo(), '/css/') === 0) {
756
+                $isScssRequest = true;
757
+            }
758
+
759
+            if (substr($request->getRequestUri(), -11) === '/status.php') {
760
+                http_response_code(400);
761
+                header('Content-Type: application/json');
762
+                echo '{"error": "Trusted domain error.", "code": 15}';
763
+                exit();
764
+            }
765
+
766
+            if (!$isScssRequest) {
767
+                http_response_code(400);
768
+
769
+                \OC::$server->getLogger()->info(
770
+                    'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
771
+                    [
772
+                        'app' => 'core',
773
+                        'remoteAddress' => $request->getRemoteAddress(),
774
+                        'host' => $host,
775
+                    ]
776
+                );
777
+
778
+                $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
779
+                $tmpl->assign('docUrl', \OC::$server->getURLGenerator()->linkToDocs('admin-trusted-domains'));
780
+                $tmpl->printPage();
781
+
782
+                exit();
783
+            }
784
+        }
785
+        $eventLogger->end('boot');
786
+    }
787
+
788
+    /**
789
+     * register hooks for the cleanup of cache and bruteforce protection
790
+     */
791
+    public static function registerCleanupHooks(\OC\SystemConfig $systemConfig) {
792
+        //don't try to do this before we are properly setup
793
+        if ($systemConfig->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
794
+
795
+            // NOTE: This will be replaced to use OCP
796
+            $userSession = self::$server->getUserSession();
797
+            $userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
798
+                if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) {
799
+                    // reset brute force delay for this IP address and username
800
+                    $uid = \OC::$server->getUserSession()->getUser()->getUID();
801
+                    $request = \OC::$server->getRequest();
802
+                    $throttler = \OC::$server->getBruteForceThrottler();
803
+                    $throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
804
+                }
805
+
806
+                try {
807
+                    $cache = new \OC\Cache\File();
808
+                    $cache->gc();
809
+                } catch (\OC\ServerNotAvailableException $e) {
810
+                    // not a GC exception, pass it on
811
+                    throw $e;
812
+                } catch (\OC\ForbiddenException $e) {
813
+                    // filesystem blocked for this request, ignore
814
+                } catch (\Exception $e) {
815
+                    // a GC exception should not prevent users from using OC,
816
+                    // so log the exception
817
+                    \OC::$server->getLogger()->logException($e, [
818
+                        'message' => 'Exception when running cache gc.',
819
+                        'level' => ILogger::WARN,
820
+                        'app' => 'core',
821
+                    ]);
822
+                }
823
+            });
824
+        }
825
+    }
826
+
827
+    private static function registerEncryptionWrapperAndHooks() {
828
+        $manager = self::$server->getEncryptionManager();
829
+        \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
830
+
831
+        $enabled = $manager->isEnabled();
832
+        if ($enabled) {
833
+            \OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared');
834
+            \OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared');
835
+            \OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename');
836
+            \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore');
837
+        }
838
+    }
839
+
840
+    private static function registerAccountHooks() {
841
+        $hookHandler = \OC::$server->get(\OC\Accounts\Hooks::class);
842
+        \OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
843
+    }
844
+
845
+    private static function registerAppRestrictionsHooks() {
846
+        /** @var \OC\Group\Manager $groupManager */
847
+        $groupManager = self::$server->query(\OCP\IGroupManager::class);
848
+        $groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) {
849
+            $appManager = self::$server->getAppManager();
850
+            $apps = $appManager->getEnabledAppsForGroup($group);
851
+            foreach ($apps as $appId) {
852
+                $restrictions = $appManager->getAppRestriction($appId);
853
+                if (empty($restrictions)) {
854
+                    continue;
855
+                }
856
+                $key = array_search($group->getGID(), $restrictions);
857
+                unset($restrictions[$key]);
858
+                $restrictions = array_values($restrictions);
859
+                if (empty($restrictions)) {
860
+                    $appManager->disableApp($appId);
861
+                } else {
862
+                    $appManager->enableAppForGroups($appId, $restrictions);
863
+                }
864
+            }
865
+        });
866
+    }
867
+
868
+    private static function registerResourceCollectionHooks() {
869
+        \OC\Collaboration\Resources\Listener::register(\OC::$server->getEventDispatcher());
870
+    }
871
+
872
+    /**
873
+     * register hooks for the filesystem
874
+     */
875
+    public static function registerFilesystemHooks() {
876
+        // Check for blacklisted files
877
+        OC_Hook::connect('OC_Filesystem', 'write', Filesystem::class, 'isBlacklisted');
878
+        OC_Hook::connect('OC_Filesystem', 'rename', Filesystem::class, 'isBlacklisted');
879
+    }
880
+
881
+    /**
882
+     * register hooks for sharing
883
+     */
884
+    public static function registerShareHooks(\OC\SystemConfig $systemConfig) {
885
+        if ($systemConfig->getValue('installed')) {
886
+            OC_Hook::connect('OC_User', 'post_deleteUser', Hooks::class, 'post_deleteUser');
887
+            OC_Hook::connect('OC_User', 'post_deleteGroup', Hooks::class, 'post_deleteGroup');
888
+
889
+            /** @var IEventDispatcher $dispatcher */
890
+            $dispatcher = \OC::$server->get(IEventDispatcher::class);
891
+            $dispatcher->addServiceListener(UserRemovedEvent::class, \OC\Share20\UserRemovedListener::class);
892
+        }
893
+    }
894
+
895
+    protected static function registerAutoloaderCache(\OC\SystemConfig $systemConfig) {
896
+        // The class loader takes an optional low-latency cache, which MUST be
897
+        // namespaced. The instanceid is used for namespacing, but might be
898
+        // unavailable at this point. Furthermore, it might not be possible to
899
+        // generate an instanceid via \OC_Util::getInstanceId() because the
900
+        // config file may not be writable. As such, we only register a class
901
+        // loader cache if instanceid is available without trying to create one.
902
+        $instanceId = $systemConfig->getValue('instanceid', null);
903
+        if ($instanceId) {
904
+            try {
905
+                $memcacheFactory = \OC::$server->getMemCacheFactory();
906
+                self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
907
+            } catch (\Exception $ex) {
908
+            }
909
+        }
910
+    }
911
+
912
+    /**
913
+     * Handle the request
914
+     */
915
+    public static function handleRequest() {
916
+        \OC::$server->getEventLogger()->start('handle_request', 'Handle request');
917
+        $systemConfig = \OC::$server->getSystemConfig();
918
+
919
+        // Check if Nextcloud is installed or in maintenance (update) mode
920
+        if (!$systemConfig->getValue('installed', false)) {
921
+            \OC::$server->getSession()->clear();
922
+            $setupHelper = new OC\Setup(
923
+                $systemConfig,
924
+                \OC::$server->get(\bantu\IniGetWrapper\IniGetWrapper::class),
925
+                \OC::$server->getL10N('lib'),
926
+                \OC::$server->query(\OCP\Defaults::class),
927
+                \OC::$server->getLogger(),
928
+                \OC::$server->getSecureRandom(),
929
+                \OC::$server->query(\OC\Installer::class)
930
+            );
931
+            $controller = new OC\Core\Controller\SetupController($setupHelper);
932
+            $controller->run($_POST);
933
+            exit();
934
+        }
935
+
936
+        $request = \OC::$server->getRequest();
937
+        $requestPath = $request->getRawPathInfo();
938
+        if ($requestPath === '/heartbeat') {
939
+            return;
940
+        }
941
+        if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
942
+            self::checkMaintenanceMode($systemConfig);
943
+
944
+            if (\OCP\Util::needUpgrade()) {
945
+                if (function_exists('opcache_reset')) {
946
+                    opcache_reset();
947
+                }
948
+                if (!((bool) $systemConfig->getValue('maintenance', false))) {
949
+                    self::printUpgradePage($systemConfig);
950
+                    exit();
951
+                }
952
+            }
953
+        }
954
+
955
+        // emergency app disabling
956
+        if ($requestPath === '/disableapp'
957
+            && $request->getMethod() === 'POST'
958
+            && ((array)$request->getParam('appid')) !== ''
959
+        ) {
960
+            \OC_JSON::callCheck();
961
+            \OC_JSON::checkAdminUser();
962
+            $appIds = (array)$request->getParam('appid');
963
+            foreach ($appIds as $appId) {
964
+                $appId = \OC_App::cleanAppId($appId);
965
+                \OC::$server->getAppManager()->disableApp($appId);
966
+            }
967
+            \OC_JSON::success();
968
+            exit();
969
+        }
970
+
971
+        // Always load authentication apps
972
+        OC_App::loadApps(['authentication']);
973
+
974
+        // Load minimum set of apps
975
+        if (!\OCP\Util::needUpgrade()
976
+            && !((bool) $systemConfig->getValue('maintenance', false))) {
977
+            // For logged-in users: Load everything
978
+            if (\OC::$server->getUserSession()->isLoggedIn()) {
979
+                OC_App::loadApps();
980
+            } else {
981
+                // For guests: Load only filesystem and logging
982
+                OC_App::loadApps(['filesystem', 'logging']);
983
+                self::handleLogin($request);
984
+            }
985
+        }
986
+
987
+        if (!self::$CLI) {
988
+            try {
989
+                if (!((bool) $systemConfig->getValue('maintenance', false)) && !\OCP\Util::needUpgrade()) {
990
+                    OC_App::loadApps(['filesystem', 'logging']);
991
+                    OC_App::loadApps();
992
+                }
993
+                OC::$server->get(\OC\Route\Router::class)->match($request->getRawPathInfo());
994
+                return;
995
+            } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
996
+                //header('HTTP/1.0 404 Not Found');
997
+            } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
998
+                http_response_code(405);
999
+                return;
1000
+            }
1001
+        }
1002
+
1003
+        // Handle WebDAV
1004
+        if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
1005
+            // not allowed any more to prevent people
1006
+            // mounting this root directly.
1007
+            // Users need to mount remote.php/webdav instead.
1008
+            http_response_code(405);
1009
+            return;
1010
+        }
1011
+
1012
+        // Someone is logged in
1013
+        if (\OC::$server->getUserSession()->isLoggedIn()) {
1014
+            OC_App::loadApps();
1015
+            OC_User::setupBackends();
1016
+            OC_Util::setupFS();
1017
+            // FIXME
1018
+            // Redirect to default application
1019
+            OC_Util::redirectToDefaultPage();
1020
+        } else {
1021
+            // Not handled and not logged in
1022
+            header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1023
+        }
1024
+    }
1025
+
1026
+    /**
1027
+     * Check login: apache auth, auth token, basic auth
1028
+     *
1029
+     * @param OCP\IRequest $request
1030
+     * @return boolean
1031
+     */
1032
+    public static function handleLogin(OCP\IRequest $request) {
1033
+        $userSession = self::$server->getUserSession();
1034
+        if (OC_User::handleApacheAuth()) {
1035
+            return true;
1036
+        }
1037
+        if ($userSession->tryTokenLogin($request)) {
1038
+            return true;
1039
+        }
1040
+        if (isset($_COOKIE['nc_username'])
1041
+            && isset($_COOKIE['nc_token'])
1042
+            && isset($_COOKIE['nc_session_id'])
1043
+            && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1044
+            return true;
1045
+        }
1046
+        if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1047
+            return true;
1048
+        }
1049
+        return false;
1050
+    }
1051
+
1052
+    protected static function handleAuthHeaders() {
1053
+        //copy http auth headers for apache+php-fcgid work around
1054
+        if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1055
+            $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1056
+        }
1057
+
1058
+        // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1059
+        $vars = [
1060
+            'HTTP_AUTHORIZATION', // apache+php-cgi work around
1061
+            'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1062
+        ];
1063
+        foreach ($vars as $var) {
1064
+            if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1065
+                $credentials = explode(':', base64_decode($matches[1]), 2);
1066
+                if (count($credentials) === 2) {
1067
+                    $_SERVER['PHP_AUTH_USER'] = $credentials[0];
1068
+                    $_SERVER['PHP_AUTH_PW'] = $credentials[1];
1069
+                    break;
1070
+                }
1071
+            }
1072
+        }
1073
+    }
1074 1074
 }
1075 1075
 
1076 1076
 OC::init();
Please login to merge, or discard this patch.
Spacing   +35 added lines, -35 removed lines patch added patch discarded remove patch
@@ -138,13 +138,13 @@  discard block
 block discarded – undo
138 138
 	 */
139 139
 	public static function initPaths() {
140 140
 		if (defined('PHPUNIT_CONFIG_DIR')) {
141
-			self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
142
-		} elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
143
-			self::$configDir = OC::$SERVERROOT . '/tests/config/';
141
+			self::$configDir = OC::$SERVERROOT.'/'.PHPUNIT_CONFIG_DIR.'/';
142
+		} elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT.'/tests/config/')) {
143
+			self::$configDir = OC::$SERVERROOT.'/tests/config/';
144 144
 		} elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
145
-			self::$configDir = rtrim($dir, '/') . '/';
145
+			self::$configDir = rtrim($dir, '/').'/';
146 146
 		} else {
147
-			self::$configDir = OC::$SERVERROOT . '/config/';
147
+			self::$configDir = OC::$SERVERROOT.'/config/';
148 148
 		}
149 149
 		self::$config = new \OC\Config(self::$configDir);
150 150
 
@@ -166,9 +166,9 @@  discard block
 block discarded – undo
166 166
 			//make sure suburi follows the same rules as scriptName
167 167
 			if (substr(OC::$SUBURI, -9) != 'index.php') {
168 168
 				if (substr(OC::$SUBURI, -1) != '/') {
169
-					OC::$SUBURI = OC::$SUBURI . '/';
169
+					OC::$SUBURI = OC::$SUBURI.'/';
170 170
 				}
171
-				OC::$SUBURI = OC::$SUBURI . 'index.php';
171
+				OC::$SUBURI = OC::$SUBURI.'index.php';
172 172
 			}
173 173
 		}
174 174
 
@@ -180,7 +180,7 @@  discard block
 block discarded – undo
180 180
 				OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
181 181
 
182 182
 				if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
183
-					OC::$WEBROOT = '/' . OC::$WEBROOT;
183
+					OC::$WEBROOT = '/'.OC::$WEBROOT;
184 184
 				}
185 185
 			} else {
186 186
 				// The scriptName is not ending with OC::$SUBURI
@@ -209,8 +209,8 @@  discard block
 block discarded – undo
209 209
 					OC::$APPSROOTS[] = $paths;
210 210
 				}
211 211
 			}
212
-		} elseif (file_exists(OC::$SERVERROOT . '/apps')) {
213
-			OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true];
212
+		} elseif (file_exists(OC::$SERVERROOT.'/apps')) {
213
+			OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT.'/apps', 'url' => '/apps', 'writable' => true];
214 214
 		}
215 215
 
216 216
 		if (empty(OC::$APPSROOTS)) {
@@ -236,7 +236,7 @@  discard block
 block discarded – undo
236 236
 		$l = \OC::$server->getL10N('lib');
237 237
 
238 238
 		// Create config if it does not already exist
239
-		$configFilePath = self::$configDir .'/config.php';
239
+		$configFilePath = self::$configDir.'/config.php';
240 240
 		if (!file_exists($configFilePath)) {
241 241
 			@touch($configFilePath);
242 242
 		}
@@ -252,14 +252,14 @@  discard block
 block discarded – undo
252 252
 				echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
253 253
 				echo "\n";
254 254
 				echo $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.')."\n";
255
-				echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ])."\n";
255
+				echo $l->t('See %s', [$urlGenerator->linkToDocs('admin-config')])."\n";
256 256
 				exit;
257 257
 			} else {
258 258
 				OC_Template::printErrorPage(
259 259
 					$l->t('Cannot write into "config" directory!'),
260
-					$l->t('This can usually be fixed by giving the webserver write access to the config directory.') . '. '
260
+					$l->t('This can usually be fixed by giving the webserver write access to the config directory.').'. '
261 261
 					. $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
262
-					[ $urlGenerator->linkToDocs('admin-config') ]),
262
+					[$urlGenerator->linkToDocs('admin-config')]),
263 263
 					503
264 264
 				);
265 265
 			}
@@ -275,8 +275,8 @@  discard block
 block discarded – undo
275 275
 			if (OC::$CLI) {
276 276
 				throw new Exception('Not installed');
277 277
 			} else {
278
-				$url = OC::$WEBROOT . '/index.php';
279
-				header('Location: ' . $url);
278
+				$url = OC::$WEBROOT.'/index.php';
279
+				header('Location: '.$url);
280 280
 			}
281 281
 			exit();
282 282
 		}
@@ -380,14 +380,14 @@  discard block
 block discarded – undo
380 380
 		$incompatibleShippedApps = [];
381 381
 		foreach ($incompatibleApps as $appInfo) {
382 382
 			if ($appManager->isShipped($appInfo['id'])) {
383
-				$incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
383
+				$incompatibleShippedApps[] = $appInfo['name'].' ('.$appInfo['id'].')';
384 384
 			}
385 385
 		}
386 386
 
387 387
 		if (!empty($incompatibleShippedApps)) {
388 388
 			$l = \OC::$server->getL10N('core');
389 389
 			$hint = $l->t('The files of the app %1$s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
390
-			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);
390
+			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);
391 391
 		}
392 392
 
393 393
 		$tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
@@ -406,7 +406,7 @@  discard block
 block discarded – undo
406 406
 		ini_set('session.cookie_httponly', 'true');
407 407
 
408 408
 		// set the cookie path to the Nextcloud directory
409
-		$cookie_path = OC::$WEBROOT ? : '/';
409
+		$cookie_path = OC::$WEBROOT ?: '/';
410 410
 		ini_set('session.cookie_path', $cookie_path);
411 411
 
412 412
 		// Let the session name be changed in the initSession Hook
@@ -433,7 +433,7 @@  discard block
 block discarded – undo
433 433
 		// session timeout
434 434
 		if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
435 435
 			if (isset($_COOKIE[session_name()])) {
436
-				setcookie(session_name(), '', -1, self::$WEBROOT ? : '/');
436
+				setcookie(session_name(), '', -1, self::$WEBROOT ?: '/');
437 437
 			}
438 438
 			\OC::$server->getUserSession()->logout();
439 439
 		}
@@ -476,7 +476,7 @@  discard block
 block discarded – undo
476 476
 		foreach ($policies as $policy) {
477 477
 			header(
478 478
 				sprintf(
479
-					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
479
+					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;'.$secureCookie.'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
480 480
 					$cookiePrefix,
481 481
 					$policy,
482 482
 					$cookieParams['path'],
@@ -550,12 +550,12 @@  discard block
 block discarded – undo
550 550
 
551 551
 		// register autoloader
552 552
 		$loaderStart = microtime(true);
553
-		require_once __DIR__ . '/autoloader.php';
553
+		require_once __DIR__.'/autoloader.php';
554 554
 		self::$loader = new \OC\Autoloader([
555
-			OC::$SERVERROOT . '/lib/private/legacy',
555
+			OC::$SERVERROOT.'/lib/private/legacy',
556 556
 		]);
557 557
 		if (defined('PHPUNIT_RUN')) {
558
-			self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
558
+			self::$loader->addValidRoot(OC::$SERVERROOT.'/tests');
559 559
 		}
560 560
 		spl_autoload_register([self::$loader, 'load']);
561 561
 		$loaderEnd = microtime(true);
@@ -563,12 +563,12 @@  discard block
 block discarded – undo
563 563
 		self::$CLI = (php_sapi_name() == 'cli');
564 564
 
565 565
 		// Add default composer PSR-4 autoloader
566
-		self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
566
+		self::$composerAutoloader = require_once OC::$SERVERROOT.'/lib/composer/autoload.php';
567 567
 
568 568
 		try {
569 569
 			self::initPaths();
570 570
 			// setup 3rdparty autoloader
571
-			$vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
571
+			$vendorAutoLoad = OC::$SERVERROOT.'/3rdparty/autoload.php';
572 572
 			if (!file_exists($vendorAutoLoad)) {
573 573
 				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".');
574 574
 			}
@@ -664,11 +664,11 @@  discard block
 block discarded – undo
664 664
 				// Convert l10n string into regular string for usage in database
665 665
 				$staticErrors = [];
666 666
 				foreach ($errors as $error) {
667
-					echo $error['error'] . "\n";
668
-					echo $error['hint'] . "\n\n";
667
+					echo $error['error']."\n";
668
+					echo $error['hint']."\n\n";
669 669
 					$staticErrors[] = [
670
-						'error' => (string)$error['error'],
671
-						'hint' => (string)$error['hint'],
670
+						'error' => (string) $error['error'],
671
+						'hint' => (string) $error['hint'],
672 672
 					];
673 673
 				}
674 674
 
@@ -684,7 +684,7 @@  discard block
 block discarded – undo
684 684
 		}
685 685
 		//try to set the session lifetime
686 686
 		$sessionLifeTime = self::getSessionLifeTime();
687
-		@ini_set('gc_maxlifetime', (string)$sessionLifeTime);
687
+		@ini_set('gc_maxlifetime', (string) $sessionLifeTime);
688 688
 
689 689
 		// User and Groups
690 690
 		if (!$systemConfig->getValue("installed", false)) {
@@ -794,7 +794,7 @@  discard block
 block discarded – undo
794 794
 
795 795
 			// NOTE: This will be replaced to use OCP
796 796
 			$userSession = self::$server->getUserSession();
797
-			$userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
797
+			$userSession->listen('\OC\User', 'postLogin', function() use ($userSession) {
798 798
 				if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) {
799 799
 					// reset brute force delay for this IP address and username
800 800
 					$uid = \OC::$server->getUserSession()->getUser()->getUID();
@@ -845,7 +845,7 @@  discard block
 block discarded – undo
845 845
 	private static function registerAppRestrictionsHooks() {
846 846
 		/** @var \OC\Group\Manager $groupManager */
847 847
 		$groupManager = self::$server->query(\OCP\IGroupManager::class);
848
-		$groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) {
848
+		$groupManager->listen('\OC\Group', 'postDelete', function(\OCP\IGroup $group) {
849 849
 			$appManager = self::$server->getAppManager();
850 850
 			$apps = $appManager->getEnabledAppsForGroup($group);
851 851
 			foreach ($apps as $appId) {
@@ -955,11 +955,11 @@  discard block
 block discarded – undo
955 955
 		// emergency app disabling
956 956
 		if ($requestPath === '/disableapp'
957 957
 			&& $request->getMethod() === 'POST'
958
-			&& ((array)$request->getParam('appid')) !== ''
958
+			&& ((array) $request->getParam('appid')) !== ''
959 959
 		) {
960 960
 			\OC_JSON::callCheck();
961 961
 			\OC_JSON::checkAdminUser();
962
-			$appIds = (array)$request->getParam('appid');
962
+			$appIds = (array) $request->getParam('appid');
963 963
 			foreach ($appIds as $appId) {
964 964
 				$appId = \OC_App::cleanAppId($appId);
965 965
 				\OC::$server->getAppManager()->disableApp($appId);
Please login to merge, or discard this patch.