Completed
Push — master ( 43edff...c60c8a )
by Morris
154:29 queued 129:13
created
lib/base.php 2 patches
Spacing   +57 added lines, -57 removed lines patch added patch discarded remove patch
@@ -128,14 +128,14 @@  discard block
 block discarded – undo
128 128
 	 * the app path list is empty or contains an invalid path
129 129
 	 */
130 130
 	public static function initPaths() {
131
-		if(defined('PHPUNIT_CONFIG_DIR')) {
132
-			self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
133
-		} elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
134
-			self::$configDir = OC::$SERVERROOT . '/tests/config/';
135
-		} elseif($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
136
-			self::$configDir = rtrim($dir, '/') . '/';
131
+		if (defined('PHPUNIT_CONFIG_DIR')) {
132
+			self::$configDir = OC::$SERVERROOT.'/'.PHPUNIT_CONFIG_DIR.'/';
133
+		} elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT.'/tests/config/')) {
134
+			self::$configDir = OC::$SERVERROOT.'/tests/config/';
135
+		} elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
136
+			self::$configDir = rtrim($dir, '/').'/';
137 137
 		} else {
138
-			self::$configDir = OC::$SERVERROOT . '/config/';
138
+			self::$configDir = OC::$SERVERROOT.'/config/';
139 139
 		}
140 140
 		self::$config = new \OC\Config(self::$configDir);
141 141
 
@@ -157,9 +157,9 @@  discard block
 block discarded – undo
157 157
 			//make sure suburi follows the same rules as scriptName
158 158
 			if (substr(OC::$SUBURI, -9) != 'index.php') {
159 159
 				if (substr(OC::$SUBURI, -1) != '/') {
160
-					OC::$SUBURI = OC::$SUBURI . '/';
160
+					OC::$SUBURI = OC::$SUBURI.'/';
161 161
 				}
162
-				OC::$SUBURI = OC::$SUBURI . 'index.php';
162
+				OC::$SUBURI = OC::$SUBURI.'index.php';
163 163
 			}
164 164
 		}
165 165
 
@@ -171,7 +171,7 @@  discard block
 block discarded – undo
171 171
 				OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
172 172
 
173 173
 				if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
174
-					OC::$WEBROOT = '/' . OC::$WEBROOT;
174
+					OC::$WEBROOT = '/'.OC::$WEBROOT;
175 175
 				}
176 176
 			} else {
177 177
 				// The scriptName is not ending with OC::$SUBURI
@@ -200,11 +200,11 @@  discard block
 block discarded – undo
200 200
 					OC::$APPSROOTS[] = $paths;
201 201
 				}
202 202
 			}
203
-		} elseif (file_exists(OC::$SERVERROOT . '/apps')) {
204
-			OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
205
-		} elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
203
+		} elseif (file_exists(OC::$SERVERROOT.'/apps')) {
204
+			OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT.'/apps', 'url' => '/apps', 'writable' => true);
205
+		} elseif (file_exists(OC::$SERVERROOT.'/../apps')) {
206 206
 			OC::$APPSROOTS[] = array(
207
-				'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
207
+				'path' => rtrim(dirname(OC::$SERVERROOT), '/').'/apps',
208 208
 				'url' => '/apps',
209 209
 				'writable' => true
210 210
 			);
@@ -234,8 +234,8 @@  discard block
 block discarded – undo
234 234
 		$l = \OC::$server->getL10N('lib');
235 235
 
236 236
 		// Create config if it does not already exist
237
-		$configFilePath = self::$configDir .'/config.php';
238
-		if(!file_exists($configFilePath)) {
237
+		$configFilePath = self::$configDir.'/config.php';
238
+		if (!file_exists($configFilePath)) {
239 239
 			@touch($configFilePath);
240 240
 		}
241 241
 
@@ -250,13 +250,13 @@  discard block
 block discarded – undo
250 250
 				echo $l->t('Cannot write into "config" directory!')."\n";
251 251
 				echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
252 252
 				echo "\n";
253
-				echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-dir_permissions') ])."\n";
253
+				echo $l->t('See %s', [$urlGenerator->linkToDocs('admin-dir_permissions')])."\n";
254 254
 				exit;
255 255
 			} else {
256 256
 				OC_Template::printErrorPage(
257 257
 					$l->t('Cannot write into "config" directory!'),
258 258
 					$l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
259
-					 [ $urlGenerator->linkToDocs('admin-dir_permissions') ])
259
+					 [$urlGenerator->linkToDocs('admin-dir_permissions')])
260 260
 				);
261 261
 			}
262 262
 		}
@@ -271,8 +271,8 @@  discard block
 block discarded – undo
271 271
 			if (OC::$CLI) {
272 272
 				throw new Exception('Not installed');
273 273
 			} else {
274
-				$url = OC::$WEBROOT . '/index.php';
275
-				header('Location: ' . $url);
274
+				$url = OC::$WEBROOT.'/index.php';
275
+				header('Location: '.$url);
276 276
 			}
277 277
 			exit();
278 278
 		}
@@ -379,14 +379,14 @@  discard block
 block discarded – undo
379 379
 		$incompatibleShippedApps = [];
380 380
 		foreach ($incompatibleApps as $appInfo) {
381 381
 			if ($appManager->isShipped($appInfo['id'])) {
382
-				$incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
382
+				$incompatibleShippedApps[] = $appInfo['name'].' ('.$appInfo['id'].')';
383 383
 			}
384 384
 		}
385 385
 
386 386
 		if (!empty($incompatibleShippedApps)) {
387 387
 			$l = \OC::$server->getL10N('core');
388 388
 			$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)]);
389
-			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
+			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);
390 390
 		}
391 391
 
392 392
 		$tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
@@ -397,7 +397,7 @@  discard block
 block discarded – undo
397 397
 	}
398 398
 
399 399
 	public static function initSession() {
400
-		if(self::$server->getRequest()->getServerProtocol() === 'https') {
400
+		if (self::$server->getRequest()->getServerProtocol() === 'https') {
401 401
 			ini_set('session.cookie_secure', true);
402 402
 		}
403 403
 
@@ -405,7 +405,7 @@  discard block
 block discarded – undo
405 405
 		ini_set('session.cookie_httponly', 'true');
406 406
 
407 407
 		// set the cookie path to the Nextcloud directory
408
-		$cookie_path = OC::$WEBROOT ? : '/';
408
+		$cookie_path = OC::$WEBROOT ?: '/';
409 409
 		ini_set('session.cookie_path', $cookie_path);
410 410
 
411 411
 		// Let the session name be changed in the initSession Hook
@@ -439,7 +439,7 @@  discard block
 block discarded – undo
439 439
 		// session timeout
440 440
 		if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
441 441
 			if (isset($_COOKIE[session_name()])) {
442
-				setcookie(session_name(), null, -1, self::$WEBROOT ? : '/');
442
+				setcookie(session_name(), null, -1, self::$WEBROOT ?: '/');
443 443
 			}
444 444
 			\OC::$server->getUserSession()->logout();
445 445
 		}
@@ -461,7 +461,7 @@  discard block
 block discarded – undo
461 461
 				continue;
462 462
 			}
463 463
 
464
-			$file = $appPath . '/appinfo/classpath.php';
464
+			$file = $appPath.'/appinfo/classpath.php';
465 465
 			if (file_exists($file)) {
466 466
 				require_once $file;
467 467
 			}
@@ -489,14 +489,14 @@  discard block
 block discarded – undo
489 489
 
490 490
 		// Append __Host to the cookie if it meets the requirements
491 491
 		$cookiePrefix = '';
492
-		if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
492
+		if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
493 493
 			$cookiePrefix = '__Host-';
494 494
 		}
495 495
 
