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