CakeRequest.php 27 KB

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