Completed
Push — master ( e0a4c6...1ad79e )
by Morris
27:44
created
lib/private/AppFramework/DependencyInjection/DIContainer.php 2 patches
Indentation   +392 added lines, -392 removed lines patch added patch discarded remove patch
@@ -63,396 +63,396 @@
 block discarded – undo
63 63
 
64 64
 class DIContainer extends SimpleContainer implements IAppContainer {
65 65
 
66
-	/**
67
-	 * @var array
68
-	 */
69
-	private $middleWares = array();
70
-
71
-	/** @var ServerContainer */
72
-	private $server;
73
-
74
-	/**
75
-	 * Put your class dependencies in here
76
-	 * @param string $appName the name of the app
77
-	 * @param array $urlParams
78
-	 * @param ServerContainer|null $server
79
-	 */
80
-	public function __construct($appName, $urlParams = array(), ServerContainer $server = null){
81
-		parent::__construct();
82
-		$this['AppName'] = $appName;
83
-		$this['urlParams'] = $urlParams;
84
-
85
-		/** @var \OC\ServerContainer $server */
86
-		if ($server === null) {
87
-			$server = \OC::$server;
88
-		}
89
-		$this->server = $server;
90
-		$this->server->registerAppContainer($appName, $this);
91
-
92
-		// aliases
93
-		$this->registerAlias('appName', 'AppName');
94
-		$this->registerAlias('webRoot', 'WebRoot');
95
-		$this->registerAlias('userId', 'UserId');
96
-
97
-		/**
98
-		 * Core services
99
-		 */
100
-		$this->registerService(IOutput::class, function($c){
101
-			return new Output($this->getServer()->getWebRoot());
102
-		});
103
-
104
-		$this->registerService(Folder::class, function() {
105
-			return $this->getServer()->getUserFolder();
106
-		});
107
-
108
-		$this->registerService(IAppData::class, function (SimpleContainer $c) {
109
-			return $this->getServer()->getAppDataDir($c->query('AppName'));
110
-		});
111
-
112
-		$this->registerService(IL10N::class, function($c) {
113
-			return $this->getServer()->getL10N($c->query('AppName'));
114
-		});
115
-
116
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
117
-		$this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
118
-
119
-		$this->registerService(IRequest::class, function() {
120
-			return $this->getServer()->query(IRequest::class);
121
-		});
122
-		$this->registerAlias('Request', IRequest::class);
123
-
124
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
125
-		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
126
-
127
-		$this->registerAlias(\OC\User\Session::class, \OCP\IUserSession::class);
128
-
129
-		$this->registerService(IServerContainer::class, function ($c) {
130
-			return $this->getServer();
131
-		});
132
-		$this->registerAlias('ServerContainer', IServerContainer::class);
133
-
134
-		$this->registerService(\OCP\WorkflowEngine\IManager::class, function ($c) {
135
-			return $c->query('OCA\WorkflowEngine\Manager');
136
-		});
137
-
138
-		$this->registerService(\OCP\AppFramework\IAppContainer::class, function ($c) {
139
-			return $c;
140
-		});
141
-
142
-		// commonly used attributes
143
-		$this->registerService('UserId', function ($c) {
144
-			return $c->query('OCP\\IUserSession')->getSession()->get('user_id');
145
-		});
146
-
147
-		$this->registerService('WebRoot', function ($c) {
148
-			return $c->query('ServerContainer')->getWebRoot();
149
-		});
150
-
151
-		$this->registerService('fromMailAddress', function() {
152
-			return Util::getDefaultEmailAddress('no-reply');
153
-		});
154
-
155
-		$this->registerService('OC_Defaults', function ($c) {
156
-			return $c->getServer()->getThemingDefaults();
157
-		});
158
-
159
-		$this->registerService('OCP\Encryption\IManager', function ($c) {
160
-			return $this->getServer()->getEncryptionManager();
161
-		});
162
-
163
-		$this->registerService(IConfig::class, function ($c) {
164
-			return $c->query(OC\GlobalScale\Config::class);
165
-		});
166
-
167
-		$this->registerService(IValidator::class, function($c) {
168
-			return $c->query(Validator::class);
169
-		});
170
-
171
-		$this->registerService(\OC\Security\IdentityProof\Manager::class, function ($c) {
172
-			return new \OC\Security\IdentityProof\Manager(
173
-				$this->getServer()->query(\OC\Files\AppData\Factory::class),
174
-				$this->getServer()->getCrypto(),
175
-				$this->getServer()->getConfig()
176
-			);
177
-		});
178
-
179
-		/**
180
-		 * App Framework APIs
181
-		 */
182
-		$this->registerService('API', function($c){
183
-			$c->query('OCP\\ILogger')->debug(
184
-				'Accessing the API class is deprecated! Use the appropriate ' .
185
-				'services instead!'
186
-			);
187
-			return new API($c['AppName']);
188
-		});
189
-
190
-		$this->registerService('Protocol', function($c){
191
-			/** @var \OC\Server $server */
192
-			$server = $c->query('ServerContainer');
193
-			$protocol = $server->getRequest()->getHttpProtocol();
194
-			return new Http($_SERVER, $protocol);
195
-		});
196
-
197
-		$this->registerService('Dispatcher', function($c) {
198
-			return new Dispatcher(
199
-				$c['Protocol'],
200
-				$c['MiddlewareDispatcher'],
201
-				$c['ControllerMethodReflector'],
202
-				$c['Request']
203
-			);
204
-		});
205
-
206
-		/**
207
-		 * App Framework default arguments
208
-		 */
209
-		$this->registerParameter('corsMethods', 'PUT, POST, GET, DELETE, PATCH');
210
-		$this->registerParameter('corsAllowedHeaders', 'Authorization, Content-Type, Accept');
211
-		$this->registerParameter('corsMaxAge', 1728000);
212
-
213
-		/**
214
-		 * Middleware
215
-		 */
216
-		$app = $this;
217
-		$this->registerService('SecurityMiddleware', function($c) use ($app){
218
-			/** @var \OC\Server $server */
219
-			$server = $app->getServer();
220
-
221
-			return new SecurityMiddleware(
222
-				$c['Request'],
223
-				$c['ControllerMethodReflector'],
224
-				$server->getNavigationManager(),
225
-				$server->getURLGenerator(),
226
-				$server->getLogger(),
227
-				$server->getSession(),
228
-				$c['AppName'],
229
-				$app->isLoggedIn(),
230
-				$app->isAdminUser(),
231
-				$server->getContentSecurityPolicyManager(),
232
-				$server->getCsrfTokenManager(),
233
-				$server->getContentSecurityPolicyNonceManager()
234
-			);
235
-
236
-		});
237
-
238
-		$this->registerService('BruteForceMiddleware', function($c) use ($app) {
239
-			/** @var \OC\Server $server */
240
-			$server = $app->getServer();
241
-
242
-			return new OC\AppFramework\Middleware\Security\BruteForceMiddleware(
243
-				$c['ControllerMethodReflector'],
244
-				$server->getBruteForceThrottler(),
245
-				$server->getRequest()
246
-			);
247
-		});
248
-
249
-		$this->registerService('RateLimitingMiddleware', function($c) use ($app) {
250
-			/** @var \OC\Server $server */
251
-			$server = $app->getServer();
252
-
253
-			return new RateLimitingMiddleware(
254
-				$server->getRequest(),
255
-				$server->getUserSession(),
256
-				$c['ControllerMethodReflector'],
257
-				$c->query(OC\Security\RateLimiting\Limiter::class)
258
-			);
259
-		});
260
-
261
-		$this->registerService('CORSMiddleware', function($c) {
262
-			return new CORSMiddleware(
263
-				$c['Request'],
264
-				$c['ControllerMethodReflector'],
265
-				$c->query(IUserSession::class),
266
-				$c->getServer()->getBruteForceThrottler()
267
-			);
268
-		});
269
-
270
-		$this->registerService('SessionMiddleware', function($c) use ($app) {
271
-			return new SessionMiddleware(
272
-				$c['Request'],
273
-				$c['ControllerMethodReflector'],
274
-				$app->getServer()->getSession()
275
-			);
276
-		});
277
-
278
-		$this->registerService('TwoFactorMiddleware', function (SimpleContainer $c) use ($app) {
279
-			$twoFactorManager = $c->getServer()->getTwoFactorAuthManager();
280
-			$userSession = $app->getServer()->getUserSession();
281
-			$session = $app->getServer()->getSession();
282
-			$urlGenerator = $app->getServer()->getURLGenerator();
283
-			$reflector = $c['ControllerMethodReflector'];
284
-			$request = $app->getServer()->getRequest();
285
-			return new TwoFactorMiddleware($twoFactorManager, $userSession, $session, $urlGenerator, $reflector, $request);
286
-		});
287
-
288
-		$this->registerService('OCSMiddleware', function (SimpleContainer $c) {
289
-			return new OCSMiddleware(
290
-				$c['Request']
291
-			);
292
-		});
293
-
294
-		$this->registerService(OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware::class, function (SimpleContainer $c) {
295
-			return new OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware(
296
-				$c['Request'],
297
-				$c['ControllerMethodReflector']
298
-			);
299
-		});
300
-
301
-		$middleWares = &$this->middleWares;
302
-		$this->registerService('MiddlewareDispatcher', function($c) use (&$middleWares) {
303
-			$dispatcher = new MiddlewareDispatcher();
304
-			$dispatcher->registerMiddleware($c[OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware::class]);
305
-			$dispatcher->registerMiddleware($c['CORSMiddleware']);
306
-			$dispatcher->registerMiddleware($c['OCSMiddleware']);
307
-			$dispatcher->registerMiddleware($c['SecurityMiddleware']);
308
-			$dispatcher->registerMiddleware($c['TwoFactorMiddleware']);
309
-			$dispatcher->registerMiddleware($c['BruteForceMiddleware']);
310
-			$dispatcher->registerMiddleware($c['RateLimitingMiddleware']);
311
-
312
-			foreach($middleWares as $middleWare) {
313
-				$dispatcher->registerMiddleware($c[$middleWare]);
314
-			}
315
-
316
-			$dispatcher->registerMiddleware($c['SessionMiddleware']);
317
-			return $dispatcher;
318
-		});
319
-
320
-	}
321
-
322
-
323
-	/**
324
-	 * @deprecated implements only deprecated methods
325
-	 * @return IApi
326
-	 */
327
-	public function getCoreApi()
328
-	{
329
-		return $this->query('API');
330
-	}
331
-
332
-	/**
333
-	 * @return \OCP\IServerContainer
334
-	 */
335
-	public function getServer()
336
-	{
337
-		return $this->server;
338
-	}
339
-
340
-	/**
341
-	 * @param string $middleWare
342
-	 * @return boolean|null
343
-	 */
344
-	public function registerMiddleWare($middleWare) {
345
-		array_push($this->middleWares, $middleWare);
346
-	}
347
-
348
-	/**
349
-	 * used to return the appname of the set application
350
-	 * @return string the name of your application
351
-	 */
352
-	public function getAppName() {
353
-		return $this->query('AppName');
354
-	}
355
-
356
-	/**
357
-	 * @deprecated use IUserSession->isLoggedIn()
358
-	 * @return boolean
359
-	 */
360
-	public function isLoggedIn() {
361
-		return \OC::$server->getUserSession()->isLoggedIn();
362
-	}
363
-
364
-	/**
365
-	 * @deprecated use IGroupManager->isAdmin($userId)
366
-	 * @return boolean
367
-	 */
368
-	public function isAdminUser() {
369
-		$uid = $this->getUserId();
370
-		return \OC_User::isAdminUser($uid);
371
-	}
372
-
373
-	private function getUserId() {
374
-		return $this->getServer()->getSession()->get('user_id');
375
-	}
376
-
377
-	/**
378
-	 * @deprecated use the ILogger instead
379
-	 * @param string $message
380
-	 * @param string $level
381
-	 * @return mixed
382
-	 */
383
-	public function log($message, $level) {
384
-		switch($level){
385
-			case 'debug':
386
-				$level = \OCP\Util::DEBUG;
387
-				break;
388
-			case 'info':
389
-				$level = \OCP\Util::INFO;
390
-				break;
391
-			case 'warn':
392
-				$level = \OCP\Util::WARN;
393
-				break;
394
-			case 'fatal':
395
-				$level = \OCP\Util::FATAL;
396
-				break;
397
-			default:
398
-				$level = \OCP\Util::ERROR;
399
-				break;
400
-		}
401
-		\OCP\Util::writeLog($this->getAppName(), $message, $level);
402
-	}
403
-
404
-	/**
405
-	 * Register a capability
406
-	 *
407
-	 * @param string $serviceName e.g. 'OCA\Files\Capabilities'
408
-	 */
409
-	public function registerCapability($serviceName) {
410
-		$this->query('OC\CapabilitiesManager')->registerCapability(function() use ($serviceName) {
411
-			return $this->query($serviceName);
412
-		});
413
-	}
414
-
415
-	/**
416
-	 * @param string $name
417
-	 * @return mixed
418
-	 * @throws QueryException if the query could not be resolved
419
-	 */
420
-	public function query($name) {
421
-		try {
422
-			return $this->queryNoFallback($name);
423
-		} catch (QueryException $firstException) {
424
-			try {
425
-				return $this->getServer()->query($name);
426
-			} catch (QueryException $secondException) {
427
-				if ($firstException->getCode() === 1) {
428
-					throw $secondException;
429
-				}
430
-				throw $firstException;
431
-			}
432
-		}
433
-	}
434
-
435
-	/**
436
-	 * @param string $name
437
-	 * @return mixed
438
-	 * @throws QueryException if the query could not be resolved
439
-	 */
440
-	public function queryNoFallback($name) {
441
-		$name = $this->sanitizeName($name);
442
-
443
-		if ($this->offsetExists($name)) {
444
-			return parent::query($name);
445
-		} else {
446
-			if ($this['AppName'] === 'settings' && strpos($name, 'OC\\Settings\\') === 0) {
447
-				return parent::query($name);
448
-			} else if ($this['AppName'] === 'core' && strpos($name, 'OC\\Core\\') === 0) {
449
-				return parent::query($name);
450
-			} else if (strpos($name, \OC\AppFramework\App::buildAppNamespace($this['AppName']) . '\\') === 0) {
451
-				return parent::query($name);
452
-			}
453
-		}
454
-
455
-		throw new QueryException('Could not resolve ' . $name . '!' .
456
-			' Class can not be instantiated', 1);
457
-	}
66
+    /**
67
+     * @var array
68
+     */
69
+    private $middleWares = array();
70
+
71
+    /** @var ServerContainer */
72
+    private $server;
73
+
74
+    /**
75
+     * Put your class dependencies in here
76
+     * @param string $appName the name of the app
77
+     * @param array $urlParams
78
+     * @param ServerContainer|null $server
79
+     */
80
+    public function __construct($appName, $urlParams = array(), ServerContainer $server = null){
81
+        parent::__construct();
82
+        $this['AppName'] = $appName;
83
+        $this['urlParams'] = $urlParams;
84
+
85
+        /** @var \OC\ServerContainer $server */
86
+        if ($server === null) {
87
+            $server = \OC::$server;
88
+        }
89
+        $this->server = $server;
90
+        $this->server->registerAppContainer($appName, $this);
91
+
92
+        // aliases
93
+        $this->registerAlias('appName', 'AppName');
94
+        $this->registerAlias('webRoot', 'WebRoot');
95
+        $this->registerAlias('userId', 'UserId');
96
+
97
+        /**
98
+         * Core services
99
+         */
100
+        $this->registerService(IOutput::class, function($c){
101
+            return new Output($this->getServer()->getWebRoot());
102
+        });
103
+
104
+        $this->registerService(Folder::class, function() {
105
+            return $this->getServer()->getUserFolder();
106
+        });
107
+
108
+        $this->registerService(IAppData::class, function (SimpleContainer $c) {
109
+            return $this->getServer()->getAppDataDir($c->query('AppName'));
110
+        });
111
+
112
+        $this->registerService(IL10N::class, function($c) {
113
+            return $this->getServer()->getL10N($c->query('AppName'));
114
+        });
115
+
116
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
117
+        $this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
118
+
119
+        $this->registerService(IRequest::class, function() {
120
+            return $this->getServer()->query(IRequest::class);
121
+        });
122
+        $this->registerAlias('Request', IRequest::class);
123
+
124
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
125
+        $this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
126
+
127
+        $this->registerAlias(\OC\User\Session::class, \OCP\IUserSession::class);
128
+
129
+        $this->registerService(IServerContainer::class, function ($c) {
130
+            return $this->getServer();
131
+        });
132
+        $this->registerAlias('ServerContainer', IServerContainer::class);
133
+
134
+        $this->registerService(\OCP\WorkflowEngine\IManager::class, function ($c) {
135
+            return $c->query('OCA\WorkflowEngine\Manager');
136
+        });
137
+
138
+        $this->registerService(\OCP\AppFramework\IAppContainer::class, function ($c) {
139
+            return $c;
140
+        });
141
+
142
+        // commonly used attributes
143
+        $this->registerService('UserId', function ($c) {
144
+            return $c->query('OCP\\IUserSession')->getSession()->get('user_id');
145
+        });
146
+
147
+        $this->registerService('WebRoot', function ($c) {
148
+            return $c->query('ServerContainer')->getWebRoot();
149
+        });
150
+
151
+        $this->registerService('fromMailAddress', function() {
152
+            return Util::getDefaultEmailAddress('no-reply');
153
+        });
154
+
155
+        $this->registerService('OC_Defaults', function ($c) {
156
+            return $c->getServer()->getThemingDefaults();
157
+        });
158
+
159
+        $this->registerService('OCP\Encryption\IManager', function ($c) {
160
+            return $this->getServer()->getEncryptionManager();
161
+        });
162
+
163
+        $this->registerService(IConfig::class, function ($c) {
164
+            return $c->query(OC\GlobalScale\Config::class);
165
+        });
166
+
167
+        $this->registerService(IValidator::class, function($c) {
168
+            return $c->query(Validator::class);
169
+        });
170
+
171
+        $this->registerService(\OC\Security\IdentityProof\Manager::class, function ($c) {
172
+            return new \OC\Security\IdentityProof\Manager(
173
+                $this->getServer()->query(\OC\Files\AppData\Factory::class),
174
+                $this->getServer()->getCrypto(),
175
+                $this->getServer()->getConfig()
176
+            );
177
+        });
178
+
179
+        /**
180
+         * App Framework APIs
181
+         */
182
+        $this->registerService('API', function($c){
183
+            $c->query('OCP\\ILogger')->debug(
184
+                'Accessing the API class is deprecated! Use the appropriate ' .
185
+                'services instead!'
186
+            );
187
+            return new API($c['AppName']);
188
+        });
189
+
190
+        $this->registerService('Protocol', function($c){
191
+            /** @var \OC\Server $server */
192
+            $server = $c->query('ServerContainer');
193
+            $protocol = $server->getRequest()->getHttpProtocol();
194
+            return new Http($_SERVER, $protocol);
195
+        });
196
+
197
+        $this->registerService('Dispatcher', function($c) {
198
+            return new Dispatcher(
199
+                $c['Protocol'],
200
+                $c['MiddlewareDispatcher'],
201
+                $c['ControllerMethodReflector'],
202
+                $c['Request']
203
+            );
204
+        });
205
+
206
+        /**
207
+         * App Framework default arguments
208
+         */
209
+        $this->registerParameter('corsMethods', 'PUT, POST, GET, DELETE, PATCH');
210
+        $this->registerParameter('corsAllowedHeaders', 'Authorization, Content-Type, Accept');
211
+        $this->registerParameter('corsMaxAge', 1728000);
212
+
213
+        /**
214
+         * Middleware
215
+         */
216
+        $app = $this;
217
+        $this->registerService('SecurityMiddleware', function($c) use ($app){
218
+            /** @var \OC\Server $server */
219
+            $server = $app->getServer();
220
+
221
+            return new SecurityMiddleware(
222
+                $c['Request'],
223
+                $c['ControllerMethodReflector'],
224
+                $server->getNavigationManager(),
225
+                $server->getURLGenerator(),
226
+                $server->getLogger(),
227
+                $server->getSession(),
228
+                $c['AppName'],
229
+                $app->isLoggedIn(),
230
+                $app->isAdminUser(),
231
+                $server->getContentSecurityPolicyManager(),
232
+                $server->getCsrfTokenManager(),
233
+                $server->getContentSecurityPolicyNonceManager()
234
+            );
235
+
236
+        });
237
+
238
+        $this->registerService('BruteForceMiddleware', function($c) use ($app) {
239
+            /** @var \OC\Server $server */
240
+            $server = $app->getServer();
241
+
242
+            return new OC\AppFramework\Middleware\Security\BruteForceMiddleware(
243
+                $c['ControllerMethodReflector'],
244
+                $server->getBruteForceThrottler(),
245
+                $server->getRequest()
246
+            );
247
+        });
248
+
249
+        $this->registerService('RateLimitingMiddleware', function($c) use ($app) {
250
+            /** @var \OC\Server $server */
251
+            $server = $app->getServer();
252
+
253
+            return new RateLimitingMiddleware(
254
+                $server->getRequest(),
255
+                $server->getUserSession(),
256
+                $c['ControllerMethodReflector'],
257
+                $c->query(OC\Security\RateLimiting\Limiter::class)
258
+            );
259
+        });
260
+
261
+        $this->registerService('CORSMiddleware', function($c) {
262
+            return new CORSMiddleware(
263
+                $c['Request'],
264
+                $c['ControllerMethodReflector'],
265
+                $c->query(IUserSession::class),
266
+                $c->getServer()->getBruteForceThrottler()
267
+            );
268
+        });
269
+
270
+        $this->registerService('SessionMiddleware', function($c) use ($app) {
271
+            return new SessionMiddleware(
272
+                $c['Request'],
273
+                $c['ControllerMethodReflector'],
274
+                $app->getServer()->getSession()
275
+            );
276
+        });
277
+
278
+        $this->registerService('TwoFactorMiddleware', function (SimpleContainer $c) use ($app) {
279
+            $twoFactorManager = $c->getServer()->getTwoFactorAuthManager();
280
+            $userSession = $app->getServer()->getUserSession();
281
+            $session = $app->getServer()->getSession();
282
+            $urlGenerator = $app->getServer()->getURLGenerator();
283
+            $reflector = $c['ControllerMethodReflector'];
284
+            $request = $app->getServer()->getRequest();
285
+            return new TwoFactorMiddleware($twoFactorManager, $userSession, $session, $urlGenerator, $reflector, $request);
286
+        });
287
+
288
+        $this->registerService('OCSMiddleware', function (SimpleContainer $c) {
289
+            return new OCSMiddleware(
290
+                $c['Request']
291
+            );
292
+        });
293
+
294
+        $this->registerService(OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware::class, function (SimpleContainer $c) {
295
+            return new OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware(
296
+                $c['Request'],
297
+                $c['ControllerMethodReflector']
298
+            );
299
+        });
300
+
301
+        $middleWares = &$this->middleWares;
302
+        $this->registerService('MiddlewareDispatcher', function($c) use (&$middleWares) {
303
+            $dispatcher = new MiddlewareDispatcher();
304
+            $dispatcher->registerMiddleware($c[OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware::class]);
305
+            $dispatcher->registerMiddleware($c['CORSMiddleware']);
306
+            $dispatcher->registerMiddleware($c['OCSMiddleware']);
307
+            $dispatcher->registerMiddleware($c['SecurityMiddleware']);
308
+            $dispatcher->registerMiddleware($c['TwoFactorMiddleware']);
309
+            $dispatcher->registerMiddleware($c['BruteForceMiddleware']);
310
+            $dispatcher->registerMiddleware($c['RateLimitingMiddleware']);
311
+
312
+            foreach($middleWares as $middleWare) {
313
+                $dispatcher->registerMiddleware($c[$middleWare]);
314
+            }
315
+
316
+            $dispatcher->registerMiddleware($c['SessionMiddleware']);
317
+            return $dispatcher;
318
+        });
319
+
320
+    }
321
+
322
+
323
+    /**
324
+     * @deprecated implements only deprecated methods
325
+     * @return IApi
326
+     */
327
+    public function getCoreApi()
328
+    {
329
+        return $this->query('API');
330
+    }
331
+
332
+    /**
333
+     * @return \OCP\IServerContainer
334
+     */
335
+    public function getServer()
336
+    {
337
+        return $this->server;
338
+    }
339
+
340
+    /**
341
+     * @param string $middleWare
342
+     * @return boolean|null
343
+     */
344
+    public function registerMiddleWare($middleWare) {
345
+        array_push($this->middleWares, $middleWare);
346
+    }
347
+
348
+    /**
349
+     * used to return the appname of the set application
350
+     * @return string the name of your application
351
+     */
352
+    public function getAppName() {
353
+        return $this->query('AppName');
354
+    }
355
+
356
+    /**
357
+     * @deprecated use IUserSession->isLoggedIn()
358
+     * @return boolean
359
+     */
360
+    public function isLoggedIn() {
361
+        return \OC::$server->getUserSession()->isLoggedIn();
362
+    }
363
+
364
+    /**
365
+     * @deprecated use IGroupManager->isAdmin($userId)
366
+     * @return boolean
367
+     */
368
+    public function isAdminUser() {
369
+        $uid = $this->getUserId();
370
+        return \OC_User::isAdminUser($uid);
371
+    }
372
+
373
+    private function getUserId() {
374
+        return $this->getServer()->getSession()->get('user_id');
375
+    }
376
+
377
+    /**
378
+     * @deprecated use the ILogger instead
379
+     * @param string $message
380
+     * @param string $level
381
+     * @return mixed
382
+     */
383
+    public function log($message, $level) {
384
+        switch($level){
385
+            case 'debug':
386
+                $level = \OCP\Util::DEBUG;
387
+                break;
388
+            case 'info':
389
+                $level = \OCP\Util::INFO;
390
+                break;
391
+            case 'warn':
392
+                $level = \OCP\Util::WARN;
393
+                break;
394
+            case 'fatal':
395
+                $level = \OCP\Util::FATAL;
396
+                break;
397
+            default:
398
+                $level = \OCP\Util::ERROR;
399
+                break;
400
+        }
401
+        \OCP\Util::writeLog($this->getAppName(), $message, $level);
402
+    }
403
+
404
+    /**
405
+     * Register a capability
406
+     *
407
+     * @param string $serviceName e.g. 'OCA\Files\Capabilities'
408
+     */
409
+    public function registerCapability($serviceName) {
410
+        $this->query('OC\CapabilitiesManager')->registerCapability(function() use ($serviceName) {
411
+            return $this->query($serviceName);
412
+        });
413
+    }
414
+
415
+    /**
416
+     * @param string $name
417
+     * @return mixed
418
+     * @throws QueryException if the query could not be resolved
419
+     */
420
+    public function query($name) {
421
+        try {
422
+            return $this->queryNoFallback($name);
423
+        } catch (QueryException $firstException) {
424
+            try {
425
+                return $this->getServer()->query($name);
426
+            } catch (QueryException $secondException) {
427
+                if ($firstException->getCode() === 1) {
428
+                    throw $secondException;
429
+                }
430
+                throw $firstException;
431
+            }
432
+        }
433
+    }
434
+
435
+    /**
436
+     * @param string $name
437
+     * @return mixed
438
+     * @throws QueryException if the query could not be resolved
439
+     */
440
+    public function queryNoFallback($name) {
441
+        $name = $this->sanitizeName($name);
442
+
443
+        if ($this->offsetExists($name)) {
444
+            return parent::query($name);
445
+        } else {
446
+            if ($this['AppName'] === 'settings' && strpos($name, 'OC\\Settings\\') === 0) {
447
+                return parent::query($name);
448
+            } else if ($this['AppName'] === 'core' && strpos($name, 'OC\\Core\\') === 0) {
449
+                return parent::query($name);
450
+            } else if (strpos($name, \OC\AppFramework\App::buildAppNamespace($this['AppName']) . '\\') === 0) {
451
+                return parent::query($name);
452
+            }
453
+        }
454
+
455
+        throw new QueryException('Could not resolve ' . $name . '!' .
456
+            ' Class can not be instantiated', 1);
457
+    }
458 458
 }