496
-		foreach($policies as $policy) {
496
+		foreach ($policies as $policy) {
497 497
 			header(
498 498
 				sprintf(
499
-					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
499
+					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;'.$secureCookie.'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
500 500
 					$cookiePrefix,
501 501
 					$policy,
502 502
 					$cookieParams['path'],
@@ -534,31 +534,31 @@  discard block
 block discarded – undo
534 534
 			];
535 535
 		}
536 536
 
537
-		if($request->isUserAgent($incompatibleUserAgents)) {
537
+		if ($request->isUserAgent($incompatibleUserAgents)) {
538 538
 			return;
539 539
 		}
540 540
 
541
-		if(count($_COOKIE) > 0) {
541
+		if (count($_COOKIE) > 0) {
542 542
 			$requestUri = $request->getScriptName();
543 543
 			$processingScript = explode('/', $requestUri);
544
-			$processingScript = $processingScript[count($processingScript)-1];
544
+			$processingScript = $processingScript[count($processingScript) - 1];
545 545
 
546 546
 			// index.php routes are handled in the middleware
547
-			if($processingScript === 'index.php') {
547
+			if ($processingScript === 'index.php') {
548 548
 				return;
549 549
 			}
550 550
 
551 551
 			// All other endpoints require the lax and the strict cookie
552
-			if(!$request->passesStrictCookieCheck()) {
552
+			if (!$request->passesStrictCookieCheck()) {
553 553
 				self::sendSameSiteCookies();
554 554
 				// Debug mode gets access to the resources without strict cookie
555 555
 				// due to the fact that the SabreDAV browser also lives there.
556
-				if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
556
+				if (!\OC::$server->getConfig()->getSystemValue('debug', false)) {
557 557
 					http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
558 558
 					exit();
559 559
 				}
560 560
 			}
561
-		} elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
561
+		} elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
562 562
 			self::sendSameSiteCookies();
563 563
 		}
564 564
 	}
@@ -569,12 +569,12 @@  discard block
 block discarded – undo
569 569
 
570 570
 		// register autoloader
571 571
 		$loaderStart = microtime(true);
572
-		require_once __DIR__ . '/autoloader.php';
572
+		require_once __DIR__.'/autoloader.php';
573 573
 		self::$loader = new \OC\Autoloader([
574
-			OC::$SERVERROOT . '/lib/private/legacy',
574
+			OC::$SERVERROOT.'/lib/private/legacy',
575 575
 		]);
576 576
 		if (defined('PHPUNIT_RUN')) {
577
-			self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
577
+			self::$loader->addValidRoot(OC::$SERVERROOT.'/tests');
578 578
 		}
579 579
 		spl_autoload_register(array(self::$loader, 'load'));
580 580
 		$loaderEnd = microtime(true);
@@ -582,12 +582,12 @@  discard block
 block discarded – undo
582 582
 		self::$CLI = (php_sapi_name() == 'cli');
583 583
 
584 584
 		// Add default composer PSR-4 autoloader
585
-		self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
585
+		self::$composerAutoloader = require_once OC::$SERVERROOT.'/lib/composer/autoload.php';
586 586
 
587 587
 		try {
588 588
 			self::initPaths();
589 589
 			// setup 3rdparty autoloader
590
-			$vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
590
+			$vendorAutoLoad = OC::$SERVERROOT.'/3rdparty/autoload.php';
591 591
 			if (!file_exists($vendorAutoLoad)) {
592 592
 				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".');
593 593
 			}
@@ -597,7 +597,7 @@  discard block
 block discarded – undo
597 597
 			if (!self::$CLI) {
598 598
 				$claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']);
599 599
 				$protocol = in_array($claimedProtocol, ['HTTP/1.0', 'HTTP/1.1', 'HTTP/2']) ? $claimedProtocol : 'HTTP/1.1';
600
-				header($protocol . ' ' . OC_Response::STATUS_SERVICE_UNAVAILABLE);
600
+				header($protocol.' '.OC_Response::STATUS_SERVICE_UNAVAILABLE);
601 601
 			}
602 602
 			// we can't use the template error page here, because this needs the
603 603
 			// DI container which isn't available yet
@@ -615,7 +615,7 @@  discard block
 block discarded – undo
615 615
 		@ini_set('display_errors', '0');
616 616
 		@ini_set('log_errors', '1');
617 617
 
618
-		if(!date_default_timezone_set('UTC')) {
618
+		if (!date_default_timezone_set('UTC')) {
619 619
 			throw new \RuntimeException('Could not set timezone to UTC');
620 620
 		}
621 621
 
@@ -669,11 +669,11 @@  discard block
 block discarded – undo
669 669
 					// Convert l10n string into regular string for usage in database
670 670
 					$staticErrors = [];
671 671
 					foreach ($errors as $error) {
672
-						echo $error['error'] . "\n";
673
-						echo $error['hint'] . "\n\n";
672
+						echo $error['error']."\n";
673
+						echo $error['hint']."\n\n";
674 674
 						$staticErrors[] = [
675
-							'error' => (string)$error['error'],
676
-							'hint' => (string)$error['hint'],
675
+							'error' => (string) $error['error'],
676
+							'hint' => (string) $error['hint'],
677 677
 						];
678 678
 					}
679 679
 
@@ -695,7 +695,7 @@  discard block
 block discarded – undo
695 695
 		}
696 696
 		//try to set the session lifetime
697 697
 		$sessionLifeTime = self::getSessionLifeTime();
698
-		@ini_set('gc_maxlifetime', (string)$sessionLifeTime);
698
+		@ini_set('gc_maxlifetime', (string) $sessionLifeTime);
699 699
 
700 700
 		$systemConfig = \OC::$server->getSystemConfig();
701 701
 
@@ -743,7 +743,7 @@  discard block
 block discarded – undo
743 743
 		register_shutdown_function(array($lockProvider, 'releaseAll'));
744 744
 
745 745
 		// Check whether the sample configuration has been copied
746
-		if($systemConfig->getValue('copied_sample_config', false)) {
746
+		if ($systemConfig->getValue('copied_sample_config', false)) {
747 747
 			$l = \OC::$server->getL10N('lib');
748 748
 			header('HTTP/1.1 503 Service Temporarily Unavailable');
749 749
 			header('Status: 503 Service Temporarily Unavailable');
@@ -769,11 +769,11 @@  discard block
 block discarded – undo
769 769
 		) {
770 770
 			// Allow access to CSS resources
771 771
 			$isScssRequest = false;
772
-			if(strpos($request->getPathInfo(), '/css/') === 0) {
772
+			if (strpos($request->getPathInfo(), '/css/') === 0) {
773 773
 				$isScssRequest = true;
774 774
 			}
775 775
 
776
-			if(substr($request->getRequestUri(), -11) === '/status.php') {
776
+			if (substr($request->getRequestUri(), -11) === '/status.php') {
777 777
 				OC_Response::setStatus(\OC_Response::STATUS_BAD_REQUEST);
778 778
 				header('Status: 400 Bad Request');
779 779
 				header('Content-Type: application/json');
@@ -813,7 +813,7 @@  discard block
 block discarded – undo
813 813
 
814 814
 			// NOTE: This will be replaced to use OCP
815 815
 			$userSession = self::$server->getUserSession();
816
-			$userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
816
+			$userSession->listen('\OC\User', 'postLogin', function() use ($userSession) {
817 817
 				if (!defined('PHPUNIT_RUN')) {
818 818
 					// reset brute force delay for this IP address and username
819 819
 					$uid = \OC::$server->getUserSession()->getUser()->getUID();
@@ -898,7 +898,7 @@  discard block
 block discarded – undo
898 898
 			} catch (\Exception $ex) {
899 899
 			}
900 900
 
901
-			self::$composerAutoloader->setApcuPrefix($instanceId . '-mainComposer');
901
+			self::$composerAutoloader->setApcuPrefix($instanceId.'-mainComposer');
902 902
 		}
903 903
 	}
904 904
 
@@ -952,12 +952,12 @@  discard block
 block discarded – undo
952 952
 		// emergency app disabling
953 953
 		if ($requestPath === '/disableapp'
954 954
 			&& $request->getMethod() === 'POST'
955
-			&& ((array)$request->getParam('appid')) !== ''
955
+			&& ((array) $request->getParam('appid')) !== ''
956 956
 		) {
957 957
 			\OC_JSON::callCheck();
958 958
 			\OC_JSON::checkAdminUser();
959
-			$appIds = (array)$request->getParam('appid');
960
-			foreach($appIds as $appId) {
959
+			$appIds = (array) $request->getParam('appid');
960
+			foreach ($appIds as $appId) {
961 961
 				$appId = \OC_App::cleanAppId($appId);
962 962
 				\OC::$server->getAppManager()->disableApp($appId);
963 963
 			}
@@ -972,7 +972,7 @@  discard block
 block discarded – undo
972 972
 		if (!\OCP\Util::needUpgrade()
973 973
 			&& !$systemConfig->getValue('maintenance', false)) {
974 974
 			// For logged-in users: Load everything
975
-			if(\OC::$server->getUserSession()->isLoggedIn()) {
975
+			if (\OC::$server->getUserSession()->isLoggedIn()) {
976 976
 				OC_App::loadApps();
977 977
 			} else {
978 978
 				// For guests: Load only filesystem and logging
Please login to merge, or discard this patch.
Indentation   +1001 added lines, -1001 removed lines patch added patch discarded remove patch
@@ -68,1007 +68,1007 @@
 block discarded – undo
68 68
  * OC_autoload!
69 69
  */
70 70
 class OC {
71
-	/**
72
-	 * Associative array for autoloading. classname => filename
73
-	 */
74
-	public static $CLASSPATH = array();
75
-	/**
76
-	 * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
77
-	 */
78
-	public static $SERVERROOT = '';
79
-	/**
80
-	 * the current request path relative to the Nextcloud root (e.g. files/index.php)
81
-	 */
82
-	private static $SUBURI = '';
83
-	/**
84
-	 * the Nextcloud root path for http requests (e.g. nextcloud/)
85
-	 */
86
-	public static $WEBROOT = '';
87
-	/**
88
-	 * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
89
-	 * web path in 'url'
90
-	 */
91
-	public static $APPSROOTS = array();
92
-
93
-	/**
94
-	 * @var string
95
-	 */
96
-	public static $configDir;
97
-
98
-	/**
99
-	 * requested app
100
-	 */
101
-	public static $REQUESTEDAPP = '';
102
-
103
-	/**
104
-	 * check if Nextcloud runs in cli mode
105
-	 */
106
-	public static $CLI = false;
107
-
108
-	/**
109
-	 * @var \OC\Autoloader $loader
110
-	 */
111
-	public static $loader = null;
112
-
113
-	/** @var \Composer\Autoload\ClassLoader $composerAutoloader */
114
-	public static $composerAutoloader = null;
115
-
116
-	/**
117
-	 * @var \OC\Server
118
-	 */
119
-	public static $server = null;
120
-
121
-	/**
122
-	 * @var \OC\Config
123
-	 */
124
-	private static $config = null;
125
-
126
-	/**
127
-	 * @throws \RuntimeException when the 3rdparty directory is missing or
128
-	 * the app path list is empty or contains an invalid path
129
-	 */
130
-	public static function initPaths() {
131
-		if(defined('PHPUNIT_CONFIG_DIR')) {
132
-			self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
133
-		} elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
134
-			self::$configDir = OC::$SERVERROOT . '/tests/config/';
135
-		} elseif($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
136
-			self::$configDir = rtrim($dir, '/') . '/';
137
-		} else {
138
-			self::$configDir = OC::$SERVERROOT . '/config/';
139
-		}
140
-		self::$config = new \OC\Config(self::$configDir);
141
-
142
-		OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
143
-		/**
144
-		 * FIXME: The following lines are required because we can't yet instantiate
145
-		 *        \OC::$server->getRequest() since \OC::$server does not yet exist.
146
-		 */
147
-		$params = [
148
-			'server' => [
149
-				'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
150
-				'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
151
-			],
152
-		];
153
-		$fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig(self::$config)));
154
-		$scriptName = $fakeRequest->getScriptName();
155
-		if (substr($scriptName, -1) == '/') {
156
-			$scriptName .= 'index.php';
157
-			//make sure suburi follows the same rules as scriptName
158
-			if (substr(OC::$SUBURI, -9) != 'index.php') {
159
-				if (substr(OC::$SUBURI, -1) != '/') {
160
-					OC::$SUBURI = OC::$SUBURI . '/';
161
-				}
162
-				OC::$SUBURI = OC::$SUBURI . 'index.php';
163
-			}
164
-		}
165
-
166
-
167
-		if (OC::$CLI) {
168
-			OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
169
-		} else {
170
-			if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
171
-				OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
172
-
173
-				if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
174
-					OC::$WEBROOT = '/' . OC::$WEBROOT;
175
-				}
176
-			} else {
177
-				// The scriptName is not ending with OC::$SUBURI
178
-				// This most likely means that we are calling from CLI.
179
-				// However some cron jobs still need to generate
180
-				// a web URL, so we use overwritewebroot as a fallback.
181
-				OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
182
-			}
183
-
184
-			// Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
185
-			// slash which is required by URL generation.
186
-			if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
187
-					substr($_SERVER['REQUEST_URI'], -1) !== '/') {
188
-				header('Location: '.\OC::$WEBROOT.'/');
189
-				exit();
190
-			}
191
-		}
192
-
193
-		// search the apps folder
194
-		$config_paths = self::$config->getValue('apps_paths', array());
195
-		if (!empty($config_paths)) {
196
-			foreach ($config_paths as $paths) {
197
-				if (isset($paths['url']) && isset($paths['path'])) {
198
-					$paths['url'] = rtrim($paths['url'], '/');
199
-					$paths['path'] = rtrim($paths['path'], '/');
200
-					OC::$APPSROOTS[] = $paths;
201
-				}
202
-			}
203
-		} elseif (file_exists(OC::$SERVERROOT . '/apps')) {
204
-			OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
205
-		} elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
206
-			OC::$APPSROOTS[] = array(
207
-				'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
208
-				'url' => '/apps',
209
-				'writable' => true
210
-			);
211
-		}
212
-
213
-		if (empty(OC::$APPSROOTS)) {
214
-			throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
215
-				. ' or the folder above. You can also configure the location in the config.php file.');
216
-		}
217
-		$paths = array();
218
-		foreach (OC::$APPSROOTS as $path) {
219
-			$paths[] = $path['path'];
220
-			if (!is_dir($path['path'])) {
221
-				throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
222
-					. ' Nextcloud folder or the folder above. You can also configure the location in the'
223
-					. ' config.php file.', $path['path']));
224
-			}
225
-		}
226
-
227
-		// set the right include path
228
-		set_include_path(
229
-			implode(PATH_SEPARATOR, $paths)
230
-		);
231
-	}
232
-
233
-	public static function checkConfig() {
234
-		$l = \OC::$server->getL10N('lib');
235
-
236
-		// Create config if it does not already exist
237
-		$configFilePath = self::$configDir .'/config.php';
238
-		if(!file_exists($configFilePath)) {
239
-			@touch($configFilePath);
240
-		}
241
-
242
-		// Check if config is writable
243
-		$configFileWritable = is_writable($configFilePath);
244
-		if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
245
-			|| !$configFileWritable && \OCP\Util::needUpgrade()) {
246
-
247
-			$urlGenerator = \OC::$server->getURLGenerator();
248
-
249
-			if (self::$CLI) {
250
-				echo $l->t('Cannot write into "config" directory!')."\n";
251
-				echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
252
-				echo "\n";
253
-				echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-dir_permissions') ])."\n";
254
-				exit;
255
-			} else {
256
-				OC_Template::printErrorPage(
257
-					$l->t('Cannot write into "config" directory!'),
258
-					$l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
259
-					 [ $urlGenerator->linkToDocs('admin-dir_permissions') ])
260
-				);
261
-			}
262
-		}
263
-	}
264
-
265
-	public static function checkInstalled() {
266
-		if (defined('OC_CONSOLE')) {
267
-			return;
268
-		}
269
-		// Redirect to installer if not installed
270
-		if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
271
-			if (OC::$CLI) {
272
-				throw new Exception('Not installed');
273
-			} else {
274
-				$url = OC::$WEBROOT . '/index.php';
275
-				header('Location: ' . $url);
276
-			}
277
-			exit();
278
-		}
279
-	}
280
-
281
-	public static function checkMaintenanceMode() {
282
-		// Allow ajax update script to execute without being stopped
283
-		if (\OC::$server->getSystemConfig()->getValue('maintenance', false) && OC::$SUBURI != '/core/ajax/update.php') {
284
-			// send http status 503
285
-			header('HTTP/1.1 503 Service Temporarily Unavailable');
286
-			header('Status: 503 Service Temporarily Unavailable');
287
-			header('Retry-After: 120');
288
-
289
-			// render error page
290
-			$template = new OC_Template('', 'update.user', 'guest');
291
-			OC_Util::addScript('maintenance-check');
292
-			OC_Util::addStyle('core', 'guest');
293
-			$template->printPage();
294
-			die();
295
-		}
296
-	}
297
-
298
-	/**
299
-	 * Prints the upgrade page
300
-	 *
301
-	 * @param \OC\SystemConfig $systemConfig
302
-	 */
303
-	private static function printUpgradePage(\OC\SystemConfig $systemConfig) {
304
-		$disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
305
-		$tooBig = false;
306
-		if (!$disableWebUpdater) {
307
-			$apps = \OC::$server->getAppManager();
308
-			if ($apps->isInstalled('user_ldap')) {
309
-				$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
310
-
311
-				$result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
312
-					->from('ldap_user_mapping')
313
-					->execute();
314
-				$row = $result->fetch();
315
-				$result->closeCursor();
316
-
317
-				$tooBig = ($row['user_count'] > 50);
318
-			}
319
-			if (!$tooBig && $apps->isInstalled('user_saml')) {
320
-				$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
321
-
322
-				$result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
323
-					->from('user_saml_users')
324
-					->execute();
325
-				$row = $result->fetch();
326
-				$result->closeCursor();
327
-
328
-				$tooBig = ($row['user_count'] > 50);
329
-			}
330
-			if (!$tooBig) {
331
-				// count users
332
-				$stats = \OC::$server->getUserManager()->countUsers();
333
-				$totalUsers = array_sum($stats);
334
-				$tooBig = ($totalUsers > 50);
335
-			}
336
-		}
337
-		$ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
338
-			$_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
339
-
340
-		if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
341
-			// send http status 503
342
-			header('HTTP/1.1 503 Service Temporarily Unavailable');
343
-			header('Status: 503 Service Temporarily Unavailable');
344
-			header('Retry-After: 120');
345
-
346
-			// render error page
347
-			$template = new OC_Template('', 'update.use-cli', 'guest');
348
-			$template->assign('productName', 'nextcloud'); // for now
349
-			$template->assign('version', OC_Util::getVersionString());
350
-			$template->assign('tooBig', $tooBig);
351
-
352
-			$template->printPage();
353
-			die();
354
-		}
355
-
356
-		// check whether this is a core update or apps update
357
-		$installedVersion = $systemConfig->getValue('version', '0.0.0');
358
-		$currentVersion = implode('.', \OCP\Util::getVersion());
359
-
360
-		// if not a core upgrade, then it's apps upgrade
361
-		$isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '=');
362
-
363
-		$oldTheme = $systemConfig->getValue('theme');
364
-		$systemConfig->setValue('theme', '');
365
-		OC_Util::addScript('config'); // needed for web root
366
-		OC_Util::addScript('update');
367
-
368
-		/** @var \OC\App\AppManager $appManager */
369
-		$appManager = \OC::$server->getAppManager();
370
-
371
-		$tmpl = new OC_Template('', 'update.admin', 'guest');
372
-		$tmpl->assign('version', OC_Util::getVersionString());
373
-		$tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
374
-
375
-		// get third party apps
376
-		$ocVersion = \OCP\Util::getVersion();
377
-		$ocVersion = implode('.', $ocVersion);
378
-		$incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
379
-		$incompatibleShippedApps = [];
380
-		foreach ($incompatibleApps as $appInfo) {
381
-			if ($appManager->isShipped($appInfo['id'])) {
382
-				$incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
383
-			}
384
-		}
385
-
386
-		if (!empty($incompatibleShippedApps)) {
387
-			$l = \OC::$server->getL10N('core');
388
-			$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)]);
389
-			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);
390
-		}
391
-
392
-		$tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
393
-		$tmpl->assign('incompatibleAppsList', $incompatibleApps);
394
-		$tmpl->assign('productName', 'Nextcloud'); // for now
395
-		$tmpl->assign('oldTheme', $oldTheme);
396
-		$tmpl->printPage();
397
-	}
398
-
399
-	public static function initSession() {
400
-		if(self::$server->getRequest()->getServerProtocol() === 'https') {
401
-			ini_set('session.cookie_secure', true);
402
-		}
403
-
404
-		// prevents javascript from accessing php session cookies
405
-		ini_set('session.cookie_httponly', 'true');
406
-
407
-		// set the cookie path to the Nextcloud directory
408
-		$cookie_path = OC::$WEBROOT ? : '/';
409
-		ini_set('session.cookie_path', $cookie_path);
410
-
411
-		// Let the session name be changed in the initSession Hook
412
-		$sessionName = OC_Util::getInstanceId();
413
-
414
-		try {
415
-			// Allow session apps to create a custom session object
416
-			$useCustomSession = false;
417
-			$session = self::$server->getSession();
418
-			OC_Hook::emit('OC', 'initSession', array('session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession));
419
-			if (!$useCustomSession) {
420
-				// set the session name to the instance id - which is unique
421
-				$session = new \OC\Session\Internal($sessionName);
422
-			}
423
-
424
-			$cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
425
-			$session = $cryptoWrapper->wrapSession($session);
426
-			self::$server->setSession($session);
427
-
428
-			// if session can't be started break with http 500 error
429
-		} catch (Exception $e) {
430
-			\OC::$server->getLogger()->logException($e, ['app' => 'base']);
431
-			//show the user a detailed error page
432
-			OC_Response::setStatus(OC_Response::STATUS_INTERNAL_SERVER_ERROR);
433
-			OC_Template::printExceptionErrorPage($e);
434
-			die();
435
-		}
436
-
437
-		$sessionLifeTime = self::getSessionLifeTime();
438
-
439
-		// session timeout
440
-		if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
441
-			if (isset($_COOKIE[session_name()])) {
442
-				setcookie(session_name(), null, -1, self::$WEBROOT ? : '/');
443
-			}
444
-			\OC::$server->getUserSession()->logout();
445
-		}
446
-
447
-		$session->set('LAST_ACTIVITY', time());
448
-	}
449
-
450
-	/**
451
-	 * @return string
452
-	 */
453
-	private static function getSessionLifeTime() {
454
-		return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
455
-	}
456
-
457
-	public static function loadAppClassPaths() {
458
-		foreach (OC_App::getEnabledApps() as $app) {
459
-			$appPath = OC_App::getAppPath($app);
460
-			if ($appPath === false) {
461
-				continue;
462
-			}
463
-
464
-			$file = $appPath . '/appinfo/classpath.php';
465
-			if (file_exists($file)) {
466
-				require_once $file;
467
-			}
468
-		}
469
-	}
470
-
471
-	/**
472
-	 * Try to set some values to the required Nextcloud default
473
-	 */
474
-	public static function setRequiredIniValues() {
475
-		@ini_set('default_charset', 'UTF-8');
476
-		@ini_set('gd.jpeg_ignore_warning', '1');
477
-	}
478
-
479
-	/**
480
-	 * Send the same site cookies
481
-	 */
482
-	private static function sendSameSiteCookies() {
483
-		$cookieParams = session_get_cookie_params();
484
-		$secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
485
-		$policies = [
486
-			'lax',
487
-			'strict',
488
-		];
489
-
490
-		// Append __Host to the cookie if it meets the requirements
491
-		$cookiePrefix = '';
492
-		if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
493
-			$cookiePrefix = '__Host-';
494
-		}
495
-
496
-		foreach($policies as $policy) {
497
-			header(
498
-				sprintf(
499
-					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
500
-					$cookiePrefix,
501
-					$policy,
502
-					$cookieParams['path'],
503
-					$policy
504
-				),
505
-				false
506
-			);
507
-		}
508
-	}
509
-
510
-	/**
511
-	 * Same Site cookie to further mitigate CSRF attacks. This cookie has to
512
-	 * be set in every request if cookies are sent to add a second level of
513
-	 * defense against CSRF.
514
-	 *
515
-	 * If the cookie is not sent this will set the cookie and reload the page.
516
-	 * We use an additional cookie since we want to protect logout CSRF and
517
-	 * also we can't directly interfere with PHP's session mechanism.
518
-	 */
519
-	private static function performSameSiteCookieProtection() {
520
-		$request = \OC::$server->getRequest();
521
-
522
-		// Some user agents are notorious and don't really properly follow HTTP
523
-		// specifications. For those, have an automated opt-out. Since the protection
524
-		// for remote.php is applied in base.php as starting point we need to opt out
525
-		// here.
526
-		$incompatibleUserAgents = \OC::$server->getConfig()->getSystemValue('csrf.optout');
527
-
528
-		// Fallback, if csrf.optout is unset
529
-		if (!is_array($incompatibleUserAgents)) {
530
-			$incompatibleUserAgents = [
531
-				// OS X Finder
532
-				'/^WebDAVFS/',
533
-				// Windows webdav drive
534
-				'/^Microsoft-WebDAV-MiniRedir/',
535
-			];
536
-		}
537
-
538
-		if($request->isUserAgent($incompatibleUserAgents)) {
539
-			return;
540
-		}
541
-
542
-		if(count($_COOKIE) > 0) {
543
-			$requestUri = $request->getScriptName();
544
-			$processingScript = explode('/', $requestUri);
545
-			$processingScript = $processingScript[count($processingScript)-1];
546
-
547
-			// index.php routes are handled in the middleware
548
-			if($processingScript === 'index.php') {
549
-				return;
550
-			}
551
-
552
-			// All other endpoints require the lax and the strict cookie
553
-			if(!$request->passesStrictCookieCheck()) {
554
-				self::sendSameSiteCookies();
555
-				// Debug mode gets access to the resources without strict cookie
556
-				// due to the fact that the SabreDAV browser also lives there.
557
-				if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
558
-					http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
559
-					exit();
560
-				}
561
-			}
562
-		} elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
563
-			self::sendSameSiteCookies();
564
-		}
565
-	}
566
-
567
-	public static function init() {
568
-		// calculate the root directories
569
-		OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
570
-
571
-		// register autoloader
572
-		$loaderStart = microtime(true);
573
-		require_once __DIR__ . '/autoloader.php';
574
-		self::$loader = new \OC\Autoloader([
575
-			OC::$SERVERROOT . '/lib/private/legacy',
576
-		]);
577
-		if (defined('PHPUNIT_RUN')) {
578
-			self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
579
-		}
580
-		spl_autoload_register(array(self::$loader, 'load'));
581
-		$loaderEnd = microtime(true);
582
-
583
-		self::$CLI = (php_sapi_name() == 'cli');
584
-
585
-		// Add default composer PSR-4 autoloader
586
-		self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
587
-
588
-		try {
589
-			self::initPaths();
590
-			// setup 3rdparty autoloader
591
-			$vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
592
-			if (!file_exists($vendorAutoLoad)) {
593
-				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".');
594
-			}
595
-			require_once $vendorAutoLoad;
596
-
597
-		} catch (\RuntimeException $e) {
598
-			if (!self::$CLI) {
599
-				$claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']);
600
-				$protocol = in_array($claimedProtocol, ['HTTP/1.0', 'HTTP/1.1', 'HTTP/2']) ? $claimedProtocol : 'HTTP/1.1';
601
-				header($protocol . ' ' . OC_Response::STATUS_SERVICE_UNAVAILABLE);
602
-			}
603
-			// we can't use the template error page here, because this needs the
604
-			// DI container which isn't available yet
605
-			print($e->getMessage());
606
-			exit();
607
-		}
608
-
609
-		// setup the basic server
610
-		self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
611
-		\OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
612
-		\OC::$server->getEventLogger()->start('boot', 'Initialize');
613
-
614
-		// Don't display errors and log them
615
-		error_reporting(E_ALL | E_STRICT);
616
-		@ini_set('display_errors', '0');
617
-		@ini_set('log_errors', '1');
618
-
619
-		if(!date_default_timezone_set('UTC')) {
620
-			throw new \RuntimeException('Could not set timezone to UTC');
621
-		}
622
-
623
-		//try to configure php to enable big file uploads.
624
-		//this doesn´t work always depending on the webserver and php configuration.
625
-		//Let´s try to overwrite some defaults anyway
626
-
627
-		//try to set the maximum execution time to 60min
628
-		if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
629
-			@set_time_limit(3600);
630
-		}
631
-		@ini_set('max_execution_time', '3600');
632
-		@ini_set('max_input_time', '3600');
633
-
634
-		//try to set the maximum filesize to 10G
635
-		@ini_set('upload_max_filesize', '10G');
636
-		@ini_set('post_max_size', '10G');
637
-		@ini_set('file_uploads', '50');
638
-
639
-		self::setRequiredIniValues();
640
-		self::handleAuthHeaders();
641
-		self::registerAutoloaderCache();
642
-
643
-		// initialize intl fallback is necessary
644
-		\Patchwork\Utf8\Bootup::initIntl();
645
-		OC_Util::isSetLocaleWorking();
646
-
647
-		if (!defined('PHPUNIT_RUN')) {
648
-			OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
649
-			$debug = \OC::$server->getConfig()->getSystemValue('debug', false);
650
-			OC\Log\ErrorHandler::register($debug);
651
-		}
652
-
653
-		\OC::$server->getEventLogger()->start('init_session', 'Initialize session');
654
-		OC_App::loadApps(array('session'));
655
-		if (!self::$CLI) {
656
-			self::initSession();
657
-		}
658
-		\OC::$server->getEventLogger()->end('init_session');
659
-		self::checkConfig();
660
-		self::checkInstalled();
661
-
662
-		OC_Response::addSecurityHeaders();
663
-
664
-		self::performSameSiteCookieProtection();
665
-
666
-		if (!defined('OC_CONSOLE')) {
667
-			$errors = OC_Util::checkServer(\OC::$server->getSystemConfig());
668
-			if (count($errors) > 0) {
669
-				if (self::$CLI) {
670
-					// Convert l10n string into regular string for usage in database
671
-					$staticErrors = [];
672
-					foreach ($errors as $error) {
673
-						echo $error['error'] . "\n";
674
-						echo $error['hint'] . "\n\n";
675
-						$staticErrors[] = [
676
-							'error' => (string)$error['error'],
677
-							'hint' => (string)$error['hint'],
678
-						];
679
-					}
680
-
681
-					try {
682
-						\OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
683
-					} catch (\Exception $e) {
684
-						echo('Writing to database failed');
685
-					}
686
-					exit(1);
687
-				} else {
688
-					OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE);
689
-					OC_Util::addStyle('guest');
690
-					OC_Template::printGuestPage('', 'error', array('errors' => $errors));
691
-					exit;
692
-				}
693
-			} elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
694
-				\OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
695
-			}
696
-		}
697
-		//try to set the session lifetime
698
-		$sessionLifeTime = self::getSessionLifeTime();
699
-		@ini_set('gc_maxlifetime', (string)$sessionLifeTime);
700
-
701
-		$systemConfig = \OC::$server->getSystemConfig();
702
-
703
-		// User and Groups
704
-		if (!$systemConfig->getValue("installed", false)) {
705
-			self::$server->getSession()->set('user_id', '');
706
-		}
707
-
708
-		OC_User::useBackend(new \OC\User\Database());
709
-		\OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
710
-
711
-		// Subscribe to the hook
712
-		\OCP\Util::connectHook(
713
-			'\OCA\Files_Sharing\API\Server2Server',
714
-			'preLoginNameUsedAsUserName',
715
-			'\OC\User\Database',
716
-			'preLoginNameUsedAsUserName'
717
-		);
718
-
719
-		//setup extra user backends
720
-		if (!\OCP\Util::needUpgrade()) {
721
-			OC_User::setupBackends();
722
-		} else {
723
-			// Run upgrades in incognito mode
724
-			OC_User::setIncognitoMode(true);
725
-		}
726
-
727
-		self::registerCleanupHooks();
728
-		self::registerFilesystemHooks();
729
-		self::registerShareHooks();
730
-		self::registerEncryptionWrapper();
731
-		self::registerEncryptionHooks();
732
-		self::registerAccountHooks();
733
-
734
-		// Make sure that the application class is not loaded before the database is setup
735
-		if ($systemConfig->getValue("installed", false)) {
736
-			$settings = new \OC\Settings\Application();
737
-			$settings->register();
738
-		}
739
-
740
-		//make sure temporary files are cleaned up
741
-		$tmpManager = \OC::$server->getTempManager();
742
-		register_shutdown_function(array($tmpManager, 'clean'));
743
-		$lockProvider = \OC::$server->getLockingProvider();
744
-		register_shutdown_function(array($lockProvider, 'releaseAll'));
745
-
746
-		// Check whether the sample configuration has been copied
747
-		if($systemConfig->getValue('copied_sample_config', false)) {
748
-			$l = \OC::$server->getL10N('lib');
749
-			header('HTTP/1.1 503 Service Temporarily Unavailable');
750
-			header('Status: 503 Service Temporarily Unavailable');
751
-			OC_Template::printErrorPage(
752
-				$l->t('Sample configuration detected'),
753
-				$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')
754
-			);
755
-			return;
756
-		}
757
-
758
-		$request = \OC::$server->getRequest();
759
-		$host = $request->getInsecureServerHost();
760
-		/**
761
-		 * if the host passed in headers isn't trusted
762
-		 * FIXME: Should not be in here at all :see_no_evil:
763
-		 */
764
-		if (!OC::$CLI
765
-			// overwritehost is always trusted, workaround to not have to make
766
-			// \OC\AppFramework\Http\Request::getOverwriteHost public
767
-			&& self::$server->getConfig()->getSystemValue('overwritehost') === ''
768
-			&& !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
769
-			&& self::$server->getConfig()->getSystemValue('installed', false)
770
-		) {
771
-			// Allow access to CSS resources
772
-			$isScssRequest = false;
773
-			if(strpos($request->getPathInfo(), '/css/') === 0) {
774
-				$isScssRequest = true;
775
-			}
776
-
777
-			if(substr($request->getRequestUri(), -11) === '/status.php') {
778
-				OC_Response::setStatus(\OC_Response::STATUS_BAD_REQUEST);
779
-				header('Status: 400 Bad Request');
780
-				header('Content-Type: application/json');
781
-				echo '{"error": "Trusted domain error.", "code": 15}';
782
-				exit();
783
-			}
784
-
785
-			if (!$isScssRequest) {
786
-				OC_Response::setStatus(\OC_Response::STATUS_BAD_REQUEST);
787
-				header('Status: 400 Bad Request');
788
-
789
-				\OC::$server->getLogger()->info(
790
-					'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
791
-					[
792
-						'app' => 'core',
793
-						'remoteAddress' => $request->getRemoteAddress(),
794
-						'host' => $host,
795
-					]
796
-				);
797
-
798
-				$tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
799
-				$tmpl->assign('docUrl', \OC::$server->getURLGenerator()->linkToDocs('admin-trusted-domains'));
800
-				$tmpl->printPage();
801
-
802
-				exit();
803
-			}
804
-		}
805
-		\OC::$server->getEventLogger()->end('boot');
806
-	}
807
-
808
-	/**
809
-	 * register hooks for the cleanup of cache and bruteforce protection
810
-	 */
811
-	public static function registerCleanupHooks() {
812
-		//don't try to do this before we are properly setup
813
-		if (\OC::$server->getSystemConfig()->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
814
-
815
-			// NOTE: This will be replaced to use OCP
816
-			$userSession = self::$server->getUserSession();
817
-			$userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
818
-				if (!defined('PHPUNIT_RUN')) {
819
-					// reset brute force delay for this IP address and username
820
-					$uid = \OC::$server->getUserSession()->getUser()->getUID();
821
-					$request = \OC::$server->getRequest();
822
-					$throttler = \OC::$server->getBruteForceThrottler();
823
-					$throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
824
-				}
825
-
826
-				try {
827
-					$cache = new \OC\Cache\File();
828
-					$cache->gc();
829
-				} catch (\OC\ServerNotAvailableException $e) {
830
-					// not a GC exception, pass it on
831
-					throw $e;
832
-				} catch (\OC\ForbiddenException $e) {
833
-					// filesystem blocked for this request, ignore
834
-				} catch (\Exception $e) {
835
-					// a GC exception should not prevent users from using OC,
836
-					// so log the exception
837
-					\OC::$server->getLogger()->logException($e, [
838
-						'message' => 'Exception when running cache gc.',
839
-						'level' => ILogger::WARN,
840
-						'app' => 'core',
841
-					]);
842
-				}
843
-			});
844
-		}
845
-	}
846
-
847
-	private static function registerEncryptionWrapper() {
848
-		$manager = self::$server->getEncryptionManager();
849
-		\OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
850
-	}
851
-
852
-	private static function registerEncryptionHooks() {
853
-		$enabled = self::$server->getEncryptionManager()->isEnabled();
854
-		if ($enabled) {
855
-			\OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared');
856
-			\OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared');
857
-			\OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename');
858
-			\OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore');
859
-		}
860
-	}
861
-
862
-	private static function registerAccountHooks() {
863
-		$hookHandler = new \OC\Accounts\Hooks(\OC::$server->getLogger());
864
-		\OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
865
-	}
866
-
867
-	/**
868
-	 * register hooks for the filesystem
869
-	 */
870
-	public static function registerFilesystemHooks() {
871
-		// Check for blacklisted files
872
-		OC_Hook::connect('OC_Filesystem', 'write', Filesystem::class, 'isBlacklisted');
873
-		OC_Hook::connect('OC_Filesystem', 'rename', Filesystem::class, 'isBlacklisted');
874
-	}
875
-
876
-	/**
877
-	 * register hooks for sharing
878
-	 */
879
-	public static function registerShareHooks() {
880
-		if (\OC::$server->getSystemConfig()->getValue('installed')) {
881
-			OC_Hook::connect('OC_User', 'post_deleteUser', Hooks::class, 'post_deleteUser');
882
-			OC_Hook::connect('OC_User', 'post_removeFromGroup', Hooks::class, 'post_removeFromGroup');
883
-			OC_Hook::connect('OC_User', 'post_deleteGroup', Hooks::class, 'post_deleteGroup');
884
-		}
885
-	}
886
-
887
-	protected static function registerAutoloaderCache() {
888
-		// The class loader takes an optional low-latency cache, which MUST be
889
-		// namespaced. The instanceid is used for namespacing, but might be
890
-		// unavailable at this point. Furthermore, it might not be possible to
891
-		// generate an instanceid via \OC_Util::getInstanceId() because the
892
-		// config file may not be writable. As such, we only register a class
893
-		// loader cache if instanceid is available without trying to create one.
894
-		$instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
895
-		if ($instanceId) {
896
-			try {
897
-				$memcacheFactory = \OC::$server->getMemCacheFactory();
898
-				self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
899
-			} catch (\Exception $ex) {
900
-			}
901
-
902
-			self::$composerAutoloader->setApcuPrefix($instanceId . '-mainComposer');
903
-		}
904
-	}
905
-
906
-	/**
907
-	 * Handle the request
908
-	 */
909
-	public static function handleRequest() {
910
-
911
-		\OC::$server->getEventLogger()->start('handle_request', 'Handle request');
912
-		$systemConfig = \OC::$server->getSystemConfig();
913
-		// load all the classpaths from the enabled apps so they are available
914
-		// in the routing files of each app
915
-		OC::loadAppClassPaths();
916
-
917
-		// Check if Nextcloud is installed or in maintenance (update) mode
918
-		if (!$systemConfig->getValue('installed', false)) {
919
-			\OC::$server->getSession()->clear();
920
-			$setupHelper = new OC\Setup(
921
-				$systemConfig,
922
-				\OC::$server->getIniWrapper(),
923
-				\OC::$server->getL10N('lib'),
924
-				\OC::$server->query(\OCP\Defaults::class),
925
-				\OC::$server->getLogger(),
926
-				\OC::$server->getSecureRandom(),
927
-				\OC::$server->query(\OC\Installer::class)
928
-			);
929
-			$controller = new OC\Core\Controller\SetupController($setupHelper);
930
-			$controller->run($_POST);
931
-			exit();
932
-		}
933
-
934
-		$request = \OC::$server->getRequest();
935
-		$requestPath = $request->getRawPathInfo();
936
-		if ($requestPath === '/heartbeat') {
937
-			return;
938
-		}
939
-		if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
940
-			self::checkMaintenanceMode();
941
-
942
-			if (\OCP\Util::needUpgrade()) {
943
-				if (function_exists('opcache_reset')) {
944
-					opcache_reset();
945
-				}
946
-				if (!$systemConfig->getValue('maintenance', false)) {
947
-					self::printUpgradePage($systemConfig);
948
-					exit();
949
-				}
950
-			}
951
-		}
952
-
953
-		// emergency app disabling
954
-		if ($requestPath === '/disableapp'
955
-			&& $request->getMethod() === 'POST'
956
-			&& ((array)$request->getParam('appid')) !== ''
957
-		) {
958
-			\OC_JSON::callCheck();
959
-			\OC_JSON::checkAdminUser();
960
-			$appIds = (array)$request->getParam('appid');
961
-			foreach($appIds as $appId) {
962
-				$appId = \OC_App::cleanAppId($appId);
963
-				\OC::$server->getAppManager()->disableApp($appId);
964
-			}
965
-			\OC_JSON::success();
966
-			exit();
967
-		}
968
-
969
-		// Always load authentication apps
970
-		OC_App::loadApps(['authentication']);
971
-
972
-		// Load minimum set of apps
973
-		if (!\OCP\Util::needUpgrade()
974
-			&& !$systemConfig->getValue('maintenance', false)) {
975
-			// For logged-in users: Load everything
976
-			if(\OC::$server->getUserSession()->isLoggedIn()) {
977
-				OC_App::loadApps();
978
-			} else {
979
-				// For guests: Load only filesystem and logging
980
-				OC_App::loadApps(array('filesystem', 'logging'));
981
-				self::handleLogin($request);
982
-			}
983
-		}
984
-
985
-		if (!self::$CLI) {
986
-			try {
987
-				if (!$systemConfig->getValue('maintenance', false) && !\OCP\Util::needUpgrade()) {
988
-					OC_App::loadApps(array('filesystem', 'logging'));
989
-					OC_App::loadApps();
990
-				}
991
-				OC_Util::setupFS();
992
-				OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
993
-				return;
994
-			} catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
995
-				//header('HTTP/1.0 404 Not Found');
996
-			} catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
997
-				OC_Response::setStatus(405);
998
-				return;
999
-			}
1000
-		}
1001
-
1002
-		// Handle WebDAV
1003
-		if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
1004
-			// not allowed any more to prevent people
1005
-			// mounting this root directly.
1006
-			// Users need to mount remote.php/webdav instead.
1007
-			header('HTTP/1.1 405 Method Not Allowed');
1008
-			header('Status: 405 Method Not Allowed');
1009
-			return;
1010
-		}
1011
-
1012
-		// Someone is logged in
1013
-		if (\OC::$server->getUserSession()->isLoggedIn()) {
1014
-			OC_App::loadApps();
1015
-			OC_User::setupBackends();
1016
-			OC_Util::setupFS();
1017
-			// FIXME
1018
-			// Redirect to default application
1019
-			OC_Util::redirectToDefaultPage();
1020
-		} else {
1021
-			// Not handled and not logged in
1022
-			header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1023
-		}
1024
-	}
1025
-
1026
-	/**
1027
-	 * Check login: apache auth, auth token, basic auth
1028
-	 *
1029
-	 * @param OCP\IRequest $request
1030
-	 * @return boolean
1031
-	 */
1032
-	static function handleLogin(OCP\IRequest $request) {
1033
-		$userSession = self::$server->getUserSession();
1034
-		if (OC_User::handleApacheAuth()) {
1035
-			return true;
1036
-		}
1037
-		if ($userSession->tryTokenLogin($request)) {
1038
-			return true;
1039
-		}
1040
-		if (isset($_COOKIE['nc_username'])
1041
-			&& isset($_COOKIE['nc_token'])
1042
-			&& isset($_COOKIE['nc_session_id'])
1043
-			&& $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1044
-			return true;
1045
-		}
1046
-		if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1047
-			return true;
1048
-		}
1049
-		return false;
1050
-	}
1051
-
1052
-	protected static function handleAuthHeaders() {
1053
-		//copy http auth headers for apache+php-fcgid work around
1054
-		if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1055
-			$_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1056
-		}
1057
-
1058
-		// Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1059
-		$vars = array(
1060
-			'HTTP_AUTHORIZATION', // apache+php-cgi work around
1061
-			'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1062
-		);
1063
-		foreach ($vars as $var) {
1064
-			if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1065
-				list($name, $password) = explode(':', base64_decode($matches[1]), 2);
1066
-				$_SERVER['PHP_AUTH_USER'] = $name;
1067
-				$_SERVER['PHP_AUTH_PW'] = $password;
1068
-				break;
1069
-			}
1070
-		}
1071
-	}
71
+    /**
72
+     * Associative array for autoloading. classname => filename
73
+     */
74
+    public static $CLASSPATH = array();
75
+    /**
76
+     * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
77
+     */
78
+    public static $SERVERROOT = '';
79
+    /**
80
+     * the current request path relative to the Nextcloud root (e.g. files/index.php)
81
+     */
82
+    private static $SUBURI = '';
83
+    /**
84
+     * the Nextcloud root path for http requests (e.g. nextcloud/)
85
+     */
86
+    public static $WEBROOT = '';
87
+    /**
88
+     * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
89
+     * web path in 'url'
90
+     */
91
+    public static $APPSROOTS = array();
92
+
93
+    /**
94
+     * @var string
95
+     */
96
+    public static $configDir;
97
+
98
+    /**
99
+     * requested app
100
+     */
101
+    public static $REQUESTEDAPP = '';
102
+
103
+    /**
104
+     * check if Nextcloud runs in cli mode
105
+     */
106
+    public static $CLI = false;
107
+
108
+    /**
109
+     * @var \OC\Autoloader $loader
110
+     */
111
+    public static $loader = null;
112
+
113
+    /** @var \Composer\Autoload\ClassLoader $composerAutoloader */
114
+    public static $composerAutoloader = null;
115
+
116
+    /**
117
+     * @var \OC\Server
118
+     */
119
+    public static $server = null;
120
+
121
+    /**
122
+     * @var \OC\Config
123
+     */
124
+    private static $config = null;
125
+
126
+    /**
127
+     * @throws \RuntimeException when the 3rdparty directory is missing or
128
+     * the app path list is empty or contains an invalid path
129
+     */
130
+    public static function initPaths() {
131
+        if(defined('PHPUNIT_CONFIG_DIR')) {
132
+            self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
133
+        } elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
134
+            self::$configDir = OC::$SERVERROOT . '/tests/config/';
135
+        } elseif($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
136
+            self::$configDir = rtrim($dir, '/') . '/';
137
+        } else {
138
+            self::$configDir = OC::$SERVERROOT . '/config/';
139
+        }
140
+        self::$config = new \OC\Config(self::$configDir);
141
+
142
+        OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
143
+        /**
144
+         * FIXME: The following lines are required because we can't yet instantiate
145
+         *        \OC::$server->getRequest() since \OC::$server does not yet exist.
146
+         */
147
+        $params = [
148
+            'server' => [
149
+                'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
150
+                'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
151
+            ],
152
+        ];
153
+        $fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig(self::$config)));
154
+        $scriptName = $fakeRequest->getScriptName();
155
+        if (substr($scriptName, -1) == '/') {
156
+            $scriptName .= 'index.php';
157
+            //make sure suburi follows the same rules as scriptName
158
+            if (substr(OC::$SUBURI, -9) != 'index.php') {
159
+                if (substr(OC::$SUBURI, -1) != '/') {
160
+                    OC::$SUBURI = OC::$SUBURI . '/';
161
+                }
162
+                OC::$SUBURI = OC::$SUBURI . 'index.php';
163
+            }
164
+        }
165
+
166
+
167
+        if (OC::$CLI) {
168
+            OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
169
+        } else {
170
+            if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
171
+                OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
172
+
173
+                if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
174
+                    OC::$WEBROOT = '/' . OC::$WEBROOT;
175
+                }
176
+            } else {
177
+                // The scriptName is not ending with OC::$SUBURI
178
+                // This most likely means that we are calling from CLI.
179
+                // However some cron jobs still need to generate
180
+                // a web URL, so we use overwritewebroot as a fallback.
181
+                OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
182
+            }
183
+
184
+            // Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
185
+            // slash which is required by URL generation.
186
+            if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
187
+                    substr($_SERVER['REQUEST_URI'], -1) !== '/') {
188
+                header('Location: '.\OC::$WEBROOT.'/');
189
+                exit();
190
+            }
191
+        }
192
+
193
+        // search the apps folder
194
+        $config_paths = self::$config->getValue('apps_paths', array());
195
+        if (!empty($config_paths)) {
196
+            foreach ($config_paths as $paths) {
197
+                if (isset($paths['url']) && isset($paths['path'])) {
198
+                    $paths['url'] = rtrim($paths['url'], '/');
199
+                    $paths['path'] = rtrim($paths['path'], '/');
200
+                    OC::$APPSROOTS[] = $paths;
201
+                }
202
+            }
203
+        } elseif (file_exists(OC::$SERVERROOT . '/apps')) {
204
+            OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
205
+        } elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
206
+            OC::$APPSROOTS[] = array(
207
+                'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
208
+                'url' => '/apps',
209
+                'writable' => true
210
+            );
211
+        }
212
+
213
+        if (empty(OC::$APPSROOTS)) {
214
+            throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
215
+                . ' or the folder above. You can also configure the location in the config.php file.');
216
+        }
217
+        $paths = array();
218
+        foreach (OC::$APPSROOTS as $path) {
219
+            $paths[] = $path['path'];
220
+            if (!is_dir($path['path'])) {
221
+                throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
222
+                    . ' Nextcloud folder or the folder above. You can also configure the location in the'
223
+                    . ' config.php file.', $path['path']));
224
+            }
225
+        }
226
+
227
+        // set the right include path
228
+        set_include_path(
229
+            implode(PATH_SEPARATOR, $paths)
230
+        );
231
+    }
232
+
233
+    public static function checkConfig() {
234
+        $l = \OC::$server->getL10N('lib');
235
+
236
+        // Create config if it does not already exist
237
+        $configFilePath = self::$configDir .'/config.php';
238
+        if(!file_exists($configFilePath)) {
239
+            @touch($configFilePath);
240
+        }
241
+
242
+        // Check if config is writable
243
+        $configFileWritable = is_writable($configFilePath);
244
+        if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
245
+            || !$configFileWritable && \OCP\Util::needUpgrade()) {
246
+
247
+            $urlGenerator = \OC::$server->getURLGenerator();
248
+
249
+            if (self::$CLI) {
250
+                echo $l->t('Cannot write into "config" directory!')."\n";
251
+                echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
252
+                echo "\n";
253
+                echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-dir_permissions') ])."\n";
254
+                exit;
255
+            } else {
256
+                OC_Template::printErrorPage(
257
+                    $l->t('Cannot write into "config" directory!'),
258
+                    $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
259
+                        [ $urlGenerator->linkToDocs('admin-dir_permissions') ])
260
+                );
261
+            }
262
+        }
263
+    }
264
+
265
+    public static function checkInstalled() {
266
+        if (defined('OC_CONSOLE')) {
267
+            return;
268
+        }
269
+        // Redirect to installer if not installed
270
+        if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
271
+            if (OC::$CLI) {
272
+                throw new Exception('Not installed');
273
+            } else {
274
+                $url = OC::$WEBROOT . '/index.php';
275
+                header('Location: ' . $url);
276
+            }
277
+            exit();
278
+        }
279
+    }
280
+
281
+    public static function checkMaintenanceMode() {
282
+        // Allow ajax update script to execute without being stopped
283
+        if (\OC::$server->getSystemConfig()->getValue('maintenance', false) && OC::$SUBURI != '/core/ajax/update.php') {
284
+            // send http status 503
285
+            header('HTTP/1.1 503 Service Temporarily Unavailable');
286
+            header('Status: 503 Service Temporarily Unavailable');
287
+            header('Retry-After: 120');
288
+
289
+            // render error page
290
+            $template = new OC_Template('', 'update.user', 'guest');
291
+            OC_Util::addScript('maintenance-check');
292
+            OC_Util::addStyle('core', 'guest');
293
+            $template->printPage();
294
+            die();
295
+        }
296
+    }
297
+
298
+    /**
299
+     * Prints the upgrade page
300
+     *
301
+     * @param \OC\SystemConfig $systemConfig
302
+     */
303
+    private static function printUpgradePage(\OC\SystemConfig $systemConfig) {
304
+        $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
305
+        $tooBig = false;
306
+        if (!$disableWebUpdater) {
307
+            $apps = \OC::$server->getAppManager();
308
+            if ($apps->isInstalled('user_ldap')) {
309
+                $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
310
+
311
+                $result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
312
+                    ->from('ldap_user_mapping')
313
+                    ->execute();
314
+                $row = $result->fetch();
315
+                $result->closeCursor();
316
+
317
+                $tooBig = ($row['user_count'] > 50);
318
+            }
319
+            if (!$tooBig && $apps->isInstalled('user_saml')) {
320
+                $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
321
+
322
+                $result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
323
+                    ->from('user_saml_users')
324
+                    ->execute();
325
+                $row = $result->fetch();
326
+                $result->closeCursor();
327
+
328
+                $tooBig = ($row['user_count'] > 50);
329
+            }
330
+            if (!$tooBig) {
331
+                // count users
332
+                $stats = \OC::$server->getUserManager()->countUsers();
333
+                $totalUsers = array_sum($stats);
334
+                $tooBig = ($totalUsers > 50);
335
+            }
336
+        }
337
+        $ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
338
+            $_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
339
+
340
+        if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
341
+            // send http status 503
342
+            header('HTTP/1.1 503 Service Temporarily Unavailable');
343
+            header('Status: 503 Service Temporarily Unavailable');
344
+            header('Retry-After: 120');
345
+
346
+            // render error page
347
+            $template = new OC_Template('', 'update.use-cli', 'guest');
348
+            $template->assign('productName', 'nextcloud'); // for now
349
+            $template->assign('version', OC_Util::getVersionString());
350
+            $template->assign('tooBig', $tooBig);
351
+
352
+            $template->printPage();
353
+            die();
354
+        }
355
+
356
+        // check whether this is a core update or apps update
357
+        $installedVersion = $systemConfig->getValue('version', '0.0.0');
358
+        $currentVersion = implode('.', \OCP\Util::getVersion());
359
+
360
+        // if not a core upgrade, then it's apps upgrade
361
+        $isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '=');
362
+
363
+        $oldTheme = $systemConfig->getValue('theme');
364
+        $systemConfig->setValue('theme', '');
365
+        OC_Util::addScript('config'); // needed for web root
366
+        OC_Util::addScript('update');
367
+
368
+        /** @var \OC\App\AppManager $appManager */
369
+        $appManager = \OC::$server->getAppManager();
370
+
371
+        $tmpl = new OC_Template('', 'update.admin', 'guest');
372
+        $tmpl->assign('version', OC_Util::getVersionString());
373
+        $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
374
+
375
+        // get third party apps
376
+        $ocVersion = \OCP\Util::getVersion();
377
+        $ocVersion = implode('.', $ocVersion);
378
+        $incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
379
+        $incompatibleShippedApps = [];
380
+        foreach ($incompatibleApps as $appInfo) {
381
+            if ($appManager->isShipped($appInfo['id'])) {
382
+                $incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
383
+            }
384
+        }
385
+
386
+        if (!empty($incompatibleShippedApps)) {
387
+            $l = \OC::$server->getL10N('core');
388
+            $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)]);
389
+            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);
390
+        }
391
+
392
+        $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
393
+        $tmpl->assign('incompatibleAppsList', $incompatibleApps);
394
+        $tmpl->assign('productName', 'Nextcloud'); // for now
395
+        $tmpl->assign('oldTheme', $oldTheme);
396
+        $tmpl->printPage();
397
+    }
398
+
399
+    public static function initSession() {
400
+        if(self::$server->getRequest()->getServerProtocol() === 'https') {
401
+            ini_set('session.cookie_secure', true);
402
+        }
403
+
404
+        // prevents javascript from accessing php session cookies
405
+        ini_set('session.cookie_httponly', 'true');
406
+
407
+        // set the cookie path to the Nextcloud directory
408
+        $cookie_path = OC::$WEBROOT ? : '/';
409
+        ini_set('session.cookie_path', $cookie_path);
410
+
411
+        // Let the session name be changed in the initSession Hook
412
+        $sessionName = OC_Util::getInstanceId();
413
+
414
+        try {
415
+            // Allow session apps to create a custom session object
416
+            $useCustomSession = false;
417
+            $session = self::$server->getSession();
418
+            OC_Hook::emit('OC', 'initSession', array('session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession));
419
+            if (!$useCustomSession) {
420
+                // set the session name to the instance id - which is unique
421
+                $session = new \OC\Session\Internal($sessionName);
422
+            }
423
+
424
+            $cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
425
+            $session = $cryptoWrapper->wrapSession($session);
426
+            self::$server->setSession($session);
427
+
428
+            // if session can't be started break with http 500 error
429
+        } catch (Exception $e) {
430
+            \OC::$server->getLogger()->logException($e, ['app' => 'base']);
431
+            //show the user a detailed error page
432
+            OC_Response::setStatus(OC_Response::STATUS_INTERNAL_SERVER_ERROR);
433
+            OC_Template::printExceptionErrorPage($e);
434
+            die();
435
+        }
436
+
437
+        $sessionLifeTime = self::getSessionLifeTime();
438
+
439
+        // session timeout
440
+        if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
441
+            if (isset($_COOKIE[session_name()])) {
442
+                setcookie(session_name(), null, -1, self::$WEBROOT ? : '/');
443
+            }
444
+            \OC::$server->getUserSession()->logout();
445
+        }
446
+
447
+        $session->set('LAST_ACTIVITY', time());
448
+    }
449
+
450
+    /**
451
+     * @return string
452
+     */
453
+    private static function getSessionLifeTime() {
454
+        return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
455
+    }
456
+
457
+    public static function loadAppClassPaths() {
458
+        foreach (OC_App::getEnabledApps() as $app) {
459
+            $appPath = OC_App::getAppPath($app);
460
+            if ($appPath === false) {
461
+                continue;
462
+            }
463
+
464
+            $file = $appPath . '/appinfo/classpath.php';
465
+            if (file_exists($file)) {
466
+                require_once $file;
467
+            }
468
+        }
469
+    }
470
+
471
+    /**
472
+     * Try to set some values to the required Nextcloud default
473
+     */
474
+    public static function setRequiredIniValues() {
475
+        @ini_set('default_charset', 'UTF-8');
476
+        @ini_set('gd.jpeg_ignore_warning', '1');
477
+    }
478
+
479
+    /**
480
+     * Send the same site cookies
481
+     */
482
+    private static function sendSameSiteCookies() {
483
+        $cookieParams = session_get_cookie_params();
484
+        $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
485
+        $policies = [
486
+            'lax',
487
+            'strict',
488
+        ];
489
+
490
+        // Append __Host to the cookie if it meets the requirements
491
+        $cookiePrefix = '';
492
+        if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
493
+            $cookiePrefix = '__Host-';
494
+        }
495
+
496
+        foreach($policies as $policy) {
497
+            header(
498
+                sprintf(
499
+                    'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
500
+                    $cookiePrefix,
501
+                    $policy,
502
+                    $cookieParams['path'],
503
+                    $policy
504
+                ),
505
+                false
506
+            );
507
+        }
508
+    }
509
+
510
+    /**
511
+     * Same Site cookie to further mitigate CSRF attacks. This cookie has to
512
+     * be set in every request if cookies are sent to add a second level of
513
+     * defense against CSRF.
514
+     *
515
+     * If the cookie is not sent this will set the cookie and reload the page.
516
+     * We use an additional cookie since we want to protect logout CSRF and
517
+     * also we can't directly interfere with PHP's session mechanism.
518
+     */
519
+    private static function performSameSiteCookieProtection() {
520
+        $request = \OC::$server->getRequest();
521
+
522
+        // Some user agents are notorious and don't really properly follow HTTP
523
+        // specifications. For those, have an automated opt-out. Since the protection
524
+        // for remote.php is applied in base.php as starting point we need to opt out
525
+        // here.
526
+        $incompatibleUserAgents = \OC::$server->getConfig()->getSystemValue('csrf.optout');
527
+
528
+        // Fallback, if csrf.optout is unset
529
+        if (!is_array($incompatibleUserAgents)) {
530
+            $incompatibleUserAgents = [
531
+                // OS X Finder
532
+                '/^WebDAVFS/',
533
+                // Windows webdav drive
534
+                '/^Microsoft-WebDAV-MiniRedir/',
535
+            ];
536
+        }
537
+
538
+        if($request->isUserAgent($incompatibleUserAgents)) {
539
+            return;
540
+        }
541
+
542
+        if(count($_COOKIE) > 0) {
543
+            $requestUri = $request->getScriptName();
544
+            $processingScript = explode('/', $requestUri);
545
+            $processingScript = $processingScript[count($processingScript)-1];
546
+
547
+            // index.php routes are handled in the middleware
548
+            if($processingScript === 'index.php') {
549
+                return;
550
+            }
551
+
552
+            // All other endpoints require the lax and the strict cookie
553
+            if(!$request->passesStrictCookieCheck()) {
554
+                self::sendSameSiteCookies();
555
+                // Debug mode gets access to the resources without strict cookie
556
+                // due to the fact that the SabreDAV browser also lives there.
557
+                if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
558
+                    http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
559
+                    exit();
560
+                }
561
+            }
562
+        } elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
563
+            self::sendSameSiteCookies();
564
+        }
565
+    }
566
+
567
+    public static function init() {
568
+        // calculate the root directories
569
+        OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
570
+
571
+        // register autoloader
572
+        $loaderStart = microtime(true);
573
+        require_once __DIR__ . '/autoloader.php';
574
+        self::$loader = new \OC\Autoloader([
575
+            OC::$SERVERROOT . '/lib/private/legacy',
576
+        ]);
577
+        if (defined('PHPUNIT_RUN')) {
578
+            self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
579
+        }
580
+        spl_autoload_register(array(self::$loader, 'load'));
581
+        $loaderEnd = microtime(true);
582
+
583
+        self::$CLI = (php_sapi_name() == 'cli');
584
+
585
+        // Add default composer PSR-4 autoloader
586
+        self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
587
+
588
+        try {
589
+            self::initPaths();
590
+            // setup 3rdparty autoloader
591
+            $vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
592
+            if (!file_exists($vendorAutoLoad)) {
593
+                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".');
594
+            }
595
+            require_once $vendorAutoLoad;
596
+
597
+        } catch (\RuntimeException $e) {
598
+            if (!self::$CLI) {
599
+                $claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']);
600
+                $protocol = in_array($claimedProtocol, ['HTTP/1.0', 'HTTP/1.1', 'HTTP/2']) ? $claimedProtocol : 'HTTP/1.1';
601
+                header($protocol . ' ' . OC_Response::STATUS_SERVICE_UNAVAILABLE);
602
+            }
603
+            // we can't use the template error page here, because this needs the
604
+            // DI container which isn't available yet
605
+            print($e->getMessage());
606
+            exit();
607
+        }
608
+
609
+        // setup the basic server
610
+        self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
611
+        \OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
612
+        \OC::$server->getEventLogger()->start('boot', 'Initialize');
613
+
614
+        // Don't display errors and log them
615
+        error_reporting(E_ALL | E_STRICT);
616
+        @ini_set('display_errors', '0');
617
+        @ini_set('log_errors', '1');
618
+
619
+        if(!date_default_timezone_set('UTC')) {
620
+            throw new \RuntimeException('Could not set timezone to UTC');
621
+        }
622
+
623
+        //try to configure php to enable big file uploads.
624
+        //this doesn´t work always depending on the webserver and php configuration.
625
+        //Let´s try to overwrite some defaults anyway
626
+
627
+        //try to set the maximum execution time to 60min
628
+        if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
629
+            @set_time_limit(3600);
630
+        }
631
+        @ini_set('max_execution_time', '3600');
632
+        @ini_set('max_input_time', '3600');
633
+
634
+        //try to set the maximum filesize to 10G
635
+        @ini_set('upload_max_filesize', '10G');
636
+        @ini_set('post_max_size', '10G');
637
+        @ini_set('file_uploads', '50');
638
+
639
+        self::setRequiredIniValues();
640
+        self::handleAuthHeaders();
641
+        self::registerAutoloaderCache();
642
+
643
+        // initialize intl fallback is necessary
644
+        \Patchwork\Utf8\Bootup::initIntl();
645
+        OC_Util::isSetLocaleWorking();
646
+
647
+        if (!defined('PHPUNIT_RUN')) {
648
+            OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
649
+            $debug = \OC::$server->getConfig()->getSystemValue('debug', false);
650
+            OC\Log\ErrorHandler::register($debug);
651
+        }
652
+
653
+        \OC::$server->getEventLogger()->start('init_session', 'Initialize session');
654
+        OC_App::loadApps(array('session'));
655
+        if (!self::$CLI) {
656
+            self::initSession();
657
+        }
658
+        \OC::$server->getEventLogger()->end('init_session');
659
+        self::checkConfig();
660
+        self::checkInstalled();
661
+
662
+        OC_Response::addSecurityHeaders();
663
+
664
+        self::performSameSiteCookieProtection();
665
+
666
+        if (!defined('OC_CONSOLE')) {
667
+            $errors = OC_Util::checkServer(\OC::$server->getSystemConfig());
668
+            if (count($errors) > 0) {
669
+                if (self::$CLI) {
670
+                    // Convert l10n string into regular string for usage in database
671
+                    $staticErrors = [];
672
+                    foreach ($errors as $error) {
673
+                        echo $error['error'] . "\n";
674
+                        echo $error['hint'] . "\n\n";
675
+                        $staticErrors[] = [
676
+                            'error' => (string)$error['error'],
677
+                            'hint' => (string)$error['hint'],
678
+                        ];
679
+                    }
680
+
681
+                    try {
682
+                        \OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
683
+                    } catch (\Exception $e) {
684
+                        echo('Writing to database failed');
685
+                    }
686
+                    exit(1);
687
+                } else {
688
+                    OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE);
689
+                    OC_Util::addStyle('guest');
690
+                    OC_Template::printGuestPage('', 'error', array('errors' => $errors));
691
+                    exit;
692
+                }
693
+            } elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
694
+                \OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
695
+            }
696
+        }
697
+        //try to set the session lifetime
698
+        $sessionLifeTime = self::getSessionLifeTime();
699
+        @ini_set('gc_maxlifetime', (string)$sessionLifeTime);
700
+
701
+        $systemConfig = \OC::$server->getSystemConfig();
702
+
703
+        // User and Groups
704
+        if (!$systemConfig->getValue("installed", false)) {
705
+            self::$server->getSession()->set('user_id', '');
706
+        }
707
+
708
+        OC_User::useBackend(new \OC\User\Database());
709
+        \OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
710
+
711
+        // Subscribe to the hook
712
+        \OCP\Util::connectHook(
713
+            '\OCA\Files_Sharing\API\Server2Server',
714
+            'preLoginNameUsedAsUserName',
715
+            '\OC\User\Database',
716
+            'preLoginNameUsedAsUserName'
717
+        );
718
+
719
+        //setup extra user backends
720
+        if (!\OCP\Util::needUpgrade()) {
721
+            OC_User::setupBackends();
722
+        } else {
723
+            // Run upgrades in incognito mode
724
+            OC_User::setIncognitoMode(true);
725
+        }
726
+
727
+        self::registerCleanupHooks();
728
+        self::registerFilesystemHooks();
729
+        self::registerShareHooks();
730
+        self::registerEncryptionWrapper();
731
+        self::registerEncryptionHooks();
732
+        self::registerAccountHooks();
733
+
734
+        // Make sure that the application class is not loaded before the database is setup
735
+        if ($systemConfig->getValue("installed", false)) {
736
+            $settings = new \OC\Settings\Application();
737
+            $settings->register();
738
+        }
739
+
740
+        //make sure temporary files are cleaned up
741
+        $tmpManager = \OC::$server->getTempManager();
742
+        register_shutdown_function(array($tmpManager, 'clean'));
743
+        $lockProvider = \OC::$server->getLockingProvider();
744
+        register_shutdown_function(array($lockProvider, 'releaseAll'));
745
+
746
+        // Check whether the sample configuration has been copied
747
+        if($systemConfig->getValue('copied_sample_config', false)) {
748
+            $l = \OC::$server->getL10N('lib');
749
+            header('HTTP/1.1 503 Service Temporarily Unavailable');
750
+            header('Status: 503 Service Temporarily Unavailable');
751
+            OC_Template::printErrorPage(
752
+                $l->t('Sample configuration detected'),
753
+                $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')
754
+            );
755
+            return;
756
+        }
757
+
758
+        $request = \OC::$server->getRequest();
759
+        $host = $request->getInsecureServerHost();
760
+        /**
761
+         * if the host passed in headers isn't trusted
762
+         * FIXME: Should not be in here at all :see_no_evil:
763
+         */
764
+        if (!OC::$CLI
765
+            // overwritehost is always trusted, workaround to not have to make
766
+            // \OC\AppFramework\Http\Request::getOverwriteHost public
767
+            && self::$server->getConfig()->getSystemValue('overwritehost') === ''
768
+            && !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
769
+            && self::$server->getConfig()->getSystemValue('installed', false)
770
+        ) {
771
+            // Allow access to CSS resources
772
+            $isScssRequest = false;
773
+            if(strpos($request->getPathInfo(), '/css/') === 0) {
774
+                $isScssRequest = true;
775
+            }
776
+
777
+            if(substr($request->getRequestUri(), -11) === '/status.php') {
778
+                OC_Response::setStatus(\OC_Response::STATUS_BAD_REQUEST);
779
+                header('Status: 400 Bad Request');
780
+                header('Content-Type: application/json');
781
+                echo '{"error": "Trusted domain error.", "code": 15}';
782
+                exit();
783
+            }
784
+
785
+            if (!$isScssRequest) {
786
+                OC_Response::setStatus(\OC_Response::STATUS_BAD_REQUEST);
787
+                header('Status: 400 Bad Request');
788
+
789
+                \OC::$server->getLogger()->info(
790
+                    'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
791
+                    [
792
+                        'app' => 'core',
793
+                        'remoteAddress' => $request->getRemoteAddress(),
794
+                        'host' => $host,
795
+                    ]
796
+                );
797
+
798
+                $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
799
+                $tmpl->assign('docUrl', \OC::$server->getURLGenerator()->linkToDocs('admin-trusted-domains'));
800
+                $tmpl->printPage();
801
+
802
+                exit();
803
+            }
804
+        }
805
+        \OC::$server->getEventLogger()->end('boot');
806
+    }
807
+
808
+    /**
809
+     * register hooks for the cleanup of cache and bruteforce protection
810
+     */
811
+    public static function registerCleanupHooks() {
812
+        //don't try to do this before we are properly setup
813
+        if (\OC::$server->getSystemConfig()->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
814
+
815
+            // NOTE: This will be replaced to use OCP
816
+            $userSession = self::$server->getUserSession();
817
+            $userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
818
+                if (!defined('PHPUNIT_RUN')) {
819
+                    // reset brute force delay for this IP address and username
820
+                    $uid = \OC::$server->getUserSession()->getUser()->getUID();
821
+                    $request = \OC::$server->getRequest();
822
+                    $throttler = \OC::$server->getBruteForceThrottler();
823
+                    $throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
824
+                }
825
+
826
+                try {
827
+                    $cache = new \OC\Cache\File();
828
+                    $cache->gc();
829
+                } catch (\OC\ServerNotAvailableException $e) {
830
+                    // not a GC exception, pass it on
831
+                    throw $e;
832
+                } catch (\OC\ForbiddenException $e) {
833
+                    // filesystem blocked for this request, ignore
834
+                } catch (\Exception $e) {
835
+                    // a GC exception should not prevent users from using OC,
836
+                    // so log the exception
837
+                    \OC::$server->getLogger()->logException($e, [
838
+                        'message' => 'Exception when running cache gc.',
839
+                        'level' => ILogger::WARN,
840
+                        'app' => 'core',
841
+                    ]);
842
+                }
843
+            });
844
+        }
845
+    }
846
+
847
+    private static function registerEncryptionWrapper() {
848
+        $manager = self::$server->getEncryptionManager();
849
+        \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
850
+    }
851
+
852
+    private static function registerEncryptionHooks() {
853
+        $enabled = self::$server->getEncryptionManager()->isEnabled();
854
+        if ($enabled) {
855
+            \OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared');
856
+            \OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared');
857
+            \OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename');
858
+            \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore');
859
+        }
860
+    }
861
+
862
+    private static function registerAccountHooks() {
863
+        $hookHandler = new \OC\Accounts\Hooks(\OC::$server->getLogger());
864
+        \OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
865
+    }
866
+
867
+    /**
868
+     * register hooks for the filesystem
869
+     */
870
+    public static function registerFilesystemHooks() {
871
+        // Check for blacklisted files
872
+        OC_Hook::connect('OC_Filesystem', 'write', Filesystem::class, 'isBlacklisted');
873
+        OC_Hook::connect('OC_Filesystem', 'rename', Filesystem::class, 'isBlacklisted');
874
+    }
875
+
876
+    /**
877
+     * register hooks for sharing
878
+     */
879
+    public static function registerShareHooks() {
880
+        if (\OC::$server->getSystemConfig()->getValue('installed')) {
881
+            OC_Hook::connect('OC_User', 'post_deleteUser', Hooks::class, 'post_deleteUser');
882
+            OC_Hook::connect('OC_User', 'post_removeFromGroup', Hooks::class, 'post_removeFromGroup');
883
+            OC_Hook::connect('OC_User', 'post_deleteGroup', Hooks::class, 'post_deleteGroup');
884
+        }
885
+    }
886
+
887
+    protected static function registerAutoloaderCache() {
888
+        // The class loader takes an optional low-latency cache, which MUST be
889
+        // namespaced. The instanceid is used for namespacing, but might be
890
+        // unavailable at this point. Furthermore, it might not be possible to
891
+        // generate an instanceid via \OC_Util::getInstanceId() because the
892
+        // config file may not be writable. As such, we only register a class
893
+        // loader cache if instanceid is available without trying to create one.
894
+        $instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
895
+        if ($instanceId) {
896
+            try {
897
+                $memcacheFactory = \OC::$server->getMemCacheFactory();
898
+                self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
899
+            } catch (\Exception $ex) {
900
+            }
901
+
902
+            self::$composerAutoloader->setApcuPrefix($instanceId . '-mainComposer');
903
+        }
904
+    }
905
+
906
+    /**
907
+     * Handle the request
908
+     */
909
+    public static function handleRequest() {
910
+
911
+        \OC::$server->getEventLogger()->start('handle_request', 'Handle request');
912
+        $systemConfig = \OC::$server->getSystemConfig();
913
+        // load all the classpaths from the enabled apps so they are available
914
+        // in the routing files of each app
915
+        OC::loadAppClassPaths();
916
+
917
+        // Check if Nextcloud is installed or in maintenance (update) mode
918
+        if (!$systemConfig->getValue('installed', false)) {
919
+            \OC::$server->getSession()->clear();
920
+            $setupHelper = new OC\Setup(
921
+                $systemConfig,
922
+                \OC::$server->getIniWrapper(),
923
+                \OC::$server->getL10N('lib'),
924
+                \OC::$server->query(\OCP\Defaults::class),
925
+                \OC::$server->getLogger(),
926
+                \OC::$server->getSecureRandom(),
927
+                \OC::$server->query(\OC\Installer::class)
928
+            );
929
+            $controller = new OC\Core\Controller\SetupController($setupHelper);
930
+            $controller->run($_POST);
931
+            exit();
932
+        }
933
+
934
+        $request = \OC::$server->getRequest();
935
+        $requestPath = $request->getRawPathInfo();
936
+        if ($requestPath === '/heartbeat') {
937
+            return;
938
+        }
939
+        if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
940
+            self::checkMaintenanceMode();
941
+
942
+            if (\OCP\Util::needUpgrade()) {
943
+                if (function_exists('opcache_reset')) {
944
+                    opcache_reset();
945
+                }
946
+                if (!$systemConfig->getValue('maintenance', false)) {
947
+                    self::printUpgradePage($systemConfig);
948
+                    exit();
949
+                }
950
+            }
951
+        }
952
+
953
+        // emergency app disabling
954
+        if ($requestPath === '/disableapp'
955
+            && $request->getMethod() === 'POST'
956
+            && ((array)$request->getParam('appid')) !== ''
957
+        ) {
958
+            \OC_JSON::callCheck();
959
+            \OC_JSON::checkAdminUser();
960
+            $appIds = (array)$request->getParam('appid');
961
+            foreach($appIds as $appId) {
962
+                $appId = \OC_App::cleanAppId($appId);
963
+                \OC::$server->getAppManager()->disableApp($appId);
964
+            }
965
+            \OC_JSON::success();
966
+            exit();
967
+        }
968
+
969
+        // Always load authentication apps
970
+        OC_App::loadApps(['authentication']);
971
+
972
+        // Load minimum set of apps
973
+        if (!\OCP\Util::needUpgrade()
974
+            && !$systemConfig->getValue('maintenance', false)) {
975
+            // For logged-in users: Load everything
976
+            if(\OC::$server->getUserSession()->isLoggedIn()) {
977
+                OC_App::loadApps();
978
+            } else {
979
+                // For guests: Load only filesystem and logging
980
+                OC_App::loadApps(array('filesystem', 'logging'));
981
+                self::handleLogin($request);
982
+            }
983
+        }
984
+
985
+        if (!self::$CLI) {
986
+            try {
987
+                if (!$systemConfig->getValue('maintenance', false) && !\OCP\Util::needUpgrade()) {
988
+                    OC_App::loadApps(array('filesystem', 'logging'));
989
+                    OC_App::loadApps();
990
+                }
991
+                OC_Util::setupFS();
992
+                OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
993
+                return;
994
+            } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
995
+                //header('HTTP/1.0 404 Not Found');
996
+            } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
997
+                OC_Response::setStatus(405);
998
+                return;
999
+            }
1000
+        }
1001
+
1002
+        // Handle WebDAV
1003
+        if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
1004
+            // not allowed any more to prevent people
1005
+            // mounting this root directly.
1006
+            // Users need to mount remote.php/webdav instead.
1007
+            header('HTTP/1.1 405 Method Not Allowed');
1008
+            header('Status: 405 Method Not Allowed');
1009
+            return;
1010
+        }
1011
+
1012
+        // Someone is logged in
1013
+        if (\OC::$server->getUserSession()->isLoggedIn()) {
1014
+            OC_App::loadApps();
1015
+            OC_User::setupBackends();
1016
+            OC_Util::setupFS();
1017
+            // FIXME
1018
+            // Redirect to default application
1019
+            OC_Util::redirectToDefaultPage();
1020
+        } else {
1021
+            // Not handled and not logged in
1022
+            header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1023
+        }
1024
+    }
1025
+
1026
+    /**
1027
+     * Check login: apache auth, auth token, basic auth
1028
+     *
1029
+     * @param OCP\IRequest $request
1030
+     * @return boolean
1031
+     */
1032
+    static function handleLogin(OCP\IRequest $request) {
1033
+        $userSession = self::$server->getUserSession();
1034
+        if (OC_User::handleApacheAuth()) {
1035
+            return true;
1036
+        }
1037
+        if ($userSession->tryTokenLogin($request)) {
1038
+            return true;
1039
+        }
1040
+        if (isset($_COOKIE['nc_username'])
1041
+            && isset($_COOKIE['nc_token'])
1042
+            && isset($_COOKIE['nc_session_id'])
1043
+            && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1044
+            return true;
1045
+        }
1046
+        if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1047
+            return true;
1048
+        }
1049
+        return false;
1050
+    }
1051
+
1052
+    protected static function handleAuthHeaders() {
1053
+        //copy http auth headers for apache+php-fcgid work around
1054
+        if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1055
+            $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1056
+        }
1057
+
1058
+        // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1059
+        $vars = array(
1060
+            'HTTP_AUTHORIZATION', // apache+php-cgi work around
1061
+            'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1062
+        );
1063
+        foreach ($vars as $var) {
1064
+            if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1065
+                list($name, $password) = explode(':', base64_decode($matches[1]), 2);
1066
+                $_SERVER['PHP_AUTH_USER'] = $name;
1067
+                $_SERVER['PHP_AUTH_PW'] = $password;
1068
+                break;
1069
+            }
1070
+        }
1071
+    }
1072 1072
 }
