CakeRequest.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  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. Set::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. $this->data = $_POST;
  151. if (ini_get('magic_quotes_gpc') === '1') {
  152. $this->data = stripslashes_deep($this->data);
  153. }
  154. if (env('HTTP_X_HTTP_METHOD_OVERRIDE')) {
  155. $this->data['_method'] = env('HTTP_X_HTTP_METHOD_OVERRIDE');
  156. }
  157. if (isset($this->data['_method'])) {
  158. if (!empty($_SERVER)) {
  159. $_SERVER['REQUEST_METHOD'] = $this->data['_method'];
  160. } else {
  161. $_ENV['REQUEST_METHOD'] = $this->data['_method'];
  162. }
  163. unset($this->data['_method']);
  164. }
  165. if (isset($this->data['data'])) {
  166. $data = $this->data['data'];
  167. if (count($this->data) <= 1) {
  168. $this->data = $data;
  169. } else {
  170. unset($this->data['data']);
  171. $this->data = Set::merge($this->data, $data);
  172. }
  173. }
  174. }
  175. /**
  176. * Process the GET parameters and move things into the object.
  177. *
  178. * @return void
  179. */
  180. protected function _processGet() {
  181. if (ini_get('magic_quotes_gpc') === '1') {
  182. $query = stripslashes_deep($_GET);
  183. } else {
  184. $query = $_GET;
  185. }
  186. unset($query['/' . str_replace('.', '_', urldecode($this->url))]);
  187. if (strpos($this->url, '?') !== false) {
  188. list(, $querystr) = explode('?', $this->url);
  189. parse_str($querystr, $queryArgs);
  190. $query += $queryArgs;
  191. }
  192. if (isset($this->params['url'])) {
  193. $query = array_merge($this->params['url'], $query);
  194. }
  195. $this->query = $query;
  196. }
  197. /**
  198. * Get the request uri. Looks in PATH_INFO first, as this is the exact value we need prepared
  199. * by PHP. Following that, REQUEST_URI, PHP_SELF, HTTP_X_REWRITE_URL and argv are checked in that order.
  200. * Each of these server variables have the base path, and query strings stripped off
  201. *
  202. * @return string URI The CakePHP request path that is being accessed.
  203. */
  204. protected function _url() {
  205. if (!empty($_SERVER['PATH_INFO'])) {
  206. return $_SERVER['PATH_INFO'];
  207. } elseif (isset($_SERVER['REQUEST_URI'])) {
  208. $uri = $_SERVER['REQUEST_URI'];
  209. } elseif (isset($_SERVER['PHP_SELF']) && isset($_SERVER['SCRIPT_NAME'])) {
  210. $uri = str_replace($_SERVER['SCRIPT_NAME'], '', $_SERVER['PHP_SELF']);
  211. } elseif (isset($_SERVER['HTTP_X_REWRITE_URL'])) {
  212. $uri = $_SERVER['HTTP_X_REWRITE_URL'];
  213. } elseif ($var = env('argv')) {
  214. $uri = $var[0];
  215. }
  216. $base = $this->base;
  217. if (strlen($base) > 0 && strpos($uri, $base) === 0) {
  218. $uri = substr($uri, strlen($base));
  219. }
  220. if (strpos($uri, '?') !== false) {
  221. list($uri) = explode('?', $uri, 2);
  222. }
  223. if (empty($uri) || $uri == '/' || $uri == '//') {
  224. return '/';
  225. }
  226. return $uri;
  227. }
  228. /**
  229. * Returns a base URL and sets the proper webroot
  230. *
  231. * @return string Base URL
  232. */
  233. protected function _base() {
  234. $dir = $webroot = null;
  235. $config = Configure::read('App');
  236. extract($config);
  237. if (!isset($base)) {
  238. $base = $this->base;
  239. }
  240. if ($base !== false) {
  241. $this->webroot = $base . '/';
  242. return $this->base = $base;
  243. }
  244. if (!$baseUrl) {
  245. $base = dirname(env('PHP_SELF'));
  246. if ($webroot === 'webroot' && $webroot === basename($base)) {
  247. $base = dirname($base);
  248. }
  249. if ($dir === 'app' && $dir === basename($base)) {
  250. $base = dirname($base);
  251. }
  252. if ($base === DS || $base === '.') {
  253. $base = '';
  254. }
  255. $this->webroot = $base . '/';
  256. return $this->base = $base;
  257. }
  258. $file = '/' . basename($baseUrl);
  259. $base = dirname($baseUrl);
  260. if ($base === DS || $base === '.') {
  261. $base = '';
  262. }
  263. $this->webroot = $base . '/';
  264. $docRoot = env('DOCUMENT_ROOT');
  265. $docRootContainsWebroot = strpos($docRoot, $dir . '/' . $webroot);
  266. if (!empty($base) || !$docRootContainsWebroot) {
  267. if (strpos($this->webroot, '/' . $dir . '/') === false) {
  268. $this->webroot .= $dir . '/';
  269. }
  270. if (strpos($this->webroot, '/' . $webroot . '/') === false) {
  271. $this->webroot .= $webroot . '/';
  272. }
  273. }
  274. return $this->base = $base . $file;
  275. }
  276. /**
  277. * Process $_FILES and move things into the object.
  278. *
  279. * @return void
  280. */
  281. protected function _processFiles() {
  282. if (isset($_FILES) && is_array($_FILES)) {
  283. foreach ($_FILES as $name => $data) {
  284. if ($name != 'data') {
  285. $this->params['form'][$name] = $data;
  286. }
  287. }
  288. }
  289. if (isset($_FILES['data'])) {
  290. foreach ($_FILES['data'] as $key => $data) {
  291. $this->_processFileData('', $data, $key);
  292. }
  293. }
  294. }
  295. /**
  296. * Recursively walks the FILES array restructuring the data
  297. * into something sane and useable.
  298. *
  299. * @param string $path The dot separated path to insert $data into.
  300. * @param array $data The data to traverse/insert.
  301. * @param string $field The terminal field name, which is the top level key in $_FILES.
  302. * @return void
  303. */
  304. protected function _processFileData($path, $data, $field) {
  305. foreach ($data as $key => $fields) {
  306. $newPath = $key;
  307. if (!empty($path)) {
  308. $newPath = $path . '.' . $key;
  309. }
  310. if (is_array($fields)) {
  311. $this->_processFileData($newPath, $fields, $field);
  312. } else {
  313. $newPath .= '.' . $field;
  314. $this->data = Set::insert($this->data, $newPath, $fields);
  315. }
  316. }
  317. }
  318. /**
  319. * Get the IP the client is using, or says they are using.
  320. *
  321. * @param boolean $safe Use safe = false when you think the user might manipulate their HTTP_CLIENT_IP
  322. * header. Setting $safe = false will will also look at HTTP_X_FORWARDED_FOR
  323. * @return string The client IP.
  324. */
  325. public function clientIp($safe = true) {
  326. if (!$safe && env('HTTP_X_FORWARDED_FOR') != null) {
  327. $ipaddr = preg_replace('/(?:,.*)/', '', env('HTTP_X_FORWARDED_FOR'));
  328. } else {
  329. if (env('HTTP_CLIENT_IP') != null) {
  330. $ipaddr = env('HTTP_CLIENT_IP');
  331. } else {
  332. $ipaddr = env('REMOTE_ADDR');
  333. }
  334. }
  335. if (env('HTTP_CLIENTADDRESS') != null) {
  336. $tmpipaddr = env('HTTP_CLIENTADDRESS');
  337. if (!empty($tmpipaddr)) {
  338. $ipaddr = preg_replace('/(?:,.*)/', '', $tmpipaddr);
  339. }
  340. }
  341. return trim($ipaddr);
  342. }
  343. /**
  344. * Returns the referer that referred this request.
  345. *
  346. * @param boolean $local Attempt to return a local address. Local addresses do not contain hostnames.
  347. * @return string The referring address for this request.
  348. */
  349. public function referer($local = false) {
  350. $ref = env('HTTP_REFERER');
  351. $forwarded = env('HTTP_X_FORWARDED_HOST');
  352. if ($forwarded) {
  353. $ref = $forwarded;
  354. }
  355. $base = '';
  356. if (defined('FULL_BASE_URL')) {
  357. $base = FULL_BASE_URL . $this->webroot;
  358. }
  359. if (!empty($ref) && !empty($base)) {
  360. if ($local && strpos($ref, $base) === 0) {
  361. $ref = substr($ref, strlen($base));
  362. if ($ref[0] != '/') {
  363. $ref = '/' . $ref;
  364. }
  365. return $ref;
  366. } elseif (!$local) {
  367. return $ref;
  368. }
  369. }
  370. return '/';
  371. }
  372. /**
  373. * Missing method handler, handles wrapping older style isAjax() type methods
  374. *
  375. * @param string $name The method called
  376. * @param array $params Array of parameters for the method call
  377. * @return mixed
  378. * @throws CakeException when an invalid method is called.
  379. */
  380. public function __call($name, $params) {
  381. if (strpos($name, 'is') === 0) {
  382. $type = strtolower(substr($name, 2));
  383. return $this->is($type);
  384. }
  385. throw new CakeException(__d('cake_dev', 'Method %s does not exist', $name));
  386. }
  387. /**
  388. * Magic get method allows access to parsed routing parameters directly on the object.
  389. *
  390. * Allows access to `$this->params['controller']` via `$this->controller`
  391. *
  392. * @param string $name The property being accessed.
  393. * @return mixed Either the value of the parameter or null.
  394. */
  395. public function __get($name) {
  396. if (isset($this->params[$name])) {
  397. return $this->params[$name];
  398. }
  399. return null;
  400. }
  401. /**
  402. * Magic isset method allows isset/empty checks
  403. * on routing parameters.
  404. *
  405. * @param string $name The property being accessed.
  406. * @return bool Existence
  407. */
  408. public function __isset($name) {
  409. return isset($this->params[$name]);
  410. }
  411. /**
  412. * Check whether or not a Request is a certain type. Uses the built in detection rules
  413. * as well as additional rules defined with CakeRequest::addDetector(). Any detector can be called
  414. * as `is($type)` or `is$Type()`.
  415. *
  416. * @param string $type The type of request you want to check.
  417. * @return boolean Whether or not the request is the type you are checking.
  418. */
  419. public function is($type) {
  420. $type = strtolower($type);
  421. if (!isset($this->_detectors[$type])) {
  422. return false;
  423. }
  424. $detect = $this->_detectors[$type];
  425. if (isset($detect['env'])) {
  426. if (isset($detect['value'])) {
  427. return env($detect['env']) == $detect['value'];
  428. }
  429. if (isset($detect['pattern'])) {
  430. return (bool)preg_match($detect['pattern'], env($detect['env']));
  431. }
  432. if (isset($detect['options'])) {
  433. $pattern = '/' . implode('|', $detect['options']) . '/i';
  434. return (bool)preg_match($pattern, env($detect['env']));
  435. }
  436. }
  437. if (isset($detect['param'])) {
  438. $key = $detect['param'];
  439. $value = $detect['value'];
  440. return isset($this->params[$key]) ? $this->params[$key] == $value : false;
  441. }
  442. if (isset($detect['callback']) && is_callable($detect['callback'])) {
  443. return call_user_func($detect['callback'], $this);
  444. }
  445. return false;
  446. }
  447. /**
  448. * Add a new detector to the list of detectors that a request can use.
  449. * There are several different formats and types of detectors that can be set.
  450. *
  451. * ### Environment value comparison
  452. *
  453. * An environment value comparison, compares a value fetched from `env()` to a known value
  454. * the environment value is equality checked against the provided value.
  455. *
  456. * e.g `addDetector('post', array('env' => 'REQUEST_METHOD', 'value' => 'POST'))`
  457. *
  458. * ### Pattern value comparison
  459. *
  460. * Pattern value comparison allows you to compare a value fetched from `env()` to a regular expression.
  461. *
  462. * e.g `addDetector('iphone', array('env' => 'HTTP_USER_AGENT', 'pattern' => '/iPhone/i'));`
  463. *
  464. * ### Option based comparison
  465. *
  466. * Option based comparisons use a list of options to create a regular expression. Subsequent calls
  467. * to add an already defined options detector will merge the options.
  468. *
  469. * e.g `addDetector('mobile', array('env' => 'HTTP_USER_AGENT', 'options' => array('Fennec')));`
  470. *
  471. * ### Callback detectors
  472. *
  473. * Callback detectors allow you to provide a 'callback' type to handle the check. The callback will
  474. * receive the request object as its only parameter.
  475. *
  476. * e.g `addDetector('custom', array('callback' => array('SomeClass', 'somemethod')));`
  477. *
  478. * ### Request parameter detectors
  479. *
  480. * Allows for custom detectors on the request parameters.
  481. *
  482. * e.g `addDetector('post', array('param' => 'requested', 'value' => 1)`
  483. *
  484. * @param string $name The name of the detector.
  485. * @param array $options The options for the detector definition. See above.
  486. * @return void
  487. */
  488. public function addDetector($name, $options) {
  489. $name = strtolower($name);
  490. if (isset($this->_detectors[$name]) && isset($options['options'])) {
  491. $options = Set::merge($this->_detectors[$name], $options);
  492. }
  493. $this->_detectors[$name] = $options;
  494. }
  495. /**
  496. * Add parameters to the request's parsed parameter set. This will overwrite any existing parameters.
  497. * This modifies the parameters available through `$request->params`.
  498. *
  499. * @param array $params Array of parameters to merge in
  500. * @return The current object, you can chain this method.
  501. */
  502. public function addParams($params) {
  503. $this->params = array_merge($this->params, (array)$params);
  504. return $this;
  505. }
  506. /**
  507. * Add paths to the requests' paths vars. This will overwrite any existing paths.
  508. * Provides an easy way to modify, here, webroot and base.
  509. *
  510. * @param array $paths Array of paths to merge in
  511. * @return CakeRequest the current object, you can chain this method.
  512. */
  513. public function addPaths($paths) {
  514. foreach (array('webroot', 'here', 'base') as $element) {
  515. if (isset($paths[$element])) {
  516. $this->{$element} = $paths[$element];
  517. }
  518. }
  519. return $this;
  520. }
  521. /**
  522. * Get the value of the current requests url. Will include named parameters and querystring arguments.
  523. *
  524. * @param boolean $base Include the base path, set to false to trim the base path off.
  525. * @return string the current request url including query string args.
  526. */
  527. public function here($base = true) {
  528. $url = $this->here;
  529. if (!empty($this->query)) {
  530. $url .= '?' . http_build_query($this->query, null, '&');
  531. }
  532. if (!$base) {
  533. $url = preg_replace('/^' . preg_quote($this->base, '/') . '/', '', $url, 1);
  534. }
  535. return $url;
  536. }
  537. /**
  538. * Read an HTTP header from the Request information.
  539. *
  540. * @param string $name Name of the header you want.
  541. * @return mixed Either false on no header being set or the value of the header.
  542. */
  543. public static function header($name) {
  544. $name = 'HTTP_' . strtoupper(str_replace('-', '_', $name));
  545. if (!empty($_SERVER[$name])) {
  546. return $_SERVER[$name];
  547. }
  548. return false;
  549. }
  550. /**
  551. * Get the HTTP method used for this request.
  552. * There are a few ways to specify a method.
  553. *
  554. * - If your client supports it you can use native HTTP methods.
  555. * - You can set the HTTP-X-Method-Override header.
  556. * - You can submit an input with the name `_method`
  557. *
  558. * Any of these 3 approaches can be used to set the HTTP method used
  559. * by CakePHP internally, and will effect the result of this method.
  560. *
  561. * @return string The name of the HTTP method used.
  562. */
  563. public function method() {
  564. return env('REQUEST_METHOD');
  565. }
  566. /**
  567. * Get the host that the request was handled on.
  568. *
  569. * @return string
  570. */
  571. public function host() {
  572. return env('HTTP_HOST');
  573. }
  574. /**
  575. * Get the domain name and include $tldLength segments of the tld.
  576. *
  577. * @param integer $tldLength Number of segments your tld contains. For example: `example.com` contains 1 tld.
  578. * While `example.co.uk` contains 2.
  579. * @return string Domain name without subdomains.
  580. */
  581. public function domain($tldLength = 1) {
  582. $segments = explode('.', $this->host());
  583. $domain = array_slice($segments, -1 * ($tldLength + 1));
  584. return implode('.', $domain);
  585. }
  586. /**
  587. * Get the subdomains for a host.
  588. *
  589. * @param integer $tldLength Number of segments your tld contains. For example: `example.com` contains 1 tld.
  590. * While `example.co.uk` contains 2.
  591. * @return array of subdomains.
  592. */
  593. public function subdomains($tldLength = 1) {
  594. $segments = explode('.', $this->host());
  595. return array_slice($segments, 0, -1 * ($tldLength + 1));
  596. }
  597. /**
  598. * Find out which content types the client accepts or check if they accept a
  599. * particular type of content.
  600. *
  601. * #### Get all types:
  602. *
  603. * `$this->request->accepts();`
  604. *
  605. * #### Check for a single type:
  606. *
  607. * `$this->request->accepts('json');`
  608. *
  609. * This method will order the returned content types by the preference values indicated
  610. * by the client.
  611. *
  612. * @param string $type The content type to check for. Leave null to get all types a client accepts.
  613. * @return mixed Either an array of all the types the client accepts or a boolean if they accept the
  614. * provided type.
  615. */
  616. public function accepts($type = null) {
  617. $raw = $this->parseAccept();
  618. $accept = array();
  619. foreach ($raw as $value => $types) {
  620. $accept = array_merge($accept, $types);
  621. }
  622. if ($type === null) {
  623. return $accept;
  624. }
  625. return in_array($type, $accept);
  626. }
  627. /**
  628. * Parse the HTTP_ACCEPT header and return a sorted array with content types
  629. * as the keys, and pref values as the values.
  630. *
  631. * Generally you want to use CakeRequest::accept() to get a simple list
  632. * of the accepted content types.
  633. *
  634. * @return array An array of prefValue => array(content/types)
  635. */
  636. public function parseAccept() {
  637. $accept = array();
  638. $header = explode(',', $this->header('accept'));
  639. foreach (array_filter($header) as $value) {
  640. $prefPos = strpos($value, ';');
  641. if ($prefPos !== false) {
  642. $prefValue = substr($value, strpos($value, '=') + 1);
  643. $value = trim(substr($value, 0, $prefPos));
  644. } else {
  645. $prefValue = '1.0';
  646. $value = trim($value);
  647. }
  648. if (!isset($accept[$prefValue])) {
  649. $accept[$prefValue] = array();
  650. }
  651. if ($prefValue) {
  652. $accept[$prefValue][] = $value;
  653. }
  654. }
  655. krsort($accept);
  656. return $accept;
  657. }
  658. /**
  659. * Get the languages accepted by the client, or check if a specific language is accepted.
  660. *
  661. * Get the list of accepted languages:
  662. *
  663. * {{{ CakeRequest::acceptLanguage(); }}}
  664. *
  665. * Check if a specific language is accepted:
  666. *
  667. * {{{ CakeRequest::acceptLanguage('es-es'); }}}
  668. *
  669. * @param string $language The language to test.
  670. * @return If a $language is provided, a boolean. Otherwise the array of accepted languages.
  671. */
  672. public static function acceptLanguage($language = null) {
  673. $accepts = preg_split('/[;,]/', self::header('Accept-Language'));
  674. foreach ($accepts as &$accept) {
  675. $accept = strtolower($accept);
  676. if (strpos($accept, '_') !== false) {
  677. $accept = str_replace('_', '-', $accept);
  678. }
  679. }
  680. if ($language === null) {
  681. return $accepts;
  682. }
  683. return in_array($language, $accepts);
  684. }
  685. /**
  686. * Provides a read/write accessor for `$this->data`. Allows you
  687. * to use a syntax similar to `CakeSession` for reading post data.
  688. *
  689. * ## Reading values.
  690. *
  691. * `$request->data('Post.title');`
  692. *
  693. * When reading values you will get `null` for keys/values that do not exist.
  694. *
  695. * ## Writing values
  696. *
  697. * `$request->data('Post.title', 'New post!');`
  698. *
  699. * You can write to any value, even paths/keys that do not exist, and the arrays
  700. * will be created for you.
  701. *
  702. * @param string $name,... Dot separated name of the value to read/write
  703. * @return mixed Either the value being read, or this so you can chain consecutive writes.
  704. */
  705. public function data($name) {
  706. $args = func_get_args();
  707. if (count($args) == 2) {
  708. $this->data = Set::insert($this->data, $name, $args[1]);
  709. return $this;
  710. }
  711. return Set::classicExtract($this->data, $name);
  712. }
  713. /**
  714. * Read data from `php://input`. Useful when interacting with XML or JSON
  715. * request body content.
  716. *
  717. * Getting input with a decoding function:
  718. *
  719. * `$this->request->input('json_decode');`
  720. *
  721. * Getting input using a decoding function, and additional params:
  722. *
  723. * `$this->request->input('Xml::build', array('return' => 'DOMDocument'));`
  724. *
  725. * Any additional parameters are applied to the callback in the order they are given.
  726. *
  727. * @param string $callback A decoding callback that will convert the string data to another
  728. * representation. Leave empty to access the raw input data. You can also
  729. * supply additional parameters for the decoding callback using var args, see above.
  730. * @return The decoded/processed request data.
  731. */
  732. public function input($callback = null) {
  733. $input = $this->_readInput();
  734. $args = func_get_args();
  735. if (!empty($args)) {
  736. $callback = array_shift($args);
  737. array_unshift($args, $input);
  738. return call_user_func_array($callback, $args);
  739. }
  740. return $input;
  741. }
  742. /**
  743. * Read data from php://input, mocked in tests.
  744. *
  745. * @return string contents of php://input
  746. */
  747. protected function _readInput() {
  748. if (empty($this->_input)) {
  749. $fh = fopen('php://input', 'r');
  750. $content = stream_get_contents($fh);
  751. fclose($fh);
  752. $this->_input = $content;
  753. }
  754. return $this->_input;
  755. }
  756. /**
  757. * Array access read implementation
  758. *
  759. * @param string $name Name of the key being accessed.
  760. * @return mixed
  761. */
  762. public function offsetGet($name) {
  763. if (isset($this->params[$name])) {
  764. return $this->params[$name];
  765. }
  766. if ($name == 'url') {
  767. return $this->query;
  768. }
  769. if ($name == 'data') {
  770. return $this->data;
  771. }
  772. return null;
  773. }
  774. /**
  775. * Array access write implementation
  776. *
  777. * @param string $name Name of the key being written
  778. * @param mixed $value The value being written.
  779. * @return void
  780. */
  781. public function offsetSet($name, $value) {
  782. $this->params[$name] = $value;
  783. }
  784. /**
  785. * Array access isset() implementation
  786. *
  787. * @param string $name thing to check.
  788. * @return boolean
  789. */
  790. public function offsetExists($name) {
  791. return isset($this->params[$name]);
  792. }
  793. /**
  794. * Array access unset() implementation
  795. *
  796. * @param string $name Name to unset.
  797. * @return void
  798. */
  799. public function offsetUnset($name) {
  800. unset($this->params[$name]);
  801. }
  802. }