Request.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771
  1. <?php
  2. /**
  3. * @author Bart Visscher <bartv@thisnet.nl>
  4. * @author Bernhard Posselt <dev@bernhard-posselt.com>
  5. * @author Joas Schilling <nickvergessen@owncloud.com>
  6. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  7. * @author Lukas Reschke <lukas@owncloud.com>
  8. * @author Mitar <mitar.git@tnode.com>
  9. * @author Morris Jobke <hey@morrisjobke.de>
  10. * @author Robin Appelman <icewind@owncloud.com>
  11. * @author Robin McCorkell <robin@mccorkell.me.uk>
  12. * @author Roeland Jago Douma <rullzer@owncloud.com>
  13. * @author Thomas Müller <thomas.mueller@tmit.eu>
  14. * @author Thomas Tanghus <thomas@tanghus.net>
  15. * @author Vincent Petry <pvince81@owncloud.com>
  16. *
  17. * @copyright Copyright (c) 2016, ownCloud, Inc.
  18. * @license AGPL-3.0
  19. *
  20. * This code is free software: you can redistribute it and/or modify
  21. * it under the terms of the GNU Affero General Public License, version 3,
  22. * as published by the Free Software Foundation.
  23. *
  24. * This program is distributed in the hope that it will be useful,
  25. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  26. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  27. * GNU Affero General Public License for more details.
  28. *
  29. * You should have received a copy of the GNU Affero General Public License, version 3,
  30. * along with this program. If not, see <http://www.gnu.org/licenses/>
  31. *
  32. */
  33. namespace OC\AppFramework\Http;
  34. use OC\Security\CSRF\CsrfToken;
  35. use OC\Security\CSRF\CsrfTokenManager;
  36. use OC\Security\TrustedDomainHelper;
  37. use OCP\IConfig;
  38. use OCP\IRequest;
  39. use OCP\Security\ICrypto;
  40. use OCP\Security\ISecureRandom;
  41. /**
  42. * Class for accessing variables in the request.
  43. * This class provides an immutable object with request variables.
  44. *
  45. * @property mixed[] cookies
  46. * @property mixed[] env
  47. * @property mixed[] files
  48. * @property string method
  49. * @property mixed[] parameters
  50. * @property mixed[] server
  51. */
  52. class Request implements \ArrayAccess, \Countable, IRequest {
  53. const USER_AGENT_IE = '/(MSIE)|(Trident)/';
  54. const USER_AGENT_IE_8 = '/MSIE 8.0/';
  55. // Microsoft Edge User Agent from https://msdn.microsoft.com/en-us/library/hh869301(v=vs.85).aspx
  56. 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.]+$/';
  57. // Firefox User Agent from https://developer.mozilla.org/en-US/docs/Web/HTTP/Gecko_user_agent_string_reference
  58. const USER_AGENT_FIREFOX = '/^Mozilla\/5\.0 \([^)]+\) Gecko\/[0-9.]+ Firefox\/[0-9.]+$/';
  59. // Chrome User Agent from https://developer.chrome.com/multidevice/user-agent
  60. const USER_AGENT_CHROME = '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\) Chrome\/[0-9.]+ (Mobile Safari|Safari)\/[0-9.]+$/';
  61. // Safari User Agent from http://www.useragentstring.com/pages/Safari/
  62. const USER_AGENT_SAFARI = '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\) Version\/[0-9.]+ Safari\/[0-9.A-Z]+$/';
  63. // Android Chrome user agent: https://developers.google.com/chrome/mobile/docs/user-agent
  64. const USER_AGENT_ANDROID_MOBILE_CHROME = '#Android.*Chrome/[.0-9]*#';
  65. const USER_AGENT_FREEBOX = '#^Mozilla/5\.0$#';
  66. const USER_AGENT_OWNCLOUD_IOS = '/^Mozilla\/5\.0 \(iOS\) ownCloud\-iOS.*$/';
  67. const USER_AGENT_OWNCLOUD_ANDROID = '/^Mozilla\/5\.0 \(Android\) ownCloud\-android.*$/';
  68. const USER_AGENT_OWNCLOUD_DESKTOP = '/^Mozilla\/5\.0 \([A-Za-z ]+\) (mirall|csyncoC)\/.*$/';
  69. const REGEX_LOCALHOST = '/^(127\.0\.0\.1|localhost)$/';
  70. protected $inputStream;
  71. protected $content;
  72. protected $items = array();
  73. protected $allowedKeys = array(
  74. 'get',
  75. 'post',
  76. 'files',
  77. 'server',
  78. 'env',
  79. 'cookies',
  80. 'urlParams',
  81. 'parameters',
  82. 'method',
  83. 'requesttoken',
  84. );
  85. /** @var ISecureRandom */
  86. protected $secureRandom;
  87. /** @var IConfig */
  88. protected $config;
  89. /** @var string */
  90. protected $requestId = '';
  91. /** @var ICrypto */
  92. protected $crypto;
  93. /** @var CsrfTokenManager|null */
  94. protected $csrfTokenManager;
  95. /** @var bool */
  96. protected $contentDecoded = false;
  97. /**
  98. * @param array $vars An associative array with the following optional values:
  99. * - array 'urlParams' the parameters which were matched from the URL
  100. * - array 'get' the $_GET array
  101. * - array|string 'post' the $_POST array or JSON string
  102. * - array 'files' the $_FILES array
  103. * - array 'server' the $_SERVER array
  104. * - array 'env' the $_ENV array
  105. * - array 'cookies' the $_COOKIE array
  106. * - string 'method' the request method (GET, POST etc)
  107. * - string|false 'requesttoken' the requesttoken or false when not available
  108. * @param ISecureRandom $secureRandom
  109. * @param IConfig $config
  110. * @param CsrfTokenManager|null $csrfTokenManager
  111. * @param string $stream
  112. * @see http://www.php.net/manual/en/reserved.variables.php
  113. */
  114. public function __construct(array $vars=array(),
  115. ISecureRandom $secureRandom = null,
  116. IConfig $config,
  117. CsrfTokenManager $csrfTokenManager = null,
  118. $stream = 'php://input') {
  119. $this->inputStream = $stream;
  120. $this->items['params'] = array();
  121. $this->secureRandom = $secureRandom;
  122. $this->config = $config;
  123. $this->csrfTokenManager = $csrfTokenManager;
  124. if(!array_key_exists('method', $vars)) {
  125. $vars['method'] = 'GET';
  126. }
  127. foreach($this->allowedKeys as $name) {
  128. $this->items[$name] = isset($vars[$name])
  129. ? $vars[$name]
  130. : array();
  131. }
  132. $this->items['parameters'] = array_merge(
  133. $this->items['get'],
  134. $this->items['post'],
  135. $this->items['urlParams'],
  136. $this->items['params']
  137. );
  138. }
  139. /**
  140. * @param array $parameters
  141. */
  142. public function setUrlParameters(array $parameters) {
  143. $this->items['urlParams'] = $parameters;
  144. $this->items['parameters'] = array_merge(
  145. $this->items['parameters'],
  146. $this->items['urlParams']
  147. );
  148. }
  149. /**
  150. * Countable method
  151. * @return int
  152. */
  153. public function count() {
  154. return count(array_keys($this->items['parameters']));
  155. }
  156. /**
  157. * ArrayAccess methods
  158. *
  159. * Gives access to the combined GET, POST and urlParams arrays
  160. *
  161. * Examples:
  162. *
  163. * $var = $request['myvar'];
  164. *
  165. * or
  166. *
  167. * if(!isset($request['myvar']) {
  168. * // Do something
  169. * }
  170. *
  171. * $request['myvar'] = 'something'; // This throws an exception.
  172. *
  173. * @param string $offset The key to lookup
  174. * @return boolean
  175. */
  176. public function offsetExists($offset) {
  177. return isset($this->items['parameters'][$offset]);
  178. }
  179. /**
  180. * @see offsetExists
  181. */
  182. public function offsetGet($offset) {
  183. return isset($this->items['parameters'][$offset])
  184. ? $this->items['parameters'][$offset]
  185. : null;
  186. }
  187. /**
  188. * @see offsetExists
  189. */
  190. public function offsetSet($offset, $value) {
  191. throw new \RuntimeException('You cannot change the contents of the request object');
  192. }
  193. /**
  194. * @see offsetExists
  195. */
  196. public function offsetUnset($offset) {
  197. throw new \RuntimeException('You cannot change the contents of the request object');
  198. }
  199. /**
  200. * Magic property accessors
  201. * @param string $name
  202. * @param mixed $value
  203. */
  204. public function __set($name, $value) {
  205. throw new \RuntimeException('You cannot change the contents of the request object');
  206. }
  207. /**
  208. * Access request variables by method and name.
  209. * Examples:
  210. *
  211. * $request->post['myvar']; // Only look for POST variables
  212. * $request->myvar; or $request->{'myvar'}; or $request->{$myvar}
  213. * Looks in the combined GET, POST and urlParams array.
  214. *
  215. * If you access e.g. ->post but the current HTTP request method
  216. * is GET a \LogicException will be thrown.
  217. *
  218. * @param string $name The key to look for.
  219. * @throws \LogicException
  220. * @return mixed|null
  221. */
  222. public function __get($name) {
  223. switch($name) {
  224. case 'put':
  225. case 'patch':
  226. case 'get':
  227. case 'post':
  228. if($this->method !== strtoupper($name)) {
  229. throw new \LogicException(sprintf('%s cannot be accessed in a %s request.', $name, $this->method));
  230. }
  231. return $this->getContent();
  232. case 'files':
  233. case 'server':
  234. case 'env':
  235. case 'cookies':
  236. case 'urlParams':
  237. case 'method':
  238. return isset($this->items[$name])
  239. ? $this->items[$name]
  240. : null;
  241. case 'parameters':
  242. case 'params':
  243. return $this->getContent();
  244. default;
  245. return isset($this[$name])
  246. ? $this[$name]
  247. : null;
  248. }
  249. }
  250. /**
  251. * @param string $name
  252. * @return bool
  253. */
  254. public function __isset($name) {
  255. return isset($this->items['parameters'][$name]);
  256. }
  257. /**
  258. * @param string $id
  259. */
  260. public function __unset($id) {
  261. throw new \RuntimeException('You cannot change the contents of the request object');
  262. }
  263. /**
  264. * Returns the value for a specific http header.
  265. *
  266. * This method returns null if the header did not exist.
  267. *
  268. * @param string $name
  269. * @return string
  270. */
  271. public function getHeader($name) {
  272. $name = strtoupper(str_replace(array('-'),array('_'),$name));
  273. if (isset($this->server['HTTP_' . $name])) {
  274. return $this->server['HTTP_' . $name];
  275. }
  276. // There's a few headers that seem to end up in the top-level
  277. // server array.
  278. switch($name) {
  279. case 'CONTENT_TYPE' :
  280. case 'CONTENT_LENGTH' :
  281. if (isset($this->server[$name])) {
  282. return $this->server[$name];
  283. }
  284. break;
  285. }
  286. return null;
  287. }
  288. /**
  289. * Lets you access post and get parameters by the index
  290. * In case of json requests the encoded json body is accessed
  291. *
  292. * @param string $key the key which you want to access in the URL Parameter
  293. * placeholder, $_POST or $_GET array.
  294. * The priority how they're returned is the following:
  295. * 1. URL parameters
  296. * 2. POST parameters
  297. * 3. GET parameters
  298. * @param mixed $default If the key is not found, this value will be returned
  299. * @return mixed the content of the array
  300. */
  301. public function getParam($key, $default = null) {
  302. return isset($this->parameters[$key])
  303. ? $this->parameters[$key]
  304. : $default;
  305. }
  306. /**
  307. * Returns all params that were received, be it from the request
  308. * (as GET or POST) or throuh the URL by the route
  309. * @return array the array with all parameters
  310. */
  311. public function getParams() {
  312. return $this->parameters;
  313. }
  314. /**
  315. * Returns the method of the request
  316. * @return string the method of the request (POST, GET, etc)
  317. */
  318. public function getMethod() {
  319. return $this->method;
  320. }
  321. /**
  322. * Shortcut for accessing an uploaded file through the $_FILES array
  323. * @param string $key the key that will be taken from the $_FILES array
  324. * @return array the file in the $_FILES element
  325. */
  326. public function getUploadedFile($key) {
  327. return isset($this->files[$key]) ? $this->files[$key] : null;
  328. }
  329. /**
  330. * Shortcut for getting env variables
  331. * @param string $key the key that will be taken from the $_ENV array
  332. * @return array the value in the $_ENV element
  333. */
  334. public function getEnv($key) {
  335. return isset($this->env[$key]) ? $this->env[$key] : null;
  336. }
  337. /**
  338. * Shortcut for getting cookie variables
  339. * @param string $key the key that will be taken from the $_COOKIE array
  340. * @return string the value in the $_COOKIE element
  341. */
  342. public function getCookie($key) {
  343. return isset($this->cookies[$key]) ? $this->cookies[$key] : null;
  344. }
  345. /**
  346. * Returns the request body content.
  347. *
  348. * If the HTTP request method is PUT and the body
  349. * not application/x-www-form-urlencoded or application/json a stream
  350. * resource is returned, otherwise an array.
  351. *
  352. * @return array|string|resource The request body content or a resource to read the body stream.
  353. *
  354. * @throws \LogicException
  355. */
  356. protected function getContent() {
  357. // If the content can't be parsed into an array then return a stream resource.
  358. if ($this->method === 'PUT'
  359. && strpos($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded') === false
  360. && strpos($this->getHeader('Content-Type'), 'application/json') === false
  361. ) {
  362. if ($this->content === false) {
  363. throw new \LogicException(
  364. '"put" can only be accessed once if not '
  365. . 'application/x-www-form-urlencoded or application/json.'
  366. );
  367. }
  368. $this->content = false;
  369. return fopen($this->inputStream, 'rb');
  370. } else {
  371. $this->decodeContent();
  372. return $this->items['parameters'];
  373. }
  374. }
  375. /**
  376. * Attempt to decode the content and populate parameters
  377. */
  378. protected function decodeContent() {
  379. if ($this->contentDecoded) {
  380. return;
  381. }
  382. $params = [];
  383. // 'application/json' must be decoded manually.
  384. if (strpos($this->getHeader('Content-Type'), 'application/json') !== false) {
  385. $params = json_decode(file_get_contents($this->inputStream), true);
  386. if(count($params) > 0) {
  387. $this->items['params'] = $params;
  388. if($this->method === 'POST') {
  389. $this->items['post'] = $params;
  390. }
  391. }
  392. // Handle application/x-www-form-urlencoded for methods other than GET
  393. // or post correctly
  394. } elseif($this->method !== 'GET'
  395. && $this->method !== 'POST'
  396. && strpos($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded') !== false) {
  397. parse_str(file_get_contents($this->inputStream), $params);
  398. if(is_array($params)) {
  399. $this->items['params'] = $params;
  400. }
  401. }
  402. if (is_array($params)) {
  403. $this->items['parameters'] = array_merge($this->items['parameters'], $params);
  404. }
  405. $this->contentDecoded = true;
  406. }
  407. /**
  408. * Checks if the CSRF check was correct
  409. * @return bool true if CSRF check passed
  410. */
  411. public function passesCSRFCheck() {
  412. if($this->csrfTokenManager === null) {
  413. return false;
  414. }
  415. if (isset($this->items['get']['requesttoken'])) {
  416. $token = $this->items['get']['requesttoken'];
  417. } elseif (isset($this->items['post']['requesttoken'])) {
  418. $token = $this->items['post']['requesttoken'];
  419. } elseif (isset($this->items['server']['HTTP_REQUESTTOKEN'])) {
  420. $token = $this->items['server']['HTTP_REQUESTTOKEN'];
  421. } else {
  422. //no token found.
  423. return false;
  424. }
  425. $token = new CsrfToken($token);
  426. return $this->csrfTokenManager->isTokenValid($token);
  427. }
  428. /**
  429. * Returns an ID for the request, value is not guaranteed to be unique and is mostly meant for logging
  430. * If `mod_unique_id` is installed this value will be taken.
  431. * @return string
  432. */
  433. public function getId() {
  434. if(isset($this->server['UNIQUE_ID'])) {
  435. return $this->server['UNIQUE_ID'];
  436. }
  437. if(empty($this->requestId)) {
  438. $this->requestId = $this->secureRandom->generate(20);
  439. }
  440. return $this->requestId;
  441. }
  442. /**
  443. * Returns the remote address, if the connection came from a trusted proxy
  444. * and `forwarded_for_headers` has been configured then the IP address
  445. * specified in this header will be returned instead.
  446. * Do always use this instead of $_SERVER['REMOTE_ADDR']
  447. * @return string IP address
  448. */
  449. public function getRemoteAddress() {
  450. $remoteAddress = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
  451. $trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
  452. if(is_array($trustedProxies) && in_array($remoteAddress, $trustedProxies)) {
  453. $forwardedForHeaders = $this->config->getSystemValue('forwarded_for_headers', [
  454. 'HTTP_X_FORWARDED_FOR'
  455. // only have one default, so we cannot ship an insecure product out of the box
  456. ]);
  457. foreach($forwardedForHeaders as $header) {
  458. if(isset($this->server[$header])) {
  459. foreach(explode(',', $this->server[$header]) as $IP) {
  460. $IP = trim($IP);
  461. if (filter_var($IP, FILTER_VALIDATE_IP) !== false) {
  462. return $IP;
  463. }
  464. }
  465. }
  466. }
  467. }
  468. return $remoteAddress;
  469. }
  470. /**
  471. * Check overwrite condition
  472. * @param string $type
  473. * @return bool
  474. */
  475. private function isOverwriteCondition($type = '') {
  476. $regex = '/' . $this->config->getSystemValue('overwritecondaddr', '') . '/';
  477. $remoteAddr = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
  478. return $regex === '//' || preg_match($regex, $remoteAddr) === 1
  479. || $type !== 'protocol';
  480. }
  481. /**
  482. * Returns the server protocol. It respects one or more reverse proxies servers
  483. * and load balancers
  484. * @return string Server protocol (http or https)
  485. */
  486. public function getServerProtocol() {
  487. if($this->config->getSystemValue('overwriteprotocol') !== ''
  488. && $this->isOverwriteCondition('protocol')) {
  489. return $this->config->getSystemValue('overwriteprotocol');
  490. }
  491. if (isset($this->server['HTTP_X_FORWARDED_PROTO'])) {
  492. if (strpos($this->server['HTTP_X_FORWARDED_PROTO'], ',') !== false) {
  493. $parts = explode(',', $this->server['HTTP_X_FORWARDED_PROTO']);
  494. $proto = strtolower(trim($parts[0]));
  495. } else {
  496. $proto = strtolower($this->server['HTTP_X_FORWARDED_PROTO']);
  497. }
  498. // Verify that the protocol is always HTTP or HTTPS
  499. // default to http if an invalid value is provided
  500. return $proto === 'https' ? 'https' : 'http';
  501. }
  502. if (isset($this->server['HTTPS'])
  503. && $this->server['HTTPS'] !== null
  504. && $this->server['HTTPS'] !== 'off'
  505. && $this->server['HTTPS'] !== '') {
  506. return 'https';
  507. }
  508. return 'http';
  509. }
  510. /**
  511. * Returns the used HTTP protocol.
  512. *
  513. * @return string HTTP protocol. HTTP/2, HTTP/1.1 or HTTP/1.0.
  514. */
  515. public function getHttpProtocol() {
  516. $claimedProtocol = strtoupper($this->server['SERVER_PROTOCOL']);
  517. $validProtocols = [
  518. 'HTTP/1.0',
  519. 'HTTP/1.1',
  520. 'HTTP/2',
  521. ];
  522. if(in_array($claimedProtocol, $validProtocols, true)) {
  523. return $claimedProtocol;
  524. }
  525. return 'HTTP/1.1';
  526. }
  527. /**
  528. * Returns the request uri, even if the website uses one or more
  529. * reverse proxies
  530. * @return string
  531. */
  532. public function getRequestUri() {
  533. $uri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : '';
  534. if($this->config->getSystemValue('overwritewebroot') !== '' && $this->isOverwriteCondition()) {
  535. $uri = $this->getScriptName() . substr($uri, strlen($this->server['SCRIPT_NAME']));
  536. }
  537. return $uri;
  538. }
  539. /**
  540. * Get raw PathInfo from request (not urldecoded)
  541. * @throws \Exception
  542. * @return string Path info
  543. */
  544. public function getRawPathInfo() {
  545. $requestUri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : '';
  546. // remove too many leading slashes - can be caused by reverse proxy configuration
  547. if (strpos($requestUri, '/') === 0) {
  548. $requestUri = '/' . ltrim($requestUri, '/');
  549. }
  550. $requestUri = preg_replace('%/{2,}%', '/', $requestUri);
  551. // Remove the query string from REQUEST_URI
  552. if ($pos = strpos($requestUri, '?')) {
  553. $requestUri = substr($requestUri, 0, $pos);
  554. }
  555. $scriptName = $this->server['SCRIPT_NAME'];
  556. $pathInfo = $requestUri;
  557. // strip off the script name's dir and file name
  558. // FIXME: Sabre does not really belong here
  559. list($path, $name) = \Sabre\HTTP\URLUtil::splitPath($scriptName);
  560. if (!empty($path)) {
  561. if($path === $pathInfo || strpos($pathInfo, $path.'/') === 0) {
  562. $pathInfo = substr($pathInfo, strlen($path));
  563. } else {
  564. throw new \Exception("The requested uri($requestUri) cannot be processed by the script '$scriptName')");
  565. }
  566. }
  567. if (strpos($pathInfo, '/'.$name) === 0) {
  568. $pathInfo = substr($pathInfo, strlen($name) + 1);
  569. }
  570. if (strpos($pathInfo, $name) === 0) {
  571. $pathInfo = substr($pathInfo, strlen($name));
  572. }
  573. if($pathInfo === false || $pathInfo === '/'){
  574. return '';
  575. } else {
  576. return $pathInfo;
  577. }
  578. }
  579. /**
  580. * Get PathInfo from request
  581. * @throws \Exception
  582. * @return string|false Path info or false when not found
  583. */
  584. public function getPathInfo() {
  585. if(isset($this->server['PATH_INFO'])) {
  586. return $this->server['PATH_INFO'];
  587. }
  588. $pathInfo = $this->getRawPathInfo();
  589. // following is taken from \Sabre\HTTP\URLUtil::decodePathSegment
  590. $pathInfo = rawurldecode($pathInfo);
  591. $encoding = mb_detect_encoding($pathInfo, ['UTF-8', 'ISO-8859-1']);
  592. switch($encoding) {
  593. case 'ISO-8859-1' :
  594. $pathInfo = utf8_encode($pathInfo);
  595. }
  596. // end copy
  597. return $pathInfo;
  598. }
  599. /**
  600. * Returns the script name, even if the website uses one or more
  601. * reverse proxies
  602. * @return string the script name
  603. */
  604. public function getScriptName() {
  605. $name = $this->server['SCRIPT_NAME'];
  606. $overwriteWebRoot = $this->config->getSystemValue('overwritewebroot');
  607. if ($overwriteWebRoot !== '' && $this->isOverwriteCondition()) {
  608. // FIXME: This code is untestable due to __DIR__, also that hardcoded path is really dangerous
  609. $serverRoot = str_replace('\\', '/', substr(__DIR__, 0, -strlen('lib/private/appframework/http/')));
  610. $suburi = str_replace('\\', '/', substr(realpath($this->server['SCRIPT_FILENAME']), strlen($serverRoot)));
  611. $name = '/' . ltrim($overwriteWebRoot . $suburi, '/');
  612. }
  613. return $name;
  614. }
  615. /**
  616. * Checks whether the user agent matches a given regex
  617. * @param array $agent array of agent names
  618. * @return bool true if at least one of the given agent matches, false otherwise
  619. */
  620. public function isUserAgent(array $agent) {
  621. if (!isset($this->server['HTTP_USER_AGENT'])) {
  622. return false;
  623. }
  624. foreach ($agent as $regex) {
  625. if (preg_match($regex, $this->server['HTTP_USER_AGENT'])) {
  626. return true;
  627. }
  628. }
  629. return false;
  630. }
  631. /**
  632. * Returns the unverified server host from the headers without checking
  633. * whether it is a trusted domain
  634. * @return string Server host
  635. */
  636. public function getInsecureServerHost() {
  637. $host = 'localhost';
  638. if (isset($this->server['HTTP_X_FORWARDED_HOST'])) {
  639. if (strpos($this->server['HTTP_X_FORWARDED_HOST'], ',') !== false) {
  640. $parts = explode(',', $this->server['HTTP_X_FORWARDED_HOST']);
  641. $host = trim(current($parts));
  642. } else {
  643. $host = $this->server['HTTP_X_FORWARDED_HOST'];
  644. }
  645. } else {
  646. if (isset($this->server['HTTP_HOST'])) {
  647. $host = $this->server['HTTP_HOST'];
  648. } else if (isset($this->server['SERVER_NAME'])) {
  649. $host = $this->server['SERVER_NAME'];
  650. }
  651. }
  652. return $host;
  653. }
  654. /**
  655. * Returns the server host from the headers, or the first configured
  656. * trusted domain if the host isn't in the trusted list
  657. * @return string Server host
  658. */
  659. public function getServerHost() {
  660. // overwritehost is always trusted
  661. $host = $this->getOverwriteHost();
  662. if ($host !== null) {
  663. return $host;
  664. }
  665. // get the host from the headers
  666. $host = $this->getInsecureServerHost();
  667. // Verify that the host is a trusted domain if the trusted domains
  668. // are defined
  669. // If no trusted domain is provided the first trusted domain is returned
  670. $trustedDomainHelper = new TrustedDomainHelper($this->config);
  671. if ($trustedDomainHelper->isTrustedDomain($host)) {
  672. return $host;
  673. } else {
  674. $trustedList = $this->config->getSystemValue('trusted_domains', []);
  675. if(!empty($trustedList)) {
  676. return $trustedList[0];
  677. } else {
  678. return '';
  679. }
  680. }
  681. }
  682. /**
  683. * Returns the overwritehost setting from the config if set and
  684. * if the overwrite condition is met
  685. * @return string|null overwritehost value or null if not defined or the defined condition
  686. * isn't met
  687. */
  688. private function getOverwriteHost() {
  689. if($this->config->getSystemValue('overwritehost') !== '' && $this->isOverwriteCondition()) {
  690. return $this->config->getSystemValue('overwritehost');
  691. }
  692. return null;
  693. }
  694. }