1073 1073
 
1074 1074
 OC::init();
Please login to merge, or discard this patch.
config/config.sample.php 1 patch
Indentation   +133 added lines, -133 removed lines patch added patch discarded remove patch
@@ -41,17 +41,17 @@  discard block
 block discarded – undo
41 41
  */
42 42
 'instanceid' => '',
43 43
 
44
- /**
45
-  * The salt used to hash all passwords, auto-generated by the Nextcloud
46
-  * installer. (There are also per-user salts.) If you lose this salt you lose
47
-  * all your passwords. This example is for documentation only, and you should
48
-  * never use it.
49
-  *
50
-  * @deprecated This salt is deprecated and only used for legacy-compatibility,
51
-  * developers should *NOT* use this value for anything nowadays.
52
-  *
53
-  * 'passwordsalt' => 'd3c944a9af095aa08f',
54
- */
44
+    /**
45
+     * The salt used to hash all passwords, auto-generated by the Nextcloud
46
+     * installer. (There are also per-user salts.) If you lose this salt you lose
47
+     * all your passwords. This example is for documentation only, and you should
48
+     * never use it.
49
+     *
50
+     * @deprecated This salt is deprecated and only used for legacy-compatibility,
51
+     * developers should *NOT* use this value for anything nowadays.
52
+     *
53
+     * 'passwordsalt' => 'd3c944a9af095aa08f',
54
+     */
55 55
 'passwordsalt' => '',