Please login to merge, or discard this patch.
Spacing   +22 added lines, -22 removed lines patch added patch discarded remove patch
@@ -77,7 +77,7 @@  discard block
 block discarded – undo
77 77
 	 * @param array $urlParams
78 78
 	 * @param ServerContainer|null $server
79 79
 	 */
80
-	public function __construct($appName, $urlParams = array(), ServerContainer $server = null){
80
+	public function __construct($appName, $urlParams = array(), ServerContainer $server = null) {
81 81
 		parent::__construct();
82 82
 		$this['AppName'] = $appName;
83 83
 		$this['urlParams'] = $urlParams;
@@ -97,7 +97,7 @@  discard block
 block discarded – undo
97 97
 		/**
98 98
 		 * Core services
99 99
 		 */
100
-		$this->registerService(IOutput::class, function($c){
100
+		$this->registerService(IOutput::class, function($c) {
101 101
 			return new Output($this->getServer()->getWebRoot());
102 102
 		});
103 103
 
@@ -105,7 +105,7 @@  discard block
 block discarded – undo
105 105
 			return $this->getServer()->getUserFolder();
106 106
 		});
107 107
 
108
-		$this->registerService(IAppData::class, function (SimpleContainer $c) {
108
+		$this->registerService(IAppData::class, function(SimpleContainer $c) {
109 109
 			return $this->getServer()->getAppDataDir($c->query('AppName'));
110 110
 		});
111 111
 
@@ -126,25 +126,25 @@  discard block
 block discarded – undo
126 126
 
127 127
 		$this->registerAlias(\OC\User\Session::class, \OCP\IUserSession::class);
128 128
 
129
-		$this->registerService(IServerContainer::class, function ($c) {
129
+		$this->registerService(IServerContainer::class, function($c) {
130 130
 			return $this->getServer();
131 131
 		});
132 132
 		$this->registerAlias('ServerContainer', IServerContainer::class);
133 133
 
134
-		$this->registerService(\OCP\WorkflowEngine\IManager::class, function ($c) {
134
+		$this->registerService(\OCP\WorkflowEngine\IManager::class, function($c) {
135 135
 			return $c->query('OCA\WorkflowEngine\Manager');
136 136
 		});
137 137
 
138
-		$this->registerService(\OCP\AppFramework\IAppContainer::class, function ($c) {
138
+		$this->registerService(\OCP\AppFramework\IAppContainer::class, function($c) {
139 139
 			return $c;
140 140
 		});
141 141
 
142 142
 		// commonly used attributes
143
-		$this->registerService('UserId', function ($c) {
143
+		$this->registerService('UserId', function($c) {
144 144
 			return $c->query('OCP\\IUserSession')->getSession()->get('user_id');
145 145
 		});
146 146
 
147
-		$this->registerService('WebRoot', function ($c) {
147
+		$this->registerService('WebRoot', function($c) {
148 148
 			return $c->query('ServerContainer')->getWebRoot();
149 149
 		});
150 150
 
@@ -152,15 +152,15 @@  discard block
 block discarded – undo
152 152
 			return Util::getDefaultEmailAddress('no-reply');
153 153
 		});
154 154
 
155
-		$this->registerService('OC_Defaults', function ($c) {
155
+		$this->registerService('OC_Defaults', function($c) {
156 156
 			return $c->getServer()->getThemingDefaults();
157 157
 		});
158 158
 
159
-		$this->registerService('OCP\Encryption\IManager', function ($c) {
159
+		$this->registerService('OCP\Encryption\IManager', function($c) {
160 160
 			return $this->getServer()->getEncryptionManager();
161 161
 		});
162 162
 
163
-		$this->registerService(IConfig::class, function ($c) {
163
+		$this->registerService(IConfig::class, function($c) {
164 164
 			return $c->query(OC\GlobalScale\Config::class);
165 165
 		});
166 166
 
@@ -168,7 +168,7 @@  discard block
 block discarded – undo
168 168
 			return $c->query(Validator::class);
169 169
 		});
170 170
 
171
-		$this->registerService(\OC\Security\IdentityProof\Manager::class, function ($c) {
171
+		$this->registerService(\OC\Security\IdentityProof\Manager::class, function($c) {
172 172
 			return new \OC\Security\IdentityProof\Manager(
173 173
 				$this->getServer()->query(\OC\Files\AppData\Factory::class),
174 174
 				$this->getServer()->getCrypto(),
@@ -179,15 +179,15 @@  discard block
 block discarded – undo
179 179
 		/**
180 180
 		 * App Framework APIs
181 181
 		 */
182
-		$this->registerService('API', function($c){
182
+		$this->registerService('API', function($c) {
183 183
 			$c->query('OCP\\ILogger')->debug(
184
-				'Accessing the API class is deprecated! Use the appropriate ' .
184
+				'Accessing the API class is deprecated! Use the appropriate '.
185 185
 				'services instead!'
186 186
 			);
187 187
 			return new API($c['AppName']);
188 188
 		});
189 189
 
190
-		$this->registerService('Protocol', function($c){
190
+		$this->registerService('Protocol', function($c) {
191 191
 			/** @var \OC\Server $server */
192 192
 			$server = $c->query('ServerContainer');
193 193
 			$protocol = $server->getRequest()->getHttpProtocol();
@@ -275,7 +275,7 @@  discard block
 block discarded – undo
275 275
 			);
276 276
 		});
277 277
 
278
-		$this->registerService('TwoFactorMiddleware', function (SimpleContainer $c) use ($app) {
278
+		$this->registerService('TwoFactorMiddleware', function(SimpleContainer $c) use ($app) {
279 279
 			$twoFactorManager = $c->getServer()->getTwoFactorAuthManager();
280 280
 			$userSession = $app->getServer()->getUserSession();
281 281
 			$session = $app->getServer()->getSession();
@@ -285,13 +285,13 @@  discard block
 block discarded – undo
285 285
 			return new TwoFactorMiddleware($twoFactorManager, $userSession, $session, $urlGenerator, $reflector, $request);
286 286
 		});
287 287
 
288
-		$this->registerService('OCSMiddleware', function (SimpleContainer $c) {
288
+		$this->registerService('OCSMiddleware', function(SimpleContainer $c) {
289 289
 			return new OCSMiddleware(
290 290
 				$c['Request']
291 291
 			);
292 292
 		});
293 293
 
294
-		$this->registerService(OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware::class, function (SimpleContainer $c) {
294
+		$this->registerService(OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware::class, function(SimpleContainer $c) {
295 295
 			return new OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware(
296 296
 				$c['Request'],
297 297
 				$c['ControllerMethodReflector']
@@ -309,7 +309,7 @@  discard block
 block discarded – undo
309 309
 			$dispatcher->registerMiddleware($c['BruteForceMiddleware']);
310 310
 			$dispatcher->registerMiddleware($c['RateLimitingMiddleware']);
311 311
 
312
-			foreach($middleWares as $middleWare) {
312
+			foreach ($middleWares as $middleWare) {
313 313
 				$dispatcher->registerMiddleware($c[$middleWare]);
314 314
 			}
315 315
 
@@ -381,7 +381,7 @@  discard block
 block discarded – undo
381 381
 	 * @return mixed
382 382
 	 */
383 383
 	public function log($message, $level) {
384
-		switch($level){
384
+		switch ($level) {
385 385
 			case 'debug':
386 386
 				$level = \OCP\Util::DEBUG;
387 387
 				break;
@@ -447,12 +447,12 @@  discard block
 block discarded – undo
447 447
 				return parent::query($name);
448 448
 			} else if ($this['AppName'] === 'core' && strpos($name, 'OC\\Core\\') === 0) {
449 449
 				return parent::query($name);
450
-			} else if (strpos($name, \OC\AppFramework\App::buildAppNamespace($this['AppName']) . '\\') === 0) {
450
+			} else if (strpos($name, \OC\AppFramework\App::buildAppNamespace($this['AppName']).'\\') === 0) {
451 451
 				return parent::query($name);
452 452
 			}
453 453
 		}
454 454
 
455
-		throw new QueryException('Could not resolve ' . $name . '!' .
455
+		throw new QueryException('Could not resolve '.$name.'!'.
456 456
 			' Class can not be instantiated', 1);
457 457
 	}
458 458
 }
Please login to merge, or discard this patch.
lib/private/AppFramework/Http/Request.php 1 patch
Indentation   +809 added lines, -809 removed lines patch added patch discarded remove patch
@@ -55,814 +55,814 @@
 block discarded – undo
55 55
  */
56 56
 class Request implements \ArrayAccess, \Countable, IRequest {
57 57
 
58
-	const USER_AGENT_IE = '/(MSIE)|(Trident)/';
59
-	// Microsoft Edge User Agent from https://msdn.microsoft.com/en-us/library/hh869301(v=vs.85).aspx
60
-	const USER_AGENT_MS_EDGE = '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\) Chrome\/[0-9.]+ (Mobile Safari|Safari)\/[0-9.]+ Edge\/[0-9.]+$/';
61
-	// Firefox User Agent from https://developer.mozilla.org/en-US/docs/Web/HTTP/Gecko_user_agent_string_reference
62
-	const USER_AGENT_FIREFOX = '/^Mozilla\/5\.0 \([^)]+\) Gecko\/[0-9.]+ Firefox\/[0-9.]+$/';
63
-	// Chrome User Agent from https://developer.chrome.com/multidevice/user-agent
64
-	const USER_AGENT_CHROME = '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\)( Ubuntu Chromium\/[0-9.]+|) Chrome\/[0-9.]+ (Mobile Safari|Safari)\/[0-9.]+$/';
65
-	// Safari User Agent from http://www.useragentstring.com/pages/Safari/
66
-	const USER_AGENT_SAFARI = '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\) Version\/[0-9.]+ Safari\/[0-9.A-Z]+$/';
67
-	// Android Chrome user agent: https://developers.google.com/chrome/mobile/docs/user-agent
68
-	const USER_AGENT_ANDROID_MOBILE_CHROME = '#Android.*Chrome/[.0-9]*#';
69
-	const USER_AGENT_FREEBOX = '#^Mozilla/5\.0$#';
70
-	const REGEX_LOCALHOST = '/^(127\.0\.0\.1|localhost|::1)$/';
71
-
72
-	/**
73
-	 * @deprecated use \OCP\IRequest::USER_AGENT_CLIENT_IOS instead
74
-	 */
75
-	const USER_AGENT_OWNCLOUD_IOS = '/^Mozilla\/5\.0 \(iOS\) (ownCloud|Nextcloud)\-iOS.*$/';
76
-	/**
77
-	 * @deprecated use \OCP\IRequest::USER_AGENT_CLIENT_ANDROID instead
78
-	 */
79
-	const USER_AGENT_OWNCLOUD_ANDROID = '/^Mozilla\/5\.0 \(Android\) ownCloud\-android.*$/';
80
-	/**
81
-	 * @deprecated use \OCP\IRequest::USER_AGENT_CLIENT_DESKTOP instead
82
-	 */
83
-	const USER_AGENT_OWNCLOUD_DESKTOP = '/^Mozilla\/5\.0 \([A-Za-z ]+\) (mirall|csyncoC)\/.*$/';
84
-
85
-	protected $inputStream;
86
-	protected $content;
87
-	protected $items = array();
88
-	protected $allowedKeys = array(
89
-		'get',
90
-		'post',
91
-		'files',
92
-		'server',
93
-		'env',
94
-		'cookies',
95
-		'urlParams',
96
-		'parameters',
97
-		'method',
98
-		'requesttoken',
99
-	);
100
-	/** @var ISecureRandom */
101
-	protected $secureRandom;
102
-	/** @var IConfig */
103
-	protected $config;
104
-	/** @var string */
105
-	protected $requestId = '';
106
-	/** @var ICrypto */
107
-	protected $crypto;
108
-	/** @var CsrfTokenManager|null */
109
-	protected $csrfTokenManager;
110
-
111
-	/** @var bool */
112
-	protected $contentDecoded = false;
113
-
114
-	/**
115
-	 * @param array $vars An associative array with the following optional values:
116
-	 *        - array 'urlParams' the parameters which were matched from the URL
117
-	 *        - array 'get' the $_GET array
118
-	 *        - array|string 'post' the $_POST array or JSON string
119
-	 *        - array 'files' the $_FILES array
120
-	 *        - array 'server' the $_SERVER array
121
-	 *        - array 'env' the $_ENV array
122
-	 *        - array 'cookies' the $_COOKIE array
123
-	 *        - string 'method' the request method (GET, POST etc)
124
-	 *        - string|false 'requesttoken' the requesttoken or false when not available
125
-	 * @param ISecureRandom $secureRandom
126
-	 * @param IConfig $config
127
-	 * @param CsrfTokenManager|null $csrfTokenManager
128
-	 * @param string $stream
129
-	 * @see http://www.php.net/manual/en/reserved.variables.php
130
-	 */
131
-	public function __construct(array $vars=array(),
132
-								ISecureRandom $secureRandom = null,
133
-								IConfig $config,
134
-								CsrfTokenManager $csrfTokenManager = null,
135
-								$stream = 'php://input') {
136
-		$this->inputStream = $stream;
137
-		$this->items['params'] = array();
138
-		$this->secureRandom = $secureRandom;
139
-		$this->config = $config;
140
-		$this->csrfTokenManager = $csrfTokenManager;
141
-
142
-		if(!array_key_exists('method', $vars)) {
143
-			$vars['method'] = 'GET';
144
-		}
145
-
146
-		foreach($this->allowedKeys as $name) {
147
-			$this->items[$name] = isset($vars[$name])
148
-				? $vars[$name]
149
-				: array();
150
-		}
151
-
152
-		$this->items['parameters'] = array_merge(
153
-			$this->items['get'],
154
-			$this->items['post'],
155
-			$this->items['urlParams'],
156
-			$this->items['params']
157
-		);
158
-
159
-	}
160
-	/**
161
-	 * @param array $parameters
162
-	 */
163
-	public function setUrlParameters(array $parameters) {
164
-		$this->items['urlParams'] = $parameters;
165
-		$this->items['parameters'] = array_merge(
166
-			$this->items['parameters'],
167
-			$this->items['urlParams']
168
-		);
169
-	}
170
-
171
-	/**
172
-	 * Countable method
173
-	 * @return int
174
-	 */
175
-	public function count() {
176
-		return count(array_keys($this->items['parameters']));
177
-	}
178
-
179
-	/**
180
-	* ArrayAccess methods
181
-	*
182
-	* Gives access to the combined GET, POST and urlParams arrays
183
-	*
184
-	* Examples:
185
-	*
186
-	* $var = $request['myvar'];
187
-	*
188
-	* or
189
-	*
190
-	* if(!isset($request['myvar']) {
191
-	* 	// Do something
192
-	* }
193
-	*
194
-	* $request['myvar'] = 'something'; // This throws an exception.
195
-	*
196
-	* @param string $offset The key to lookup
197
-	* @return boolean
198
-	*/
199
-	public function offsetExists($offset) {
200
-		return isset($this->items['parameters'][$offset]);
201
-	}
202
-
203
-	/**
204
-	* @see offsetExists
205
-	*/
206
-	public function offsetGet($offset) {
207
-		return isset($this->items['parameters'][$offset])
208
-			? $this->items['parameters'][$offset]
209
-			: null;
210
-	}
211
-
212
-	/**
213
-	* @see offsetExists
214
-	*/
215
-	public function offsetSet($offset, $value) {
216
-		throw new \RuntimeException('You cannot change the contents of the request object');
217
-	}
218
-
219
-	/**
220
-	* @see offsetExists
221
-	*/
222
-	public function offsetUnset($offset) {
223
-		throw new \RuntimeException('You cannot change the contents of the request object');
224
-	}
225
-
226
-	/**
227
-	 * Magic property accessors
228
-	 * @param string $name
229
-	 * @param mixed $value
230
-	 */
231
-	public function __set($name, $value) {
232
-		throw new \RuntimeException('You cannot change the contents of the request object');
233
-	}
234
-
235
-	/**
236
-	* Access request variables by method and name.
237
-	* Examples:
238
-	*
239
-	* $request->post['myvar']; // Only look for POST variables
240
-	* $request->myvar; or $request->{'myvar'}; or $request->{$myvar}
241
-	* Looks in the combined GET, POST and urlParams array.
242
-	*
243
-	* If you access e.g. ->post but the current HTTP request method
244
-	* is GET a \LogicException will be thrown.
245
-	*
246
-	* @param string $name The key to look for.
247
-	* @throws \LogicException
248
-	* @return mixed|null
249
-	*/
250
-	public function __get($name) {
251
-		switch($name) {
252
-			case 'put':
253
-			case 'patch':
254
-			case 'get':
255
-			case 'post':
256
-				if($this->method !== strtoupper($name)) {
257
-					throw new \LogicException(sprintf('%s cannot be accessed in a %s request.', $name, $this->method));
258
-				}
259
-				return $this->getContent();
260
-			case 'files':
261
-			case 'server':
262
-			case 'env':
263
-			case 'cookies':
264
-			case 'urlParams':
265
-			case 'method':
266
-				return isset($this->items[$name])
267
-					? $this->items[$name]
268
-					: null;
269
-			case 'parameters':
270
-			case 'params':
271
-				return $this->getContent();
272
-			default;
273
-				return isset($this[$name])
274
-					? $this[$name]
275
-					: null;
276
-		}
277
-	}
278
-
279
-	/**
280
-	 * @param string $name
281
-	 * @return bool
282
-	 */
283
-	public function __isset($name) {
284
-		if (in_array($name, $this->allowedKeys, true)) {
285
-			return true;
286
-		}
287
-		return isset($this->items['parameters'][$name]);
288
-	}
289
-
290
-	/**
291
-	 * @param string $id
292
-	 */
293
-	public function __unset($id) {
294
-		throw new \RuntimeException('You cannot change the contents of the request object');
295
-	}
296
-
297
-	/**
298
-	 * Returns the value for a specific http header.
299
-	 *
300
-	 * This method returns null if the header did not exist.
301
-	 *
302
-	 * @param string $name
303
-	 * @return string
304
-	 */
305
-	public function getHeader($name) {
306
-
307
-		$name = strtoupper(str_replace(array('-'),array('_'),$name));
308
-		if (isset($this->server['HTTP_' . $name])) {
309
-			return $this->server['HTTP_' . $name];
310
-		}
311
-
312
-		// There's a few headers that seem to end up in the top-level
313
-		// server array.
314
-		switch($name) {
315
-			case 'CONTENT_TYPE' :
316
-			case 'CONTENT_LENGTH' :
317
-				if (isset($this->server[$name])) {
318
-					return $this->server[$name];
319
-				}
320
-				break;
321
-
322
-		}
323
-
324
-		return null;
325
-	}
326
-
327
-	/**
328
-	 * Lets you access post and get parameters by the index
329
-	 * In case of json requests the encoded json body is accessed
330
-	 *
331
-	 * @param string $key the key which you want to access in the URL Parameter
332
-	 *                     placeholder, $_POST or $_GET array.
333
-	 *                     The priority how they're returned is the following:
334
-	 *                     1. URL parameters
335
-	 *                     2. POST parameters
336
-	 *                     3. GET parameters
337
-	 * @param mixed $default If the key is not found, this value will be returned
338
-	 * @return mixed the content of the array
339
-	 */
340
-	public function getParam($key, $default = null) {
341
-		return isset($this->parameters[$key])
342
-			? $this->parameters[$key]
343
-			: $default;
344
-	}
345
-
346
-	/**
347
-	 * Returns all params that were received, be it from the request
348
-	 * (as GET or POST) or throuh the URL by the route
349
-	 * @return array the array with all parameters
350
-	 */
351
-	public function getParams() {
352
-		return $this->parameters;
353
-	}
354
-
355
-	/**
356
-	 * Returns the method of the request
357
-	 * @return string the method of the request (POST, GET, etc)
358
-	 */
359
-	public function getMethod() {
360
-		return $this->method;
361
-	}
362
-
363
-	/**
364
-	 * Shortcut for accessing an uploaded file through the $_FILES array
365
-	 * @param string $key the key that will be taken from the $_FILES array
366
-	 * @return array the file in the $_FILES element
367
-	 */
368
-	public function getUploadedFile($key) {
369
-		return isset($this->files[$key]) ? $this->files[$key] : null;
370
-	}
371
-
372
-	/**
373
-	 * Shortcut for getting env variables
374
-	 * @param string $key the key that will be taken from the $_ENV array
375
-	 * @return array the value in the $_ENV element
376
-	 */
377
-	public function getEnv($key) {
378
-		return isset($this->env[$key]) ? $this->env[$key] : null;
379
-	}
380
-
381
-	/**
382
-	 * Shortcut for getting cookie variables
383
-	 * @param string $key the key that will be taken from the $_COOKIE array
384
-	 * @return string the value in the $_COOKIE element
385
-	 */
386
-	public function getCookie($key) {
387
-		return isset($this->cookies[$key]) ? $this->cookies[$key] : null;
388
-	}
389
-
390
-	/**
391
-	 * Returns the request body content.
392
-	 *
393
-	 * If the HTTP request method is PUT and the body
394
-	 * not application/x-www-form-urlencoded or application/json a stream
395
-	 * resource is returned, otherwise an array.
396
-	 *
397
-	 * @return array|string|resource The request body content or a resource to read the body stream.
398
-	 *
399
-	 * @throws \LogicException
400
-	 */
401
-	protected function getContent() {
402
-		// If the content can't be parsed into an array then return a stream resource.
403
-		if ($this->method === 'PUT'
404
-			&& $this->getHeader('Content-Length') !== 0
405
-			&& $this->getHeader('Content-Length') !== null
406
-			&& strpos($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded') === false
407
-			&& strpos($this->getHeader('Content-Type'), 'application/json') === false
408
-		) {
409
-			if ($this->content === false) {
410
-				throw new \LogicException(
411
-					'"put" can only be accessed once if not '
412
-					. 'application/x-www-form-urlencoded or application/json.'
413
-				);
414
-			}
415
-			$this->content = false;
416
-			return fopen($this->inputStream, 'rb');
417
-		} else {
418
-			$this->decodeContent();
419
-			return $this->items['parameters'];
420
-		}
421
-	}
422
-
423
-	/**
424
-	 * Attempt to decode the content and populate parameters
425
-	 */
426
-	protected function decodeContent() {
427
-		if ($this->contentDecoded) {
428
-			return;
429
-		}
430
-		$params = [];
431
-
432
-		// 'application/json' must be decoded manually.
433
-		if (strpos($this->getHeader('Content-Type'), 'application/json') !== false) {
434
-			$params = json_decode(file_get_contents($this->inputStream), true);
435
-			if($params !== null && count($params) > 0) {
436
-				$this->items['params'] = $params;
437
-				if($this->method === 'POST') {
438
-					$this->items['post'] = $params;
439
-				}
440
-			}
441
-
442
-		// Handle application/x-www-form-urlencoded for methods other than GET
443
-		// or post correctly
444
-		} elseif($this->method !== 'GET'
445
-				&& $this->method !== 'POST'
446
-				&& strpos($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded') !== false) {
447
-
448
-			parse_str(file_get_contents($this->inputStream), $params);
449
-			if(is_array($params)) {
450
-				$this->items['params'] = $params;
451
-			}
452
-		}
453
-
454
-		if (is_array($params)) {
455
-			$this->items['parameters'] = array_merge($this->items['parameters'], $params);
456
-		}
457
-		$this->contentDecoded = true;
458
-	}
459
-
460
-
461
-	/**
462
-	 * Checks if the CSRF check was correct
463
-	 * @return bool true if CSRF check passed
464
-	 */
465
-	public function passesCSRFCheck() {
466
-		if($this->csrfTokenManager === null) {
467
-			return false;
468
-		}
469
-
470
-		if(!$this->passesStrictCookieCheck()) {
471
-			return false;
472
-		}
473
-
474
-		if (isset($this->items['get']['requesttoken'])) {
475
-			$token = $this->items['get']['requesttoken'];
476
-		} elseif (isset($this->items['post']['requesttoken'])) {
477
-			$token = $this->items['post']['requesttoken'];
478
-		} elseif (isset($this->items['server']['HTTP_REQUESTTOKEN'])) {
479
-			$token = $this->items['server']['HTTP_REQUESTTOKEN'];
480
-		} else {
481
-			//no token found.
482
-			return false;
483
-		}
484
-		$token = new CsrfToken($token);
485
-
486
-		return $this->csrfTokenManager->isTokenValid($token);
487
-	}
488
-
489
-	/**
490
-	 * Whether the cookie checks are required
491
-	 *
492
-	 * @return bool
493
-	 */
494
-	private function cookieCheckRequired() {
495
-		if ($this->getHeader('OCS-APIREQUEST')) {
496
-			return false;
497
-		}
498
-		if($this->getCookie(session_name()) === null && $this->getCookie('nc_token') === null) {
499
-			return false;
500
-		}
501
-
502
-		return true;
503
-	}
504
-
505
-	/**
506
-	 * Wrapper around session_get_cookie_params
507
-	 *
508
-	 * @return array
509
-	 */
510
-	public function getCookieParams() {
511
-		return session_get_cookie_params();
512
-	}
513
-
514
-	/**
515
-	 * Appends the __Host- prefix to the cookie if applicable
516
-	 *
517
-	 * @param string $name
518
-	 * @return string
519
-	 */
520
-	protected function getProtectedCookieName($name) {
521
-		$cookieParams = $this->getCookieParams();
522
-		$prefix = '';
523
-		if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
524
-			$prefix = '__Host-';
525
-		}
526
-
527
-		return $prefix.$name;
528
-	}
529
-
530
-	/**
531
-	 * Checks if the strict cookie has been sent with the request if the request
532
-	 * is including any cookies.
533
-	 *
534
-	 * @return bool
535
-	 * @since 9.1.0
536
-	 */
537
-	public function passesStrictCookieCheck() {
538
-		if(!$this->cookieCheckRequired()) {
539
-			return true;
540
-		}
541
-
542
-		$cookieName = $this->getProtectedCookieName('nc_sameSiteCookiestrict');
543
-		if($this->getCookie($cookieName) === 'true'
544
-			&& $this->passesLaxCookieCheck()) {
545
-			return true;
546
-		}
547
-		return false;
548
-	}
549
-
550
-	/**
551
-	 * Checks if the lax cookie has been sent with the request if the request
552
-	 * is including any cookies.
553
-	 *
554
-	 * @return bool
555
-	 * @since 9.1.0
556
-	 */
557
-	public function passesLaxCookieCheck() {
558
-		if(!$this->cookieCheckRequired()) {
559
-			return true;
560
-		}
561
-
562
-		$cookieName = $this->getProtectedCookieName('nc_sameSiteCookielax');
563
-		if($this->getCookie($cookieName) === 'true') {
564
-			return true;
565
-		}
566
-		return false;
567
-	}
568
-
569
-
570
-	/**
571
-	 * Returns an ID for the request, value is not guaranteed to be unique and is mostly meant for logging
572
-	 * If `mod_unique_id` is installed this value will be taken.
573
-	 * @return string
574
-	 */
575
-	public function getId() {
576
-		if(isset($this->server['UNIQUE_ID'])) {
577
-			return $this->server['UNIQUE_ID'];
578
-		}
579
-
580
-		if(empty($this->requestId)) {
581
-			$validChars = ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS;
582
-			$this->requestId = $this->secureRandom->generate(20, $validChars);
583
-		}
584
-
585
-		return $this->requestId;
586
-	}
587
-
588
-	/**
589
-	 * Returns the remote address, if the connection came from a trusted proxy
590
-	 * and `forwarded_for_headers` has been configured then the IP address
591
-	 * specified in this header will be returned instead.
592
-	 * Do always use this instead of $_SERVER['REMOTE_ADDR']
593
-	 * @return string IP address
594
-	 */
595
-	public function getRemoteAddress() {
596
-		$remoteAddress = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
597
-		$trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
598
-
599
-		if(is_array($trustedProxies) && in_array($remoteAddress, $trustedProxies)) {
600
-			$forwardedForHeaders = $this->config->getSystemValue('forwarded_for_headers', [
601
-				'HTTP_X_FORWARDED_FOR'
602
-				// only have one default, so we cannot ship an insecure product out of the box
603
-			]);
604
-
605
-			foreach($forwardedForHeaders as $header) {
606
-				if(isset($this->server[$header])) {
607
-					foreach(explode(',', $this->server[$header]) as $IP) {
608
-						$IP = trim($IP);
609
-						if (filter_var($IP, FILTER_VALIDATE_IP) !== false) {
610
-							return $IP;
611
-						}
612
-					}
613
-				}
614
-			}
615
-		}
616
-
617
-		return $remoteAddress;
618
-	}
619
-
620
-	/**
621
-	 * Check overwrite condition
622
-	 * @param string $type
623
-	 * @return bool
624
-	 */
625
-	private function isOverwriteCondition($type = '') {
626
-		$regex = '/' . $this->config->getSystemValue('overwritecondaddr', '')  . '/';
627
-		$remoteAddr = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
628
-		return $regex === '//' || preg_match($regex, $remoteAddr) === 1
629
-		|| $type !== 'protocol';
630
-	}
631
-
632
-	/**
633
-	 * Returns the server protocol. It respects one or more reverse proxies servers
634
-	 * and load balancers
635
-	 * @return string Server protocol (http or https)
636
-	 */
637
-	public function getServerProtocol() {
638
-		if($this->config->getSystemValue('overwriteprotocol') !== ''
639
-			&& $this->isOverwriteCondition('protocol')) {
640
-			return $this->config->getSystemValue('overwriteprotocol');
641
-		}
642
-
643
-		if (isset($this->server['HTTP_X_FORWARDED_PROTO'])) {
644
-			if (strpos($this->server['HTTP_X_FORWARDED_PROTO'], ',') !== false) {
645
-				$parts = explode(',', $this->server['HTTP_X_FORWARDED_PROTO']);
646
-				$proto = strtolower(trim($parts[0]));
647
-			} else {
648
-				$proto = strtolower($this->server['HTTP_X_FORWARDED_PROTO']);
649
-			}
650
-
651
-			// Verify that the protocol is always HTTP or HTTPS
652
-			// default to http if an invalid value is provided
653
-			return $proto === 'https' ? 'https' : 'http';
654
-		}
655
-
656
-		if (isset($this->server['HTTPS'])
657
-			&& $this->server['HTTPS'] !== null
658
-			&& $this->server['HTTPS'] !== 'off'
659
-			&& $this->server['HTTPS'] !== '') {
660
-			return 'https';
661
-		}
662
-
663
-		return 'http';
664
-	}
665
-
666
-	/**
667
-	 * Returns the used HTTP protocol.
668
-	 *
669
-	 * @return string HTTP protocol. HTTP/2, HTTP/1.1 or HTTP/1.0.
670
-	 */
671
-	public function getHttpProtocol() {
672
-		$claimedProtocol = strtoupper($this->server['SERVER_PROTOCOL']);
673
-
674
-		$validProtocols = [
675
-			'HTTP/1.0',
676
-			'HTTP/1.1',
677
-			'HTTP/2',
678
-		];
679
-
680
-		if(in_array($claimedProtocol, $validProtocols, true)) {
681
-			return $claimedProtocol;
682
-		}
683
-
684
-		return 'HTTP/1.1';
685
-	}
686
-
687
-	/**
688
-	 * Returns the request uri, even if the website uses one or more
689
-	 * reverse proxies
690
-	 * @return string
691
-	 */
692
-	public function getRequestUri() {
693
-		$uri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : '';
694
-		if($this->config->getSystemValue('overwritewebroot') !== '' && $this->isOverwriteCondition()) {
695
-			$uri = $this->getScriptName() . substr($uri, strlen($this->server['SCRIPT_NAME']));
696
-		}
697
-		return $uri;
698
-	}
699
-
700
-	/**
701
-	 * Get raw PathInfo from request (not urldecoded)
702
-	 * @throws \Exception
703
-	 * @return string Path info
704
-	 */
705
-	public function getRawPathInfo() {
706
-		$requestUri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : '';
707
-		// remove too many leading slashes - can be caused by reverse proxy configuration
708
-		if (strpos($requestUri, '/') === 0) {
709
-			$requestUri = '/' . ltrim($requestUri, '/');
710
-		}
711
-
712
-		$requestUri = preg_replace('%/{2,}%', '/', $requestUri);
713
-
714
-		// Remove the query string from REQUEST_URI
715
-		if ($pos = strpos($requestUri, '?')) {
716
-			$requestUri = substr($requestUri, 0, $pos);
717
-		}
718
-
719
-		$scriptName = $this->server['SCRIPT_NAME'];
720
-		$pathInfo = $requestUri;
721
-
722
-		// strip off the script name's dir and file name
723
-		// FIXME: Sabre does not really belong here
724
-		list($path, $name) = \Sabre\Uri\split($scriptName);
725
-		if (!empty($path)) {
726
-			if($path === $pathInfo || strpos($pathInfo, $path.'/') === 0) {
727
-				$pathInfo = substr($pathInfo, strlen($path));
728
-			} else {
729
-				throw new \Exception("The requested uri($requestUri) cannot be processed by the script '$scriptName')");
730
-			}
731
-		}
732
-		if (strpos($pathInfo, '/'.$name) === 0) {
733
-			$pathInfo = substr($pathInfo, strlen($name) + 1);
734
-		}
735
-		if (strpos($pathInfo, $name) === 0) {
736
-			$pathInfo = substr($pathInfo, strlen($name));
737
-		}
738
-		if($pathInfo === false || $pathInfo === '/'){
739
-			return '';
740
-		} else {
741
-			return $pathInfo;
742
-		}
743
-	}
744
-
745
-	/**
746
-	 * Get PathInfo from request
747
-	 * @throws \Exception
748
-	 * @return string|false Path info or false when not found
749
-	 */
750
-	public function getPathInfo() {
751
-		$pathInfo = $this->getRawPathInfo();
752
-		// following is taken from \Sabre\HTTP\URLUtil::decodePathSegment
753
-		$pathInfo = rawurldecode($pathInfo);
754
-		$encoding = mb_detect_encoding($pathInfo, ['UTF-8', 'ISO-8859-1']);
755
-
756
-		switch($encoding) {
757
-			case 'ISO-8859-1' :
758
-				$pathInfo = utf8_encode($pathInfo);
759
-		}
760
-		// end copy
761
-
762
-		return $pathInfo;
763
-	}
764
-
765
-	/**
766
-	 * Returns the script name, even if the website uses one or more
767
-	 * reverse proxies
768
-	 * @return string the script name
769
-	 */
770
-	public function getScriptName() {
771
-		$name = $this->server['SCRIPT_NAME'];
772
-		$overwriteWebRoot =  $this->config->getSystemValue('overwritewebroot');
773
-		if ($overwriteWebRoot !== '' && $this->isOverwriteCondition()) {
774
-			// FIXME: This code is untestable due to __DIR__, also that hardcoded path is really dangerous
775
-			$serverRoot = str_replace('\\', '/', substr(__DIR__, 0, -strlen('lib/private/appframework/http/')));
776
-			$suburi = str_replace('\\', '/', substr(realpath($this->server['SCRIPT_FILENAME']), strlen($serverRoot)));
777
-			$name = '/' . ltrim($overwriteWebRoot . $suburi, '/');
778
-		}
779
-		return $name;
780
-	}
781
-
782
-	/**
783
-	 * Checks whether the user agent matches a given regex
784
-	 * @param array $agent array of agent names
785
-	 * @return bool true if at least one of the given agent matches, false otherwise
786
-	 */
787
-	public function isUserAgent(array $agent) {
788
-		if (!isset($this->server['HTTP_USER_AGENT'])) {
789
-			return false;
790
-		}
791
-		foreach ($agent as $regex) {
792
-			if (preg_match($regex, $this->server['HTTP_USER_AGENT'])) {
793
-				return true;
794
-			}
795
-		}
796
-		return false;
797
-	}
798
-
799
-	/**
800
-	 * Returns the unverified server host from the headers without checking
801
-	 * whether it is a trusted domain
802
-	 * @return string Server host
803
-	 */
804
-	public function getInsecureServerHost() {
805
-		$host = 'localhost';
806
-		if (isset($this->server['HTTP_X_FORWARDED_HOST'])) {
807
-			if (strpos($this->server['HTTP_X_FORWARDED_HOST'], ',') !== false) {
808
-				$parts = explode(',', $this->server['HTTP_X_FORWARDED_HOST']);
809
-				$host = trim(current($parts));
810
-			} else {
811
-				$host = $this->server['HTTP_X_FORWARDED_HOST'];
812
-			}
813
-		} else {
814
-			if (isset($this->server['HTTP_HOST'])) {
815
-				$host = $this->server['HTTP_HOST'];
816
-			} else if (isset($this->server['SERVER_NAME'])) {
817
-				$host = $this->server['SERVER_NAME'];
818
-			}
819
-		}
820
-		return $host;
821
-	}
822
-
823
-
824
-	/**
825
-	 * Returns the server host from the headers, or the first configured
826
-	 * trusted domain if the host isn't in the trusted list
827
-	 * @return string Server host
828
-	 */
829
-	public function getServerHost() {
830
-		// overwritehost is always trusted
831
-		$host = $this->getOverwriteHost();
832
-		if ($host !== null) {
833
-			return $host;
834
-		}
835
-
836
-		// get the host from the headers
837
-		$host = $this->getInsecureServerHost();
838
-
839
-		// Verify that the host is a trusted domain if the trusted domains
840
-		// are defined
841
-		// If no trusted domain is provided the first trusted domain is returned
842
-		$trustedDomainHelper = new TrustedDomainHelper($this->config);
843
-		if ($trustedDomainHelper->isTrustedDomain($host)) {
844
-			return $host;
845
-		} else {
846
-			$trustedList = $this->config->getSystemValue('trusted_domains', []);
847
-			if(!empty($trustedList)) {
848
-				return $trustedList[0];
849
-			} else {
850
-				return '';
851
-			}
852
-		}
853
-	}
854
-
855
-	/**
856
-	 * Returns the overwritehost setting from the config if set and
857
-	 * if the overwrite condition is met
858
-	 * @return string|null overwritehost value or null if not defined or the defined condition
859
-	 * isn't met
860
-	 */
861
-	private function getOverwriteHost() {
862
-		if($this->config->getSystemValue('overwritehost') !== '' && $this->isOverwriteCondition()) {
863
-			return $this->config->getSystemValue('overwritehost');
864
-		}
865
-		return null;
866
-	}
58
+    const USER_AGENT_IE = '/(MSIE)|(Trident)/';
59
+    // Microsoft Edge User Agent from https://msdn.microsoft.com/en-us/library/hh869301(v=vs.85).aspx
60
+    const USER_AGENT_MS_EDGE = '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\) Chrome\/[0-9.]+ (Mobile Safari|Safari)\/[0-9.]+ Edge\/[0-9.]+$/';
61
+    // Firefox User Agent from https://developer.mozilla.org/en-US/docs/Web/HTTP/Gecko_user_agent_string_reference
62
+    const USER_AGENT_FIREFOX = '/^Mozilla\/5\.0 \([^)]+\) Gecko\/[0-9.]+ Firefox\/[0-9.]+$/';
63
+    // Chrome User Agent from https://developer.chrome.com/multidevice/user-agent
64
+    const USER_AGENT_CHROME = '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\)( Ubuntu Chromium\/[0-9.]+|) Chrome\/[0-9.]+ (Mobile Safari|Safari)\/[0-9.]+$/';
65
+    // Safari User Agent from http://www.useragentstring.com/pages/Safari/
66
+    const USER_AGENT_SAFARI = '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\) Version\/[0-9.]+ Safari\/[0-9.A-Z]+$/';
67
+    // Android Chrome user agent: https://developers.google.com/chrome/mobile/docs/user-agent
68
+    const USER_AGENT_ANDROID_MOBILE_CHROME = '#Android.*Chrome/[.0-9]*#';
69
+    const USER_AGENT_FREEBOX = '#^Mozilla/5\.0$#';
70
+    const REGEX_LOCALHOST = '/^(127\.0\.0\.1|localhost|::1)$/';
71
+
72
+    /**
73
+     * @deprecated use \OCP\IRequest::USER_AGENT_CLIENT_IOS instead
74
+     */
75
+    const USER_AGENT_OWNCLOUD_IOS = '/^Mozilla\/5\.0 \(iOS\) (ownCloud|Nextcloud)\-iOS.*$/';
76
+    /**
77
+     * @deprecated use \OCP\IRequest::USER_AGENT_CLIENT_ANDROID instead
78
+     */
79
+    const USER_AGENT_OWNCLOUD_ANDROID = '/^Mozilla\/5\.0 \(Android\) ownCloud\-android.*$/';
80
+    /**
81
+     * @deprecated use \OCP\IRequest::USER_AGENT_CLIENT_DESKTOP instead
82
+     */
83
+    const USER_AGENT_OWNCLOUD_DESKTOP = '/^Mozilla\/5\.0 \([A-Za-z ]+\) (mirall|csyncoC)\/.*$/';
84
+
85
+    protected $inputStream;
86
+    protected $content;
87
+    protected $items = array();
88
+    protected $allowedKeys = array(
89
+        'get',
90
+        'post',
91
+        'files',
92
+        'server',
93
+        'env',
94
+        'cookies',
95
+        'urlParams',
96
+        'parameters',
97
+        'method',
98
+        'requesttoken',
99
+    );
100
+    /** @var ISecureRandom */
101
+    protected $secureRandom;
102
+    /** @var IConfig */
103
+    protected $config;
104
+    /** @var string */
105
+    protected $requestId = '';
106
+    /** @var ICrypto */
107
+    protected $crypto;
108
+    /** @var CsrfTokenManager|null */
109
+    protected $csrfTokenManager;
110
+
111
+    /** @var bool */
112
+    protected $contentDecoded = false;
113
+
114
+    /**
115
+     * @param array $vars An associative array with the following optional values:
116
+     *        - array 'urlParams' the parameters which were matched from the URL
117
+     *        - array 'get' the $_GET array
118
+     *        - array|string 'post' the $_POST array or JSON string
119
+     *        - array 'files' the $_FILES array
120
+     *        - array 'server' the $_SERVER array
121
+     *        - array 'env' the $_ENV array
122
+     *        - array 'cookies' the $_COOKIE array
123
+     *        - string 'method' the request method (GET, POST etc)
124
+     *        - string|false 'requesttoken' the requesttoken or false when not available
125
+     * @param ISecureRandom $secureRandom
126
+     * @param IConfig $config
127
+     * @param CsrfTokenManager|null $csrfTokenManager
128
+     * @param string $stream
129
+     * @see http://www.php.net/manual/en/reserved.variables.php
130
+     */
131
+    public function __construct(array $vars=array(),
132
+                                ISecureRandom $secureRandom = null,
133
+                                IConfig $config,
134
+                                CsrfTokenManager $csrfTokenManager = null,
135
+                                $stream = 'php://input') {
136
+        $this->inputStream = $stream;
137
+        $this->items['params'] = array();
138
+        $this->secureRandom = $secureRandom;
139
+        $this->config = $config;
140
+        $this->csrfTokenManager = $csrfTokenManager;
141
+
142
+        if(!array_key_exists('method', $vars)) {
143
+            $vars['method'] = 'GET';
144
+        }
145
+
146
+        foreach($this->allowedKeys as $name) {
147
+            $this->items[$name] = isset($vars[$name])
148
+                ? $vars[$name]
149
+                : array();
150
+        }
151
+
152
+        $this->items['parameters'] = array_merge(
153
+            $this->items['get'],
154
+            $this->items['post'],
155
+            $this->items['urlParams'],
156
+            $this->items['params']
157
+        );
158
+
159
+    }
160
+    /**
161
+     * @param array $parameters
162
+     */
163
+    public function setUrlParameters(array $parameters) {
164
+        $this->items['urlParams'] = $parameters;
165
+        $this->items['parameters'] = array_merge(
166
+            $this->items['parameters'],
167
+            $this->items['urlParams']
168
+        );
169
+    }
170
+
171
+    /**
172
+     * Countable method
173
+     * @return int
174
+     */
175
+    public function count() {
176
+        return count(array_keys($this->items['parameters']));
177
+    }
178
+
179
+    /**
180
+     * ArrayAccess methods
181
+     *
182
+     * Gives access to the combined GET, POST and urlParams arrays
183
+     *
184
+     * Examples:
185
+     *
186
+     * $var = $request['myvar'];
187
+     *
188
+     * or
189
+     *
190
+     * if(!isset($request['myvar']) {
191
+     * 	// Do something
192
+     * }
193
+     *
194
+     * $request['myvar'] = 'something'; // This throws an exception.
195
+     *
196
+     * @param string $offset The key to lookup
197
+     * @return boolean
198
+     */
199
+    public function offsetExists($offset) {
200
+        return isset($this->items['parameters'][$offset]);
201
+    }
202
+
203
+    /**
204
+     * @see offsetExists
205
+     */
206
+    public function offsetGet($offset) {
207
+        return isset($this->items['parameters'][$offset])
208
+            ? $this->items['parameters'][$offset]
209
+            : null;
210
+    }
211
+
212
+    /**
213
+     * @see offsetExists
214
+     */
215
+    public function offsetSet($offset, $value) {
216
+        throw new \RuntimeException('You cannot change the contents of the request object');
217
+    }
218
+
219
+    /**
220
+     * @see offsetExists
221
+     */
222
+    public function offsetUnset($offset) {
223
+        throw new \RuntimeException('You cannot change the contents of the request object');
224
+    }
225
+
226
+    /**
227
+     * Magic property accessors
228
+     * @param string $name
229
+     * @param mixed $value
230
+     */
231
+    public function __set($name, $value) {
232
+        throw new \RuntimeException('You cannot change the contents of the request object');
233
+    }
234
+
235
+    /**
236
+     * Access request variables by method and name.
237
+     * Examples:
238
+     *
239
+     * $request->post['myvar']; // Only look for POST variables
240
+     * $request->myvar; or $request->{'myvar'}; or $request->{$myvar}
241
+     * Looks in the combined GET, POST and urlParams array.
242
+     *
243
+     * If you access e.g. ->post but the current HTTP request method
244
+     * is GET a \LogicException will be thrown.
245
+     *
246
+     * @param string $name The key to look for.
247
+     * @throws \LogicException
248
+     * @return mixed|null
249
+     */
250
+    public function __get($name) {
251
+        switch($name) {
252
+            case 'put':
253
+            case 'patch':
254
+            case 'get':
255
+            case 'post':
256
+                if($this->method !== strtoupper($name)) {
257
+                    throw new \LogicException(sprintf('%s cannot be accessed in a %s request.', $name, $this->method));
258
+                }
259
+                return $this->getContent();
260
+            case 'files':
261
+            case 'server':
262
+            case 'env':
263
+            case 'cookies':
264
+            case 'urlParams':
265
+            case 'method':
266
+                return isset($this->items[$name])
267
+                    ? $this->items[$name]
268
+                    : null;
269
+            case 'parameters':
270
+            case 'params':
271
+                return $this->getContent();
272
+            default;
273
+                return isset($this[$name])
274
+                    ? $this[$name]
275
+                    : null;
276
+        }
277
+    }
278
+
279
+    /**
280
+     * @param string $name
281
+     * @return bool
282
+     */
283
+    public function __isset($name) {
284
+        if (in_array($name, $this->allowedKeys, true)) {
285
+            return true;
286
+        }
287
+        return isset($this->items['parameters'][$name]);
288
+    }
289
+
290
+    /**
291
+     * @param string $id
292
+     */
293
+    public function __unset($id) {
294
+        throw new \RuntimeException('You cannot change the contents of the request object');
295
+    }
296
+
297
+    /**
298
+     * Returns the value for a specific http header.
299
+     *
300
+     * This method returns null if the header did not exist.
301
+     *
302
+     * @param string $name
303
+     * @return string
304
+     */
305
+    public function getHeader($name) {
306
+
307
+        $name = strtoupper(str_replace(array('-'),array('_'),$name));
308
+        if (isset($this->server['HTTP_' . $name])) {
309
+            return $this->server['HTTP_' . $name];
310
+        }
311
+
312
+        // There's a few headers that seem to end up in the top-level
313
+        // server array.
314
+        switch($name) {
315
+            case 'CONTENT_TYPE' :
316
+            case 'CONTENT_LENGTH' :
317
+                if (isset($this->server[$name])) {
318
+                    return $this->server[$name];
319
+                }
320
+                break;
321
+
322
+        }
323
+
324
+        return null;
325
+    }
326
+
327
+    /**
328
+     * Lets you access post and get parameters by the index
329
+     * In case of json requests the encoded json body is accessed
330
+     *
331
+     * @param string $key the key which you want to access in the URL Parameter
332
+     *                     placeholder, $_POST or $_GET array.
333
+     *                     The priority how they're returned is the following:
334
+     *                     1. URL parameters
335
+     *                     2. POST parameters
336
+     *                     3. GET parameters
337
+     * @param mixed $default If the key is not found, this value will be returned
338
+     * @return mixed the content of the array
339
+     */
340
+    public function getParam($key, $default = null) {
341
+        return isset($this->parameters[$key])
342
+            ? $this->parameters[$key]
343
+            : $default;
344
+    }
345
+
346
+    /**
347
+     * Returns all params that were received, be it from the request
348
+     * (as GET or POST) or throuh the URL by the route
349
+     * @return array the array with all parameters
350
+     */
351
+    public function getParams() {
352
+        return $this->parameters;
353
+    }
354
+
355
+    /**
356
+     * Returns the method of the request
357
+     * @return string the method of the request (POST, GET, etc)
358
+     */
359
+    public function getMethod() {
360
+        return $this->method;
361
+    }
362
+
363
+    /**
364
+     * Shortcut for accessing an uploaded file through the $_FILES array
365
+     * @param string $key the key that will be taken from the $_FILES array
366
+     * @return array the file in the $_FILES element
367
+     */
368
+    public function getUploadedFile($key) {
369
+        return isset($this->files[$key]) ? $this->files[$key] : null;
370
+    }
371
+
372
+    /**
373
+     * Shortcut for getting env variables
374
+     * @param string $key the key that will be taken from the $_ENV array
375
+     * @return array the value in the $_ENV element
376
+     */
377
+    public function getEnv($key) {
378
+        return isset($this->env[$key]) ? $this->env[$key] : null;
379
+    }
380
+
381
+    /**
382
+     * Shortcut for getting cookie variables
383
+     * @param string $key the key that will be taken from the $_COOKIE array
384
+     * @return string the value in the $_COOKIE element
385
+     */
386
+    public function getCookie($key) {
387
+        return isset($this->cookies[$key]) ? $this->cookies[$key] : null;
388
+    }
389
+
390
+    /**
391
+     * Returns the request body content.
392
+     *
393
+     * If the HTTP request method is PUT and the body
394
+     * not application/x-www-form-urlencoded or application/json a stream
395
+     * resource is returned, otherwise an array.
396
+     *
397
+     * @return array|string|resource The request body content or a resource to read the body stream.
398
+     *
399
+     * @throws \LogicException
400
+     */
401
+    protected function getContent() {
402
+        // If the content can't be parsed into an array then return a stream resource.
403
+        if ($this->method === 'PUT'
404
+            && $this->getHeader('Content-Length') !== 0
405
+            && $this->getHeader('Content-Length') !== null
406
+            && strpos($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded') === false
407
+            && strpos($this->getHeader('Content-Type'), 'application/json') === false
408
+        ) {
409
+            if ($this->content === false) {
410
+                throw new \LogicException(
411
+                    '"put" can only be accessed once if not '
412
+                    . 'application/x-www-form-urlencoded or application/json.'
413
+                );
414
+            }
415
+            $this->content = false;
416
+            return fopen($this->inputStream, 'rb');
417
+        } else {
418
+            $this->decodeContent();
419
+            return $this->items['parameters'];
420
+        }
421
+    }
422
+
423
+    /**
424
+     * Attempt to decode the content and populate parameters
425
+     */
426
+    protected function decodeContent() {
427
+        if ($this->contentDecoded) {
428
+            return;
429
+        }
430
+        $params = [];
431
+
432
+        // 'application/json' must be decoded manually.
433
+        if (strpos($this->getHeader('Content-Type'), 'application/json') !== false) {
434
+            $params = json_decode(file_get_contents($this->inputStream), true);
435
+            if($params !== null && count($params) > 0) {
436
+                $this->items['params'] = $params;
437
+                if($this->method === 'POST') {
438
+                    $this->items['post'] = $params;
439
+                }
440
+            }
441
+
442
+        // Handle application/x-www-form-urlencoded for methods other than GET
443
+        // or post correctly
444
+        } elseif($this->method !== 'GET'
445
+                && $this->method !== 'POST'
446
+                && strpos($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded') !== false) {
447
+
448
+            parse_str(file_get_contents($this->inputStream), $params);
449
+            if(is_array($params)) {
450
+                $this->items['params'] = $params;
451
+            }
452
+        }
453
+
454
+        if (is_array($params)) {
455
+            $this->items['parameters'] = array_merge($this->items['parameters'], $params);
456
+        }
457
+        $this->contentDecoded = true;
458
+    }
459
+
460
+
461
+    /**
462
+     * Checks if the CSRF check was correct
463
+     * @return bool true if CSRF check passed
464
+     */
465
+    public function passesCSRFCheck() {
466
+        if($this->csrfTokenManager === null) {
467
+            return false;
468
+        }
469
+
470
+        if(!$this->passesStrictCookieCheck()) {
471
+            return false;
472
+        }
473
+
474
+        if (isset($this->items['get']['requesttoken'])) {
475
+            $token = $this->items['get']['requesttoken'];
476
+        } elseif (isset($this->items['post']['requesttoken'])) {
477
+            $token = $this->items['post']['requesttoken'];
478
+        } elseif (isset($this->items['server']['HTTP_REQUESTTOKEN'])) {
479
+            $token = $this->items['server']['HTTP_REQUESTTOKEN'];
480
+        } else {
481
+            //no token found.
482
+            return false;
483
+        }
484
+        $token = new CsrfToken($token);
485
+
486
+        return $this->csrfTokenManager->isTokenValid($token);
487
+    }
488
+
489
+    /**
490
+     * Whether the cookie checks are required
491
+     *
492
+     * @return bool
493
+     */
494
+    private function cookieCheckRequired() {
495
+        if ($this->getHeader('OCS-APIREQUEST')) {
496
+            return false;
497
+        }
498
+        if($this->getCookie(session_name()) === null && $this->getCookie('nc_token') === null) {
499
+            return false;
500
+        }
501
+
502
+        return true;
503
+    }
504
+
505
+    /**
506
+     * Wrapper around session_get_cookie_params
507
+     *
508
+     * @return array
509
+     */
510
+    public function getCookieParams() {
511
+        return session_get_cookie_params();
512
+    }
513
+
514
+    /**
515
+     * Appends the __Host- prefix to the cookie if applicable
516
+     *
517
+     * @param string $name
518
+     * @return string
519
+     */
520
+    protected function getProtectedCookieName($name) {
521
+        $cookieParams = $this->getCookieParams();
522
+        $prefix = '';
523
+        if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
524
+            $prefix = '__Host-';
525
+        }
526
+
527
+        return $prefix.$name;
528
+    }
529
+
530
+    /**
531
+     * Checks if the strict cookie has been sent with the request if the request
532
+     * is including any cookies.
533
+     *
534
+     * @return bool
535
+     * @since 9.1.0
536
+     */
537
+    public function passesStrictCookieCheck() {
538
+        if(!$this->cookieCheckRequired()) {
539
+            return true;
540
+        }
541
+
542
+        $cookieName = $this->getProtectedCookieName('nc_sameSiteCookiestrict');
543
+        if($this->getCookie($cookieName) === 'true'
544
+            && $this->passesLaxCookieCheck()) {
545
+            return true;
546
+        }
547
+        return false;
548
+    }
549
+
550
+    /**
551
+     * Checks if the lax cookie has been sent with the request if the request
552
+     * is including any cookies.
553
+     *
554
+     * @return bool
555
+     * @since 9.1.0
556
+     */
557
+    public function passesLaxCookieCheck() {
558
+        if(!$this->cookieCheckRequired()) {
559
+            return true;
560
+        }
561
+
562
+        $cookieName = $this->getProtectedCookieName('nc_sameSiteCookielax');
563
+        if($this->getCookie($cookieName) === 'true') {
564
+            return true;
565
+        }
566
+        return false;
567
+    }
568
+
569
+
570
+    /**
571
+     * Returns an ID for the request, value is not guaranteed to be unique and is mostly meant for logging
572
+     * If `mod_unique_id` is installed this value will be taken.
573
+     * @return string
574
+     */
575
+    public function getId() {
576
+        if(isset($this->server['UNIQUE_ID'])) {
577
+            return $this->server['UNIQUE_ID'];
578
+        }
579
+
580
+        if(empty($this->requestId)) {
581
+            $validChars = ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS;
582
+            $this->requestId = $this->secureRandom->generate(20, $validChars);
583
+        }
584
+
585
+        return $this->requestId;
586
+    }
587
+
588
+    /**
589
+     * Returns the remote address, if the connection came from a trusted proxy
590
+     * and `forwarded_for_headers` has been configured then the IP address
591
+     * specified in this header will be returned instead.
592
+     * Do always use this instead of $_SERVER['REMOTE_ADDR']
593
+     * @return string IP address
594
+     */
595
+    public function getRemoteAddress() {
596
+        $remoteAddress = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
597
+        $trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
598
+
599
+        if(is_array($trustedProxies) && in_array($remoteAddress, $trustedProxies)) {
600
+            $forwardedForHeaders = $this->config->getSystemValue('forwarded_for_headers', [
601
+                'HTTP_X_FORWARDED_FOR'
602
+                // only have one default, so we cannot ship an insecure product out of the box
603
+            ]);
604
+
605
+            foreach($forwardedForHeaders as $header) {
606
+                if(isset($this->server[$header])) {
607
+                    foreach(explode(',', $this->server[$header]) as $IP) {
608
+                        $IP = trim($IP);
609
+                        if (filter_var($IP, FILTER_VALIDATE_IP) !== false) {
610
+                            return $IP;
611
+                        }
612
+                    }
613
+                }
614
+            }
615
+        }
616
+
617
+        return $remoteAddress;
618
+    }
619
+
620
+    /**
621
+     * Check overwrite condition
622
+     * @param string $type
623
+     * @return bool
624
+     */
625
+    private function isOverwriteCondition($type = '') {
626
+        $regex = '/' . $this->config->getSystemValue('overwritecondaddr', '')  . '/';
627
+        $remoteAddr = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
628
+        return $regex === '//' || preg_match($regex, $remoteAddr) === 1
629
+        || $type !== 'protocol';
630
+    }
631
+
632
+    /**
633
+     * Returns the server protocol. It respects one or more reverse proxies servers
634
+     * and load balancers
635
+     * @return string Server protocol (http or https)
636
+     */
637
+    public function getServerProtocol() {
638
+        if($this->config->getSystemValue('overwriteprotocol') !== ''
639
+            && $this->isOverwriteCondition('protocol')) {
640
+            return $this->config->getSystemValue('overwriteprotocol');
641
+        }
642
+
643
+        if (isset($this->server['HTTP_X_FORWARDED_PROTO'])) {
644
+            if (strpos($this->server['HTTP_X_FORWARDED_PROTO'], ',') !== false) {
645
+                $parts = explode(',', $this->server['HTTP_X_FORWARDED_PROTO']);
646
+                $proto = strtolower(trim($parts[0]));
647
+            } else {
648
+                $proto = strtolower($this->server['HTTP_X_FORWARDED_PROTO']);
649
+            }
650
+
651
+            // Verify that the protocol is always HTTP or HTTPS
652
+            // default to http if an invalid value is provided
653
+            return $proto === 'https' ? 'https' : 'http';
654
+        }
655
+
656
+        if (isset($this->server['HTTPS'])
657
+            && $this->server['HTTPS'] !== null
658
+            && $this->server['HTTPS'] !== 'off'
659
+            && $this->server['HTTPS'] !== '') {
660
+            return 'https';
661
+        }
662
+
663
+        return 'http';
664
+    }
665
+
666
+    /**
667
+     * Returns the used HTTP protocol.
668
+     *
669
+     * @return string HTTP protocol. HTTP/2, HTTP/1.1 or HTTP/1.0.
670
+     */
671
+    public function getHttpProtocol() {
672
+        $claimedProtocol = strtoupper($this->server['SERVER_PROTOCOL']);
673
+
674
+        $validProtocols = [
675
+            'HTTP/1.0',
676
+            'HTTP/1.1',
677
+            'HTTP/2',
678
+        ];
679
+
680
+        if(in_array($claimedProtocol, $validProtocols, true)) {
681
+            return $claimedProtocol;
682
+        }
683
+
684
+        return 'HTTP/1.1';
685
+    }
686
+
687
+    /**
688
+     * Returns the request uri, even if the website uses one or more
689
+     * reverse proxies
690
+     * @return string
691
+     */
692
+    public function getRequestUri() {
693
+        $uri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : '';
694
+        if($this->config->getSystemValue('overwritewebroot') !== '' && $this->isOverwriteCondition()) {
695
+            $uri = $this->getScriptName() . substr($uri, strlen($this->server['SCRIPT_NAME']));
696
+        }
697
+        return $uri;
698
+    }
699
+
700
+    /**
701
+     * Get raw PathInfo from request (not urldecoded)
702
+     * @throws \Exception
703
+     * @return string Path info
704
+     */
705
+    public function getRawPathInfo() {
706
+        $requestUri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : '';
707
+        // remove too many leading slashes - can be caused by reverse proxy configuration
708
+        if (strpos($requestUri, '/') === 0) {
709
+            $requestUri = '/' . ltrim($requestUri, '/');
710
+        }
711
+
712
+        $requestUri = preg_replace('%/{2,}%', '/', $requestUri);
713
+
714
+        // Remove the query string from REQUEST_URI
715
+        if ($pos = strpos($requestUri, '?')) {
716
+            $requestUri = substr($requestUri, 0, $pos);
717
+        }
718
+
719
+        $scriptName = $this->server['SCRIPT_NAME'];
720
+        $pathInfo = $requestUri;
721
+
722
+        // strip off the script name's dir and file name
723
+        // FIXME: Sabre does not really belong here
724
+        list($path, $name) = \Sabre\Uri\split($scriptName);
725
+        if (!empty($path)) {
726
+            if($path === $pathInfo || strpos($pathInfo, $path.'/') === 0) {
727
+                $pathInfo = substr($pathInfo, strlen($path));
728
+            } else {
729
+                throw new \Exception("The requested uri($requestUri) cannot be processed by the script '$scriptName')");
730
+            }
731
+        }
732
+        if (strpos($pathInfo, '/'.$name) === 0) {
733
+            $pathInfo = substr($pathInfo, strlen($name) + 1);
734
+        }
735
+        if (strpos($pathInfo, $name) === 0) {
736
+            $pathInfo = substr($pathInfo, strlen($name));
737
+        }
738
+        if($pathInfo === false || $pathInfo === '/'){
739
+            return '';
740
+        } else {
741
+            return $pathInfo;
742
+        }
743
+    }
744
+
745
+    /**
746
+     * Get PathInfo from request
747
+     * @throws \Exception
748
+     * @return string|false Path info or false when not found
749
+     */
750
+    public function getPathInfo() {
751
+        $pathInfo = $this->getRawPathInfo();
752
+        // following is taken from \Sabre\HTTP\URLUtil::decodePathSegment
753
+        $pathInfo = rawurldecode($pathInfo);
754
+        $encoding = mb_detect_encoding($pathInfo, ['UTF-8', 'ISO-8859-1']);
755
+
756
+        switch($encoding) {
757
+            case 'ISO-8859-1' :
758
+                $pathInfo = utf8_encode($pathInfo);
759
+        }
760
+        // end copy
761
+
762
+        return $pathInfo;
763
+    }
764
+
765
+    /**
766
+     * Returns the script name, even if the website uses one or more
767
+     * reverse proxies
768
+     * @return string the script name
769
+     */
770
+    public function getScriptName() {
771
+        $name = $this->server['SCRIPT_NAME'];
772
+        $overwriteWebRoot =  $this->config->getSystemValue('overwritewebroot');
773
+        if ($overwriteWebRoot !== '' && $this->isOverwriteCondition()) {
774
+            // FIXME: This code is untestable due to __DIR__, also that hardcoded path is really dangerous
775
+            $serverRoot = str_replace('\\', '/', substr(__DIR__, 0, -strlen('lib/private/appframework/http/')));
776
+            $suburi = str_replace('\\', '/', substr(realpath($this->server['SCRIPT_FILENAME']), strlen($serverRoot)));
777
+            $name = '/' . ltrim($overwriteWebRoot . $suburi, '/');
778
+        }
779
+        return $name;
780
+    }
781
+
782
+    /**
783
+     * Checks whether the user agent matches a given regex
784
+     * @param array $agent array of agent names
785
+     * @return bool true if at least one of the given agent matches, false otherwise
786
+     */
787
+    public function isUserAgent(array $agent) {
788
+        if (!isset($this->server['HTTP_USER_AGENT'])) {
789
+            return false;
790
+        }
791
+        foreach ($agent as $regex) {
792
+            if (preg_match($regex, $this->server['HTTP_USER_AGENT'])) {
793
+                return true;
794
+            }
795
+        }
796
+        return false;
797
+    }
798
+
799
+    /**
800
+     * Returns the unverified server host from the headers without checking
801
+     * whether it is a trusted domain
802
+     * @return string Server host
803
+     */
804
+    public function getInsecureServerHost() {
805
+        $host = 'localhost';
806
+        if (isset($this->server['HTTP_X_FORWARDED_HOST'])) {
807
+            if (strpos($this->server['HTTP_X_FORWARDED_HOST'], ',') !== false) {
808
+                $parts = explode(',', $this->server['HTTP_X_FORWARDED_HOST']);
809
+                $host = trim(current($parts));
810
+            } else {
811
+                $host = $this->server['HTTP_X_FORWARDED_HOST'];
812
+            }
813
+        } else {
814
+            if (isset($this->server['HTTP_HOST'])) {
815
+                $host = $this->server['HTTP_HOST'];
816
+            } else if (isset($this->server['SERVER_NAME'])) {
817
+                $host = $this->server['SERVER_NAME'];
818
+            }
819
+        }
820
+        return $host;
821
+    }
822
+
823
+
824
+    /**
825
+     * Returns the server host from the headers, or the first configured
826
+     * trusted domain if the host isn't in the trusted list
827
+     * @return string Server host
828
+     */
829
+    public function getServerHost() {
830
+        // overwritehost is always trusted
831
+        $host = $this->getOverwriteHost();
832
+        if ($host !== null) {
833
+            return $host;
834
+        }
835
+
836
+        // get the host from the headers
837
+        $host = $this->getInsecureServerHost();
838
+
839
+        // Verify that the host is a trusted domain if the trusted domains
840
+        // are defined
841
+        // If no trusted domain is provided the first trusted domain is returned
842
+        $trustedDomainHelper = new TrustedDomainHelper($this->config);
843
+        if ($trustedDomainHelper->isTrustedDomain($host)) {
844
+            return $host;
845
+        } else {
846
+            $trustedList = $this->config->getSystemValue('trusted_domains', []);
847
+            if(!empty($trustedList)) {
848
+                return $trustedList[0];
849
+            } else {
850
+                return '';
851
+            }
852
+        }
853
+    }
854
+
855
+    /**
856
+     * Returns the overwritehost setting from the config if set and
857
+     * if the overwrite condition is met
858
+     * @return string|null overwritehost value or null if not defined or the defined condition
859
+     * isn't met
860
+     */
861
+    private function getOverwriteHost() {
862
+        if($this->config->getSystemValue('overwritehost') !== '' && $this->isOverwriteCondition()) {
863
+            return $this->config->getSystemValue('overwritehost');
864
+        }
865
+        return null;
866
+    }
867 867
 
868 868
 }
Please login to merge, or discard this patch.
lib/private/AppFramework/Middleware/Security/SameSiteCookieMiddleware.php 2 patches
Indentation   +72 added lines, -72 removed lines patch added patch discarded remove patch
@@ -31,76 +31,76 @@
 block discarded – undo
31 31
 
32 32
 class SameSiteCookieMiddleware extends Middleware {
33 33
 
34
-	/** @var Request */
35
-	private $request;
36
-
37
-	/** @var ControllerMethodReflector */
38
-	private $reflector;
39
-
40
-	public function __construct(Request $request,
41
-								ControllerMethodReflector $reflector) {
42
-		$this->request = $request;
43
-		$this->reflector = $reflector;
44
-	}
45
-
46
-	public function beforeController($controller, $methodName) {
47
-		$requestUri = $this->request->getScriptName();
48
-		$processingScript = explode('/', $requestUri);
49
-		$processingScript = $processingScript[count($processingScript)-1];
50
-
51
-		if ($processingScript !== 'index.php') {
52
-			return;
53
-		}
54
-
55
-		$noSSC = $this->reflector->hasAnnotation('NoSameSiteCookieRequired');
56
-		if ($noSSC) {
57
-			return;
58
-		}
59
-
60
-		if (!$this->request->passesLaxCookieCheck()) {
61
-			throw new LaxSameSiteCookieFailedException();
62
-		}
63
-	}
64
-
65
-	public function afterException($controller, $methodName, \Exception $exception) {
66
-		if ($exception instanceof LaxSameSiteCookieFailedException) {
67
-			$respone = new Response();
68
-			$respone->setStatus(Http::STATUS_FOUND);
69
-			$respone->addHeader('Location', $this->request->getRequestUri());
70
-
71
-			$this->setSameSiteCookie();
72
-
73
-			return $respone;
74
-		}
75
-
76
-		throw $exception;
77
-	}
78
-
79
-	protected function setSameSiteCookie() {
80
-		$cookieParams = $this->request->getCookieParams();
81
-		$secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
82
-		$policies = [
83
-			'lax',
84
-			'strict',
85
-		];
86
-
87
-		// Append __Host to the cookie if it meets the requirements
88
-		$cookiePrefix = '';
89
-		if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
90
-			$cookiePrefix = '__Host-';
91
-		}
92
-
93
-		foreach($policies as $policy) {
94
-			header(
95
-				sprintf(
96
-					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
97
-					$cookiePrefix,
98
-					$policy,
99
-					$cookieParams['path'],
100
-					$policy
101
-				),
102
-				false
103
-			);
104
-		}
105
-	}
34
+    /** @var Request */
35
+    private $request;
36
+
37
+    /** @var ControllerMethodReflector */
38
+    private $reflector;
39
+
40
+    public function __construct(Request $request,
41
+                                ControllerMethodReflector $reflector) {
42
+        $this->request = $request;
43
+        $this->reflector = $reflector;
44
+    }
45
+
46
+    public function beforeController($controller, $methodName) {
47
+        $requestUri = $this->request->getScriptName();
48
+        $processingScript = explode('/', $requestUri);
49
+        $processingScript = $processingScript[count($processingScript)-1];
50
+
51
+        if ($processingScript !== 'index.php') {
52
+            return;
53
+        }
54
+
55
+        $noSSC = $this->reflector->hasAnnotation('NoSameSiteCookieRequired');
56
+        if ($noSSC) {
57
+            return;
58
+        }
59
+
60
+        if (!$this->request->passesLaxCookieCheck()) {
61
+            throw new LaxSameSiteCookieFailedException();
62
+        }
63
+    }
64
+
65
+    public function afterException($controller, $methodName, \Exception $exception) {
66
+        if ($exception instanceof LaxSameSiteCookieFailedException) {
67
+            $respone = new Response();
68
+            $respone->setStatus(Http::STATUS_FOUND);
69
+            $respone->addHeader('Location', $this->request->getRequestUri());
70
+
71
+            $this->setSameSiteCookie();
72
+
73
+            return $respone;
74
+        }
75
+
76
+        throw $exception;
77
+    }
78
+
79
+    protected function setSameSiteCookie() {
80
+        $cookieParams = $this->request->getCookieParams();
81
+        $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
82
+        $policies = [
83
+            'lax',
84
+            'strict',
85
+        ];
86
+
87
+        // Append __Host to the cookie if it meets the requirements
88
+        $cookiePrefix = '';
89
+        if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
90
+            $cookiePrefix = '__Host-';
91
+        }
92
+
93
+        foreach($policies as $policy) {
94
+            header(
95
+                sprintf(
96
+                    'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
97
+                    $cookiePrefix,
98
+                    $policy,
99
+                    $cookieParams['path'],
100
+                    $policy
101
+                ),
102
+                false
103
+            );
104
+        }
105
+    }
106 106
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -46,7 +46,7 @@  discard block
 block discarded – undo
46 46
 	public function beforeController($controller, $methodName) {
47 47
 		$requestUri = $this->request->getScriptName();
48 48
 		$processingScript = explode('/', $requestUri);
49
-		$processingScript = $processingScript[count($processingScript)-1];
49
+		$processingScript = $processingScript[count($processingScript) - 1];
50 50
 
51 51
 		if ($processingScript !== 'index.php') {
52 52
 			return;
@@ -86,14 +86,14 @@  discard block
 block discarded – undo
86 86
 
87 87
 		// Append __Host to the cookie if it meets the requirements
88 88
 		$cookiePrefix = '';
89
-		if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
89
+		if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
90 90
 			$cookiePrefix = '__Host-';
91 91
 		}
92 92
 
93
-		foreach($policies as $policy) {
93
+		foreach ($policies as $policy) {
94 94
 			header(
95 95
 				sprintf(
96
-					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
96
+					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;'.$secureCookie.'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
97 97
 					$cookiePrefix,
98 98
 					$policy,
99 99
 					$cookieParams['path'],
Please login to merge, or discard this patch.
lib/base.php 2 patches
Indentation   +1018 added lines, -1018 removed lines patch added patch discarded remove patch
@@ -59,1024 +59,1024 @@
 block discarded – undo
59 59
  * OC_autoload!
60 60
  */
61 61
 class OC {
62
-	/**
63
-	 * Associative array for autoloading. classname => filename
64
-	 */
65
-	public static $CLASSPATH = array();
66
-	/**
67
-	 * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
68
-	 */
69
-	public static $SERVERROOT = '';
70
-	/**
71
-	 * the current request path relative to the Nextcloud root (e.g. files/index.php)
72
-	 */
73
-	private static $SUBURI = '';
74
-	/**
75
-	 * the Nextcloud root path for http requests (e.g. nextcloud/)
76
-	 */
77
-	public static $WEBROOT = '';
78
-	/**
79
-	 * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
80
-	 * web path in 'url'
81
-	 */
82
-	public static $APPSROOTS = array();
83
-
84
-	/**
85
-	 * @var string
86
-	 */
87
-	public static $configDir;
88
-
89
-	/**
90
-	 * requested app
91
-	 */
92
-	public static $REQUESTEDAPP = '';
93
-
94
-	/**
95
-	 * check if Nextcloud runs in cli mode
96
-	 */
97
-	public static $CLI = false;
98
-
99
-	/**
100
-	 * @var \OC\Autoloader $loader
101
-	 */
102
-	public static $loader = null;
103
-
104
-	/** @var \Composer\Autoload\ClassLoader $composerAutoloader */
105
-	public static $composerAutoloader = null;
106
-
107
-	/**
108
-	 * @var \OC\Server
109
-	 */
110
-	public static $server = null;
111
-
112
-	/**
113
-	 * @var \OC\Config
114
-	 */
115
-	private static $config = null;
116
-
117
-	/**
118
-	 * @throws \RuntimeException when the 3rdparty directory is missing or
119
-	 * the app path list is empty or contains an invalid path
120
-	 */
121
-	public static function initPaths() {
122
-		if(defined('PHPUNIT_CONFIG_DIR')) {
123
-			self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
124
-		} elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
125
-			self::$configDir = OC::$SERVERROOT . '/tests/config/';
126
-		} elseif($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
127
-			self::$configDir = rtrim($dir, '/') . '/';
128
-		} else {
129
-			self::$configDir = OC::$SERVERROOT . '/config/';
130
-		}
131
-		self::$config = new \OC\Config(self::$configDir);
132
-
133
-		OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
134
-		/**
135
-		 * FIXME: The following lines are required because we can't yet instantiate
136
-		 *        \OC::$server->getRequest() since \OC::$server does not yet exist.
137
-		 */
138
-		$params = [
139
-			'server' => [
140
-				'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
141
-				'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
142
-			],
143
-		];
144
-		$fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig(self::$config)));
145
-		$scriptName = $fakeRequest->getScriptName();
146
-		if (substr($scriptName, -1) == '/') {
147
-			$scriptName .= 'index.php';
148
-			//make sure suburi follows the same rules as scriptName
149
-			if (substr(OC::$SUBURI, -9) != 'index.php') {
150
-				if (substr(OC::$SUBURI, -1) != '/') {
151
-					OC::$SUBURI = OC::$SUBURI . '/';
152
-				}
153
-				OC::$SUBURI = OC::$SUBURI . 'index.php';
154
-			}
155
-		}
156
-
157
-
158
-		if (OC::$CLI) {
159
-			OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
160
-		} else {
161
-			if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
162
-				OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
163
-
164
-				if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
165
-					OC::$WEBROOT = '/' . OC::$WEBROOT;
166
-				}
167
-			} else {
168
-				// The scriptName is not ending with OC::$SUBURI
169
-				// This most likely means that we are calling from CLI.
170
-				// However some cron jobs still need to generate
171
-				// a web URL, so we use overwritewebroot as a fallback.
172
-				OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
173
-			}
174
-
175
-			// Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
176
-			// slash which is required by URL generation.
177
-			if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
178
-					substr($_SERVER['REQUEST_URI'], -1) !== '/') {
179
-				header('Location: '.\OC::$WEBROOT.'/');
180
-				exit();
181
-			}
182
-		}
183
-
184
-		// search the apps folder
185
-		$config_paths = self::$config->getValue('apps_paths', array());
186
-		if (!empty($config_paths)) {
187
-			foreach ($config_paths as $paths) {
188
-				if (isset($paths['url']) && isset($paths['path'])) {
189
-					$paths['url'] = rtrim($paths['url'], '/');
190
-					$paths['path'] = rtrim($paths['path'], '/');
191
-					OC::$APPSROOTS[] = $paths;
192
-				}
193
-			}
194
-		} elseif (file_exists(OC::$SERVERROOT . '/apps')) {
195
-			OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
196
-		} elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
197
-			OC::$APPSROOTS[] = array(
198
-				'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
199
-				'url' => '/apps',
200
-				'writable' => true
201
-			);
202
-		}
203
-
204
-		if (empty(OC::$APPSROOTS)) {
205
-			throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
206
-				. ' or the folder above. You can also configure the location in the config.php file.');
207
-		}
208
-		$paths = array();
209
-		foreach (OC::$APPSROOTS as $path) {
210
-			$paths[] = $path['path'];
211
-			if (!is_dir($path['path'])) {
212
-				throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
213
-					. ' Nextcloud folder or the folder above. You can also configure the location in the'
214
-					. ' config.php file.', $path['path']));
215
-			}
216
-		}
217
-
218
-		// set the right include path
219
-		set_include_path(
220
-			implode(PATH_SEPARATOR, $paths)
221
-		);
222
-	}
223
-
224
-	public static function checkConfig() {
225
-		$l = \OC::$server->getL10N('lib');
226
-
227
-		// Create config if it does not already exist
228
-		$configFilePath = self::$configDir .'/config.php';
229
-		if(!file_exists($configFilePath)) {
230
-			@touch($configFilePath);
231
-		}
232
-
233
-		// Check if config is writable
234
-		$configFileWritable = is_writable($configFilePath);
235
-		if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
236
-			|| !$configFileWritable && self::checkUpgrade(false)) {
237
-
238
-			$urlGenerator = \OC::$server->getURLGenerator();
239
-
240
-			if (self::$CLI) {
241
-				echo $l->t('Cannot write into "config" directory!')."\n";
242
-				echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
243
-				echo "\n";
244
-				echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-dir_permissions') ])."\n";
245
-				exit;
246
-			} else {
247
-				OC_Template::printErrorPage(
248
-					$l->t('Cannot write into "config" directory!'),
249
-					$l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
250
-					 [ $urlGenerator->linkToDocs('admin-dir_permissions') ])
251
-				);
252
-			}
253
-		}
254
-	}
255
-
256
-	public static function checkInstalled() {
257
-		if (defined('OC_CONSOLE')) {
258
-			return;
259
-		}
260
-		// Redirect to installer if not installed
261
-		if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
262
-			if (OC::$CLI) {
263
-				throw new Exception('Not installed');
264
-			} else {
265
-				$url = OC::$WEBROOT . '/index.php';
266
-				header('Location: ' . $url);
267
-			}
268
-			exit();
269
-		}
270
-	}
271
-
272
-	public static function checkMaintenanceMode() {
273
-		// Allow ajax update script to execute without being stopped
274
-		if (\OC::$server->getSystemConfig()->getValue('maintenance', false) && OC::$SUBURI != '/core/ajax/update.php') {
275
-			// send http status 503
276
-			header('HTTP/1.1 503 Service Temporarily Unavailable');
277
-			header('Status: 503 Service Temporarily Unavailable');
278
-			header('Retry-After: 120');
279
-
280
-			// render error page
281
-			$template = new OC_Template('', 'update.user', 'guest');
282
-			OC_Util::addScript('maintenance-check');
283
-			OC_Util::addStyle('core', 'guest');
284
-			$template->printPage();
285
-			die();
286
-		}
287
-	}
288
-
289
-	/**
290
-	 * Checks if the version requires an update and shows
291
-	 * @param bool $showTemplate Whether an update screen should get shown
292
-	 * @return bool|void
293
-	 */
294
-	public static function checkUpgrade($showTemplate = true) {
295
-		if (\OCP\Util::needUpgrade()) {
296
-			if (function_exists('opcache_reset')) {
297
-				opcache_reset();
298
-			}
299
-			$systemConfig = \OC::$server->getSystemConfig();
300
-			if ($showTemplate && !$systemConfig->getValue('maintenance', false)) {
301
-				self::printUpgradePage();
302
-				exit();
303
-			} else {
304
-				return true;
305
-			}
306
-		}
307
-		return false;
308
-	}
309
-
310
-	/**
311
-	 * Prints the upgrade page
312
-	 */
313
-	private static function printUpgradePage() {
314
-		$systemConfig = \OC::$server->getSystemConfig();
315
-
316
-		$disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
317
-		$tooBig = false;
318
-		if (!$disableWebUpdater) {
319
-			$apps = \OC::$server->getAppManager();
320
-			$tooBig = false;
321
-			if ($apps->isInstalled('user_ldap')) {
322
-				$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
323
-
324
-				$result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
325
-					->from('ldap_user_mapping')
326
-					->execute();
327
-				$row = $result->fetch();
328
-				$result->closeCursor();
329
-
330
-				$tooBig = ($row['user_count'] > 50);
331
-			}
332
-			if (!$tooBig && $apps->isInstalled('user_saml')) {
333
-				$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
334
-
335
-				$result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
336
-					->from('user_saml_users')
337
-					->execute();
338
-				$row = $result->fetch();
339
-				$result->closeCursor();
340
-
341
-				$tooBig = ($row['user_count'] > 50);
342
-			}
343
-			if (!$tooBig) {
344
-				// count users
345
-				$stats = \OC::$server->getUserManager()->countUsers();
346
-				$totalUsers = array_sum($stats);
347
-				$tooBig = ($totalUsers > 50);
348
-			}
349
-		}
350
-		$ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
351
-			$_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
352
-
353
-		if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
354
-			// send http status 503
355
-			header('HTTP/1.1 503 Service Temporarily Unavailable');
356
-			header('Status: 503 Service Temporarily Unavailable');
357
-			header('Retry-After: 120');
358
-
359
-			// render error page
360
-			$template = new OC_Template('', 'update.use-cli', 'guest');
361
-			$template->assign('productName', 'nextcloud'); // for now
362
-			$template->assign('version', OC_Util::getVersionString());
363
-			$template->assign('tooBig', $tooBig);
364
-
365
-			$template->printPage();
366
-			die();
367
-		}
368
-
369
-		// check whether this is a core update or apps update
370
-		$installedVersion = $systemConfig->getValue('version', '0.0.0');
371
-		$currentVersion = implode('.', \OCP\Util::getVersion());
372
-
373
-		// if not a core upgrade, then it's apps upgrade
374
-		$isAppsOnlyUpgrade = (version_compare($currentVersion, $installedVersion, '='));
375
-
376
-		$oldTheme = $systemConfig->getValue('theme');
377
-		$systemConfig->setValue('theme', '');
378
-		OC_Util::addScript('config'); // needed for web root
379
-		OC_Util::addScript('update');
380
-
381
-		/** @var \OC\App\AppManager $appManager */
382
-		$appManager = \OC::$server->getAppManager();
383
-
384
-		$tmpl = new OC_Template('', 'update.admin', 'guest');
385
-		$tmpl->assign('version', OC_Util::getVersionString());
386
-		$tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
387
-
388
-		// get third party apps
389
-		$ocVersion = \OCP\Util::getVersion();
390
-		$incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
391
-		$incompatibleShippedApps = [];
392
-		foreach ($incompatibleApps as $appInfo) {
393
-			if ($appManager->isShipped($appInfo['id'])) {
394
-				$incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
395
-			}
396
-		}
397
-
398
-		if (!empty($incompatibleShippedApps)) {
399
-			$l = \OC::$server->getL10N('core');
400
-			$hint = $l->t('The files of the app %$1s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
401
-			throw new \OC\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
402
-		}
403
-
404
-		$tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
405
-		$tmpl->assign('incompatibleAppsList', $incompatibleApps);
406
-		$tmpl->assign('productName', 'Nextcloud'); // for now
407
-		$tmpl->assign('oldTheme', $oldTheme);
408
-		$tmpl->printPage();
409
-	}
410
-
411
-	public static function initSession() {
412
-		// prevents javascript from accessing php session cookies
413
-		ini_set('session.cookie_httponly', true);
414
-
415
-		// set the cookie path to the Nextcloud directory
416
-		$cookie_path = OC::$WEBROOT ? : '/';
417
-		ini_set('session.cookie_path', $cookie_path);
418
-
419
-		// Let the session name be changed in the initSession Hook
420
-		$sessionName = OC_Util::getInstanceId();
421
-
422
-		try {
423
-			// Allow session apps to create a custom session object
424
-			$useCustomSession = false;
425
-			$session = self::$server->getSession();
426
-			OC_Hook::emit('OC', 'initSession', array('session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession));
427
-			if (!$useCustomSession) {
428
-				// set the session name to the instance id - which is unique
429
-				$session = new \OC\Session\Internal($sessionName);
430
-			}
431
-
432
-			$cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
433
-			$session = $cryptoWrapper->wrapSession($session);
434
-			self::$server->setSession($session);
435
-
436
-			// if session can't be started break with http 500 error
437
-		} catch (Exception $e) {
438
-			\OCP\Util::logException('base', $e);
439
-			//show the user a detailed error page
440
-			OC_Response::setStatus(OC_Response::STATUS_INTERNAL_SERVER_ERROR);
441
-			OC_Template::printExceptionErrorPage($e);
442
-			die();
443
-		}
444
-
445
-		$sessionLifeTime = self::getSessionLifeTime();
446
-
447
-		// session timeout
448
-		if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
449
-			if (isset($_COOKIE[session_name()])) {
450
-				setcookie(session_name(), null, -1, self::$WEBROOT ? : '/');
451
-			}
452
-			\OC::$server->getUserSession()->logout();
453
-		}
454
-
455
-		$session->set('LAST_ACTIVITY', time());
456
-	}
457
-
458
-	/**
459
-	 * @return string
460
-	 */
461
-	private static function getSessionLifeTime() {
462
-		return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
463
-	}
464
-
465
-	public static function loadAppClassPaths() {
466
-		foreach (OC_App::getEnabledApps() as $app) {
467
-			$appPath = OC_App::getAppPath($app);
468
-			if ($appPath === false) {
469
-				continue;
470
-			}
471
-
472
-			$file = $appPath . '/appinfo/classpath.php';
473
-			if (file_exists($file)) {
474
-				require_once $file;
475
-			}
476
-		}
477
-	}
478
-
479
-	/**
480
-	 * Try to set some values to the required Nextcloud default
481
-	 */
482
-	public static function setRequiredIniValues() {
483
-		@ini_set('default_charset', 'UTF-8');
484
-		@ini_set('gd.jpeg_ignore_warning', 1);
485
-	}
486
-
487
-	/**
488
-	 * Send the same site cookies
489
-	 */
490
-	private static function sendSameSiteCookies() {
491
-		$cookieParams = session_get_cookie_params();
492
-		$secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
493
-		$policies = [
494
-			'lax',
495
-			'strict',
496
-		];
497
-
498
-		// Append __Host to the cookie if it meets the requirements
499
-		$cookiePrefix = '';
500
-		if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
501
-			$cookiePrefix = '__Host-';
502
-		}
503
-
504
-		foreach($policies as $policy) {
505
-			header(
506
-				sprintf(
507
-					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
508
-					$cookiePrefix,
509
-					$policy,
510
-					$cookieParams['path'],
511
-					$policy
512
-				),
513
-				false
514
-			);
515
-		}
516
-	}
517
-
518
-	/**
519
-	 * Same Site cookie to further mitigate CSRF attacks. This cookie has to
520
-	 * be set in every request if cookies are sent to add a second level of
521
-	 * defense against CSRF.
522
-	 *
523
-	 * If the cookie is not sent this will set the cookie and reload the page.
524
-	 * We use an additional cookie since we want to protect logout CSRF and
525
-	 * also we can't directly interfere with PHP's session mechanism.
526
-	 */
527
-	private static function performSameSiteCookieProtection() {
528
-		$request = \OC::$server->getRequest();
529
-
530
-		// Some user agents are notorious and don't really properly follow HTTP
531
-		// specifications. For those, have an automated opt-out. Since the protection
532
-		// for remote.php is applied in base.php as starting point we need to opt out
533
-		// here.
534
-		$incompatibleUserAgents = [
535
-			// OS X Finder
536
-			'/^WebDAVFS/',
537
-		];
538
-		if($request->isUserAgent($incompatibleUserAgents)) {
539
-			return;
540
-		}
541
-
542
-		if(count($_COOKIE) > 0) {
543
-			$requestUri = $request->getScriptName();
544
-			$processingScript = explode('/', $requestUri);
545
-			$processingScript = $processingScript[count($processingScript)-1];
546
-			// FIXME: In a SAML scenario we don't get any strict or lax cookie
547
-			// send for the ACS endpoint. Since we have some legacy code in Nextcloud
548
-			// (direct PHP files) the enforcement of lax cookies is performed here
549
-			// instead of the middleware.
550
-			//
551
-			// This means we cannot exclude some routes from the cookie validation,
552
-			// which normally is not a problem but is a little bit cumbersome for
553
-			// this use-case.
554
-			// Once the old legacy PHP endpoints have been removed we can move
555
-			// the verification into a middleware and also adds some exemptions.
556
-			//
557
-			// Questions about this code? Ask Lukas ;-)
558
-			$currentUrl = substr(explode('?',$request->getRequestUri(), 2)[0], strlen(\OC::$WEBROOT));
559
-			if($currentUrl === '/index.php/apps/user_saml/saml/acs' || $currentUrl === '/apps/user_saml/saml/acs') {
560
-				return;
561
-			}
562
-			// index.php routes are handled in the middleware
563
-			if($processingScript === 'index.php') {
564
-				return;
565
-			}
566
-
567
-			// All other endpoints require the lax and the strict cookie
568
-			if(!$request->passesStrictCookieCheck()) {
569
-				self::sendSameSiteCookies();
570
-				// Debug mode gets access to the resources without strict cookie
571
-				// due to the fact that the SabreDAV browser also lives there.
572
-				if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
573
-					http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
574
-					exit();
575
-				}
576
-			}
577
-		} elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
578
-			self::sendSameSiteCookies();
579
-		}
580
-	}
581
-
582
-	public static function init() {
583
-		// calculate the root directories
584
-		OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
585
-
586
-		// register autoloader
587
-		$loaderStart = microtime(true);
588
-		require_once __DIR__ . '/autoloader.php';
589
-		self::$loader = new \OC\Autoloader([
590
-			OC::$SERVERROOT . '/lib/private/legacy',
591
-		]);
592
-		if (defined('PHPUNIT_RUN')) {
593
-			self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
594
-		}
595
-		spl_autoload_register(array(self::$loader, 'load'));
596
-		$loaderEnd = microtime(true);
597
-
598
-		self::$CLI = (php_sapi_name() == 'cli');
599
-
600
-		// Add default composer PSR-4 autoloader
601
-		self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
602
-
603
-		try {
604
-			self::initPaths();
605
-			// setup 3rdparty autoloader
606
-			$vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
607
-			if (!file_exists($vendorAutoLoad)) {
608
-				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".');
609
-			}
610
-			require_once $vendorAutoLoad;
611
-
612
-		} catch (\RuntimeException $e) {
613
-			if (!self::$CLI) {
614
-				$claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']);
615
-				$protocol = in_array($claimedProtocol, ['HTTP/1.0', 'HTTP/1.1', 'HTTP/2']) ? $claimedProtocol : 'HTTP/1.1';
616
-				header($protocol . ' ' . OC_Response::STATUS_SERVICE_UNAVAILABLE);
617
-			}
618
-			// we can't use the template error page here, because this needs the
619
-			// DI container which isn't available yet
620
-			print($e->getMessage());
621
-			exit();
622
-		}
623
-
624
-		// setup the basic server
625
-		self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
626
-		\OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
627
-		\OC::$server->getEventLogger()->start('boot', 'Initialize');
628
-
629
-		// Don't display errors and log them
630
-		error_reporting(E_ALL | E_STRICT);
631
-		@ini_set('display_errors', 0);
632
-		@ini_set('log_errors', 1);
633
-
634
-		if(!date_default_timezone_set('UTC')) {
635
-			throw new \RuntimeException('Could not set timezone to UTC');
636
-		};
637
-
638
-		//try to configure php to enable big file uploads.
639
-		//this doesn´t work always depending on the webserver and php configuration.
640
-		//Let´s try to overwrite some defaults anyway
641
-
642
-		//try to set the maximum execution time to 60min
643
-		if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
644
-			@set_time_limit(3600);
645
-		}
646
-		@ini_set('max_execution_time', 3600);
647
-		@ini_set('max_input_time', 3600);
648
-
649
-		//try to set the maximum filesize to 10G
650
-		@ini_set('upload_max_filesize', '10G');
651
-		@ini_set('post_max_size', '10G');
652
-		@ini_set('file_uploads', '50');
653
-
654
-		self::setRequiredIniValues();
655
-		self::handleAuthHeaders();
656
-		self::registerAutoloaderCache();
657
-
658
-		// initialize intl fallback is necessary
659
-		\Patchwork\Utf8\Bootup::initIntl();
660
-		OC_Util::isSetLocaleWorking();
661
-
662
-		if (!defined('PHPUNIT_RUN')) {
663
-			OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
664
-			$debug = \OC::$server->getConfig()->getSystemValue('debug', false);
665
-			OC\Log\ErrorHandler::register($debug);
666
-		}
667
-
668
-		\OC::$server->getEventLogger()->start('init_session', 'Initialize session');
669
-		OC_App::loadApps(array('session'));
670
-		if (!self::$CLI) {
671
-			self::initSession();
672
-		}
673
-		\OC::$server->getEventLogger()->end('init_session');
674
-		self::checkConfig();
675
-		self::checkInstalled();
676
-
677
-		OC_Response::addSecurityHeaders();
678
-		if(self::$server->getRequest()->getServerProtocol() === 'https') {
679
-			ini_set('session.cookie_secure', true);
680
-		}
681
-
682
-		self::performSameSiteCookieProtection();
683
-
684
-		if (!defined('OC_CONSOLE')) {
685
-			$errors = OC_Util::checkServer(\OC::$server->getSystemConfig());
686
-			if (count($errors) > 0) {
687
-				if (self::$CLI) {
688
-					// Convert l10n string into regular string for usage in database
689
-					$staticErrors = [];
690
-					foreach ($errors as $error) {
691
-						echo $error['error'] . "\n";
692
-						echo $error['hint'] . "\n\n";
693
-						$staticErrors[] = [
694
-							'error' => (string)$error['error'],
695
-							'hint' => (string)$error['hint'],
696
-						];
697
-					}
698
-
699
-					try {
700
-						\OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
701
-					} catch (\Exception $e) {
702
-						echo('Writing to database failed');
703
-					}
704
-					exit(1);
705
-				} else {
706
-					OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE);
707
-					OC_Util::addStyle('guest');
708
-					OC_Template::printGuestPage('', 'error', array('errors' => $errors));
709
-					exit;
710
-				}
711
-			} elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
712
-				\OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
713
-			}
714
-		}
715
-		//try to set the session lifetime
716
-		$sessionLifeTime = self::getSessionLifeTime();
717
-		@ini_set('gc_maxlifetime', (string)$sessionLifeTime);
718
-
719
-		$systemConfig = \OC::$server->getSystemConfig();
720
-
721
-		// User and Groups
722
-		if (!$systemConfig->getValue("installed", false)) {
723
-			self::$server->getSession()->set('user_id', '');
724
-		}
725
-
726
-		OC_User::useBackend(new \OC\User\Database());
727
-		\OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
728
-
729
-		// Subscribe to the hook
730
-		\OCP\Util::connectHook(
731
-			'\OCA\Files_Sharing\API\Server2Server',
732
-			'preLoginNameUsedAsUserName',
733
-			'\OC\User\Database',
734
-			'preLoginNameUsedAsUserName'
735
-		);
736
-
737
-		//setup extra user backends
738
-		if (!self::checkUpgrade(false)) {
739
-			OC_User::setupBackends();
740
-		} else {
741
-			// Run upgrades in incognito mode
742
-			OC_User::setIncognitoMode(true);
743
-		}
744
-
745
-		self::registerCacheHooks();
746
-		self::registerFilesystemHooks();
747
-		self::registerShareHooks();
748
-		self::registerLogRotate();
749
-		self::registerEncryptionWrapper();
750
-		self::registerEncryptionHooks();
751
-		self::registerAccountHooks();
752
-		self::registerSettingsHooks();
753
-
754
-		$settings = new \OC\Settings\Application();
755
-		$settings->register();
756
-
757
-		//make sure temporary files are cleaned up
758
-		$tmpManager = \OC::$server->getTempManager();
759
-		register_shutdown_function(array($tmpManager, 'clean'));
760
-		$lockProvider = \OC::$server->getLockingProvider();
761
-		register_shutdown_function(array($lockProvider, 'releaseAll'));
762
-
763
-		// Check whether the sample configuration has been copied
764
-		if($systemConfig->getValue('copied_sample_config', false)) {
765
-			$l = \OC::$server->getL10N('lib');
766
-			header('HTTP/1.1 503 Service Temporarily Unavailable');
767
-			header('Status: 503 Service Temporarily Unavailable');
768
-			OC_Template::printErrorPage(
769
-				$l->t('Sample configuration detected'),
770
-				$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')
771
-			);
772
-			return;
773
-		}
774
-
775
-		$request = \OC::$server->getRequest();
776
-		$host = $request->getInsecureServerHost();
777
-		/**
778
-		 * if the host passed in headers isn't trusted
779
-		 * FIXME: Should not be in here at all :see_no_evil:
780
-		 */
781
-		if (!OC::$CLI
782
-			// overwritehost is always trusted, workaround to not have to make
783
-			// \OC\AppFramework\Http\Request::getOverwriteHost public
784
-			&& self::$server->getConfig()->getSystemValue('overwritehost') === ''
785
-			&& !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
786
-			&& self::$server->getConfig()->getSystemValue('installed', false)
787
-		) {
788
-			// Allow access to CSS resources
789
-			$isScssRequest = false;
790
-			if(strpos($request->getPathInfo(), '/css/') === 0) {
791
-				$isScssRequest = true;
792
-			}
793
-
794
-			if (!$isScssRequest) {
795
-				header('HTTP/1.1 400 Bad Request');
796
-				header('Status: 400 Bad Request');
797
-
798
-				\OC::$server->getLogger()->warning(
799
-					'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
800
-					[
801
-						'app' => 'core',
802
-						'remoteAddress' => $request->getRemoteAddress(),
803
-						'host' => $host,
804
-					]
805
-				);
806
-
807
-				$tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
808
-				$tmpl->assign('domain', $host);
809
-				$tmpl->printPage();
810
-
811
-				exit();
812
-			}
813
-		}
814
-		\OC::$server->getEventLogger()->end('boot');
815
-	}
816
-
817
-	/**
818
-	 * register hooks for the cache
819
-	 */
820
-	public static function registerCacheHooks() {
821
-		//don't try to do this before we are properly setup
822
-		if (\OC::$server->getSystemConfig()->getValue('installed', false) && !self::checkUpgrade(false)) {
823
-
824
-			// NOTE: This will be replaced to use OCP
825
-			$userSession = self::$server->getUserSession();
826
-			$userSession->listen('\OC\User', 'postLogin', function () {
827
-				try {
828
-					$cache = new \OC\Cache\File();
829
-					$cache->gc();
830
-				} catch (\OC\ServerNotAvailableException $e) {
831
-					// not a GC exception, pass it on
832
-					throw $e;
833
-				} catch (\OC\ForbiddenException $e) {
834
-					// filesystem blocked for this request, ignore
835
-				} catch (\Exception $e) {
836
-					// a GC exception should not prevent users from using OC,
837
-					// so log the exception
838
-					\OC::$server->getLogger()->warning('Exception when running cache gc: ' . $e->getMessage(), array('app' => 'core'));
839
-				}
840
-			});
841
-		}
842
-	}
843
-
844
-	public static function registerSettingsHooks() {
845
-		$dispatcher = \OC::$server->getEventDispatcher();
846
-		$dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_DISABLE, function($event) {
847
-			/** @var \OCP\App\ManagerEvent $event */
848
-			\OC::$server->getSettingsManager()->onAppDisabled($event->getAppID());
849
-		});
850
-		$dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_UPDATE, function($event) {
851
-			/** @var \OCP\App\ManagerEvent $event */
852
-			$jobList = \OC::$server->getJobList();
853
-			$job = 'OC\\Settings\\RemoveOrphaned';
854
-			if(!($jobList->has($job, null))) {
855
-				$jobList->add($job);
856
-			}
857
-		});
858
-	}
859
-
860
-	private static function registerEncryptionWrapper() {
861
-		$manager = self::$server->getEncryptionManager();
862
-		\OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
863
-	}
864
-
865
-	private static function registerEncryptionHooks() {
866
-		$enabled = self::$server->getEncryptionManager()->isEnabled();
867
-		if ($enabled) {
868
-			\OCP\Util::connectHook('OCP\Share', 'post_shared', 'OC\Encryption\HookManager', 'postShared');
869
-			\OCP\Util::connectHook('OCP\Share', 'post_unshare', 'OC\Encryption\HookManager', 'postUnshared');
870
-			\OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OC\Encryption\HookManager', 'postRename');
871
-			\OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', 'OC\Encryption\HookManager', 'postRestore');
872
-		}
873
-	}
874
-
875
-	private static function registerAccountHooks() {
876
-		$hookHandler = new \OC\Accounts\Hooks(\OC::$server->getLogger());
877
-		\OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
878
-	}
879
-
880
-	/**
881
-	 * register hooks for the cache
882
-	 */
883
-	public static function registerLogRotate() {
884
-		$systemConfig = \OC::$server->getSystemConfig();
885
-		if ($systemConfig->getValue('installed', false) && $systemConfig->getValue('log_rotate_size', false) && !self::checkUpgrade(false)) {
886
-			//don't try to do this before we are properly setup
887
-			//use custom logfile path if defined, otherwise use default of nextcloud.log in data directory
888
-			\OC::$server->getJobList()->add('OC\Log\Rotate');
889
-		}
890
-	}
891
-
892
-	/**
893
-	 * register hooks for the filesystem
894
-	 */
895
-	public static function registerFilesystemHooks() {
896
-		// Check for blacklisted files
897
-		OC_Hook::connect('OC_Filesystem', 'write', 'OC\Files\Filesystem', 'isBlacklisted');
898
-		OC_Hook::connect('OC_Filesystem', 'rename', 'OC\Files\Filesystem', 'isBlacklisted');
899
-	}
900
-
901
-	/**
902
-	 * register hooks for sharing
903
-	 */
904
-	public static function registerShareHooks() {
905
-		if (\OC::$server->getSystemConfig()->getValue('installed')) {
906
-			OC_Hook::connect('OC_User', 'post_deleteUser', 'OC\Share20\Hooks', 'post_deleteUser');
907
-			OC_Hook::connect('OC_User', 'post_removeFromGroup', 'OC\Share20\Hooks', 'post_removeFromGroup');
908
-			OC_Hook::connect('OC_User', 'post_deleteGroup', 'OC\Share20\Hooks', 'post_deleteGroup');
909
-		}
910
-	}
911
-
912
-	protected static function registerAutoloaderCache() {
913
-		// The class loader takes an optional low-latency cache, which MUST be
914
-		// namespaced. The instanceid is used for namespacing, but might be
915
-		// unavailable at this point. Furthermore, it might not be possible to
916
-		// generate an instanceid via \OC_Util::getInstanceId() because the
917
-		// config file may not be writable. As such, we only register a class
918
-		// loader cache if instanceid is available without trying to create one.
919
-		$instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
920
-		if ($instanceId) {
921
-			try {
922
-				$memcacheFactory = \OC::$server->getMemCacheFactory();
923
-				self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
924
-			} catch (\Exception $ex) {
925
-			}
926
-		}
927
-	}
928
-
929
-	/**
930
-	 * Handle the request
931
-	 */
932
-	public static function handleRequest() {
933
-
934
-		\OC::$server->getEventLogger()->start('handle_request', 'Handle request');
935
-		$systemConfig = \OC::$server->getSystemConfig();
936
-		// load all the classpaths from the enabled apps so they are available
937
-		// in the routing files of each app
938
-		OC::loadAppClassPaths();
939
-
940
-		// Check if Nextcloud is installed or in maintenance (update) mode
941
-		if (!$systemConfig->getValue('installed', false)) {
942
-			\OC::$server->getSession()->clear();
943
-			$setupHelper = new OC\Setup(\OC::$server->getSystemConfig(), \OC::$server->getIniWrapper(),
944
-				\OC::$server->getL10N('lib'), \OC::$server->query(\OCP\Defaults::class), \OC::$server->getLogger(),
945
-				\OC::$server->getSecureRandom());
946
-			$controller = new OC\Core\Controller\SetupController($setupHelper);
947
-			$controller->run($_POST);
948
-			exit();
949
-		}
950
-
951
-		$request = \OC::$server->getRequest();
952
-		$requestPath = $request->getRawPathInfo();
953
-		if ($requestPath === '/heartbeat') {
954
-			return;
955
-		}
956
-		if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
957
-			self::checkMaintenanceMode();
958
-			self::checkUpgrade();
959
-		}
960
-
961
-		// emergency app disabling
962
-		if ($requestPath === '/disableapp'
963
-			&& $request->getMethod() === 'POST'
964
-			&& ((array)$request->getParam('appid')) !== ''
965
-		) {
966
-			\OCP\JSON::callCheck();
967
-			\OCP\JSON::checkAdminUser();
968
-			$appIds = (array)$request->getParam('appid');
969
-			foreach($appIds as $appId) {
970
-				$appId = \OC_App::cleanAppId($appId);
971
-				\OC_App::disable($appId);
972
-			}
973
-			\OC_JSON::success();
974
-			exit();
975
-		}
976
-
977
-		// Always load authentication apps
978
-		OC_App::loadApps(['authentication']);
979
-
980
-		// Load minimum set of apps
981
-		if (!self::checkUpgrade(false)
982
-			&& !$systemConfig->getValue('maintenance', false)) {
983
-			// For logged-in users: Load everything
984
-			if(\OC::$server->getUserSession()->isLoggedIn()) {
985
-				OC_App::loadApps();
986
-			} else {
987
-				// For guests: Load only filesystem and logging
988
-				OC_App::loadApps(array('filesystem', 'logging'));
989
-				self::handleLogin($request);
990
-			}
991
-		}
992
-
993
-		if (!self::$CLI) {
994
-			try {
995
-				if (!$systemConfig->getValue('maintenance', false) && !self::checkUpgrade(false)) {
996
-					OC_App::loadApps(array('filesystem', 'logging'));
997
-					OC_App::loadApps();
998
-				}
999
-				OC_Util::setupFS();
1000
-				OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
1001
-				return;
1002
-			} catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
1003
-				//header('HTTP/1.0 404 Not Found');
1004
-			} catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
1005
-				OC_Response::setStatus(405);
1006
-				return;
1007
-			}
1008
-		}
1009
-
1010
-		// Handle WebDAV
1011
-		if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
1012
-			// not allowed any more to prevent people
1013
-			// mounting this root directly.
1014
-			// Users need to mount remote.php/webdav instead.
1015
-			header('HTTP/1.1 405 Method Not Allowed');
1016
-			header('Status: 405 Method Not Allowed');
1017
-			return;
1018
-		}
1019
-
1020
-		// Someone is logged in
1021
-		if (\OC::$server->getUserSession()->isLoggedIn()) {
1022
-			OC_App::loadApps();
1023
-			OC_User::setupBackends();
1024
-			OC_Util::setupFS();
1025
-			// FIXME
1026
-			// Redirect to default application
1027
-			OC_Util::redirectToDefaultPage();
1028
-		} else {
1029
-			// Not handled and not logged in
1030
-			header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1031
-		}
1032
-	}
1033
-
1034
-	/**
1035
-	 * Check login: apache auth, auth token, basic auth
1036
-	 *
1037
-	 * @param OCP\IRequest $request
1038
-	 * @return boolean
1039
-	 */
1040
-	static function handleLogin(OCP\IRequest $request) {
1041
-		$userSession = self::$server->getUserSession();
1042
-		if (OC_User::handleApacheAuth()) {
1043
-			return true;
1044
-		}
1045
-		if ($userSession->tryTokenLogin($request)) {
1046
-			return true;
1047
-		}
1048
-		if (isset($_COOKIE['nc_username'])
1049
-			&& isset($_COOKIE['nc_token'])
1050
-			&& isset($_COOKIE['nc_session_id'])
1051
-			&& $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1052
-			return true;
1053
-		}
1054
-		if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1055
-			return true;
1056
-		}
1057
-		return false;
1058
-	}
1059
-
1060
-	protected static function handleAuthHeaders() {
1061
-		//copy http auth headers for apache+php-fcgid work around
1062
-		if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1063
-			$_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1064
-		}
1065
-
1066
-		// Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1067
-		$vars = array(
1068
-			'HTTP_AUTHORIZATION', // apache+php-cgi work around
1069
-			'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1070
-		);
1071
-		foreach ($vars as $var) {
1072
-			if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1073
-				list($name, $password) = explode(':', base64_decode($matches[1]), 2);
1074
-				$_SERVER['PHP_AUTH_USER'] = $name;
1075
-				$_SERVER['PHP_AUTH_PW'] = $password;
1076
-				break;
1077
-			}
1078
-		}
1079
-	}
62
+    /**
63
+     * Associative array for autoloading. classname => filename
64
+     */
65
+    public static $CLASSPATH = array();
66
+    /**
67
+     * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
68
+     */
69
+    public static $SERVERROOT = '';
70
+    /**
71
+     * the current request path relative to the Nextcloud root (e.g. files/index.php)
72
+     */
73
+    private static $SUBURI = '';
74
+    /**
75
+     * the Nextcloud root path for http requests (e.g. nextcloud/)
76
+     */
77
+    public static $WEBROOT = '';
78
+    /**
79
+     * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
80
+     * web path in 'url'
81
+     */
82
+    public static $APPSROOTS = array();
83
+
84
+    /**
85
+     * @var string
86
+     */
87
+    public static $configDir;
88
+
89
+    /**
90
+     * requested app
91
+     */
92
+    public static $REQUESTEDAPP = '';
93
+
94
+    /**
95
+     * check if Nextcloud runs in cli mode
96
+     */
97
+    public static $CLI = false;
98
+
99
+    /**
100
+     * @var \OC\Autoloader $loader
101
+     */
102
+    public static $loader = null;
103
+
104
+    /** @var \Composer\Autoload\ClassLoader $composerAutoloader */
105
+    public static $composerAutoloader = null;
106
+
107
+    /**
108
+     * @var \OC\Server
109
+     */
110
+    public static $server = null;
111
+
112
+    /**
113
+     * @var \OC\Config
114
+     */
115
+    private static $config = null;
116
+
117
+    /**
118
+     * @throws \RuntimeException when the 3rdparty directory is missing or
119
+     * the app path list is empty or contains an invalid path
120
+     */
121
+    public static function initPaths() {
122
+        if(defined('PHPUNIT_CONFIG_DIR')) {
123
+            self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
124
+        } elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
125
+            self::$configDir = OC::$SERVERROOT . '/tests/config/';
126
+        } elseif($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
127
+            self::$configDir = rtrim($dir, '/') . '/';
128
+        } else {
129
+            self::$configDir = OC::$SERVERROOT . '/config/';
130
+        }
131
+        self::$config = new \OC\Config(self::$configDir);
132
+
133
+        OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
134
+        /**
135
+         * FIXME: The following lines are required because we can't yet instantiate
136
+         *        \OC::$server->getRequest() since \OC::$server does not yet exist.
137
+         */
138
+        $params = [
139
+            'server' => [
140
+                'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
141
+                'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
142
+            ],
143
+        ];
144
+        $fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig(self::$config)));
145
+        $scriptName = $fakeRequest->getScriptName();
146
+        if (substr($scriptName, -1) == '/') {
147
+            $scriptName .= 'index.php';
148
+            //make sure suburi follows the same rules as scriptName
149
+            if (substr(OC::$SUBURI, -9) != 'index.php') {
150
+                if (substr(OC::$SUBURI, -1) != '/') {
151
+                    OC::$SUBURI = OC::$SUBURI . '/';
152
+                }
153
+                OC::$SUBURI = OC::$SUBURI . 'index.php';
154
+            }
155
+        }
156
+
157
+
158
+        if (OC::$CLI) {
159
+            OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
160
+        } else {
161
+            if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
162
+                OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
163
+
164
+                if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
165
+                    OC::$WEBROOT = '/' . OC::$WEBROOT;
166
+                }
167
+            } else {
168
+                // The scriptName is not ending with OC::$SUBURI
169
+                // This most likely means that we are calling from CLI.
170
+                // However some cron jobs still need to generate
171
+                // a web URL, so we use overwritewebroot as a fallback.
172
+                OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
173
+            }
174
+
175
+            // Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
176
+            // slash which is required by URL generation.
177
+            if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
178
+                    substr($_SERVER['REQUEST_URI'], -1) !== '/') {
179
+                header('Location: '.\OC::$WEBROOT.'/');
180
+                exit();
181
+            }
182
+        }
183
+
184
+        // search the apps folder
185
+        $config_paths = self::$config->getValue('apps_paths', array());
186
+        if (!empty($config_paths)) {
187
+            foreach ($config_paths as $paths) {
188
+                if (isset($paths['url']) && isset($paths['path'])) {
189
+                    $paths['url'] = rtrim($paths['url'], '/');
190
+                    $paths['path'] = rtrim($paths['path'], '/');
191
+                    OC::$APPSROOTS[] = $paths;
192
+                }
193
+            }
194
+        } elseif (file_exists(OC::$SERVERROOT . '/apps')) {
195
+            OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
196
+        } elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
197
+            OC::$APPSROOTS[] = array(
198
+                'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
199
+                'url' => '/apps',
200
+                'writable' => true
201
+            );
202
+        }
203
+
204
+        if (empty(OC::$APPSROOTS)) {
205
+            throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
206
+                . ' or the folder above. You can also configure the location in the config.php file.');
207
+        }
208
+        $paths = array();
209
+        foreach (OC::$APPSROOTS as $path) {
210
+            $paths[] = $path['path'];
211
+            if (!is_dir($path['path'])) {
212
+                throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
213
+                    . ' Nextcloud folder or the folder above. You can also configure the location in the'
214
+                    . ' config.php file.', $path['path']));
215
+            }
216
+        }
217
+
218
+        // set the right include path
219
+        set_include_path(
220
+            implode(PATH_SEPARATOR, $paths)
221
+        );
222
+    }
223
+
224
+    public static function checkConfig() {
225
+        $l = \OC::$server->getL10N('lib');
226
+
227
+        // Create config if it does not already exist
228
+        $configFilePath = self::$configDir .'/config.php';
229
+        if(!file_exists($configFilePath)) {
230
+            @touch($configFilePath);
231
+        }
232
+
233
+        // Check if config is writable
234
+        $configFileWritable = is_writable($configFilePath);
235
+        if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
236
+            || !$configFileWritable && self::checkUpgrade(false)) {
237
+
238
+            $urlGenerator = \OC::$server->getURLGenerator();
239
+
240
+            if (self::$CLI) {
241
+                echo $l->t('Cannot write into "config" directory!')."\n";
242
+                echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
243
+                echo "\n";
244
+                echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-dir_permissions') ])."\n";
245
+                exit;
246
+            } else {
247
+                OC_Template::printErrorPage(
248
+                    $l->t('Cannot write into "config" directory!'),
249
+                    $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
250
+                        [ $urlGenerator->linkToDocs('admin-dir_permissions') ])
251
+                );
252
+            }
253
+        }
254
+    }
255
+
256
+    public static function checkInstalled() {
257
+        if (defined('OC_CONSOLE')) {
258
+            return;
259
+        }
260
+        // Redirect to installer if not installed
261
+        if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
262
+            if (OC::$CLI) {
263
+                throw new Exception('Not installed');
264
+            } else {
265
+                $url = OC::$WEBROOT . '/index.php';
266
+                header('Location: ' . $url);
267
+            }
268
+            exit();
269
+        }
270
+    }
271
+
272
+    public static function checkMaintenanceMode() {
273
+        // Allow ajax update script to execute without being stopped
274
+        if (\OC::$server->getSystemConfig()->getValue('maintenance', false) && OC::$SUBURI != '/core/ajax/update.php') {
275
+            // send http status 503
276
+            header('HTTP/1.1 503 Service Temporarily Unavailable');
277
+            header('Status: 503 Service Temporarily Unavailable');
278
+            header('Retry-After: 120');
279
+
280
+            // render error page
281
+            $template = new OC_Template('', 'update.user', 'guest');
282
+            OC_Util::addScript('maintenance-check');
283
+            OC_Util::addStyle('core', 'guest');
284
+            $template->printPage();
285
+            die();
286
+        }
287
+    }
288
+
289
+    /**
290
+     * Checks if the version requires an update and shows
291
+     * @param bool $showTemplate Whether an update screen should get shown
292
+     * @return bool|void
293
+     */
294
+    public static function checkUpgrade($showTemplate = true) {
295
+        if (\OCP\Util::needUpgrade()) {
296
+            if (function_exists('opcache_reset')) {
297
+                opcache_reset();
298
+            }
299
+            $systemConfig = \OC::$server->getSystemConfig();
300
+            if ($showTemplate && !$systemConfig->getValue('maintenance', false)) {
301
+                self::printUpgradePage();
302
+                exit();
303
+            } else {
304
+                return true;
305
+            }
306
+        }
307
+        return false;
308
+    }
309
+
310
+    /**
311
+     * Prints the upgrade page
312
+     */
313
+    private static function printUpgradePage() {
314
+        $systemConfig = \OC::$server->getSystemConfig();
315
+
316
+        $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
317
+        $tooBig = false;
318
+        if (!$disableWebUpdater) {
319
+            $apps = \OC::$server->getAppManager();
320
+            $tooBig = false;
321
+            if ($apps->isInstalled('user_ldap')) {
322
+                $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
323
+
324
+                $result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
325
+                    ->from('ldap_user_mapping')
326
+                    ->execute();
327
+                $row = $result->fetch();
328
+                $result->closeCursor();
329
+
330
+                $tooBig = ($row['user_count'] > 50);
331
+            }
332
+            if (!$tooBig && $apps->isInstalled('user_saml')) {
333
+                $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
334
+
335
+                $result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
336
+                    ->from('user_saml_users')
337
+                    ->execute();
338
+                $row = $result->fetch();
339
+                $result->closeCursor();
340
+
341
+                $tooBig = ($row['user_count'] > 50);
342
+            }
343
+            if (!$tooBig) {
344
+                // count users
345
+                $stats = \OC::$server->getUserManager()->countUsers();
346
+                $totalUsers = array_sum($stats);
347
+                $tooBig = ($totalUsers > 50);
348
+            }
349
+        }
350
+        $ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
351
+            $_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
352
+
353
+        if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
354
+            // send http status 503
355
+            header('HTTP/1.1 503 Service Temporarily Unavailable');
356
+            header('Status: 503 Service Temporarily Unavailable');
357
+            header('Retry-After: 120');
358
+
359
+            // render error page
360
+            $template = new OC_Template('', 'update.use-cli', 'guest');
361
+            $template->assign('productName', 'nextcloud'); // for now
362
+            $template->assign('version', OC_Util::getVersionString());
363
+            $template->assign('tooBig', $tooBig);
364
+
365
+            $template->printPage();
366
+            die();
367
+        }
368
+
369
+        // check whether this is a core update or apps update
370
+        $installedVersion = $systemConfig->getValue('version', '0.0.0');
371
+        $currentVersion = implode('.', \OCP\Util::getVersion());
372
+
373
+        // if not a core upgrade, then it's apps upgrade
374
+        $isAppsOnlyUpgrade = (version_compare($currentVersion, $installedVersion, '='));
375
+
376
+        $oldTheme = $systemConfig->getValue('theme');
377
+        $systemConfig->setValue('theme', '');
378
+        OC_Util::addScript('config'); // needed for web root
379
+        OC_Util::addScript('update');
380
+
381
+        /** @var \OC\App\AppManager $appManager */
382
+        $appManager = \OC::$server->getAppManager();
383
+
384
+        $tmpl = new OC_Template('', 'update.admin', 'guest');
385
+        $tmpl->assign('version', OC_Util::getVersionString());
386
+        $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
387
+
388
+        // get third party apps
389
+        $ocVersion = \OCP\Util::getVersion();
390
+        $incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
391
+        $incompatibleShippedApps = [];
392
+        foreach ($incompatibleApps as $appInfo) {
393
+            if ($appManager->isShipped($appInfo['id'])) {
394
+                $incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
395
+            }
396
+        }
397
+
398
+        if (!empty($incompatibleShippedApps)) {
399
+            $l = \OC::$server->getL10N('core');
400
+            $hint = $l->t('The files of the app %$1s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
401
+            throw new \OC\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
402
+        }
403
+
404
+        $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
405
+        $tmpl->assign('incompatibleAppsList', $incompatibleApps);
406
+        $tmpl->assign('productName', 'Nextcloud'); // for now
407
+        $tmpl->assign('oldTheme', $oldTheme);
408
+        $tmpl->printPage();
409
+    }
410
+
411
+    public static function initSession() {
412
+        // prevents javascript from accessing php session cookies
413
+        ini_set('session.cookie_httponly', true);
414
+
415
+        // set the cookie path to the Nextcloud directory
416
+        $cookie_path = OC::$WEBROOT ? : '/';
417
+        ini_set('session.cookie_path', $cookie_path);
418
+
419
+        // Let the session name be changed in the initSession Hook
420
+        $sessionName = OC_Util::getInstanceId();
421
+
422
+        try {
423
+            // Allow session apps to create a custom session object
424
+            $useCustomSession = false;
425
+            $session = self::$server->getSession();
426
+            OC_Hook::emit('OC', 'initSession', array('session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession));
427
+            if (!$useCustomSession) {
428
+                // set the session name to the instance id - which is unique
429
+                $session = new \OC\Session\Internal($sessionName);
430
+            }
431
+
432
+            $cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
433
+            $session = $cryptoWrapper->wrapSession($session);
434
+            self::$server->setSession($session);
435
+
436
+            // if session can't be started break with http 500 error
437
+        } catch (Exception $e) {
438
+            \OCP\Util::logException('base', $e);
439
+            //show the user a detailed error page
440
+            OC_Response::setStatus(OC_Response::STATUS_INTERNAL_SERVER_ERROR);
441
+            OC_Template::printExceptionErrorPage($e);
442
+            die();
443
+        }
444
+
445
+        $sessionLifeTime = self::getSessionLifeTime();
446
+
447
+        // session timeout
448
+        if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
449
+            if (isset($_COOKIE[session_name()])) {
450
+                setcookie(session_name(), null, -1, self::$WEBROOT ? : '/');
451
+            }
452
+            \OC::$server->getUserSession()->logout();
453
+        }
454
+
455
+        $session->set('LAST_ACTIVITY', time());
456
+    }
457
+
458
+    /**
459
+     * @return string
460
+     */
461
+    private static function getSessionLifeTime() {
462
+        return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
463
+    }
464
+
465
+    public static function loadAppClassPaths() {
466
+        foreach (OC_App::getEnabledApps() as $app) {
467
+            $appPath = OC_App::getAppPath($app);
468
+            if ($appPath === false) {
469
+                continue;
470
+            }
471
+
472
+            $file = $appPath . '/appinfo/classpath.php';
473
+            if (file_exists($file)) {
474
+                require_once $file;
475
+            }
476
+        }
477
+    }
478
+
479
+    /**
480
+     * Try to set some values to the required Nextcloud default
481
+     */
482
+    public static function setRequiredIniValues() {
483
+        @ini_set('default_charset', 'UTF-8');
484
+        @ini_set('gd.jpeg_ignore_warning', 1);
485
+    }
486
+
487
+    /**
488
+     * Send the same site cookies
489
+     */
490
+    private static function sendSameSiteCookies() {
491
+        $cookieParams = session_get_cookie_params();
492
+        $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
493
+        $policies = [
494
+            'lax',
495
+            'strict',
496
+        ];
497
+
498
+        // Append __Host to the cookie if it meets the requirements
499
+        $cookiePrefix = '';
500
+        if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
501
+            $cookiePrefix = '__Host-';
502
+        }
503
+
504
+        foreach($policies as $policy) {
505
+            header(
506
+                sprintf(
507
+                    'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
508
+                    $cookiePrefix,
509
+                    $policy,
510
+                    $cookieParams['path'],
511
+                    $policy
512
+                ),
513
+                false
514
+            );
515
+        }
516
+    }
517
+
518
+    /**
519
+     * Same Site cookie to further mitigate CSRF attacks. This cookie has to
520
+     * be set in every request if cookies are sent to add a second level of
521
+     * defense against CSRF.
522
+     *
523
+     * If the cookie is not sent this will set the cookie and reload the page.
524
+     * We use an additional cookie since we want to protect logout CSRF and
525
+     * also we can't directly interfere with PHP's session mechanism.
526
+     */
527
+    private static function performSameSiteCookieProtection() {
528
+        $request = \OC::$server->getRequest();
529
+
530
+        // Some user agents are notorious and don't really properly follow HTTP
531
+        // specifications. For those, have an automated opt-out. Since the protection
532
+        // for remote.php is applied in base.php as starting point we need to opt out
533
+        // here.
534
+        $incompatibleUserAgents = [
535
+            // OS X Finder
536
+            '/^WebDAVFS/',
537
+        ];
538
+        if($request->isUserAgent($incompatibleUserAgents)) {
539
+            return;
540
+        }
541
+
542
+        if(count($_COOKIE) > 0) {
543
+            $requestUri = $request->getScriptName();
544
+            $processingScript = explode('/', $requestUri);
545
+            $processingScript = $processingScript[count($processingScript)-1];
546
+            // FIXME: In a SAML scenario we don't get any strict or lax cookie
547
+            // send for the ACS endpoint. Since we have some legacy code in Nextcloud
548
+            // (direct PHP files) the enforcement of lax cookies is performed here
549
+            // instead of the middleware.
550
+            //
551
+            // This means we cannot exclude some routes from the cookie validation,
552
+            // which normally is not a problem but is a little bit cumbersome for
553
+            // this use-case.
554
+            // Once the old legacy PHP endpoints have been removed we can move
555
+            // the verification into a middleware and also adds some exemptions.
556
+            //
557
+            // Questions about this code? Ask Lukas ;-)
558
+            $currentUrl = substr(explode('?',$request->getRequestUri(), 2)[0], strlen(\OC::$WEBROOT));
559
+            if($currentUrl === '/index.php/apps/user_saml/saml/acs' || $currentUrl === '/apps/user_saml/saml/acs') {
560
+                return;
561
+            }
562
+            // index.php routes are handled in the middleware
563
+            if($processingScript === 'index.php') {
564
+                return;
565
+            }
566
+
567
+            // All other endpoints require the lax and the strict cookie
568
+            if(!$request->passesStrictCookieCheck()) {
569
+                self::sendSameSiteCookies();
570
+                // Debug mode gets access to the resources without strict cookie
571
+                // due to the fact that the SabreDAV browser also lives there.
572
+                if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
573
+                    http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
574
+                    exit();
575
+                }
576
+            }
577
+        } elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
578
+            self::sendSameSiteCookies();
579
+        }
580
+    }
581
+
582
+    public static function init() {
583
+        // calculate the root directories
584
+        OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
585
+
586
+        // register autoloader
587
+        $loaderStart = microtime(true);
588
+        require_once __DIR__ . '/autoloader.php';
589
+        self::$loader = new \OC\Autoloader([
590
+            OC::$SERVERROOT . '/lib/private/legacy',
591
+        ]);
592
+        if (defined('PHPUNIT_RUN')) {
593
+            self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
594
+        }
595
+        spl_autoload_register(array(self::$loader, 'load'));
596
+        $loaderEnd = microtime(true);
597
+
598
+        self::$CLI = (php_sapi_name() == 'cli');
599
+
600
+        // Add default composer PSR-4 autoloader
601
+        self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
602
+
603
+        try {
604
+            self::initPaths();
605
+            // setup 3rdparty autoloader
606
+            $vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
607
+            if (!file_exists($vendorAutoLoad)) {
608
+                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".');
609
+            }
610
+            require_once $vendorAutoLoad;
611
+
612
+        } catch (\RuntimeException $e) {
613
+            if (!self::$CLI) {
614
+                $claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']);
615
+                $protocol = in_array($claimedProtocol, ['HTTP/1.0', 'HTTP/1.1', 'HTTP/2']) ? $claimedProtocol : 'HTTP/1.1';
616
+                header($protocol . ' ' . OC_Response::STATUS_SERVICE_UNAVAILABLE);
617
+            }
618
+            // we can't use the template error page here, because this needs the
619
+            // DI container which isn't available yet
620
+            print($e->getMessage());
621
+            exit();
622
+        }
623
+
624
+        // setup the basic server
625
+        self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
626
+        \OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
627
+        \OC::$server->getEventLogger()->start('boot', 'Initialize');
628
+
629
+        // Don't display errors and log them
630
+        error_reporting(E_ALL | E_STRICT);
631
+        @ini_set('display_errors', 0);
632
+        @ini_set('log_errors', 1);
633
+
634
+        if(!date_default_timezone_set('UTC')) {
635
+            throw new \RuntimeException('Could not set timezone to UTC');
636
+        };
637
+
638
+        //try to configure php to enable big file uploads.
639
+        //this doesn´t work always depending on the webserver and php configuration.
640
+        //Let´s try to overwrite some defaults anyway
641
+
642
+        //try to set the maximum execution time to 60min
643
+        if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
644
+            @set_time_limit(3600);
645
+        }
646
+        @ini_set('max_execution_time', 3600);
647
+        @ini_set('max_input_time', 3600);
648
+
649
+        //try to set the maximum filesize to 10G
650
+        @ini_set('upload_max_filesize', '10G');
651
+        @ini_set('post_max_size', '10G');
652
+        @ini_set('file_uploads', '50');
653
+
654
+        self::setRequiredIniValues();
655
+        self::handleAuthHeaders();
656
+        self::registerAutoloaderCache();
657
+
658
+        // initialize intl fallback is necessary
659
+        \Patchwork\Utf8\Bootup::initIntl();
660
+        OC_Util::isSetLocaleWorking();
661
+
662
+        if (!defined('PHPUNIT_RUN')) {
663
+            OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
664
+            $debug = \OC::$server->getConfig()->getSystemValue('debug', false);
665
+            OC\Log\ErrorHandler::register($debug);
666
+        }
667
+
668
+        \OC::$server->getEventLogger()->start('init_session', 'Initialize session');
669
+        OC_App::loadApps(array('session'));
670
+        if (!self::$CLI) {
671
+            self::initSession();
672
+        }
673
+        \OC::$server->getEventLogger()->end('init_session');
674
+        self::checkConfig();
675
+        self::checkInstalled();
676
+
677
+        OC_Response::addSecurityHeaders();
678
+        if(self::$server->getRequest()->getServerProtocol() === 'https') {
679
+            ini_set('session.cookie_secure', true);
680
+        }
681
+
682
+        self::performSameSiteCookieProtection();
683
+
684
+        if (!defined('OC_CONSOLE')) {
685
+            $errors = OC_Util::checkServer(\OC::$server->getSystemConfig());
686
+            if (count($errors) > 0) {
687
+                if (self::$CLI) {
688
+                    // Convert l10n string into regular string for usage in database
689
+                    $staticErrors = [];
690
+                    foreach ($errors as $error) {
691
+                        echo $error['error'] . "\n";
692
+                        echo $error['hint'] . "\n\n";
693
+                        $staticErrors[] = [
694
+                            'error' => (string)$error['error'],
695
+                            'hint' => (string)$error['hint'],
696
+                        ];
697
+                    }
698
+
699
+                    try {
700
+                        \OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
701
+                    } catch (\Exception $e) {
702
+                        echo('Writing to database failed');
703
+                    }
704
+                    exit(1);
705
+                } else {
706
+                    OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE);
707
+                    OC_Util::addStyle('guest');
708
+                    OC_Template::printGuestPage('', 'error', array('errors' => $errors));
709
+                    exit;
710
+                }
711
+            } elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
712
+                \OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
713
+            }
714
+        }
715
+        //try to set the session lifetime
716
+        $sessionLifeTime = self::getSessionLifeTime();
717
+        @ini_set('gc_maxlifetime', (string)$sessionLifeTime);
718
+
719
+        $systemConfig = \OC::$server->getSystemConfig();
720
+
721
+        // User and Groups
722
+        if (!$systemConfig->getValue("installed", false)) {
723
+            self::$server->getSession()->set('user_id', '');
724
+        }
725
+
726
+        OC_User::useBackend(new \OC\User\Database());
727
+        \OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
728
+
729
+        // Subscribe to the hook
730
+        \OCP\Util::connectHook(
731
+            '\OCA\Files_Sharing\API\Server2Server',
732
+            'preLoginNameUsedAsUserName',
733
+            '\OC\User\Database',
734
+            'preLoginNameUsedAsUserName'
735
+        );
736
+
737
+        //setup extra user backends
738
+        if (!self::checkUpgrade(false)) {
739
+            OC_User::setupBackends();
740
+        } else {
741
+            // Run upgrades in incognito mode
742
+            OC_User::setIncognitoMode(true);
743
+        }
744
+
745
+        self::registerCacheHooks();
746
+        self::registerFilesystemHooks();
747
+        self::registerShareHooks();
748
+        self::registerLogRotate();
749
+        self::registerEncryptionWrapper();
750
+        self::registerEncryptionHooks();
751
+        self::registerAccountHooks();
752
+        self::registerSettingsHooks();
753
+
754
+        $settings = new \OC\Settings\Application();
755
+        $settings->register();
756
+
757
+        //make sure temporary files are cleaned up
758
+        $tmpManager = \OC::$server->getTempManager();
759
+        register_shutdown_function(array($tmpManager, 'clean'));
760
+        $lockProvider = \OC::$server->getLockingProvider();
761
+        register_shutdown_function(array($lockProvider, 'releaseAll'));
762
+
763
+        // Check whether the sample configuration has been copied
764
+        if($systemConfig->getValue('copied_sample_config', false)) {
765
+            $l = \OC::$server->getL10N('lib');
766
+            header('HTTP/1.1 503 Service Temporarily Unavailable');
767
+            header('Status: 503 Service Temporarily Unavailable');
768
+            OC_Template::printErrorPage(
769
+                $l->t('Sample configuration detected'),
770
+                $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')
771
+            );
772
+            return;
773
+        }
774
+
775
+        $request = \OC::$server->getRequest();
776
+        $host = $request->getInsecureServerHost();
777
+        /**
778
+         * if the host passed in headers isn't trusted
779
+         * FIXME: Should not be in here at all :see_no_evil:
780
+         */
781
+        if (!OC::$CLI
782
+            // overwritehost is always trusted, workaround to not have to make
783
+            // \OC\AppFramework\Http\Request::getOverwriteHost public
784
+            && self::$server->getConfig()->getSystemValue('overwritehost') === ''
785
+            && !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
786
+            && self::$server->getConfig()->getSystemValue('installed', false)
787
+        ) {
788
+            // Allow access to CSS resources
789
+            $isScssRequest = false;
790
+            if(strpos($request->getPathInfo(), '/css/') === 0) {
791
+                $isScssRequest = true;
792
+            }
793
+
794
+            if (!$isScssRequest) {
795
+                header('HTTP/1.1 400 Bad Request');
796
+                header('Status: 400 Bad Request');
797
+
798
+                \OC::$server->getLogger()->warning(
799
+                    'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
800
+                    [
801
+                        'app' => 'core',
802
+                        'remoteAddress' => $request->getRemoteAddress(),
803
+                        'host' => $host,
804
+                    ]
805
+                );
806
+
807
+                $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
808
+                $tmpl->assign('domain', $host);
809
+                $tmpl->printPage();
810
+
811
+                exit();
812
+            }
813
+        }
814
+        \OC::$server->getEventLogger()->end('boot');
815
+    }
816
+
817
+    /**
818
+     * register hooks for the cache
819
+     */
820
+    public static function registerCacheHooks() {
821
+        //don't try to do this before we are properly setup
822
+        if (\OC::$server->getSystemConfig()->getValue('installed', false) && !self::checkUpgrade(false)) {
823
+
824
+            // NOTE: This will be replaced to use OCP
825
+            $userSession = self::$server->getUserSession();
826
+            $userSession->listen('\OC\User', 'postLogin', function () {
827
+                try {
828
+                    $cache = new \OC\Cache\File();
829
+                    $cache->gc();
830
+                } catch (\OC\ServerNotAvailableException $e) {
831
+                    // not a GC exception, pass it on
832
+                    throw $e;
833
+                } catch (\OC\ForbiddenException $e) {
834
+                    // filesystem blocked for this request, ignore
835
+                } catch (\Exception $e) {
836
+                    // a GC exception should not prevent users from using OC,
837
+                    // so log the exception
838
+                    \OC::$server->getLogger()->warning('Exception when running cache gc: ' . $e->getMessage(), array('app' => 'core'));
839
+                }
840
+            });
841
+        }
842
+    }
843
+
844
+    public static function registerSettingsHooks() {
845
+        $dispatcher = \OC::$server->getEventDispatcher();
846
+        $dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_DISABLE, function($event) {
847
+            /** @var \OCP\App\ManagerEvent $event */
848
+            \OC::$server->getSettingsManager()->onAppDisabled($event->getAppID());
849
+        });
850
+        $dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_UPDATE, function($event) {
851
+            /** @var \OCP\App\ManagerEvent $event */
852
+            $jobList = \OC::$server->getJobList();
853
+            $job = 'OC\\Settings\\RemoveOrphaned';
854
+            if(!($jobList->has($job, null))) {
855
+                $jobList->add($job);
856
+            }
857
+        });
858
+    }
859
+
860
+    private static function registerEncryptionWrapper() {
861
+        $manager = self::$server->getEncryptionManager();
862
+        \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
863
+    }
864
+
865
+    private static function registerEncryptionHooks() {
866
+        $enabled = self::$server->getEncryptionManager()->isEnabled();
867
+        if ($enabled) {
868
+            \OCP\Util::connectHook('OCP\Share', 'post_shared', 'OC\Encryption\HookManager', 'postShared');
869
+            \OCP\Util::connectHook('OCP\Share', 'post_unshare', 'OC\Encryption\HookManager', 'postUnshared');
870
+            \OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OC\Encryption\HookManager', 'postRename');
871
+            \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', 'OC\Encryption\HookManager', 'postRestore');
872
+        }
873
+    }
874
+
875
+    private static function registerAccountHooks() {
876
+        $hookHandler = new \OC\Accounts\Hooks(\OC::$server->getLogger());
877
+        \OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
878
+    }
879
+
880
+    /**
881
+     * register hooks for the cache
882
+     */
883
+    public static function registerLogRotate() {
884
+        $systemConfig = \OC::$server->getSystemConfig();
885
+        if ($systemConfig->getValue('installed', false) && $systemConfig->getValue('log_rotate_size', false) && !self::checkUpgrade(false)) {
886
+            //don't try to do this before we are properly setup
887
+            //use custom logfile path if defined, otherwise use default of nextcloud.log in data directory
888
+            \OC::$server->getJobList()->add('OC\Log\Rotate');
889
+        }
890
+    }
891
+
892
+    /**
893
+     * register hooks for the filesystem
894
+     */
895
+    public static function registerFilesystemHooks() {
896
+        // Check for blacklisted files
897
+        OC_Hook::connect('OC_Filesystem', 'write', 'OC\Files\Filesystem', 'isBlacklisted');
898
+        OC_Hook::connect('OC_Filesystem', 'rename', 'OC\Files\Filesystem', 'isBlacklisted');
899
+    }
900
+
901
+    /**
902
+     * register hooks for sharing
903
+     */
904
+    public static function registerShareHooks() {
905
+        if (\OC::$server->getSystemConfig()->getValue('installed')) {
906
+            OC_Hook::connect('OC_User', 'post_deleteUser', 'OC\Share20\Hooks', 'post_deleteUser');
907
+            OC_Hook::connect('OC_User', 'post_removeFromGroup', 'OC\Share20\Hooks', 'post_removeFromGroup');
908
+            OC_Hook::connect('OC_User', 'post_deleteGroup', 'OC\Share20\Hooks', 'post_deleteGroup');
909
+        }
910
+    }
911
+
912
+    protected static function registerAutoloaderCache() {
913
+        // The class loader takes an optional low-latency cache, which MUST be
914
+        // namespaced. The instanceid is used for namespacing, but might be
915
+        // unavailable at this point. Furthermore, it might not be possible to
916
+        // generate an instanceid via \OC_Util::getInstanceId() because the
917
+        // config file may not be writable. As such, we only register a class
918
+        // loader cache if instanceid is available without trying to create one.
919
+        $instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
920
+        if ($instanceId) {
921
+            try {
922
+                $memcacheFactory = \OC::$server->getMemCacheFactory();
923
+                self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
924
+            } catch (\Exception $ex) {
925
+            }
926
+        }
927
+    }
928
+
929
+    /**
930
+     * Handle the request
931
+     */
932
+    public static function handleRequest() {
933
+
934
+        \OC::$server->getEventLogger()->start('handle_request', 'Handle request');
935
+        $systemConfig = \OC::$server->getSystemConfig();
936
+        // load all the classpaths from the enabled apps so they are available
937
+        // in the routing files of each app
938
+        OC::loadAppClassPaths();
939
+
940
+        // Check if Nextcloud is installed or in maintenance (update) mode
941
+        if (!$systemConfig->getValue('installed', false)) {
942
+            \OC::$server->getSession()->clear();
943
+            $setupHelper = new OC\Setup(\OC::$server->getSystemConfig(), \OC::$server->getIniWrapper(),
944
+                \OC::$server->getL10N('lib'), \OC::$server->query(\OCP\Defaults::class), \OC::$server->getLogger(),
945
+                \OC::$server->getSecureRandom());
946
+            $controller = new OC\Core\Controller\SetupController($setupHelper);
947
+            $controller->run($_POST);
948
+            exit();
949
+        }
950
+
951
+        $request = \OC::$server->getRequest();
952
+        $requestPath = $request->getRawPathInfo();
953
+        if ($requestPath === '/heartbeat') {
954
+            return;
955
+        }
956
+        if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
957
+            self::checkMaintenanceMode();
958
+            self::checkUpgrade();
959
+        }
960
+
961
+        // emergency app disabling
962
+        if ($requestPath === '/disableapp'
963
+            && $request->getMethod() === 'POST'
964
+            && ((array)$request->getParam('appid')) !== ''
965
+        ) {
966
+            \OCP\JSON::callCheck();
967
+            \OCP\JSON::checkAdminUser();
968
+            $appIds = (array)$request->getParam('appid');
969
+            foreach($appIds as $appId) {
970
+                $appId = \OC_App::cleanAppId($appId);
971
+                \OC_App::disable($appId);
972
+            }
973
+            \OC_JSON::success();
974
+            exit();
975
+        }
976
+
977
+        // Always load authentication apps
978
+        OC_App::loadApps(['authentication']);
979
+
980
+        // Load minimum set of apps
981
+        if (!self::checkUpgrade(false)
982
+            && !$systemConfig->getValue('maintenance', false)) {
983
+            // For logged-in users: Load everything
984
+            if(\OC::$server->getUserSession()->isLoggedIn()) {
985
+                OC_App::loadApps();
986
+            } else {
987
+                // For guests: Load only filesystem and logging
988
+                OC_App::loadApps(array('filesystem', 'logging'));
989
+                self::handleLogin($request);
990
+            }
991
+        }
992
+
993
+        if (!self::$CLI) {
994
+            try {
995
+                if (!$systemConfig->getValue('maintenance', false) && !self::checkUpgrade(false)) {
996
+                    OC_App::loadApps(array('filesystem', 'logging'));
997
+                    OC_App::loadApps();
998
+                }
999
+                OC_Util::setupFS();
1000
+                OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
1001
+                return;
1002
+            } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
1003
+                //header('HTTP/1.0 404 Not Found');
1004
+            } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
1005
+                OC_Response::setStatus(405);
1006
+                return;
1007
+            }
1008
+        }
1009
+
1010
+        // Handle WebDAV
1011
+        if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
1012
+            // not allowed any more to prevent people
1013
+            // mounting this root directly.
1014
+            // Users need to mount remote.php/webdav instead.
1015
+            header('HTTP/1.1 405 Method Not Allowed');
1016
+            header('Status: 405 Method Not Allowed');
1017
+            return;
1018
+        }
1019
+
1020
+        // Someone is logged in
1021
+        if (\OC::$server->getUserSession()->isLoggedIn()) {
1022
+            OC_App::loadApps();
1023
+            OC_User::setupBackends();
1024
+            OC_Util::setupFS();
1025
+            // FIXME
1026
+            // Redirect to default application
1027
+            OC_Util::redirectToDefaultPage();
1028
+        } else {
1029
+            // Not handled and not logged in
1030
+            header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1031
+        }
1032
+    }
1033
+
1034
+    /**
1035
+     * Check login: apache auth, auth token, basic auth
1036
+     *
1037
+     * @param OCP\IRequest $request
1038
+     * @return boolean
1039
+     */
1040
+    static function handleLogin(OCP\IRequest $request) {
1041
+        $userSession = self::$server->getUserSession();
1042
+        if (OC_User::handleApacheAuth()) {
1043
+            return true;
1044
+        }
1045
+        if ($userSession->tryTokenLogin($request)) {
1046
+            return true;
1047
+        }
1048
+        if (isset($_COOKIE['nc_username'])
1049
+            && isset($_COOKIE['nc_token'])
1050
+            && isset($_COOKIE['nc_session_id'])
1051
+            && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1052
+            return true;
1053
+        }
1054
+        if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1055
+            return true;
1056
+        }
1057
+        return false;
1058
+    }
1059
+
1060
+    protected static function handleAuthHeaders() {
1061
+        //copy http auth headers for apache+php-fcgid work around
1062
+        if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1063
+            $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1064
+        }
1065
+
1066
+        // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1067
+        $vars = array(
1068
+            'HTTP_AUTHORIZATION', // apache+php-cgi work around
1069
+            'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1070
+        );
1071
+        foreach ($vars as $var) {
1072
+            if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1073
+                list($name, $password) = explode(':', base64_decode($matches[1]), 2);
1074
+                $_SERVER['PHP_AUTH_USER'] = $name;
1075
+                $_SERVER['PHP_AUTH_PW'] = $password;
1076
+                break;
1077
+            }
1078
+        }
1079
+    }
1080 1080
 }
