CakeRequest.php 26 KB

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