56 56
 
57 57
 /**
@@ -67,10 +67,10 @@  discard block
 block discarded – undo
67 67
  *   ubos-raspberry-pi.local and ubos-raspberry-pi-2.local
68 68
  */
69 69
 'trusted_domains' =>
70
-  array (
70
+    array (
71 71
     'demo.example.org',
72 72
     'otherdomain.example.org',
73
-  ),
73
+    ),
74 74
 
75 75
 
76 76
 /**
@@ -260,10 +260,10 @@  discard block
 block discarded – undo
260 260
  * IMAP (OC_User_IMAP), SMB (OC_User_SMB), and FTP (OC_User_FTP).
261 261
  */
262 262
 'user_backends' => array(
263
-	array(
264
-		'class' => 'OC_User_IMAP',
265
-		'arguments' => array('{imap.gmail.com:993/imap/ssl}INBOX')
266
-	)
263
+    array(
264
+        'class' => 'OC_User_IMAP',
265
+        'arguments' => array('{imap.gmail.com:993/imap/ssl}INBOX')
266
+    )
267 267
 ),
268 268
 
269 269
 /**
@@ -736,9 +736,9 @@  discard block
 block discarded – undo
736 736
  * Defaults to an empty array.
737 737
  */
738 738
 'log.condition' => [
739
-	'shared_secret' => '57b58edb6637fe3059b3595cf9c41b9',
740
-	'users' => ['sample-user'],
741
-	'apps' => ['files'],
739
+    'shared_secret' => '57b58edb6637fe3059b3595cf9c41b9',
740
+    'users' => ['sample-user'],
741
+    'apps' => ['files'],
742 742
 ],
