CakeRequest.php 26 KB

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