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