743 743
 
744 744
 /**
@@ -792,18 +792,18 @@  discard block
 block discarded – undo
792 792
  *  *iOS client app id: ``1125420102``
793 793
  */
794 794
 'customclient_desktop' =>
795
-	'https://nextcloud.com/install/#install-clients',
795
+    'https://nextcloud.com/install/#install-clients',
796 796
 'customclient_android' =>
797
-	'https://play.google.com/store/apps/details?id=com.nextcloud.client',
797
+    'https://play.google.com/store/apps/details?id=com.nextcloud.client',
798 798
 'customclient_ios' =>
799
-	'https://itunes.apple.com/us/app/nextcloud/id1125420102?mt=8',
799
+    'https://itunes.apple.com/us/app/nextcloud/id1125420102?mt=8',
800 800
 'customclient_ios_appid' =>
801
-		'1125420102',
801
+        '1125420102',
802 802
 /**
803
- * Apps
804
- *
805
- * Options for the Apps folder, Apps store, and App code checker.
806
- */
803
+         * Apps
804
+         *
805
+         * Options for the Apps folder, Apps store, and App code checker.
806
+         */
807 807
 
808 808
 /**
809 809
  * When enabled, admins may install apps from the Nextcloud app store.
@@ -821,11 +821,11 @@  discard block
 block discarded – undo
821 821
  * indicates if a Web server can write files to that folder.
822 822
  */
