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