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