You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

833 lines
24 KiB

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