1081 1081
 
1082 1082
 OC::init();
Please login to merge, or discard this patch.
Spacing   +59 added lines, -59 removed lines patch added patch discarded remove patch
@@ -119,14 +119,14 @@  discard block
 block discarded – undo
119 119
 	 * the app path list is empty or contains an invalid path
120 120
 	 */
121 121
 	public static function initPaths() {
122
-		if(defined('PHPUNIT_CONFIG_DIR')) {
123
-			self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
124
-		} elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
125
-			self::$configDir = OC::$SERVERROOT . '/tests/config/';
126
-		} elseif($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
127
-			self::$configDir = rtrim($dir, '/') . '/';
122
+		if (defined('PHPUNIT_CONFIG_DIR')) {
123
+			self::$configDir = OC::$SERVERROOT.'/'.PHPUNIT_CONFIG_DIR.'/';
124
+		} elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT.'/tests/config/')) {
125
+			self::$configDir = OC::$SERVERROOT.'/tests/config/';
126
+		} elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
127
+			self::$configDir = rtrim($dir, '/').'/';
128 128
 		} else {
129
-			self::$configDir = OC::$SERVERROOT . '/config/';
129
+			self::$configDir = OC::$SERVERROOT.'/config/';
130 130
 		}
131 131
 		self::$config = new \OC\Config(self::$configDir);
