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