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