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