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