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