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