CakeRequest.php 29 KB

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