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