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