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