Base for a static organization website

CakeRequest.php 32KB

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