Request.php 30 KB

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