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