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