Request.php 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 2.0.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Network;
  16. use ArrayAccess;
  17. use BadMethodCallException;
  18. use Cake\Core\Configure;
  19. use Cake\Network\Exception\MethodNotAllowedException;
  20. use Cake\Utility\Hash;
  21. /**
  22. * A class that helps wrap Request information and particulars about a single request.
  23. * Provides methods commonly used to introspect on the request headers and request body.
  24. *
  25. * Has both an Array and Object interface. You can access framework parameters using indexes:
  26. *
  27. * `$request['controller']` or `$request->controller`.
  28. */
  29. class Request implements ArrayAccess
  30. {
  31. /**
  32. * Array of parameters parsed from the URL.
  33. *
  34. * @var array
  35. */
  36. public $params = [
  37. 'plugin' => null,
  38. 'controller' => null,
  39. 'action' => null,
  40. '_ext' => null,
  41. 'pass' => []
  42. ];
  43. /**
  44. * Array of POST data. Will contain form data as well as uploaded files.
  45. * In PUT/PATCH/DELETE requests this property will contain the form-urlencoded
  46. * data.
  47. *
  48. * @var array
  49. */
  50. public $data = [];
  51. /**
  52. * Array of querystring arguments
  53. *
  54. * @var array
  55. */
  56. public $query = [];
  57. /**
  58. * Array of cookie data.
  59. *
  60. * @var array
  61. */
  62. public $cookies = [];
  63. /**
  64. * Array of environment data.
  65. *
  66. * @var array
  67. */
  68. protected $_environment = [];
  69. /**
  70. * The URL string used for the request.
  71. *
  72. * @var string
  73. */
  74. public $url;
  75. /**
  76. * Base URL path.
  77. *
  78. * @var string
  79. */
  80. public $base;
  81. /**
  82. * webroot path segment for the request.
  83. *
  84. * @var string
  85. */
  86. public $webroot = '/';
  87. /**
  88. * The full address to the current request
  89. *
  90. * @var string
  91. */
  92. public $here;
  93. /**
  94. * Whether or not to trust HTTP_X headers set by most load balancers.
  95. * Only set to true if your application runs behind load balancers/proxies
  96. * that you control.
  97. *
  98. * @var bool
  99. */
  100. public $trustProxy = false;
  101. /**
  102. * The built in detectors used with `is()` can be modified with `addDetector()`.
  103. *
  104. * There are several ways to specify a detector, see Cake\Network\Request::addDetector() for the
  105. * various formats and ways to define detectors.
  106. *
  107. * @var array
  108. */
  109. protected static $_detectors = [
  110. 'get' => ['env' => 'REQUEST_METHOD', 'value' => 'GET'],
  111. 'post' => ['env' => 'REQUEST_METHOD', 'value' => 'POST'],
  112. 'put' => ['env' => 'REQUEST_METHOD', 'value' => 'PUT'],
  113. 'patch' => ['env' => 'REQUEST_METHOD', 'value' => 'PATCH'],
  114. 'delete' => ['env' => 'REQUEST_METHOD', 'value' => 'DELETE'],
  115. 'head' => ['env' => 'REQUEST_METHOD', 'value' => 'HEAD'],
  116. 'options' => ['env' => 'REQUEST_METHOD', 'value' => 'OPTIONS'],
  117. 'ssl' => ['env' => 'HTTPS', 'options' => [1, 'on']],
  118. 'ajax' => ['env' => 'HTTP_X_REQUESTED_WITH', 'value' => 'XMLHttpRequest'],
  119. 'flash' => ['env' => 'HTTP_USER_AGENT', 'pattern' => '/^(Shockwave|Adobe) Flash/'],
  120. 'requested' => ['param' => 'requested', 'value' => 1],
  121. 'json' => ['accept' => ['application/json'], 'param' => '_ext', 'value' => 'json'],
  122. 'xml' => ['accept' => ['application/xml', 'text/xml'], 'param' => '_ext', 'value' => 'xml'],
  123. ];
  124. /**
  125. * Instance cache for results of is(something) calls
  126. *
  127. * @var array
  128. */
  129. protected $_detectorCache = [];
  130. /**
  131. * Copy of php://input. Since this stream can only be read once in most SAPI's
  132. * keep a copy of it so users don't need to know about that detail.
  133. *
  134. * @var string
  135. */
  136. protected $_input = '';
  137. /**
  138. * Instance of a Session object relative to this request
  139. *
  140. * @var \Cake\Network\Session
  141. */
  142. protected $_session;
  143. /**
  144. * Wrapper method to create a new request from PHP superglobals.
  145. *
  146. * Uses the $_GET, $_POST, $_FILES, $_COOKIE, $_SERVER, $_ENV and php://input data to construct
  147. * the request.
  148. *
  149. * @return \Cake\Network\Request
  150. */
  151. public static function createFromGlobals()
  152. {
  153. list($base, $webroot) = static::_base();
  154. $sessionConfig = (array)Configure::read('Session') + [
  155. 'defaults' => 'php',
  156. 'cookiePath' => $webroot
  157. ];
  158. $config = [
  159. 'query' => $_GET,
  160. 'post' => $_POST,
  161. 'files' => $_FILES,
  162. 'cookies' => $_COOKIE,
  163. 'environment' => $_SERVER + $_ENV,
  164. 'base' => $base,
  165. 'webroot' => $webroot,
  166. 'session' => Session::create($sessionConfig)
  167. ];
  168. $config['url'] = static::_url($config);
  169. return new static($config);
  170. }
  171. /**
  172. * Create a new request object.
  173. *
  174. * You can supply the data as either an array or as a string. If you use
  175. * a string you can only supply the URL for the request. Using an array will
  176. * let you provide the following keys:
  177. *
  178. * - `post` POST data or non query string data
  179. * - `query` Additional data from the query string.
  180. * - `files` Uploaded file data formatted like $_FILES.
  181. * - `cookies` Cookies for this request.
  182. * - `environment` $_SERVER and $_ENV data.
  183. * - `url` The URL without the base path for the request.
  184. * - `base` The base URL for the request.
  185. * - `webroot` The webroot directory for the request.
  186. * - `input` The data that would come from php://input this is useful for simulating
  187. * - `session` An instance of a Session object
  188. * requests with put, patch or delete data.
  189. *
  190. * @param string|array $config An array of request data to create a request with.
  191. */
  192. public function __construct($config = [])
  193. {
  194. if (is_string($config)) {
  195. $config = ['url' => $config];
  196. }
  197. $config += [
  198. 'params' => $this->params,
  199. 'query' => [],
  200. 'post' => [],
  201. 'files' => [],
  202. 'cookies' => [],
  203. 'environment' => [],
  204. 'url' => '',
  205. 'base' => '',
  206. 'webroot' => '',
  207. 'input' => null,
  208. ];
  209. $this->_setConfig($config);
  210. }
  211. /**
  212. * Process the config/settings data into properties.
  213. *
  214. * @param array $config The config data to use.
  215. * @return void
  216. */
  217. protected function _setConfig($config)
  218. {
  219. if (!empty($config['url']) && $config['url'][0] === '/') {
  220. $config['url'] = substr($config['url'], 1);
  221. }
  222. if (empty($config['session'])) {
  223. $config['session'] = new Session([
  224. 'cookiePath' => $config['base']
  225. ]);
  226. }
  227. $this->url = $config['url'];
  228. $this->base = $config['base'];
  229. $this->cookies = $config['cookies'];
  230. $this->here = $this->base . '/' . $this->url;
  231. $this->webroot = $config['webroot'];
  232. $this->_environment = $config['environment'];
  233. if (isset($config['input'])) {
  234. $this->_input = $config['input'];
  235. }
  236. $config['post'] = $this->_processPost($config['post']);
  237. $this->data = $this->_processFiles($config['post'], $config['files']);
  238. $this->query = $this->_processGet($config['query']);
  239. $this->params = $config['params'];
  240. $this->_session = $config['session'];
  241. }
  242. /**
  243. * Sets the REQUEST_METHOD environment variable based on the simulated _method
  244. * HTTP override value. The 'ORIGINAL_REQUEST_METHOD' is also preserved, if you
  245. * want the read the non-simulated HTTP method the client used.
  246. *
  247. * @param array $data Array of post data.
  248. * @return array
  249. */
  250. protected function _processPost($data)
  251. {
  252. $method = $this->env('REQUEST_METHOD');
  253. $override = false;
  254. if (in_array($method, ['PUT', 'DELETE', 'PATCH']) &&
  255. strpos($this->contentType(), 'application/x-www-form-urlencoded') === 0
  256. ) {
  257. $data = $this->input();
  258. parse_str($data, $data);
  259. }
  260. if ($this->env('HTTP_X_HTTP_METHOD_OVERRIDE')) {
  261. $data['_method'] = $this->env('HTTP_X_HTTP_METHOD_OVERRIDE');
  262. $override = true;
  263. }
  264. $this->_environment['ORIGINAL_REQUEST_METHOD'] = $method;
  265. if (isset($data['_method'])) {
  266. $this->_environment['REQUEST_METHOD'] = $data['_method'];
  267. unset($data['_method']);
  268. $override = true;
  269. }
  270. if ($override && !in_array($this->_environment['REQUEST_METHOD'], ['PUT', 'POST', 'DELETE', 'PATCH'])) {
  271. $data = [];
  272. }
  273. return $data;
  274. }
  275. /**
  276. * Process the GET parameters and move things into the object.
  277. *
  278. * @param array $query The array to which the parsed keys/values are being added.
  279. * @return array An array containing the parsed querystring keys/values.
  280. */
  281. protected function _processGet($query)
  282. {
  283. $unsetUrl = '/' . str_replace(['.', ' '], '_', urldecode($this->url));
  284. unset($query[$unsetUrl]);
  285. unset($query[$this->base . $unsetUrl]);
  286. if (strpos($this->url, '?') !== false) {
  287. list(, $querystr) = explode('?', $this->url);
  288. parse_str($querystr, $queryArgs);
  289. $query += $queryArgs;
  290. }
  291. return $query;
  292. }
  293. /**
  294. * Get the request uri. Looks in PATH_INFO first, as this is the exact value we need prepared
  295. * by PHP. Following that, REQUEST_URI, PHP_SELF, HTTP_X_REWRITE_URL and argv are checked in that order.
  296. * Each of these server variables have the base path, and query strings stripped off
  297. *
  298. * @param array $config Configuration to set.
  299. * @return string URI The CakePHP request path that is being accessed.
  300. */
  301. protected static function _url($config)
  302. {
  303. if (!empty($_SERVER['PATH_INFO'])) {
  304. return $_SERVER['PATH_INFO'];
  305. }
  306. if (isset($_SERVER['REQUEST_URI']) && strpos($_SERVER['REQUEST_URI'], '://') === false) {
  307. $uri = $_SERVER['REQUEST_URI'];
  308. } elseif (isset($_SERVER['REQUEST_URI'])) {
  309. $qPosition = strpos($_SERVER['REQUEST_URI'], '?');
  310. if ($qPosition !== false && strpos($_SERVER['REQUEST_URI'], '://') > $qPosition) {
  311. $uri = $_SERVER['REQUEST_URI'];
  312. } else {
  313. $uri = substr($_SERVER['REQUEST_URI'], strlen(Configure::read('App.fullBaseUrl')));
  314. }
  315. } elseif (isset($_SERVER['PHP_SELF'], $_SERVER['SCRIPT_NAME'])) {
  316. $uri = str_replace($_SERVER['SCRIPT_NAME'], '', $_SERVER['PHP_SELF']);
  317. } elseif (isset($_SERVER['HTTP_X_REWRITE_URL'])) {
  318. $uri = $_SERVER['HTTP_X_REWRITE_URL'];
  319. } elseif ($var = env('argv')) {
  320. $uri = $var[0];
  321. }
  322. $base = $config['base'];
  323. if (strlen($base) > 0 && strpos($uri, $base) === 0) {
  324. $uri = substr($uri, strlen($base));
  325. }
  326. if (strpos($uri, '?') !== false) {
  327. list($uri) = explode('?', $uri, 2);
  328. }
  329. if (empty($uri) || $uri === '/' || $uri === '//' || $uri === '/index.php') {
  330. $uri = '/';
  331. }
  332. $endsWithIndex = '/webroot/index.php';
  333. $endsWithLength = strlen($endsWithIndex);
  334. if (strlen($uri) >= $endsWithLength &&
  335. substr($uri, -$endsWithLength) === $endsWithIndex
  336. ) {
  337. $uri = '/';
  338. }
  339. return $uri;
  340. }
  341. /**
  342. * Returns a base URL and sets the proper webroot
  343. *
  344. * If CakePHP is called with index.php in the URL even though
  345. * URL Rewriting is activated (and thus not needed) it swallows
  346. * the unnecessary part from $base to prevent issue #3318.
  347. *
  348. * @return array Base URL, webroot dir ending in /
  349. */
  350. protected static function _base()
  351. {
  352. $base = $webroot = $baseUrl = null;
  353. $config = Configure::read('App');
  354. extract($config);
  355. if ($base !== false && $base !== null) {
  356. return [$base, $base . '/'];
  357. }
  358. if (!$baseUrl) {
  359. $base = dirname(env('PHP_SELF'));
  360. // Clean up additional / which cause following code to fail..
  361. $base = preg_replace('#/+#', '/', $base);
  362. $indexPos = strpos($base, '/' . $webroot . '/index.php');
  363. if ($indexPos !== false) {
  364. $base = substr($base, 0, $indexPos) . '/' . $webroot;
  365. }
  366. if ($webroot === basename($base)) {
  367. $base = dirname($base);
  368. }
  369. if ($base === DIRECTORY_SEPARATOR || $base === '.') {
  370. $base = '';
  371. }
  372. $base = implode('/', array_map('rawurlencode', explode('/', $base)));
  373. return [$base, $base . '/'];
  374. }
  375. $file = '/' . basename($baseUrl);
  376. $base = dirname($baseUrl);
  377. if ($base === DIRECTORY_SEPARATOR || $base === '.') {
  378. $base = '';
  379. }
  380. $webrootDir = $base . '/';
  381. $docRoot = env('DOCUMENT_ROOT');
  382. $docRootContainsWebroot = strpos($docRoot, $webroot);
  383. if (!empty($base) || !$docRootContainsWebroot) {
  384. if (strpos($webrootDir, '/' . $webroot . '/') === false) {
  385. $webrootDir .= $webroot . '/';
  386. }
  387. }
  388. return [$base . $file, $webrootDir];
  389. }
  390. /**
  391. * Process uploaded files and move things onto the post data.
  392. *
  393. * @param array $post Post data to merge files onto.
  394. * @param array $files Uploaded files to merge in.
  395. * @return array merged post + file data.
  396. */
  397. protected function _processFiles($post, $files)
  398. {
  399. if (is_array($files)) {
  400. foreach ($files as $key => $data) {
  401. if (isset($data['tmp_name']) && is_string($data['tmp_name'])) {
  402. $post[$key] = $data;
  403. } else {
  404. $keyData = isset($post[$key]) ? $post[$key] : [];
  405. $post[$key] = $this->_processFileData($keyData, $data);
  406. }
  407. }
  408. }
  409. return $post;
  410. }
  411. /**
  412. * Recursively walks the FILES array restructuring the data
  413. * into something sane and usable.
  414. *
  415. * @param array $data The data being built
  416. * @param array $post The post data being traversed
  417. * @param string $path The dot separated path to insert $data into.
  418. * @param string $field The terminal field in the path. This is one of the
  419. * $_FILES properties e.g. name, tmp_name, size, error
  420. * @return array The restructured FILES data
  421. */
  422. protected function _processFileData($data, $post, $path = '', $field = '')
  423. {
  424. foreach ($post as $key => $fields) {
  425. $newField = $field;
  426. $newPath = $path;
  427. if ($path === '' && $newField === '') {
  428. $newField = $key;
  429. }
  430. if ($field === $newField) {
  431. $newPath .= '.' . $key;
  432. }
  433. if (is_array($fields)) {
  434. $data = $this->_processFileData($data, $fields, $newPath, $newField);
  435. } else {
  436. $newPath = trim($newPath . '.' . $field, '.');
  437. $data = Hash::insert($data, $newPath, $fields);
  438. }
  439. }
  440. return $data;
  441. }
  442. /**
  443. * Get the content type used in this request.
  444. *
  445. * @return string
  446. */
  447. public function contentType()
  448. {
  449. $type = $this->env('CONTENT_TYPE');
  450. if ($type) {
  451. return $type;
  452. }
  453. return $this->env('HTTP_CONTENT_TYPE');
  454. }
  455. /**
  456. * Returns the instance of the Session object for this request
  457. *
  458. * If a session object is passed as first argument it will be set as
  459. * the session to use for this request
  460. *
  461. * @param \Cake\Network\Session|null $session the session object to use
  462. * @return \Cake\Network\Session
  463. */
  464. public function session(Session $session = null)
  465. {
  466. if ($session === null) {
  467. return $this->_session;
  468. }
  469. return $this->_session = $session;
  470. }
  471. /**
  472. * Get the IP the client is using, or says they are using.
  473. *
  474. * @return string The client IP.
  475. */
  476. public function clientIp()
  477. {
  478. if ($this->trustProxy && $this->env('HTTP_X_FORWARDED_FOR')) {
  479. $ipaddr = preg_replace('/(?:,.*)/', '', $this->env('HTTP_X_FORWARDED_FOR'));
  480. } else {
  481. if ($this->env('HTTP_CLIENT_IP')) {
  482. $ipaddr = $this->env('HTTP_CLIENT_IP');
  483. } else {
  484. $ipaddr = $this->env('REMOTE_ADDR');
  485. }
  486. }
  487. if ($this->env('HTTP_CLIENTADDRESS')) {
  488. $tmpipaddr = $this->env('HTTP_CLIENTADDRESS');
  489. if (!empty($tmpipaddr)) {
  490. $ipaddr = preg_replace('/(?:,.*)/', '', $tmpipaddr);
  491. }
  492. }
  493. return trim($ipaddr);
  494. }
  495. /**
  496. * Returns the referer that referred this request.
  497. *
  498. * @param bool $local Attempt to return a local address.
  499. * Local addresses do not contain hostnames.
  500. * @return string The referring address for this request.
  501. */
  502. public function referer($local = false)
  503. {
  504. $ref = $this->env('HTTP_REFERER');
  505. $base = Configure::read('App.fullBaseUrl') . $this->webroot;
  506. if (!empty($ref) && !empty($base)) {
  507. if ($local && strpos($ref, $base) === 0) {
  508. $ref = substr($ref, strlen($base));
  509. if ($ref[0] !== '/') {
  510. $ref = '/' . $ref;
  511. }
  512. return $ref;
  513. }
  514. if (!$local) {
  515. return $ref;
  516. }
  517. }
  518. return '/';
  519. }
  520. /**
  521. * Missing method handler, handles wrapping older style isAjax() type methods
  522. *
  523. * @param string $name The method called
  524. * @param array $params Array of parameters for the method call
  525. * @return mixed
  526. * @throws \BadMethodCallException when an invalid method is called.
  527. */
  528. public function __call($name, $params)
  529. {
  530. if (strpos($name, 'is') === 0) {
  531. $type = strtolower(substr($name, 2));
  532. return $this->is($type);
  533. }
  534. throw new BadMethodCallException(sprintf('Method %s does not exist', $name));
  535. }
  536. /**
  537. * Magic get method allows access to parsed routing parameters directly on the object.
  538. *
  539. * Allows access to `$this->params['controller']` via `$this->controller`
  540. *
  541. * @param string $name The property being accessed.
  542. * @return mixed Either the value of the parameter or null.
  543. */
  544. public function __get($name)
  545. {
  546. if (isset($this->params[$name])) {
  547. return $this->params[$name];
  548. }
  549. return null;
  550. }
  551. /**
  552. * Magic isset method allows isset/empty checks
  553. * on routing parameters.
  554. *
  555. * @param string $name The property being accessed.
  556. * @return bool Existence
  557. */
  558. public function __isset($name)
  559. {
  560. return isset($this->params[$name]);
  561. }
  562. /**
  563. * Check whether or not a Request is a certain type.
  564. *
  565. * Uses the built in detection rules as well as additional rules
  566. * defined with Cake\Network\CakeRequest::addDetector(). Any detector can be called
  567. * as `is($type)` or `is$Type()`.
  568. *
  569. * @param string|array $type The type of request you want to check. If an array
  570. * this method will return true if the request matches any type.
  571. * @return bool Whether or not the request is the type you are checking.
  572. */
  573. public function is($type)
  574. {
  575. if (is_array($type)) {
  576. $result = array_map([$this, 'is'], $type);
  577. return count(array_filter($result)) > 0;
  578. }
  579. $type = strtolower($type);
  580. if (!isset(static::$_detectors[$type])) {
  581. return false;
  582. }
  583. if (!isset($this->_detectorCache[$type])) {
  584. $this->_detectorCache[$type] = $this->_is($type);
  585. }
  586. return $this->_detectorCache[$type];
  587. }
  588. /**
  589. * Clears the instance detector cache, used by the is() function
  590. *
  591. * @return void
  592. */
  593. public function clearDetectorCache()
  594. {
  595. $this->_detectorCache = [];
  596. }
  597. /**
  598. * Worker for the public is() function
  599. *
  600. * @param string|array $type The type of request you want to check. If an array
  601. * this method will return true if the request matches any type.
  602. * @return bool Whether or not the request is the type you are checking.
  603. */
  604. protected function _is($type)
  605. {
  606. $detect = static::$_detectors[$type];
  607. if (is_callable($detect)) {
  608. return call_user_func($detect, $this);
  609. }
  610. if (isset($detect['env']) && $this->_environmentDetector($detect)) {
  611. return true;
  612. }
  613. if (isset($detect['header']) && $this->_headerDetector($detect)) {
  614. return true;
  615. }
  616. if (isset($detect['accept']) && $this->_acceptHeaderDetector($detect)) {
  617. return true;
  618. }
  619. if (isset($detect['param']) && $this->_paramDetector($detect)) {
  620. return true;
  621. }
  622. return false;
  623. }
  624. /**
  625. * Detects if a specific accept header is present.
  626. *
  627. * @param array $detect Detector options array.
  628. * @return bool Whether or not the request is the type you are checking.
  629. */
  630. protected function _acceptHeaderDetector($detect)
  631. {
  632. $acceptHeaders = explode(',', $this->env('HTTP_ACCEPT'));
  633. foreach ($detect['accept'] as $header) {
  634. if (in_array($header, $acceptHeaders)) {
  635. return true;
  636. }
  637. }
  638. return false;
  639. }
  640. /**
  641. * Detects if a specific header is present.
  642. *
  643. * @param array $detect Detector options array.
  644. * @return bool Whether or not the request is the type you are checking.
  645. */
  646. protected function _headerDetector($detect)
  647. {
  648. foreach ($detect['header'] as $header => $value) {
  649. $header = $this->env('http_' . $header);
  650. if ($header !== null) {
  651. if (!is_string($value) && !is_bool($value) && is_callable($value)) {
  652. return call_user_func($value, $header);
  653. }
  654. return ($header === $value);
  655. }
  656. }
  657. return false;
  658. }
  659. /**
  660. * Detects if a specific request parameter is present.
  661. *
  662. * @param array $detect Detector options array.
  663. * @return bool Whether or not the request is the type you are checking.
  664. */
  665. protected function _paramDetector($detect)
  666. {
  667. $key = $detect['param'];
  668. if (isset($detect['value'])) {
  669. $value = $detect['value'];
  670. return isset($this->params[$key]) ? $this->params[$key] == $value : false;
  671. }
  672. if (isset($detect['options'])) {
  673. return isset($this->params[$key]) ? in_array($this->params[$key], $detect['options']) : false;
  674. }
  675. return false;
  676. }
  677. /**
  678. * Detects if a specific environment variable is present.
  679. *
  680. * @param array $detect Detector options array.
  681. * @return bool Whether or not the request is the type you are checking.
  682. */
  683. protected function _environmentDetector($detect)
  684. {
  685. if (isset($detect['env'])) {
  686. if (isset($detect['value'])) {
  687. return $this->env($detect['env']) == $detect['value'];
  688. }
  689. if (isset($detect['pattern'])) {
  690. return (bool)preg_match($detect['pattern'], $this->env($detect['env']));
  691. }
  692. if (isset($detect['options'])) {
  693. $pattern = '/' . implode('|', $detect['options']) . '/i';
  694. return (bool)preg_match($pattern, $this->env($detect['env']));
  695. }
  696. }
  697. return false;
  698. }
  699. /**
  700. * Check that a request matches all the given types.
  701. *
  702. * Allows you to test multiple types and union the results.
  703. * See Request::is() for how to add additional types and the
  704. * built-in types.
  705. *
  706. * @param array $types The types to check.
  707. * @return bool Success.
  708. * @see \Cake\Network\Request::is()
  709. */
  710. public function isAll(array $types)
  711. {
  712. $result = array_filter(array_map([$this, 'is'], $types));
  713. return count($result) === count($types);
  714. }
  715. /**
  716. * Add a new detector to the list of detectors that a request can use.
  717. * There are several different formats and types of detectors that can be set.
  718. *
  719. * ### Callback detectors
  720. *
  721. * Callback detectors allow you to provide a callable to handle the check.
  722. * The callback will receive the request object as its only parameter.
  723. *
  724. * ```
  725. * addDetector('custom', function ($request) { //Return a boolean });
  726. * addDetector('custom', ['SomeClass', 'somemethod']);
  727. * ```
  728. *
  729. * ### Environment value comparison
  730. *
  731. * An environment value comparison, compares a value fetched from `env()` to a known value
  732. * the environment value is equality checked against the provided value.
  733. *
  734. * e.g `addDetector('post', ['env' => 'REQUEST_METHOD', 'value' => 'POST'])`
  735. *
  736. * ### Pattern value comparison
  737. *
  738. * Pattern value comparison allows you to compare a value fetched from `env()` to a regular expression.
  739. *
  740. * ```
  741. * addDetector('iphone', ['env' => 'HTTP_USER_AGENT', 'pattern' => '/iPhone/i']);
  742. * ```
  743. *
  744. * ### Option based comparison
  745. *
  746. * Option based comparisons use a list of options to create a regular expression. Subsequent calls
  747. * to add an already defined options detector will merge the options.
  748. *
  749. * ```
  750. * addDetector('mobile', ['env' => 'HTTP_USER_AGENT', 'options' => ['Fennec']]);
  751. * ```
  752. *
  753. * ### Request parameter detectors
  754. *
  755. * Allows for custom detectors on the request parameters.
  756. *
  757. * e.g `addDetector('requested', ['param' => 'requested', 'value' => 1]`
  758. *
  759. * You can also make parameter detectors that accept multiple values
  760. * using the `options` key. This is useful when you want to check
  761. * if a request parameter is in a list of options.
  762. *
  763. * `addDetector('extension', ['param' => 'ext', 'options' => ['pdf', 'csv']]`
  764. *
  765. * @param string $name The name of the detector.
  766. * @param callable|array $callable A callable or options array for the detector definition.
  767. * @return void
  768. */
  769. public static function addDetector($name, $callable)
  770. {
  771. $name = strtolower($name);
  772. if (is_callable($callable)) {
  773. static::$_detectors[$name] = $callable;
  774. return;
  775. }
  776. if (isset(static::$_detectors[$name], $callable['options'])) {
  777. $callable = Hash::merge(static::$_detectors[$name], $callable);
  778. }
  779. static::$_detectors[$name] = $callable;
  780. }
  781. /**
  782. * Add parameters to the request's parsed parameter set. This will overwrite any existing parameters.
  783. * This modifies the parameters available through `$request->params`.
  784. *
  785. * @param array $params Array of parameters to merge in
  786. * @return $this The current object, you can chain this method.
  787. */
  788. public function addParams(array $params)
  789. {
  790. $this->params = array_merge($this->params, $params);
  791. return $this;
  792. }
  793. /**
  794. * Add paths to the requests' paths vars. This will overwrite any existing paths.
  795. * Provides an easy way to modify, here, webroot and base.
  796. *
  797. * @param array $paths Array of paths to merge in
  798. * @return $this The current object, you can chain this method.
  799. */
  800. public function addPaths(array $paths)
  801. {
  802. foreach (['webroot', 'here', 'base'] as $element) {
  803. if (isset($paths[$element])) {
  804. $this->{$element} = $paths[$element];
  805. }
  806. }
  807. return $this;
  808. }
  809. /**
  810. * Get the value of the current requests URL. Will include querystring arguments.
  811. *
  812. * @param bool $base Include the base path, set to false to trim the base path off.
  813. * @return string The current request URL including query string args.
  814. */
  815. public function here($base = true)
  816. {
  817. $url = $this->here;
  818. if (!empty($this->query)) {
  819. $url .= '?' . http_build_query($this->query, null, '&');
  820. }
  821. if (!$base) {
  822. $url = preg_replace('/^' . preg_quote($this->base, '/') . '/', '', $url, 1);
  823. }
  824. return $url;
  825. }
  826. /**
  827. * Read an HTTP header from the Request information.
  828. *
  829. * @param string $name Name of the header you want.
  830. * @return string|null Either null on no header being set or the value of the header.
  831. */
  832. public function header($name)
  833. {
  834. $name = 'HTTP_' . str_replace('-', '_', $name);
  835. return $this->env($name);
  836. }
  837. /**
  838. * Get the HTTP method used for this request.
  839. * There are a few ways to specify a method.
  840. *
  841. * - If your client supports it you can use native HTTP methods.
  842. * - You can set the HTTP-X-Method-Override header.
  843. * - You can submit an input with the name `_method`
  844. *
  845. * Any of these 3 approaches can be used to set the HTTP method used
  846. * by CakePHP internally, and will effect the result of this method.
  847. *
  848. * @return string The name of the HTTP method used.
  849. */
  850. public function method()
  851. {
  852. return $this->env('REQUEST_METHOD');
  853. }
  854. /**
  855. * Get the host that the request was handled on.
  856. *
  857. * @return string
  858. */
  859. public function host()
  860. {
  861. if ($this->trustProxy && $this->env('HTTP_X_FORWARDED_HOST')) {
  862. return $this->env('HTTP_X_FORWARDED_HOST');
  863. }
  864. return $this->env('HTTP_HOST');
  865. }
  866. /**
  867. * Get the port the request was handled on.
  868. *
  869. * @return string
  870. */
  871. public function port()
  872. {
  873. if ($this->trustProxy && $this->env('HTTP_X_FORWARDED_PORT')) {
  874. return $this->env('HTTP_X_FORWARDED_PORT');
  875. }
  876. return $this->env('SERVER_PORT');
  877. }
  878. /**
  879. * Get the current url scheme used for the request.
  880. *
  881. * e.g. 'http', or 'https'
  882. *
  883. * @return string The scheme used for the request.
  884. */
  885. public function scheme()
  886. {
  887. if ($this->trustProxy && $this->env('HTTP_X_FORWARDED_PROTO')) {
  888. return $this->env('HTTP_X_FORWARDED_PROTO');
  889. }
  890. return $this->env('HTTPS') ? 'https' : 'http';
  891. }
  892. /**
  893. * Get the domain name and include $tldLength segments of the tld.
  894. *
  895. * @param int $tldLength Number of segments your tld contains. For example: `example.com` contains 1 tld.
  896. * While `example.co.uk` contains 2.
  897. * @return string Domain name without subdomains.
  898. */
  899. public function domain($tldLength = 1)
  900. {
  901. $segments = explode('.', $this->host());
  902. $domain = array_slice($segments, -1 * ($tldLength + 1));
  903. return implode('.', $domain);
  904. }
  905. /**
  906. * Get the subdomains for a host.
  907. *
  908. * @param int $tldLength Number of segments your tld contains. For example: `example.com` contains 1 tld.
  909. * While `example.co.uk` contains 2.
  910. * @return array An array of subdomains.
  911. */
  912. public function subdomains($tldLength = 1)
  913. {
  914. $segments = explode('.', $this->host());
  915. return array_slice($segments, 0, -1 * ($tldLength + 1));
  916. }
  917. /**
  918. * Find out which content types the client accepts or check if they accept a
  919. * particular type of content.
  920. *
  921. * #### Get all types:
  922. *
  923. * ```
  924. * $this->request->accepts();
  925. * ```
  926. *
  927. * #### Check for a single type:
  928. *
  929. * ```
  930. * $this->request->accepts('application/json');
  931. * ```
  932. *
  933. * This method will order the returned content types by the preference values indicated
  934. * by the client.
  935. *
  936. * @param string|null $type The content type to check for. Leave null to get all types a client accepts.
  937. * @return array|bool Either an array of all the types the client accepts or a boolean if they accept the
  938. * provided type.
  939. */
  940. public function accepts($type = null)
  941. {
  942. $raw = $this->parseAccept();
  943. $accept = [];
  944. foreach ($raw as $types) {
  945. $accept = array_merge($accept, $types);
  946. }
  947. if ($type === null) {
  948. return $accept;
  949. }
  950. return in_array($type, $accept);
  951. }
  952. /**
  953. * Parse the HTTP_ACCEPT header and return a sorted array with content types
  954. * as the keys, and pref values as the values.
  955. *
  956. * Generally you want to use Cake\Network\Request::accept() to get a simple list
  957. * of the accepted content types.
  958. *
  959. * @return array An array of prefValue => [content/types]
  960. */
  961. public function parseAccept()
  962. {
  963. return $this->_parseAcceptWithQualifier($this->header('accept'));
  964. }
  965. /**
  966. * Get the languages accepted by the client, or check if a specific language is accepted.
  967. *
  968. * Get the list of accepted languages:
  969. *
  970. * ``` \Cake\Network\Request::acceptLanguage(); ```
  971. *
  972. * Check if a specific language is accepted:
  973. *
  974. * ``` \Cake\Network\Request::acceptLanguage('es-es'); ```
  975. *
  976. * @param string|null $language The language to test.
  977. * @return array|bool If a $language is provided, a boolean. Otherwise the array of accepted languages.
  978. */
  979. public function acceptLanguage($language = null)
  980. {
  981. $raw = $this->_parseAcceptWithQualifier($this->header('Accept-Language'));
  982. $accept = [];
  983. foreach ($raw as $languages) {
  984. foreach ($languages as &$lang) {
  985. if (strpos($lang, '_')) {
  986. $lang = str_replace('_', '-', $lang);
  987. }
  988. $lang = strtolower($lang);
  989. }
  990. $accept = array_merge($accept, $languages);
  991. }
  992. if ($language === null) {
  993. return $accept;
  994. }
  995. return in_array(strtolower($language), $accept);
  996. }
  997. /**
  998. * Parse Accept* headers with qualifier options.
  999. *
  1000. * Only qualifiers will be extracted, any other accept extensions will be
  1001. * discarded as they are not frequently used.
  1002. *
  1003. * @param string $header Header to parse.
  1004. * @return array
  1005. */
  1006. protected function _parseAcceptWithQualifier($header)
  1007. {
  1008. $accept = [];
  1009. $header = explode(',', $header);
  1010. foreach (array_filter($header) as $value) {
  1011. $prefValue = '1.0';
  1012. $value = trim($value);
  1013. $semiPos = strpos($value, ';');
  1014. if ($semiPos !== false) {
  1015. $params = explode(';', $value);
  1016. $value = trim($params[0]);
  1017. foreach ($params as $param) {
  1018. $qPos = strpos($param, 'q=');
  1019. if ($qPos !== false) {
  1020. $prefValue = substr($param, $qPos + 2);
  1021. }
  1022. }
  1023. }
  1024. if (!isset($accept[$prefValue])) {
  1025. $accept[$prefValue] = [];
  1026. }
  1027. if ($prefValue) {
  1028. $accept[$prefValue][] = $value;
  1029. }
  1030. }
  1031. krsort($accept);
  1032. return $accept;
  1033. }
  1034. /**
  1035. * Provides a read accessor for `$this->query`. Allows you
  1036. * to use a syntax similar to `CakeSession` for reading URL query data.
  1037. *
  1038. * @param string $name Query string variable name
  1039. * @return mixed The value being read
  1040. */
  1041. public function query($name)
  1042. {
  1043. return Hash::get($this->query, $name);
  1044. }
  1045. /**
  1046. * Provides a read/write accessor for `$this->data`. Allows you
  1047. * to use a syntax similar to `Cake\Model\Datasource\Session` for reading post data.
  1048. *
  1049. * ### Reading values.
  1050. *
  1051. * ```
  1052. * $request->data('Post.title');
  1053. * ```
  1054. *
  1055. * When reading values you will get `null` for keys/values that do not exist.
  1056. *
  1057. * ### Writing values
  1058. *
  1059. * ```
  1060. * $request->data('Post.title', 'New post!');
  1061. * ```
  1062. *
  1063. * You can write to any value, even paths/keys that do not exist, and the arrays
  1064. * will be created for you.
  1065. *
  1066. * @param string|null $name Dot separated name of the value to read/write
  1067. * @return mixed|$this Either the value being read, or this so you can chain consecutive writes.
  1068. */
  1069. public function data($name = null)
  1070. {
  1071. $args = func_get_args();
  1072. if (count($args) === 2) {
  1073. $this->data = Hash::insert($this->data, $name, $args[1]);
  1074. return $this;
  1075. }
  1076. if ($name !== null) {
  1077. return Hash::get($this->data, $name);
  1078. }
  1079. return $this->data;
  1080. }
  1081. /**
  1082. * Safely access the values in $this->params.
  1083. *
  1084. * @param string $name The name of the parameter to get.
  1085. * @return mixed|$this The value of the provided parameter. Will
  1086. * return false if the parameter doesn't exist or is falsey.
  1087. */
  1088. public function param($name)
  1089. {
  1090. $args = func_get_args();
  1091. if (count($args) === 2) {
  1092. $this->params = Hash::insert($this->params, $name, $args[1]);
  1093. return $this;
  1094. }
  1095. if (!isset($this->params[$name])) {
  1096. return Hash::get($this->params, $name, false);
  1097. }
  1098. return $this->params[$name];
  1099. }
  1100. /**
  1101. * Read data from `php://input`. Useful when interacting with XML or JSON
  1102. * request body content.
  1103. *
  1104. * Getting input with a decoding function:
  1105. *
  1106. * ```
  1107. * $this->request->input('json_decode');
  1108. * ```
  1109. *
  1110. * Getting input using a decoding function, and additional params:
  1111. *
  1112. * ```
  1113. * $this->request->input('Xml::build', ['return' => 'DOMDocument']);
  1114. * ```
  1115. *
  1116. * Any additional parameters are applied to the callback in the order they are given.
  1117. *
  1118. * @param string|null $callback A decoding callback that will convert the string data to another
  1119. * representation. Leave empty to access the raw input data. You can also
  1120. * supply additional parameters for the decoding callback using var args, see above.
  1121. * @return string The decoded/processed request data.
  1122. */
  1123. public function input($callback = null)
  1124. {
  1125. $input = $this->_readInput();
  1126. $args = func_get_args();
  1127. if (!empty($args)) {
  1128. $callback = array_shift($args);
  1129. array_unshift($args, $input);
  1130. return call_user_func_array($callback, $args);
  1131. }
  1132. return $input;
  1133. }
  1134. /**
  1135. * Read cookie data from the request's cookie data.
  1136. *
  1137. * @param string $key The key you want to read.
  1138. * @return null|string Either the cookie value, or null if the value doesn't exist.
  1139. */
  1140. public function cookie($key)
  1141. {
  1142. if (isset($this->cookies[$key])) {
  1143. return $this->cookies[$key];
  1144. }
  1145. return null;
  1146. }
  1147. /**
  1148. * Get/Set value from the request's environment data.
  1149. * Fallback to using env() if key not set in $environment property.
  1150. *
  1151. * @param string $key The key you want to read/write from/to.
  1152. * @param string|null $value Value to set. Default null.
  1153. * @param string|null $default Default value when trying to retrieve an environment
  1154. * variable's value that does not exist. The value parameter must be null.
  1155. * @return $this|string|null This instance if used as setter,
  1156. * if used as getter either the environment value, or null if the value doesn't exist.
  1157. */
  1158. public function env($key, $value = null, $default = null)
  1159. {
  1160. if ($value !== null) {
  1161. $this->_environment[$key] = $value;
  1162. $this->clearDetectorCache();
  1163. return $this;
  1164. }
  1165. $key = strtoupper($key);
  1166. if (!array_key_exists($key, $this->_environment)) {
  1167. $this->_environment[$key] = env($key);
  1168. }
  1169. return $this->_environment[$key] !== null ? $this->_environment[$key] : $default;
  1170. }
  1171. /**
  1172. * Allow only certain HTTP request methods, if the request method does not match
  1173. * a 405 error will be shown and the required "Allow" response header will be set.
  1174. *
  1175. * Example:
  1176. *
  1177. * $this->request->allowMethod('post');
  1178. * or
  1179. * $this->request->allowMethod(['post', 'delete']);
  1180. *
  1181. * If the request would be GET, response header "Allow: POST, DELETE" will be set
  1182. * and a 405 error will be returned.
  1183. *
  1184. * @param string|array $methods Allowed HTTP request methods.
  1185. * @return bool true
  1186. * @throws \Cake\Network\Exception\MethodNotAllowedException
  1187. */
  1188. public function allowMethod($methods)
  1189. {
  1190. $methods = (array)$methods;
  1191. foreach ($methods as $method) {
  1192. if ($this->is($method)) {
  1193. return true;
  1194. }
  1195. }
  1196. $allowed = strtoupper(implode(', ', $methods));
  1197. $e = new MethodNotAllowedException();
  1198. $e->responseHeader('Allow', $allowed);
  1199. throw $e;
  1200. }
  1201. /**
  1202. * Read data from php://input, mocked in tests.
  1203. *
  1204. * @return string contents of php://input
  1205. */
  1206. protected function _readInput()
  1207. {
  1208. if (empty($this->_input)) {
  1209. $fh = fopen('php://input', 'r');
  1210. $content = stream_get_contents($fh);
  1211. fclose($fh);
  1212. $this->_input = $content;
  1213. }
  1214. return $this->_input;
  1215. }
  1216. /**
  1217. * Modify data originally from `php://input`. Useful for altering json/xml data
  1218. * in middleware or DispatcherFilters before it gets to RequestHandlerComponent
  1219. *
  1220. * @param string $input A string to replace original parsed data from input()
  1221. * @return void
  1222. */
  1223. public function setInput($input)
  1224. {
  1225. $this->_input = $input;
  1226. }
  1227. /**
  1228. * Array access read implementation
  1229. *
  1230. * @param string $name Name of the key being accessed.
  1231. * @return mixed
  1232. */
  1233. public function offsetGet($name)
  1234. {
  1235. if (isset($this->params[$name])) {
  1236. return $this->params[$name];
  1237. }
  1238. if ($name === 'url') {
  1239. return $this->query;
  1240. }
  1241. if ($name === 'data') {
  1242. return $this->data;
  1243. }
  1244. return null;
  1245. }
  1246. /**
  1247. * Array access write implementation
  1248. *
  1249. * @param string $name Name of the key being written
  1250. * @param mixed $value The value being written.
  1251. * @return void
  1252. */
  1253. public function offsetSet($name, $value)
  1254. {
  1255. $this->params[$name] = $value;
  1256. }
  1257. /**
  1258. * Array access isset() implementation
  1259. *
  1260. * @param string $name thing to check.
  1261. * @return bool
  1262. */
  1263. public function offsetExists($name)
  1264. {
  1265. return isset($this->params[$name]);
  1266. }
  1267. /**
  1268. * Array access unset() implementation
  1269. *
  1270. * @param string $name Name to unset.
  1271. * @return void
  1272. */
  1273. public function offsetUnset($name)
  1274. {
  1275. unset($this->params[$name]);
  1276. }
  1277. }