CakeRequest.php 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010
  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 http://www.opensource.org/licenses/mit-license.php MIT License
  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(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 boolean $safe Use safe = false when you think the user might manipulate their HTTP_CLIENT_IP
  357. * header. Setting $safe = false will 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 boolean $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. $forwarded = env('HTTP_X_FORWARDED_HOST');
  387. if ($forwarded) {
  388. $ref = $forwarded;
  389. }
  390. $base = Configure::read('App.fullBaseUrl') . $this->webroot;
  391. if (!empty($ref) && !empty($base)) {
  392. if ($local && strpos($ref, $base) === 0) {
  393. $ref = substr($ref, strlen($base));
  394. if ($ref[0] !== '/') {
  395. $ref = '/' . $ref;
  396. }
  397. return $ref;
  398. } elseif (!$local) {
  399. return $ref;
  400. }
  401. }
  402. return '/';
  403. }
  404. /**
  405. * Missing method handler, handles wrapping older style isAjax() type methods
  406. *
  407. * @param string $name The method called
  408. * @param array $params Array of parameters for the method call
  409. * @return mixed
  410. * @throws CakeException when an invalid method is called.
  411. */
  412. public function __call($name, $params) {
  413. if (strpos($name, 'is') === 0) {
  414. $type = strtolower(substr($name, 2));
  415. return $this->is($type);
  416. }
  417. throw new CakeException(__d('cake_dev', 'Method %s does not exist', $name));
  418. }
  419. /**
  420. * Magic get method allows access to parsed routing parameters directly on the object.
  421. *
  422. * Allows access to `$this->params['controller']` via `$this->controller`
  423. *
  424. * @param string $name The property being accessed.
  425. * @return mixed Either the value of the parameter or null.
  426. */
  427. public function __get($name) {
  428. if (isset($this->params[$name])) {
  429. return $this->params[$name];
  430. }
  431. return null;
  432. }
  433. /**
  434. * Magic isset method allows isset/empty checks
  435. * on routing parameters.
  436. *
  437. * @param string $name The property being accessed.
  438. * @return boolean Existence
  439. */
  440. public function __isset($name) {
  441. return isset($this->params[$name]);
  442. }
  443. /**
  444. * Check whether or not a Request is a certain type.
  445. *
  446. * Uses the built in detection rules as well as additional rules
  447. * defined with CakeRequest::addDetector(). Any detector can be called
  448. * as `is($type)` or `is$Type()`.
  449. *
  450. * @param string|array $type The type of request you want to check. If an array
  451. * this method will return true if the request matches any type.
  452. * @return boolean Whether or not the request is the type you are checking.
  453. */
  454. public function is($type) {
  455. if (is_array($type)) {
  456. $result = array_map(array($this, 'is'), $type);
  457. return count(array_filter($result)) > 0;
  458. }
  459. $type = strtolower($type);
  460. if (!isset($this->_detectors[$type])) {
  461. return false;
  462. }
  463. $detect = $this->_detectors[$type];
  464. if (isset($detect['env'])) {
  465. if (isset($detect['value'])) {
  466. return env($detect['env']) == $detect['value'];
  467. }
  468. if (isset($detect['pattern'])) {
  469. return (bool)preg_match($detect['pattern'], env($detect['env']));
  470. }
  471. if (isset($detect['options'])) {
  472. $pattern = '/' . implode('|', $detect['options']) . '/i';
  473. return (bool)preg_match($pattern, env($detect['env']));
  474. }
  475. }
  476. if (isset($detect['param'])) {
  477. $key = $detect['param'];
  478. if (isset($detect['value'])) {
  479. $value = $detect['value'];
  480. return isset($this->params[$key]) ? $this->params[$key] == $value : false;
  481. }
  482. if (isset($detect['options'])) {
  483. return isset($this->params[$key]) ? in_array($this->params[$key], $detect['options']) : false;
  484. }
  485. }
  486. if (isset($detect['callback']) && is_callable($detect['callback'])) {
  487. return call_user_func($detect['callback'], $this);
  488. }
  489. return false;
  490. }
  491. /**
  492. * Check that a request matches all the given types.
  493. *
  494. * Allows you to test multiple types and union the results.
  495. * See CakeRequest::is() for how to add additional types and the
  496. * built-in types.
  497. *
  498. * @param array $types The types to check.
  499. * @return boolean Success.
  500. * @see CakeRequest::is()
  501. */
  502. public function isAll(array $types) {
  503. $result = array_filter(array_map(array($this, 'is'), $types));
  504. return count($result) === count($types);
  505. }
  506. /**
  507. * Add a new detector to the list of detectors that a request can use.
  508. * There are several different formats and types of detectors that can be set.
  509. *
  510. * ### Environment value comparison
  511. *
  512. * An environment value comparison, compares a value fetched from `env()` to a known value
  513. * the environment value is equality checked against the provided value.
  514. *
  515. * e.g `addDetector('post', array('env' => 'REQUEST_METHOD', 'value' => 'POST'))`
  516. *
  517. * ### Pattern value comparison
  518. *
  519. * Pattern value comparison allows you to compare a value fetched from `env()` to a regular expression.
  520. *
  521. * e.g `addDetector('iphone', array('env' => 'HTTP_USER_AGENT', 'pattern' => '/iPhone/i'));`
  522. *
  523. * ### Option based comparison
  524. *
  525. * Option based comparisons use a list of options to create a regular expression. Subsequent calls
  526. * to add an already defined options detector will merge the options.
  527. *
  528. * e.g `addDetector('mobile', array('env' => 'HTTP_USER_AGENT', 'options' => array('Fennec')));`
  529. *
  530. * ### Callback detectors
  531. *
  532. * Callback detectors allow you to provide a 'callback' type to handle the check. The callback will
  533. * receive the request object as its only parameter.
  534. *
  535. * e.g `addDetector('custom', array('callback' => array('SomeClass', 'somemethod')));`
  536. *
  537. * ### Request parameter detectors
  538. *
  539. * Allows for custom detectors on the request parameters.
  540. *
  541. * e.g `addDetector('requested', array('param' => 'requested', 'value' => 1)`
  542. *
  543. * You can also make parameter detectors that accept multiple values
  544. * using the `options` key. This is useful when you want to check
  545. * if a request parameter is in a list of options.
  546. *
  547. * `addDetector('extension', array('param' => 'ext', 'options' => array('pdf', 'csv'))`
  548. *
  549. * @param string $name The name of the detector.
  550. * @param array $options The options for the detector definition. See above.
  551. * @return void
  552. */
  553. public function addDetector($name, $options) {
  554. $name = strtolower($name);
  555. if (isset($this->_detectors[$name]) && isset($options['options'])) {
  556. $options = Hash::merge($this->_detectors[$name], $options);
  557. }
  558. $this->_detectors[$name] = $options;
  559. }
  560. /**
  561. * Add parameters to the request's parsed parameter set. This will overwrite any existing parameters.
  562. * This modifies the parameters available through `$request->params`.
  563. *
  564. * @param array $params Array of parameters to merge in
  565. * @return The current object, you can chain this method.
  566. */
  567. public function addParams($params) {
  568. $this->params = array_merge($this->params, (array)$params);
  569. return $this;
  570. }
  571. /**
  572. * Add paths to the requests' paths vars. This will overwrite any existing paths.
  573. * Provides an easy way to modify, here, webroot and base.
  574. *
  575. * @param array $paths Array of paths to merge in
  576. * @return CakeRequest the current object, you can chain this method.
  577. */
  578. public function addPaths($paths) {
  579. foreach (array('webroot', 'here', 'base') as $element) {
  580. if (isset($paths[$element])) {
  581. $this->{$element} = $paths[$element];
  582. }
  583. }
  584. return $this;
  585. }
  586. /**
  587. * Get the value of the current requests URL. Will include named parameters and querystring arguments.
  588. *
  589. * @param boolean $base Include the base path, set to false to trim the base path off.
  590. * @return string the current request URL including query string args.
  591. */
  592. public function here($base = true) {
  593. $url = $this->here;
  594. if (!empty($this->query)) {
  595. $url .= '?' . http_build_query($this->query, null, '&');
  596. }
  597. if (!$base) {
  598. $url = preg_replace('/^' . preg_quote($this->base, '/') . '/', '', $url, 1);
  599. }
  600. return $url;
  601. }
  602. /**
  603. * Read an HTTP header from the Request information.
  604. *
  605. * @param string $name Name of the header you want.
  606. * @return mixed Either false on no header being set or the value of the header.
  607. */
  608. public static function header($name) {
  609. $name = 'HTTP_' . strtoupper(str_replace('-', '_', $name));
  610. if (!empty($_SERVER[$name])) {
  611. return $_SERVER[$name];
  612. }
  613. return false;
  614. }
  615. /**
  616. * Get the HTTP method used for this request.
  617. * There are a few ways to specify a method.
  618. *
  619. * - If your client supports it you can use native HTTP methods.
  620. * - You can set the HTTP-X-Method-Override header.
  621. * - You can submit an input with the name `_method`
  622. *
  623. * Any of these 3 approaches can be used to set the HTTP method used
  624. * by CakePHP internally, and will effect the result of this method.
  625. *
  626. * @return string The name of the HTTP method used.
  627. */
  628. public function method() {
  629. return env('REQUEST_METHOD');
  630. }
  631. /**
  632. * Get the host that the request was handled on.
  633. *
  634. * @return string
  635. */
  636. public function host() {
  637. return env('HTTP_HOST');
  638. }
  639. /**
  640. * Get the domain name and include $tldLength segments of the tld.
  641. *
  642. * @param integer $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 integer $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
  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
  799. * @return mixed 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. * Only allow 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->onlyAllow('post', 'delete');
  858. * or
  859. * $this->request->onlyAllow(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 boolean true
  866. * @throws MethodNotAllowedException
  867. */
  868. public function onlyAllow($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. * Read data from php://input, mocked in tests.
  884. *
  885. * @return string contents of php://input
  886. */
  887. protected function _readInput() {
  888. if (empty($this->_input)) {
  889. $fh = fopen('php://input', 'r');
  890. $content = stream_get_contents($fh);
  891. fclose($fh);
  892. $this->_input = $content;
  893. }
  894. return $this->_input;
  895. }
  896. /**
  897. * Array access read implementation
  898. *
  899. * @param string $name Name of the key being accessed.
  900. * @return mixed
  901. */
  902. public function offsetGet($name) {
  903. if (isset($this->params[$name])) {
  904. return $this->params[$name];
  905. }
  906. if ($name === 'url') {
  907. return $this->query;
  908. }
  909. if ($name === 'data') {
  910. return $this->data;
  911. }
  912. return null;
  913. }
  914. /**
  915. * Array access write implementation
  916. *
  917. * @param string $name Name of the key being written
  918. * @param mixed $value The value being written.
  919. * @return void
  920. */
  921. public function offsetSet($name, $value) {
  922. $this->params[$name] = $value;
  923. }
  924. /**
  925. * Array access isset() implementation
  926. *
  927. * @param string $name thing to check.
  928. * @return boolean
  929. */
  930. public function offsetExists($name) {
  931. return isset($this->params[$name]);
  932. }
  933. /**
  934. * Array access unset() implementation
  935. *
  936. * @param string $name Name to unset.
  937. * @return void
  938. */
  939. public function offsetUnset($name) {
  940. unset($this->params[$name]);
  941. }
  942. }