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