132 132
 
@@ -148,9 +148,9 @@  discard block
 block discarded – undo
148 148
 			//make sure suburi follows the same rules as scriptName
149 149
 			if (substr(OC::$SUBURI, -9) != 'index.php') {
150 150
 				if (substr(OC::$SUBURI, -1) != '/') {
151
-					OC::$SUBURI = OC::$SUBURI . '/';
151
+					OC::$SUBURI = OC::$SUBURI.'/';
152 152
 				}
153
-				OC::$SUBURI = OC::$SUBURI . 'index.php';
153
+				OC::$SUBURI = OC::$SUBURI.'index.php';
154 154
 			}
155 155
 		}
156 156
 
@@ -162,7 +162,7 @@  discard block
 block discarded – undo
162 162
 				OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
163 163
 
164 164
 				if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
165
-					OC::$WEBROOT = '/' . OC::$WEBROOT;
165
+					OC::$WEBROOT = '/'.OC::$WEBROOT;
166 166
 				}
167 167
 			} else {
168 168
 				// The scriptName is not ending with OC::$SUBURI
@@ -191,11 +191,11 @@  discard block
 block discarded – undo
191 191
 					OC::$APPSROOTS[] = $paths;
192 192
 				}
193 193
 			}
194
-		} elseif (file_exists(OC::$SERVERROOT . '/apps')) {
195
-			OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
196
-		} elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
194
+		} elseif (file_exists(OC::$SERVERROOT.'/apps')) {
195
+			OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT.'/apps', 'url' => '/apps', 'writable' => true);
196
+		} elseif (file_exists(OC::$SERVERROOT.'/../apps')) {
197 197
 			OC::$APPSROOTS[] = array(
198
-				'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
198
+				'path' => rtrim(dirname(OC::$SERVERROOT), '/').'/apps',
199 199
 				'url' => '/apps',
200 200
 				'writable' => true
201 201
 			);
@@ -225,8 +225,8 @@  discard block
 block discarded – undo
225 225
 		$l = \OC::$server->getL10N('lib');
226 226
 
227 227
 		// Create config if it does not already exist
228
-		$configFilePath = self::$configDir .'/config.php';
229
-		if(!file_exists($configFilePath)) {
228
+		$configFilePath = self::$configDir.'/config.php';
229
+		if (!file_exists($configFilePath)) {
230 230
 			@touch($configFilePath);
231 231
 		}
232 232
 
@@ -241,13 +241,13 @@  discard block
 block discarded – undo
241 241
 				echo $l->t('Cannot write into "config" directory!')."\n";
242 242
 				echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
243 243
 				echo "\n";
244
-				echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-dir_permissions') ])."\n";
244
+				echo $l->t('See %s', [$urlGenerator->linkToDocs('admin-dir_permissions')])."\n";
245 245
 				exit;
246 246
 			} else {
247 247
 				OC_Template::printErrorPage(
248 248
 					$l->t('Cannot write into "config" directory!'),
249 249
 					$l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
250
-					 [ $urlGenerator->linkToDocs('admin-dir_permissions') ])
250
+					 [$urlGenerator->linkToDocs('admin-dir_permissions')])
251 251
 				);
