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