CakeRequest.php 25 KB

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