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