252 252
 			}
253 253
 		}
@@ -262,8 +262,8 @@  discard block
 block discarded – undo
262 262
 			if (OC::$CLI) {
263 263
 				throw new Exception('Not installed');
264 264
 			} else {
265
-				$url = OC::$WEBROOT . '/index.php';
266
-				header('Location: ' . $url);
265
+				$url = OC::$WEBROOT.'/index.php';
266
+				header('Location: '.$url);
267 267
 			}
268 268
 			exit();
269 269
 		}
@@ -391,14 +391,14 @@  discard block
 block discarded – undo
391 391
 		$incompatibleShippedApps = [];
392 392
 		foreach ($incompatibleApps as $appInfo) {
393 393
 			if ($appManager->isShipped($appInfo['id'])) {
394
-				$incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
394
+				$incompatibleShippedApps[] = $appInfo['name'].' ('.$appInfo['id'].')';
395 395
 			}
396 396
 		}
397 397
 
398 398
 		if (!empty($incompatibleShippedApps)) {
399 399
 			$l = \OC::$server->getL10N('core');
400 400
 			$hint = $l->t('The files of the app %$1s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
401
-			throw new \OC\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
401
+			throw new \OC\HintException('The files of the app '.implode(', ', $incompatibleShippedApps).' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
402 402
 		}
403 403
 
404 404
 		$tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
@@ -413,7 +413,7 @@  discard block
 block discarded – undo
413 413
 		ini_set('session.cookie_httponly', true);
414 414
 
415 415
 		// set the cookie path to the Nextcloud directory
416
-		$cookie_path = OC::$WEBROOT ? : '/';
416
+		$cookie_path = OC::$WEBROOT ?: '/';
417 417
 		ini_set('session.cookie_path', $cookie_path);
418 418
 
419 419
 		// Let the session name be changed in the initSession Hook
@@ -447,7 +447,7 @@  discard block
 block discarded – undo
447 447
 		// session timeout
448 448
 		if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
449 449
 			if (isset($_COOKIE[session_name()])) {
450
-				setcookie(session_name(), null, -1, self::$WEBROOT ? : '/');
450
+				setcookie(session_name(), null, -1, self::$WEBROOT ?: '/');
451 451
 			}
452 452
 			\OC::$server->getUserSession()->logout();
453 453
 		}
@@ -469,7 +469,7 @@  discard block
 block discarded – undo
469 469
 				continue;
470 470
 			}
