Passed
Push — master ( 114b47...fbbb48 )
by Julius
15:20 queued 10s
created
lib/private/AppFramework/Http/Request.php 1 patch
Indentation   +871 added lines, -871 removed lines patch added patch discarded remove patch
@@ -63,875 +63,875 @@
 block discarded – undo
63 63
  * @property mixed[] server
64 64
  */
65 65
 class Request implements \ArrayAccess, \Countable, IRequest {
66
-	public const USER_AGENT_IE = '/(MSIE)|(Trident)/';
67
-	// Microsoft Edge User Agent from https://msdn.microsoft.com/en-us/library/hh869301(v=vs.85).aspx
68
-	public 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.]+$/';
69
-	// Firefox User Agent from https://developer.mozilla.org/en-US/docs/Web/HTTP/Gecko_user_agent_string_reference
70
-	public const USER_AGENT_FIREFOX = '/^Mozilla\/5\.0 \([^)]+\) Gecko\/[0-9.]+ Firefox\/[0-9.]+$/';
71
-	// Chrome User Agent from https://developer.chrome.com/multidevice/user-agent
72
-	public 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.]+( (Vivaldi|Brave|OPR)\/[0-9.]+|)$/';
73
-	// Safari User Agent from http://www.useragentstring.com/pages/Safari/
74
-	public const USER_AGENT_SAFARI = '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\) Version\/[0-9.]+ Safari\/[0-9.A-Z]+$/';
75
-	// Android Chrome user agent: https://developers.google.com/chrome/mobile/docs/user-agent
76
-	public const USER_AGENT_ANDROID_MOBILE_CHROME = '#Android.*Chrome/[.0-9]*#';
77
-	public const USER_AGENT_FREEBOX = '#^Mozilla/5\.0$#';
78
-	public const REGEX_LOCALHOST = '/^(127\.0\.0\.1|localhost|\[::1\])$/';
79
-
80
-	/**
81
-	 * @deprecated use \OCP\IRequest::USER_AGENT_CLIENT_IOS instead
82
-	 */
83
-	public const USER_AGENT_OWNCLOUD_IOS = '/^Mozilla\/5\.0 \(iOS\) (ownCloud|Nextcloud)\-iOS.*$/';
84
-	/**
85
-	 * @deprecated use \OCP\IRequest::USER_AGENT_CLIENT_ANDROID instead
86
-	 */
87
-	public const USER_AGENT_OWNCLOUD_ANDROID = '/^Mozilla\/5\.0 \(Android\) ownCloud\-android.*$/';
88
-	/**
89
-	 * @deprecated use \OCP\IRequest::USER_AGENT_CLIENT_DESKTOP instead
90
-	 */
91
-	public const USER_AGENT_OWNCLOUD_DESKTOP = '/^Mozilla\/5\.0 \([A-Za-z ]+\) (mirall|csyncoC)\/.*$/';
92
-
93
-	protected $inputStream;
94
-	protected $content;
95
-	protected $items = [];
96
-	protected $allowedKeys = [
97
-		'get',
98
-		'post',
99
-		'files',
100
-		'server',
101
-		'env',
102
-		'cookies',
103
-		'urlParams',
104
-		'parameters',
105
-		'method',
106
-		'requesttoken',
107
-	];
108
-	/** @var ISecureRandom */
109
-	protected $secureRandom;
110
-	/** @var IConfig */
111
-	protected $config;
112
-	/** @var string */
113
-	protected $requestId = '';
114
-	/** @var ICrypto */
115
-	protected $crypto;
116
-	/** @var CsrfTokenManager|null */
117
-	protected $csrfTokenManager;
118
-
119
-	/** @var bool */
120
-	protected $contentDecoded = false;
121
-
122
-	/**
123
-	 * @param array $vars An associative array with the following optional values:
124
-	 *        - array 'urlParams' the parameters which were matched from the URL
125
-	 *        - array 'get' the $_GET array
126
-	 *        - array|string 'post' the $_POST array or JSON string
127
-	 *        - array 'files' the $_FILES array
128
-	 *        - array 'server' the $_SERVER array
129
-	 *        - array 'env' the $_ENV array
130
-	 *        - array 'cookies' the $_COOKIE array
131
-	 *        - string 'method' the request method (GET, POST etc)
132
-	 *        - string|false 'requesttoken' the requesttoken or false when not available
133
-	 * @param ISecureRandom $secureRandom
134
-	 * @param IConfig $config
135
-	 * @param CsrfTokenManager|null $csrfTokenManager
136
-	 * @param string $stream
137
-	 * @see http://www.php.net/manual/en/reserved.variables.php
138
-	 */
139
-	public function __construct(array $vars,
140
-								ISecureRandom $secureRandom,
141
-								IConfig $config,
142
-								CsrfTokenManager $csrfTokenManager = null,
143
-								string $stream = 'php://input') {
144
-		$this->inputStream = $stream;
145
-		$this->items['params'] = [];
146
-		$this->secureRandom = $secureRandom;
147
-		$this->config = $config;
148
-		$this->csrfTokenManager = $csrfTokenManager;
149
-
150
-		if (!array_key_exists('method', $vars)) {
151
-			$vars['method'] = 'GET';
152
-		}
153
-
154
-		foreach ($this->allowedKeys as $name) {
155
-			$this->items[$name] = isset($vars[$name])
156
-				? $vars[$name]
157
-				: [];
158
-		}
159
-
160
-		$this->items['parameters'] = array_merge(
161
-			$this->items['get'],
162
-			$this->items['post'],
163
-			$this->items['urlParams'],
164
-			$this->items['params']
165
-		);
166
-	}
167
-	/**
168
-	 * @param array $parameters
169
-	 */
170
-	public function setUrlParameters(array $parameters) {
171
-		$this->items['urlParams'] = $parameters;
172
-		$this->items['parameters'] = array_merge(
173
-			$this->items['parameters'],
174
-			$this->items['urlParams']
175
-		);
176
-	}
177
-
178
-	/**
179
-	 * Countable method
180
-	 * @return int
181
-	 */
182
-	public function count(): int {
183
-		return \count($this->items['parameters']);
184
-	}
185
-
186
-	/**
187
-	 * ArrayAccess methods
188
-	 *
189
-	 * Gives access to the combined GET, POST and urlParams arrays
190
-	 *
191
-	 * Examples:
192
-	 *
193
-	 * $var = $request['myvar'];
194
-	 *
195
-	 * or
196
-	 *
197
-	 * if(!isset($request['myvar']) {
198
-	 * 	// Do something
199
-	 * }
200
-	 *
201
-	 * $request['myvar'] = 'something'; // This throws an exception.
202
-	 *
203
-	 * @param string $offset The key to lookup
204
-	 * @return boolean
205
-	 */
206
-	public function offsetExists($offset): bool {
207
-		return isset($this->items['parameters'][$offset]);
208
-	}
209
-
210
-	/**
211
-	 * @see offsetExists
212
-	 * @param string $offset
213
-	 * @return mixed
214
-	 */
215
-	public function offsetGet($offset) {
216
-		return isset($this->items['parameters'][$offset])
217
-			? $this->items['parameters'][$offset]
218
-			: null;
219
-	}
220
-
221
-	/**
222
-	 * @see offsetExists
223
-	 * @param string $offset
224
-	 * @param mixed $value
225
-	 */
226
-	public function offsetSet($offset, $value) {
227
-		throw new \RuntimeException('You cannot change the contents of the request object');
228
-	}
229
-
230
-	/**
231
-	 * @see offsetExists
232
-	 * @param string $offset
233
-	 */
234
-	public function offsetUnset($offset) {
235
-		throw new \RuntimeException('You cannot change the contents of the request object');
236
-	}
237
-
238
-	/**
239
-	 * Magic property accessors
240
-	 * @param string $name
241
-	 * @param mixed $value
242
-	 */
243
-	public function __set($name, $value) {
244
-		throw new \RuntimeException('You cannot change the contents of the request object');
245
-	}
246
-
247
-	/**
248
-	 * Access request variables by method and name.
249
-	 * Examples:
250
-	 *
251
-	 * $request->post['myvar']; // Only look for POST variables
252
-	 * $request->myvar; or $request->{'myvar'}; or $request->{$myvar}
253
-	 * Looks in the combined GET, POST and urlParams array.
254
-	 *
255
-	 * If you access e.g. ->post but the current HTTP request method
256
-	 * is GET a \LogicException will be thrown.
257
-	 *
258
-	 * @param string $name The key to look for.
259
-	 * @throws \LogicException
260
-	 * @return mixed|null
261
-	 */
262
-	public function __get($name) {
263
-		switch ($name) {
264
-			case 'put':
265
-			case 'patch':
266
-			case 'get':
267
-			case 'post':
268
-				if ($this->method !== strtoupper($name)) {
269
-					throw new \LogicException(sprintf('%s cannot be accessed in a %s request.', $name, $this->method));
270
-				}
271
-				return $this->getContent();
272
-			case 'files':
273
-			case 'server':
274
-			case 'env':
275
-			case 'cookies':
276
-			case 'urlParams':
277
-			case 'method':
278
-				return isset($this->items[$name])
279
-					? $this->items[$name]
280
-					: null;
281
-			case 'parameters':
282
-			case 'params':
283
-				return $this->getContent();
284
-			default:
285
-				return isset($this[$name])
286
-					? $this[$name]
287
-					: null;
288
-		}
289
-	}
290
-
291
-	/**
292
-	 * @param string $name
293
-	 * @return bool
294
-	 */
295
-	public function __isset($name) {
296
-		if (\in_array($name, $this->allowedKeys, true)) {
297
-			return true;
298
-		}
299
-		return isset($this->items['parameters'][$name]);
300
-	}
301
-
302
-	/**
303
-	 * @param string $id
304
-	 */
305
-	public function __unset($id) {
306
-		throw new \RuntimeException('You cannot change the contents of the request object');
307
-	}
308
-
309
-	/**
310
-	 * Returns the value for a specific http header.
311
-	 *
312
-	 * This method returns an empty string if the header did not exist.
313
-	 *
314
-	 * @param string $name
315
-	 * @return string
316
-	 */
317
-	public function getHeader(string $name): string {
318
-		$name = strtoupper(str_replace('-', '_',$name));
319
-		if (isset($this->server['HTTP_' . $name])) {
320
-			return $this->server['HTTP_' . $name];
321
-		}
322
-
323
-		// There's a few headers that seem to end up in the top-level
324
-		// server array.
325
-		switch ($name) {
326
-			case 'CONTENT_TYPE':
327
-			case 'CONTENT_LENGTH':
328
-			case 'REMOTE_ADDR':
329
-				if (isset($this->server[$name])) {
330
-					return $this->server[$name];
331
-				}
332
-				break;
333
-		}
334
-
335
-		return '';
336
-	}
337
-
338
-	/**
339
-	 * Lets you access post and get parameters by the index
340
-	 * In case of json requests the encoded json body is accessed
341
-	 *
342
-	 * @param string $key the key which you want to access in the URL Parameter
343
-	 *                     placeholder, $_POST or $_GET array.
344
-	 *                     The priority how they're returned is the following:
345
-	 *                     1. URL parameters
346
-	 *                     2. POST parameters
347
-	 *                     3. GET parameters
348
-	 * @param mixed $default If the key is not found, this value will be returned
349
-	 * @return mixed the content of the array
350
-	 */
351
-	public function getParam(string $key, $default = null) {
352
-		return isset($this->parameters[$key])
353
-			? $this->parameters[$key]
354
-			: $default;
355
-	}
356
-
357
-	/**
358
-	 * Returns all params that were received, be it from the request
359
-	 * (as GET or POST) or throuh the URL by the route
360
-	 * @return array the array with all parameters
361
-	 */
362
-	public function getParams(): array {
363
-		return is_array($this->parameters) ? $this->parameters : [];
364
-	}
365
-
366
-	/**
367
-	 * Returns the method of the request
368
-	 * @return string the method of the request (POST, GET, etc)
369
-	 */
370
-	public function getMethod(): string {
371
-		return $this->method;
372
-	}
373
-
374
-	/**
375
-	 * Shortcut for accessing an uploaded file through the $_FILES array
376
-	 * @param string $key the key that will be taken from the $_FILES array
377
-	 * @return array the file in the $_FILES element
378
-	 */
379
-	public function getUploadedFile(string $key) {
380
-		return isset($this->files[$key]) ? $this->files[$key] : null;
381
-	}
382
-
383
-	/**
384
-	 * Shortcut for getting env variables
385
-	 * @param string $key the key that will be taken from the $_ENV array
386
-	 * @return array the value in the $_ENV element
387
-	 */
388
-	public function getEnv(string $key) {
389
-		return isset($this->env[$key]) ? $this->env[$key] : null;
390
-	}
391
-
392
-	/**
393
-	 * Shortcut for getting cookie variables
394
-	 * @param string $key the key that will be taken from the $_COOKIE array
395
-	 * @return string the value in the $_COOKIE element
396
-	 */
397
-	public function getCookie(string $key) {
398
-		return isset($this->cookies[$key]) ? $this->cookies[$key] : null;
399
-	}
400
-
401
-	/**
402
-	 * Returns the request body content.
403
-	 *
404
-	 * If the HTTP request method is PUT and the body
405
-	 * not application/x-www-form-urlencoded or application/json a stream
406
-	 * resource is returned, otherwise an array.
407
-	 *
408
-	 * @return array|string|resource The request body content or a resource to read the body stream.
409
-	 *
410
-	 * @throws \LogicException
411
-	 */
412
-	protected function getContent() {
413
-		// If the content can't be parsed into an array then return a stream resource.
414
-		if ($this->method === 'PUT'
415
-			&& $this->getHeader('Content-Length') !== '0'
416
-			&& $this->getHeader('Content-Length') !== ''
417
-			&& strpos($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded') === false
418
-			&& strpos($this->getHeader('Content-Type'), 'application/json') === false
419
-		) {
420
-			if ($this->content === false) {
421
-				throw new \LogicException(
422
-					'"put" can only be accessed once if not '
423
-					. 'application/x-www-form-urlencoded or application/json.'
424
-				);
425
-			}
426
-			$this->content = false;
427
-			return fopen($this->inputStream, 'rb');
428
-		} else {
429
-			$this->decodeContent();
430
-			return $this->items['parameters'];
431
-		}
432
-	}
433
-
434
-	/**
435
-	 * Attempt to decode the content and populate parameters
436
-	 */
437
-	protected function decodeContent() {
438
-		if ($this->contentDecoded) {
439
-			return;
440
-		}
441
-		$params = [];
442
-
443
-		// 'application/json' must be decoded manually.
444
-		if (strpos($this->getHeader('Content-Type'), 'application/json') !== false) {
445
-			$params = json_decode(file_get_contents($this->inputStream), true);
446
-			if ($params !== null && \count($params) > 0) {
447
-				$this->items['params'] = $params;
448
-				if ($this->method === 'POST') {
449
-					$this->items['post'] = $params;
450
-				}
451
-			}
452
-
453
-			// Handle application/x-www-form-urlencoded for methods other than GET
454
-		// or post correctly
455
-		} elseif ($this->method !== 'GET'
456
-				&& $this->method !== 'POST'
457
-				&& strpos($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded') !== false) {
458
-			parse_str(file_get_contents($this->inputStream), $params);
459
-			if (\is_array($params)) {
460
-				$this->items['params'] = $params;
461
-			}
462
-		}
463
-
464
-		if (\is_array($params)) {
465
-			$this->items['parameters'] = array_merge($this->items['parameters'], $params);
466
-		}
467
-		$this->contentDecoded = true;
468
-	}
469
-
470
-
471
-	/**
472
-	 * Checks if the CSRF check was correct
473
-	 * @return bool true if CSRF check passed
474
-	 */
475
-	public function passesCSRFCheck(): bool {
476
-		if ($this->csrfTokenManager === null) {
477
-			return false;
478
-		}
479
-
480
-		if (!$this->passesStrictCookieCheck()) {
481
-			return false;
482
-		}
483
-
484
-		if (isset($this->items['get']['requesttoken'])) {
485
-			$token = $this->items['get']['requesttoken'];
486
-		} elseif (isset($this->items['post']['requesttoken'])) {
487
-			$token = $this->items['post']['requesttoken'];
488
-		} elseif (isset($this->items['server']['HTTP_REQUESTTOKEN'])) {
489
-			$token = $this->items['server']['HTTP_REQUESTTOKEN'];
490
-		} else {
491
-			//no token found.
492
-			return false;
493
-		}
494
-		$token = new CsrfToken($token);
495
-
496
-		return $this->csrfTokenManager->isTokenValid($token);
497
-	}
498
-
499
-	/**
500
-	 * Whether the cookie checks are required
501
-	 *
502
-	 * @return bool
503
-	 */
504
-	private function cookieCheckRequired(): bool {
505
-		if ($this->getHeader('OCS-APIREQUEST')) {
506
-			return false;
507
-		}
508
-		if ($this->getCookie(session_name()) === null && $this->getCookie('nc_token') === null) {
509
-			return false;
510
-		}
511
-
512
-		return true;
513
-	}
514
-
515
-	/**
516
-	 * Wrapper around session_get_cookie_params
517
-	 *
518
-	 * @return array
519
-	 */
520
-	public function getCookieParams(): array {
521
-		return session_get_cookie_params();
522
-	}
523
-
524
-	/**
525
-	 * Appends the __Host- prefix to the cookie if applicable
526
-	 *
527
-	 * @param string $name
528
-	 * @return string
529
-	 */
530
-	protected function getProtectedCookieName(string $name): string {
531
-		$cookieParams = $this->getCookieParams();
532
-		$prefix = '';
533
-		if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
534
-			$prefix = '__Host-';
535
-		}
536
-
537
-		return $prefix.$name;
538
-	}
539
-
540
-	/**
541
-	 * Checks if the strict cookie has been sent with the request if the request
542
-	 * is including any cookies.
543
-	 *
544
-	 * @return bool
545
-	 * @since 9.1.0
546
-	 */
547
-	public function passesStrictCookieCheck(): bool {
548
-		if (!$this->cookieCheckRequired()) {
549
-			return true;
550
-		}
551
-
552
-		$cookieName = $this->getProtectedCookieName('nc_sameSiteCookiestrict');
553
-		if ($this->getCookie($cookieName) === 'true'
554
-			&& $this->passesLaxCookieCheck()) {
555
-			return true;
556
-		}
557
-		return false;
558
-	}
559
-
560
-	/**
561
-	 * Checks if the lax cookie has been sent with the request if the request
562
-	 * is including any cookies.
563
-	 *
564
-	 * @return bool
565
-	 * @since 9.1.0
566
-	 */
567
-	public function passesLaxCookieCheck(): bool {
568
-		if (!$this->cookieCheckRequired()) {
569
-			return true;
570
-		}
571
-
572
-		$cookieName = $this->getProtectedCookieName('nc_sameSiteCookielax');
573
-		if ($this->getCookie($cookieName) === 'true') {
574
-			return true;
575
-		}
576
-		return false;
577
-	}
578
-
579
-
580
-	/**
581
-	 * Returns an ID for the request, value is not guaranteed to be unique and is mostly meant for logging
582
-	 * If `mod_unique_id` is installed this value will be taken.
583
-	 * @return string
584
-	 */
585
-	public function getId(): string {
586
-		if (isset($this->server['UNIQUE_ID'])) {
587
-			return $this->server['UNIQUE_ID'];
588
-		}
589
-
590
-		if (empty($this->requestId)) {
591
-			$validChars = ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS;
592
-			$this->requestId = $this->secureRandom->generate(20, $validChars);
593
-		}
594
-
595
-		return $this->requestId;
596
-	}
597
-
598
-	/**
599
-	 * Checks if given $remoteAddress matches given $trustedProxy.
600
-	 * If $trustedProxy is an IPv4 IP range given in CIDR notation, true will be returned if
601
-	 * $remoteAddress is an IPv4 address within that IP range.
602
-	 * Otherwise $remoteAddress will be compared to $trustedProxy literally and the result
603
-	 * will be returned.
604
-	 * @return boolean true if $remoteAddress matches $trustedProxy, false otherwise
605
-	 */
606
-	protected function matchesTrustedProxy($trustedProxy, $remoteAddress) {
607
-		$cidrre = '/^([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})\/([0-9]{1,2})$/';
608
-
609
-		if (preg_match($cidrre, $trustedProxy, $match)) {
610
-			$net = $match[1];
611
-			$shiftbits = min(32, max(0, 32 - intval($match[2])));
612
-			$netnum = ip2long($net) >> $shiftbits;
613
-			$ipnum = ip2long($remoteAddress) >> $shiftbits;
614
-
615
-			return $ipnum === $netnum;
616
-		}
617
-
618
-		return $trustedProxy === $remoteAddress;
619
-	}
620
-
621
-	/**
622
-	 * Checks if given $remoteAddress matches any entry in the given array $trustedProxies.
623
-	 * For details regarding what "match" means, refer to `matchesTrustedProxy`.
624
-	 * @return boolean true if $remoteAddress matches any entry in $trustedProxies, false otherwise
625
-	 */
626
-	protected function isTrustedProxy($trustedProxies, $remoteAddress) {
627
-		foreach ($trustedProxies as $tp) {
628
-			if ($this->matchesTrustedProxy($tp, $remoteAddress)) {
629
-				return true;
630
-			}
631
-		}
632
-
633
-		return false;
634
-	}
635
-
636
-	/**
637
-	 * Returns the remote address, if the connection came from a trusted proxy
638
-	 * and `forwarded_for_headers` has been configured then the IP address
639
-	 * specified in this header will be returned instead.
640
-	 * Do always use this instead of $_SERVER['REMOTE_ADDR']
641
-	 * @return string IP address
642
-	 */
643
-	public function getRemoteAddress(): string {
644
-		$remoteAddress = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
645
-		$trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
646
-
647
-		if (\is_array($trustedProxies) && $this->isTrustedProxy($trustedProxies, $remoteAddress)) {
648
-			$forwardedForHeaders = $this->config->getSystemValue('forwarded_for_headers', [
649
-				'HTTP_X_FORWARDED_FOR'
650
-				// only have one default, so we cannot ship an insecure product out of the box
651
-			]);
652
-
653
-			foreach ($forwardedForHeaders as $header) {
654
-				if (isset($this->server[$header])) {
655
-					foreach (explode(',', $this->server[$header]) as $IP) {
656
-						$IP = trim($IP);
657
-
658
-						// remove brackets from IPv6 addresses
659
-						if (strpos($IP, '[') === 0 && substr($IP, -1) === ']') {
660
-							$IP = substr($IP, 1, -1);
661
-						}
662
-
663
-						if (filter_var($IP, FILTER_VALIDATE_IP) !== false) {
664
-							return $IP;
665
-						}
666
-					}
667
-				}
668
-			}
669
-		}
670
-
671
-		return $remoteAddress;
672
-	}
673
-
674
-	/**
675
-	 * Check overwrite condition
676
-	 * @param string $type
677
-	 * @return bool
678
-	 */
679
-	private function isOverwriteCondition(string $type = ''): bool {
680
-		$regex = '/' . $this->config->getSystemValue('overwritecondaddr', '')  . '/';
681
-		$remoteAddr = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
682
-		return $regex === '//' || preg_match($regex, $remoteAddr) === 1
683
-		|| $type !== 'protocol';
684
-	}
685
-
686
-	/**
687
-	 * Returns the server protocol. It respects one or more reverse proxies servers
688
-	 * and load balancers
689
-	 * @return string Server protocol (http or https)
690
-	 */
691
-	public function getServerProtocol(): string {
692
-		if ($this->config->getSystemValue('overwriteprotocol') !== ''
693
-			&& $this->isOverwriteCondition('protocol')) {
694
-			return $this->config->getSystemValue('overwriteprotocol');
695
-		}
696
-
697
-		if ($this->fromTrustedProxy() && isset($this->server['HTTP_X_FORWARDED_PROTO'])) {
698
-			if (strpos($this->server['HTTP_X_FORWARDED_PROTO'], ',') !== false) {
699
-				$parts = explode(',', $this->server['HTTP_X_FORWARDED_PROTO']);
700
-				$proto = strtolower(trim($parts[0]));
701
-			} else {
702
-				$proto = strtolower($this->server['HTTP_X_FORWARDED_PROTO']);
703
-			}
704
-
705
-			// Verify that the protocol is always HTTP or HTTPS
706
-			// default to http if an invalid value is provided
707
-			return $proto === 'https' ? 'https' : 'http';
708
-		}
709
-
710
-		if (isset($this->server['HTTPS'])
711
-			&& $this->server['HTTPS'] !== null
712
-			&& $this->server['HTTPS'] !== 'off'
713
-			&& $this->server['HTTPS'] !== '') {
714
-			return 'https';
715
-		}
716
-
717
-		return 'http';
718
-	}
719
-
720
-	/**
721
-	 * Returns the used HTTP protocol.
722
-	 *
723
-	 * @return string HTTP protocol. HTTP/2, HTTP/1.1 or HTTP/1.0.
724
-	 */
725
-	public function getHttpProtocol(): string {
726
-		$claimedProtocol = $this->server['SERVER_PROTOCOL'];
727
-
728
-		if (\is_string($claimedProtocol)) {
729
-			$claimedProtocol = strtoupper($claimedProtocol);
730
-		}
731
-
732
-		$validProtocols = [
733
-			'HTTP/1.0',
734
-			'HTTP/1.1',
735
-			'HTTP/2',
736
-		];
737
-
738
-		if (\in_array($claimedProtocol, $validProtocols, true)) {
739
-			return $claimedProtocol;
740
-		}
741
-
742
-		return 'HTTP/1.1';
743
-	}
744
-
745
-	/**
746
-	 * Returns the request uri, even if the website uses one or more
747
-	 * reverse proxies
748
-	 * @return string
749
-	 */
750
-	public function getRequestUri(): string {
751
-		$uri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : '';
752
-		if ($this->config->getSystemValue('overwritewebroot') !== '' && $this->isOverwriteCondition()) {
753
-			$uri = $this->getScriptName() . substr($uri, \strlen($this->server['SCRIPT_NAME']));
754
-		}
755
-		return $uri;
756
-	}
757
-
758
-	/**
759
-	 * Get raw PathInfo from request (not urldecoded)
760
-	 * @throws \Exception
761
-	 * @return string Path info
762
-	 */
763
-	public function getRawPathInfo(): string {
764
-		$requestUri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : '';
765
-		// remove too many slashes - can be caused by reverse proxy configuration
766
-		$requestUri = preg_replace('%/{2,}%', '/', $requestUri);
767
-
768
-		// Remove the query string from REQUEST_URI
769
-		if ($pos = strpos($requestUri, '?')) {
770
-			$requestUri = substr($requestUri, 0, $pos);
771
-		}
772
-
773
-		$scriptName = $this->server['SCRIPT_NAME'];
774
-		$pathInfo = $requestUri;
775
-
776
-		// strip off the script name's dir and file name
777
-		// FIXME: Sabre does not really belong here
778
-		list($path, $name) = \Sabre\Uri\split($scriptName);
779
-		if (!empty($path)) {
780
-			if ($path === $pathInfo || strpos($pathInfo, $path.'/') === 0) {
781
-				$pathInfo = substr($pathInfo, \strlen($path));
782
-			} else {
783
-				throw new \Exception("The requested uri($requestUri) cannot be processed by the script '$scriptName')");
784
-			}
785
-		}
786
-		if ($name === null) {
787
-			$name = '';
788
-		}
789
-
790
-		if (strpos($pathInfo, '/'.$name) === 0) {
791
-			$pathInfo = substr($pathInfo, \strlen($name) + 1);
792
-		}
793
-		if ($name !== '' && strpos($pathInfo, $name) === 0) {
794
-			$pathInfo = substr($pathInfo, \strlen($name));
795
-		}
796
-		if ($pathInfo === false || $pathInfo === '/') {
797
-			return '';
798
-		} else {
799
-			return $pathInfo;
800
-		}
801
-	}
802
-
803
-	/**
804
-	 * Get PathInfo from request
805
-	 * @throws \Exception
806
-	 * @return string|false Path info or false when not found
807
-	 */
808
-	public function getPathInfo() {
809
-		$pathInfo = $this->getRawPathInfo();
810
-		// following is taken from \Sabre\HTTP\URLUtil::decodePathSegment
811
-		$pathInfo = rawurldecode($pathInfo);
812
-		$encoding = mb_detect_encoding($pathInfo, ['UTF-8', 'ISO-8859-1']);
813
-
814
-		switch ($encoding) {
815
-			case 'ISO-8859-1':
816
-				$pathInfo = utf8_encode($pathInfo);
817
-		}
818
-		// end copy
819
-
820
-		return $pathInfo;
821
-	}
822
-
823
-	/**
824
-	 * Returns the script name, even if the website uses one or more
825
-	 * reverse proxies
826
-	 * @return string the script name
827
-	 */
828
-	public function getScriptName(): string {
829
-		$name = $this->server['SCRIPT_NAME'];
830
-		$overwriteWebRoot = $this->config->getSystemValue('overwritewebroot');
831
-		if ($overwriteWebRoot !== '' && $this->isOverwriteCondition()) {
832
-			// FIXME: This code is untestable due to __DIR__, also that hardcoded path is really dangerous
833
-			$serverRoot = str_replace('\\', '/', substr(__DIR__, 0, -\strlen('lib/private/appframework/http/')));
834
-			$suburi = str_replace('\\', '/', substr(realpath($this->server['SCRIPT_FILENAME']), \strlen($serverRoot)));
835
-			$name = '/' . ltrim($overwriteWebRoot . $suburi, '/');
836
-		}
837
-		return $name;
838
-	}
839
-
840
-	/**
841
-	 * Checks whether the user agent matches a given regex
842
-	 * @param array $agent array of agent names
843
-	 * @return bool true if at least one of the given agent matches, false otherwise
844
-	 */
845
-	public function isUserAgent(array $agent): bool {
846
-		if (!isset($this->server['HTTP_USER_AGENT'])) {
847
-			return false;
848
-		}
849
-		foreach ($agent as $regex) {
850
-			if (preg_match($regex, $this->server['HTTP_USER_AGENT'])) {
851
-				return true;
852
-			}
853
-		}
854
-		return false;
855
-	}
856
-
857
-	/**
858
-	 * Returns the unverified server host from the headers without checking
859
-	 * whether it is a trusted domain
860
-	 * @return string Server host
861
-	 */
862
-	public function getInsecureServerHost(): string {
863
-		if ($this->fromTrustedProxy() && $this->getOverwriteHost() !== null) {
864
-			return $this->getOverwriteHost();
865
-		}
866
-
867
-		$host = 'localhost';
868
-		if ($this->fromTrustedProxy() && isset($this->server['HTTP_X_FORWARDED_HOST'])) {
869
-			if (strpos($this->server['HTTP_X_FORWARDED_HOST'], ',') !== false) {
870
-				$parts = explode(',', $this->server['HTTP_X_FORWARDED_HOST']);
871
-				$host = trim(current($parts));
872
-			} else {
873
-				$host = $this->server['HTTP_X_FORWARDED_HOST'];
874
-			}
875
-		} else {
876
-			if (isset($this->server['HTTP_HOST'])) {
877
-				$host = $this->server['HTTP_HOST'];
878
-			} elseif (isset($this->server['SERVER_NAME'])) {
879
-				$host = $this->server['SERVER_NAME'];
880
-			}
881
-		}
882
-
883
-		return $host;
884
-	}
885
-
886
-
887
-	/**
888
-	 * Returns the server host from the headers, or the first configured
889
-	 * trusted domain if the host isn't in the trusted list
890
-	 * @return string Server host
891
-	 */
892
-	public function getServerHost(): string {
893
-		// overwritehost is always trusted
894
-		$host = $this->getOverwriteHost();
895
-		if ($host !== null) {
896
-			return $host;
897
-		}
898
-
899
-		// get the host from the headers
900
-		$host = $this->getInsecureServerHost();
901
-
902
-		// Verify that the host is a trusted domain if the trusted domains
903
-		// are defined
904
-		// If no trusted domain is provided the first trusted domain is returned
905
-		$trustedDomainHelper = new TrustedDomainHelper($this->config);
906
-		if ($trustedDomainHelper->isTrustedDomain($host)) {
907
-			return $host;
908
-		}
909
-
910
-		$trustedList = (array)$this->config->getSystemValue('trusted_domains', []);
911
-		if (count($trustedList) > 0) {
912
-			return reset($trustedList);
913
-		}
914
-
915
-		return '';
916
-	}
917
-
918
-	/**
919
-	 * Returns the overwritehost setting from the config if set and
920
-	 * if the overwrite condition is met
921
-	 * @return string|null overwritehost value or null if not defined or the defined condition
922
-	 * isn't met
923
-	 */
924
-	private function getOverwriteHost() {
925
-		if ($this->config->getSystemValue('overwritehost') !== '' && $this->isOverwriteCondition()) {
926
-			return $this->config->getSystemValue('overwritehost');
927
-		}
928
-		return null;
929
-	}
930
-
931
-	private function fromTrustedProxy(): bool {
932
-		$remoteAddress = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
933
-		$trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
934
-
935
-		return \is_array($trustedProxies) && $this->isTrustedProxy($trustedProxies, $remoteAddress);
936
-	}
66
+    public const USER_AGENT_IE = '/(MSIE)|(Trident)/';
67
+    // Microsoft Edge User Agent from https://msdn.microsoft.com/en-us/library/hh869301(v=vs.85).aspx
68
+    public 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.]+$/';
69
+    // Firefox User Agent from https://developer.mozilla.org/en-US/docs/Web/HTTP/Gecko_user_agent_string_reference
70
+    public const USER_AGENT_FIREFOX = '/^Mozilla\/5\.0 \([^)]+\) Gecko\/[0-9.]+ Firefox\/[0-9.]+$/';
71
+    // Chrome User Agent from https://developer.chrome.com/multidevice/user-agent
72
+    public 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.]+( (Vivaldi|Brave|OPR)\/[0-9.]+|)$/';
73
+    // Safari User Agent from http://www.useragentstring.com/pages/Safari/
74
+    public const USER_AGENT_SAFARI = '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\) Version\/[0-9.]+ Safari\/[0-9.A-Z]+$/';
75
+    // Android Chrome user agent: https://developers.google.com/chrome/mobile/docs/user-agent
76
+    public const USER_AGENT_ANDROID_MOBILE_CHROME = '#Android.*Chrome/[.0-9]*#';
77
+    public const USER_AGENT_FREEBOX = '#^Mozilla/5\.0$#';
78
+    public const REGEX_LOCALHOST = '/^(127\.0\.0\.1|localhost|\[::1\])$/';
79
+
80
+    /**
81
+     * @deprecated use \OCP\IRequest::USER_AGENT_CLIENT_IOS instead
82
+     */
83
+    public const USER_AGENT_OWNCLOUD_IOS = '/^Mozilla\/5\.0 \(iOS\) (ownCloud|Nextcloud)\-iOS.*$/';
84
+    /**
85
+     * @deprecated use \OCP\IRequest::USER_AGENT_CLIENT_ANDROID instead
86
+     */
87
+    public const USER_AGENT_OWNCLOUD_ANDROID = '/^Mozilla\/5\.0 \(Android\) ownCloud\-android.*$/';
88
+    /**
89
+     * @deprecated use \OCP\IRequest::USER_AGENT_CLIENT_DESKTOP instead
90
+     */
91
+    public const USER_AGENT_OWNCLOUD_DESKTOP = '/^Mozilla\/5\.0 \([A-Za-z ]+\) (mirall|csyncoC)\/.*$/';
92
+
93
+    protected $inputStream;
94
+    protected $content;
95
+    protected $items = [];
96
+    protected $allowedKeys = [
97
+        'get',
98
+        'post',
99
+        'files',
100
+        'server',
101
+        'env',
102
+        'cookies',
103
+        'urlParams',
104
+        'parameters',
105
+        'method',
106
+        'requesttoken',
107
+    ];
108
+    /** @var ISecureRandom */
109
+    protected $secureRandom;
110
+    /** @var IConfig */
111
+    protected $config;
112
+    /** @var string */
113
+    protected $requestId = '';
114
+    /** @var ICrypto */
115
+    protected $crypto;
116
+    /** @var CsrfTokenManager|null */
117
+    protected $csrfTokenManager;
118
+
119
+    /** @var bool */
120
+    protected $contentDecoded = false;
121
+
122
+    /**
123
+     * @param array $vars An associative array with the following optional values:
124
+     *        - array 'urlParams' the parameters which were matched from the URL
125
+     *        - array 'get' the $_GET array
126
+     *        - array|string 'post' the $_POST array or JSON string
127
+     *        - array 'files' the $_FILES array
128
+     *        - array 'server' the $_SERVER array
129
+     *        - array 'env' the $_ENV array
130
+     *        - array 'cookies' the $_COOKIE array
131
+     *        - string 'method' the request method (GET, POST etc)
132
+     *        - string|false 'requesttoken' the requesttoken or false when not available
133
+     * @param ISecureRandom $secureRandom
134
+     * @param IConfig $config
135
+     * @param CsrfTokenManager|null $csrfTokenManager
136
+     * @param string $stream
137
+     * @see http://www.php.net/manual/en/reserved.variables.php
138
+     */
139
+    public function __construct(array $vars,
140
+                                ISecureRandom $secureRandom,
141
+                                IConfig $config,
142
+                                CsrfTokenManager $csrfTokenManager = null,
143
+                                string $stream = 'php://input') {
144
+        $this->inputStream = $stream;
145
+        $this->items['params'] = [];
146
+        $this->secureRandom = $secureRandom;
147
+        $this->config = $config;
148
+        $this->csrfTokenManager = $csrfTokenManager;
149
+
150
+        if (!array_key_exists('method', $vars)) {
151
+            $vars['method'] = 'GET';
152
+        }
153
+
154
+        foreach ($this->allowedKeys as $name) {
155
+            $this->items[$name] = isset($vars[$name])
156
+                ? $vars[$name]
157
+                : [];
158
+        }
159
+
160
+        $this->items['parameters'] = array_merge(
161
+            $this->items['get'],
162
+            $this->items['post'],
163
+            $this->items['urlParams'],
164
+            $this->items['params']
165
+        );
166
+    }
167
+    /**
168
+     * @param array $parameters
169
+     */
170
+    public function setUrlParameters(array $parameters) {
171
+        $this->items['urlParams'] = $parameters;
172
+        $this->items['parameters'] = array_merge(
173
+            $this->items['parameters'],
174
+            $this->items['urlParams']
175
+        );
176
+    }
177
+
178
+    /**
179
+     * Countable method
180
+     * @return int
181
+     */
182
+    public function count(): int {
183
+        return \count($this->items['parameters']);
184
+    }
185
+
186
+    /**
187
+     * ArrayAccess methods
188
+     *
189
+     * Gives access to the combined GET, POST and urlParams arrays
190
+     *
191
+     * Examples:
192
+     *
193
+     * $var = $request['myvar'];
194
+     *
195
+     * or
196
+     *
197
+     * if(!isset($request['myvar']) {
198
+     * 	// Do something
199
+     * }
200
+     *
201
+     * $request['myvar'] = 'something'; // This throws an exception.
202
+     *
203
+     * @param string $offset The key to lookup
204
+     * @return boolean
205
+     */
206
+    public function offsetExists($offset): bool {
207
+        return isset($this->items['parameters'][$offset]);
208
+    }
209
+
210
+    /**
211
+     * @see offsetExists
212
+     * @param string $offset
213
+     * @return mixed
214
+     */
215
+    public function offsetGet($offset) {
216
+        return isset($this->items['parameters'][$offset])
217
+            ? $this->items['parameters'][$offset]
218
+            : null;
219
+    }
220
+
221
+    /**
222
+     * @see offsetExists
223
+     * @param string $offset
224
+     * @param mixed $value
225
+     */
226
+    public function offsetSet($offset, $value) {
227
+        throw new \RuntimeException('You cannot change the contents of the request object');
228
+    }
229
+
230
+    /**
231
+     * @see offsetExists
232
+     * @param string $offset
233
+     */
234
+    public function offsetUnset($offset) {
235
+        throw new \RuntimeException('You cannot change the contents of the request object');
236
+    }
237
+
238
+    /**
239
+     * Magic property accessors
240
+     * @param string $name
241
+     * @param mixed $value
242
+     */
243
+    public function __set($name, $value) {
244
+        throw new \RuntimeException('You cannot change the contents of the request object');
245
+    }
246
+
247
+    /**
248
+     * Access request variables by method and name.
249
+     * Examples:
250
+     *
251
+     * $request->post['myvar']; // Only look for POST variables
252
+     * $request->myvar; or $request->{'myvar'}; or $request->{$myvar}
253
+     * Looks in the combined GET, POST and urlParams array.
254
+     *
255
+     * If you access e.g. ->post but the current HTTP request method
256
+     * is GET a \LogicException will be thrown.
257
+     *
258
+     * @param string $name The key to look for.
259
+     * @throws \LogicException
260
+     * @return mixed|null
261
+     */
262
+    public function __get($name) {
263
+        switch ($name) {
264
+            case 'put':
265
+            case 'patch':
266
+            case 'get':
267
+            case 'post':
268
+                if ($this->method !== strtoupper($name)) {
269
+                    throw new \LogicException(sprintf('%s cannot be accessed in a %s request.', $name, $this->method));
270
+                }
271
+                return $this->getContent();
272
+            case 'files':
273
+            case 'server':
274
+            case 'env':
275
+            case 'cookies':
276
+            case 'urlParams':
277
+            case 'method':
278
+                return isset($this->items[$name])
279
+                    ? $this->items[$name]
280
+                    : null;
281
+            case 'parameters':
282
+            case 'params':
283
+                return $this->getContent();
284
+            default:
285
+                return isset($this[$name])
286
+                    ? $this[$name]
287
+                    : null;
288
+        }
289
+    }
290
+
291
+    /**
292
+     * @param string $name
293
+     * @return bool
294
+     */
295
+    public function __isset($name) {
296
+        if (\in_array($name, $this->allowedKeys, true)) {
297
+            return true;
298
+        }
299
+        return isset($this->items['parameters'][$name]);
300
+    }
301
+
302
+    /**
303
+     * @param string $id
304
+     */
305
+    public function __unset($id) {
306
+        throw new \RuntimeException('You cannot change the contents of the request object');
307
+    }
308
+
309
+    /**
310
+     * Returns the value for a specific http header.
311
+     *
312
+     * This method returns an empty string if the header did not exist.
313
+     *
314
+     * @param string $name
315
+     * @return string
316
+     */
317
+    public function getHeader(string $name): string {
318
+        $name = strtoupper(str_replace('-', '_',$name));
319
+        if (isset($this->server['HTTP_' . $name])) {
320
+            return $this->server['HTTP_' . $name];
321
+        }
322
+
323
+        // There's a few headers that seem to end up in the top-level
324
+        // server array.
325
+        switch ($name) {
326
+            case 'CONTENT_TYPE':
327
+            case 'CONTENT_LENGTH':
328
+            case 'REMOTE_ADDR':
329
+                if (isset($this->server[$name])) {
330
+                    return $this->server[$name];
331
+                }
332
+                break;
333
+        }
334
+
335
+        return '';
336
+    }
337
+
338
+    /**
339
+     * Lets you access post and get parameters by the index
340
+     * In case of json requests the encoded json body is accessed
341
+     *
342
+     * @param string $key the key which you want to access in the URL Parameter
343
+     *                     placeholder, $_POST or $_GET array.
344
+     *                     The priority how they're returned is the following:
345
+     *                     1. URL parameters
346
+     *                     2. POST parameters
347
+     *                     3. GET parameters
348
+     * @param mixed $default If the key is not found, this value will be returned
349
+     * @return mixed the content of the array
350
+     */
351
+    public function getParam(string $key, $default = null) {
352
+        return isset($this->parameters[$key])
353
+            ? $this->parameters[$key]
354
+            : $default;
355
+    }
356
+
357
+    /**
358
+     * Returns all params that were received, be it from the request
359
+     * (as GET or POST) or throuh the URL by the route
360
+     * @return array the array with all parameters
361
+     */
362
+    public function getParams(): array {
363
+        return is_array($this->parameters) ? $this->parameters : [];
364
+    }
365
+
366
+    /**
367
+     * Returns the method of the request
368
+     * @return string the method of the request (POST, GET, etc)
369
+     */
370
+    public function getMethod(): string {
371
+        return $this->method;
372
+    }
373
+
374
+    /**
375
+     * Shortcut for accessing an uploaded file through the $_FILES array
376
+     * @param string $key the key that will be taken from the $_FILES array
377
+     * @return array the file in the $_FILES element
378
+     */
379
+    public function getUploadedFile(string $key) {
380
+        return isset($this->files[$key]) ? $this->files[$key] : null;
381
+    }
382
+
383
+    /**
384
+     * Shortcut for getting env variables
385
+     * @param string $key the key that will be taken from the $_ENV array
386
+     * @return array the value in the $_ENV element
387
+     */
388
+    public function getEnv(string $key) {
389
+        return isset($this->env[$key]) ? $this->env[$key] : null;
390
+    }
391
+
392
+    /**
393
+     * Shortcut for getting cookie variables
394
+     * @param string $key the key that will be taken from the $_COOKIE array
395
+     * @return string the value in the $_COOKIE element
396
+     */
397
+    public function getCookie(string $key) {
398
+        return isset($this->cookies[$key]) ? $this->cookies[$key] : null;
399
+    }
400
+
401
+    /**
402
+     * Returns the request body content.
403
+     *
404
+     * If the HTTP request method is PUT and the body
405
+     * not application/x-www-form-urlencoded or application/json a stream
406
+     * resource is returned, otherwise an array.
407
+     *
408
+     * @return array|string|resource The request body content or a resource to read the body stream.
409
+     *
410
+     * @throws \LogicException
411
+     */
412
+    protected function getContent() {
413
+        // If the content can't be parsed into an array then return a stream resource.
414
+        if ($this->method === 'PUT'
415
+            && $this->getHeader('Content-Length') !== '0'
416
+            && $this->getHeader('Content-Length') !== ''
417
+            && strpos($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded') === false
418
+            && strpos($this->getHeader('Content-Type'), 'application/json') === false
419
+        ) {
420
+            if ($this->content === false) {
421
+                throw new \LogicException(
422
+                    '"put" can only be accessed once if not '
423
+                    . 'application/x-www-form-urlencoded or application/json.'
424
+                );
425
+            }
426
+            $this->content = false;
427
+            return fopen($this->inputStream, 'rb');
428
+        } else {
429
+            $this->decodeContent();
430
+            return $this->items['parameters'];
431
+        }
432
+    }
433
+
434
+    /**
435
+     * Attempt to decode the content and populate parameters
436
+     */
437
+    protected function decodeContent() {
438
+        if ($this->contentDecoded) {
439
+            return;
440
+        }
441
+        $params = [];
442
+
443
+        // 'application/json' must be decoded manually.
444
+        if (strpos($this->getHeader('Content-Type'), 'application/json') !== false) {
445
+            $params = json_decode(file_get_contents($this->inputStream), true);
446
+            if ($params !== null && \count($params) > 0) {
447
+                $this->items['params'] = $params;
448
+                if ($this->method === 'POST') {
449
+                    $this->items['post'] = $params;
450
+                }
451
+            }
452
+
453
+            // Handle application/x-www-form-urlencoded for methods other than GET
454
+        // or post correctly
455
+        } elseif ($this->method !== 'GET'
456
+                && $this->method !== 'POST'
457
+                && strpos($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded') !== false) {
458
+            parse_str(file_get_contents($this->inputStream), $params);
459
+            if (\is_array($params)) {
460
+                $this->items['params'] = $params;
461
+            }
462
+        }
463
+
464
+        if (\is_array($params)) {
465
+            $this->items['parameters'] = array_merge($this->items['parameters'], $params);
466
+        }
467
+        $this->contentDecoded = true;
468
+    }
469
+
470
+
471
+    /**
472
+     * Checks if the CSRF check was correct
473
+     * @return bool true if CSRF check passed
474
+     */
475
+    public function passesCSRFCheck(): bool {
476
+        if ($this->csrfTokenManager === null) {
477
+            return false;
478
+        }
479
+
480
+        if (!$this->passesStrictCookieCheck()) {
481
+            return false;
482
+        }
483
+
484
+        if (isset($this->items['get']['requesttoken'])) {
485
+            $token = $this->items['get']['requesttoken'];
486
+        } elseif (isset($this->items['post']['requesttoken'])) {
487
+            $token = $this->items['post']['requesttoken'];
488
+        } elseif (isset($this->items['server']['HTTP_REQUESTTOKEN'])) {
489
+            $token = $this->items['server']['HTTP_REQUESTTOKEN'];
490
+        } else {
491
+            //no token found.
492
+            return false;
493
+        }
494
+        $token = new CsrfToken($token);
495
+
496
+        return $this->csrfTokenManager->isTokenValid($token);
497
+    }
498
+
499
+    /**
500
+     * Whether the cookie checks are required
501
+     *
502
+     * @return bool
503
+     */
504
+    private function cookieCheckRequired(): bool {
505
+        if ($this->getHeader('OCS-APIREQUEST')) {
506
+            return false;
507
+        }
508
+        if ($this->getCookie(session_name()) === null && $this->getCookie('nc_token') === null) {
509
+            return false;
510
+        }
511
+
512
+        return true;
513
+    }
514
+
515
+    /**
516
+     * Wrapper around session_get_cookie_params
517
+     *
518
+     * @return array
519
+     */
520
+    public function getCookieParams(): array {
521
+        return session_get_cookie_params();
522
+    }
523
+
524
+    /**
525
+     * Appends the __Host- prefix to the cookie if applicable
526
+     *
527
+     * @param string $name
528
+     * @return string
529
+     */
530
+    protected function getProtectedCookieName(string $name): string {
531
+        $cookieParams = $this->getCookieParams();
532
+        $prefix = '';
533
+        if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
534
+            $prefix = '__Host-';
535
+        }
536
+
537
+        return $prefix.$name;
538
+    }
539
+
540
+    /**
541
+     * Checks if the strict cookie has been sent with the request if the request
542
+     * is including any cookies.
543
+     *
544
+     * @return bool
545
+     * @since 9.1.0
546
+     */
547
+    public function passesStrictCookieCheck(): bool {
548
+        if (!$this->cookieCheckRequired()) {
549
+            return true;
550
+        }
551
+
552
+        $cookieName = $this->getProtectedCookieName('nc_sameSiteCookiestrict');
553
+        if ($this->getCookie($cookieName) === 'true'
554
+            && $this->passesLaxCookieCheck()) {
555
+            return true;
556
+        }
557
+        return false;
558
+    }
559
+
560
+    /**
561
+     * Checks if the lax cookie has been sent with the request if the request
562
+     * is including any cookies.
563
+     *
564
+     * @return bool
565
+     * @since 9.1.0
566
+     */
567
+    public function passesLaxCookieCheck(): bool {
568
+        if (!$this->cookieCheckRequired()) {
569
+            return true;
570
+        }
571
+
572
+        $cookieName = $this->getProtectedCookieName('nc_sameSiteCookielax');
573
+        if ($this->getCookie($cookieName) === 'true') {
574
+            return true;
575
+        }
576
+        return false;
577
+    }
578
+
579
+
580
+    /**
581
+     * Returns an ID for the request, value is not guaranteed to be unique and is mostly meant for logging
582
+     * If `mod_unique_id` is installed this value will be taken.
583
+     * @return string
584
+     */
585
+    public function getId(): string {
586
+        if (isset($this->server['UNIQUE_ID'])) {
587
+            return $this->server['UNIQUE_ID'];
588
+        }
589
+
590
+        if (empty($this->requestId)) {
591
+            $validChars = ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS;
592
+            $this->requestId = $this->secureRandom->generate(20, $validChars);
593
+        }
594
+
595
+        return $this->requestId;
596
+    }
597
+
598
+    /**
599
+     * Checks if given $remoteAddress matches given $trustedProxy.
600
+     * If $trustedProxy is an IPv4 IP range given in CIDR notation, true will be returned if
601
+     * $remoteAddress is an IPv4 address within that IP range.
602
+     * Otherwise $remoteAddress will be compared to $trustedProxy literally and the result
603
+     * will be returned.
604
+     * @return boolean true if $remoteAddress matches $trustedProxy, false otherwise
605
+     */
606
+    protected function matchesTrustedProxy($trustedProxy, $remoteAddress) {
607
+        $cidrre = '/^([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})\/([0-9]{1,2})$/';
608
+
609
+        if (preg_match($cidrre, $trustedProxy, $match)) {
610
+            $net = $match[1];
611
+            $shiftbits = min(32, max(0, 32 - intval($match[2])));
612
+            $netnum = ip2long($net) >> $shiftbits;
613
+            $ipnum = ip2long($remoteAddress) >> $shiftbits;
614
+
615
+            return $ipnum === $netnum;
616
+        }
617
+
618
+        return $trustedProxy === $remoteAddress;
619
+    }
620
+
621
+    /**
622
+     * Checks if given $remoteAddress matches any entry in the given array $trustedProxies.
623
+     * For details regarding what "match" means, refer to `matchesTrustedProxy`.
624
+     * @return boolean true if $remoteAddress matches any entry in $trustedProxies, false otherwise
625
+     */
626
+    protected function isTrustedProxy($trustedProxies, $remoteAddress) {
627
+        foreach ($trustedProxies as $tp) {
628
+            if ($this->matchesTrustedProxy($tp, $remoteAddress)) {
629
+                return true;
630
+            }
631
+        }
632
+
633
+        return false;
634
+    }
635
+
636
+    /**
637
+     * Returns the remote address, if the connection came from a trusted proxy
638
+     * and `forwarded_for_headers` has been configured then the IP address
639
+     * specified in this header will be returned instead.
640
+     * Do always use this instead of $_SERVER['REMOTE_ADDR']
641
+     * @return string IP address
642
+     */
643
+    public function getRemoteAddress(): string {
644
+        $remoteAddress = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
645
+        $trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
646
+
647
+        if (\is_array($trustedProxies) && $this->isTrustedProxy($trustedProxies, $remoteAddress)) {
648
+            $forwardedForHeaders = $this->config->getSystemValue('forwarded_for_headers', [
649
+                'HTTP_X_FORWARDED_FOR'
650
+                // only have one default, so we cannot ship an insecure product out of the box
651
+            ]);
652
+
653
+            foreach ($forwardedForHeaders as $header) {
654
+                if (isset($this->server[$header])) {
655
+                    foreach (explode(',', $this->server[$header]) as $IP) {
656
+                        $IP = trim($IP);
657
+
658
+                        // remove brackets from IPv6 addresses
659
+                        if (strpos($IP, '[') === 0 && substr($IP, -1) === ']') {
660
+                            $IP = substr($IP, 1, -1);
661
+                        }
662
+
663
+                        if (filter_var($IP, FILTER_VALIDATE_IP) !== false) {
664
+                            return $IP;
665
+                        }
666
+                    }
667
+                }
668
+            }
669
+        }
670
+
671
+        return $remoteAddress;
672
+    }
673
+
674
+    /**
675
+     * Check overwrite condition
676
+     * @param string $type
677
+     * @return bool
678
+     */
679
+    private function isOverwriteCondition(string $type = ''): bool {
680
+        $regex = '/' . $this->config->getSystemValue('overwritecondaddr', '')  . '/';
681
+        $remoteAddr = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
682
+        return $regex === '//' || preg_match($regex, $remoteAddr) === 1
683
+        || $type !== 'protocol';
684
+    }
685
+
686
+    /**
687
+     * Returns the server protocol. It respects one or more reverse proxies servers
688
+     * and load balancers
689
+     * @return string Server protocol (http or https)
690
+     */
691
+    public function getServerProtocol(): string {
692
+        if ($this->config->getSystemValue('overwriteprotocol') !== ''
693
+            && $this->isOverwriteCondition('protocol')) {
694
+            return $this->config->getSystemValue('overwriteprotocol');
695
+        }
696
+
697
+        if ($this->fromTrustedProxy() && isset($this->server['HTTP_X_FORWARDED_PROTO'])) {
698
+            if (strpos($this->server['HTTP_X_FORWARDED_PROTO'], ',') !== false) {
699
+                $parts = explode(',', $this->server['HTTP_X_FORWARDED_PROTO']);
700
+                $proto = strtolower(trim($parts[0]));
701
+            } else {
702
+                $proto = strtolower($this->server['HTTP_X_FORWARDED_PROTO']);
703
+            }
704
+
705
+            // Verify that the protocol is always HTTP or HTTPS
706
+            // default to http if an invalid value is provided
707
+            return $proto === 'https' ? 'https' : 'http';
708
+        }
709
+
710
+        if (isset($this->server['HTTPS'])
711
+            && $this->server['HTTPS'] !== null
712
+            && $this->server['HTTPS'] !== 'off'
713
+            && $this->server['HTTPS'] !== '') {
714
+            return 'https';
715
+        }
716
+
717
+        return 'http';
718
+    }
719
+
720
+    /**
721
+     * Returns the used HTTP protocol.
722
+     *
723
+     * @return string HTTP protocol. HTTP/2, HTTP/1.1 or HTTP/1.0.
724
+     */
725
+    public function getHttpProtocol(): string {
726
+        $claimedProtocol = $this->server['SERVER_PROTOCOL'];
727
+
728
+        if (\is_string($claimedProtocol)) {
729
+            $claimedProtocol = strtoupper($claimedProtocol);
730
+        }
731
+
732
+        $validProtocols = [
733
+            'HTTP/1.0',
734
+            'HTTP/1.1',
735
+            'HTTP/2',
736
+        ];
737
+
738
+        if (\in_array($claimedProtocol, $validProtocols, true)) {
739
+            return $claimedProtocol;
740
+        }
741
+
742
+        return 'HTTP/1.1';
743
+    }
744
+
745
+    /**
746
+     * Returns the request uri, even if the website uses one or more
747
+     * reverse proxies
748
+     * @return string
749
+     */
750
+    public function getRequestUri(): string {
751
+        $uri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : '';
752
+        if ($this->config->getSystemValue('overwritewebroot') !== '' && $this->isOverwriteCondition()) {
753
+            $uri = $this->getScriptName() . substr($uri, \strlen($this->server['SCRIPT_NAME']));
754
+        }
755
+        return $uri;
756
+    }
757
+
758
+    /**
759
+     * Get raw PathInfo from request (not urldecoded)
760
+     * @throws \Exception
761
+     * @return string Path info
762
+     */
763
+    public function getRawPathInfo(): string {
764
+        $requestUri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : '';
765
+        // remove too many slashes - can be caused by reverse proxy configuration
766
+        $requestUri = preg_replace('%/{2,}%', '/', $requestUri);
767
+
768
+        // Remove the query string from REQUEST_URI
769
+        if ($pos = strpos($requestUri, '?')) {
770
+            $requestUri = substr($requestUri, 0, $pos);
771
+        }
772
+
773
+        $scriptName = $this->server['SCRIPT_NAME'];
774
+        $pathInfo = $requestUri;
775
+
776
+        // strip off the script name's dir and file name
777
+        // FIXME: Sabre does not really belong here
778
+        list($path, $name) = \Sabre\Uri\split($scriptName);
779
+        if (!empty($path)) {
780
+            if ($path === $pathInfo || strpos($pathInfo, $path.'/') === 0) {
781
+                $pathInfo = substr($pathInfo, \strlen($path));
782
+            } else {
783
+                throw new \Exception("The requested uri($requestUri) cannot be processed by the script '$scriptName')");
784
+            }
785
+        }
786
+        if ($name === null) {
787
+            $name = '';
788
+        }
789
+
790
+        if (strpos($pathInfo, '/'.$name) === 0) {
791
+            $pathInfo = substr($pathInfo, \strlen($name) + 1);
792
+        }
793
+        if ($name !== '' && strpos($pathInfo, $name) === 0) {
794
+            $pathInfo = substr($pathInfo, \strlen($name));
795
+        }
796
+        if ($pathInfo === false || $pathInfo === '/') {
797
+            return '';
798
+        } else {
799
+            return $pathInfo;
800
+        }
801
+    }
802
+
803
+    /**
804
+     * Get PathInfo from request
805
+     * @throws \Exception
806
+     * @return string|false Path info or false when not found
807
+     */
808
+    public function getPathInfo() {
809
+        $pathInfo = $this->getRawPathInfo();
810
+        // following is taken from \Sabre\HTTP\URLUtil::decodePathSegment
811
+        $pathInfo = rawurldecode($pathInfo);
812
+        $encoding = mb_detect_encoding($pathInfo, ['UTF-8', 'ISO-8859-1']);
813
+
814
+        switch ($encoding) {
815
+            case 'ISO-8859-1':
816
+                $pathInfo = utf8_encode($pathInfo);
817
+        }
818
+        // end copy
819
+
820
+        return $pathInfo;
821
+    }
822
+
823
+    /**
824
+     * Returns the script name, even if the website uses one or more
825
+     * reverse proxies
826
+     * @return string the script name
827
+     */
828
+    public function getScriptName(): string {
829
+        $name = $this->server['SCRIPT_NAME'];
830
+        $overwriteWebRoot = $this->config->getSystemValue('overwritewebroot');
831
+        if ($overwriteWebRoot !== '' && $this->isOverwriteCondition()) {
832
+            // FIXME: This code is untestable due to __DIR__, also that hardcoded path is really dangerous
833
+            $serverRoot = str_replace('\\', '/', substr(__DIR__, 0, -\strlen('lib/private/appframework/http/')));
834
+            $suburi = str_replace('\\', '/', substr(realpath($this->server['SCRIPT_FILENAME']), \strlen($serverRoot)));
835
+            $name = '/' . ltrim($overwriteWebRoot . $suburi, '/');
836
+        }
837
+        return $name;
838
+    }
839
+
840
+    /**
841
+     * Checks whether the user agent matches a given regex
842
+     * @param array $agent array of agent names
843
+     * @return bool true if at least one of the given agent matches, false otherwise
844
+     */
845
+    public function isUserAgent(array $agent): bool {
846
+        if (!isset($this->server['HTTP_USER_AGENT'])) {
847
+            return false;
848
+        }
849
+        foreach ($agent as $regex) {
850
+            if (preg_match($regex, $this->server['HTTP_USER_AGENT'])) {
851
+                return true;
852
+            }
853
+        }
854
+        return false;
855
+    }
856
+
857
+    /**
858
+     * Returns the unverified server host from the headers without checking
859
+     * whether it is a trusted domain
860
+     * @return string Server host
861
+     */
862
+    public function getInsecureServerHost(): string {
863
+        if ($this->fromTrustedProxy() && $this->getOverwriteHost() !== null) {
864
+            return $this->getOverwriteHost();
865
+        }
866
+
867
+        $host = 'localhost';
868
+        if ($this->fromTrustedProxy() && isset($this->server['HTTP_X_FORWARDED_HOST'])) {
869
+            if (strpos($this->server['HTTP_X_FORWARDED_HOST'], ',') !== false) {
870
+                $parts = explode(',', $this->server['HTTP_X_FORWARDED_HOST']);
871
+                $host = trim(current($parts));
872
+            } else {
873
+                $host = $this->server['HTTP_X_FORWARDED_HOST'];
874
+            }
875
+        } else {
876
+            if (isset($this->server['HTTP_HOST'])) {
877
+                $host = $this->server['HTTP_HOST'];
878
+            } elseif (isset($this->server['SERVER_NAME'])) {
879
+                $host = $this->server['SERVER_NAME'];
880
+            }
881
+        }
882
+
883
+        return $host;
884
+    }
885
+
886
+
887
+    /**
888
+     * Returns the server host from the headers, or the first configured
889
+     * trusted domain if the host isn't in the trusted list
890
+     * @return string Server host
891
+     */
892
+    public function getServerHost(): string {
893
+        // overwritehost is always trusted
894
+        $host = $this->getOverwriteHost();
895
+        if ($host !== null) {
896
+            return $host;
897
+        }
898
+
899
+        // get the host from the headers
900
+        $host = $this->getInsecureServerHost();
901
+
902
+        // Verify that the host is a trusted domain if the trusted domains
903
+        // are defined
904
+        // If no trusted domain is provided the first trusted domain is returned
905
+        $trustedDomainHelper = new TrustedDomainHelper($this->config);
906
+        if ($trustedDomainHelper->isTrustedDomain($host)) {
907
+            return $host;
908
+        }
909
+
910
+        $trustedList = (array)$this->config->getSystemValue('trusted_domains', []);
911
+        if (count($trustedList) > 0) {
912
+            return reset($trustedList);
913
+        }
914
+
915
+        return '';
916
+    }
917
+
918
+    /**
919
+     * Returns the overwritehost setting from the config if set and
920
+     * if the overwrite condition is met
921
+     * @return string|null overwritehost value or null if not defined or the defined condition
922
+     * isn't met
923
+     */
924
+    private function getOverwriteHost() {
925
+        if ($this->config->getSystemValue('overwritehost') !== '' && $this->isOverwriteCondition()) {
926
+            return $this->config->getSystemValue('overwritehost');
927
+        }
928
+        return null;
929
+    }
930
+
931
+    private function fromTrustedProxy(): bool {
932
+        $remoteAddress = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
933
+        $trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
934
+
935
+        return \is_array($trustedProxies) && $this->isTrustedProxy($trustedProxies, $remoteAddress);
936
+    }
937 937
 }
Please login to merge, or discard this patch.