Passed
Push — master ( 2d5047...0999f0 )
by Morris
15:20 queued 03:08
created
lib/private/AppFramework/Http/Request.php 2 patches
Indentation   +826 added lines, -826 removed lines patch added patch discarded remove patch
@@ -59,831 +59,831 @@
 block discarded – undo
59 59
  */
60 60
 class Request implements \ArrayAccess, \Countable, IRequest {
61 61
 
62
-	const USER_AGENT_IE = '/(MSIE)|(Trident)/';
63
-	// Microsoft Edge User Agent from https://msdn.microsoft.com/en-us/library/hh869301(v=vs.85).aspx
64
-	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.]+$/';
65
-	// Firefox User Agent from https://developer.mozilla.org/en-US/docs/Web/HTTP/Gecko_user_agent_string_reference
66
-	const USER_AGENT_FIREFOX = '/^Mozilla\/5\.0 \([^)]+\) Gecko\/[0-9.]+ Firefox\/[0-9.]+$/';
67
-	// Chrome User Agent from https://developer.chrome.com/multidevice/user-agent
68
-	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.]+$/';
69
-	// Safari User Agent from http://www.useragentstring.com/pages/Safari/
70
-	const USER_AGENT_SAFARI = '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\) Version\/[0-9.]+ Safari\/[0-9.A-Z]+$/';
71
-	// Android Chrome user agent: https://developers.google.com/chrome/mobile/docs/user-agent
72
-	const USER_AGENT_ANDROID_MOBILE_CHROME = '#Android.*Chrome/[.0-9]*#';
73
-	const USER_AGENT_FREEBOX = '#^Mozilla/5\.0$#';
74
-	const REGEX_LOCALHOST = '/^(127\.0\.0\.1|localhost|::1)$/';
75
-
76
-	/**
77
-	 * @deprecated use \OCP\IRequest::USER_AGENT_CLIENT_IOS instead
78
-	 */
79
-	const USER_AGENT_OWNCLOUD_IOS = '/^Mozilla\/5\.0 \(iOS\) (ownCloud|Nextcloud)\-iOS.*$/';
80
-	/**
81
-	 * @deprecated use \OCP\IRequest::USER_AGENT_CLIENT_ANDROID instead
82
-	 */
83
-	const USER_AGENT_OWNCLOUD_ANDROID = '/^Mozilla\/5\.0 \(Android\) ownCloud\-android.*$/';
84
-	/**
85
-	 * @deprecated use \OCP\IRequest::USER_AGENT_CLIENT_DESKTOP instead
86
-	 */
87
-	const USER_AGENT_OWNCLOUD_DESKTOP = '/^Mozilla\/5\.0 \([A-Za-z ]+\) (mirall|csyncoC)\/.*$/';
88
-
89
-	protected $inputStream;
90
-	protected $content;
91
-	protected $items = [];
92
-	protected $allowedKeys = [
93
-		'get',
94
-		'post',
95
-		'files',
96
-		'server',
97
-		'env',
98
-		'cookies',
99
-		'urlParams',
100
-		'parameters',
101
-		'method',
102
-		'requesttoken',
103
-	];
104
-	/** @var ISecureRandom */
105
-	protected $secureRandom;
106
-	/** @var IConfig */
107
-	protected $config;
108
-	/** @var string */
109
-	protected $requestId = '';
110
-	/** @var ICrypto */
111
-	protected $crypto;
112
-	/** @var CsrfTokenManager|null */
113
-	protected $csrfTokenManager;
114
-
115
-	/** @var bool */
116
-	protected $contentDecoded = false;
117
-
118
-	/**
119
-	 * @param array $vars An associative array with the following optional values:
120
-	 *        - array 'urlParams' the parameters which were matched from the URL
121
-	 *        - array 'get' the $_GET array
122
-	 *        - array|string 'post' the $_POST array or JSON string
123
-	 *        - array 'files' the $_FILES array
124
-	 *        - array 'server' the $_SERVER array
125
-	 *        - array 'env' the $_ENV array
126
-	 *        - array 'cookies' the $_COOKIE array
127
-	 *        - string 'method' the request method (GET, POST etc)
128
-	 *        - string|false 'requesttoken' the requesttoken or false when not available
129
-	 * @param ISecureRandom $secureRandom
130
-	 * @param IConfig $config
131
-	 * @param CsrfTokenManager|null $csrfTokenManager
132
-	 * @param string $stream
133
-	 * @see http://www.php.net/manual/en/reserved.variables.php
134
-	 */
135
-	public function __construct(array $vars= [],
136
-								ISecureRandom $secureRandom = null,
137
-								IConfig $config,
138
-								CsrfTokenManager $csrfTokenManager = null,
139
-								string $stream = 'php://input') {
140
-		$this->inputStream = $stream;
141
-		$this->items['params'] = [];
142
-		$this->secureRandom = $secureRandom;
143
-		$this->config = $config;
144
-		$this->csrfTokenManager = $csrfTokenManager;
145
-
146
-		if(!array_key_exists('method', $vars)) {
147
-			$vars['method'] = 'GET';
148
-		}
149
-
150
-		foreach($this->allowedKeys as $name) {
151
-			$this->items[$name] = isset($vars[$name])
152
-				? $vars[$name]
153
-				: [];
154
-		}
155
-
156
-		$this->items['parameters'] = array_merge(
157
-			$this->items['get'],
158
-			$this->items['post'],
159
-			$this->items['urlParams'],
160
-			$this->items['params']
161
-		);
162
-
163
-	}
164
-	/**
165
-	 * @param array $parameters
166
-	 */
167
-	public function setUrlParameters(array $parameters) {
168
-		$this->items['urlParams'] = $parameters;
169
-		$this->items['parameters'] = array_merge(
170
-			$this->items['parameters'],
171
-			$this->items['urlParams']
172
-		);
173
-	}
174
-
175
-	/**
176
-	 * Countable method
177
-	 * @return int
178
-	 */
179
-	public function count(): int {
180
-		return \count($this->items['parameters']);
181
-	}
182
-
183
-	/**
184
-	* ArrayAccess methods
185
-	*
186
-	* Gives access to the combined GET, POST and urlParams arrays
187
-	*
188
-	* Examples:
189
-	*
190
-	* $var = $request['myvar'];
191
-	*
192
-	* or
193
-	*
194
-	* if(!isset($request['myvar']) {
195
-	* 	// Do something
196
-	* }
197
-	*
198
-	* $request['myvar'] = 'something'; // This throws an exception.
199
-	*
200
-	* @param string $offset The key to lookup
201
-	* @return boolean
202
-	*/
203
-	public function offsetExists($offset): bool {
204
-		return isset($this->items['parameters'][$offset]);
205
-	}
206
-
207
-	/**
208
-	 * @see offsetExists
209
-	 * @param string $offset
210
-	 * @return mixed
211
-	 */
212
-	public function offsetGet($offset) {
213
-		return isset($this->items['parameters'][$offset])
214
-			? $this->items['parameters'][$offset]
215
-			: null;
216
-	}
217
-
218
-	/**
219
-	 * @see offsetExists
220
-	 * @param string $offset
221
-	 * @param mixed $value
222
-	 */
223
-	public function offsetSet($offset, $value) {
224
-		throw new \RuntimeException('You cannot change the contents of the request object');
225
-	}
226
-
227
-	/**
228
-	 * @see offsetExists
229
-	 * @param string $offset
230
-	 */
231
-	public function offsetUnset($offset) {
232
-		throw new \RuntimeException('You cannot change the contents of the request object');
233
-	}
234
-
235
-	/**
236
-	 * Magic property accessors
237
-	 * @param string $name
238
-	 * @param mixed $value
239
-	 */
240
-	public function __set($name, $value) {
241
-		throw new \RuntimeException('You cannot change the contents of the request object');
242
-	}
243
-
244
-	/**
245
-	* Access request variables by method and name.
246
-	* Examples:
247
-	*
248
-	* $request->post['myvar']; // Only look for POST variables
249
-	* $request->myvar; or $request->{'myvar'}; or $request->{$myvar}
250
-	* Looks in the combined GET, POST and urlParams array.
251
-	*
252
-	* If you access e.g. ->post but the current HTTP request method
253
-	* is GET a \LogicException will be thrown.
254
-	*
255
-	* @param string $name The key to look for.
256
-	* @throws \LogicException
257
-	* @return mixed|null
258
-	*/
259
-	public function __get($name) {
260
-		switch($name) {
261
-			case 'put':
262
-			case 'patch':
263
-			case 'get':
264
-			case 'post':
265
-				if($this->method !== strtoupper($name)) {
266
-					throw new \LogicException(sprintf('%s cannot be accessed in a %s request.', $name, $this->method));
267
-				}
268
-				return $this->getContent();
269
-			case 'files':
270
-			case 'server':
271
-			case 'env':
272
-			case 'cookies':
273
-			case 'urlParams':
274
-			case 'method':
275
-				return isset($this->items[$name])
276
-					? $this->items[$name]
277
-					: null;
278
-			case 'parameters':
279
-			case 'params':
280
-				return $this->getContent();
281
-			default;
282
-				return isset($this[$name])
283
-					? $this[$name]
284
-					: null;
285
-		}
286
-	}
287
-
288
-	/**
289
-	 * @param string $name
290
-	 * @return bool
291
-	 */
292
-	public function __isset($name) {
293
-		if (\in_array($name, $this->allowedKeys, true)) {
294
-			return true;
295
-		}
296
-		return isset($this->items['parameters'][$name]);
297
-	}
298
-
299
-	/**
300
-	 * @param string $id
301
-	 */
302
-	public function __unset($id) {
303
-		throw new \RuntimeException('You cannot change the contents of the request object');
304
-	}
305
-
306
-	/**
307
-	 * Returns the value for a specific http header.
308
-	 *
309
-	 * This method returns null if the header did not exist.
310
-	 *
311
-	 * @param string $name
312
-	 * @return string
313
-	 */
314
-	public function getHeader(string $name): string {
315
-
316
-		$name = strtoupper(str_replace('-', '_',$name));
317
-		if (isset($this->server['HTTP_' . $name])) {
318
-			return $this->server['HTTP_' . $name];
319
-		}
320
-
321
-		// There's a few headers that seem to end up in the top-level
322
-		// server array.
323
-		switch ($name) {
324
-			case 'CONTENT_TYPE' :
325
-			case 'CONTENT_LENGTH' :
326
-				if (isset($this->server[$name])) {
327
-					return $this->server[$name];
328
-				}
329
-				break;
330
-			case 'REMOTE_ADDR' :
331
-				if (isset($this->server[$name])) {
332
-					return $this->server[$name];
333
-				}
334
-				break;
335
-		}
336
-
337
-		return '';
338
-	}
339
-
340
-	/**
341
-	 * Lets you access post and get parameters by the index
342
-	 * In case of json requests the encoded json body is accessed
343
-	 *
344
-	 * @param string $key the key which you want to access in the URL Parameter
345
-	 *                     placeholder, $_POST or $_GET array.
346
-	 *                     The priority how they're returned is the following:
347
-	 *                     1. URL parameters
348
-	 *                     2. POST parameters
349
-	 *                     3. GET parameters
350
-	 * @param mixed $default If the key is not found, this value will be returned
351
-	 * @return mixed the content of the array
352
-	 */
353
-	public function getParam(string $key, $default = null) {
354
-		return isset($this->parameters[$key])
355
-			? $this->parameters[$key]
356
-			: $default;
357
-	}
358
-
359
-	/**
360
-	 * Returns all params that were received, be it from the request
361
-	 * (as GET or POST) or throuh the URL by the route
362
-	 * @return array the array with all parameters
363
-	 */
364
-	public function getParams(): array {
365
-		return is_array($this->parameters) ? $this->parameters : [];
366
-	}
367
-
368
-	/**
369
-	 * Returns the method of the request
370
-	 * @return string the method of the request (POST, GET, etc)
371
-	 */
372
-	public function getMethod(): string {
373
-		return $this->method;
374
-	}
375
-
376
-	/**
377
-	 * Shortcut for accessing an uploaded file through the $_FILES array
378
-	 * @param string $key the key that will be taken from the $_FILES array
379
-	 * @return array the file in the $_FILES element
380
-	 */
381
-	public function getUploadedFile(string $key) {
382
-		return isset($this->files[$key]) ? $this->files[$key] : null;
383
-	}
384
-
385
-	/**
386
-	 * Shortcut for getting env variables
387
-	 * @param string $key the key that will be taken from the $_ENV array
388
-	 * @return array the value in the $_ENV element
389
-	 */
390
-	public function getEnv(string $key) {
391
-		return isset($this->env[$key]) ? $this->env[$key] : null;
392
-	}
393
-
394
-	/**
395
-	 * Shortcut for getting cookie variables
396
-	 * @param string $key the key that will be taken from the $_COOKIE array
397
-	 * @return string the value in the $_COOKIE element
398
-	 */
399
-	public function getCookie(string $key) {
400
-		return isset($this->cookies[$key]) ? $this->cookies[$key] : null;
401
-	}
402
-
403
-	/**
404
-	 * Returns the request body content.
405
-	 *
406
-	 * If the HTTP request method is PUT and the body
407
-	 * not application/x-www-form-urlencoded or application/json a stream
408
-	 * resource is returned, otherwise an array.
409
-	 *
410
-	 * @return array|string|resource The request body content or a resource to read the body stream.
411
-	 *
412
-	 * @throws \LogicException
413
-	 */
414
-	protected function getContent() {
415
-		// If the content can't be parsed into an array then return a stream resource.
416
-		if ($this->method === 'PUT'
417
-			&& $this->getHeader('Content-Length') !== '0'
418
-			&& $this->getHeader('Content-Length') !== ''
419
-			&& strpos($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded') === false
420
-			&& strpos($this->getHeader('Content-Type'), 'application/json') === false
421
-		) {
422
-			if ($this->content === false) {
423
-				throw new \LogicException(
424
-					'"put" can only be accessed once if not '
425
-					. 'application/x-www-form-urlencoded or application/json.'
426
-				);
427
-			}
428
-			$this->content = false;
429
-			return fopen($this->inputStream, 'rb');
430
-		} else {
431
-			$this->decodeContent();
432
-			return $this->items['parameters'];
433
-		}
434
-	}
435
-
436
-	/**
437
-	 * Attempt to decode the content and populate parameters
438
-	 */
439
-	protected function decodeContent() {
440
-		if ($this->contentDecoded) {
441
-			return;
442
-		}
443
-		$params = [];
444
-
445
-		// 'application/json' must be decoded manually.
446
-		if (strpos($this->getHeader('Content-Type'), 'application/json') !== false) {
447
-			$params = json_decode(file_get_contents($this->inputStream), true);
448
-			if($params !== null && \count($params) > 0) {
449
-				$this->items['params'] = $params;
450
-				if($this->method === 'POST') {
451
-					$this->items['post'] = $params;
452
-				}
453
-			}
454
-
455
-		// Handle application/x-www-form-urlencoded for methods other than GET
456
-		// or post correctly
457
-		} elseif($this->method !== 'GET'
458
-				&& $this->method !== 'POST'
459
-				&& strpos($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded') !== false) {
460
-
461
-			parse_str(file_get_contents($this->inputStream), $params);
462
-			if(\is_array($params)) {
463
-				$this->items['params'] = $params;
464
-			}
465
-		}
466
-
467
-		if (\is_array($params)) {
468
-			$this->items['parameters'] = array_merge($this->items['parameters'], $params);
469
-		}
470
-		$this->contentDecoded = true;
471
-	}
472
-
473
-
474
-	/**
475
-	 * Checks if the CSRF check was correct
476
-	 * @return bool true if CSRF check passed
477
-	 */
478
-	public function passesCSRFCheck(): bool {
479
-		if($this->csrfTokenManager === null) {
480
-			return false;
481
-		}
482
-
483
-		if(!$this->passesStrictCookieCheck()) {
484
-			return false;
485
-		}
486
-
487
-		if (isset($this->items['get']['requesttoken'])) {
488
-			$token = $this->items['get']['requesttoken'];
489
-		} elseif (isset($this->items['post']['requesttoken'])) {
490
-			$token = $this->items['post']['requesttoken'];
491
-		} elseif (isset($this->items['server']['HTTP_REQUESTTOKEN'])) {
492
-			$token = $this->items['server']['HTTP_REQUESTTOKEN'];
493
-		} else {
494
-			//no token found.
495
-			return false;
496
-		}
497
-		$token = new CsrfToken($token);
498
-
499
-		return $this->csrfTokenManager->isTokenValid($token);
500
-	}
501
-
502
-	/**
503
-	 * Whether the cookie checks are required
504
-	 *
505
-	 * @return bool
506
-	 */
507
-	private function cookieCheckRequired(): bool {
508
-		if ($this->getHeader('OCS-APIREQUEST')) {
509
-			return false;
510
-		}
511
-		if($this->getCookie(session_name()) === null && $this->getCookie('nc_token') === null) {
512
-			return false;
513
-		}
514
-
515
-		return true;
516
-	}
517
-
518
-	/**
519
-	 * Wrapper around session_get_cookie_params
520
-	 *
521
-	 * @return array
522
-	 */
523
-	public function getCookieParams(): array {
524
-		return session_get_cookie_params();
525
-	}
526
-
527
-	/**
528
-	 * Appends the __Host- prefix to the cookie if applicable
529
-	 *
530
-	 * @param string $name
531
-	 * @return string
532
-	 */
533
-	protected function getProtectedCookieName(string $name): string {
534
-		$cookieParams = $this->getCookieParams();
535
-		$prefix = '';
536
-		if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
537
-			$prefix = '__Host-';
538
-		}
539
-
540
-		return $prefix.$name;
541
-	}
542
-
543
-	/**
544
-	 * Checks if the strict cookie has been sent with the request if the request
545
-	 * is including any cookies.
546
-	 *
547
-	 * @return bool
548
-	 * @since 9.1.0
549
-	 */
550
-	public function passesStrictCookieCheck(): bool {
551
-		if(!$this->cookieCheckRequired()) {
552
-			return true;
553
-		}
554
-
555
-		$cookieName = $this->getProtectedCookieName('nc_sameSiteCookiestrict');
556
-		if($this->getCookie($cookieName) === 'true'
557
-			&& $this->passesLaxCookieCheck()) {
558
-			return true;
559
-		}
560
-		return false;
561
-	}
562
-
563
-	/**
564
-	 * Checks if the lax cookie has been sent with the request if the request
565
-	 * is including any cookies.
566
-	 *
567
-	 * @return bool
568
-	 * @since 9.1.0
569
-	 */
570
-	public function passesLaxCookieCheck(): bool {
571
-		if(!$this->cookieCheckRequired()) {
572
-			return true;
573
-		}
574
-
575
-		$cookieName = $this->getProtectedCookieName('nc_sameSiteCookielax');
576
-		if($this->getCookie($cookieName) === 'true') {
577
-			return true;
578
-		}
579
-		return false;
580
-	}
581
-
582
-
583
-	/**
584
-	 * Returns an ID for the request, value is not guaranteed to be unique and is mostly meant for logging
585
-	 * If `mod_unique_id` is installed this value will be taken.
586
-	 * @return string
587
-	 */
588
-	public function getId(): string {
589
-		if(isset($this->server['UNIQUE_ID'])) {
590
-			return $this->server['UNIQUE_ID'];
591
-		}
592
-
593
-		if(empty($this->requestId)) {
594
-			$validChars = ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS;
595
-			$this->requestId = $this->secureRandom->generate(20, $validChars);
596
-		}
597
-
598
-		return $this->requestId;
599
-	}
600
-
601
-	/**
602
-	 * Returns the remote address, if the connection came from a trusted proxy
603
-	 * and `forwarded_for_headers` has been configured then the IP address
604
-	 * specified in this header will be returned instead.
605
-	 * Do always use this instead of $_SERVER['REMOTE_ADDR']
606
-	 * @return string IP address
607
-	 */
608
-	public function getRemoteAddress(): string {
609
-		$remoteAddress = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
610
-		$trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
611
-
612
-		if(\is_array($trustedProxies) && \in_array($remoteAddress, $trustedProxies)) {
613
-			$forwardedForHeaders = $this->config->getSystemValue('forwarded_for_headers', [
614
-				'HTTP_X_FORWARDED_FOR'
615
-				// only have one default, so we cannot ship an insecure product out of the box
616
-			]);
617
-
618
-			foreach($forwardedForHeaders as $header) {
619
-				if(isset($this->server[$header])) {
620
-					foreach(explode(',', $this->server[$header]) as $IP) {
621
-						$IP = trim($IP);
622
-						if (filter_var($IP, FILTER_VALIDATE_IP) !== false) {
623
-							return $IP;
624
-						}
625
-					}
626
-				}
627
-			}
628
-		}
629
-
630
-		return $remoteAddress;
631
-	}
632
-
633
-	/**
634
-	 * Check overwrite condition
635
-	 * @param string $type
636
-	 * @return bool
637
-	 */
638
-	private function isOverwriteCondition(string $type = ''): bool {
639
-		$regex = '/' . $this->config->getSystemValue('overwritecondaddr', '')  . '/';
640
-		$remoteAddr = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
641
-		return $regex === '//' || preg_match($regex, $remoteAddr) === 1
642
-		|| $type !== 'protocol';
643
-	}
644
-
645
-	/**
646
-	 * Returns the server protocol. It respects one or more reverse proxies servers
647
-	 * and load balancers
648
-	 * @return string Server protocol (http or https)
649
-	 */
650
-	public function getServerProtocol(): string {
651
-		if($this->config->getSystemValue('overwriteprotocol') !== ''
652
-			&& $this->isOverwriteCondition('protocol')) {
653
-			return $this->config->getSystemValue('overwriteprotocol');
654
-		}
655
-
656
-		if (isset($this->server['HTTP_X_FORWARDED_PROTO'])) {
657
-			if (strpos($this->server['HTTP_X_FORWARDED_PROTO'], ',') !== false) {
658
-				$parts = explode(',', $this->server['HTTP_X_FORWARDED_PROTO']);
659
-				$proto = strtolower(trim($parts[0]));
660
-			} else {
661
-				$proto = strtolower($this->server['HTTP_X_FORWARDED_PROTO']);
662
-			}
663
-
664
-			// Verify that the protocol is always HTTP or HTTPS
665
-			// default to http if an invalid value is provided
666
-			return $proto === 'https' ? 'https' : 'http';
667
-		}
668
-
669
-		if (isset($this->server['HTTPS'])
670
-			&& $this->server['HTTPS'] !== null
671
-			&& $this->server['HTTPS'] !== 'off'
672
-			&& $this->server['HTTPS'] !== '') {
673
-			return 'https';
674
-		}
675
-
676
-		return 'http';
677
-	}
678
-
679
-	/**
680
-	 * Returns the used HTTP protocol.
681
-	 *
682
-	 * @return string HTTP protocol. HTTP/2, HTTP/1.1 or HTTP/1.0.
683
-	 */
684
-	public function getHttpProtocol(): string {
685
-		$claimedProtocol = $this->server['SERVER_PROTOCOL'];
686
-
687
-		if (\is_string($claimedProtocol)) {
688
-			$claimedProtocol = strtoupper($claimedProtocol);
689
-		}
690
-
691
-		$validProtocols = [
692
-			'HTTP/1.0',
693
-			'HTTP/1.1',
694
-			'HTTP/2',
695
-		];
696
-
697
-		if(\in_array($claimedProtocol, $validProtocols, true)) {
698
-			return $claimedProtocol;
699
-		}
700
-
701
-		return 'HTTP/1.1';
702
-	}
703
-
704
-	/**
705
-	 * Returns the request uri, even if the website uses one or more
706
-	 * reverse proxies
707
-	 * @return string
708
-	 */
709
-	public function getRequestUri(): string {
710
-		$uri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : '';
711
-		if($this->config->getSystemValue('overwritewebroot') !== '' && $this->isOverwriteCondition()) {
712
-			$uri = $this->getScriptName() . substr($uri, \strlen($this->server['SCRIPT_NAME']));
713
-		}
714
-		return $uri;
715
-	}
716
-
717
-	/**
718
-	 * Get raw PathInfo from request (not urldecoded)
719
-	 * @throws \Exception
720
-	 * @return string Path info
721
-	 */
722
-	public function getRawPathInfo(): string {
723
-		$requestUri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : '';
724
-		// remove too many leading slashes - can be caused by reverse proxy configuration
725
-		if (strpos($requestUri, '/') === 0) {
726
-			$requestUri = '/' . ltrim($requestUri, '/');
727
-		}
728
-
729
-		$requestUri = preg_replace('%/{2,}%', '/', $requestUri);
730
-
731
-		// Remove the query string from REQUEST_URI
732
-		if ($pos = strpos($requestUri, '?')) {
733
-			$requestUri = substr($requestUri, 0, $pos);
734
-		}
735
-
736
-		$scriptName = $this->server['SCRIPT_NAME'];
737
-		$pathInfo = $requestUri;
738
-
739
-		// strip off the script name's dir and file name
740
-		// FIXME: Sabre does not really belong here
741
-		list($path, $name) = \Sabre\Uri\split($scriptName);
742
-		if (!empty($path)) {
743
-			if($path === $pathInfo || strpos($pathInfo, $path.'/') === 0) {
744
-				$pathInfo = substr($pathInfo, \strlen($path));
745
-			} else {
746
-				throw new \Exception("The requested uri($requestUri) cannot be processed by the script '$scriptName')");
747
-			}
748
-		}
749
-		if ($name === null) {
750
-			$name = '';
751
-		}
752
-
753
-		if (strpos($pathInfo, '/'.$name) === 0) {
754
-			$pathInfo = substr($pathInfo, \strlen($name) + 1);
755
-		}
756
-		if ($name !== '' && strpos($pathInfo, $name) === 0) {
757
-			$pathInfo = substr($pathInfo, \strlen($name));
758
-		}
759
-		if($pathInfo === false || $pathInfo === '/'){
760
-			return '';
761
-		} else {
762
-			return $pathInfo;
763
-		}
764
-	}
765
-
766
-	/**
767
-	 * Get PathInfo from request
768
-	 * @throws \Exception
769
-	 * @return string|false Path info or false when not found
770
-	 */
771
-	public function getPathInfo() {
772
-		$pathInfo = $this->getRawPathInfo();
773
-		// following is taken from \Sabre\HTTP\URLUtil::decodePathSegment
774
-		$pathInfo = rawurldecode($pathInfo);
775
-		$encoding = mb_detect_encoding($pathInfo, ['UTF-8', 'ISO-8859-1']);
776
-
777
-		switch($encoding) {
778
-			case 'ISO-8859-1' :
779
-				$pathInfo = utf8_encode($pathInfo);
780
-		}
781
-		// end copy
782
-
783
-		return $pathInfo;
784
-	}
785
-
786
-	/**
787
-	 * Returns the script name, even if the website uses one or more
788
-	 * reverse proxies
789
-	 * @return string the script name
790
-	 */
791
-	public function getScriptName(): string {
792
-		$name = $this->server['SCRIPT_NAME'];
793
-		$overwriteWebRoot =  $this->config->getSystemValue('overwritewebroot');
794
-		if ($overwriteWebRoot !== '' && $this->isOverwriteCondition()) {
795
-			// FIXME: This code is untestable due to __DIR__, also that hardcoded path is really dangerous
796
-			$serverRoot = str_replace('\\', '/', substr(__DIR__, 0, -\strlen('lib/private/appframework/http/')));
797
-			$suburi = str_replace('\\', '/', substr(realpath($this->server['SCRIPT_FILENAME']), \strlen($serverRoot)));
798
-			$name = '/' . ltrim($overwriteWebRoot . $suburi, '/');
799
-		}
800
-		return $name;
801
-	}
802
-
803
-	/**
804
-	 * Checks whether the user agent matches a given regex
805
-	 * @param array $agent array of agent names
806
-	 * @return bool true if at least one of the given agent matches, false otherwise
807
-	 */
808
-	public function isUserAgent(array $agent): bool {
809
-		if (!isset($this->server['HTTP_USER_AGENT'])) {
810
-			return false;
811
-		}
812
-		foreach ($agent as $regex) {
813
-			if (preg_match($regex, $this->server['HTTP_USER_AGENT'])) {
814
-				return true;
815
-			}
816
-		}
817
-		return false;
818
-	}
819
-
820
-	/**
821
-	 * Returns the unverified server host from the headers without checking
822
-	 * whether it is a trusted domain
823
-	 * @return string Server host
824
-	 */
825
-	public function getInsecureServerHost(): string {
826
-		$host = 'localhost';
827
-		if (isset($this->server['HTTP_X_FORWARDED_HOST'])) {
828
-			if (strpos($this->server['HTTP_X_FORWARDED_HOST'], ',') !== false) {
829
-				$parts = explode(',', $this->server['HTTP_X_FORWARDED_HOST']);
830
-				$host = trim(current($parts));
831
-			} else {
832
-				$host = $this->server['HTTP_X_FORWARDED_HOST'];
833
-			}
834
-		} else {
835
-			if (isset($this->server['HTTP_HOST'])) {
836
-				$host = $this->server['HTTP_HOST'];
837
-			} else if (isset($this->server['SERVER_NAME'])) {
838
-				$host = $this->server['SERVER_NAME'];
839
-			}
840
-		}
841
-		return $host;
842
-	}
843
-
844
-
845
-	/**
846
-	 * Returns the server host from the headers, or the first configured
847
-	 * trusted domain if the host isn't in the trusted list
848
-	 * @return string Server host
849
-	 */
850
-	public function getServerHost(): string {
851
-		// overwritehost is always trusted
852
-		$host = $this->getOverwriteHost();
853
-		if ($host !== null) {
854
-			return $host;
855
-		}
856
-
857
-		// get the host from the headers
858
-		$host = $this->getInsecureServerHost();
859
-
860
-		// Verify that the host is a trusted domain if the trusted domains
861
-		// are defined
862
-		// If no trusted domain is provided the first trusted domain is returned
863
-		$trustedDomainHelper = new TrustedDomainHelper($this->config);
864
-		if ($trustedDomainHelper->isTrustedDomain($host)) {
865
-			return $host;
866
-		} else {
867
-			$trustedList = $this->config->getSystemValue('trusted_domains', []);
868
-			if(!empty($trustedList)) {
869
-				return $trustedList[0];
870
-			} else {
871
-				return '';
872
-			}
873
-		}
874
-	}
875
-
876
-	/**
877
-	 * Returns the overwritehost setting from the config if set and
878
-	 * if the overwrite condition is met
879
-	 * @return string|null overwritehost value or null if not defined or the defined condition
880
-	 * isn't met
881
-	 */
882
-	private function getOverwriteHost() {
883
-		if($this->config->getSystemValue('overwritehost') !== '' && $this->isOverwriteCondition()) {
884
-			return $this->config->getSystemValue('overwritehost');
885
-		}
886
-		return null;
887
-	}
62
+    const USER_AGENT_IE = '/(MSIE)|(Trident)/';
63
+    // Microsoft Edge User Agent from https://msdn.microsoft.com/en-us/library/hh869301(v=vs.85).aspx
64
+    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.]+$/';
65
+    // Firefox User Agent from https://developer.mozilla.org/en-US/docs/Web/HTTP/Gecko_user_agent_string_reference
66
+    const USER_AGENT_FIREFOX = '/^Mozilla\/5\.0 \([^)]+\) Gecko\/[0-9.]+ Firefox\/[0-9.]+$/';
67
+    // Chrome User Agent from https://developer.chrome.com/multidevice/user-agent
68
+    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.]+$/';
69
+    // Safari User Agent from http://www.useragentstring.com/pages/Safari/
70
+    const USER_AGENT_SAFARI = '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\) Version\/[0-9.]+ Safari\/[0-9.A-Z]+$/';
71
+    // Android Chrome user agent: https://developers.google.com/chrome/mobile/docs/user-agent
72
+    const USER_AGENT_ANDROID_MOBILE_CHROME = '#Android.*Chrome/[.0-9]*#';
73
+    const USER_AGENT_FREEBOX = '#^Mozilla/5\.0$#';
74
+    const REGEX_LOCALHOST = '/^(127\.0\.0\.1|localhost|::1)$/';
75
+
76
+    /**
77
+     * @deprecated use \OCP\IRequest::USER_AGENT_CLIENT_IOS instead
78
+     */
79
+    const USER_AGENT_OWNCLOUD_IOS = '/^Mozilla\/5\.0 \(iOS\) (ownCloud|Nextcloud)\-iOS.*$/';
80
+    /**
81
+     * @deprecated use \OCP\IRequest::USER_AGENT_CLIENT_ANDROID instead
82
+     */
83
+    const USER_AGENT_OWNCLOUD_ANDROID = '/^Mozilla\/5\.0 \(Android\) ownCloud\-android.*$/';
84
+    /**
85
+     * @deprecated use \OCP\IRequest::USER_AGENT_CLIENT_DESKTOP instead
86
+     */
87
+    const USER_AGENT_OWNCLOUD_DESKTOP = '/^Mozilla\/5\.0 \([A-Za-z ]+\) (mirall|csyncoC)\/.*$/';
88
+
89
+    protected $inputStream;
90
+    protected $content;
91
+    protected $items = [];
92
+    protected $allowedKeys = [
93
+        'get',
94
+        'post',
95
+        'files',
96
+        'server',
97
+        'env',
98
+        'cookies',
99
+        'urlParams',
100
+        'parameters',
101
+        'method',
102
+        'requesttoken',
103
+    ];
104
+    /** @var ISecureRandom */
105
+    protected $secureRandom;
106
+    /** @var IConfig */
107
+    protected $config;
108
+    /** @var string */
109
+    protected $requestId = '';
110
+    /** @var ICrypto */
111
+    protected $crypto;
112
+    /** @var CsrfTokenManager|null */
113
+    protected $csrfTokenManager;
114
+
115
+    /** @var bool */
116
+    protected $contentDecoded = false;
117
+
118
+    /**
119
+     * @param array $vars An associative array with the following optional values:
120
+     *        - array 'urlParams' the parameters which were matched from the URL
121
+     *        - array 'get' the $_GET array
122
+     *        - array|string 'post' the $_POST array or JSON string
123
+     *        - array 'files' the $_FILES array
124
+     *        - array 'server' the $_SERVER array
125
+     *        - array 'env' the $_ENV array
126
+     *        - array 'cookies' the $_COOKIE array
127
+     *        - string 'method' the request method (GET, POST etc)
128
+     *        - string|false 'requesttoken' the requesttoken or false when not available
129
+     * @param ISecureRandom $secureRandom
130
+     * @param IConfig $config
131
+     * @param CsrfTokenManager|null $csrfTokenManager
132
+     * @param string $stream
133
+     * @see http://www.php.net/manual/en/reserved.variables.php
134
+     */
135
+    public function __construct(array $vars= [],
136
+                                ISecureRandom $secureRandom = null,
137
+                                IConfig $config,
138
+                                CsrfTokenManager $csrfTokenManager = null,
139
+                                string $stream = 'php://input') {
140
+        $this->inputStream = $stream;
141
+        $this->items['params'] = [];
142
+        $this->secureRandom = $secureRandom;
143
+        $this->config = $config;
144
+        $this->csrfTokenManager = $csrfTokenManager;
145
+
146
+        if(!array_key_exists('method', $vars)) {
147
+            $vars['method'] = 'GET';
148
+        }
149
+
150
+        foreach($this->allowedKeys as $name) {
151
+            $this->items[$name] = isset($vars[$name])
152
+                ? $vars[$name]
153
+                : [];
154
+        }
155
+
156
+        $this->items['parameters'] = array_merge(
157
+            $this->items['get'],
158
+            $this->items['post'],
159
+            $this->items['urlParams'],
160
+            $this->items['params']
161
+        );
162
+
163
+    }
164
+    /**
165
+     * @param array $parameters
166
+     */
167
+    public function setUrlParameters(array $parameters) {
168
+        $this->items['urlParams'] = $parameters;
169
+        $this->items['parameters'] = array_merge(
170
+            $this->items['parameters'],
171
+            $this->items['urlParams']
172
+        );
173
+    }
174
+
175
+    /**
176
+     * Countable method
177
+     * @return int
178
+     */
179
+    public function count(): int {
180
+        return \count($this->items['parameters']);
181
+    }
182
+
183
+    /**
184
+     * ArrayAccess methods
185
+     *
186
+     * Gives access to the combined GET, POST and urlParams arrays
187
+     *
188
+     * Examples:
189
+     *
190
+     * $var = $request['myvar'];
191
+     *
192
+     * or
193
+     *
194
+     * if(!isset($request['myvar']) {
195
+     * 	// Do something
196
+     * }
197
+     *
198
+     * $request['myvar'] = 'something'; // This throws an exception.
199
+     *
200
+     * @param string $offset The key to lookup
201
+     * @return boolean
202
+     */
203
+    public function offsetExists($offset): bool {
204
+        return isset($this->items['parameters'][$offset]);
205
+    }
206
+
207
+    /**
208
+     * @see offsetExists
209
+     * @param string $offset
210
+     * @return mixed
211
+     */
212
+    public function offsetGet($offset) {
213
+        return isset($this->items['parameters'][$offset])
214
+            ? $this->items['parameters'][$offset]
215
+            : null;
216
+    }
217
+
218
+    /**
219
+     * @see offsetExists
220
+     * @param string $offset
221
+     * @param mixed $value
222
+     */
223
+    public function offsetSet($offset, $value) {
224
+        throw new \RuntimeException('You cannot change the contents of the request object');
225
+    }
226
+
227
+    /**
228
+     * @see offsetExists
229
+     * @param string $offset
230
+     */
231
+    public function offsetUnset($offset) {
232
+        throw new \RuntimeException('You cannot change the contents of the request object');
233
+    }
234
+
235
+    /**
236
+     * Magic property accessors
237
+     * @param string $name
238
+     * @param mixed $value
239
+     */
240
+    public function __set($name, $value) {
241
+        throw new \RuntimeException('You cannot change the contents of the request object');
242
+    }
243
+
244
+    /**
245
+     * Access request variables by method and name.
246
+     * Examples:
247
+     *
248
+     * $request->post['myvar']; // Only look for POST variables
249
+     * $request->myvar; or $request->{'myvar'}; or $request->{$myvar}
250
+     * Looks in the combined GET, POST and urlParams array.
251
+     *
252
+     * If you access e.g. ->post but the current HTTP request method
253
+     * is GET a \LogicException will be thrown.
254
+     *
255
+     * @param string $name The key to look for.
256
+     * @throws \LogicException
257
+     * @return mixed|null
258
+     */
259
+    public function __get($name) {
260
+        switch($name) {
261
+            case 'put':
262
+            case 'patch':
263
+            case 'get':
264
+            case 'post':
265
+                if($this->method !== strtoupper($name)) {
266
+                    throw new \LogicException(sprintf('%s cannot be accessed in a %s request.', $name, $this->method));
267
+                }
268
+                return $this->getContent();
269
+            case 'files':
270
+            case 'server':
271
+            case 'env':
272
+            case 'cookies':
273
+            case 'urlParams':
274
+            case 'method':
275
+                return isset($this->items[$name])
276
+                    ? $this->items[$name]
277
+                    : null;
278
+            case 'parameters':
279
+            case 'params':
280
+                return $this->getContent();
281
+            default;
282
+                return isset($this[$name])
283
+                    ? $this[$name]
284
+                    : null;
285
+        }
286
+    }
287
+
288
+    /**
289
+     * @param string $name
290
+     * @return bool
291
+     */
292
+    public function __isset($name) {
293
+        if (\in_array($name, $this->allowedKeys, true)) {
294
+            return true;
295
+        }
296
+        return isset($this->items['parameters'][$name]);
297
+    }
298
+
299
+    /**
300
+     * @param string $id
301
+     */
302
+    public function __unset($id) {
303
+        throw new \RuntimeException('You cannot change the contents of the request object');
304
+    }
305
+
306
+    /**
307
+     * Returns the value for a specific http header.
308
+     *
309
+     * This method returns null if the header did not exist.
310
+     *
311
+     * @param string $name
312
+     * @return string
313
+     */
314
+    public function getHeader(string $name): string {
315
+
316
+        $name = strtoupper(str_replace('-', '_',$name));
317
+        if (isset($this->server['HTTP_' . $name])) {
318
+            return $this->server['HTTP_' . $name];
319
+        }
320
+
321
+        // There's a few headers that seem to end up in the top-level
322
+        // server array.
323
+        switch ($name) {
324
+            case 'CONTENT_TYPE' :
325
+            case 'CONTENT_LENGTH' :
326
+                if (isset($this->server[$name])) {
327
+                    return $this->server[$name];
328
+                }
329
+                break;
330
+            case 'REMOTE_ADDR' :
331
+                if (isset($this->server[$name])) {
332
+                    return $this->server[$name];
333
+                }
334
+                break;
335
+        }
336
+
337
+        return '';
338
+    }
339
+
340
+    /**
341
+     * Lets you access post and get parameters by the index
342
+     * In case of json requests the encoded json body is accessed
343
+     *
344
+     * @param string $key the key which you want to access in the URL Parameter
345
+     *                     placeholder, $_POST or $_GET array.
346
+     *                     The priority how they're returned is the following:
347
+     *                     1. URL parameters
348
+     *                     2. POST parameters
349
+     *                     3. GET parameters
350
+     * @param mixed $default If the key is not found, this value will be returned
351
+     * @return mixed the content of the array
352
+     */
353
+    public function getParam(string $key, $default = null) {
354
+        return isset($this->parameters[$key])
355
+            ? $this->parameters[$key]
356
+            : $default;
357
+    }
358
+
359
+    /**
360
+     * Returns all params that were received, be it from the request
361
+     * (as GET or POST) or throuh the URL by the route
362
+     * @return array the array with all parameters
363
+     */
364
+    public function getParams(): array {
365
+        return is_array($this->parameters) ? $this->parameters : [];
366
+    }
367
+
368
+    /**
369
+     * Returns the method of the request
370
+     * @return string the method of the request (POST, GET, etc)
371
+     */
372
+    public function getMethod(): string {
373
+        return $this->method;
374
+    }
375
+
376
+    /**
377
+     * Shortcut for accessing an uploaded file through the $_FILES array
378
+     * @param string $key the key that will be taken from the $_FILES array
379
+     * @return array the file in the $_FILES element
380
+     */
381
+    public function getUploadedFile(string $key) {
382
+        return isset($this->files[$key]) ? $this->files[$key] : null;
383
+    }
384
+
385
+    /**
386
+     * Shortcut for getting env variables
387
+     * @param string $key the key that will be taken from the $_ENV array
388
+     * @return array the value in the $_ENV element
389
+     */
390
+    public function getEnv(string $key) {
391
+        return isset($this->env[$key]) ? $this->env[$key] : null;
392
+    }
393
+
394
+    /**
395
+     * Shortcut for getting cookie variables
396
+     * @param string $key the key that will be taken from the $_COOKIE array
397
+     * @return string the value in the $_COOKIE element
398
+     */
399
+    public function getCookie(string $key) {
400
+        return isset($this->cookies[$key]) ? $this->cookies[$key] : null;
401
+    }
402
+
403
+    /**
404
+     * Returns the request body content.
405
+     *
406
+     * If the HTTP request method is PUT and the body
407
+     * not application/x-www-form-urlencoded or application/json a stream
408
+     * resource is returned, otherwise an array.
409
+     *
410
+     * @return array|string|resource The request body content or a resource to read the body stream.
411
+     *
412
+     * @throws \LogicException
413
+     */
414
+    protected function getContent() {
415
+        // If the content can't be parsed into an array then return a stream resource.
416
+        if ($this->method === 'PUT'
417
+            && $this->getHeader('Content-Length') !== '0'
418
+            && $this->getHeader('Content-Length') !== ''
419
+            && strpos($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded') === false
420
+            && strpos($this->getHeader('Content-Type'), 'application/json') === false
421
+        ) {
422
+            if ($this->content === false) {
423
+                throw new \LogicException(
424
+                    '"put" can only be accessed once if not '
425
+                    . 'application/x-www-form-urlencoded or application/json.'
426
+                );
427
+            }
428
+            $this->content = false;
429
+            return fopen($this->inputStream, 'rb');
430
+        } else {
431
+            $this->decodeContent();
432
+            return $this->items['parameters'];
433
+        }
434
+    }
435
+
436
+    /**
437
+     * Attempt to decode the content and populate parameters
438
+     */
439
+    protected function decodeContent() {
440
+        if ($this->contentDecoded) {
441
+            return;
442
+        }
443
+        $params = [];
444
+
445
+        // 'application/json' must be decoded manually.
446
+        if (strpos($this->getHeader('Content-Type'), 'application/json') !== false) {
447
+            $params = json_decode(file_get_contents($this->inputStream), true);
448
+            if($params !== null && \count($params) > 0) {
449
+                $this->items['params'] = $params;
450
+                if($this->method === 'POST') {
451
+                    $this->items['post'] = $params;
452
+                }
453
+            }
454
+
455
+        // Handle application/x-www-form-urlencoded for methods other than GET
456
+        // or post correctly
457
+        } elseif($this->method !== 'GET'
458
+                && $this->method !== 'POST'
459
+                && strpos($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded') !== false) {
460
+
461
+            parse_str(file_get_contents($this->inputStream), $params);
462
+            if(\is_array($params)) {
463
+                $this->items['params'] = $params;
464
+            }
465
+        }
466
+
467
+        if (\is_array($params)) {
468
+            $this->items['parameters'] = array_merge($this->items['parameters'], $params);
469
+        }
470
+        $this->contentDecoded = true;
471
+    }
472
+
473
+
474
+    /**
475
+     * Checks if the CSRF check was correct
476
+     * @return bool true if CSRF check passed
477
+     */
478
+    public function passesCSRFCheck(): bool {
479
+        if($this->csrfTokenManager === null) {
480
+            return false;
481
+        }
482
+
483
+        if(!$this->passesStrictCookieCheck()) {
484
+            return false;
485
+        }
486
+
487
+        if (isset($this->items['get']['requesttoken'])) {
488
+            $token = $this->items['get']['requesttoken'];
489
+        } elseif (isset($this->items['post']['requesttoken'])) {
490
+            $token = $this->items['post']['requesttoken'];
491
+        } elseif (isset($this->items['server']['HTTP_REQUESTTOKEN'])) {
492
+            $token = $this->items['server']['HTTP_REQUESTTOKEN'];
493
+        } else {
494
+            //no token found.
495
+            return false;
496
+        }
497
+        $token = new CsrfToken($token);
498
+
499
+        return $this->csrfTokenManager->isTokenValid($token);
500
+    }
501
+
502
+    /**
503
+     * Whether the cookie checks are required
504
+     *
505
+     * @return bool
506
+     */
507
+    private function cookieCheckRequired(): bool {
508
+        if ($this->getHeader('OCS-APIREQUEST')) {
509
+            return false;
510
+        }
511
+        if($this->getCookie(session_name()) === null && $this->getCookie('nc_token') === null) {
512
+            return false;
513
+        }
514
+
515
+        return true;
516
+    }
517
+
518
+    /**
519
+     * Wrapper around session_get_cookie_params
520
+     *
521
+     * @return array
522
+     */
523
+    public function getCookieParams(): array {
524
+        return session_get_cookie_params();
525
+    }
526
+
527
+    /**
528
+     * Appends the __Host- prefix to the cookie if applicable
529
+     *
530
+     * @param string $name
531
+     * @return string
532
+     */
533
+    protected function getProtectedCookieName(string $name): string {
534
+        $cookieParams = $this->getCookieParams();
535
+        $prefix = '';
536
+        if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
537
+            $prefix = '__Host-';
538
+        }
539
+
540
+        return $prefix.$name;
541
+    }
542
+
543
+    /**
544
+     * Checks if the strict cookie has been sent with the request if the request
545
+     * is including any cookies.
546
+     *
547
+     * @return bool
548
+     * @since 9.1.0
549
+     */
550
+    public function passesStrictCookieCheck(): bool {
551
+        if(!$this->cookieCheckRequired()) {
552
+            return true;
553
+        }
554
+
555
+        $cookieName = $this->getProtectedCookieName('nc_sameSiteCookiestrict');
556
+        if($this->getCookie($cookieName) === 'true'
557
+            && $this->passesLaxCookieCheck()) {
558
+            return true;
559
+        }
560
+        return false;
561
+    }
562
+
563
+    /**
564
+     * Checks if the lax cookie has been sent with the request if the request
565
+     * is including any cookies.
566
+     *
567
+     * @return bool
568
+     * @since 9.1.0
569
+     */
570
+    public function passesLaxCookieCheck(): bool {
571
+        if(!$this->cookieCheckRequired()) {
572
+            return true;
573
+        }
574
+
575
+        $cookieName = $this->getProtectedCookieName('nc_sameSiteCookielax');
576
+        if($this->getCookie($cookieName) === 'true') {
577
+            return true;
578
+        }
579
+        return false;
580
+    }
581
+
582
+
583
+    /**
584
+     * Returns an ID for the request, value is not guaranteed to be unique and is mostly meant for logging
585
+     * If `mod_unique_id` is installed this value will be taken.
586
+     * @return string
587
+     */
588
+    public function getId(): string {
589
+        if(isset($this->server['UNIQUE_ID'])) {
590
+            return $this->server['UNIQUE_ID'];
591
+        }
592
+
593
+        if(empty($this->requestId)) {
594
+            $validChars = ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS;
595
+            $this->requestId = $this->secureRandom->generate(20, $validChars);
596
+        }
597
+
598
+        return $this->requestId;
599
+    }
600
+
601
+    /**
602
+     * Returns the remote address, if the connection came from a trusted proxy
603
+     * and `forwarded_for_headers` has been configured then the IP address
604
+     * specified in this header will be returned instead.
605
+     * Do always use this instead of $_SERVER['REMOTE_ADDR']
606
+     * @return string IP address
607
+     */
608
+    public function getRemoteAddress(): string {
609
+        $remoteAddress = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
610
+        $trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
611
+
612
+        if(\is_array($trustedProxies) && \in_array($remoteAddress, $trustedProxies)) {
613
+            $forwardedForHeaders = $this->config->getSystemValue('forwarded_for_headers', [
614
+                'HTTP_X_FORWARDED_FOR'
615
+                // only have one default, so we cannot ship an insecure product out of the box
616
+            ]);
617
+
618
+            foreach($forwardedForHeaders as $header) {
619
+                if(isset($this->server[$header])) {
620
+                    foreach(explode(',', $this->server[$header]) as $IP) {
621
+                        $IP = trim($IP);
622
+                        if (filter_var($IP, FILTER_VALIDATE_IP) !== false) {
623
+                            return $IP;
624
+                        }
625
+                    }
626
+                }
627
+            }
628
+        }
629
+
630
+        return $remoteAddress;
631
+    }
632
+
633
+    /**
634
+     * Check overwrite condition
635
+     * @param string $type
636
+     * @return bool
637
+     */
638
+    private function isOverwriteCondition(string $type = ''): bool {
639
+        $regex = '/' . $this->config->getSystemValue('overwritecondaddr', '')  . '/';
640
+        $remoteAddr = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
641
+        return $regex === '//' || preg_match($regex, $remoteAddr) === 1
642
+        || $type !== 'protocol';
643
+    }
644
+
645
+    /**
646
+     * Returns the server protocol. It respects one or more reverse proxies servers
647
+     * and load balancers
648
+     * @return string Server protocol (http or https)
649
+     */
650
+    public function getServerProtocol(): string {
651
+        if($this->config->getSystemValue('overwriteprotocol') !== ''
652
+            && $this->isOverwriteCondition('protocol')) {
653
+            return $this->config->getSystemValue('overwriteprotocol');
654
+        }
655
+
656
+        if (isset($this->server['HTTP_X_FORWARDED_PROTO'])) {
657
+            if (strpos($this->server['HTTP_X_FORWARDED_PROTO'], ',') !== false) {
658
+                $parts = explode(',', $this->server['HTTP_X_FORWARDED_PROTO']);
659
+                $proto = strtolower(trim($parts[0]));
660
+            } else {
661
+                $proto = strtolower($this->server['HTTP_X_FORWARDED_PROTO']);
662
+            }
663
+
664
+            // Verify that the protocol is always HTTP or HTTPS
665
+            // default to http if an invalid value is provided
666
+            return $proto === 'https' ? 'https' : 'http';
667
+        }
668
+
669
+        if (isset($this->server['HTTPS'])
670
+            && $this->server['HTTPS'] !== null
671
+            && $this->server['HTTPS'] !== 'off'
672
+            && $this->server['HTTPS'] !== '') {
673
+            return 'https';
674
+        }
675
+
676
+        return 'http';
677
+    }
678
+
679
+    /**
680
+     * Returns the used HTTP protocol.
681
+     *
682
+     * @return string HTTP protocol. HTTP/2, HTTP/1.1 or HTTP/1.0.
683
+     */
684
+    public function getHttpProtocol(): string {
685
+        $claimedProtocol = $this->server['SERVER_PROTOCOL'];
686
+
687
+        if (\is_string($claimedProtocol)) {
688
+            $claimedProtocol = strtoupper($claimedProtocol);
689
+        }
690
+
691
+        $validProtocols = [
692
+            'HTTP/1.0',
693
+            'HTTP/1.1',
694
+            'HTTP/2',
695
+        ];
696
+
697
+        if(\in_array($claimedProtocol, $validProtocols, true)) {
698
+            return $claimedProtocol;
699
+        }
700
+
701
+        return 'HTTP/1.1';
702
+    }
703
+
704
+    /**
705
+     * Returns the request uri, even if the website uses one or more
706
+     * reverse proxies
707
+     * @return string
708
+     */
709
+    public function getRequestUri(): string {
710
+        $uri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : '';
711
+        if($this->config->getSystemValue('overwritewebroot') !== '' && $this->isOverwriteCondition()) {
712
+            $uri = $this->getScriptName() . substr($uri, \strlen($this->server['SCRIPT_NAME']));
713
+        }
714
+        return $uri;
715
+    }
716
+
717
+    /**
718
+     * Get raw PathInfo from request (not urldecoded)
719
+     * @throws \Exception
720
+     * @return string Path info
721
+     */
722
+    public function getRawPathInfo(): string {
723
+        $requestUri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : '';
724
+        // remove too many leading slashes - can be caused by reverse proxy configuration
725
+        if (strpos($requestUri, '/') === 0) {
726
+            $requestUri = '/' . ltrim($requestUri, '/');
727
+        }
728
+
729
+        $requestUri = preg_replace('%/{2,}%', '/', $requestUri);
730
+
731
+        // Remove the query string from REQUEST_URI
732
+        if ($pos = strpos($requestUri, '?')) {
733
+            $requestUri = substr($requestUri, 0, $pos);
734
+        }
735
+
736
+        $scriptName = $this->server['SCRIPT_NAME'];
737
+        $pathInfo = $requestUri;
738
+
739
+        // strip off the script name's dir and file name
740
+        // FIXME: Sabre does not really belong here
741
+        list($path, $name) = \Sabre\Uri\split($scriptName);
742
+        if (!empty($path)) {
743
+            if($path === $pathInfo || strpos($pathInfo, $path.'/') === 0) {
744
+                $pathInfo = substr($pathInfo, \strlen($path));
745
+            } else {
746
+                throw new \Exception("The requested uri($requestUri) cannot be processed by the script '$scriptName')");
747
+            }
748
+        }
749
+        if ($name === null) {
750
+            $name = '';
751
+        }
752
+
753
+        if (strpos($pathInfo, '/'.$name) === 0) {
754
+            $pathInfo = substr($pathInfo, \strlen($name) + 1);
755
+        }
756
+        if ($name !== '' && strpos($pathInfo, $name) === 0) {
757
+            $pathInfo = substr($pathInfo, \strlen($name));
758
+        }
759
+        if($pathInfo === false || $pathInfo === '/'){
760
+            return '';
761
+        } else {
762
+            return $pathInfo;
763
+        }
764
+    }
765
+
766
+    /**
767
+     * Get PathInfo from request
768
+     * @throws \Exception
769
+     * @return string|false Path info or false when not found
770
+     */
771
+    public function getPathInfo() {
772
+        $pathInfo = $this->getRawPathInfo();
773
+        // following is taken from \Sabre\HTTP\URLUtil::decodePathSegment
774
+        $pathInfo = rawurldecode($pathInfo);
775
+        $encoding = mb_detect_encoding($pathInfo, ['UTF-8', 'ISO-8859-1']);
776
+
777
+        switch($encoding) {
778
+            case 'ISO-8859-1' :
779
+                $pathInfo = utf8_encode($pathInfo);
780
+        }
781
+        // end copy
782
+
783
+        return $pathInfo;
784
+    }
785
+
786
+    /**
787
+     * Returns the script name, even if the website uses one or more
788
+     * reverse proxies
789
+     * @return string the script name
790
+     */
791
+    public function getScriptName(): string {
792
+        $name = $this->server['SCRIPT_NAME'];
793
+        $overwriteWebRoot =  $this->config->getSystemValue('overwritewebroot');
794
+        if ($overwriteWebRoot !== '' && $this->isOverwriteCondition()) {
795
+            // FIXME: This code is untestable due to __DIR__, also that hardcoded path is really dangerous
796
+            $serverRoot = str_replace('\\', '/', substr(__DIR__, 0, -\strlen('lib/private/appframework/http/')));
797
+            $suburi = str_replace('\\', '/', substr(realpath($this->server['SCRIPT_FILENAME']), \strlen($serverRoot)));
798
+            $name = '/' . ltrim($overwriteWebRoot . $suburi, '/');
799
+        }
800
+        return $name;
801
+    }
802
+
803
+    /**
804
+     * Checks whether the user agent matches a given regex
805
+     * @param array $agent array of agent names
806
+     * @return bool true if at least one of the given agent matches, false otherwise
807
+     */
808
+    public function isUserAgent(array $agent): bool {
809
+        if (!isset($this->server['HTTP_USER_AGENT'])) {
810
+            return false;
811
+        }
812
+        foreach ($agent as $regex) {
813
+            if (preg_match($regex, $this->server['HTTP_USER_AGENT'])) {
814
+                return true;
815
+            }
816
+        }
817
+        return false;
818
+    }
819
+
820
+    /**
821
+     * Returns the unverified server host from the headers without checking
822
+     * whether it is a trusted domain
823
+     * @return string Server host
824
+     */
825
+    public function getInsecureServerHost(): string {
826
+        $host = 'localhost';
827
+        if (isset($this->server['HTTP_X_FORWARDED_HOST'])) {
828
+            if (strpos($this->server['HTTP_X_FORWARDED_HOST'], ',') !== false) {
829
+                $parts = explode(',', $this->server['HTTP_X_FORWARDED_HOST']);
830
+                $host = trim(current($parts));
831
+            } else {
832
+                $host = $this->server['HTTP_X_FORWARDED_HOST'];
833
+            }
834
+        } else {
835
+            if (isset($this->server['HTTP_HOST'])) {
836
+                $host = $this->server['HTTP_HOST'];
837
+            } else if (isset($this->server['SERVER_NAME'])) {
838
+                $host = $this->server['SERVER_NAME'];
839
+            }
840
+        }
841
+        return $host;
842
+    }
843
+
844
+
845
+    /**
846
+     * Returns the server host from the headers, or the first configured
847
+     * trusted domain if the host isn't in the trusted list
848
+     * @return string Server host
849
+     */
850
+    public function getServerHost(): string {
851
+        // overwritehost is always trusted
852
+        $host = $this->getOverwriteHost();
853
+        if ($host !== null) {
854
+            return $host;
855
+        }
856
+
857
+        // get the host from the headers
858
+        $host = $this->getInsecureServerHost();
859
+
860
+        // Verify that the host is a trusted domain if the trusted domains
861
+        // are defined
862
+        // If no trusted domain is provided the first trusted domain is returned
863
+        $trustedDomainHelper = new TrustedDomainHelper($this->config);
864
+        if ($trustedDomainHelper->isTrustedDomain($host)) {
865
+            return $host;
866
+        } else {
867
+            $trustedList = $this->config->getSystemValue('trusted_domains', []);
868
+            if(!empty($trustedList)) {
869
+                return $trustedList[0];
870
+            } else {
871
+                return '';
872
+            }
873
+        }
874
+    }
875
+
876
+    /**
877
+     * Returns the overwritehost setting from the config if set and
878
+     * if the overwrite condition is met
879
+     * @return string|null overwritehost value or null if not defined or the defined condition
880
+     * isn't met
881
+     */
882
+    private function getOverwriteHost() {
883
+        if($this->config->getSystemValue('overwritehost') !== '' && $this->isOverwriteCondition()) {
884
+            return $this->config->getSystemValue('overwritehost');
885
+        }
886
+        return null;
887
+    }
888 888
 
889 889
 }
