CakeRequest.php 29 KB

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