823 823
 'apps_paths' => array(
824
-	array(
825
-		'path'=> '/var/www/nextcloud/apps',
826
-		'url' => '/apps',
827
-		'writable' => true,
828
-	),
824
+    array(
825
+        'path'=> '/var/www/nextcloud/apps',
826
+        'url' => '/apps',
827
+        'writable' => true,
828
+    ),
829 829
 ),
830 830
 
831 831
 /**
@@ -890,8 +890,8 @@  discard block
 block discarded – undo
890 890
  * Defaults to ``''`` (empty string)
891 891
  */
892 892
 'preview_office_cl_parameters' =>
893
-	' --headless --nologo --nofirststartwizard --invisible --norestore '.
894
-	'--convert-to pdf --outdir ',
893
+    ' --headless --nologo --nofirststartwizard --invisible --norestore '.
894
+    '--convert-to pdf --outdir ',
895 895
 
896 896
 /**
897 897
  * Only register providers that have been explicitly enabled
@@ -934,14 +934,14 @@  discard block
 block discarded – undo
934 934
  *  - OC\Preview\XBitmap
935 935
  */
936 936
 'enabledPreviewProviders' => array(
937
-	'OC\Preview\PNG',
938
-	'OC\Preview\JPEG',
939
-	'OC\Preview\GIF',
940
-	'OC\Preview\BMP',
941
-	'OC\Preview\XBitmap',
942
-	'OC\Preview\MP3',
943
-	'OC\Preview\TXT',
944
-	'OC\Preview\MarkDown'
937
+    'OC\Preview\PNG',
938
+    'OC\Preview\JPEG',
939
+    'OC\Preview\GIF',
940
+    'OC\Preview\BMP',
941
+    'OC\Preview\XBitmap',
942
+    'OC\Preview\MP3',
943
+    'OC\Preview\TXT',
944
+    'OC\Preview\MarkDown'
945 945
 ),
