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