CakeRequest.php 22 KB

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