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