946 946
 
947 947
 /**
@@ -1017,11 +1017,11 @@  discard block
 block discarded – undo
1017 1017
 
1018 1018
 /**
1019 1019
  * Extra SSL options to be used for configuration.
1020
-  *
1020
+ *
1021 1021
  * Defaults to an empty array.
1022 1022
  */
1023 1023
 'openssl' => array(
1024
-	'config' => '/absolute/location/of/openssl.cnf',
1024
+    'config' => '/absolute/location/of/openssl.cnf',
1025 1025
 ),
1026 1026
 
1027 1027
 /**
@@ -1070,11 +1070,11 @@  discard block
 block discarded – undo
1070 1070
  * for more information.
1071 1071
  */
1072 1072
 'redis' => [
1073
-	'host' => 'localhost', // can also be a unix domain socket: '/tmp/redis.sock'
1074
-	'port' => 6379,
1075
-	'timeout' => 0.0,
1076
-	'password' => '', // Optional, if not defined no password will be used.
1077
-	'dbindex' => 0, // Optional, if undefined SELECT will not run and will use Redis Server's default DB Index.
1073
+    'host' => 'localhost', // can also be a unix domain socket: '/tmp/redis.sock'
1074
+    'port' => 6379,
1075
+    'timeout' => 0.0,
1076
+    'password' => '', // Optional, if not defined no password will be used.
1077
+    'dbindex' => 0, // Optional, if undefined SELECT will not run and will use Redis Server's default DB Index.
1078 1078
 ],
