ServerRequest.php 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://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. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 2.0.0
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Http;
  16. use ArrayAccess;
  17. use BadMethodCallException;
  18. use Cake\Core\Configure;
  19. use Cake\Http\Cookie\CookieCollection;
  20. use Cake\Http\Exception\MethodNotAllowedException;
  21. use Cake\Http\Session;
  22. use Cake\Utility\Hash;
  23. use InvalidArgumentException;
  24. use Psr\Http\Message\ServerRequestInterface;
  25. use Psr\Http\Message\StreamInterface;
  26. use Psr\Http\Message\UploadedFileInterface;
  27. use Psr\Http\Message\UriInterface;
  28. use Zend\Diactoros\PhpInputStream;
  29. use Zend\Diactoros\Stream;
  30. use Zend\Diactoros\UploadedFile;
  31. /**
  32. * A class that helps wrap Request information and particulars about a single request.
  33. * Provides methods commonly used to introspect on the request headers and request body.
  34. */
  35. class ServerRequest implements ArrayAccess, ServerRequestInterface
  36. {
  37. /**
  38. * Array of parameters parsed from the URL.
  39. *
  40. * @var array
  41. * @deprecated 3.4.0 This public property will be removed in 4.0.0. Use getParam() instead.
  42. */
  43. public $params = [
  44. 'plugin' => null,
  45. 'controller' => null,
  46. 'action' => null,
  47. '_ext' => null,
  48. 'pass' => []
  49. ];
  50. /**
  51. * Array of POST data. Will contain form data as well as uploaded files.
  52. * In PUT/PATCH/DELETE requests this property will contain the form-urlencoded
  53. * data.
  54. *
  55. * @var array
  56. * @deprecated 3.4.0 This public property will be removed in 4.0.0. Use getData() instead.
  57. */
  58. public $data = [];
  59. /**
  60. * Array of query string arguments
  61. *
  62. * @var array
  63. * @deprecated 3.4.0 This public property will be removed in 4.0.0. Use getQuery() or getQueryParams() instead.
  64. */
  65. public $query = [];
  66. /**
  67. * Array of cookie data.
  68. *
  69. * @var array
  70. * @deprecated 3.4.0 This public property will be removed in 4.0.0. Use getCookie() instead.
  71. */
  72. public $cookies = [];
  73. /**
  74. * Array of environment data.
  75. *
  76. * @var array
  77. */
  78. protected $_environment = [];
  79. /**
  80. * The URL string used for the request.
  81. *
  82. * @var string
  83. */
  84. public $url;
  85. /**
  86. * Base URL path.
  87. *
  88. * @var string
  89. * @deprecated 3.4.0 This public property will be removed in 4.0.0. Use getAttribute('base') instead.
  90. */
  91. public $base;
  92. /**
  93. * webroot path segment for the request.
  94. *
  95. * @var string
  96. * @deprecated 3.4.0 This public property will be removed in 4.0.0. Use getAttribute('webroot') instead.
  97. */
  98. public $webroot = '/';
  99. /**
  100. * The full address to the current request
  101. *
  102. * @var string
  103. * @deprecated 3.4.0 This public property will be removed in 4.0.0. Use getUri()->getPath() instead.
  104. */
  105. public $here;
  106. /**
  107. * Whether or not to trust HTTP_X headers set by most load balancers.
  108. * Only set to true if your application runs behind load balancers/proxies
  109. * that you control.
  110. *
  111. * @var bool
  112. */
  113. public $trustProxy = false;
  114. /**
  115. * Contents of php://input
  116. *
  117. * @var string
  118. */
  119. protected $_input;
  120. /**
  121. * The built in detectors used with `is()` can be modified with `addDetector()`.
  122. *
  123. * There are several ways to specify a detector, see \Cake\Http\ServerRequest::addDetector() for the
  124. * various formats and ways to define detectors.
  125. *
  126. * @var array
  127. */
  128. protected static $_detectors = [
  129. 'get' => ['env' => 'REQUEST_METHOD', 'value' => 'GET'],
  130. 'post' => ['env' => 'REQUEST_METHOD', 'value' => 'POST'],
  131. 'put' => ['env' => 'REQUEST_METHOD', 'value' => 'PUT'],
  132. 'patch' => ['env' => 'REQUEST_METHOD', 'value' => 'PATCH'],
  133. 'delete' => ['env' => 'REQUEST_METHOD', 'value' => 'DELETE'],
  134. 'head' => ['env' => 'REQUEST_METHOD', 'value' => 'HEAD'],
  135. 'options' => ['env' => 'REQUEST_METHOD', 'value' => 'OPTIONS'],
  136. 'ssl' => ['env' => 'HTTPS', 'options' => [1, 'on']],
  137. 'ajax' => ['env' => 'HTTP_X_REQUESTED_WITH', 'value' => 'XMLHttpRequest'],
  138. 'flash' => ['env' => 'HTTP_USER_AGENT', 'pattern' => '/^(Shockwave|Adobe) Flash/'],
  139. 'requested' => ['param' => 'requested', 'value' => 1],
  140. 'json' => ['accept' => ['application/json'], 'param' => '_ext', 'value' => 'json'],
  141. 'xml' => ['accept' => ['application/xml', 'text/xml'], 'param' => '_ext', 'value' => 'xml'],
  142. ];
  143. /**
  144. * Instance cache for results of is(something) calls
  145. *
  146. * @var array
  147. */
  148. protected $_detectorCache = [];
  149. /**
  150. * Request body stream. Contains php://input unless `input` constructor option is used.
  151. *
  152. * @var \Psr\Http\Message\StreamInterface
  153. */
  154. protected $stream;
  155. /**
  156. * Uri instance
  157. *
  158. * @var \Psr\Http\Message\UriInterface
  159. */
  160. protected $uri;
  161. /**
  162. * Instance of a Session object relative to this request
  163. *
  164. * @var \Cake\Http\Session
  165. */
  166. protected $session;
  167. /**
  168. * Store the additional attributes attached to the request.
  169. *
  170. * @var array
  171. */
  172. protected $attributes = [];
  173. /**
  174. * A list of propertes that emulated by the PSR7 attribute methods.
  175. *
  176. * @var array
  177. */
  178. protected $emulatedAttributes = ['session', 'webroot', 'base', 'params'];
  179. /**
  180. * Array of Psr\Http\Message\UploadedFileInterface objects.
  181. *
  182. * @var array
  183. */
  184. protected $uploadedFiles = [];
  185. /**
  186. * The HTTP protocol version used.
  187. *
  188. * @var string|null
  189. */
  190. protected $protocol;
  191. /**
  192. * The request target if overridden
  193. *
  194. * @var string|null
  195. */
  196. protected $requestTarget;
  197. /**
  198. * Wrapper method to create a new request from PHP superglobals.
  199. *
  200. * Uses the $_GET, $_POST, $_FILES, $_COOKIE, $_SERVER, $_ENV and php://input data to construct
  201. * the request.
  202. *
  203. * @return self
  204. * @deprecated 3.4.0 Use `Cake\Http\ServerRequestFactory` instead.
  205. */
  206. public static function createFromGlobals()
  207. {
  208. deprecationWarning(
  209. 'ServerRequest::createFromGlobals() is deprecated. ' .
  210. 'Use `Cake\Http\ServerRequestFactory` instead.'
  211. );
  212. return ServerRequestFactory::fromGlobals();
  213. }
  214. /**
  215. * Create a new request object.
  216. *
  217. * You can supply the data as either an array or as a string. If you use
  218. * a string you can only supply the URL for the request. Using an array will
  219. * let you provide the following keys:
  220. *
  221. * - `post` POST data or non query string data
  222. * - `query` Additional data from the query string.
  223. * - `files` Uploaded file data formatted like $_FILES.
  224. * - `cookies` Cookies for this request.
  225. * - `environment` $_SERVER and $_ENV data.
  226. * - ~~`url`~~ The URL without the base path for the request. This option is deprecated and will be removed in 4.0.0
  227. * - `uri` The PSR7 UriInterface object. If null, one will be created.
  228. * - `base` The base URL for the request.
  229. * - `webroot` The webroot directory for the request.
  230. * - `input` The data that would come from php://input this is useful for simulating
  231. * requests with put, patch or delete data.
  232. * - `session` An instance of a Session object
  233. *
  234. * @param string|array $config An array of request data to create a request with.
  235. * The string version of this argument is *deprecated* and will be removed in 4.0.0
  236. */
  237. public function __construct($config = [])
  238. {
  239. if (is_string($config)) {
  240. $config = ['url' => $config];
  241. }
  242. $config += [
  243. 'params' => $this->params,
  244. 'query' => [],
  245. 'post' => [],
  246. 'files' => [],
  247. 'cookies' => [],
  248. 'environment' => [],
  249. 'url' => '',
  250. 'uri' => null,
  251. 'base' => '',
  252. 'webroot' => '',
  253. 'input' => null,
  254. ];
  255. $this->_setConfig($config);
  256. }
  257. /**
  258. * Process the config/settings data into properties.
  259. *
  260. * @param array $config The config data to use.
  261. * @return void
  262. */
  263. protected function _setConfig($config)
  264. {
  265. if (!empty($config['url']) && $config['url'][0] === '/') {
  266. $config['url'] = substr($config['url'], 1);
  267. }
  268. if (empty($config['session'])) {
  269. $config['session'] = new Session([
  270. 'cookiePath' => $config['base']
  271. ]);
  272. }
  273. $this->_environment = $config['environment'];
  274. $this->cookies = $config['cookies'];
  275. if (isset($config['uri']) && $config['uri'] instanceof UriInterface) {
  276. $uri = $config['uri'];
  277. } else {
  278. $uri = ServerRequestFactory::createUri($config['environment']);
  279. }
  280. // Extract a query string from config[url] if present.
  281. // This is required for backwards compatibility and keeping
  282. // UriInterface implementations happy.
  283. $querystr = '';
  284. if (strpos($config['url'], '?') !== false) {
  285. list($config['url'], $querystr) = explode('?', $config['url']);
  286. }
  287. if (strlen($config['url'])) {
  288. $uri = $uri->withPath('/' . $config['url']);
  289. }
  290. if (strlen($querystr)) {
  291. $uri = $uri->withQuery($querystr);
  292. }
  293. $this->uri = $uri;
  294. $this->base = $config['base'];
  295. $this->webroot = $config['webroot'];
  296. $this->url = substr($uri->getPath(), 1);
  297. $this->here = $this->base . '/' . $this->url;
  298. if (isset($config['input'])) {
  299. $stream = new Stream('php://memory', 'rw');
  300. $stream->write($config['input']);
  301. $stream->rewind();
  302. } else {
  303. $stream = new PhpInputStream();
  304. }
  305. $this->stream = $stream;
  306. $config['post'] = $this->_processPost($config['post']);
  307. $this->data = $this->_processFiles($config['post'], $config['files']);
  308. $this->query = $this->_processGet($config['query'], $querystr);
  309. $this->params = $config['params'];
  310. $this->session = $config['session'];
  311. }
  312. /**
  313. * Sets the REQUEST_METHOD environment variable based on the simulated _method
  314. * HTTP override value. The 'ORIGINAL_REQUEST_METHOD' is also preserved, if you
  315. * want the read the non-simulated HTTP method the client used.
  316. *
  317. * @param array $data Array of post data.
  318. * @return array
  319. */
  320. protected function _processPost($data)
  321. {
  322. $method = $this->getEnv('REQUEST_METHOD');
  323. $override = false;
  324. if (in_array($method, ['PUT', 'DELETE', 'PATCH']) &&
  325. strpos($this->contentType(), 'application/x-www-form-urlencoded') === 0
  326. ) {
  327. $data = $this->input();
  328. parse_str($data, $data);
  329. }
  330. if ($this->hasHeader('X-Http-Method-Override')) {
  331. $data['_method'] = $this->getHeaderLine('X-Http-Method-Override');
  332. $override = true;
  333. }
  334. $this->_environment['ORIGINAL_REQUEST_METHOD'] = $method;
  335. if (isset($data['_method'])) {
  336. $this->_environment['REQUEST_METHOD'] = $data['_method'];
  337. unset($data['_method']);
  338. $override = true;
  339. }
  340. if ($override && !in_array($this->_environment['REQUEST_METHOD'], ['PUT', 'POST', 'DELETE', 'PATCH'])) {
  341. $data = [];
  342. }
  343. return $data;
  344. }
  345. /**
  346. * Process the GET parameters and move things into the object.
  347. *
  348. * @param array $query The array to which the parsed keys/values are being added.
  349. * @param string $queryString A query string from the URL if provided
  350. * @return array An array containing the parsed query string as keys/values.
  351. */
  352. protected function _processGet($query, $queryString = '')
  353. {
  354. $unsetUrl = '/' . str_replace(['.', ' '], '_', urldecode($this->url));
  355. unset($query[$unsetUrl], $query[$this->base . $unsetUrl]);
  356. if (strlen($queryString)) {
  357. parse_str($queryString, $queryArgs);
  358. $query += $queryArgs;
  359. }
  360. return $query;
  361. }
  362. /**
  363. * Process uploaded files and move things onto the post data.
  364. *
  365. * @param array $post Post data to merge files onto.
  366. * @param array $files Uploaded files to merge in.
  367. * @return array merged post + file data.
  368. */
  369. protected function _processFiles($post, $files)
  370. {
  371. if (!is_array($files)) {
  372. return $post;
  373. }
  374. $fileData = [];
  375. foreach ($files as $key => $value) {
  376. if ($value instanceof UploadedFileInterface) {
  377. $fileData[$key] = $value;
  378. continue;
  379. }
  380. if (is_array($value) && isset($value['tmp_name'])) {
  381. $fileData[$key] = $this->_createUploadedFile($value);
  382. continue;
  383. }
  384. throw new InvalidArgumentException(sprintf(
  385. 'Invalid value in FILES "%s"',
  386. json_encode($value)
  387. ));
  388. }
  389. $this->uploadedFiles = $fileData;
  390. // Make a flat map that can be inserted into $post for BC.
  391. $fileMap = Hash::flatten($fileData);
  392. foreach ($fileMap as $key => $file) {
  393. $error = $file->getError();
  394. $tmpName = '';
  395. if ($error === UPLOAD_ERR_OK) {
  396. $tmpName = $file->getStream()->getMetadata('uri');
  397. }
  398. $post = Hash::insert($post, $key, [
  399. 'tmp_name' => $tmpName,
  400. 'error' => $error,
  401. 'name' => $file->getClientFilename(),
  402. 'type' => $file->getClientMediaType(),
  403. 'size' => $file->getSize(),
  404. ]);
  405. }
  406. return $post;
  407. }
  408. /**
  409. * Create an UploadedFile instance from a $_FILES array.
  410. *
  411. * If the value represents an array of values, this method will
  412. * recursively process the data.
  413. *
  414. * @param array $value $_FILES struct
  415. * @return array|UploadedFileInterface
  416. */
  417. protected function _createUploadedFile(array $value)
  418. {
  419. if (is_array($value['tmp_name'])) {
  420. return $this->_normalizeNestedFiles($value);
  421. }
  422. return new UploadedFile(
  423. $value['tmp_name'],
  424. $value['size'],
  425. $value['error'],
  426. $value['name'],
  427. $value['type']
  428. );
  429. }
  430. /**
  431. * Normalize an array of file specifications.
  432. *
  433. * Loops through all nested files and returns a normalized array of
  434. * UploadedFileInterface instances.
  435. *
  436. * @param array $files The file data to normalize & convert.
  437. * @return array An array of UploadedFileInterface objects.
  438. */
  439. protected function _normalizeNestedFiles(array $files = [])
  440. {
  441. $normalizedFiles = [];
  442. foreach (array_keys($files['tmp_name']) as $key) {
  443. $spec = [
  444. 'tmp_name' => $files['tmp_name'][$key],
  445. 'size' => $files['size'][$key],
  446. 'error' => $files['error'][$key],
  447. 'name' => $files['name'][$key],
  448. 'type' => $files['type'][$key],
  449. ];
  450. $normalizedFiles[$key] = $this->_createUploadedFile($spec);
  451. }
  452. return $normalizedFiles;
  453. }
  454. /**
  455. * Get the content type used in this request.
  456. *
  457. * @return string
  458. */
  459. public function contentType()
  460. {
  461. $type = $this->getEnv('CONTENT_TYPE');
  462. if ($type) {
  463. return $type;
  464. }
  465. return $this->getEnv('HTTP_CONTENT_TYPE');
  466. }
  467. /**
  468. * Returns the instance of the Session object for this request
  469. *
  470. * @return \Cake\Http\Session
  471. */
  472. public function getSession()
  473. {
  474. return $this->session;
  475. }
  476. /**
  477. * Returns the instance of the Session object for this request
  478. *
  479. * If a session object is passed as first argument it will be set as
  480. * the session to use for this request
  481. *
  482. * @deprecated 3.5.0 Use getSession() instead. The setter part will be removed.
  483. * @param \Cake\Http\Session|null $session the session object to use
  484. * @return \Cake\Http\Session
  485. */
  486. public function session(Session $session = null)
  487. {
  488. deprecationWarning(
  489. 'ServerRequest::session() is deprecated. ' .
  490. 'Use getSession() instead. The setter part will be removed.'
  491. );
  492. if ($session === null) {
  493. return $this->session;
  494. }
  495. return $this->session = $session;
  496. }
  497. /**
  498. * Get the IP the client is using, or says they are using.
  499. *
  500. * @return string The client IP.
  501. */
  502. public function clientIp()
  503. {
  504. if ($this->trustProxy && $this->getEnv('HTTP_X_FORWARDED_FOR')) {
  505. $addresses = explode(',', $this->getEnv('HTTP_X_FORWARDED_FOR'));
  506. $ipaddr = end($addresses);
  507. } elseif ($this->trustProxy && $this->getEnv('HTTP_CLIENT_IP')) {
  508. $ipaddr = $this->getEnv('HTTP_CLIENT_IP');
  509. } else {
  510. $ipaddr = $this->getEnv('REMOTE_ADDR');
  511. }
  512. return trim($ipaddr);
  513. }
  514. /**
  515. * Returns the referer that referred this request.
  516. *
  517. * @param bool $local Attempt to return a local address.
  518. * Local addresses do not contain hostnames.
  519. * @return string The referring address for this request.
  520. */
  521. public function referer($local = false)
  522. {
  523. $ref = $this->getEnv('HTTP_REFERER');
  524. $base = Configure::read('App.fullBaseUrl') . $this->webroot;
  525. if (!empty($ref) && !empty($base)) {
  526. if ($local && strpos($ref, $base) === 0) {
  527. $ref = substr($ref, strlen($base));
  528. if (!strlen($ref)) {
  529. $ref = '/';
  530. }
  531. if ($ref[0] !== '/') {
  532. $ref = '/' . $ref;
  533. }
  534. return $ref;
  535. }
  536. if (!$local) {
  537. return $ref;
  538. }
  539. }
  540. return '/';
  541. }
  542. /**
  543. * Missing method handler, handles wrapping older style isAjax() type methods
  544. *
  545. * @param string $name The method called
  546. * @param array $params Array of parameters for the method call
  547. * @return mixed
  548. * @throws \BadMethodCallException when an invalid method is called.
  549. */
  550. public function __call($name, $params)
  551. {
  552. if (strpos($name, 'is') === 0) {
  553. $type = strtolower(substr($name, 2));
  554. array_unshift($params, $type);
  555. return $this->is(...$params);
  556. }
  557. throw new BadMethodCallException(sprintf('Method %s does not exist', $name));
  558. }
  559. /**
  560. * Magic get method allows access to parsed routing parameters directly on the object.
  561. *
  562. * Allows access to `$this->params['controller']` via `$this->controller`
  563. *
  564. * @param string $name The property being accessed.
  565. * @return mixed Either the value of the parameter or null.
  566. * @deprecated 3.4.0 Accessing routing parameters through __get will removed in 4.0.0.
  567. * Use getParam() instead.
  568. */
  569. public function __get($name)
  570. {
  571. deprecationWarning(sprintf(
  572. 'Accessing routing parameters through `%s` will removed in 4.0.0. ' .
  573. 'Use `getParam()` instead.',
  574. $name
  575. ));
  576. if (isset($this->params[$name])) {
  577. return $this->params[$name];
  578. }
  579. return null;
  580. }
  581. /**
  582. * Magic isset method allows isset/empty checks
  583. * on routing parameters.
  584. *
  585. * @param string $name The property being accessed.
  586. * @return bool Existence
  587. * @deprecated 3.4.0 Accessing routing parameters through __isset will removed in 4.0.0.
  588. * Use getParam() instead.
  589. */
  590. public function __isset($name)
  591. {
  592. deprecationWarning(
  593. 'Accessing routing parameters through __isset will removed in 4.0.0. ' .
  594. 'Use getParam() instead.'
  595. );
  596. return isset($this->params[$name]);
  597. }
  598. /**
  599. * Check whether or not a Request is a certain type.
  600. *
  601. * Uses the built in detection rules as well as additional rules
  602. * defined with Cake\Http\ServerRequest::addDetector(). Any detector can be called
  603. * as `is($type)` or `is$Type()`.
  604. *
  605. * @param string|array $type The type of request you want to check. If an array
  606. * this method will return true if the request matches any type.
  607. * @param array ...$args List of arguments
  608. * @return bool Whether or not the request is the type you are checking.
  609. */
  610. public function is($type, ...$args)
  611. {
  612. if (is_array($type)) {
  613. $result = array_map([$this, 'is'], $type);
  614. return count(array_filter($result)) > 0;
  615. }
  616. $type = strtolower($type);
  617. if (!isset(static::$_detectors[$type])) {
  618. return false;
  619. }
  620. if ($args) {
  621. return $this->_is($type, $args);
  622. }
  623. if (!isset($this->_detectorCache[$type])) {
  624. $this->_detectorCache[$type] = $this->_is($type, $args);
  625. }
  626. return $this->_detectorCache[$type];
  627. }
  628. /**
  629. * Clears the instance detector cache, used by the is() function
  630. *
  631. * @return void
  632. */
  633. public function clearDetectorCache()
  634. {
  635. $this->_detectorCache = [];
  636. }
  637. /**
  638. * Worker for the public is() function
  639. *
  640. * @param string|array $type The type of request you want to check. If an array
  641. * this method will return true if the request matches any type.
  642. * @param array $args Array of custom detector arguments.
  643. * @return bool Whether or not the request is the type you are checking.
  644. */
  645. protected function _is($type, $args)
  646. {
  647. $detect = static::$_detectors[$type];
  648. if (is_callable($detect)) {
  649. array_unshift($args, $this);
  650. return $detect(...$args);
  651. }
  652. if (isset($detect['env']) && $this->_environmentDetector($detect)) {
  653. return true;
  654. }
  655. if (isset($detect['header']) && $this->_headerDetector($detect)) {
  656. return true;
  657. }
  658. if (isset($detect['accept']) && $this->_acceptHeaderDetector($detect)) {
  659. return true;
  660. }
  661. if (isset($detect['param']) && $this->_paramDetector($detect)) {
  662. return true;
  663. }
  664. return false;
  665. }
  666. /**
  667. * Detects if a specific accept header is present.
  668. *
  669. * @param array $detect Detector options array.
  670. * @return bool Whether or not the request is the type you are checking.
  671. */
  672. protected function _acceptHeaderDetector($detect)
  673. {
  674. $acceptHeaders = explode(',', $this->getEnv('HTTP_ACCEPT'));
  675. foreach ($detect['accept'] as $header) {
  676. if (in_array($header, $acceptHeaders)) {
  677. return true;
  678. }
  679. }
  680. return false;
  681. }
  682. /**
  683. * Detects if a specific header is present.
  684. *
  685. * @param array $detect Detector options array.
  686. * @return bool Whether or not the request is the type you are checking.
  687. */
  688. protected function _headerDetector($detect)
  689. {
  690. foreach ($detect['header'] as $header => $value) {
  691. $header = $this->getEnv('http_' . $header);
  692. if ($header !== null) {
  693. if (!is_string($value) && !is_bool($value) && is_callable($value)) {
  694. return call_user_func($value, $header);
  695. }
  696. return ($header === $value);
  697. }
  698. }
  699. return false;
  700. }
  701. /**
  702. * Detects if a specific request parameter is present.
  703. *
  704. * @param array $detect Detector options array.
  705. * @return bool Whether or not the request is the type you are checking.
  706. */
  707. protected function _paramDetector($detect)
  708. {
  709. $key = $detect['param'];
  710. if (isset($detect['value'])) {
  711. $value = $detect['value'];
  712. return isset($this->params[$key]) ? $this->params[$key] == $value : false;
  713. }
  714. if (isset($detect['options'])) {
  715. return isset($this->params[$key]) ? in_array($this->params[$key], $detect['options']) : false;
  716. }
  717. return false;
  718. }
  719. /**
  720. * Detects if a specific environment variable is present.
  721. *
  722. * @param array $detect Detector options array.
  723. * @return bool Whether or not the request is the type you are checking.
  724. */
  725. protected function _environmentDetector($detect)
  726. {
  727. if (isset($detect['env'])) {
  728. if (isset($detect['value'])) {
  729. return $this->getEnv($detect['env']) == $detect['value'];
  730. }
  731. if (isset($detect['pattern'])) {
  732. return (bool)preg_match($detect['pattern'], $this->getEnv($detect['env']));
  733. }
  734. if (isset($detect['options'])) {
  735. $pattern = '/' . implode('|', $detect['options']) . '/i';
  736. return (bool)preg_match($pattern, $this->getEnv($detect['env']));
  737. }
  738. }
  739. return false;
  740. }
  741. /**
  742. * Check that a request matches all the given types.
  743. *
  744. * Allows you to test multiple types and union the results.
  745. * See Request::is() for how to add additional types and the
  746. * built-in types.
  747. *
  748. * @param array $types The types to check.
  749. * @return bool Success.
  750. * @see \Cake\Http\ServerRequest::is()
  751. */
  752. public function isAll(array $types)
  753. {
  754. $result = array_filter(array_map([$this, 'is'], $types));
  755. return count($result) === count($types);
  756. }
  757. /**
  758. * Add a new detector to the list of detectors that a request can use.
  759. * There are several different formats and types of detectors that can be set.
  760. *
  761. * ### Callback detectors
  762. *
  763. * Callback detectors allow you to provide a callable to handle the check.
  764. * The callback will receive the request object as its only parameter.
  765. *
  766. * ```
  767. * addDetector('custom', function ($request) { //Return a boolean });
  768. * addDetector('custom', ['SomeClass', 'somemethod']);
  769. * ```
  770. *
  771. * ### Environment value comparison
  772. *
  773. * An environment value comparison, compares a value fetched from `env()` to a known value
  774. * the environment value is equality checked against the provided value.
  775. *
  776. * e.g `addDetector('post', ['env' => 'REQUEST_METHOD', 'value' => 'POST'])`
  777. *
  778. * ### Pattern value comparison
  779. *
  780. * Pattern value comparison allows you to compare a value fetched from `env()` to a regular expression.
  781. *
  782. * ```
  783. * addDetector('iphone', ['env' => 'HTTP_USER_AGENT', 'pattern' => '/iPhone/i']);
  784. * ```
  785. *
  786. * ### Option based comparison
  787. *
  788. * Option based comparisons use a list of options to create a regular expression. Subsequent calls
  789. * to add an already defined options detector will merge the options.
  790. *
  791. * ```
  792. * addDetector('mobile', ['env' => 'HTTP_USER_AGENT', 'options' => ['Fennec']]);
  793. * ```
  794. *
  795. * ### Request parameter detectors
  796. *
  797. * Allows for custom detectors on the request parameters.
  798. *
  799. * e.g `addDetector('requested', ['param' => 'requested', 'value' => 1]`
  800. *
  801. * You can also make parameter detectors that accept multiple values
  802. * using the `options` key. This is useful when you want to check
  803. * if a request parameter is in a list of options.
  804. *
  805. * `addDetector('extension', ['param' => 'ext', 'options' => ['pdf', 'csv']]`
  806. *
  807. * @param string $name The name of the detector.
  808. * @param callable|array $callable A callable or options array for the detector definition.
  809. * @return void
  810. */
  811. public static function addDetector($name, $callable)
  812. {
  813. $name = strtolower($name);
  814. if (is_callable($callable)) {
  815. static::$_detectors[$name] = $callable;
  816. return;
  817. }
  818. if (isset(static::$_detectors[$name], $callable['options'])) {
  819. $callable = Hash::merge(static::$_detectors[$name], $callable);
  820. }
  821. static::$_detectors[$name] = $callable;
  822. }
  823. /**
  824. * Add parameters to the request's parsed parameter set. This will overwrite any existing parameters.
  825. * This modifies the parameters available through `$request->getParam()`.
  826. *
  827. * @param array $params Array of parameters to merge in
  828. * @return $this The current object, you can chain this method.
  829. * @deprecated 3.6.0 ServerRequest::addParams() is deprecated. Use `withParam()` or
  830. * `withAttribute('params')` instead.
  831. */
  832. public function addParams(array $params)
  833. {
  834. deprecationWarning(
  835. 'ServerRequest::addParams() is deprecated. ' .
  836. 'Use `withParam()` or `withAttribute("params", $params)` instead.'
  837. );
  838. $this->params = array_merge($this->params, $params);
  839. return $this;
  840. }
  841. /**
  842. * Add paths to the requests' paths vars. This will overwrite any existing paths.
  843. * Provides an easy way to modify, here, webroot and base.
  844. *
  845. * @param array $paths Array of paths to merge in
  846. * @return $this The current object, you can chain this method.
  847. * @deprecated 3.6.0 Mutating a request in place is deprecated. Use `withAttribute()` to modify paths instead.
  848. */
  849. public function addPaths(array $paths)
  850. {
  851. deprecationWarning(
  852. 'ServerRequest::addPaths() is deprecated. ' .
  853. 'Use `withAttribute($key, $value)` instead.'
  854. );
  855. foreach (['webroot', 'here', 'base'] as $element) {
  856. if (isset($paths[$element])) {
  857. $this->{$element} = $paths[$element];
  858. }
  859. }
  860. return $this;
  861. }
  862. /**
  863. * Get the value of the current requests URL. Will include the query string arguments.
  864. *
  865. * @param bool $base Include the base path, set to false to trim the base path off.
  866. * @return string The current request URL including query string args.
  867. * @deprecated 3.4.0 This method will be removed in 4.0.0. You should use getRequestTarget() instead.
  868. */
  869. public function here($base = true)
  870. {
  871. deprecationWarning(
  872. 'ServerRequest::here() will be removed in 4.0.0. You should use getRequestTarget() instead.'
  873. );
  874. $url = $this->here;
  875. if (!empty($this->query)) {
  876. $url .= '?' . http_build_query($this->query, null, '&');
  877. }
  878. if (!$base) {
  879. $url = preg_replace('/^' . preg_quote($this->base, '/') . '/', '', $url, 1);
  880. }
  881. return $url;
  882. }
  883. /**
  884. * Normalize a header name into the SERVER version.
  885. *
  886. * @param string $name The header name.
  887. * @return string The normalized header name.
  888. */
  889. protected function normalizeHeaderName($name)
  890. {
  891. $name = str_replace('-', '_', strtoupper($name));
  892. if (!in_array($name, ['CONTENT_LENGTH', 'CONTENT_TYPE'])) {
  893. $name = 'HTTP_' . $name;
  894. }
  895. return $name;
  896. }
  897. /**
  898. * Read an HTTP header from the Request information.
  899. *
  900. * If the header is not defined in the request, this method
  901. * will fallback to reading data from $_SERVER and $_ENV.
  902. * This fallback behavior is deprecated, and will be removed in 4.0.0
  903. *
  904. * @param string $name Name of the header you want.
  905. * @return string|null Either null on no header being set or the value of the header.
  906. * @deprecated 4.0.0 The automatic fallback to env() will be removed in 4.0.0, see getHeader()
  907. */
  908. public function header($name)
  909. {
  910. deprecationWarning(
  911. 'ServerRequest::header() is deprecated. ' .
  912. 'The automatic fallback to env() will be removed in 4.0.0, see getHeader()'
  913. );
  914. $name = $this->normalizeHeaderName($name);
  915. return $this->getEnv($name);
  916. }
  917. /**
  918. * Get all headers in the request.
  919. *
  920. * Returns an associative array where the header names are
  921. * the keys and the values are a list of header values.
  922. *
  923. * While header names are not case-sensitive, getHeaders() will normalize
  924. * the headers.
  925. *
  926. * @return array An associative array of headers and their values.
  927. * @link http://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface.
  928. */
  929. public function getHeaders()
  930. {
  931. $headers = [];
  932. foreach ($this->_environment as $key => $value) {
  933. $name = null;
  934. if (strpos($key, 'HTTP_') === 0) {
  935. $name = substr($key, 5);
  936. }
  937. if (strpos($key, 'CONTENT_') === 0) {
  938. $name = $key;
  939. }
  940. if ($name !== null) {
  941. $name = strtr(strtolower($name), '_', ' ');
  942. $name = strtr(ucwords($name), ' ', '-');
  943. $headers[$name] = (array)$value;
  944. }
  945. }
  946. return $headers;
  947. }
  948. /**
  949. * Check if a header is set in the request.
  950. *
  951. * @param string $name The header you want to get (case-insensitive)
  952. * @return bool Whether or not the header is defined.
  953. * @link http://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface.
  954. */
  955. public function hasHeader($name)
  956. {
  957. $name = $this->normalizeHeaderName($name);
  958. return isset($this->_environment[$name]);
  959. }
  960. /**
  961. * Get a single header from the request.
  962. *
  963. * Return the header value as an array. If the header
  964. * is not present an empty array will be returned.
  965. *
  966. * @param string $name The header you want to get (case-insensitive)
  967. * @return array An associative array of headers and their values.
  968. * If the header doesn't exist, an empty array will be returned.
  969. * @link http://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface.
  970. */
  971. public function getHeader($name)
  972. {
  973. $name = $this->normalizeHeaderName($name);
  974. if (isset($this->_environment[$name])) {
  975. return (array)$this->_environment[$name];
  976. }
  977. return [];
  978. }
  979. /**
  980. * Get a single header as a string from the request.
  981. *
  982. * @param string $name The header you want to get (case-insensitive)
  983. * @return string Header values collapsed into a comma separated string.
  984. * @link http://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface.
  985. */
  986. public function getHeaderLine($name)
  987. {
  988. $value = $this->getHeader($name);
  989. return implode(', ', $value);
  990. }
  991. /**
  992. * Get a modified request with the provided header.
  993. *
  994. * @param string $name The header name.
  995. * @param string|array $value The header value
  996. * @return static
  997. * @link http://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface.
  998. */
  999. public function withHeader($name, $value)
  1000. {
  1001. $new = clone $this;
  1002. $name = $this->normalizeHeaderName($name);
  1003. $new->_environment[$name] = $value;
  1004. return $new;
  1005. }
  1006. /**
  1007. * Get a modified request with the provided header.
  1008. *
  1009. * Existing header values will be retained. The provided value
  1010. * will be appended into the existing values.
  1011. *
  1012. * @param string $name The header name.
  1013. * @param string|array $value The header value
  1014. * @return static
  1015. * @link http://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface.
  1016. */
  1017. public function withAddedHeader($name, $value)
  1018. {
  1019. $new = clone $this;
  1020. $name = $this->normalizeHeaderName($name);
  1021. $existing = [];
  1022. if (isset($new->_environment[$name])) {
  1023. $existing = (array)$new->_environment[$name];
  1024. }
  1025. $existing = array_merge($existing, (array)$value);
  1026. $new->_environment[$name] = $existing;
  1027. return $new;
  1028. }
  1029. /**
  1030. * Get a modified request without a provided header.
  1031. *
  1032. * @param string $name The header name to remove.
  1033. * @return static
  1034. * @link http://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface.
  1035. */
  1036. public function withoutHeader($name)
  1037. {
  1038. $new = clone $this;
  1039. $name = $this->normalizeHeaderName($name);
  1040. unset($new->_environment[$name]);
  1041. return $new;
  1042. }
  1043. /**
  1044. * Get the HTTP method used for this request.
  1045. *
  1046. * @return string The name of the HTTP method used.
  1047. * @deprecated 3.4.0 This method will be removed in 4.0.0. Use getMethod() instead.
  1048. */
  1049. public function method()
  1050. {
  1051. deprecationWarning(
  1052. 'ServerRequest::method() is deprecated. ' .
  1053. 'This method will be removed in 4.0.0. Use getMethod() instead.'
  1054. );
  1055. return $this->getEnv('REQUEST_METHOD');
  1056. }
  1057. /**
  1058. * Get the HTTP method used for this request.
  1059. * There are a few ways to specify a method.
  1060. *
  1061. * - If your client supports it you can use native HTTP methods.
  1062. * - You can set the HTTP-X-Method-Override header.
  1063. * - You can submit an input with the name `_method`
  1064. *
  1065. * Any of these 3 approaches can be used to set the HTTP method used
  1066. * by CakePHP internally, and will effect the result of this method.
  1067. *
  1068. * @return string The name of the HTTP method used.
  1069. * @link http://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface.
  1070. */
  1071. public function getMethod()
  1072. {
  1073. return $this->getEnv('REQUEST_METHOD');
  1074. }
  1075. /**
  1076. * Update the request method and get a new instance.
  1077. *
  1078. * @param string $method The HTTP method to use.
  1079. * @return static A new instance with the updated method.
  1080. * @link http://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface.
  1081. */
  1082. public function withMethod($method)
  1083. {
  1084. $new = clone $this;
  1085. if (!is_string($method) ||
  1086. !preg_match('/^[!#$%&\'*+.^_`\|~0-9a-z-]+$/i', $method)
  1087. ) {
  1088. throw new InvalidArgumentException(sprintf(
  1089. 'Unsupported HTTP method "%s" provided',
  1090. $method
  1091. ));
  1092. }
  1093. $new->_environment['REQUEST_METHOD'] = $method;
  1094. return $new;
  1095. }
  1096. /**
  1097. * Get all the server environment parameters.
  1098. *
  1099. * Read all of the 'environment' or 'server' data that was
  1100. * used to create this request.
  1101. *
  1102. * @return array
  1103. * @link http://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface.
  1104. */
  1105. public function getServerParams()
  1106. {
  1107. return $this->_environment;
  1108. }
  1109. /**
  1110. * Get all the query parameters in accordance to the PSR-7 specifications. To read specific query values
  1111. * use the alternative getQuery() method.
  1112. *
  1113. * @return array
  1114. * @link http://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface.
  1115. */
  1116. public function getQueryParams()
  1117. {
  1118. return $this->query;
  1119. }
  1120. /**
  1121. * Update the query string data and get a new instance.
  1122. *
  1123. * @param array $query The query string data to use
  1124. * @return static A new instance with the updated query string data.
  1125. * @link http://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface.
  1126. */
  1127. public function withQueryParams(array $query)
  1128. {
  1129. $new = clone $this;
  1130. $new->query = $query;
  1131. return $new;
  1132. }
  1133. /**
  1134. * Get the host that the request was handled on.
  1135. *
  1136. * @return string
  1137. */
  1138. public function host()
  1139. {
  1140. if ($this->trustProxy && $this->getEnv('HTTP_X_FORWARDED_HOST')) {
  1141. return $this->getEnv('HTTP_X_FORWARDED_HOST');
  1142. }
  1143. return $this->getEnv('HTTP_HOST');
  1144. }
  1145. /**
  1146. * Get the port the request was handled on.
  1147. *
  1148. * @return string
  1149. */
  1150. public function port()
  1151. {
  1152. if ($this->trustProxy && $this->getEnv('HTTP_X_FORWARDED_PORT')) {
  1153. return $this->getEnv('HTTP_X_FORWARDED_PORT');
  1154. }
  1155. return $this->getEnv('SERVER_PORT');
  1156. }
  1157. /**
  1158. * Get the current url scheme used for the request.
  1159. *
  1160. * e.g. 'http', or 'https'
  1161. *
  1162. * @return string The scheme used for the request.
  1163. */
  1164. public function scheme()
  1165. {
  1166. if ($this->trustProxy && $this->getEnv('HTTP_X_FORWARDED_PROTO')) {
  1167. return $this->getEnv('HTTP_X_FORWARDED_PROTO');
  1168. }
  1169. return $this->getEnv('HTTPS') ? 'https' : 'http';
  1170. }
  1171. /**
  1172. * Get the domain name and include $tldLength segments of the tld.
  1173. *
  1174. * @param int $tldLength Number of segments your tld contains. For example: `example.com` contains 1 tld.
  1175. * While `example.co.uk` contains 2.
  1176. * @return string Domain name without subdomains.
  1177. */
  1178. public function domain($tldLength = 1)
  1179. {
  1180. $segments = explode('.', $this->host());
  1181. $domain = array_slice($segments, -1 * ($tldLength + 1));
  1182. return implode('.', $domain);
  1183. }
  1184. /**
  1185. * Get the subdomains for a host.
  1186. *
  1187. * @param int $tldLength Number of segments your tld contains. For example: `example.com` contains 1 tld.
  1188. * While `example.co.uk` contains 2.
  1189. * @return array An array of subdomains.
  1190. */
  1191. public function subdomains($tldLength = 1)
  1192. {
  1193. $segments = explode('.', $this->host());
  1194. return array_slice($segments, 0, -1 * ($tldLength + 1));
  1195. }
  1196. /**
  1197. * Find out which content types the client accepts or check if they accept a
  1198. * particular type of content.
  1199. *
  1200. * #### Get all types:
  1201. *
  1202. * ```
  1203. * $this->request->accepts();
  1204. * ```
  1205. *
  1206. * #### Check for a single type:
  1207. *
  1208. * ```
  1209. * $this->request->accepts('application/json');
  1210. * ```
  1211. *
  1212. * This method will order the returned content types by the preference values indicated
  1213. * by the client.
  1214. *
  1215. * @param string|null $type The content type to check for. Leave null to get all types a client accepts.
  1216. * @return array|bool Either an array of all the types the client accepts or a boolean if they accept the
  1217. * provided type.
  1218. */
  1219. public function accepts($type = null)
  1220. {
  1221. $raw = $this->parseAccept();
  1222. $accept = [];
  1223. foreach ($raw as $types) {
  1224. $accept = array_merge($accept, $types);
  1225. }
  1226. if ($type === null) {
  1227. return $accept;
  1228. }
  1229. return in_array($type, $accept);
  1230. }
  1231. /**
  1232. * Parse the HTTP_ACCEPT header and return a sorted array with content types
  1233. * as the keys, and pref values as the values.
  1234. *
  1235. * Generally you want to use Cake\Http\ServerRequest::accept() to get a simple list
  1236. * of the accepted content types.
  1237. *
  1238. * @return array An array of prefValue => [content/types]
  1239. */
  1240. public function parseAccept()
  1241. {
  1242. return $this->_parseAcceptWithQualifier($this->getHeaderLine('Accept'));
  1243. }
  1244. /**
  1245. * Get the languages accepted by the client, or check if a specific language is accepted.
  1246. *
  1247. * Get the list of accepted languages:
  1248. *
  1249. * ``` \Cake\Http\ServerRequest::acceptLanguage(); ```
  1250. *
  1251. * Check if a specific language is accepted:
  1252. *
  1253. * ``` \Cake\Http\ServerRequest::acceptLanguage('es-es'); ```
  1254. *
  1255. * @param string|null $language The language to test.
  1256. * @return array|bool If a $language is provided, a boolean. Otherwise the array of accepted languages.
  1257. */
  1258. public function acceptLanguage($language = null)
  1259. {
  1260. $raw = $this->_parseAcceptWithQualifier($this->getHeaderLine('Accept-Language'));
  1261. $accept = [];
  1262. foreach ($raw as $languages) {
  1263. foreach ($languages as &$lang) {
  1264. if (strpos($lang, '_')) {
  1265. $lang = str_replace('_', '-', $lang);
  1266. }
  1267. $lang = strtolower($lang);
  1268. }
  1269. $accept = array_merge($accept, $languages);
  1270. }
  1271. if ($language === null) {
  1272. return $accept;
  1273. }
  1274. return in_array(strtolower($language), $accept);
  1275. }
  1276. /**
  1277. * Parse Accept* headers with qualifier options.
  1278. *
  1279. * Only qualifiers will be extracted, any other accept extensions will be
  1280. * discarded as they are not frequently used.
  1281. *
  1282. * @param string $header Header to parse.
  1283. * @return array
  1284. */
  1285. protected function _parseAcceptWithQualifier($header)
  1286. {
  1287. $accept = [];
  1288. $header = explode(',', $header);
  1289. foreach (array_filter($header) as $value) {
  1290. $prefValue = '1.0';
  1291. $value = trim($value);
  1292. $semiPos = strpos($value, ';');
  1293. if ($semiPos !== false) {
  1294. $params = explode(';', $value);
  1295. $value = trim($params[0]);
  1296. foreach ($params as $param) {
  1297. $qPos = strpos($param, 'q=');
  1298. if ($qPos !== false) {
  1299. $prefValue = substr($param, $qPos + 2);
  1300. }
  1301. }
  1302. }
  1303. if (!isset($accept[$prefValue])) {
  1304. $accept[$prefValue] = [];
  1305. }
  1306. if ($prefValue) {
  1307. $accept[$prefValue][] = $value;
  1308. }
  1309. }
  1310. krsort($accept);
  1311. return $accept;
  1312. }
  1313. /**
  1314. * Provides a read accessor for `$this->query`.
  1315. * Allows you to use a `Hash::get()` compatible syntax for reading post data.
  1316. *
  1317. * @param string|null $name Query string variable name or null to read all.
  1318. * @return string|array|null The value being read
  1319. * @deprecated 3.4.0 Use getQuery() or the PSR-7 getQueryParams() and withQueryParams() methods instead.
  1320. */
  1321. public function query($name = null)
  1322. {
  1323. deprecationWarning(
  1324. 'ServerRequest::query() is deprecated. ' .
  1325. 'Use getQuery() or the PSR-7 getQueryParams() and withQueryParams() methods instead.'
  1326. );
  1327. if ($name === null) {
  1328. return $this->query;
  1329. }
  1330. return $this->getQuery($name);
  1331. }
  1332. /**
  1333. * Read a specific query value or dotted path.
  1334. *
  1335. * Developers are encouraged to use getQueryParams() when possible as it is PSR-7 compliant, and this method
  1336. * is not.
  1337. *
  1338. * ### PSR-7 Alternative
  1339. *
  1340. * ```
  1341. * $value = Hash::get($request->getQueryParams(), 'Post.id', null);
  1342. * ```
  1343. *
  1344. * @param string|null $name The name or dotted path to the query param or null to read all.
  1345. * @param mixed $default The default value if the named parameter is not set, and $name is not null.
  1346. * @return null|string|array Query data.
  1347. * @see ServerRequest::getQueryParams()
  1348. */
  1349. public function getQuery($name = null, $default = null)
  1350. {
  1351. if ($name === null) {
  1352. return $this->query;
  1353. }
  1354. return Hash::get($this->query, $name, $default);
  1355. }
  1356. /**
  1357. * Provides a read/write accessor for `$this->data`.
  1358. * Allows you to use a `Hash::get()` compatible syntax for reading post data.
  1359. *
  1360. * ### Reading values.
  1361. *
  1362. * ```
  1363. * $request->data('Post.title');
  1364. * ```
  1365. *
  1366. * When reading values you will get `null` for keys/values that do not exist.
  1367. *
  1368. * ### Writing values
  1369. *
  1370. * ```
  1371. * $request->data('Post.title', 'New post!');
  1372. * ```
  1373. *
  1374. * You can write to any value, even paths/keys that do not exist, and the arrays
  1375. * will be created for you.
  1376. *
  1377. * @param string|null $name Dot separated name of the value to read/write
  1378. * @param mixed ...$args The data to set (deprecated)
  1379. * @return mixed|$this Either the value being read, or this so you can chain consecutive writes.
  1380. * @deprecated 3.4.0 Use withData() and getData() or getParsedBody() instead.
  1381. */
  1382. public function data($name = null, ...$args)
  1383. {
  1384. deprecationWarning(
  1385. 'ServerRequest::data() is deprecated. ' .
  1386. 'Use withData() and getData() or getParsedBody() instead.'
  1387. );
  1388. if (count($args) === 1) {
  1389. $this->data = Hash::insert($this->data, $name, $args[0]);
  1390. return $this;
  1391. }
  1392. if ($name !== null) {
  1393. return Hash::get($this->data, $name);
  1394. }
  1395. return $this->data;
  1396. }
  1397. /**
  1398. * Provides a safe accessor for request data. Allows
  1399. * you to use Hash::get() compatible paths.
  1400. *
  1401. * ### Reading values.
  1402. *
  1403. * ```
  1404. * // get all data
  1405. * $request->getData();
  1406. *
  1407. * // Read a specific field.
  1408. * $request->getData('Post.title');
  1409. *
  1410. * // With a default value.
  1411. * $request->getData('Post.not there', 'default value');
  1412. * ```
  1413. *
  1414. * When reading values you will get `null` for keys/values that do not exist.
  1415. *
  1416. * @param string|null $name Dot separated name of the value to read. Or null to read all data.
  1417. * @param mixed $default The default data.
  1418. * @return null|string|array The value being read.
  1419. */
  1420. public function getData($name = null, $default = null)
  1421. {
  1422. if ($name === null) {
  1423. return $this->data;
  1424. }
  1425. if (!is_array($this->data) && $name) {
  1426. return $default;
  1427. }
  1428. return Hash::get($this->data, $name, $default);
  1429. }
  1430. /**
  1431. * Safely access the values in $this->params.
  1432. *
  1433. * @param string $name The name of the parameter to get.
  1434. * @param mixed ...$args Value to set (deprecated).
  1435. * @return mixed|$this The value of the provided parameter. Will
  1436. * return false if the parameter doesn't exist or is falsey.
  1437. * @deprecated 3.4.0 Use getParam() and withParam() instead.
  1438. */
  1439. public function param($name, ...$args)
  1440. {
  1441. deprecationWarning(
  1442. 'ServerRequest::param() is deprecated. ' .
  1443. 'Use getParam() and withParam() instead.'
  1444. );
  1445. if (count($args) === 1) {
  1446. $this->params = Hash::insert($this->params, $name, $args[0]);
  1447. return $this;
  1448. }
  1449. return $this->getParam($name);
  1450. }
  1451. /**
  1452. * Read data from `php://input`. Useful when interacting with XML or JSON
  1453. * request body content.
  1454. *
  1455. * Getting input with a decoding function:
  1456. *
  1457. * ```
  1458. * $this->request->input('json_decode');
  1459. * ```
  1460. *
  1461. * Getting input using a decoding function, and additional params:
  1462. *
  1463. * ```
  1464. * $this->request->input('Xml::build', ['return' => 'DOMDocument']);
  1465. * ```
  1466. *
  1467. * Any additional parameters are applied to the callback in the order they are given.
  1468. *
  1469. * @param string|null $callback A decoding callback that will convert the string data to another
  1470. * representation. Leave empty to access the raw input data. You can also
  1471. * supply additional parameters for the decoding callback using var args, see above.
  1472. * @param array ...$args The additional arguments
  1473. * @return string The decoded/processed request data.
  1474. */
  1475. public function input($callback = null, ...$args)
  1476. {
  1477. $this->stream->rewind();
  1478. $input = $this->stream->getContents();
  1479. if ($callback) {
  1480. array_unshift($args, $input);
  1481. return call_user_func_array($callback, $args);
  1482. }
  1483. return $input;
  1484. }
  1485. /**
  1486. * Read cookie data from the request's cookie data.
  1487. *
  1488. * @param string $key The key you want to read.
  1489. * @return null|string Either the cookie value, or null if the value doesn't exist.
  1490. * @deprecated 3.4.0 Use getCookie() instead.
  1491. */
  1492. public function cookie($key)
  1493. {
  1494. deprecationWarning(
  1495. 'ServerRequest::cookie() is deprecated. ' .
  1496. 'Use getCookie() instead.'
  1497. );
  1498. if (isset($this->cookies[$key])) {
  1499. return $this->cookies[$key];
  1500. }
  1501. return null;
  1502. }
  1503. /**
  1504. * Read cookie data from the request's cookie data.
  1505. *
  1506. * @param string $key The key or dotted path you want to read.
  1507. * @param string $default The default value if the cookie is not set.
  1508. * @return null|array|string Either the cookie value, or null if the value doesn't exist.
  1509. */
  1510. public function getCookie($key, $default = null)
  1511. {
  1512. return Hash::get($this->cookies, $key, $default);
  1513. }
  1514. /**
  1515. * Get a cookie collection based on the request's cookies
  1516. *
  1517. * The CookieCollection lets you interact with request cookies using
  1518. * `\Cake\Http\Cookie\Cookie` objects and can make converting request cookies
  1519. * into response cookies easier.
  1520. *
  1521. * This method will create a new cookie collection each time it is called.
  1522. * This is an optimization that allows fewer objects to be allocated until
  1523. * the more complex CookieCollection is needed. In general you should prefer
  1524. * `getCookie()` and `getCookieParams()` over this method. Using a CookieCollection
  1525. * is ideal if your cookies contain complex JSON encoded data.
  1526. *
  1527. * @return \Cake\Http\Cookie\CookieCollection
  1528. */
  1529. public function getCookieCollection()
  1530. {
  1531. return CookieCollection::createFromServerRequest($this);
  1532. }
  1533. /**
  1534. * Replace the cookies in the request with those contained in
  1535. * the provided CookieCollection.
  1536. *
  1537. * @param \Cake\Http\Cookie\CookieCollection $cookies The cookie collection
  1538. * @return static
  1539. */
  1540. public function withCookieCollection(CookieCollection $cookies)
  1541. {
  1542. $new = clone $this;
  1543. $values = [];
  1544. foreach ($cookies as $cookie) {
  1545. $values[$cookie->getName()] = $cookie->getValue();
  1546. }
  1547. $new->cookies = $values;
  1548. return $new;
  1549. }
  1550. /**
  1551. * Get all the cookie data from the request.
  1552. *
  1553. * @return array An array of cookie data.
  1554. */
  1555. public function getCookieParams()
  1556. {
  1557. return $this->cookies;
  1558. }
  1559. /**
  1560. * Replace the cookies and get a new request instance.
  1561. *
  1562. * @param array $cookies The new cookie data to use.
  1563. * @return static
  1564. */
  1565. public function withCookieParams(array $cookies)
  1566. {
  1567. $new = clone $this;
  1568. $new->cookies = $cookies;
  1569. return $new;
  1570. }
  1571. /**
  1572. * Get the parsed request body data.
  1573. *
  1574. * If the request Content-Type is either application/x-www-form-urlencoded
  1575. * or multipart/form-data, nd the request method is POST, this will be the
  1576. * post data. For other content types, it may be the deserialized request
  1577. * body.
  1578. *
  1579. * @return null|array|object The deserialized body parameters, if any.
  1580. * These will typically be an array or object.
  1581. */
  1582. public function getParsedBody()
  1583. {
  1584. return $this->data;
  1585. }
  1586. /**
  1587. * Update the parsed body and get a new instance.
  1588. *
  1589. * @param null|array|object $data The deserialized body data. This will
  1590. * typically be in an array or object.
  1591. * @return static
  1592. */
  1593. public function withParsedBody($data)
  1594. {
  1595. $new = clone $this;
  1596. $new->data = $data;
  1597. return $new;
  1598. }
  1599. /**
  1600. * Retrieves the HTTP protocol version as a string.
  1601. *
  1602. * @return string HTTP protocol version.
  1603. */
  1604. public function getProtocolVersion()
  1605. {
  1606. if ($this->protocol) {
  1607. return $this->protocol;
  1608. }
  1609. // Lazily populate this data as it is generally not used.
  1610. preg_match('/^HTTP\/([\d.]+)$/', $this->getEnv('SERVER_PROTOCOL'), $match);
  1611. $protocol = '1.1';
  1612. if (isset($match[1])) {
  1613. $protocol = $match[1];
  1614. }
  1615. $this->protocol = $protocol;
  1616. return $this->protocol;
  1617. }
  1618. /**
  1619. * Return an instance with the specified HTTP protocol version.
  1620. *
  1621. * The version string MUST contain only the HTTP version number (e.g.,
  1622. * "1.1", "1.0").
  1623. *
  1624. * @param string $version HTTP protocol version
  1625. * @return static
  1626. */
  1627. public function withProtocolVersion($version)
  1628. {
  1629. if (!preg_match('/^(1\.[01]|2)$/', $version)) {
  1630. throw new InvalidArgumentException("Unsupported protocol version '{$version}' provided");
  1631. }
  1632. $new = clone $this;
  1633. $new->protocol = $version;
  1634. return $new;
  1635. }
  1636. /**
  1637. * Get a value from the request's environment data.
  1638. * Fallback to using env() if the key is not set in the $environment property.
  1639. *
  1640. * @param string $key The key you want to read from.
  1641. * @param string|null $default Default value when trying to retrieve an environment
  1642. * variable's value that does not exist.
  1643. * @return string|null Either the environment value, or null if the value doesn't exist.
  1644. */
  1645. public function getEnv($key, $default = null)
  1646. {
  1647. $key = strtoupper($key);
  1648. if (!array_key_exists($key, $this->_environment)) {
  1649. $this->_environment[$key] = env($key);
  1650. }
  1651. return $this->_environment[$key] !== null ? $this->_environment[$key] : $default;
  1652. }
  1653. /**
  1654. * Update the request with a new environment data element.
  1655. *
  1656. * Returns an updated request object. This method returns
  1657. * a *new* request object and does not mutate the request in-place.
  1658. *
  1659. * @param string $key The key you want to write to.
  1660. * @param string $value Value to set
  1661. * @return static
  1662. */
  1663. public function withEnv($key, $value)
  1664. {
  1665. $new = clone $this;
  1666. $new->_environment[$key] = $value;
  1667. $new->clearDetectorCache();
  1668. return $new;
  1669. }
  1670. /**
  1671. * Get/Set value from the request's environment data.
  1672. * Fallback to using env() if key not set in $environment property.
  1673. *
  1674. * @deprecated 3.5.0 Use getEnv()/withEnv() instead.
  1675. * @param string $key The key you want to read/write from/to.
  1676. * @param string|null $value Value to set. Default null.
  1677. * @param string|null $default Default value when trying to retrieve an environment
  1678. * variable's value that does not exist. The value parameter must be null.
  1679. * @return $this|string|null This instance if used as setter,
  1680. * if used as getter either the environment value, or null if the value doesn't exist.
  1681. */
  1682. public function env($key, $value = null, $default = null)
  1683. {
  1684. deprecationWarning(
  1685. 'ServerRequest::env() is deprecated. ' .
  1686. 'Use getEnv()/withEnv() instead.'
  1687. );
  1688. if ($value !== null) {
  1689. $this->_environment[$key] = $value;
  1690. $this->clearDetectorCache();
  1691. return $this;
  1692. }
  1693. $key = strtoupper($key);
  1694. if (!array_key_exists($key, $this->_environment)) {
  1695. $this->_environment[$key] = env($key);
  1696. }
  1697. return $this->_environment[$key] !== null ? $this->_environment[$key] : $default;
  1698. }
  1699. /**
  1700. * Allow only certain HTTP request methods, if the request method does not match
  1701. * a 405 error will be shown and the required "Allow" response header will be set.
  1702. *
  1703. * Example:
  1704. *
  1705. * $this->request->allowMethod('post');
  1706. * or
  1707. * $this->request->allowMethod(['post', 'delete']);
  1708. *
  1709. * If the request would be GET, response header "Allow: POST, DELETE" will be set
  1710. * and a 405 error will be returned.
  1711. *
  1712. * @param string|array $methods Allowed HTTP request methods.
  1713. * @return bool true
  1714. * @throws \Cake\Http\Exception\MethodNotAllowedException
  1715. */
  1716. public function allowMethod($methods)
  1717. {
  1718. $methods = (array)$methods;
  1719. foreach ($methods as $method) {
  1720. if ($this->is($method)) {
  1721. return true;
  1722. }
  1723. }
  1724. $allowed = strtoupper(implode(', ', $methods));
  1725. $e = new MethodNotAllowedException();
  1726. $e->responseHeader('Allow', $allowed);
  1727. throw $e;
  1728. }
  1729. /**
  1730. * Read data from php://input, mocked in tests.
  1731. *
  1732. * @return string contents of php://input
  1733. */
  1734. protected function _readInput()
  1735. {
  1736. if (empty($this->_input)) {
  1737. $fh = fopen('php://input', 'rb');
  1738. $content = stream_get_contents($fh);
  1739. fclose($fh);
  1740. $this->_input = $content;
  1741. }
  1742. return $this->_input;
  1743. }
  1744. /**
  1745. * Modify data originally from `php://input`. Useful for altering json/xml data
  1746. * in middleware or DispatcherFilters before it gets to RequestHandlerComponent
  1747. *
  1748. * @param string $input A string to replace original parsed data from input()
  1749. * @return void
  1750. * @deprecated 3.4.0 This method will be removed in 4.0.0. Use withBody() instead.
  1751. */
  1752. public function setInput($input)
  1753. {
  1754. deprecationWarning(
  1755. 'This method will be removed in 4.0.0.' .
  1756. 'Use withBody() instead.'
  1757. );
  1758. $stream = new Stream('php://memory', 'rw');
  1759. $stream->write($input);
  1760. $stream->rewind();
  1761. $this->stream = $stream;
  1762. }
  1763. /**
  1764. * Update the request with a new request data element.
  1765. *
  1766. * Returns an updated request object. This method returns
  1767. * a *new* request object and does not mutate the request in-place.
  1768. *
  1769. * @param string $name The dot separated path to insert $value at.
  1770. * @param mixed $value The value to insert into the request data.
  1771. * @return static
  1772. */
  1773. public function withData($name, $value)
  1774. {
  1775. $copy = clone $this;
  1776. $copy->data = Hash::insert($copy->data, $name, $value);
  1777. return $copy;
  1778. }
  1779. /**
  1780. * Update the request removing a data element.
  1781. *
  1782. * Returns an updated request object. This method returns
  1783. * a *new* request object and does not mutate the request in-place.
  1784. *
  1785. * @param string $name The dot separated path to remove.
  1786. * @return static
  1787. */
  1788. public function withoutData($name)
  1789. {
  1790. $copy = clone $this;
  1791. $copy->data = Hash::remove($copy->data, $name);
  1792. return $copy;
  1793. }
  1794. /**
  1795. * Update the request with a new routing parameter
  1796. *
  1797. * Returns an updated request object. This method returns
  1798. * a *new* request object and does not mutate the request in-place.
  1799. *
  1800. * @param string $name The dot separated path to insert $value at.
  1801. * @param mixed $value The value to insert into the the request parameters.
  1802. * @return static
  1803. */
  1804. public function withParam($name, $value)
  1805. {
  1806. $copy = clone $this;
  1807. $copy->params = Hash::insert($copy->params, $name, $value);
  1808. return $copy;
  1809. }
  1810. /**
  1811. * Safely access the values in $this->params.
  1812. *
  1813. * @param string $name The name or dotted path to parameter.
  1814. * @param mixed $default The default value if $name is not set.
  1815. * @return mixed
  1816. */
  1817. public function getParam($name, $default = false)
  1818. {
  1819. return Hash::get($this->params, $name, $default);
  1820. }
  1821. /**
  1822. * Return an instance with the specified request attribute.
  1823. *
  1824. * @param string $name The attribute name.
  1825. * @param mixed $value The value of the attribute.
  1826. * @return static
  1827. */
  1828. public function withAttribute($name, $value)
  1829. {
  1830. $new = clone $this;
  1831. if (in_array($name, $this->emulatedAttributes, true)) {
  1832. $new->{$name} = $value;
  1833. } else {
  1834. $new->attributes[$name] = $value;
  1835. }
  1836. return $new;
  1837. }
  1838. /**
  1839. * Return an instance without the specified request attribute.
  1840. *
  1841. * @param string $name The attribute name.
  1842. * @return static
  1843. * @throws InvalidArgumentException
  1844. */
  1845. public function withoutAttribute($name)
  1846. {
  1847. $new = clone $this;
  1848. if (in_array($name, $this->emulatedAttributes, true)) {
  1849. throw new InvalidArgumentException(
  1850. "You cannot unset '$name'. It is a required CakePHP attribute."
  1851. );
  1852. }
  1853. unset($new->attributes[$name]);
  1854. return $new;
  1855. }
  1856. /**
  1857. * Read an attribute from the request, or get the default
  1858. *
  1859. * @param string $name The attribute name.
  1860. * @param mixed|null $default The default value if the attribute has not been set.
  1861. * @return mixed
  1862. */
  1863. public function getAttribute($name, $default = null)
  1864. {
  1865. if (in_array($name, $this->emulatedAttributes, true)) {
  1866. return $this->{$name};
  1867. }
  1868. if (array_key_exists($name, $this->attributes)) {
  1869. return $this->attributes[$name];
  1870. }
  1871. return $default;
  1872. }
  1873. /**
  1874. * Get all the attributes in the request.
  1875. *
  1876. * This will include the params, webroot, and base attributes that CakePHP
  1877. * provides.
  1878. *
  1879. * @return array
  1880. */
  1881. public function getAttributes()
  1882. {
  1883. $emulated = [
  1884. 'params' => $this->params,
  1885. 'webroot' => $this->webroot,
  1886. 'base' => $this->base
  1887. ];
  1888. return $this->attributes + $emulated;
  1889. }
  1890. /**
  1891. * Get the uploaded file from a dotted path.
  1892. *
  1893. * @param string $path The dot separated path to the file you want.
  1894. * @return null|\Psr\Http\Message\UploadedFileInterface
  1895. */
  1896. public function getUploadedFile($path)
  1897. {
  1898. $file = Hash::get($this->uploadedFiles, $path);
  1899. if (!$file instanceof UploadedFile) {
  1900. return null;
  1901. }
  1902. return $file;
  1903. }
  1904. /**
  1905. * Get the array of uploaded files from the request.
  1906. *
  1907. * @return array
  1908. */
  1909. public function getUploadedFiles()
  1910. {
  1911. return $this->uploadedFiles;
  1912. }
  1913. /**
  1914. * Update the request replacing the files, and creating a new instance.
  1915. *
  1916. * @param array $files An array of uploaded file objects.
  1917. * @return static
  1918. * @throws InvalidArgumentException when $files contains an invalid object.
  1919. */
  1920. public function withUploadedFiles(array $files)
  1921. {
  1922. $this->validateUploadedFiles($files, '');
  1923. $new = clone $this;
  1924. $new->uploadedFiles = $files;
  1925. return $new;
  1926. }
  1927. /**
  1928. * Recursively validate uploaded file data.
  1929. *
  1930. * @param array $uploadedFiles The new files array to validate.
  1931. * @param string $path The path thus far.
  1932. * @return void
  1933. * @throws InvalidArgumentException If any leaf elements are not valid files.
  1934. */
  1935. protected function validateUploadedFiles(array $uploadedFiles, $path)
  1936. {
  1937. foreach ($uploadedFiles as $key => $file) {
  1938. if (is_array($file)) {
  1939. $this->validateUploadedFiles($file, $key . '.');
  1940. continue;
  1941. }
  1942. if (!$file instanceof UploadedFileInterface) {
  1943. throw new InvalidArgumentException("Invalid file at '{$path}{$key}'");
  1944. }
  1945. }
  1946. }
  1947. /**
  1948. * Gets the body of the message.
  1949. *
  1950. * @return \Psr\Http\Message\StreamInterface Returns the body as a stream.
  1951. */
  1952. public function getBody()
  1953. {
  1954. return $this->stream;
  1955. }
  1956. /**
  1957. * Return an instance with the specified message body.
  1958. *
  1959. * @param \Psr\Http\Message\StreamInterface $body The new request body
  1960. * @return static
  1961. */
  1962. public function withBody(StreamInterface $body)
  1963. {
  1964. $new = clone $this;
  1965. $new->stream = $body;
  1966. return $new;
  1967. }
  1968. /**
  1969. * Retrieves the URI instance.
  1970. *
  1971. * @return \Psr\Http\Message\UriInterface Returns a UriInterface instance
  1972. * representing the URI of the request.
  1973. */
  1974. public function getUri()
  1975. {
  1976. return $this->uri;
  1977. }
  1978. /**
  1979. * Return an instance with the specified uri
  1980. *
  1981. * *Warning* Replacing the Uri will not update the `base`, `webroot`,
  1982. * and `url` attributes.
  1983. *
  1984. * @param \Psr\Http\Message\UriInterface $uri The new request uri
  1985. * @param bool $preserveHost Whether or not the host should be retained.
  1986. * @return static
  1987. */
  1988. public function withUri(UriInterface $uri, $preserveHost = false)
  1989. {
  1990. $new = clone $this;
  1991. $new->uri = $uri;
  1992. if ($preserveHost && $this->hasHeader('Host')) {
  1993. return $new;
  1994. }
  1995. $host = $uri->getHost();
  1996. if (!$host) {
  1997. return $new;
  1998. }
  1999. if ($uri->getPort()) {
  2000. $host .= ':' . $uri->getPort();
  2001. }
  2002. $new->_environment['HTTP_HOST'] = $host;
  2003. return $new;
  2004. }
  2005. /**
  2006. * Create a new instance with a specific request-target.
  2007. *
  2008. * You can use this method to overwrite the request target that is
  2009. * inferred from the request's Uri. This also lets you change the request
  2010. * target's form to an absolute-form, authority-form or asterisk-form
  2011. *
  2012. * @link https://tools.ietf.org/html/rfc7230#section-2.7 (for the various
  2013. * request-target forms allowed in request messages)
  2014. * @param string $target The request target.
  2015. * @return static
  2016. */
  2017. public function withRequestTarget($target)
  2018. {
  2019. $new = clone $this;
  2020. $new->requestTarget = $target;
  2021. return $new;
  2022. }
  2023. /**
  2024. * Retrieves the request's target.
  2025. *
  2026. * Retrieves the message's request-target either as it was requested,
  2027. * or as set with `withRequestTarget()`. By default this will return the
  2028. * application relative path without base directory, and the query string
  2029. * defined in the SERVER environment.
  2030. *
  2031. * @return string
  2032. */
  2033. public function getRequestTarget()
  2034. {
  2035. if ($this->requestTarget !== null) {
  2036. return $this->requestTarget;
  2037. }
  2038. $target = $this->uri->getPath();
  2039. if ($this->uri->getQuery()) {
  2040. $target .= '?' . $this->uri->getQuery();
  2041. }
  2042. if (empty($target)) {
  2043. $target = '/';
  2044. }
  2045. return $target;
  2046. }
  2047. /**
  2048. * Array access read implementation
  2049. *
  2050. * @param string $name Name of the key being accessed.
  2051. * @return mixed
  2052. * @deprecated 3.4.0 The ArrayAccess methods will be removed in 4.0.0. Use getParam(), getData() and getQuery() instead.
  2053. */
  2054. public function offsetGet($name)
  2055. {
  2056. deprecationWarning(
  2057. 'The ArrayAccess methods will be removed in 4.0.0.' .
  2058. 'Use getParam(), getData() and getQuery() instead.'
  2059. );
  2060. if (isset($this->params[$name])) {
  2061. return $this->params[$name];
  2062. }
  2063. if ($name === 'url') {
  2064. return $this->query;
  2065. }
  2066. if ($name === 'data') {
  2067. return $this->data;
  2068. }
  2069. return null;
  2070. }
  2071. /**
  2072. * Array access write implementation
  2073. *
  2074. * @param string $name Name of the key being written
  2075. * @param mixed $value The value being written.
  2076. * @return void
  2077. * @deprecated 3.4.0 The ArrayAccess methods will be removed in 4.0.0. Use withParam() instead.
  2078. */
  2079. public function offsetSet($name, $value)
  2080. {
  2081. deprecationWarning(
  2082. 'The ArrayAccess methods will be removed in 4.0.0.' .
  2083. 'Use withParam() instead.'
  2084. );
  2085. $this->params[$name] = $value;
  2086. }
  2087. /**
  2088. * Array access isset() implementation
  2089. *
  2090. * @param string $name thing to check.
  2091. * @return bool
  2092. * @deprecated 3.4.0 The ArrayAccess methods will be removed in 4.0.0. Use getParam() instead.
  2093. */
  2094. public function offsetExists($name)
  2095. {
  2096. deprecationWarning(
  2097. 'The ArrayAccess methods will be removed in 4.0.0.' .
  2098. 'Use getParam() instead.'
  2099. );
  2100. if ($name === 'url' || $name === 'data') {
  2101. return true;
  2102. }
  2103. return isset($this->params[$name]);
  2104. }
  2105. /**
  2106. * Array access unset() implementation
  2107. *
  2108. * @param string $name Name to unset.
  2109. * @return void
  2110. * @deprecated 3.4.0 The ArrayAccess methods will be removed in 4.0.0. Use withParam() instead.
  2111. */
  2112. public function offsetUnset($name)
  2113. {
  2114. deprecationWarning(
  2115. 'The ArrayAccess methods will be removed in 4.0.0.' .
  2116. 'Use withParam() instead.'
  2117. );
  2118. unset($this->params[$name]);
  2119. }
  2120. }
  2121. // @deprecated Add backwards compat alias.
  2122. class_alias('Cake\Http\ServerRequest', 'Cake\Network\Request');