471 471
 
472
-			$file = $appPath . '/appinfo/classpath.php';
472
+			$file = $appPath.'/appinfo/classpath.php';
473 473
 			if (file_exists($file)) {
474 474
 				require_once $file;
475 475
 			}
@@ -497,14 +497,14 @@  discard block
 block discarded – undo
497 497
 
498 498
 		// Append __Host to the cookie if it meets the requirements
499 499
 		$cookiePrefix = '';
500
-		if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
500
+		if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
501 501
 			$cookiePrefix = '__Host-';
502 502
 		}
503 503
 
504
-		foreach($policies as $policy) {
504
+		foreach ($policies as $policy) {
505 505
 			header(
506 506
 				sprintf(
507
-					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
507
+					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;'.$secureCookie.'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
508 508
 					$cookiePrefix,
509 509
 					$policy,
510 510
 					$cookieParams['path'],
@@ -535,14 +535,14 @@  discard block
 block discarded – undo
535 535
 			// OS X Finder
536 536
 			'/^WebDAVFS/',
537 537
 		];
538
-		if($request->isUserAgent($incompatibleUserAgents)) {
538
+		if ($request->isUserAgent($incompatibleUserAgents)) {
539 539
 			return;
540 540
 		}
541 541
 
542
-		if(count($_COOKIE) > 0) {
542
+		if (count($_COOKIE) > 0) {
543 543
 			$requestUri = $request->getScriptName();
544 544
 			$processingScript = explode('/', $requestUri);
545
-			$processingScript = $processingScript[count($processingScript)-1];
545
+			$processingScript = $processingScript[count($processingScript) - 1];
546 546
 			// FIXME: In a SAML scenario we don't get any strict or lax cookie
547 547
 			// send for the ACS endpoint. Since we have some legacy code in Nextcloud
548 548
 			// (direct PHP files) the enforcement of lax cookies is performed here
@@ -555,26 +555,26 @@  discard block
 block discarded – undo
555 555
 			// the verification into a middleware and also adds some exemptions.
556 556
 			//
557 557
 			// Questions about this code? Ask Lukas ;-)
558
-			$currentUrl = substr(explode('?',$request->getRequestUri(), 2)[0], strlen(\OC::$WEBROOT));
559
-			if($currentUrl === '/index.php/apps/user_saml/saml/acs' || $currentUrl === '/apps/user_saml/saml/acs') {
558
+			$currentUrl = substr(explode('?', $request->getRequestUri(), 2)[0], strlen(\OC::$WEBROOT));
559
+			if ($currentUrl === '/index.php/apps/user_saml/saml/acs' || $currentUrl === '/apps/user_saml/saml/acs') {
560 560
 				return;
561 561
 			}
562 562
 			// index.php routes are handled in the middleware
563
-			if($processingScript === 'index.php') {
563
+			if ($processingScript === 'index.php') {
564 564
 				return;
565 565
 			}
566 566
 
567 567
 			// All other endpoints require the lax and the strict cookie
568
-			if(!$request->passesStrictCookieCheck()) {
568
+			if (!$request->passesStrictCookieCheck()) {
569 569
 				self::sendSameSiteCookies();
570 570
 				// Debug mode gets access to the resources without strict cookie
571 571
 				// due to the fact that the SabreDAV browser also lives there.
572
-				if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
572
+				if (!\OC::$server->getConfig()->getSystemValue('debug', false)) {
573 573
 					http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
574 574
 					exit();
575 575
 				}
576 576
 			}
577
-		} elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
577
+		} elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
578 578
 			self::sendSameSiteCookies();
579 579
 		}
580 580
 	}
@@ -585,12 +585,12 @@  discard block
 block discarded – undo
585 585
 
586 586
 		// register autoloader
587 587
 		$loaderStart = microtime(true);
588
-		require_once __DIR__ . '/autoloader.php';
588
+		require_once __DIR__.'/autoloader.php';
589 589
 		self::$loader = new \OC\Autoloader([
590
-			OC::$SERVERROOT . '/lib/private/legacy',
590
+			OC::$SERVERROOT.'/lib/private/legacy',
591 591
 		]);
592 592
 		if (defined('PHPUNIT_RUN')) {
593
-			self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
593
+			self::$loader->addValidRoot(OC::$SERVERROOT.'/tests');
594 594
 		}
595 595
 		spl_autoload_register(array(self::$loader, 'load'));
596 596
 		$loaderEnd = microtime(true);
@@ -598,12 +598,12 @@  discard block
 block discarded – undo
598 598
 		self::$CLI = (php_sapi_name() == 'cli');
599 599
 
600 600
 		// Add default composer PSR-4 autoloader
601
-		self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
601
+		self::$composerAutoloader = require_once OC::$SERVERROOT.'/lib/composer/autoload.php';
602 602
 
603 603
 		try {
604 604
 			self::initPaths();
605 605
 			// setup 3rdparty autoloader
606
-			$vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
606
+			$vendorAutoLoad = OC::$SERVERROOT.'/3rdparty/autoload.php';
607 607
 			if (!file_exists($vendorAutoLoad)) {
608 608
 				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".');
609 609
 			}
@@ -613,7 +613,7 @@  discard block
 block discarded – undo
613 613
 			if (!self::$CLI) {
614 614
 				$claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']);
615 615
 				$protocol = in_array($claimedProtocol, ['HTTP/1.0', 'HTTP/1.1', 'HTTP/2']) ? $claimedProtocol : 'HTTP/1.1';
616
-				header($protocol . ' ' . OC_Response::STATUS_SERVICE_UNAVAILABLE);
616
+				header($protocol.' '.OC_Response::STATUS_SERVICE_UNAVAILABLE);
617 617
 			}
618 618
 			// we can't use the template error page here, because this needs the
619 619
 			// DI container which isn't available yet
@@ -631,7 +631,7 @@  discard block
 block discarded – undo
631 631
 		@ini_set('display_errors', 0);
632 632
 		@ini_set('log_errors', 1);
633 633
 
634
-		if(!date_default_timezone_set('UTC')) {
634
+		if (!date_default_timezone_set('UTC')) {
635 635
 			throw new \RuntimeException('Could not set timezone to UTC');
636 636
 		};
637 637
 
@@ -675,7 +675,7 @@  discard block
 block discarded – undo
675 675
 		self::checkInstalled();
676 676
 
677 677
 		OC_Response::addSecurityHeaders();
678
-		if(self::$server->getRequest()->getServerProtocol() === 'https') {
678
+		if (self::$server->getRequest()->getServerProtocol() === 'https') {
679 679
 			ini_set('session.cookie_secure', true);
680 680
 		}
681 681
 
@@ -688,11 +688,11 @@  discard block
 block discarded – undo
688 688
 					// Convert l10n string into regular string for usage in database
689 689
 					$staticErrors = [];
690 690
 					foreach ($errors as $error) {
691
-						echo $error['error'] . "\n";
692
-						echo $error['hint'] . "\n\n";
691
+						echo $error['error']."\n";
692
+						echo $error['hint']."\n\n";
693 693
 						$staticErrors[] = [
694
-							'error' => (string)$error['error'],
695
-							'hint' => (string)$error['hint'],
694
+							'error' => (string) $error['error'],
695
+							'hint' => (string) $error['hint'],
696 696
 						];
697 697
 					}
698 698
 
@@ -714,7 +714,7 @@  discard block
 block discarded – undo
714 714
 		}
715 715
 		//try to set the session lifetime
716 716
 		$sessionLifeTime = self::getSessionLifeTime();
717
-		@ini_set('gc_maxlifetime', (string)$sessionLifeTime);
717
+		@ini_set('gc_maxlifetime', (string) $sessionLifeTime);
718 718
 
719 719
 		$systemConfig = \OC::$server->getSystemConfig();
720 720
 
@@ -761,7 +761,7 @@  discard block
 block discarded – undo
761 761
 		register_shutdown_function(array($lockProvider, 'releaseAll'));
762 762
 
763 763
 		// Check whether the sample configuration has been copied
764
-		if($systemConfig->getValue('copied_sample_config', false)) {
764
+		if ($systemConfig->getValue('copied_sample_config', false)) {
765 765
 			$l = \OC::$server->getL10N('lib');
766 766
 			header('HTTP/1.1 503 Service Temporarily Unavailable');
767 767
 			header('Status: 503 Service Temporarily Unavailable');
@@ -787,7 +787,7 @@  discard block
 block discarded – undo
787 787
 		) {
788 788
 			// Allow access to CSS resources
789 789
 			$isScssRequest = false;
790
-			if(strpos($request->getPathInfo(), '/css/') === 0) {
790
+			if (strpos($request->getPathInfo(), '/css/') === 0) {
791 791
 				$isScssRequest = true;
792 792
 			}
793 793
 
@@ -823,7 +823,7 @@  discard block
 block discarded – undo
823 823
 
824 824
 			// NOTE: This will be replaced to use OCP
825 825
 			$userSession = self::$server->getUserSession();
826
-			$userSession->listen('\OC\User', 'postLogin', function () {
826
+			$userSession->listen('\OC\User', 'postLogin', function() {
827 827
 				try {
828 828
 					$cache = new \OC\Cache\File();
829 829
 					$cache->gc();
@@ -835,7 +835,7 @@  discard block
 block discarded – undo
835 835
 				} catch (\Exception $e) {
836 836
 					// a GC exception should not prevent users from using OC,
837 837
 					// so log the exception
838
-					\OC::$server->getLogger()->warning('Exception when running cache gc: ' . $e->getMessage(), array('app' => 'core'));
838
+					\OC::$server->getLogger()->warning('Exception when running cache gc: '.$e->getMessage(), array('app' => 'core'));
839 839
 				}
840 840
 			});
841 841
 		}
@@ -851,7 +851,7 @@  discard block
 block discarded – undo
851 851
 			/** @var \OCP\App\ManagerEvent $event */
852 852
 			$jobList = \OC::$server->getJobList();
853 853
 			$job = 'OC\\Settings\\RemoveOrphaned';
854
-			if(!($jobList->has($job, null))) {
854
+			if (!($jobList->has($job, null))) {
855 855
 				$jobList->add($job);
856 856
 			}
857 857
 		});
@@ -961,12 +961,12 @@  discard block
 block discarded – undo
961 961
 		// emergency app disabling
962 962
 		if ($requestPath === '/disableapp'
963 963
 			&& $request->getMethod() === 'POST'
964
-			&& ((array)$request->getParam('appid')) !== ''
964
+			&& ((array) $request->getParam('appid')) !== ''
965 965
 		) {
966 966
 			\OCP\JSON::callCheck();
967 967
 			\OCP\JSON::checkAdminUser();
968
-			$appIds = (array)$request->getParam('appid');
969
-			foreach($appIds as $appId) {
968
+			$appIds = (array) $request->getParam('appid');
969
+			foreach ($appIds as $appId) {
970 970
 				$appId = \OC_App::cleanAppId($appId);
971 971
 				\OC_App::disable($appId);
972 972
 			}
@@ -981,7 +981,7 @@  discard block
 block discarded – undo
981 981
 		if (!self::checkUpgrade(false)
982 982
 			&& !$systemConfig->getValue('maintenance', false)) {
983 983
 			// For logged-in users: Load everything
984
-			if(\OC::$server->getUserSession()->isLoggedIn()) {
984
+			if (\OC::$server->getUserSession()->isLoggedIn()) {
985 985
 				OC_App::loadApps();
986 986
 			} else {
987 987
 				// For guests: Load only filesystem and logging
Please login to merge, or discard this patch.
Middleware/Security/Exceptions/LaxSameSiteCookieFailedException.php 1 patch
Indentation   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -32,7 +32,7 @@
 block discarded – undo
32 32
  * @package OC\AppFramework\Middleware\Security\Exceptions
33 33
  */
34 34
 class LaxSameSiteCookieFailedException extends SecurityException {
35
-	public function __construct() {
36
-		parent::__construct('Lax Same Site Cookie is invalid in request.', Http::STATUS_PRECONDITION_FAILED);
37
-	}
35
+    public function __construct() {
36
+        parent::__construct('Lax Same Site Cookie is invalid in request.', Http::STATUS_PRECONDITION_FAILED);
37
+    }
38 38
 }
Please login to merge, or discard this patch.