Request.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167
  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('.', '_', 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. if ($path === '' && $newField === '') {
  393. $newField = $key;
  394. }
  395. if ($field === $newField) {
  396. $path .= '.' . $key;
  397. }
  398. if (is_array($fields)) {
  399. $data = $this->_processFileData($data, $fields, $path, $newField);
  400. } else {
  401. $path = trim($path . '.' . $field, '.');
  402. $data = Hash::insert($data, $path, $fields);
  403. }
  404. }
  405. return $data;
  406. }
  407. /**
  408. * Returns the instance of the Session object for this request
  409. *
  410. * If a session object is passed as first argument it will be set as
  411. * the session to use for this request
  412. *
  413. * @param \Cake\Network\Session $session the session object to use
  414. * @return \Cake\Network\Session
  415. */
  416. public function session(Session $session = null) {
  417. if ($session === null) {
  418. return $this->_session;
  419. }
  420. return $this->_session = $session;
  421. }
  422. /**
  423. * Get the IP the client is using, or says they are using.
  424. *
  425. * @return string The client IP.
  426. */
  427. public function clientIp() {
  428. if ($this->trustProxy && $this->env('HTTP_X_FORWARDED_FOR')) {
  429. $ipaddr = preg_replace('/(?:,.*)/', '', $this->env('HTTP_X_FORWARDED_FOR'));
  430. } else {
  431. if ($this->env('HTTP_CLIENT_IP')) {
  432. $ipaddr = $this->env('HTTP_CLIENT_IP');
  433. } else {
  434. $ipaddr = $this->env('REMOTE_ADDR');
  435. }
  436. }
  437. if ($this->env('HTTP_CLIENTADDRESS')) {
  438. $tmpipaddr = $this->env('HTTP_CLIENTADDRESS');
  439. if (!empty($tmpipaddr)) {
  440. $ipaddr = preg_replace('/(?:,.*)/', '', $tmpipaddr);
  441. }
  442. }
  443. return trim($ipaddr);
  444. }
  445. /**
  446. * Returns the referer that referred this request.
  447. *
  448. * @param bool $local Attempt to return a local address.
  449. * Local addresses do not contain hostnames.
  450. * @return string The referring address for this request.
  451. */
  452. public function referer($local = false) {
  453. $ref = $this->env('HTTP_REFERER');
  454. $base = Configure::read('App.fullBaseUrl') . $this->webroot;
  455. if (!empty($ref) && !empty($base)) {
  456. if ($local && strpos($ref, $base) === 0) {
  457. $ref = substr($ref, strlen($base));
  458. if ($ref[0] !== '/') {
  459. $ref = '/' . $ref;
  460. }
  461. return $ref;
  462. } elseif (!$local) {
  463. return $ref;
  464. }
  465. }
  466. return '/';
  467. }
  468. /**
  469. * Missing method handler, handles wrapping older style isAjax() type methods
  470. *
  471. * @param string $name The method called
  472. * @param array $params Array of parameters for the method call
  473. * @return mixed
  474. * @throws \Cake\Error\Exception when an invalid method is called.
  475. */
  476. public function __call($name, $params) {
  477. if (strpos($name, 'is') === 0) {
  478. $type = strtolower(substr($name, 2));
  479. return $this->is($type);
  480. }
  481. throw new Error\Exception(sprintf('Method %s does not exist', $name));
  482. }
  483. /**
  484. * Magic get method allows access to parsed routing parameters directly on the object.
  485. *
  486. * Allows access to `$this->params['controller']` via `$this->controller`
  487. *
  488. * @param string $name The property being accessed.
  489. * @return mixed Either the value of the parameter or null.
  490. */
  491. public function __get($name) {
  492. if (isset($this->params[$name])) {
  493. return $this->params[$name];
  494. }
  495. return null;
  496. }
  497. /**
  498. * Magic isset method allows isset/empty checks
  499. * on routing parameters.
  500. *
  501. * @param string $name The property being accessed.
  502. * @return bool Existence
  503. */
  504. public function __isset($name) {
  505. return isset($this->params[$name]);
  506. }
  507. /**
  508. * Check whether or not a Request is a certain type.
  509. *
  510. * Uses the built in detection rules as well as additional rules
  511. * defined with Cake\Network\CakeRequest::addDetector(). Any detector can be called
  512. * as `is($type)` or `is$Type()`.
  513. *
  514. * @param string|array $type The type of request you want to check. If an array
  515. * this method will return true if the request matches any type.
  516. * @return bool Whether or not the request is the type you are checking.
  517. */
  518. public function is($type) {
  519. if (is_array($type)) {
  520. $result = array_map(array($this, 'is'), $type);
  521. return count(array_filter($result)) > 0;
  522. }
  523. $type = strtolower($type);
  524. if (!isset(static::$_detectors[$type])) {
  525. return false;
  526. }
  527. $detect = static::$_detectors[$type];
  528. if (is_callable($detect)) {
  529. return call_user_func($detect, $this);
  530. }
  531. if (isset($detect['env'])) {
  532. if (isset($detect['value'])) {
  533. return $this->env($detect['env']) == $detect['value'];
  534. }
  535. if (isset($detect['pattern'])) {
  536. return (bool)preg_match($detect['pattern'], $this->env($detect['env']));
  537. }
  538. if (isset($detect['options'])) {
  539. $pattern = '/' . implode('|', $detect['options']) . '/i';
  540. return (bool)preg_match($pattern, $this->env($detect['env']));
  541. }
  542. }
  543. if (isset($detect['param'])) {
  544. $key = $detect['param'];
  545. if (isset($detect['value'])) {
  546. $value = $detect['value'];
  547. return isset($this->params[$key]) ? $this->params[$key] == $value : false;
  548. }
  549. if (isset($detect['options'])) {
  550. return isset($this->params[$key]) ? in_array($this->params[$key], $detect['options']) : false;
  551. }
  552. }
  553. if (isset($detect['callback']) && is_callable($detect['callback'])) {
  554. return call_user_func($detect['callback'], $this);
  555. }
  556. return false;
  557. }
  558. /**
  559. * Check that a request matches all the given types.
  560. *
  561. * Allows you to test multiple types and union the results.
  562. * See Request::is() for how to add additional types and the
  563. * built-in types.
  564. *
  565. * @param array $types The types to check.
  566. * @return bool Success.
  567. * @see \Cake\Network\Request::is()
  568. */
  569. public function isAll(array $types) {
  570. $result = array_filter(array_map(array($this, 'is'), $types));
  571. return count($result) === count($types);
  572. }
  573. /**
  574. * Add a new detector to the list of detectors that a request can use.
  575. * There are several different formats and types of detectors that can be set.
  576. *
  577. * ### Callback detectors
  578. *
  579. * Callback detectors allow you to provide a callable to handle the check.
  580. * The callback will receive the request object as its only parameter.
  581. *
  582. * e.g `addDetector('custom', function($request) { //Return a boolean });`
  583. * e.g `addDetector('custom', array('SomeClass', 'somemethod'));`
  584. *
  585. * ### Environment value comparison
  586. *
  587. * An environment value comparison, compares a value fetched from `env()` to a known value
  588. * the environment value is equality checked against the provided value.
  589. *
  590. * e.g `addDetector('post', array('env' => 'REQUEST_METHOD', 'value' => 'POST'))`
  591. *
  592. * ### Pattern value comparison
  593. *
  594. * Pattern value comparison allows you to compare a value fetched from `env()` to a regular expression.
  595. *
  596. * e.g `addDetector('iphone', array('env' => 'HTTP_USER_AGENT', 'pattern' => '/iPhone/i'));`
  597. *
  598. * ### Option based comparison
  599. *
  600. * Option based comparisons use a list of options to create a regular expression. Subsequent calls
  601. * to add an already defined options detector will merge the options.
  602. *
  603. * e.g `addDetector('mobile', array('env' => 'HTTP_USER_AGENT', 'options' => array('Fennec')));`
  604. *
  605. * ### Request parameter detectors
  606. *
  607. * Allows for custom detectors on the request parameters.
  608. *
  609. * e.g `addDetector('requested', array('param' => 'requested', 'value' => 1)`
  610. *
  611. * You can also make parameter detectors that accept multiple values
  612. * using the `options` key. This is useful when you want to check
  613. * if a request parameter is in a list of options.
  614. *
  615. * `addDetector('extension', array('param' => 'ext', 'options' => array('pdf', 'csv'))`
  616. *
  617. * @param string $name The name of the detector.
  618. * @param callable|array $callable A callable or options array for the detector definition.
  619. * @return void
  620. */
  621. public static function addDetector($name, $callable) {
  622. $name = strtolower($name);
  623. if (is_callable($callable)) {
  624. static::$_detectors[$name] = $callable;
  625. return;
  626. }
  627. if (isset(static::$_detectors[$name]) && isset($callable['options'])) {
  628. $callable = Hash::merge(static::$_detectors[$name], $callable);
  629. }
  630. static::$_detectors[$name] = $callable;
  631. }
  632. /**
  633. * Add parameters to the request's parsed parameter set. This will overwrite any existing parameters.
  634. * This modifies the parameters available through `$request->params`.
  635. *
  636. * @param array $params Array of parameters to merge in
  637. * @return $this The current object, you can chain this method.
  638. */
  639. public function addParams(array $params) {
  640. $this->params = array_merge($this->params, $params);
  641. return $this;
  642. }
  643. /**
  644. * Add paths to the requests' paths vars. This will overwrite any existing paths.
  645. * Provides an easy way to modify, here, webroot and base.
  646. *
  647. * @param array $paths Array of paths to merge in
  648. * @return $this The current object, you can chain this method.
  649. */
  650. public function addPaths(array $paths) {
  651. foreach (array('webroot', 'here', 'base') as $element) {
  652. if (isset($paths[$element])) {
  653. $this->{$element} = $paths[$element];
  654. }
  655. }
  656. return $this;
  657. }
  658. /**
  659. * Get the value of the current requests URL. Will include querystring arguments.
  660. *
  661. * @param bool $base Include the base path, set to false to trim the base path off.
  662. * @return string The current request URL including query string args.
  663. */
  664. public function here($base = true) {
  665. $url = $this->here;
  666. if (!empty($this->query)) {
  667. $url .= '?' . http_build_query($this->query, null, '&');
  668. }
  669. if (!$base) {
  670. $url = preg_replace('/^' . preg_quote($this->base, '/') . '/', '', $url, 1);
  671. }
  672. return $url;
  673. }
  674. /**
  675. * Read an HTTP header from the Request information.
  676. *
  677. * @param string $name Name of the header you want.
  678. * @return mixed Either null on no header being set or the value of the header.
  679. */
  680. public function header($name) {
  681. $name = 'HTTP_' . str_replace('-', '_', $name);
  682. return $this->env($name);
  683. }
  684. /**
  685. * Get the HTTP method used for this request.
  686. * There are a few ways to specify a method.
  687. *
  688. * - If your client supports it you can use native HTTP methods.
  689. * - You can set the HTTP-X-Method-Override header.
  690. * - You can submit an input with the name `_method`
  691. *
  692. * Any of these 3 approaches can be used to set the HTTP method used
  693. * by CakePHP internally, and will effect the result of this method.
  694. *
  695. * @return string The name of the HTTP method used.
  696. */
  697. public function method() {
  698. return $this->env('REQUEST_METHOD');
  699. }
  700. /**
  701. * Get the host that the request was handled on.
  702. *
  703. * @return string
  704. */
  705. public function host() {
  706. if ($this->trustProxy && $this->env('HTTP_X_FORWARDED_HOST')) {
  707. return $this->env('HTTP_X_FORWARDED_HOST');
  708. }
  709. return $this->env('HTTP_HOST');
  710. }
  711. /**
  712. * Get the port the request was handled on.
  713. *
  714. * @return string
  715. */
  716. public function port() {
  717. if ($this->trustProxy && $this->env('HTTP_X_FORWARDED_PORT')) {
  718. return $this->env('HTTP_X_FORWARDED_PORT');
  719. }
  720. return $this->env('SERVER_PORT');
  721. }
  722. /**
  723. * Get the current url scheme used for the request.
  724. *
  725. * e.g. 'http', or 'https'
  726. *
  727. * @return string The scheme used for the request.
  728. */
  729. public function scheme() {
  730. if ($this->trustProxy && $this->env('HTTP_X_FORWARDED_PROTO')) {
  731. return $this->env('HTTP_X_FORWARDED_PROTO');
  732. }
  733. return $this->env('HTTPS') ? 'https' : 'http';
  734. }
  735. /**
  736. * Get the domain name and include $tldLength segments of the tld.
  737. *
  738. * @param int $tldLength Number of segments your tld contains. For example: `example.com` contains 1 tld.
  739. * While `example.co.uk` contains 2.
  740. * @return string Domain name without subdomains.
  741. */
  742. public function domain($tldLength = 1) {
  743. $segments = explode('.', $this->host());
  744. $domain = array_slice($segments, -1 * ($tldLength + 1));
  745. return implode('.', $domain);
  746. }
  747. /**
  748. * Get the subdomains for a host.
  749. *
  750. * @param int $tldLength Number of segments your tld contains. For example: `example.com` contains 1 tld.
  751. * While `example.co.uk` contains 2.
  752. * @return array An array of subdomains.
  753. */
  754. public function subdomains($tldLength = 1) {
  755. $segments = explode('.', $this->host());
  756. return array_slice($segments, 0, -1 * ($tldLength + 1));
  757. }
  758. /**
  759. * Find out which content types the client accepts or check if they accept a
  760. * particular type of content.
  761. *
  762. * #### Get all types:
  763. *
  764. * `$this->request->accepts();`
  765. *
  766. * #### Check for a single type:
  767. *
  768. * `$this->request->accepts('application/json');`
  769. *
  770. * This method will order the returned content types by the preference values indicated
  771. * by the client.
  772. *
  773. * @param string $type The content type to check for. Leave null to get all types a client accepts.
  774. * @return mixed Either an array of all the types the client accepts or a boolean if they accept the
  775. * provided type.
  776. */
  777. public function accepts($type = null) {
  778. $raw = $this->parseAccept();
  779. $accept = array();
  780. foreach ($raw as $types) {
  781. $accept = array_merge($accept, $types);
  782. }
  783. if ($type === null) {
  784. return $accept;
  785. }
  786. return in_array($type, $accept);
  787. }
  788. /**
  789. * Parse the HTTP_ACCEPT header and return a sorted array with content types
  790. * as the keys, and pref values as the values.
  791. *
  792. * Generally you want to use Cake\Network\Request::accept() to get a simple list
  793. * of the accepted content types.
  794. *
  795. * @return array An array of prefValue => array(content/types)
  796. */
  797. public function parseAccept() {
  798. return $this->_parseAcceptWithQualifier($this->header('accept'));
  799. }
  800. /**
  801. * Get the languages accepted by the client, or check if a specific language is accepted.
  802. *
  803. * Get the list of accepted languages:
  804. *
  805. * {{{ \Cake\Network\Request::acceptLanguage(); }}}
  806. *
  807. * Check if a specific language is accepted:
  808. *
  809. * {{{ \Cake\Network\Request::acceptLanguage('es-es'); }}}
  810. *
  811. * @param string $language The language to test.
  812. * @return mixed If a $language is provided, a boolean. Otherwise the array of accepted languages.
  813. */
  814. public function acceptLanguage($language = null) {
  815. $raw = $this->_parseAcceptWithQualifier($this->header('Accept-Language'));
  816. $accept = array();
  817. foreach ($raw as $languages) {
  818. foreach ($languages as &$lang) {
  819. if (strpos($lang, '_')) {
  820. $lang = str_replace('_', '-', $lang);
  821. }
  822. $lang = strtolower($lang);
  823. }
  824. $accept = array_merge($accept, $languages);
  825. }
  826. if ($language === null) {
  827. return $accept;
  828. }
  829. return in_array(strtolower($language), $accept);
  830. }
  831. /**
  832. * Parse Accept* headers with qualifier options.
  833. *
  834. * Only qualifiers will be extracted, any other accept extensions will be
  835. * discarded as they are not frequently used.
  836. *
  837. * @param string $header Header to parse.
  838. * @return array
  839. */
  840. protected function _parseAcceptWithQualifier($header) {
  841. $accept = array();
  842. $header = explode(',', $header);
  843. foreach (array_filter($header) as $value) {
  844. $prefValue = '1.0';
  845. $value = trim($value);
  846. $semiPos = strpos($value, ';');
  847. if ($semiPos !== false) {
  848. $params = explode(';', $value);
  849. $value = trim($params[0]);
  850. foreach ($params as $param) {
  851. $qPos = strpos($param, 'q=');
  852. if ($qPos !== false) {
  853. $prefValue = substr($param, $qPos + 2);
  854. }
  855. }
  856. }
  857. if (!isset($accept[$prefValue])) {
  858. $accept[$prefValue] = array();
  859. }
  860. if ($prefValue) {
  861. $accept[$prefValue][] = $value;
  862. }
  863. }
  864. krsort($accept);
  865. return $accept;
  866. }
  867. /**
  868. * Provides a read accessor for `$this->query`. Allows you
  869. * to use a syntax similar to `CakeSession` for reading URL query data.
  870. *
  871. * @param string $name Query string variable name
  872. * @return mixed The value being read
  873. */
  874. public function query($name) {
  875. return Hash::get($this->query, $name);
  876. }
  877. /**
  878. * Provides a read/write accessor for `$this->data`. Allows you
  879. * to use a syntax similar to `Cake\Model\Datasource\Session` for reading post data.
  880. *
  881. * ## Reading values.
  882. *
  883. * `$request->data('Post.title');`
  884. *
  885. * When reading values you will get `null` for keys/values that do not exist.
  886. *
  887. * ## Writing values
  888. *
  889. * `$request->data('Post.title', 'New post!');`
  890. *
  891. * You can write to any value, even paths/keys that do not exist, and the arrays
  892. * will be created for you.
  893. *
  894. * @param string|null $name Dot separated name of the value to read/write
  895. * @return mixed|$this Either the value being read, or this so you can chain consecutive writes.
  896. */
  897. public function data($name = null) {
  898. $args = func_get_args();
  899. if (count($args) === 2) {
  900. $this->data = Hash::insert($this->data, $name, $args[1]);
  901. return $this;
  902. }
  903. if ($name !== null) {
  904. return Hash::get($this->data, $name);
  905. }
  906. return $this->data;
  907. }
  908. /**
  909. * Safely access the values in $this->params.
  910. *
  911. * @param string $name The name of the parameter to get.
  912. * @return mixed The value of the provided parameter. Will
  913. * return false if the parameter doesn't exist or is falsey.
  914. */
  915. public function param($name) {
  916. $args = func_get_args();
  917. if (count($args) === 2) {
  918. $this->params = Hash::insert($this->params, $name, $args[1]);
  919. return $this;
  920. }
  921. if (!isset($this->params[$name])) {
  922. return Hash::get($this->params, $name, false);
  923. }
  924. return $this->params[$name];
  925. }
  926. /**
  927. * Read data from `php://input`. Useful when interacting with XML or JSON
  928. * request body content.
  929. *
  930. * Getting input with a decoding function:
  931. *
  932. * `$this->request->input('json_decode');`
  933. *
  934. * Getting input using a decoding function, and additional params:
  935. *
  936. * `$this->request->input('Xml::build', array('return' => 'DOMDocument'));`
  937. *
  938. * Any additional parameters are applied to the callback in the order they are given.
  939. *
  940. * @param string $callback A decoding callback that will convert the string data to another
  941. * representation. Leave empty to access the raw input data. You can also
  942. * supply additional parameters for the decoding callback using var args, see above.
  943. * @return string The decoded/processed request data.
  944. */
  945. public function input($callback = null) {
  946. $input = $this->_readInput();
  947. $args = func_get_args();
  948. if (!empty($args)) {
  949. $callback = array_shift($args);
  950. array_unshift($args, $input);
  951. return call_user_func_array($callback, $args);
  952. }
  953. return $input;
  954. }
  955. /**
  956. * Read cookie data from the request's cookie data.
  957. *
  958. * @param string $key The key you want to read.
  959. * @return null|string Either the cookie value, or null if the value doesn't exist.
  960. */
  961. public function cookie($key) {
  962. if (isset($this->cookies[$key])) {
  963. return $this->cookies[$key];
  964. }
  965. return null;
  966. }
  967. /**
  968. * Get/Set value from the request's environment data.
  969. * Fallback to using env() if key not set in $environment property.
  970. *
  971. * @param string $key The key you want to read/write from/to.
  972. * @param string $value Value to set. Default null.
  973. * @return null|string|\Cake\Network\Request Request instance if used as setter,
  974. * if used as getter either the environment value, or null if the value doesn't exist.
  975. */
  976. public function env($key, $value = null) {
  977. if ($value !== null) {
  978. $this->_environment[$key] = $value;
  979. return $this;
  980. }
  981. $key = strtoupper($key);
  982. if (!array_key_exists($key, $this->_environment)) {
  983. $this->_environment[$key] = env($key);
  984. }
  985. return $this->_environment[$key];
  986. }
  987. /**
  988. * Allow only certain HTTP request methods, if the request method does not match
  989. * a 405 error will be shown and the required "Allow" response header will be set.
  990. *
  991. * Example:
  992. *
  993. * $this->request->allowMethod('post');
  994. * or
  995. * $this->request->allowMethod(['post', 'delete']);
  996. *
  997. * If the request would be GET, response header "Allow: POST, DELETE" will be set
  998. * and a 405 error will be returned.
  999. *
  1000. * @param string|array $methods Allowed HTTP request methods.
  1001. * @return bool true
  1002. * @throws \Cake\Error\MethodNotAllowedException
  1003. */
  1004. public function allowMethod($methods) {
  1005. $methods = (array)$methods;
  1006. foreach ($methods as $method) {
  1007. if ($this->is($method)) {
  1008. return true;
  1009. }
  1010. }
  1011. $allowed = strtoupper(implode(', ', $methods));
  1012. $e = new Error\MethodNotAllowedException();
  1013. $e->responseHeader('Allow', $allowed);
  1014. throw $e;
  1015. }
  1016. /**
  1017. * Read data from php://input, mocked in tests.
  1018. *
  1019. * @return string contents of php://input
  1020. */
  1021. protected function _readInput() {
  1022. if (empty($this->_input)) {
  1023. $fh = fopen('php://input', 'r');
  1024. $content = stream_get_contents($fh);
  1025. fclose($fh);
  1026. $this->_input = $content;
  1027. }
  1028. return $this->_input;
  1029. }
  1030. /**
  1031. * Modify data originally from `php://input`. Useful for altering json/xml data
  1032. * in middleware or DispatcherFilters before it gets to RequestHandlerComponent
  1033. *
  1034. * @param string $input A string to replace original parsed data from input()
  1035. * @return void
  1036. */
  1037. public function setInput($input) {
  1038. $this->_input = $input;
  1039. }
  1040. /**
  1041. * Array access read implementation
  1042. *
  1043. * @param string $name Name of the key being accessed.
  1044. * @return mixed
  1045. */
  1046. public function offsetGet($name) {
  1047. if (isset($this->params[$name])) {
  1048. return $this->params[$name];
  1049. }
  1050. if ($name === 'url') {
  1051. return $this->query;
  1052. }
  1053. if ($name === 'data') {
  1054. return $this->data;
  1055. }
  1056. return null;
  1057. }
  1058. /**
  1059. * Array access write implementation
  1060. *
  1061. * @param string $name Name of the key being written
  1062. * @param mixed $value The value being written.
  1063. * @return void
  1064. */
  1065. public function offsetSet($name, $value) {
  1066. $this->params[$name] = $value;
  1067. }
  1068. /**
  1069. * Array access isset() implementation
  1070. *
  1071. * @param string $name thing to check.
  1072. * @return bool
  1073. */
  1074. public function offsetExists($name) {
  1075. return isset($this->params[$name]);
  1076. }
  1077. /**
  1078. * Array access unset() implementation
  1079. *
  1080. * @param string $name Name to unset.
  1081. * @return void
  1082. */
  1083. public function offsetUnset($name) {
  1084. unset($this->params[$name]);
  1085. }
  1086. }