1079 1079
 
1080 1080
 /**
@@ -1100,13 +1100,13 @@  discard block
 block discarded – undo
1100 1100
  * See https://redis.io/topics/cluster-spec for details about the Redis cluster
1101 1101
  */
1102 1102
 'redis.cluster' => [
1103
-	'seeds' => [ // provide some/all of the cluster servers to bootstrap discovery, port required
1104
-		'localhost:7000',
1105
-		'localhost:7001'
1106
-	],
1107
-	'timeout' => 0.0,
1108
-	'read_timeout' => 0.0,
1109
-	'failover_mode' => \RedisCluster::FAILOVER_ERROR
1103
+    'seeds' => [ // provide some/all of the cluster servers to bootstrap discovery, port required
1104
+        'localhost:7000',
1105
+        'localhost:7001'
1106
+    ],
1107
+    'timeout' => 0.0,
1108
+    'read_timeout' => 0.0,
1109
+    'failover_mode' => \RedisCluster::FAILOVER_ERROR
1110 1110
 ],
1111 1111
 
1112 1112
 
@@ -1114,35 +1114,35 @@  discard block
 block discarded – undo
1114 1114
  * Server details for one or more memcached servers to use for memory caching.
1115 1115
  */
1116 1116
 'memcached_servers' => array(
1117
-	// hostname, port and optional weight. Also see:
1118
-	// http://www.php.net/manual/en/memcached.addservers.php
1119
-	// http://www.php.net/manual/en/memcached.addserver.php
1120
-	array('localhost', 11211),
1121
-	//array('other.host.local', 11211),
1117
+    // hostname, port and optional weight. Also see:
1118
+    // http://www.php.net/manual/en/memcached.addservers.php
1119
+    // http://www.php.net/manual/en/memcached.addserver.php
1120
+    array('localhost', 11211),
1121
+    //array('other.host.local', 11211),
1122 1122
 ),
1123 1123
 
1124 1124
 /**
1125 1125
  * Connection options for memcached, see http://apprize.info/php/scaling/15.html
1126 1126
  */
1127 1127
 'memcached_options' => array(
1128
-	// Set timeouts to 50ms
1129
-	\Memcached::OPT_CONNECT_TIMEOUT => 50,
1130
-	\Memcached::OPT_RETRY_TIMEOUT =>   50,
1131
-	\Memcached::OPT_SEND_TIMEOUT =>    50,
1132
-	\Memcached::OPT_RECV_TIMEOUT =>    50,
1133
-	\Memcached::OPT_POLL_TIMEOUT =>    50,
1128
+    // Set timeouts to 50ms
1129
+    \Memcached::OPT_CONNECT_TIMEOUT => 50,
1130
+    \Memcached::OPT_RETRY_TIMEOUT =>   50,
1131
+    \Memcached::OPT_SEND_TIMEOUT =>    50,
1132
+    \Memcached::OPT_RECV_TIMEOUT =>    50,
1133
+    \Memcached::OPT_POLL_TIMEOUT =>    50,
1134 1134
 
1135
-	// Enable compression
1136
-	\Memcached::OPT_COMPRESSION =>          true,
1135
+    // Enable compression
1136
+    \Memcached::OPT_COMPRESSION =>          true,
1137 1137
 
1138
-	// Turn on consistent hashing
1139
-	\Memcached::OPT_LIBKETAMA_COMPATIBLE => true,
1138
+    // Turn on consistent hashing
1139
+    \Memcached::OPT_LIBKETAMA_COMPATIBLE => true,
1140 1140
 
1141
-	// Enable Binary Protocol
1142
-	\Memcached::OPT_BINARY_PROTOCOL =>      true,
1141
+    // Enable Binary Protocol
1142
+    \Memcached::OPT_BINARY_PROTOCOL =>      true,
1143 1143
 
1144
-	// Binary serializer vill be enabled if the igbinary PECL module is available
1145
-	//\Memcached::OPT_SERIALIZER => \Memcached::SERIALIZER_IGBINARY,
1144
+    // Binary serializer vill be enabled if the igbinary PECL module is available
1145
+    //\Memcached::OPT_SERIALIZER => \Memcached::SERIALIZER_IGBINARY,
1146 1146
 ),
1147 1147
 
1148 1148
 
@@ -1188,61 +1188,61 @@  discard block
 block discarded – undo
1188 1188
  * One way to test is applying for a trystack account at http://trystack.org/
1189 1189
  */
1190 1190
 'objectstore' => [
1191
-	'class' => 'OC\\Files\\ObjectStore\\Swift',
1192
-	'arguments' => [
1193
-		// trystack will use your facebook id as the user name
1194
-		'username' => 'facebook100000123456789',
1195
-		// in the trystack dashboard go to user -> settings -> API Password to
1196
-		// generate a password
1197
-		'password' => 'Secr3tPaSSWoRdt7',
1198
-		// must already exist in the objectstore, name can be different
1199
-		'container' => 'nextcloud',
1200
-		// prefix to prepend to the fileid, default is 'oid:urn:'
1201
-		'objectPrefix' => 'oid:urn:',
1202
-		// create the container if it does not exist. default is false
1203
-		'autocreate' => true,
1204
-		// required, dev-/trystack defaults to 'RegionOne'
1205
-		'region' => 'RegionOne',
1206
-		// The Identity / Keystone endpoint
1207
-		'url' => 'http://8.21.28.222:5000/v2.0',
1208
-		// required on dev-/trystack
1209
-		'tenantName' => 'facebook100000123456789',
1210
-		// dev-/trystack uses swift by default, the lib defaults to 'cloudFiles'
1211
-		// if omitted
1212
-		'serviceName' => 'swift',
1213
-		// The Interface / url Type, optional
1214
-		'urlType' => 'internal'
1215
-	],
1191
+    'class' => 'OC\\Files\\ObjectStore\\Swift',
1192
+    'arguments' => [
1193
+        // trystack will use your facebook id as the user name
1194
+        'username' => 'facebook100000123456789',
1195
+        // in the trystack dashboard go to user -> settings -> API Password to
1196
+        // generate a password
1197
+        'password' => 'Secr3tPaSSWoRdt7',
1198
+        // must already exist in the objectstore, name can be different
1199
+        'container' => 'nextcloud',
1200
+        // prefix to prepend to the fileid, default is 'oid:urn:'
1201
+        'objectPrefix' => 'oid:urn:',
1202
+        // create the container if it does not exist. default is false
1203
+        'autocreate' => true,
1204
+        // required, dev-/trystack defaults to 'RegionOne'
1205
+        'region' => 'RegionOne',
1206
+        // The Identity / Keystone endpoint
1207
+        'url' => 'http://8.21.28.222:5000/v2.0',
1208
+        // required on dev-/trystack
1209
+        'tenantName' => 'facebook100000123456789',
1210
+        // dev-/trystack uses swift by default, the lib defaults to 'cloudFiles'
1211
+        // if omitted
1212
+        'serviceName' => 'swift',
1213
+        // The Interface / url Type, optional
1214
+        'urlType' => 'internal'
1215
+    ],
1216 1216
 ],
1217 1217
 
1218 1218
 /**
1219 1219
  * To use swift V3
1220 1220
  */
1221 1221
 'objectstore' => [
1222
-	'class' => 'OC\\Files\\ObjectStore\\Swift',
1223
-	'arguments' => [
1224
-		'autocreate' => true,
1225
-		'user' => [
1226
-			'name' => 'swift',
1227
-			'password' => 'swift',
1228
-			'domain' => [
1229
-				'name' => 'default',
1230
-			],
1231
-		],
1232
-		'scope' => [
1233
-			'project' => [
1234
-				'name' => 'service',
1235
-				'domain' => [
1236
-					'name' => 'default',
1237
-				],
1238
-			],
1239
-		],
1240
-		'tenantName' => 'service',
1241
-		'serviceName' => 'swift',
1242
-		'region' => 'regionOne',
1243
-		'url' => 'http://yourswifthost:5000/v3',
1244
-		'bucket' => 'nextcloud',
1245
-	],
1222
+    'class' => 'OC\\Files\\ObjectStore\\Swift',
1223
+    'arguments' => [
1224
+        'autocreate' => true,
1225
+        'user' => [
1226
+            'name' => 'swift',
1227
+            'password' => 'swift',
1228
+            'domain' => [
1229
+                'name' => 'default',
1230
+            ],
1231
+        ],
1232
+        'scope' => [
1233
+            'project' => [
1234
+                'name' => 'service',
1235
+                'domain' => [
1236
+                    'name' => 'default',
1237
+                ],
1238
+            ],
1239
+        ],
1240
+        'tenantName' => 'service',
1241
+        'serviceName' => 'swift',
1242
+        'region' => 'regionOne',
1243
+        'url' => 'http://yourswifthost:5000/v3',
1244
+        'bucket' => 'nextcloud',
1245
+    ],
1246 1246
 ],
1247 1247
 
1248 1248
 
@@ -1282,8 +1282,8 @@  discard block
 block discarded – undo
1282 1282
  * encryption in MySQL or specify a custom wait timeout on a cheap hoster.
1283 1283
  */
1284 1284
 'dbdriveroptions' => array(
1285
-	PDO::MYSQL_ATTR_SSL_CA => '/file/path/to/ca_cert.pem',
1286
-	PDO::MYSQL_ATTR_INIT_COMMAND => 'SET wait_timeout = 28800'
1285
+    PDO::MYSQL_ATTR_SSL_CA => '/file/path/to/ca_cert.pem',
1286
+    PDO::MYSQL_ATTR_INIT_COMMAND => 'SET wait_timeout = 28800'
1287 1287
 ),
1288 1288
 
1289 1289
 /**
@@ -1340,10 +1340,10 @@  discard block
 block discarded – undo
1340 1340
  *  - pgsql (PostgreSQL)
1341 1341
  */
1342 1342
 'supportedDatabases' => array(
1343
-	'sqlite',
1344
-	'mysql',
1345
-	'pgsql',
1346
-	'oci',
1343
+    'sqlite',
1344
+    'mysql',
1345
+    'pgsql',
1346
+    'oci',
1347 1347
 ),
1348 1348
 
1349 1349
 /**
@@ -1603,8 +1603,8 @@  discard block
 block discarded – undo
1603 1603
  * WARNING: only use this if you know what you are doing
1604 1604
  */
1605 1605
 'csrf.optout' => array(
1606
-	'/^WebDAVFS/', // OS X Finder
1607
-	'/^Microsoft-WebDAV-MiniRedir/', // Windows webdav drive
1606
+    '/^WebDAVFS/', // OS X Finder
1607
+    '/^Microsoft-WebDAV-MiniRedir/', // Windows webdav drive
1608 1608
 ),
1609 1609
 
1610 1610
 );
Please login to merge, or discard this patch.