Request.php 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 2.0.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Network;
  16. use Cake\Core\Configure;
  17. use Cake\Error;
  18. use Cake\Network\Session;
  19. use Cake\Utility\Hash;
  20. /**
  21. * A class that helps wrap Request information and particulars about a single request.
  22. * Provides methods commonly used to introspect on the request headers and request body.
  23. *
  24. * Has both an Array and Object interface. You can access framework parameters using indexes:
  25. *
  26. * `$request['controller']` or `$request->controller`.
  27. */
  28. class Request implements \ArrayAccess {
  29. /**
  30. * Array of parameters parsed from the URL.
  31. *
  32. * @var array
  33. */
  34. public $params = array(
  35. 'plugin' => null,
  36. 'controller' => null,
  37. 'action' => null,
  38. '_ext' => null,
  39. 'pass' => []
  40. );
  41. /**
  42. * Array of POST data. Will contain form data as well as uploaded files.
  43. * In PUT/PATCH/DELETE requests this property will contain the form-urlencoded
  44. * data.
  45. *
  46. * @var array
  47. */
  48. public $data = [];
  49. /**
  50. * Array of querystring arguments
  51. *
  52. * @var array
  53. */
  54. public $query = [];
  55. /**
  56. * Array of cookie data.
  57. *
  58. * @var array
  59. */
  60. public $cookies = [];
  61. /**
  62. * Array of environment data.
  63. *
  64. * @var array
  65. */
  66. protected $_environment = [];
  67. /**
  68. * The URL string used for the request.
  69. *
  70. * @var string
  71. */
  72. public $url;
  73. /**
  74. * Base URL path.
  75. *
  76. * @var string
  77. */
  78. public $base;
  79. /**
  80. * webroot path segment for the request.
  81. *
  82. * @var string
  83. */
  84. public $webroot = '/';
  85. /**
  86. * The full address to the current request
  87. *
  88. * @var string
  89. */
  90. public $here;
  91. /**
  92. * Whether or not to trust HTTP_X headers set by most load balancers.
  93. * Only set to true if your application runs behind load balancers/proxies
  94. * that you control.
  95. *
  96. * @var bool
  97. */
  98. public $trustProxy = false;
  99. /**
  100. * The built in detectors used with `is()` can be modified with `addDetector()`.
  101. *
  102. * There are several ways to specify a detector, see Cake\Network\Request::addDetector() for the
  103. * various formats and ways to define detectors.
  104. *
  105. * @var array
  106. */
  107. protected static $_detectors = array(
  108. 'get' => array('env' => 'REQUEST_METHOD', 'value' => 'GET'),
  109. 'post' => array('env' => 'REQUEST_METHOD', 'value' => 'POST'),
  110. 'put' => array('env' => 'REQUEST_METHOD', 'value' => 'PUT'),
  111. 'patch' => array('env' => 'REQUEST_METHOD', 'value' => 'PATCH'),
  112. 'delete' => array('env' => 'REQUEST_METHOD', 'value' => 'DELETE'),
  113. 'head' => array('env' => 'REQUEST_METHOD', 'value' => 'HEAD'),
  114. 'options' => array('env' => 'REQUEST_METHOD', 'value' => 'OPTIONS'),
  115. 'ssl' => array('env' => 'HTTPS', 'value' => 1),
  116. 'ajax' => array('env' => 'HTTP_X_REQUESTED_WITH', 'value' => 'XMLHttpRequest'),
  117. 'flash' => array('env' => 'HTTP_USER_AGENT', 'pattern' => '/^(Shockwave|Adobe) Flash/'),
  118. 'requested' => array('param' => 'requested', 'value' => 1)
  119. );
  120. /**
  121. * Copy of php://input. Since this stream can only be read once in most SAPI's
  122. * keep a copy of it so users don't need to know about that detail.
  123. *
  124. * @var string
  125. */
  126. protected $_input = '';
  127. /**
  128. * Instance of a Session object relative to this request
  129. *
  130. * @var \Cake\Network\Session
  131. */
  132. protected $_session;
  133. /**
  134. * Wrapper method to create a new request from PHP superglobals.
  135. *
  136. * Uses the $_GET, $_POST, $_FILES, $_COOKIE, $_SERVER, $_ENV and php://input data to construct
  137. * the request.
  138. *
  139. * @return \Cake\Network\Request
  140. */
  141. public static function createFromGlobals() {
  142. list($base, $webroot) = static::_base();
  143. $config = array(
  144. 'query' => $_GET,
  145. 'post' => $_POST,
  146. 'files' => $_FILES,
  147. 'cookies' => $_COOKIE,
  148. 'environment' => $_SERVER + $_ENV,
  149. 'base' => $base,
  150. 'webroot' => $webroot,
  151. 'session' => Session::create(Configure::read('Session'))
  152. );
  153. $config['url'] = static::_url($config);
  154. return new static($config);
  155. }
  156. /**
  157. * Create a new request object.
  158. *
  159. * You can supply the data as either an array or as a string. If you use
  160. * a string you can only supply the url for the request. Using an array will
  161. * let you provide the following keys:
  162. *
  163. * - `post` POST data or non query string data
  164. * - `query` Additional data from the query string.
  165. * - `files` Uploaded file data formatted like $_FILES.
  166. * - `cookies` Cookies for this request.
  167. * - `environment` $_SERVER and $_ENV data.
  168. * - `url` The url without the base path for the request.
  169. * - `base` The base url for the request.
  170. * - `webroot` The webroot directory for the request.
  171. * - `input` The data that would come from php://input this is useful for simulating
  172. * - `session` An instance of a Session object
  173. * requests with put, patch or delete data.
  174. *
  175. * @param string|array $config An array of request data to create a request with.
  176. */
  177. public function __construct($config = array()) {
  178. if (is_string($config)) {
  179. $config = array('url' => $config);
  180. }
  181. $config += array(
  182. 'params' => $this->params,
  183. 'query' => array(),
  184. 'post' => array(),
  185. 'files' => array(),
  186. 'cookies' => array(),
  187. 'environment' => array(),
  188. 'url' => '',
  189. 'base' => '',
  190. 'webroot' => '',
  191. 'input' => null,
  192. );
  193. if (empty($config['session'])) {
  194. $config['session'] = new Session();
  195. }
  196. $this->_setConfig($config);
  197. }
  198. /**
  199. * Process the config/settings data into properties.
  200. *
  201. * @param array $config The config data to use.
  202. * @return void
  203. */
  204. protected function _setConfig($config) {
  205. if (!empty($config['url']) && $config['url'][0] === '/') {
  206. $config['url'] = substr($config['url'], 1);
  207. }
  208. $this->url = $config['url'];
  209. $this->base = $config['base'];
  210. $this->cookies = $config['cookies'];
  211. $this->here = $this->base . '/' . $this->url;
  212. $this->webroot = $config['webroot'];
  213. $this->_environment = $config['environment'];
  214. if (isset($config['input'])) {
  215. $this->_input = $config['input'];
  216. }
  217. $config['post'] = $this->_processPost($config['post']);
  218. $this->data = $this->_processFiles($config['post'], $config['files']);
  219. $this->query = $this->_processGet($config['query']);
  220. $this->params = $config['params'];
  221. $this->_session = $config['session'];
  222. }
  223. /**
  224. * Sets the REQUEST_METHOD environment variable based on the simulated _method
  225. * HTTP override value.
  226. *
  227. * @param array $data Array of post data.
  228. * @return array
  229. */
  230. protected function _processPost($data) {
  231. if (
  232. in_array($this->env('REQUEST_METHOD'), array('PUT', 'DELETE', 'PATCH')) &&
  233. strpos($this->env('CONTENT_TYPE'), 'application/x-www-form-urlencoded') === 0
  234. ) {
  235. $data = $this->input();
  236. parse_str($data, $data);
  237. }
  238. if ($this->env('HTTP_X_HTTP_METHOD_OVERRIDE')) {
  239. $data['_method'] = $this->env('HTTP_X_HTTP_METHOD_OVERRIDE');
  240. }
  241. if (isset($data['_method'])) {
  242. $this->_environment['REQUEST_METHOD'] = $data['_method'];
  243. unset($data['_method']);
  244. }
  245. return $data;
  246. }
  247. /**
  248. * Process the GET parameters and move things into the object.
  249. *
  250. * @param array $query Contains querystring data such as `pag`
  251. * @return void
  252. */
  253. protected function _processGet($query) {
  254. $unsetUrl = '/' . str_replace(array('.', ' '), '_', urldecode($this->url));
  255. unset($query[$unsetUrl]);
  256. unset($query[$this->base . $unsetUrl]);
  257. if (strpos($this->url, '?') !== false) {
  258. list(, $querystr) = explode('?', $this->url);
  259. parse_str($querystr, $queryArgs);
  260. $query += $queryArgs;
  261. }
  262. return $query;
  263. }
  264. /**
  265. * Get the request uri. Looks in PATH_INFO first, as this is the exact value we need prepared
  266. * by PHP. Following that, REQUEST_URI, PHP_SELF, HTTP_X_REWRITE_URL and argv are checked in that order.
  267. * Each of these server variables have the base path, and query strings stripped off
  268. *
  269. * @param array $config Configuration to set.
  270. * @return string URI The CakePHP request path that is being accessed.
  271. */
  272. protected static function _url($config) {
  273. if (!empty($_SERVER['PATH_INFO'])) {
  274. return $_SERVER['PATH_INFO'];
  275. } elseif (isset($_SERVER['REQUEST_URI']) && strpos($_SERVER['REQUEST_URI'], '://') === false) {
  276. $uri = $_SERVER['REQUEST_URI'];
  277. } elseif (isset($_SERVER['REQUEST_URI'])) {
  278. $qPosition = strpos($_SERVER['REQUEST_URI'], '?');
  279. if ($qPosition !== false && strpos($_SERVER['REQUEST_URI'], '://') > $qPosition) {
  280. $uri = $_SERVER['REQUEST_URI'];
  281. } else {
  282. $uri = substr($_SERVER['REQUEST_URI'], strlen(Configure::read('App.fullBaseUrl')));
  283. }
  284. } elseif (isset($_SERVER['PHP_SELF']) && isset($_SERVER['SCRIPT_NAME'])) {
  285. $uri = str_replace($_SERVER['SCRIPT_NAME'], '', $_SERVER['PHP_SELF']);
  286. } elseif (isset($_SERVER['HTTP_X_REWRITE_URL'])) {
  287. $uri = $_SERVER['HTTP_X_REWRITE_URL'];
  288. } elseif ($var = env('argv')) {
  289. $uri = $var[0];
  290. }
  291. $base = $config['base'];
  292. if (strlen($base) > 0 && strpos($uri, $base) === 0) {
  293. $uri = substr($uri, strlen($base));
  294. }
  295. if (strpos($uri, '?') !== false) {
  296. list($uri) = explode('?', $uri, 2);
  297. }
  298. if (empty($uri) || $uri === '/' || $uri === '//' || $uri === '/index.php') {
  299. $uri = '/';
  300. }
  301. $endsWithIndex = '/webroot/index.php';
  302. $endsWithLength = strlen($endsWithIndex);
  303. if (
  304. strlen($uri) >= $endsWithLength &&
  305. substr($uri, -$endsWithLength) === $endsWithIndex
  306. ) {
  307. $uri = '/';
  308. }
  309. return $uri;
  310. }
  311. /**
  312. * Returns a base URL and sets the proper webroot
  313. *
  314. * If CakePHP is called with index.php in the URL even though
  315. * URL Rewriting is activated (and thus not needed) it swallows
  316. * the unnecessary part from $base to prevent issue #3318.
  317. *
  318. * @return array Base URL, webroot dir ending in /
  319. * @link https://cakephp.lighthouseapp.com/projects/42648-cakephp/tickets/3318
  320. */
  321. protected static function _base() {
  322. $base = $dir = $webroot = $baseUrl = null;
  323. $config = Configure::read('App');
  324. extract($config);
  325. if ($base !== false && $base !== null) {
  326. return array($base, $base . '/');
  327. }
  328. if (!$baseUrl) {
  329. $base = dirname(env('PHP_SELF'));
  330. $indexPos = strpos($base, '/' . $webroot . '/index.php');
  331. if ($indexPos !== false) {
  332. $base = substr($base, 0, $indexPos) . '/' . $webroot;
  333. }
  334. if ($webroot === basename($base)) {
  335. $base = dirname($base);
  336. }
  337. if ($base === DS || $base === '.') {
  338. $base = '';
  339. }
  340. $base = implode('/', array_map('rawurlencode', explode('/', $base)));
  341. return array($base, $base . '/');
  342. }
  343. $file = '/' . basename($baseUrl);
  344. $base = dirname($baseUrl);
  345. if ($base === DS || $base === '.') {
  346. $base = '';
  347. }
  348. $webrootDir = $base . '/';
  349. $docRoot = env('DOCUMENT_ROOT');
  350. $docRootContainsWebroot = strpos($docRoot, $webroot);
  351. if (!empty($base) || !$docRootContainsWebroot) {
  352. if (strpos($webrootDir, '/' . $webroot . '/') === false) {
  353. $webrootDir .= $webroot . '/';
  354. }
  355. }
  356. return array($base . $file, $webrootDir);
  357. }
  358. /**
  359. * Process uploaded files and move things onto the post data.
  360. *
  361. * @param array $post Post data to merge files onto.
  362. * @param array $files Uploaded files to merge in.
  363. * @return array merged post + file data.
  364. */
  365. protected function _processFiles($post, $files) {
  366. if (is_array($files)) {
  367. foreach ($files as $key => $data) {
  368. if (isset($data['tmp_name']) && is_string($data['tmp_name'])) {
  369. $post[$key] = $data;
  370. } else {
  371. $keyData = isset($post[$key]) ? $post[$key] : [];
  372. $post[$key] = $this->_processFileData($keyData, $data);
  373. }
  374. }
  375. }
  376. return $post;
  377. }
  378. /**
  379. * Recursively walks the FILES array restructuring the data
  380. * into something sane and usable.
  381. *
  382. * @param array $data The data being built
  383. * @param array $post The post data being traversed
  384. * @param string $path The dot separated path to insert $data into.
  385. * @param string $field The terminal field in the path. This is one of the
  386. * $_FILES properties e.g. name, tmp_name, size, error
  387. * @return void
  388. */
  389. protected function _processFileData($data, $post, $path = '', $field = '') {
  390. foreach ($post as $key => $fields) {
  391. $newField = $field;
  392. $newPath = $path;
  393. if ($path === '' && $newField === '') {
  394. $newField = $key;
  395. }
  396. if ($field === $newField) {
  397. $newPath .= '.' . $key;
  398. }
  399. if (is_array($fields)) {
  400. $data = $this->_processFileData($data, $fields, $newPath, $newField);
  401. } else {
  402. $newPath = trim($newPath . '.' . $field, '.');
  403. $data = Hash::insert($data, $newPath, $fields);
  404. }
  405. }
  406. return $data;
  407. }
  408. /**
  409. * Returns the instance of the Session object for this request
  410. *
  411. * If a session object is passed as first argument it will be set as
  412. * the session to use for this request
  413. *
  414. * @param \Cake\Network\Session $session the session object to use
  415. * @return \Cake\Network\Session
  416. */
  417. public function session(Session $session = null) {
  418. if ($session === null) {
  419. return $this->_session;
  420. }
  421. return $this->_session = $session;
  422. }
  423. /**
  424. * Get the IP the client is using, or says they are using.
  425. *
  426. * @return string The client IP.
  427. */
  428. public function clientIp() {
  429. if ($this->trustProxy && $this->env('HTTP_X_FORWARDED_FOR')) {
  430. $ipaddr = preg_replace('/(?:,.*)/', '', $this->env('HTTP_X_FORWARDED_FOR'));
  431. } else {
  432. if ($this->env('HTTP_CLIENT_IP')) {
  433. $ipaddr = $this->env('HTTP_CLIENT_IP');
  434. } else {
  435. $ipaddr = $this->env('REMOTE_ADDR');
  436. }
  437. }
  438. if ($this->env('HTTP_CLIENTADDRESS')) {
  439. $tmpipaddr = $this->env('HTTP_CLIENTADDRESS');
  440. if (!empty($tmpipaddr)) {
  441. $ipaddr = preg_replace('/(?:,.*)/', '', $tmpipaddr);
  442. }
  443. }
  444. return trim($ipaddr);
  445. }
  446. /**
  447. * Returns the referer that referred this request.
  448. *
  449. * @param bool $local Attempt to return a local address.
  450. * Local addresses do not contain hostnames.
  451. * @return string The referring address for this request.
  452. */
  453. public function referer($local = false) {
  454. $ref = $this->env('HTTP_REFERER');
  455. $base = Configure::read('App.fullBaseUrl') . $this->webroot;
  456. if (!empty($ref) && !empty($base)) {
  457. if ($local && strpos($ref, $base) === 0) {
  458. $ref = substr($ref, strlen($base));
  459. if ($ref[0] !== '/') {
  460. $ref = '/' . $ref;
  461. }
  462. return $ref;
  463. } elseif (!$local) {
  464. return $ref;
  465. }
  466. }
  467. return '/';
  468. }
  469. /**
  470. * Missing method handler, handles wrapping older style isAjax() type methods
  471. *
  472. * @param string $name The method called
  473. * @param array $params Array of parameters for the method call
  474. * @return mixed
  475. * @throws \Cake\Error\Exception when an invalid method is called.
  476. */
  477. public function __call($name, $params) {
  478. if (strpos($name, 'is') === 0) {
  479. $type = strtolower(substr($name, 2));
  480. return $this->is($type);
  481. }
  482. throw new Error\Exception(sprintf('Method %s does not exist', $name));
  483. }
  484. /**
  485. * Magic get method allows access to parsed routing parameters directly on the object.
  486. *
  487. * Allows access to `$this->params['controller']` via `$this->controller`
  488. *
  489. * @param string $name The property being accessed.
  490. * @return mixed Either the value of the parameter or null.
  491. */
  492. public function __get($name) {
  493. if (isset($this->params[$name])) {
  494. return $this->params[$name];
  495. }
  496. return null;
  497. }
  498. /**
  499. * Magic isset method allows isset/empty checks
  500. * on routing parameters.
  501. *
  502. * @param string $name The property being accessed.
  503. * @return bool Existence
  504. */
  505. public function __isset($name) {
  506. return isset($this->params[$name]);
  507. }
  508. /**
  509. * Check whether or not a Request is a certain type.
  510. *
  511. * Uses the built in detection rules as well as additional rules
  512. * defined with Cake\Network\CakeRequest::addDetector(). Any detector can be called
  513. * as `is($type)` or `is$Type()`.
  514. *
  515. * @param string|array $type The type of request you want to check. If an array
  516. * this method will return true if the request matches any type.
  517. * @return bool Whether or not the request is the type you are checking.
  518. */
  519. public function is($type) {
  520. if (is_array($type)) {
  521. $result = array_map(array($this, 'is'), $type);
  522. return count(array_filter($result)) > 0;
  523. }
  524. $type = strtolower($type);
  525. if (!isset(static::$_detectors[$type])) {
  526. return false;
  527. }
  528. $detect = static::$_detectors[$type];
  529. if (is_callable($detect)) {
  530. return call_user_func($detect, $this);
  531. }
  532. if (isset($detect['env'])) {
  533. if (isset($detect['value'])) {
  534. return $this->env($detect['env']) == $detect['value'];
  535. }
  536. if (isset($detect['pattern'])) {
  537. return (bool)preg_match($detect['pattern'], $this->env($detect['env']));
  538. }
  539. if (isset($detect['options'])) {
  540. $pattern = '/' . implode('|', $detect['options']) . '/i';
  541. return (bool)preg_match($pattern, $this->env($detect['env']));
  542. }
  543. }
  544. if (isset($detect['param'])) {
  545. $key = $detect['param'];
  546. if (isset($detect['value'])) {
  547. $value = $detect['value'];
  548. return isset($this->params[$key]) ? $this->params[$key] == $value : false;
  549. }
  550. if (isset($detect['options'])) {
  551. return isset($this->params[$key]) ? in_array($this->params[$key], $detect['options']) : false;
  552. }
  553. }
  554. if (isset($detect['callback']) && is_callable($detect['callback'])) {
  555. return call_user_func($detect['callback'], $this);
  556. }
  557. return false;
  558. }
  559. /**
  560. * Check that a request matches all the given types.
  561. *
  562. * Allows you to test multiple types and union the results.
  563. * See Request::is() for how to add additional types and the
  564. * built-in types.
  565. *
  566. * @param array $types The types to check.
  567. * @return bool Success.
  568. * @see \Cake\Network\Request::is()
  569. */
  570. public function isAll(array $types) {
  571. $result = array_filter(array_map(array($this, 'is'), $types));
  572. return count($result) === count($types);
  573. }
  574. /**
  575. * Add a new detector to the list of detectors that a request can use.
  576. * There are several different formats and types of detectors that can be set.
  577. *
  578. * ### Callback detectors
  579. *
  580. * Callback detectors allow you to provide a callable to handle the check.
  581. * The callback will receive the request object as its only parameter.
  582. *
  583. * e.g `addDetector('custom', function($request) { //Return a boolean });`
  584. * e.g `addDetector('custom', array('SomeClass', 'somemethod'));`
  585. *
  586. * ### Environment value comparison
  587. *
  588. * An environment value comparison, compares a value fetched from `env()` to a known value
  589. * the environment value is equality checked against the provided value.
  590. *
  591. * e.g `addDetector('post', array('env' => 'REQUEST_METHOD', 'value' => 'POST'))`
  592. *
  593. * ### Pattern value comparison
  594. *
  595. * Pattern value comparison allows you to compare a value fetched from `env()` to a regular expression.
  596. *
  597. * e.g `addDetector('iphone', array('env' => 'HTTP_USER_AGENT', 'pattern' => '/iPhone/i'));`
  598. *
  599. * ### Option based comparison
  600. *
  601. * Option based comparisons use a list of options to create a regular expression. Subsequent calls
  602. * to add an already defined options detector will merge the options.
  603. *
  604. * e.g `addDetector('mobile', array('env' => 'HTTP_USER_AGENT', 'options' => array('Fennec')));`
  605. *
  606. * ### Request parameter detectors
  607. *
  608. * Allows for custom detectors on the request parameters.
  609. *
  610. * e.g `addDetector('requested', array('param' => 'requested', 'value' => 1)`
  611. *
  612. * You can also make parameter detectors that accept multiple values
  613. * using the `options` key. This is useful when you want to check
  614. * if a request parameter is in a list of options.
  615. *
  616. * `addDetector('extension', array('param' => 'ext', 'options' => array('pdf', 'csv'))`
  617. *
  618. * @param string $name The name of the detector.
  619. * @param callable|array $callable A callable or options array for the detector definition.
  620. * @return void
  621. */
  622. public static function addDetector($name, $callable) {
  623. $name = strtolower($name);
  624. if (is_callable($callable)) {
  625. static::$_detectors[$name] = $callable;
  626. return;
  627. }
  628. if (isset(static::$_detectors[$name]) && isset($callable['options'])) {
  629. $callable = Hash::merge(static::$_detectors[$name], $callable);
  630. }
  631. static::$_detectors[$name] = $callable;
  632. }
  633. /**
  634. * Add parameters to the request's parsed parameter set. This will overwrite any existing parameters.
  635. * This modifies the parameters available through `$request->params`.
  636. *
  637. * @param array $params Array of parameters to merge in
  638. * @return $this The current object, you can chain this method.
  639. */
  640. public function addParams(array $params) {
  641. $this->params = array_merge($this->params, $params);
  642. return $this;
  643. }
  644. /**
  645. * Add paths to the requests' paths vars. This will overwrite any existing paths.
  646. * Provides an easy way to modify, here, webroot and base.
  647. *
  648. * @param array $paths Array of paths to merge in
  649. * @return $this The current object, you can chain this method.
  650. */
  651. public function addPaths(array $paths) {
  652. foreach (array('webroot', 'here', 'base') as $element) {
  653. if (isset($paths[$element])) {
  654. $this->{$element} = $paths[$element];
  655. }
  656. }
  657. return $this;
  658. }
  659. /**
  660. * Get the value of the current requests URL. Will include querystring arguments.
  661. *
  662. * @param bool $base Include the base path, set to false to trim the base path off.
  663. * @return string The current request URL including query string args.
  664. */
  665. public function here($base = true) {
  666. $url = $this->here;
  667. if (!empty($this->query)) {
  668. $url .= '?' . http_build_query($this->query, null, '&');
  669. }
  670. if (!$base) {
  671. $url = preg_replace('/^' . preg_quote($this->base, '/') . '/', '', $url, 1);
  672. }
  673. return $url;
  674. }
  675. /**
  676. * Read an HTTP header from the Request information.
  677. *
  678. * @param string $name Name of the header you want.
  679. * @return mixed Either null on no header being set or the value of the header.
  680. */
  681. public function header($name) {
  682. $name = 'HTTP_' . str_replace('-', '_', $name);
  683. return $this->env($name);
  684. }
  685. /**
  686. * Get the HTTP method used for this request.
  687. * There are a few ways to specify a method.
  688. *
  689. * - If your client supports it you can use native HTTP methods.
  690. * - You can set the HTTP-X-Method-Override header.
  691. * - You can submit an input with the name `_method`
  692. *
  693. * Any of these 3 approaches can be used to set the HTTP method used
  694. * by CakePHP internally, and will effect the result of this method.
  695. *
  696. * @return string The name of the HTTP method used.
  697. */
  698. public function method() {
  699. return $this->env('REQUEST_METHOD');
  700. }
  701. /**
  702. * Get the host that the request was handled on.
  703. *
  704. * @return string
  705. */
  706. public function host() {
  707. if ($this->trustProxy && $this->env('HTTP_X_FORWARDED_HOST')) {
  708. return $this->env('HTTP_X_FORWARDED_HOST');
  709. }
  710. return $this->env('HTTP_HOST');
  711. }
  712. /**
  713. * Get the port the request was handled on.
  714. *
  715. * @return string
  716. */
  717. public function port() {
  718. if ($this->trustProxy && $this->env('HTTP_X_FORWARDED_PORT')) {
  719. return $this->env('HTTP_X_FORWARDED_PORT');
  720. }
  721. return $this->env('SERVER_PORT');
  722. }
  723. /**
  724. * Get the current url scheme used for the request.
  725. *
  726. * e.g. 'http', or 'https'
  727. *
  728. * @return string The scheme used for the request.
  729. */
  730. public function scheme() {
  731. if ($this->trustProxy && $this->env('HTTP_X_FORWARDED_PROTO')) {
  732. return $this->env('HTTP_X_FORWARDED_PROTO');
  733. }
  734. return $this->env('HTTPS') ? 'https' : 'http';
  735. }
  736. /**
  737. * Get the domain name and include $tldLength segments of the tld.
  738. *
  739. * @param int $tldLength Number of segments your tld contains. For example: `example.com` contains 1 tld.
  740. * While `example.co.uk` contains 2.
  741. * @return string Domain name without subdomains.
  742. */
  743. public function domain($tldLength = 1) {
  744. $segments = explode('.', $this->host());
  745. $domain = array_slice($segments, -1 * ($tldLength + 1));
  746. return implode('.', $domain);
  747. }
  748. /**
  749. * Get the subdomains for a host.
  750. *
  751. * @param int $tldLength Number of segments your tld contains. For example: `example.com` contains 1 tld.
  752. * While `example.co.uk` contains 2.
  753. * @return array An array of subdomains.
  754. */
  755. public function subdomains($tldLength = 1) {
  756. $segments = explode('.', $this->host());
  757. return array_slice($segments, 0, -1 * ($tldLength + 1));
  758. }
  759. /**
  760. * Find out which content types the client accepts or check if they accept a
  761. * particular type of content.
  762. *
  763. * #### Get all types:
  764. *
  765. * `$this->request->accepts();`
  766. *
  767. * #### Check for a single type:
  768. *
  769. * `$this->request->accepts('application/json');`
  770. *
  771. * This method will order the returned content types by the preference values indicated
  772. * by the client.
  773. *
  774. * @param string $type The content type to check for. Leave null to get all types a client accepts.
  775. * @return mixed Either an array of all the types the client accepts or a boolean if they accept the
  776. * provided type.
  777. */
  778. public function accepts($type = null) {
  779. $raw = $this->parseAccept();
  780. $accept = array();
  781. foreach ($raw as $types) {
  782. $accept = array_merge($accept, $types);
  783. }
  784. if ($type === null) {
  785. return $accept;
  786. }
  787. return in_array($type, $accept);
  788. }
  789. /**
  790. * Parse the HTTP_ACCEPT header and return a sorted array with content types
  791. * as the keys, and pref values as the values.
  792. *
  793. * Generally you want to use Cake\Network\Request::accept() to get a simple list
  794. * of the accepted content types.
  795. *
  796. * @return array An array of prefValue => array(content/types)
  797. */
  798. public function parseAccept() {
  799. return $this->_parseAcceptWithQualifier($this->header('accept'));
  800. }
  801. /**
  802. * Get the languages accepted by the client, or check if a specific language is accepted.
  803. *
  804. * Get the list of accepted languages:
  805. *
  806. * {{{ \Cake\Network\Request::acceptLanguage(); }}}
  807. *
  808. * Check if a specific language is accepted:
  809. *
  810. * {{{ \Cake\Network\Request::acceptLanguage('es-es'); }}}
  811. *
  812. * @param string $language The language to test.
  813. * @return mixed If a $language is provided, a boolean. Otherwise the array of accepted languages.
  814. */
  815. public function acceptLanguage($language = null) {
  816. $raw = $this->_parseAcceptWithQualifier($this->header('Accept-Language'));
  817. $accept = array();
  818. foreach ($raw as $languages) {
  819. foreach ($languages as &$lang) {
  820. if (strpos($lang, '_')) {
  821. $lang = str_replace('_', '-', $lang);
  822. }
  823. $lang = strtolower($lang);
  824. }
  825. $accept = array_merge($accept, $languages);
  826. }
  827. if ($language === null) {
  828. return $accept;
  829. }
  830. return in_array(strtolower($language), $accept);
  831. }
  832. /**
  833. * Parse Accept* headers with qualifier options.
  834. *
  835. * Only qualifiers will be extracted, any other accept extensions will be
  836. * discarded as they are not frequently used.
  837. *
  838. * @param string $header Header to parse.
  839. * @return array
  840. */
  841. protected function _parseAcceptWithQualifier($header) {
  842. $accept = array();
  843. $header = explode(',', $header);
  844. foreach (array_filter($header) as $value) {
  845. $prefValue = '1.0';
  846. $value = trim($value);
  847. $semiPos = strpos($value, ';');
  848. if ($semiPos !== false) {
  849. $params = explode(';', $value);
  850. $value = trim($params[0]);
  851. foreach ($params as $param) {
  852. $qPos = strpos($param, 'q=');
  853. if ($qPos !== false) {
  854. $prefValue = substr($param, $qPos + 2);
  855. }
  856. }
  857. }
  858. if (!isset($accept[$prefValue])) {
  859. $accept[$prefValue] = array();
  860. }
  861. if ($prefValue) {
  862. $accept[$prefValue][] = $value;
  863. }
  864. }
  865. krsort($accept);
  866. return $accept;
  867. }
  868. /**
  869. * Provides a read accessor for `$this->query`. Allows you
  870. * to use a syntax similar to `CakeSession` for reading URL query data.
  871. *
  872. * @param string $name Query string variable name
  873. * @return mixed The value being read
  874. */
  875. public function query($name) {
  876. return Hash::get($this->query, $name);
  877. }
  878. /**
  879. * Provides a read/write accessor for `$this->data`. Allows you
  880. * to use a syntax similar to `Cake\Model\Datasource\Session` for reading post data.
  881. *
  882. * ## Reading values.
  883. *
  884. * `$request->data('Post.title');`
  885. *
  886. * When reading values you will get `null` for keys/values that do not exist.
  887. *
  888. * ## Writing values
  889. *
  890. * `$request->data('Post.title', 'New post!');`
  891. *
  892. * You can write to any value, even paths/keys that do not exist, and the arrays
  893. * will be created for you.
  894. *
  895. * @param string|null $name Dot separated name of the value to read/write
  896. * @return mixed|$this Either the value being read, or this so you can chain consecutive writes.
  897. */
  898. public function data($name = null) {
  899. $args = func_get_args();
  900. if (count($args) === 2) {
  901. $this->data = Hash::insert($this->data, $name, $args[1]);
  902. return $this;
  903. }
  904. if ($name !== null) {
  905. return Hash::get($this->data, $name);
  906. }
  907. return $this->data;
  908. }
  909. /**
  910. * Safely access the values in $this->params.
  911. *
  912. * @param string $name The name of the parameter to get.
  913. * @return mixed The value of the provided parameter. Will
  914. * return false if the parameter doesn't exist or is falsey.
  915. */
  916. public function param($name) {
  917. $args = func_get_args();
  918. if (count($args) === 2) {
  919. $this->params = Hash::insert($this->params, $name, $args[1]);
  920. return $this;
  921. }
  922. if (!isset($this->params[$name])) {
  923. return Hash::get($this->params, $name, false);
  924. }
  925. return $this->params[$name];
  926. }
  927. /**
  928. * Read data from `php://input`. Useful when interacting with XML or JSON
  929. * request body content.
  930. *
  931. * Getting input with a decoding function:
  932. *
  933. * `$this->request->input('json_decode');`
  934. *
  935. * Getting input using a decoding function, and additional params:
  936. *
  937. * `$this->request->input('Xml::build', array('return' => 'DOMDocument'));`
  938. *
  939. * Any additional parameters are applied to the callback in the order they are given.
  940. *
  941. * @param string $callback A decoding callback that will convert the string data to another
  942. * representation. Leave empty to access the raw input data. You can also
  943. * supply additional parameters for the decoding callback using var args, see above.
  944. * @return string The decoded/processed request data.
  945. */
  946. public function input($callback = null) {
  947. $input = $this->_readInput();
  948. $args = func_get_args();
  949. if (!empty($args)) {
  950. $callback = array_shift($args);
  951. array_unshift($args, $input);
  952. return call_user_func_array($callback, $args);
  953. }
  954. return $input;
  955. }
  956. /**
  957. * Read cookie data from the request's cookie data.
  958. *
  959. * @param string $key The key you want to read.
  960. * @return null|string Either the cookie value, or null if the value doesn't exist.
  961. */
  962. public function cookie($key) {
  963. if (isset($this->cookies[$key])) {
  964. return $this->cookies[$key];
  965. }
  966. return null;
  967. }
  968. /**
  969. * Get/Set value from the request's environment data.
  970. * Fallback to using env() if key not set in $environment property.
  971. *
  972. * @param string $key The key you want to read/write from/to.
  973. * @param string $value Value to set. Default null.
  974. * @return null|string|\Cake\Network\Request Request instance if used as setter,
  975. * if used as getter either the environment value, or null if the value doesn't exist.
  976. */
  977. public function env($key, $value = null) {
  978. if ($value !== null) {
  979. $this->_environment[$key] = $value;
  980. return $this;
  981. }
  982. $key = strtoupper($key);
  983. if (!array_key_exists($key, $this->_environment)) {
  984. $this->_environment[$key] = env($key);
  985. }
  986. return $this->_environment[$key];
  987. }
  988. /**
  989. * Allow only certain HTTP request methods, if the request method does not match
  990. * a 405 error will be shown and the required "Allow" response header will be set.
  991. *
  992. * Example:
  993. *
  994. * $this->request->allowMethod('post');
  995. * or
  996. * $this->request->allowMethod(['post', 'delete']);
  997. *
  998. * If the request would be GET, response header "Allow: POST, DELETE" will be set
  999. * and a 405 error will be returned.
  1000. *
  1001. * @param string|array $methods Allowed HTTP request methods.
  1002. * @return bool true
  1003. * @throws \Cake\Error\MethodNotAllowedException
  1004. */
  1005. public function allowMethod($methods) {
  1006. $methods = (array)$methods;
  1007. foreach ($methods as $method) {
  1008. if ($this->is($method)) {
  1009. return true;
  1010. }
  1011. }
  1012. $allowed = strtoupper(implode(', ', $methods));
  1013. $e = new Error\MethodNotAllowedException();
  1014. $e->responseHeader('Allow', $allowed);
  1015. throw $e;
  1016. }
  1017. /**
  1018. * Read data from php://input, mocked in tests.
  1019. *
  1020. * @return string contents of php://input
  1021. */
  1022. protected function _readInput() {
  1023. if (empty($this->_input)) {
  1024. $fh = fopen('php://input', 'r');
  1025. $content = stream_get_contents($fh);
  1026. fclose($fh);
  1027. $this->_input = $content;
  1028. }
  1029. return $this->_input;
  1030. }
  1031. /**
  1032. * Modify data originally from `php://input`. Useful for altering json/xml data
  1033. * in middleware or DispatcherFilters before it gets to RequestHandlerComponent
  1034. *
  1035. * @param string $input A string to replace original parsed data from input()
  1036. * @return void
  1037. */
  1038. public function setInput($input) {
  1039. $this->_input = $input;
  1040. }
  1041. /**
  1042. * Array access read implementation
  1043. *
  1044. * @param string $name Name of the key being accessed.
  1045. * @return mixed
  1046. */
  1047. public function offsetGet($name) {
  1048. if (isset($this->params[$name])) {
  1049. return $this->params[$name];
  1050. }
  1051. if ($name === 'url') {
  1052. return $this->query;
  1053. }
  1054. if ($name === 'data') {
  1055. return $this->data;
  1056. }
  1057. return null;
  1058. }
  1059. /**
  1060. * Array access write implementation
  1061. *
  1062. * @param string $name Name of the key being written
  1063. * @param mixed $value The value being written.
  1064. * @return void
  1065. */
  1066. public function offsetSet($name, $value) {
  1067. $this->params[$name] = $value;
  1068. }
  1069. /**
  1070. * Array access isset() implementation
  1071. *
  1072. * @param string $name thing to check.
  1073. * @return bool
  1074. */
  1075. public function offsetExists($name) {
  1076. return isset($this->params[$name]);
  1077. }
  1078. /**
  1079. * Array access unset() implementation
  1080. *
  1081. * @param string $name Name to unset.
  1082. * @return void
  1083. */
  1084. public function offsetUnset($name) {
  1085. unset($this->params[$name]);
  1086. }
  1087. }