Please login to merge, or discard this patch.
Spacing   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -132,7 +132,7 @@  discard block
 block discarded – undo
132 132
 	 * @param string $stream
133 133
 	 * @see http://www.php.net/manual/en/reserved.variables.php
134 134
 	 */
135
-	public function __construct(array $vars= [],
135
+	public function __construct(array $vars = [],
136 136
 								ISecureRandom $secureRandom = null,
137 137
 								IConfig $config,
138 138
 								CsrfTokenManager $csrfTokenManager = null,
@@ -143,11 +143,11 @@  discard block
 block discarded – undo
143 143
 		$this->config = $config;
144 144
 		$this->csrfTokenManager = $csrfTokenManager;
145 145
 
146
-		if(!array_key_exists('method', $vars)) {
146
+		if (!array_key_exists('method', $vars)) {
147 147
 			$vars['method'] = 'GET';
148 148
 		}
149 149
 
150
-		foreach($this->allowedKeys as $name) {
150
+		foreach ($this->allowedKeys as $name) {
151 151
 			$this->items[$name] = isset($vars[$name])
152 152
 				? $vars[$name]
153 153
 				: [];
@@ -257,12 +257,12 @@  discard block
 block discarded – undo
257 257
 	* @return mixed|null
258 258
 	*/
259 259
 	public function __get($name) {
260
-		switch($name) {
260
+		switch ($name) {
261 261
 			case 'put':
262 262
 			case 'patch':
263 263
 			case 'get':
264 264
 			case 'post':
265
-				if($this->method !== strtoupper($name)) {
265
+				if ($this->method !== strtoupper($name)) {
266 266
 					throw new \LogicException(sprintf('%s cannot be accessed in a %s request.', $name, $this->method));
267 267
 				}
268 268
 				return $this->getContent();
@@ -313,9 +313,9 @@  discard block
 block discarded – undo
313 313
 	 */
314 314
 	public function getHeader(string $name): string {
315 315
 
316
-		$name = strtoupper(str_replace('-', '_',$name));
317
-		if (isset($this->server['HTTP_' . $name])) {
318
-			return $this->server['HTTP_' . $name];
316
+		$name = strtoupper(str_replace('-', '_', $name));
317
+		if (isset($this->server['HTTP_'.$name])) {
318
+			return $this->server['HTTP_'.$name];
319 319
 		}
320 320
 
321 321
 		// There's a few headers that seem to end up in the top-level
@@ -445,21 +445,21 @@  discard block
 block discarded – undo
445 445
 		// 'application/json' must be decoded manually.
446 446
 		if (strpos($this->getHeader('Content-Type'), 'application/json') !== false) {
447 447
 			$params = json_decode(file_get_contents($this->inputStream), true);
448
-			if($params !== null && \count($params) > 0) {
448
+			if ($params !== null && \count($params) > 0) {
449 449
 				$this->items['params'] = $params;
450
-				if($this->method === 'POST') {
450
+				if ($this->method === 'POST') {
451 451
 					$this->items['post'] = $params;
452 452
 				}
453 453
 			}
454 454
 
455 455
 		// Handle application/x-www-form-urlencoded for methods other than GET
456 456
 		// or post correctly
457
-		} elseif($this->method !== 'GET'
457
+		} elseif ($this->method !== 'GET'
458 458
 				&& $this->method !== 'POST'
459 459
 				&& strpos($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded') !== false) {
460 460
 
461 461
 			parse_str(file_get_contents($this->inputStream), $params);
462
-			if(\is_array($params)) {
462
+			if (\is_array($params)) {
463 463
 				$this->items['params'] = $params;
464 464
 			}
465 465
 		}
@@ -476,11 +476,11 @@  discard block
 block discarded – undo
476 476
 	 * @return bool true if CSRF check passed
477 477
 	 */
478 478
 	public function passesCSRFCheck(): bool {
479
-		if($this->csrfTokenManager === null) {
479
+		if ($this->csrfTokenManager === null) {
480 480
 			return false;
481 481
 		}
482 482
 
483
-		if(!$this->passesStrictCookieCheck()) {
483
+		if (!$this->passesStrictCookieCheck()) {
484 484
 			return false;
485 485
 		}
486 486
 
@@ -508,7 +508,7 @@  discard block
 block discarded – undo
508 508
 		if ($this->getHeader('OCS-APIREQUEST')) {
509 509
 			return false;
510 510
 		}
511
-		if($this->getCookie(session_name()) === null && $this->getCookie('nc_token') === null) {
511
+		if ($this->getCookie(session_name()) === null && $this->getCookie('nc_token') === null) {
512 512
 			return false;
513 513
 		}
514 514
 
@@ -533,7 +533,7 @@  discard block
 block discarded – undo
533 533
 	protected function getProtectedCookieName(string $name): string {
534 534
 		$cookieParams = $this->getCookieParams();
535 535
 		$prefix = '';
536
-		if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
536
+		if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
537 537
 			$prefix = '__Host-';
538 538
 		}
539 539
 
@@ -548,12 +548,12 @@  discard block
 block discarded – undo
548 548
 	 * @since 9.1.0
549 549
 	 */
550 550
 	public function passesStrictCookieCheck(): bool {
551
-		if(!$this->cookieCheckRequired()) {
551
+		if (!$this->cookieCheckRequired()) {
552 552
 			return true;
553 553
 		}
554 554
 
555 555
 		$cookieName = $this->getProtectedCookieName('nc_sameSiteCookiestrict');
556
-		if($this->getCookie($cookieName) === 'true'
556
+		if ($this->getCookie($cookieName) === 'true'
557 557
 			&& $this->passesLaxCookieCheck()) {
558 558
 			return true;
559 559
 		}
@@ -568,12 +568,12 @@  discard block
 block discarded – undo
568 568
 	 * @since 9.1.0
569 569
 	 */
570 570
 	public function passesLaxCookieCheck(): bool {
571
-		if(!$this->cookieCheckRequired()) {
571
+		if (!$this->cookieCheckRequired()) {
572 572
 			return true;
573 573
 		}
574 574
 
575 575
 		$cookieName = $this->getProtectedCookieName('nc_sameSiteCookielax');
576
-		if($this->getCookie($cookieName) === 'true') {
576
+		if ($this->getCookie($cookieName) === 'true') {
577 577
 			return true;
578 578
 		}
579 579
 		return false;
@@ -586,12 +586,12 @@  discard block
 block discarded – undo
586 586
 	 * @return string
587 587
 	 */
588 588
 	public function getId(): string {
589
-		if(isset($this->server['UNIQUE_ID'])) {
589
+		if (isset($this->server['UNIQUE_ID'])) {
590 590
 			return $this->server['UNIQUE_ID'];
591 591
 		}
592 592
 
593
-		if(empty($this->requestId)) {
594
-			$validChars = ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS;
593
+		if (empty($this->requestId)) {
594
+			$validChars = ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_DIGITS;
595 595
 			$this->requestId = $this->secureRandom->generate(20, $validChars);
596 596
 		}
597 597
 
@@ -609,15 +609,15 @@  discard block
 block discarded – undo
609 609
 		$remoteAddress = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
610 610
 		$trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
611 611
 
612
-		if(\is_array($trustedProxies) && \in_array($remoteAddress, $trustedProxies)) {
612
+		if (\is_array($trustedProxies) && \in_array($remoteAddress, $trustedProxies)) {
613 613
 			$forwardedForHeaders = $this->config->getSystemValue('forwarded_for_headers', [
614 614
 				'HTTP_X_FORWARDED_FOR'
615 615
 				// only have one default, so we cannot ship an insecure product out of the box
616 616
 			]);
617 617
 
618
-			foreach($forwardedForHeaders as $header) {
619
-				if(isset($this->server[$header])) {
620
-					foreach(explode(',', $this->server[$header]) as $IP) {
618
+			foreach ($forwardedForHeaders as $header) {
619
+				if (isset($this->server[$header])) {
620
+					foreach (explode(',', $this->server[$header]) as $IP) {
621 621
 						$IP = trim($IP);
622 622
 						if (filter_var($IP, FILTER_VALIDATE_IP) !== false) {
623 623
 							return $IP;
@@ -636,7 +636,7 @@  discard block
 block discarded – undo
636 636
 	 * @return bool
637 637
 	 */
638 638
 	private function isOverwriteCondition(string $type = ''): bool {
639
-		$regex = '/' . $this->config->getSystemValue('overwritecondaddr', '')  . '/';
639
+		$regex = '/'.$this->config->getSystemValue('overwritecondaddr', '').'/';
640 640
 		$remoteAddr = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
641 641
 		return $regex === '//' || preg_match($regex, $remoteAddr) === 1
642 642
 		|| $type !== 'protocol';
@@ -648,7 +648,7 @@  discard block
 block discarded – undo
648 648
 	 * @return string Server protocol (http or https)
649 649
 	 */
650 650
 	public function getServerProtocol(): string {
651
-		if($this->config->getSystemValue('overwriteprotocol') !== ''
651
+		if ($this->config->getSystemValue('overwriteprotocol') !== ''
652 652
 			&& $this->isOverwriteCondition('protocol')) {
653 653
 			return $this->config->getSystemValue('overwriteprotocol');
654 654
 		}
@@ -694,7 +694,7 @@  discard block
 block discarded – undo
694 694
 			'HTTP/2',
695 695
 		];
696 696
 
697
-		if(\in_array($claimedProtocol, $validProtocols, true)) {
697
+		if (\in_array($claimedProtocol, $validProtocols, true)) {
698 698
 			return $claimedProtocol;
699 699
 		}
700 700
 
@@ -708,8 +708,8 @@  discard block
 block discarded – undo
708 708
 	 */
709 709
 	public function getRequestUri(): string {
710 710
 		$uri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : '';
711
-		if($this->config->getSystemValue('overwritewebroot') !== '' && $this->isOverwriteCondition()) {
712
-			$uri = $this->getScriptName() . substr($uri, \strlen($this->server['SCRIPT_NAME']));
711
+		if ($this->config->getSystemValue('overwritewebroot') !== '' && $this->isOverwriteCondition()) {
712
+			$uri = $this->getScriptName().substr($uri, \strlen($this->server['SCRIPT_NAME']));
713 713
 		}
714 714
 		return $uri;
715 715
 	}
@@ -723,7 +723,7 @@  discard block
 block discarded – undo
723 723
 		$requestUri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : '';
724 724
 		// remove too many leading slashes - can be caused by reverse proxy configuration
725 725
 		if (strpos($requestUri, '/') === 0) {
726
-			$requestUri = '/' . ltrim($requestUri, '/');
726
+			$requestUri = '/'.ltrim($requestUri, '/');
727 727
 		}
728 728
 
729 729
 		$requestUri = preg_replace('%/{2,}%', '/', $requestUri);
@@ -740,7 +740,7 @@  discard block
 block discarded – undo
740 740
 		// FIXME: Sabre does not really belong here
741 741
 		list($path, $name) = \Sabre\Uri\split($scriptName);
742 742
 		if (!empty($path)) {
743
-			if($path === $pathInfo || strpos($pathInfo, $path.'/') === 0) {
743
+			if ($path === $pathInfo || strpos($pathInfo, $path.'/') === 0) {
744 744
 				$pathInfo = substr($pathInfo, \strlen($path));
745 745
 			} else {
746 746
 				throw new \Exception("The requested uri($requestUri) cannot be processed by the script '$scriptName')");
@@ -756,7 +756,7 @@  discard block
 block discarded – undo
756 756
 		if ($name !== '' && strpos($pathInfo, $name) === 0) {
757 757
 			$pathInfo = substr($pathInfo, \strlen($name));
758 758
 		}
759
-		if($pathInfo === false || $pathInfo === '/'){
759
+		if ($pathInfo === false || $pathInfo === '/') {
760 760
 			return '';
761 761
 		} else {
762 762
 			return $pathInfo;
@@ -774,7 +774,7 @@  discard block
 block discarded – undo
774 774
 		$pathInfo = rawurldecode($pathInfo);
775 775
 		$encoding = mb_detect_encoding($pathInfo, ['UTF-8', 'ISO-8859-1']);
776 776
 
777
-		switch($encoding) {
777
+		switch ($encoding) {
778 778
 			case 'ISO-8859-1' :
779 779
 				$pathInfo = utf8_encode($pathInfo);
780 780
 		}
@@ -790,12 +790,12 @@  discard block
 block discarded – undo
790 790
 	 */
791 791
 	public function getScriptName(): string {
792 792
 		$name = $this->server['SCRIPT_NAME'];
793
-		$overwriteWebRoot =  $this->config->getSystemValue('overwritewebroot');
793
+		$overwriteWebRoot = $this->config->getSystemValue('overwritewebroot');
794 794
 		if ($overwriteWebRoot !== '' && $this->isOverwriteCondition()) {
795 795
 			// FIXME: This code is untestable due to __DIR__, also that hardcoded path is really dangerous
796 796
 			$serverRoot = str_replace('\\', '/', substr(__DIR__, 0, -\strlen('lib/private/appframework/http/')));
797 797
 			$suburi = str_replace('\\', '/', substr(realpath($this->server['SCRIPT_FILENAME']), \strlen($serverRoot)));
798
-			$name = '/' . ltrim($overwriteWebRoot . $suburi, '/');
798
+			$name = '/'.ltrim($overwriteWebRoot.$suburi, '/');
799 799
 		}
800 800
 		return $name;
801 801
 	}
@@ -865,7 +865,7 @@  discard block
 block discarded – undo
865 865
 			return $host;
866 866
 		} else {
867 867
 			$trustedList = $this->config->getSystemValue('trusted_domains', []);
868
-			if(!empty($trustedList)) {
868
+			if (!empty($trustedList)) {
869 869
 				return $trustedList[0];
870 870
 			} else {
871 871
 				return '';
@@ -880,7 +880,7 @@  discard block
 block discarded – undo
880 880
 	 * isn't met
881 881
 	 */
882 882
 	private function getOverwriteHost() {
883
-		if($this->config->getSystemValue('overwritehost') !== '' && $this->isOverwriteCondition()) {
883
+		if ($this->config->getSystemValue('overwritehost') !== '' && $this->isOverwriteCondition()) {
884 884
 			return $this->config->getSystemValue('overwritehost');
885 885
 		}
886 886
 		return null;
Please login to merge, or discard this patch.
settings/Controller/CheckSetupController.php 1 patch
Indentation   +552 added lines, -552 removed lines patch added patch discarded remove patch
@@ -63,293 +63,293 @@  discard block
 block discarded – undo
63 63
  * @package OC\Settings\Controller
64 64
  */
65 65
 class CheckSetupController extends Controller {
66
-	/** @var IConfig */
67
-	private $config;
68
-	/** @var IClientService */
69
-	private $clientService;
70
-	/** @var \OC_Util */
71
-	private $util;
72
-	/** @var IURLGenerator */
73
-	private $urlGenerator;
74
-	/** @var IL10N */
75
-	private $l10n;
76
-	/** @var Checker */
77
-	private $checker;
78
-	/** @var ILogger */
79
-	private $logger;
80
-	/** @var EventDispatcherInterface */
81
-	private $dispatcher;
82
-	/** @var IDBConnection|Connection */
83
-	private $db;
84
-	/** @var ILockingProvider */
85
-	private $lockingProvider;
86
-	/** @var IDateTimeFormatter */
87
-	private $dateTimeFormatter;
88
-	/** @var MemoryInfo */
89
-	private $memoryInfo;
90
-	/** @var ISecureRandom */
91
-	private $secureRandom;
92
-
93
-	public function __construct($AppName,
94
-								IRequest $request,
95
-								IConfig $config,
96
-								IClientService $clientService,
97
-								IURLGenerator $urlGenerator,
98
-								\OC_Util $util,
99
-								IL10N $l10n,
100
-								Checker $checker,
101
-								ILogger $logger,
102
-								EventDispatcherInterface $dispatcher,
103
-								IDBConnection $db,
104
-								ILockingProvider $lockingProvider,
105
-								IDateTimeFormatter $dateTimeFormatter,
106
-								MemoryInfo $memoryInfo,
107
-								ISecureRandom $secureRandom) {
108
-		parent::__construct($AppName, $request);
109
-		$this->config = $config;
110
-		$this->clientService = $clientService;
111
-		$this->util = $util;
112
-		$this->urlGenerator = $urlGenerator;
113
-		$this->l10n = $l10n;
114
-		$this->checker = $checker;
115
-		$this->logger = $logger;
116
-		$this->dispatcher = $dispatcher;
117
-		$this->db = $db;
118
-		$this->lockingProvider = $lockingProvider;
119
-		$this->dateTimeFormatter = $dateTimeFormatter;
120
-		$this->memoryInfo = $memoryInfo;
121
-		$this->secureRandom = $secureRandom;
122
-	}
123
-
124
-	/**
125
-	 * Checks if the server can connect to the internet using HTTPS and HTTP
126
-	 * @return bool
127
-	 */
128
-	private function isInternetConnectionWorking() {
129
-		if ($this->config->getSystemValue('has_internet_connection', true) === false) {
130
-			return false;
131
-		}
132
-
133
-		$siteArray = ['www.nextcloud.com',
134
-						'www.startpage.com',
135
-						'www.eff.org',
136
-						'www.edri.org',
137
-			];
138
-
139
-		foreach($siteArray as $site) {
140
-			if ($this->isSiteReachable($site)) {
141
-				return true;
142
-			}
143
-		}
144
-		return false;
145
-	}
146
-
147
-	/**
148
-	* Checks if the Nextcloud server can connect to a specific URL using both HTTPS and HTTP
149
-	* @return bool
150
-	*/
151
-	private function isSiteReachable($sitename) {
152
-		$httpSiteName = 'http://' . $sitename . '/';
153
-		$httpsSiteName = 'https://' . $sitename . '/';
154
-
155
-		try {
156
-			$client = $this->clientService->newClient();
157
-			$client->get($httpSiteName);
158
-			$client->get($httpsSiteName);
159
-		} catch (\Exception $e) {
160
-			$this->logger->logException($e, ['app' => 'internet_connection_check']);
161
-			return false;
162
-		}
163
-		return true;
164
-	}
165
-
166
-	/**
167
-	 * Checks whether a local memcache is installed or not
168
-	 * @return bool
169
-	 */
170
-	private function isMemcacheConfigured() {
171
-		return $this->config->getSystemValue('memcache.local', null) !== null;
172
-	}
173
-
174
-	/**
175
-	 * Whether PHP can generate "secure" pseudorandom integers
176
-	 *
177
-	 * @return bool
178
-	 */
179
-	private function isRandomnessSecure() {
180
-		try {
181
-			$this->secureRandom->generate(1);
182
-		} catch (\Exception $ex) {
183
-			return false;
184
-		}
185
-		return true;
186
-	}
187
-
188
-	/**
189
-	 * Public for the sake of unit-testing
190
-	 *
191
-	 * @return array
192
-	 */
193
-	protected function getCurlVersion() {
194
-		return curl_version();
195
-	}
196
-
197
-	/**
198
-	 * Check if the used  SSL lib is outdated. Older OpenSSL and NSS versions do
199
-	 * have multiple bugs which likely lead to problems in combination with
200
-	 * functionality required by ownCloud such as SNI.
201
-	 *
202
-	 * @link https://github.com/owncloud/core/issues/17446#issuecomment-122877546
203
-	 * @link https://bugzilla.redhat.com/show_bug.cgi?id=1241172
204
-	 * @return string
205
-	 */
206
-	private function isUsedTlsLibOutdated() {
207
-		// Don't run check when:
208
-		// 1. Server has `has_internet_connection` set to false
209
-		// 2. AppStore AND S2S is disabled
210
-		if(!$this->config->getSystemValue('has_internet_connection', true)) {
211
-			return '';
212
-		}
213
-		if(!$this->config->getSystemValue('appstoreenabled', true)
214
-			&& $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'no'
215
-			&& $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes') === 'no') {
216
-			return '';
217
-		}
218
-
219
-		$versionString = $this->getCurlVersion();
220
-		if(isset($versionString['ssl_version'])) {
221
-			$versionString = $versionString['ssl_version'];
222
-		} else {
223
-			return '';
224
-		}
225
-
226
-		$features = (string)$this->l10n->t('installing and updating apps via the app store or Federated Cloud Sharing');
227
-		if(!$this->config->getSystemValue('appstoreenabled', true)) {
228
-			$features = (string)$this->l10n->t('Federated Cloud Sharing');
229
-		}
230
-
231
-		// Check if at least OpenSSL after 1.01d or 1.0.2b
232
-		if(strpos($versionString, 'OpenSSL/') === 0) {
233
-			$majorVersion = substr($versionString, 8, 5);
234
-			$patchRelease = substr($versionString, 13, 6);
235
-
236
-			if(($majorVersion === '1.0.1' && ord($patchRelease) < ord('d')) ||
237
-				($majorVersion === '1.0.2' && ord($patchRelease) < ord('b'))) {
238
-				return $this->l10n->t('cURL is using an outdated %1$s version (%2$s). Please update your operating system or features such as %3$s will not work reliably.', ['OpenSSL', $versionString, $features]);
239
-			}
240
-		}
241
-
242
-		// Check if NSS and perform heuristic check
243
-		if(strpos($versionString, 'NSS/') === 0) {
244
-			try {
245
-				$firstClient = $this->clientService->newClient();
246
-				$firstClient->get('https://nextcloud.com/');
247
-
248
-				$secondClient = $this->clientService->newClient();
249
-				$secondClient->get('https://nextcloud.com/');
250
-			} catch (ClientException $e) {
251
-				if($e->getResponse()->getStatusCode() === 400) {
252
-					return $this->l10n->t('cURL is using an outdated %1$s version (%2$s). Please update your operating system or features such as %3$s will not work reliably.', ['NSS', $versionString, $features]);
253
-				}
254
-			}
255
-		}
256
-
257
-		return '';
258
-	}
259
-
260
-	/**
261
-	 * Whether the version is outdated
262
-	 *
263
-	 * @return bool
264
-	 */
265
-	protected function isPhpOutdated() {
266
-		if (version_compare(PHP_VERSION, '7.0.0', '<')) {
267
-			return true;
268
-		}
269
-
270
-		return false;
271
-	}
272
-
273
-	/**
274
-	 * Whether the php version is still supported (at time of release)
275
-	 * according to: https://secure.php.net/supported-versions.php
276
-	 *
277
-	 * @return array
278
-	 */
279
-	private function isPhpSupported() {
280
-		return ['eol' => $this->isPhpOutdated(), 'version' => PHP_VERSION];
281
-	}
282
-
283
-	/**
284
-	 * Check if the reverse proxy configuration is working as expected
285
-	 *
286
-	 * @return bool
287
-	 */
288
-	private function forwardedForHeadersWorking() {
289
-		$trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
290
-		$remoteAddress = $this->request->getHeader('REMOTE_ADDR');
291
-
292
-		if (\is_array($trustedProxies) && \in_array($remoteAddress, $trustedProxies)) {
293
-			return $remoteAddress !== $this->request->getRemoteAddress();
294
-		}
295
-		// either not enabled or working correctly
296
-		return true;
297
-	}
298
-
299
-	/**
300
-	 * Checks if the correct memcache module for PHP is installed. Only
301
-	 * fails if memcached is configured and the working module is not installed.
302
-	 *
303
-	 * @return bool
304
-	 */
305
-	private function isCorrectMemcachedPHPModuleInstalled() {
306
-		if ($this->config->getSystemValue('memcache.distributed', null) !== '\OC\Memcache\Memcached') {
307
-			return true;
308
-		}
309
-
310
-		// there are two different memcached modules for PHP
311
-		// we only support memcached and not memcache
312
-		// https://code.google.com/p/memcached/wiki/PHPClientComparison
313
-		return !(!extension_loaded('memcached') && extension_loaded('memcache'));
314
-	}
315
-
316
-	/**
317
-	 * Checks if set_time_limit is not disabled.
318
-	 *
319
-	 * @return bool
320
-	 */
321
-	private function isSettimelimitAvailable() {
322
-		if (function_exists('set_time_limit')
323
-			&& strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
324
-			return true;
325
-		}
326
-
327
-		return false;
328
-	}
329
-
330
-	/**
331
-	 * @return RedirectResponse
332
-	 */
333
-	public function rescanFailedIntegrityCheck() {
334
-		$this->checker->runInstanceVerification();
335
-		return new RedirectResponse(
336
-			$this->urlGenerator->linkToRoute('settings.AdminSettings.index')
337
-		);
338
-	}
339
-
340
-	/**
341
-	 * @NoCSRFRequired
342
-	 * @return DataResponse
343
-	 */
344
-	public function getFailedIntegrityCheckFiles() {
345
-		if(!$this->checker->isCodeCheckEnforced()) {
346
-			return new DataDisplayResponse('Integrity checker has been disabled. Integrity cannot be verified.');
347
-		}
348
-
349
-		$completeResults = $this->checker->getResults();
350
-
351
-		if(!empty($completeResults)) {
352
-			$formattedTextResponse = 'Technical information
66
+    /** @var IConfig */
67
+    private $config;
68
+    /** @var IClientService */
69
+    private $clientService;
70
+    /** @var \OC_Util */
71
+    private $util;
72
+    /** @var IURLGenerator */
73
+    private $urlGenerator;
74
+    /** @var IL10N */
75
+    private $l10n;
76
+    /** @var Checker */
77
+    private $checker;
78
+    /** @var ILogger */
79
+    private $logger;
80
+    /** @var EventDispatcherInterface */
81
+    private $dispatcher;
82
+    /** @var IDBConnection|Connection */
83
+    private $db;
84
+    /** @var ILockingProvider */
85
+    private $lockingProvider;
86
+    /** @var IDateTimeFormatter */
87
+    private $dateTimeFormatter;
88
+    /** @var MemoryInfo */
89
+    private $memoryInfo;
90
+    /** @var ISecureRandom */
91
+    private $secureRandom;
92
+
93
+    public function __construct($AppName,
94
+                                IRequest $request,
95
+                                IConfig $config,
96
+                                IClientService $clientService,
97
+                                IURLGenerator $urlGenerator,
98
+                                \OC_Util $util,
99
+                                IL10N $l10n,
100
+                                Checker $checker,
101
+                                ILogger $logger,
102
+                                EventDispatcherInterface $dispatcher,
103
+                                IDBConnection $db,
104
+                                ILockingProvider $lockingProvider,
105
+                                IDateTimeFormatter $dateTimeFormatter,
106
+                                MemoryInfo $memoryInfo,
107
+                                ISecureRandom $secureRandom) {
108
+        parent::__construct($AppName, $request);
109
+        $this->config = $config;
110
+        $this->clientService = $clientService;
111
+        $this->util = $util;
112
+        $this->urlGenerator = $urlGenerator;
113
+        $this->l10n = $l10n;
114
+        $this->checker = $checker;
115
+        $this->logger = $logger;
116
+        $this->dispatcher = $dispatcher;
117
+        $this->db = $db;
118
+        $this->lockingProvider = $lockingProvider;
119
+        $this->dateTimeFormatter = $dateTimeFormatter;
120
+        $this->memoryInfo = $memoryInfo;
121
+        $this->secureRandom = $secureRandom;
122
+    }
123
+
124
+    /**
125
+     * Checks if the server can connect to the internet using HTTPS and HTTP
126
+     * @return bool
127
+     */
128
+    private function isInternetConnectionWorking() {
129
+        if ($this->config->getSystemValue('has_internet_connection', true) === false) {
130
+            return false;
131
+        }
132
+
133
+        $siteArray = ['www.nextcloud.com',
134
+                        'www.startpage.com',
135
+                        'www.eff.org',
136
+                        'www.edri.org',
137
+            ];
138
+
139
+        foreach($siteArray as $site) {
140
+            if ($this->isSiteReachable($site)) {
141
+                return true;
142
+            }
143
+        }
144
+        return false;
145
+    }
146
+
147
+    /**
148
+     * Checks if the Nextcloud server can connect to a specific URL using both HTTPS and HTTP
149
+     * @return bool
150
+     */
151
+    private function isSiteReachable($sitename) {
152
+        $httpSiteName = 'http://' . $sitename . '/';
153
+        $httpsSiteName = 'https://' . $sitename . '/';
154
+
155
+        try {
156
+            $client = $this->clientService->newClient();
157
+            $client->get($httpSiteName);
158
+            $client->get($httpsSiteName);
159
+        } catch (\Exception $e) {
160
+            $this->logger->logException($e, ['app' => 'internet_connection_check']);
161
+            return false;
162
+        }
163
+        return true;
164
+    }
165
+
166
+    /**
167
+     * Checks whether a local memcache is installed or not
168
+     * @return bool
169
+     */
170
+    private function isMemcacheConfigured() {
171
+        return $this->config->getSystemValue('memcache.local', null) !== null;
172
+    }
173
+
174
+    /**
175
+     * Whether PHP can generate "secure" pseudorandom integers
176
+     *
177
+     * @return bool
178
+     */
179
+    private function isRandomnessSecure() {
180
+        try {
181
+            $this->secureRandom->generate(1);
182
+        } catch (\Exception $ex) {
183
+            return false;
184
+        }
185
+        return true;
186
+    }
187
+
188
+    /**
189
+     * Public for the sake of unit-testing
190
+     *
191
+     * @return array
192
+     */
193
+    protected function getCurlVersion() {
194
+        return curl_version();
195
+    }
196
+
197
+    /**
198
+     * Check if the used  SSL lib is outdated. Older OpenSSL and NSS versions do
199
+     * have multiple bugs which likely lead to problems in combination with
200
+     * functionality required by ownCloud such as SNI.
201
+     *
202
+     * @link https://github.com/owncloud/core/issues/17446#issuecomment-122877546
203
+     * @link https://bugzilla.redhat.com/show_bug.cgi?id=1241172
204
+     * @return string
205
+     */
206
+    private function isUsedTlsLibOutdated() {
207
+        // Don't run check when:
208
+        // 1. Server has `has_internet_connection` set to false
209
+        // 2. AppStore AND S2S is disabled
210
+        if(!$this->config->getSystemValue('has_internet_connection', true)) {
211
+            return '';
212
+        }
213
+        if(!$this->config->getSystemValue('appstoreenabled', true)
214
+            && $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'no'
215
+            && $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes') === 'no') {
216
+            return '';
217
+        }
218
+
219
+        $versionString = $this->getCurlVersion();
220
+        if(isset($versionString['ssl_version'])) {
221
+            $versionString = $versionString['ssl_version'];
222
+        } else {
223
+            return '';
224
+        }
225
+
226
+        $features = (string)$this->l10n->t('installing and updating apps via the app store or Federated Cloud Sharing');
227
+        if(!$this->config->getSystemValue('appstoreenabled', true)) {
228
+            $features = (string)$this->l10n->t('Federated Cloud Sharing');
229
+        }
230
+
231
+        // Check if at least OpenSSL after 1.01d or 1.0.2b
232
+        if(strpos($versionString, 'OpenSSL/') === 0) {
233
+            $majorVersion = substr($versionString, 8, 5);
234
+            $patchRelease = substr($versionString, 13, 6);
235
+
236
+            if(($majorVersion === '1.0.1' && ord($patchRelease) < ord('d')) ||
237
+                ($majorVersion === '1.0.2' && ord($patchRelease) < ord('b'))) {
238
+                return $this->l10n->t('cURL is using an outdated %1$s version (%2$s). Please update your operating system or features such as %3$s will not work reliably.', ['OpenSSL', $versionString, $features]);
239
+            }
240
+        }
241
+
242
+        // Check if NSS and perform heuristic check
243
+        if(strpos($versionString, 'NSS/') === 0) {
244
+            try {
245
+                $firstClient = $this->clientService->newClient();
246
+                $firstClient->get('https://nextcloud.com/');
247
+
248
+                $secondClient = $this->clientService->newClient();
249
+                $secondClient->get('https://nextcloud.com/');
250
+            } catch (ClientException $e) {
251
+                if($e->getResponse()->getStatusCode() === 400) {
252
+                    return $this->l10n->t('cURL is using an outdated %1$s version (%2$s). Please update your operating system or features such as %3$s will not work reliably.', ['NSS', $versionString, $features]);
253
+                }
254
+            }
255
+        }
256
+
257
+        return '';
258
+    }
259
+
260
+    /**
261
+     * Whether the version is outdated
262
+     *
263
+     * @return bool
264
+     */
265
+    protected function isPhpOutdated() {
266
+        if (version_compare(PHP_VERSION, '7.0.0', '<')) {
267
+            return true;
268
+        }
269
+
270
+        return false;
271
+    }
272
+
273
+    /**
274
+     * Whether the php version is still supported (at time of release)
275
+     * according to: https://secure.php.net/supported-versions.php
276
+     *
277
+     * @return array
278
+     */
279
+    private function isPhpSupported() {
280
+        return ['eol' => $this->isPhpOutdated(), 'version' => PHP_VERSION];
281
+    }
282
+
283
+    /**
284
+     * Check if the reverse proxy configuration is working as expected
285
+     *
286
+     * @return bool
287
+     */
288
+    private function forwardedForHeadersWorking() {
289
+        $trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
290
+        $remoteAddress = $this->request->getHeader('REMOTE_ADDR');
291
+
292
+        if (\is_array($trustedProxies) && \in_array($remoteAddress, $trustedProxies)) {
293
+            return $remoteAddress !== $this->request->getRemoteAddress();
294
+        }
295
+        // either not enabled or working correctly
296
+        return true;
297
+    }
298
+
299
+    /**
300
+     * Checks if the correct memcache module for PHP is installed. Only
301
+     * fails if memcached is configured and the working module is not installed.
302
+     *
303
+     * @return bool
304
+     */
305
+    private function isCorrectMemcachedPHPModuleInstalled() {
306
+        if ($this->config->getSystemValue('memcache.distributed', null) !== '\OC\Memcache\Memcached') {
307
+            return true;
308
+        }
309
+
310
+        // there are two different memcached modules for PHP
311
+        // we only support memcached and not memcache
312
+        // https://code.google.com/p/memcached/wiki/PHPClientComparison
313
+        return !(!extension_loaded('memcached') && extension_loaded('memcache'));
314
+    }
315
+
316
+    /**
317
+     * Checks if set_time_limit is not disabled.
318
+     *
319
+     * @return bool
320
+     */
321
+    private function isSettimelimitAvailable() {
322
+        if (function_exists('set_time_limit')
323
+            && strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
324
+            return true;
325
+        }
326
+
327
+        return false;
328
+    }
329
+
330
+    /**
331
+     * @return RedirectResponse
332
+     */
333
+    public function rescanFailedIntegrityCheck() {
334
+        $this->checker->runInstanceVerification();
335
+        return new RedirectResponse(
336
+            $this->urlGenerator->linkToRoute('settings.AdminSettings.index')
337
+        );
338
+    }
339
+
340
+    /**
341
+     * @NoCSRFRequired
342
+     * @return DataResponse
343
+     */
344
+    public function getFailedIntegrityCheckFiles() {
345
+        if(!$this->checker->isCodeCheckEnforced()) {
346
+            return new DataDisplayResponse('Integrity checker has been disabled. Integrity cannot be verified.');
347
+        }
348
+
349
+        $completeResults = $this->checker->getResults();
350
+
351
+        if(!empty($completeResults)) {
352
+            $formattedTextResponse = 'Technical information
353 353
 =====================
354 354
 The following list covers which files have failed the integrity check. Please read
355 355
 the previous linked documentation to learn more about the errors and how to fix
@@ -358,272 +358,272 @@  discard block
 block discarded – undo
358 358
 Results
359 359
 =======
360 360
 ';
361
-			foreach($completeResults as $context => $contextResult) {
362
-				$formattedTextResponse .= "- $context\n";
363
-
364
-				foreach($contextResult as $category => $result) {
365
-					$formattedTextResponse .= "\t- $category\n";
366
-					if($category !== 'EXCEPTION') {
367
-						foreach ($result as $key => $results) {
368
-							$formattedTextResponse .= "\t\t- $key\n";
369
-						}
370
-					} else {
371
-						foreach ($result as $key => $results) {
372
-							$formattedTextResponse .= "\t\t- $results\n";
373
-						}
374
-					}
375
-
376
-				}
377
-			}
378
-
379
-			$formattedTextResponse .= '
361
+            foreach($completeResults as $context => $contextResult) {
362
+                $formattedTextResponse .= "- $context\n";
363
+
364
+                foreach($contextResult as $category => $result) {
365
+                    $formattedTextResponse .= "\t- $category\n";
366
+                    if($category !== 'EXCEPTION') {
367
+                        foreach ($result as $key => $results) {
368
+                            $formattedTextResponse .= "\t\t- $key\n";
369
+                        }
370
+                    } else {
371
+                        foreach ($result as $key => $results) {
372
+                            $formattedTextResponse .= "\t\t- $results\n";
373
+                        }
374
+                    }
375
+
376
+                }
377
+            }
378
+
379
+            $formattedTextResponse .= '
380 380
 Raw output
381 381
 ==========
382 382
 ';
383
-			$formattedTextResponse .= print_r($completeResults, true);
384
-		} else {
385
-			$formattedTextResponse = 'No errors have been found.';
386
-		}
387
-
388
-
389
-		$response = new DataDisplayResponse(
390
-			$formattedTextResponse,
391
-			Http::STATUS_OK,
392
-			[
393
-				'Content-Type' => 'text/plain',
394
-			]
395
-		);
396
-
397
-		return $response;
398
-	}
399
-
400
-	/**
401
-	 * Checks whether a PHP opcache is properly set up
402
-	 * @return bool
403
-	 */
404
-	protected function isOpcacheProperlySetup() {
405
-		$iniWrapper = new IniGetWrapper();
406
-
407
-		if(!$iniWrapper->getBool('opcache.enable')) {
408
-			return false;
409
-		}
410
-
411
-		if(!$iniWrapper->getBool('opcache.save_comments')) {
412
-			return false;
413
-		}
414
-
415
-		if(!$iniWrapper->getBool('opcache.enable_cli')) {
416
-			return false;
417
-		}
418
-
419
-		if($iniWrapper->getNumeric('opcache.max_accelerated_files') < 10000) {
420
-			return false;
421
-		}
422
-
423
-		if($iniWrapper->getNumeric('opcache.memory_consumption') < 128) {
424
-			return false;
425
-		}
426
-
427
-		if($iniWrapper->getNumeric('opcache.interned_strings_buffer') < 8) {
428
-			return false;
429
-		}
430
-
431
-		return true;
432
-	}
433
-
434
-	/**
435
-	 * Check if the required FreeType functions are present
436
-	 * @return bool
437
-	 */
438
-	protected function hasFreeTypeSupport() {
439
-		return function_exists('imagettfbbox') && function_exists('imagettftext');
440
-	}
441
-
442
-	protected function hasMissingIndexes(): array {
443
-		$indexInfo = new MissingIndexInformation();
444
-		// Dispatch event so apps can also hint for pending index updates if needed
445
-		$event = new GenericEvent($indexInfo);
446
-		$this->dispatcher->dispatch(IDBConnection::CHECK_MISSING_INDEXES_EVENT, $event);
447
-
448
-		return $indexInfo->getListOfMissingIndexes();
449
-	}
450
-
451
-	/**
452
-	 * warn if outdated version of a memcache module is used
453
-	 */
454
-	protected function getOutdatedCaches(): array {
455
-		$caches = [
456
-			'apcu'	=> ['name' => 'APCu', 'version' => '4.0.6'],
457
-			'redis'	=> ['name' => 'Redis', 'version' => '2.2.5'],
458
-		];
459
-		$outdatedCaches = [];
460
-		foreach ($caches as $php_module => $data) {
461
-			$isOutdated = extension_loaded($php_module) && version_compare(phpversion($php_module), $data['version'], '<');
462
-			if ($isOutdated) {
463
-				$outdatedCaches[] = $data;
464
-			}
465
-		}
466
-
467
-		return $outdatedCaches;
468
-	}
469
-
470
-	protected function isSqliteUsed() {
471
-		return strpos($this->config->getSystemValue('dbtype'), 'sqlite') !== false;
472
-	}
473
-
474
-	protected function isReadOnlyConfig(): bool {
475
-		return \OC_Helper::isReadOnlyConfigEnabled();
476
-	}
477
-
478
-	protected function hasValidTransactionIsolationLevel(): bool {
479
-		try {
480
-			if ($this->db->getDatabasePlatform() instanceof SqlitePlatform) {
481
-				return true;
482
-			}
483
-
484
-			return $this->db->getTransactionIsolation() === Connection::TRANSACTION_READ_COMMITTED;
485
-		} catch (DBALException $e) {
486
-			// ignore
487
-		}
488
-
489
-		return true;
490
-	}
491
-
492
-	protected function hasFileinfoInstalled(): bool {
493
-		return \OC_Util::fileInfoLoaded();
494
-	}
495
-
496
-	protected function hasWorkingFileLocking(): bool {
497
-		return !($this->lockingProvider instanceof NoopLockingProvider);
498
-	}
499
-
500
-	protected function getSuggestedOverwriteCliURL(): string {
501
-		$suggestedOverwriteCliUrl = '';
502
-		if ($this->config->getSystemValue('overwrite.cli.url', '') === '') {
503
-			$suggestedOverwriteCliUrl = $this->request->getServerProtocol() . '://' . $this->request->getInsecureServerHost() . \OC::$WEBROOT;
504
-			if (!$this->config->getSystemValue('config_is_read_only', false)) {
505
-				// Set the overwrite URL when it was not set yet.
506
-				$this->config->setSystemValue('overwrite.cli.url', $suggestedOverwriteCliUrl);
507
-				$suggestedOverwriteCliUrl = '';
508
-			}
509
-		}
510
-		return $suggestedOverwriteCliUrl;
511
-	}
512
-
513
-	protected function getLastCronInfo(): array {
514
-		$lastCronRun = $this->config->getAppValue('core', 'lastcron', 0);
515
-		return [
516
-			'diffInSeconds' => time() - $lastCronRun,
517
-			'relativeTime' => $this->dateTimeFormatter->formatTimeSpan($lastCronRun),
518
-			'backgroundJobsUrl' => $this->urlGenerator->linkToRoute('settings.AdminSettings.index', ['section' => 'server']) . '#backgroundjobs',
519
-		];
520
-	}
521
-
522
-	protected function getCronErrors() {
523
-		$errors = json_decode($this->config->getAppValue('core', 'cronErrors', ''), true);
524
-
525
-		if (is_array($errors)) {
526
-			return $errors;
527
-		}
528
-
529
-		return [];
530
-	}
531
-
532
-	protected function isPhpMailerUsed(): bool {
533
-		return $this->config->getSystemValue('mail_smtpmode', 'php') === 'php';
534
-	}
535
-
536
-	protected function hasOpcacheLoaded(): bool {
537
-		return function_exists('opcache_get_status');
538
-	}
539
-
540
-	/**
541
-	 * Iterates through the configured app roots and
542
-	 * tests if the subdirectories are owned by the same user than the current user.
543
-	 *
544
-	 * @return array
545
-	 */
546
-	protected function getAppDirsWithDifferentOwner(): array {
547
-		$currentUser = posix_getuid();
548
-		$appDirsWithDifferentOwner = [[]];
549
-
550
-		foreach (OC::$APPSROOTS as $appRoot) {
551
-			if ($appRoot['writable'] === true) {
552
-				$appDirsWithDifferentOwner[] = $this->getAppDirsWithDifferentOwnerForAppRoot($currentUser, $appRoot);
553
-			}
554
-		}
555
-
556
-		$appDirsWithDifferentOwner = array_merge(...$appDirsWithDifferentOwner);
557
-		sort($appDirsWithDifferentOwner);
558
-
559
-		return $appDirsWithDifferentOwner;
560
-	}
561
-
562
-	/**
563
-	 * Tests if the directories for one apps directory are writable by the current user.
564
-	 *
565
-	 * @param int $currentUser The current user
566
-	 * @param array $appRoot The app root config
567
-	 * @return string[] The none writable directory paths inside the app root
568
-	 */
569
-	private function getAppDirsWithDifferentOwnerForAppRoot(int $currentUser, array $appRoot): array {
570
-		$appDirsWithDifferentOwner = [];
571
-		$appsPath = $appRoot['path'];
572
-		$appsDir = new DirectoryIterator($appRoot['path']);
573
-
574
-		foreach ($appsDir as $fileInfo) {
575
-			if ($fileInfo->isDir() && !$fileInfo->isDot()) {
576
-				$absAppPath = $appsPath . DIRECTORY_SEPARATOR . $fileInfo->getFilename();
577
-				$appDirUser = fileowner($absAppPath);
578
-				if ($appDirUser !== $currentUser) {
579
-					$appDirsWithDifferentOwner[] = $absAppPath;
580
-				}
581
-			}
582
-		}
583
-
584
-		return $appDirsWithDifferentOwner;
585
-	}
586
-
587
-	/**
588
-	 * @return DataResponse
589
-	 */
590
-	public function check() {
591
-		return new DataResponse(
592
-			[
593
-				'isGetenvServerWorking' => !empty(getenv('PATH')),
594
-				'isReadOnlyConfig' => $this->isReadOnlyConfig(),
595
-				'hasValidTransactionIsolationLevel' => $this->hasValidTransactionIsolationLevel(),
596
-				'outdatedCaches' => $this->getOutdatedCaches(),
597
-				'hasFileinfoInstalled' => $this->hasFileinfoInstalled(),
598
-				'hasWorkingFileLocking' => $this->hasWorkingFileLocking(),
599
-				'suggestedOverwriteCliURL' => $this->getSuggestedOverwriteCliURL(),
600
-				'cronInfo' => $this->getLastCronInfo(),
601
-				'cronErrors' => $this->getCronErrors(),
602
-				'serverHasInternetConnection' => $this->isInternetConnectionWorking(),
603
-				'isMemcacheConfigured' => $this->isMemcacheConfigured(),
604
-				'memcacheDocs' => $this->urlGenerator->linkToDocs('admin-performance'),
605
-				'isRandomnessSecure' => $this->isRandomnessSecure(),
606
-				'securityDocs' => $this->urlGenerator->linkToDocs('admin-security'),
607
-				'isUsedTlsLibOutdated' => $this->isUsedTlsLibOutdated(),
608
-				'phpSupported' => $this->isPhpSupported(),
609
-				'forwardedForHeadersWorking' => $this->forwardedForHeadersWorking(),
610
-				'reverseProxyDocs' => $this->urlGenerator->linkToDocs('admin-reverse-proxy'),
611
-				'isCorrectMemcachedPHPModuleInstalled' => $this->isCorrectMemcachedPHPModuleInstalled(),
612
-				'hasPassedCodeIntegrityCheck' => $this->checker->hasPassedCheck(),
613
-				'codeIntegrityCheckerDocumentation' => $this->urlGenerator->linkToDocs('admin-code-integrity'),
614
-				'isOpcacheProperlySetup' => $this->isOpcacheProperlySetup(),
615
-				'hasOpcacheLoaded' => $this->hasOpcacheLoaded(),
616
-				'phpOpcacheDocumentation' => $this->urlGenerator->linkToDocs('admin-php-opcache'),
617
-				'isSettimelimitAvailable' => $this->isSettimelimitAvailable(),
618
-				'hasFreeTypeSupport' => $this->hasFreeTypeSupport(),
619
-				'missingIndexes' => $this->hasMissingIndexes(),
620
-				'isSqliteUsed' => $this->isSqliteUsed(),
621
-				'databaseConversionDocumentation' => $this->urlGenerator->linkToDocs('admin-db-conversion'),
622
-				'isPhpMailerUsed' => $this->isPhpMailerUsed(),
623
-				'mailSettingsDocumentation' => $this->urlGenerator->getAbsoluteURL('index.php/settings/admin'),
624
-				'isMemoryLimitSufficient' => $this->memoryInfo->isMemoryLimitSufficient(),
625
-				'appDirsWithDifferentOwner' => $this->getAppDirsWithDifferentOwner(),
626
-			]
627
-		);
628
-	}
383
+            $formattedTextResponse .= print_r($completeResults, true);
384
+        } else {
385
+            $formattedTextResponse = 'No errors have been found.';
386
+        }
387
+
388
+
389
+        $response = new DataDisplayResponse(
390
+            $formattedTextResponse,
391
+            Http::STATUS_OK,
392
+            [
393
+                'Content-Type' => 'text/plain',
394
+            ]
395
+        );
396
+
397
+        return $response;
398
+    }
399
+
400
+    /**
401
+     * Checks whether a PHP opcache is properly set up
402
+     * @return bool
403
+     */
404
+    protected function isOpcacheProperlySetup() {
405
+        $iniWrapper = new IniGetWrapper();
406
+
407
+        if(!$iniWrapper->getBool('opcache.enable')) {
408
+            return false;
409
+        }
410
+
411
+        if(!$iniWrapper->getBool('opcache.save_comments')) {
412
+            return false;
413
+        }
414
+
415
+        if(!$iniWrapper->getBool('opcache.enable_cli')) {
416
+            return false;
417
+        }
418
+
419
+        if($iniWrapper->getNumeric('opcache.max_accelerated_files') < 10000) {
420
+            return false;
421
+        }
422
+
423
+        if($iniWrapper->getNumeric('opcache.memory_consumption') < 128) {
424
+            return false;
425
+        }
426
+
427
+        if($iniWrapper->getNumeric('opcache.interned_strings_buffer') < 8) {
428
+            return false;
429
+        }
430
+
431
+        return true;
432
+    }
433
+
434
+    /**
435
+     * Check if the required FreeType functions are present
436
+     * @return bool
437
+     */
438
+    protected function hasFreeTypeSupport() {
439
+        return function_exists('imagettfbbox') && function_exists('imagettftext');
440
+    }
441
+
442
+    protected function hasMissingIndexes(): array {
443
+        $indexInfo = new MissingIndexInformation();
444
+        // Dispatch event so apps can also hint for pending index updates if needed
445
+        $event = new GenericEvent($indexInfo);
446
+        $this->dispatcher->dispatch(IDBConnection::CHECK_MISSING_INDEXES_EVENT, $event);
447
+
448
+        return $indexInfo->getListOfMissingIndexes();
449
+    }
450
+
451
+    /**
452
+     * warn if outdated version of a memcache module is used
453
+     */
454
+    protected function getOutdatedCaches(): array {
455
+        $caches = [
456
+            'apcu'	=> ['name' => 'APCu', 'version' => '4.0.6'],
457
+            'redis'	=> ['name' => 'Redis', 'version' => '2.2.5'],
458
+        ];
459
+        $outdatedCaches = [];
460
+        foreach ($caches as $php_module => $data) {
461
+            $isOutdated = extension_loaded($php_module) && version_compare(phpversion($php_module), $data['version'], '<');
462
+            if ($isOutdated) {
463
+                $outdatedCaches[] = $data;
464
+            }
465
+        }
466
+
467
+        return $outdatedCaches;
468
+    }
469
+
470
+    protected function isSqliteUsed() {
471
+        return strpos($this->config->getSystemValue('dbtype'), 'sqlite') !== false;
472
+    }
473
+
474
+    protected function isReadOnlyConfig(): bool {
475
+        return \OC_Helper::isReadOnlyConfigEnabled();
476
+    }
477
+
478
+    protected function hasValidTransactionIsolationLevel(): bool {
479
+        try {
480
+            if ($this->db->getDatabasePlatform() instanceof SqlitePlatform) {
481
+                return true;
482
+            }
483
+
484
+            return $this->db->getTransactionIsolation() === Connection::TRANSACTION_READ_COMMITTED;
485
+        } catch (DBALException $e) {
486
+            // ignore
487
+        }
488
+
489
+        return true;
490
+    }
491
+
492
+    protected function hasFileinfoInstalled(): bool {
493
+        return \OC_Util::fileInfoLoaded();
494
+    }
495
+
496
+    protected function hasWorkingFileLocking(): bool {
497
+        return !($this->lockingProvider instanceof NoopLockingProvider);
498
+    }
499
+
500
+    protected function getSuggestedOverwriteCliURL(): string {
501
+        $suggestedOverwriteCliUrl = '';
502
+        if ($this->config->getSystemValue('overwrite.cli.url', '') === '') {
503
+            $suggestedOverwriteCliUrl = $this->request->getServerProtocol() . '://' . $this->request->getInsecureServerHost() . \OC::$WEBROOT;
504
+            if (!$this->config->getSystemValue('config_is_read_only', false)) {
505
+                // Set the overwrite URL when it was not set yet.
506
+                $this->config->setSystemValue('overwrite.cli.url', $suggestedOverwriteCliUrl);
507
+                $suggestedOverwriteCliUrl = '';
508
+            }
509
+        }
510
+        return $suggestedOverwriteCliUrl;
511
+    }
512
+
513
+    protected function getLastCronInfo(): array {
514
+        $lastCronRun = $this->config->getAppValue('core', 'lastcron', 0);
515
+        return [
516
+            'diffInSeconds' => time() - $lastCronRun,
517
+            'relativeTime' => $this->dateTimeFormatter->formatTimeSpan($lastCronRun),
518
+            'backgroundJobsUrl' => $this->urlGenerator->linkToRoute('settings.AdminSettings.index', ['section' => 'server']) . '#backgroundjobs',
519
+        ];
520
+    }
521
+
522
+    protected function getCronErrors() {
523
+        $errors = json_decode($this->config->getAppValue('core', 'cronErrors', ''), true);
524
+
525
+        if (is_array($errors)) {
526
+            return $errors;
527
+        }
528
+
529
+        return [];
530
+    }
531
+
532
+    protected function isPhpMailerUsed(): bool {
533
+        return $this->config->getSystemValue('mail_smtpmode', 'php') === 'php';
534
+    }
535
+
536
+    protected function hasOpcacheLoaded(): bool {
537
+        return function_exists('opcache_get_status');
538
+    }
539
+
540
+    /**
541
+     * Iterates through the configured app roots and
542
+     * tests if the subdirectories are owned by the same user than the current user.
543
+     *
544
+     * @return array
545
+     */
546
+    protected function getAppDirsWithDifferentOwner(): array {
547
+        $currentUser = posix_getuid();
548
+        $appDirsWithDifferentOwner = [[]];
549
+
550
+        foreach (OC::$APPSROOTS as $appRoot) {
551
+            if ($appRoot['writable'] === true) {
552
+                $appDirsWithDifferentOwner[] = $this->getAppDirsWithDifferentOwnerForAppRoot($currentUser, $appRoot);
553
+            }
554
+        }
555
+
556
+        $appDirsWithDifferentOwner = array_merge(...$appDirsWithDifferentOwner);
557
+        sort($appDirsWithDifferentOwner);
558
+
559
+        return $appDirsWithDifferentOwner;
560
+    }
561
+
562
+    /**
563
+     * Tests if the directories for one apps directory are writable by the current user.
564
+     *
565
+     * @param int $currentUser The current user
566
+     * @param array $appRoot The app root config
567
+     * @return string[] The none writable directory paths inside the app root
568
+     */
569
+    private function getAppDirsWithDifferentOwnerForAppRoot(int $currentUser, array $appRoot): array {
570
+        $appDirsWithDifferentOwner = [];
571
+        $appsPath = $appRoot['path'];
572
+        $appsDir = new DirectoryIterator($appRoot['path']);
573
+
574
+        foreach ($appsDir as $fileInfo) {
575
+            if ($fileInfo->isDir() && !$fileInfo->isDot()) {
576
+                $absAppPath = $appsPath . DIRECTORY_SEPARATOR . $fileInfo->getFilename();
577
+                $appDirUser = fileowner($absAppPath);
578
+                if ($appDirUser !== $currentUser) {
579
+                    $appDirsWithDifferentOwner[] = $absAppPath;
580
+                }
581
+            }
582
+        }
583
+
584
+        return $appDirsWithDifferentOwner;
585
+    }
586
+
587
+    /**
588
+     * @return DataResponse
589
+     */
590
+    public function check() {
591
+        return new DataResponse(
592
+            [
593
+                'isGetenvServerWorking' => !empty(getenv('PATH')),
594
+                'isReadOnlyConfig' => $this->isReadOnlyConfig(),
595
+                'hasValidTransactionIsolationLevel' => $this->hasValidTransactionIsolationLevel(),
596
+                'outdatedCaches' => $this->getOutdatedCaches(),
597
+                'hasFileinfoInstalled' => $this->hasFileinfoInstalled(),
598
+                'hasWorkingFileLocking' => $this->hasWorkingFileLocking(),
599
+                'suggestedOverwriteCliURL' => $this->getSuggestedOverwriteCliURL(),
600
+                'cronInfo' => $this->getLastCronInfo(),
601
+                'cronErrors' => $this->getCronErrors(),
602
+                'serverHasInternetConnection' => $this->isInternetConnectionWorking(),
603
+                'isMemcacheConfigured' => $this->isMemcacheConfigured(),
604
+                'memcacheDocs' => $this->urlGenerator->linkToDocs('admin-performance'),
605
+                'isRandomnessSecure' => $this->isRandomnessSecure(),
606
+                'securityDocs' => $this->urlGenerator->linkToDocs('admin-security'),
607
+                'isUsedTlsLibOutdated' => $this->isUsedTlsLibOutdated(),
608
+                'phpSupported' => $this->isPhpSupported(),
609
+                'forwardedForHeadersWorking' => $this->forwardedForHeadersWorking(),
610
+                'reverseProxyDocs' => $this->urlGenerator->linkToDocs('admin-reverse-proxy'),
611
+                'isCorrectMemcachedPHPModuleInstalled' => $this->isCorrectMemcachedPHPModuleInstalled(),
612
+                'hasPassedCodeIntegrityCheck' => $this->checker->hasPassedCheck(),
613
+                'codeIntegrityCheckerDocumentation' => $this->urlGenerator->linkToDocs('admin-code-integrity'),
614
+                'isOpcacheProperlySetup' => $this->isOpcacheProperlySetup(),
615
+                'hasOpcacheLoaded' => $this->hasOpcacheLoaded(),
616
+                'phpOpcacheDocumentation' => $this->urlGenerator->linkToDocs('admin-php-opcache'),
617
+                'isSettimelimitAvailable' => $this->isSettimelimitAvailable(),
618
+                'hasFreeTypeSupport' => $this->hasFreeTypeSupport(),
619
+                'missingIndexes' => $this->hasMissingIndexes(),
620
+                'isSqliteUsed' => $this->isSqliteUsed(),
621
+                'databaseConversionDocumentation' => $this->urlGenerator->linkToDocs('admin-db-conversion'),
622
+                'isPhpMailerUsed' => $this->isPhpMailerUsed(),
623
+                'mailSettingsDocumentation' => $this->urlGenerator->getAbsoluteURL('index.php/settings/admin'),
624
+                'isMemoryLimitSufficient' => $this->memoryInfo->isMemoryLimitSufficient(),
625
+                'appDirsWithDifferentOwner' => $this->getAppDirsWithDifferentOwner(),
626
+            ]
627
+        );
628
+    }
629 629
 }
Please login to merge, or discard this patch.