CakeRequest.php 26 KB

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