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