CakeRequest.php 22 KB

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