Response.php 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587
  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 Cake\Core\Configure;
  17. use Cake\Filesystem\File;
  18. use Cake\Http\Cookie\Cookie;
  19. use Cake\Http\Cookie\CookieCollection;
  20. use Cake\Http\Cookie\CookieInterface;
  21. use Cake\Log\Log;
  22. use Cake\Network\CorsBuilder;
  23. use Cake\Network\Exception\NotFoundException;
  24. use DateTime;
  25. use DateTimeZone;
  26. use InvalidArgumentException;
  27. use Psr\Http\Message\ResponseInterface;
  28. use Psr\Http\Message\StreamInterface;
  29. use Zend\Diactoros\MessageTrait;
  30. use Zend\Diactoros\Stream;
  31. /**
  32. * Responses contain the response text, status and headers of a HTTP response.
  33. */
  34. class Response implements ResponseInterface
  35. {
  36. use MessageTrait;
  37. /**
  38. * Holds HTTP response statuses
  39. *
  40. * @var array
  41. */
  42. protected $_statusCodes = [
  43. 100 => 'Continue',
  44. 101 => 'Switching Protocols',
  45. 102 => 'Processing',
  46. 200 => 'OK',
  47. 201 => 'Created',
  48. 202 => 'Accepted',
  49. 203 => 'Non-Authoritative Information',
  50. 204 => 'No Content',
  51. 205 => 'Reset Content',
  52. 206 => 'Partial Content',
  53. 207 => 'Multi-status',
  54. 208 => 'Already Reported',
  55. 226 => 'IM used',
  56. 300 => 'Multiple Choices',
  57. 301 => 'Moved Permanently',
  58. 302 => 'Found',
  59. 303 => 'See Other',
  60. 304 => 'Not Modified',
  61. 305 => 'Use Proxy',
  62. 306 => '(Unused)',
  63. 307 => 'Temporary Redirect',
  64. 308 => 'Permanent Redirect',
  65. 400 => 'Bad Request',
  66. 401 => 'Unauthorized',
  67. 402 => 'Payment Required',
  68. 403 => 'Forbidden',
  69. 404 => 'Not Found',
  70. 405 => 'Method Not Allowed',
  71. 406 => 'Not Acceptable',
  72. 407 => 'Proxy Authentication Required',
  73. 408 => 'Request Timeout',
  74. 409 => 'Conflict',
  75. 410 => 'Gone',
  76. 411 => 'Length Required',
  77. 412 => 'Precondition Failed',
  78. 413 => 'Request Entity Too Large',
  79. 414 => 'Request-URI Too Large',
  80. 415 => 'Unsupported Media Type',
  81. 416 => 'Requested range not satisfiable',
  82. 417 => 'Expectation Failed',
  83. 418 => 'I\'m a teapot',
  84. 421 => 'Misdirected Request',
  85. 422 => 'Unprocessable Entity',
  86. 423 => 'Locked',
  87. 424 => 'Failed Dependency',
  88. 425 => 'Unordered Collection',
  89. 426 => 'Upgrade Required',
  90. 428 => 'Precondition Required',
  91. 429 => 'Too Many Requests',
  92. 431 => 'Request Header Fields Too Large',
  93. 444 => 'Connection Closed Without Response',
  94. 451 => 'Unavailable For Legal Reasons',
  95. 499 => 'Client Closed Request',
  96. 500 => 'Internal Server Error',
  97. 501 => 'Not Implemented',
  98. 502 => 'Bad Gateway',
  99. 503 => 'Service Unavailable',
  100. 504 => 'Gateway Timeout',
  101. 505 => 'Unsupported Version',
  102. 506 => 'Variant Also Negotiates',
  103. 507 => 'Insufficient Storage',
  104. 508 => 'Loop Detected',
  105. 510 => 'Not Extended',
  106. 511 => 'Network Authentication Required',
  107. 599 => 'Network Connect Timeout Error',
  108. ];
  109. /**
  110. * Holds type key to mime type mappings for known mime types.
  111. *
  112. * @var array
  113. */
  114. protected $_mimeTypes = [
  115. 'html' => ['text/html', '*/*'],
  116. 'json' => 'application/json',
  117. 'xml' => ['application/xml', 'text/xml'],
  118. 'xhtml' => ['application/xhtml+xml', 'application/xhtml', 'text/xhtml'],
  119. 'webp' => 'image/webp',
  120. 'rss' => 'application/rss+xml',
  121. 'ai' => 'application/postscript',
  122. 'bcpio' => 'application/x-bcpio',
  123. 'bin' => 'application/octet-stream',
  124. 'ccad' => 'application/clariscad',
  125. 'cdf' => 'application/x-netcdf',
  126. 'class' => 'application/octet-stream',
  127. 'cpio' => 'application/x-cpio',
  128. 'cpt' => 'application/mac-compactpro',
  129. 'csh' => 'application/x-csh',
  130. 'csv' => ['text/csv', 'application/vnd.ms-excel'],
  131. 'dcr' => 'application/x-director',
  132. 'dir' => 'application/x-director',
  133. 'dms' => 'application/octet-stream',
  134. 'doc' => 'application/msword',
  135. 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  136. 'drw' => 'application/drafting',
  137. 'dvi' => 'application/x-dvi',
  138. 'dwg' => 'application/acad',
  139. 'dxf' => 'application/dxf',
  140. 'dxr' => 'application/x-director',
  141. 'eot' => 'application/vnd.ms-fontobject',
  142. 'eps' => 'application/postscript',
  143. 'exe' => 'application/octet-stream',
  144. 'ez' => 'application/andrew-inset',
  145. 'flv' => 'video/x-flv',
  146. 'gtar' => 'application/x-gtar',
  147. 'gz' => 'application/x-gzip',
  148. 'bz2' => 'application/x-bzip',
  149. '7z' => 'application/x-7z-compressed',
  150. 'hdf' => 'application/x-hdf',
  151. 'hqx' => 'application/mac-binhex40',
  152. 'ico' => 'image/x-icon',
  153. 'ips' => 'application/x-ipscript',
  154. 'ipx' => 'application/x-ipix',
  155. 'js' => 'application/javascript',
  156. 'jsonapi' => 'application/vnd.api+json',
  157. 'latex' => 'application/x-latex',
  158. 'lha' => 'application/octet-stream',
  159. 'lsp' => 'application/x-lisp',
  160. 'lzh' => 'application/octet-stream',
  161. 'man' => 'application/x-troff-man',
  162. 'me' => 'application/x-troff-me',
  163. 'mif' => 'application/vnd.mif',
  164. 'ms' => 'application/x-troff-ms',
  165. 'nc' => 'application/x-netcdf',
  166. 'oda' => 'application/oda',
  167. 'otf' => 'font/otf',
  168. 'pdf' => 'application/pdf',
  169. 'pgn' => 'application/x-chess-pgn',
  170. 'pot' => 'application/vnd.ms-powerpoint',
  171. 'pps' => 'application/vnd.ms-powerpoint',
  172. 'ppt' => 'application/vnd.ms-powerpoint',
  173. 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  174. 'ppz' => 'application/vnd.ms-powerpoint',
  175. 'pre' => 'application/x-freelance',
  176. 'prt' => 'application/pro_eng',
  177. 'ps' => 'application/postscript',
  178. 'roff' => 'application/x-troff',
  179. 'scm' => 'application/x-lotusscreencam',
  180. 'set' => 'application/set',
  181. 'sh' => 'application/x-sh',
  182. 'shar' => 'application/x-shar',
  183. 'sit' => 'application/x-stuffit',
  184. 'skd' => 'application/x-koan',
  185. 'skm' => 'application/x-koan',
  186. 'skp' => 'application/x-koan',
  187. 'skt' => 'application/x-koan',
  188. 'smi' => 'application/smil',
  189. 'smil' => 'application/smil',
  190. 'sol' => 'application/solids',
  191. 'spl' => 'application/x-futuresplash',
  192. 'src' => 'application/x-wais-source',
  193. 'step' => 'application/STEP',
  194. 'stl' => 'application/SLA',
  195. 'stp' => 'application/STEP',
  196. 'sv4cpio' => 'application/x-sv4cpio',
  197. 'sv4crc' => 'application/x-sv4crc',
  198. 'svg' => 'image/svg+xml',
  199. 'svgz' => 'image/svg+xml',
  200. 'swf' => 'application/x-shockwave-flash',
  201. 't' => 'application/x-troff',
  202. 'tar' => 'application/x-tar',
  203. 'tcl' => 'application/x-tcl',
  204. 'tex' => 'application/x-tex',
  205. 'texi' => 'application/x-texinfo',
  206. 'texinfo' => 'application/x-texinfo',
  207. 'tr' => 'application/x-troff',
  208. 'tsp' => 'application/dsptype',
  209. 'ttc' => 'font/ttf',
  210. 'ttf' => 'font/ttf',
  211. 'unv' => 'application/i-deas',
  212. 'ustar' => 'application/x-ustar',
  213. 'vcd' => 'application/x-cdlink',
  214. 'vda' => 'application/vda',
  215. 'xlc' => 'application/vnd.ms-excel',
  216. 'xll' => 'application/vnd.ms-excel',
  217. 'xlm' => 'application/vnd.ms-excel',
  218. 'xls' => 'application/vnd.ms-excel',
  219. 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  220. 'xlw' => 'application/vnd.ms-excel',
  221. 'zip' => 'application/zip',
  222. 'aif' => 'audio/x-aiff',
  223. 'aifc' => 'audio/x-aiff',
  224. 'aiff' => 'audio/x-aiff',
  225. 'au' => 'audio/basic',
  226. 'kar' => 'audio/midi',
  227. 'mid' => 'audio/midi',
  228. 'midi' => 'audio/midi',
  229. 'mp2' => 'audio/mpeg',
  230. 'mp3' => 'audio/mpeg',
  231. 'mpga' => 'audio/mpeg',
  232. 'ogg' => 'audio/ogg',
  233. 'oga' => 'audio/ogg',
  234. 'spx' => 'audio/ogg',
  235. 'ra' => 'audio/x-realaudio',
  236. 'ram' => 'audio/x-pn-realaudio',
  237. 'rm' => 'audio/x-pn-realaudio',
  238. 'rpm' => 'audio/x-pn-realaudio-plugin',
  239. 'snd' => 'audio/basic',
  240. 'tsi' => 'audio/TSP-audio',
  241. 'wav' => 'audio/x-wav',
  242. 'aac' => 'audio/aac',
  243. 'asc' => 'text/plain',
  244. 'c' => 'text/plain',
  245. 'cc' => 'text/plain',
  246. 'css' => 'text/css',
  247. 'etx' => 'text/x-setext',
  248. 'f' => 'text/plain',
  249. 'f90' => 'text/plain',
  250. 'h' => 'text/plain',
  251. 'hh' => 'text/plain',
  252. 'htm' => ['text/html', '*/*'],
  253. 'ics' => 'text/calendar',
  254. 'm' => 'text/plain',
  255. 'rtf' => 'text/rtf',
  256. 'rtx' => 'text/richtext',
  257. 'sgm' => 'text/sgml',
  258. 'sgml' => 'text/sgml',
  259. 'tsv' => 'text/tab-separated-values',
  260. 'tpl' => 'text/template',
  261. 'txt' => 'text/plain',
  262. 'text' => 'text/plain',
  263. 'avi' => 'video/x-msvideo',
  264. 'fli' => 'video/x-fli',
  265. 'mov' => 'video/quicktime',
  266. 'movie' => 'video/x-sgi-movie',
  267. 'mpe' => 'video/mpeg',
  268. 'mpeg' => 'video/mpeg',
  269. 'mpg' => 'video/mpeg',
  270. 'qt' => 'video/quicktime',
  271. 'viv' => 'video/vnd.vivo',
  272. 'vivo' => 'video/vnd.vivo',
  273. 'ogv' => 'video/ogg',
  274. 'webm' => 'video/webm',
  275. 'mp4' => 'video/mp4',
  276. 'm4v' => 'video/mp4',
  277. 'f4v' => 'video/mp4',
  278. 'f4p' => 'video/mp4',
  279. 'm4a' => 'audio/mp4',
  280. 'f4a' => 'audio/mp4',
  281. 'f4b' => 'audio/mp4',
  282. 'gif' => 'image/gif',
  283. 'ief' => 'image/ief',
  284. 'jpg' => 'image/jpeg',
  285. 'jpeg' => 'image/jpeg',
  286. 'jpe' => 'image/jpeg',
  287. 'pbm' => 'image/x-portable-bitmap',
  288. 'pgm' => 'image/x-portable-graymap',
  289. 'png' => 'image/png',
  290. 'pnm' => 'image/x-portable-anymap',
  291. 'ppm' => 'image/x-portable-pixmap',
  292. 'ras' => 'image/cmu-raster',
  293. 'rgb' => 'image/x-rgb',
  294. 'tif' => 'image/tiff',
  295. 'tiff' => 'image/tiff',
  296. 'xbm' => 'image/x-xbitmap',
  297. 'xpm' => 'image/x-xpixmap',
  298. 'xwd' => 'image/x-xwindowdump',
  299. 'psd' => ['application/photoshop', 'application/psd', 'image/psd', 'image/x-photoshop', 'image/photoshop', 'zz-application/zz-winassoc-psd'],
  300. 'ice' => 'x-conference/x-cooltalk',
  301. 'iges' => 'model/iges',
  302. 'igs' => 'model/iges',
  303. 'mesh' => 'model/mesh',
  304. 'msh' => 'model/mesh',
  305. 'silo' => 'model/mesh',
  306. 'vrml' => 'model/vrml',
  307. 'wrl' => 'model/vrml',
  308. 'mime' => 'www/mime',
  309. 'pdb' => 'chemical/x-pdb',
  310. 'xyz' => 'chemical/x-pdb',
  311. 'javascript' => 'application/javascript',
  312. 'form' => 'application/x-www-form-urlencoded',
  313. 'file' => 'multipart/form-data',
  314. 'xhtml-mobile' => 'application/vnd.wap.xhtml+xml',
  315. 'atom' => 'application/atom+xml',
  316. 'amf' => 'application/x-amf',
  317. 'wap' => ['text/vnd.wap.wml', 'text/vnd.wap.wmlscript', 'image/vnd.wap.wbmp'],
  318. 'wml' => 'text/vnd.wap.wml',
  319. 'wmlscript' => 'text/vnd.wap.wmlscript',
  320. 'wbmp' => 'image/vnd.wap.wbmp',
  321. 'woff' => 'application/x-font-woff',
  322. 'appcache' => 'text/cache-manifest',
  323. 'manifest' => 'text/cache-manifest',
  324. 'htc' => 'text/x-component',
  325. 'rdf' => 'application/xml',
  326. 'crx' => 'application/x-chrome-extension',
  327. 'oex' => 'application/x-opera-extension',
  328. 'xpi' => 'application/x-xpinstall',
  329. 'safariextz' => 'application/octet-stream',
  330. 'webapp' => 'application/x-web-app-manifest+json',
  331. 'vcf' => 'text/x-vcard',
  332. 'vtt' => 'text/vtt',
  333. 'mkv' => 'video/x-matroska',
  334. 'pkpass' => 'application/vnd.apple.pkpass',
  335. 'ajax' => 'text/html'
  336. ];
  337. /**
  338. * Protocol header to send to the client
  339. *
  340. * @var string
  341. */
  342. protected $_protocol = 'HTTP/1.1';
  343. /**
  344. * Status code to send to the client
  345. *
  346. * @var int
  347. */
  348. protected $_status = 200;
  349. /**
  350. * Content type to send. This can be an 'extension' that will be transformed using the $_mimetypes array
  351. * or a complete mime-type
  352. *
  353. * @var string
  354. */
  355. protected $_contentType = 'text/html';
  356. /**
  357. * File object for file to be read out as response
  358. *
  359. * @var \Cake\Filesystem\File
  360. */
  361. protected $_file;
  362. /**
  363. * File range. Used for requesting ranges of files.
  364. *
  365. * @var array
  366. */
  367. protected $_fileRange = [];
  368. /**
  369. * The charset the response body is encoded with
  370. *
  371. * @var string
  372. */
  373. protected $_charset = 'UTF-8';
  374. /**
  375. * Holds all the cache directives that will be converted
  376. * into headers when sending the request
  377. *
  378. * @var array
  379. */
  380. protected $_cacheDirectives = [];
  381. /**
  382. * Collection of cookies to send to the client
  383. *
  384. * @var \Cake\Http\Cookie\CookieCollection
  385. */
  386. protected $_cookies = null;
  387. /**
  388. * Reason Phrase
  389. *
  390. * @var string
  391. */
  392. protected $_reasonPhrase = 'OK';
  393. /**
  394. * Stream mode options.
  395. *
  396. * @var string
  397. */
  398. protected $_streamMode = 'wb+';
  399. /**
  400. * Stream target or resource object.
  401. *
  402. * @var string|resource
  403. */
  404. protected $_streamTarget = 'php://memory';
  405. /**
  406. * Constructor
  407. *
  408. * @param array $options list of parameters to setup the response. Possible values are:
  409. * - body: the response text that should be sent to the client
  410. * - statusCodes: additional allowable response codes
  411. * - status: the HTTP status code to respond with
  412. * - type: a complete mime-type string or an extension mapped in this class
  413. * - charset: the charset for the response body
  414. */
  415. public function __construct(array $options = [])
  416. {
  417. if (isset($options['streamTarget'])) {
  418. $this->_streamTarget = $options['streamTarget'];
  419. }
  420. if (isset($options['streamMode'])) {
  421. $this->_streamMode = $options['streamMode'];
  422. }
  423. if (isset($options['stream'])) {
  424. if (!$options['stream'] instanceof StreamInterface) {
  425. throw new InvalidArgumentException('Stream option must be an object that implements StreamInterface');
  426. }
  427. $this->stream = $options['stream'];
  428. } else {
  429. $this->_createStream();
  430. }
  431. if (isset($options['body'])) {
  432. $this->body($options['body']);
  433. }
  434. if (isset($options['statusCodes'])) {
  435. $this->httpCodes($options['statusCodes']);
  436. }
  437. if (isset($options['status'])) {
  438. $this->statusCode($options['status']);
  439. }
  440. if (!isset($options['charset'])) {
  441. $options['charset'] = Configure::read('App.encoding');
  442. }
  443. $this->_charset = $options['charset'];
  444. if (isset($options['type'])) {
  445. $this->_contentType = $this->resolveType($options['type']);
  446. }
  447. $this->_setContentType();
  448. $this->_cookies = new CookieCollection();
  449. }
  450. /**
  451. * Creates the stream object.
  452. *
  453. * @return void
  454. */
  455. protected function _createStream()
  456. {
  457. $this->stream = new Stream($this->_streamTarget, $this->_streamMode);
  458. }
  459. /**
  460. * Sends the complete response to the client including headers and message body.
  461. * Will echo out the content in the response body.
  462. *
  463. * @return void
  464. * @deprecated 3.4.0 Will be removed in 4.0.0
  465. */
  466. public function send()
  467. {
  468. if ($this->hasHeader('Location') && $this->_status === 200) {
  469. $this->statusCode(302);
  470. }
  471. $this->_setContent();
  472. $this->sendHeaders();
  473. if ($this->_file) {
  474. $this->_sendFile($this->_file, $this->_fileRange);
  475. $this->_file = $this->_fileRange = null;
  476. } else {
  477. $this->_sendContent($this->body());
  478. }
  479. if (function_exists('fastcgi_finish_request')) {
  480. fastcgi_finish_request();
  481. }
  482. }
  483. /**
  484. * Sends the HTTP headers and cookies.
  485. *
  486. * @return void
  487. * @deprecated 3.4.0 Will be removed in 4.0.0
  488. */
  489. public function sendHeaders()
  490. {
  491. $file = $line = null;
  492. if (headers_sent($file, $line)) {
  493. Log::warning("Headers already sent in {$file}:{$line}");
  494. return;
  495. }
  496. $codeMessage = $this->_statusCodes[$this->_status];
  497. $this->_setCookies();
  498. $this->_sendHeader("{$this->_protocol} {$this->_status} {$codeMessage}");
  499. $this->_setContentType();
  500. foreach ($this->headers as $header => $values) {
  501. foreach ((array)$values as $value) {
  502. $this->_sendHeader($header, $value);
  503. }
  504. }
  505. }
  506. /**
  507. * Sets the cookies that have been added via Cake\Http\Response::cookie() before any
  508. * other output is sent to the client. Will set the cookies in the order they
  509. * have been set.
  510. *
  511. * @return void
  512. * @deprecated 3.4.0 Will be removed in 4.0.0
  513. */
  514. protected function _setCookies()
  515. {
  516. foreach ($this->_cookies as $cookie) {
  517. setcookie(
  518. $cookie->getName(),
  519. $cookie->getValue(),
  520. $cookie->getExpiresTimestamp(),
  521. $cookie->getPath(),
  522. $cookie->getDomain(),
  523. $cookie->isSecure(),
  524. $cookie->isHttpOnly()
  525. );
  526. }
  527. }
  528. /**
  529. * Formats the Content-Type header based on the configured contentType and charset
  530. * the charset will only be set in the header if the response is of type text/*
  531. *
  532. * @return void
  533. */
  534. protected function _setContentType()
  535. {
  536. if (in_array($this->_status, [304, 204])) {
  537. $this->_clearHeader('Content-Type');
  538. return;
  539. }
  540. $whitelist = [
  541. 'application/javascript', 'application/json', 'application/xml', 'application/rss+xml'
  542. ];
  543. $charset = false;
  544. if ($this->_charset &&
  545. (strpos($this->_contentType, 'text/') === 0 || in_array($this->_contentType, $whitelist))
  546. ) {
  547. $charset = true;
  548. }
  549. if ($charset) {
  550. $this->_setHeader('Content-Type', "{$this->_contentType}; charset={$this->_charset}");
  551. } else {
  552. $this->_setHeader('Content-Type', "{$this->_contentType}");
  553. }
  554. }
  555. /**
  556. * Sets the response body to an empty text if the status code is 204 or 304
  557. *
  558. * @return void
  559. * @deprecated 3.4.0 Will be removed in 4.0.0
  560. */
  561. protected function _setContent()
  562. {
  563. if (in_array($this->_status, [304, 204])) {
  564. $this->body('');
  565. }
  566. }
  567. /**
  568. * Sends a header to the client.
  569. *
  570. * @param string $name the header name
  571. * @param string|null $value the header value
  572. * @return void
  573. * @deprecated 3.4.0 Will be removed in 4.0.0
  574. */
  575. protected function _sendHeader($name, $value = null)
  576. {
  577. if ($value === null) {
  578. header($name);
  579. } else {
  580. header("{$name}: {$value}");
  581. }
  582. }
  583. /**
  584. * Sends a content string to the client.
  585. *
  586. * If the content is a callable, it is invoked. The callable should either
  587. * return a string or output content directly and have no return value.
  588. *
  589. * @param string|callable $content String to send as response body or callable
  590. * which returns/outputs content.
  591. * @return void
  592. * @deprecated 3.4.0 Will be removed in 4.0.0
  593. */
  594. protected function _sendContent($content)
  595. {
  596. if (!is_string($content) && is_callable($content)) {
  597. $content = $content();
  598. }
  599. echo $content;
  600. }
  601. /**
  602. * Buffers a header string to be sent
  603. * Returns the complete list of buffered headers
  604. *
  605. * ### Single header
  606. * ```
  607. * header('Location', 'http://example.com');
  608. * ```
  609. *
  610. * ### Multiple headers
  611. * ```
  612. * header(['Location' => 'http://example.com', 'X-Extra' => 'My header']);
  613. * ```
  614. *
  615. * ### String header
  616. * ```
  617. * header('WWW-Authenticate: Negotiate');
  618. * ```
  619. *
  620. * ### Array of string headers
  621. * ```
  622. * header(['WWW-Authenticate: Negotiate', 'Content-type: application/pdf']);
  623. * ```
  624. *
  625. * Multiple calls for setting the same header name will have the same effect as setting the header once
  626. * with the last value sent for it
  627. * ```
  628. * header('WWW-Authenticate: Negotiate');
  629. * header('WWW-Authenticate: Not-Negotiate');
  630. * ```
  631. * will have the same effect as only doing
  632. * ```
  633. * header('WWW-Authenticate: Not-Negotiate');
  634. * ```
  635. *
  636. * @param string|array|null $header An array of header strings or a single header string
  637. * - an associative array of "header name" => "header value" is also accepted
  638. * - an array of string headers is also accepted
  639. * @param string|array|null $value The header value(s)
  640. * @return array List of headers to be sent
  641. * @deprecated 3.4.0 Use `withHeader()`, `getHeaderLine()` and `getHeaders()` instead.
  642. */
  643. public function header($header = null, $value = null)
  644. {
  645. if ($header === null) {
  646. return $this->getSimpleHeaders();
  647. }
  648. $headers = is_array($header) ? $header : [$header => $value];
  649. foreach ($headers as $header => $value) {
  650. if (is_numeric($header)) {
  651. list($header, $value) = [$value, null];
  652. }
  653. if ($value === null) {
  654. list($header, $value) = explode(':', $header, 2);
  655. }
  656. $lower = strtolower($header);
  657. if (array_key_exists($lower, $this->headerNames)) {
  658. $header = $this->headerNames[$lower];
  659. } else {
  660. $this->headerNames[$lower] = $header;
  661. }
  662. $this->headers[$header] = is_array($value) ? array_map('trim', $value) : [trim($value)];
  663. }
  664. return $this->getSimpleHeaders();
  665. }
  666. /**
  667. * Backwards compatibility helper for getting flattened headers.
  668. *
  669. * Previously CakePHP would store headers as a simple dictionary, now that
  670. * we're supporting PSR7, the internal storage has each header as an array.
  671. *
  672. * @return array
  673. */
  674. protected function getSimpleHeaders()
  675. {
  676. $out = [];
  677. foreach ($this->headers as $key => $values) {
  678. $header = $this->headerNames[strtolower($key)];
  679. if (count($values) === 1) {
  680. $values = $values[0];
  681. }
  682. $out[$header] = $values;
  683. }
  684. return $out;
  685. }
  686. /**
  687. * Accessor for the location header.
  688. *
  689. * Get/Set the Location header value.
  690. *
  691. * @param null|string $url Either null to get the current location, or a string to set one.
  692. * @return string|null When setting the location null will be returned. When reading the location
  693. * a string of the current location header value (if any) will be returned.
  694. * @deprecated 3.4.0 Mutable responses are deprecated. Use `withLocation()` and `getHeaderLine()`
  695. * instead.
  696. */
  697. public function location($url = null)
  698. {
  699. if ($url === null) {
  700. $result = $this->getHeaderLine('Location');
  701. if (!$result) {
  702. return null;
  703. }
  704. return $result;
  705. }
  706. if ($this->_status === 200) {
  707. $this->_status = 302;
  708. }
  709. $this->_setHeader('Location', $url);
  710. return null;
  711. }
  712. /**
  713. * Return an instance with an updated location header.
  714. *
  715. * If the current status code is 200, it will be replaced
  716. * with 302.
  717. *
  718. * @param string $url The location to redirect to.
  719. * @return static A new response with the Location header set.
  720. */
  721. public function withLocation($url)
  722. {
  723. $new = $this->withHeader('Location', $url);
  724. if ($new->_status === 200) {
  725. $new->_status = 302;
  726. }
  727. return $new;
  728. }
  729. /**
  730. * Sets a header.
  731. *
  732. * @param string $header Header key.
  733. * @param string $value Header value.
  734. * @return void
  735. */
  736. protected function _setHeader($header, $value)
  737. {
  738. $normalized = strtolower($header);
  739. $this->headerNames[$normalized] = $header;
  740. $this->headers[$header] = [$value];
  741. }
  742. /**
  743. * Clear header
  744. *
  745. * @param string $header Header key.
  746. * @return void
  747. */
  748. protected function _clearHeader($header)
  749. {
  750. $normalized = strtolower($header);
  751. if (!isset($this->headerNames[$normalized])) {
  752. return;
  753. }
  754. $original = $this->headerNames[$normalized];
  755. unset($this->headerNames[$normalized], $this->headers[$original]);
  756. }
  757. /**
  758. * Buffers the response message to be sent
  759. * if $content is null the current buffer is returned
  760. *
  761. * @param string|callable|null $content the string or callable message to be sent
  762. * @return string Current message buffer if $content param is passed as null
  763. * @deprecated 3.4.0 Mutable response methods are deprecated. Use `withBody()` and `getBody()` instead.
  764. */
  765. public function body($content = null)
  766. {
  767. if ($content === null) {
  768. if ($this->stream->isSeekable()) {
  769. $this->stream->rewind();
  770. }
  771. $result = $this->stream->getContents();
  772. if (strlen($result) === 0) {
  773. return null;
  774. }
  775. return $result;
  776. }
  777. // Compatibility with closure/streaming responses
  778. if (is_callable($content)) {
  779. $this->stream = new CallbackStream($content);
  780. } else {
  781. $this->_createStream();
  782. $this->stream->write($content);
  783. }
  784. return $content;
  785. }
  786. /**
  787. * Handles the callable body for backward compatibility reasons.
  788. *
  789. * @param callable $content Callable content.
  790. * @return string
  791. */
  792. protected function _handleCallableBody(callable $content)
  793. {
  794. ob_start();
  795. $result1 = $content();
  796. $result2 = ob_get_contents();
  797. ob_get_clean();
  798. if ($result1) {
  799. return $result1;
  800. }
  801. return $result2;
  802. }
  803. /**
  804. * Sets the HTTP status code to be sent
  805. * if $code is null the current code is returned
  806. *
  807. * If the status code is 304 or 204, the existing Content-Type header
  808. * will be cleared, as these response codes have no body.
  809. *
  810. * @param int|null $code the HTTP status code
  811. * @return int Current status code
  812. * @throws \InvalidArgumentException When an unknown status code is reached.
  813. * @deprecated 3.4.0 Use `getStatusCode()` and `withStatus()` instead.
  814. */
  815. public function statusCode($code = null)
  816. {
  817. if ($code === null) {
  818. return $this->_status;
  819. }
  820. if (!isset($this->_statusCodes[$code])) {
  821. throw new InvalidArgumentException('Unknown status code');
  822. }
  823. if (isset($this->_statusCodes[$code])) {
  824. $this->_reasonPhrase = $this->_statusCodes[$code];
  825. }
  826. $this->_status = $code;
  827. $this->_setContentType();
  828. return $code;
  829. }
  830. /**
  831. * Gets the response status code.
  832. *
  833. * The status code is a 3-digit integer result code of the server's attempt
  834. * to understand and satisfy the request.
  835. *
  836. * @return int Status code.
  837. */
  838. public function getStatusCode()
  839. {
  840. return $this->_status;
  841. }
  842. /**
  843. * Return an instance with the specified status code and, optionally, reason phrase.
  844. *
  845. * If no reason phrase is specified, implementations MAY choose to default
  846. * to the RFC 7231 or IANA recommended reason phrase for the response's
  847. * status code.
  848. *
  849. * This method MUST be implemented in such a way as to retain the
  850. * immutability of the message, and MUST return an instance that has the
  851. * updated status and reason phrase.
  852. *
  853. * If the status code is 304 or 204, the existing Content-Type header
  854. * will be cleared, as these response codes have no body.
  855. *
  856. * @link https://tools.ietf.org/html/rfc7231#section-6
  857. * @link https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  858. * @param int $code The 3-digit integer result code to set.
  859. * @param string $reasonPhrase The reason phrase to use with the
  860. * provided status code; if none is provided, implementations MAY
  861. * use the defaults as suggested in the HTTP specification.
  862. * @return static
  863. * @throws \InvalidArgumentException For invalid status code arguments.
  864. */
  865. public function withStatus($code, $reasonPhrase = '')
  866. {
  867. $new = clone $this;
  868. $new->_status = $code;
  869. if (empty($reasonPhrase) && isset($new->_statusCodes[$code])) {
  870. $reasonPhrase = $new->_statusCodes[$code];
  871. }
  872. $new->_reasonPhrase = $reasonPhrase;
  873. $new->_setContentType();
  874. return $new;
  875. }
  876. /**
  877. * Gets the response reason phrase associated with the status code.
  878. *
  879. * Because a reason phrase is not a required element in a response
  880. * status line, the reason phrase value MAY be null. Implementations MAY
  881. * choose to return the default RFC 7231 recommended reason phrase (or those
  882. * listed in the IANA HTTP Status Code Registry) for the response's
  883. * status code.
  884. *
  885. * @link https://tools.ietf.org/html/rfc7231#section-6
  886. * @link http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  887. * @return string Reason phrase; must return an empty string if none present.
  888. */
  889. public function getReasonPhrase()
  890. {
  891. return $this->_reasonPhrase;
  892. }
  893. /**
  894. * Queries & sets valid HTTP response codes & messages.
  895. *
  896. * @param int|array|null $code If $code is an integer, then the corresponding code/message is
  897. * returned if it exists, null if it does not exist. If $code is an array, then the
  898. * keys are used as codes and the values as messages to add to the default HTTP
  899. * codes. The codes must be integers greater than 99 and less than 1000. Keep in
  900. * mind that the HTTP specification outlines that status codes begin with a digit
  901. * between 1 and 5, which defines the class of response the client is to expect.
  902. * Example:
  903. *
  904. * httpCodes(404); // returns [404 => 'Not Found']
  905. *
  906. * httpCodes([
  907. * 381 => 'Unicorn Moved',
  908. * 555 => 'Unexpected Minotaur'
  909. * ]); // sets these new values, and returns true
  910. *
  911. * httpCodes([
  912. * 0 => 'Nothing Here',
  913. * -1 => 'Reverse Infinity',
  914. * 12345 => 'Universal Password',
  915. * 'Hello' => 'World'
  916. * ]); // throws an exception due to invalid codes
  917. *
  918. * For more on HTTP status codes see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6.1
  919. *
  920. * @return mixed Associative array of the HTTP codes as keys, and the message
  921. * strings as values, or null of the given $code does not exist.
  922. * @throws \InvalidArgumentException If an attempt is made to add an invalid status code
  923. * @deprecated 3.4.0 Will be removed in 4.0.0
  924. */
  925. public function httpCodes($code = null)
  926. {
  927. if (empty($code)) {
  928. return $this->_statusCodes;
  929. }
  930. if (is_array($code)) {
  931. $codes = array_keys($code);
  932. $min = min($codes);
  933. if (!is_int($min) || $min < 100 || max($codes) > 999) {
  934. throw new InvalidArgumentException('Invalid status code');
  935. }
  936. $this->_statusCodes = $code + $this->_statusCodes;
  937. return true;
  938. }
  939. if (!isset($this->_statusCodes[$code])) {
  940. return null;
  941. }
  942. return [$code => $this->_statusCodes[$code]];
  943. }
  944. /**
  945. * Sets the response content type. It can be either a file extension
  946. * which will be mapped internally to a mime-type or a string representing a mime-type
  947. * if $contentType is null the current content type is returned
  948. * if $contentType is an associative array, content type definitions will be stored/replaced
  949. *
  950. * ### Setting the content type
  951. *
  952. * ```
  953. * type('jpg');
  954. * ```
  955. *
  956. * If you attempt to set the type on a 304 or 204 status code response, the
  957. * content type will not take effect as these status codes do not have content-types.
  958. *
  959. * ### Returning the current content type
  960. *
  961. * ```
  962. * type();
  963. * ```
  964. *
  965. * ### Storing content type definitions
  966. *
  967. * ```
  968. * type(['keynote' => 'application/keynote', 'bat' => 'application/bat']);
  969. * ```
  970. *
  971. * ### Replacing a content type definition
  972. *
  973. * ```
  974. * type(['jpg' => 'text/plain']);
  975. * ```
  976. *
  977. * @param string|null $contentType Content type key.
  978. * @return mixed Current content type or false if supplied an invalid content type
  979. */
  980. public function type($contentType = null)
  981. {
  982. if ($contentType === null) {
  983. return $this->_contentType;
  984. }
  985. if (is_array($contentType)) {
  986. foreach ($contentType as $type => $definition) {
  987. $this->_mimeTypes[$type] = $definition;
  988. }
  989. return $this->_contentType;
  990. }
  991. if (isset($this->_mimeTypes[$contentType])) {
  992. $contentType = $this->_mimeTypes[$contentType];
  993. $contentType = is_array($contentType) ? current($contentType) : $contentType;
  994. }
  995. if (strpos($contentType, '/') === false) {
  996. return false;
  997. }
  998. $this->_contentType = $contentType;
  999. $this->_setContentType();
  1000. return $contentType;
  1001. }
  1002. /**
  1003. * Get an updated response with the content type set.
  1004. *
  1005. * If you attempt to set the type on a 304 or 204 status code response, the
  1006. * content type will not take effect as these status codes do not have content-types.
  1007. *
  1008. * @param string $contentType Either a file extension which will be mapped to a mime-type or a concrete mime-type.
  1009. * @return static
  1010. */
  1011. public function withType($contentType)
  1012. {
  1013. $mappedType = $this->resolveType($contentType);
  1014. $new = clone $this;
  1015. $new->_contentType = $mappedType;
  1016. $new->_setContentType();
  1017. return $new;
  1018. }
  1019. /**
  1020. * Translate and validate content-types.
  1021. *
  1022. * @param string $contentType The content-type or type alias.
  1023. * @return string The resolved content-type
  1024. * @throws \InvalidArgumentException When an invalid content-type or alias is used.
  1025. */
  1026. protected function resolveType($contentType)
  1027. {
  1028. $mapped = $this->getMimeType($contentType);
  1029. if ($mapped) {
  1030. return is_array($mapped) ? current($mapped) : $mapped;
  1031. }
  1032. if (strpos($contentType, '/') === false) {
  1033. throw new InvalidArgumentException(sprintf('"%s" is an invalid content type.', $contentType));
  1034. }
  1035. return $contentType;
  1036. }
  1037. /**
  1038. * Returns the mime type definition for an alias
  1039. *
  1040. * e.g `getMimeType('pdf'); // returns 'application/pdf'`
  1041. *
  1042. * @param string $alias the content type alias to map
  1043. * @return mixed String mapped mime type or false if $alias is not mapped
  1044. */
  1045. public function getMimeType($alias)
  1046. {
  1047. if (isset($this->_mimeTypes[$alias])) {
  1048. return $this->_mimeTypes[$alias];
  1049. }
  1050. return false;
  1051. }
  1052. /**
  1053. * Maps a content-type back to an alias
  1054. *
  1055. * e.g `mapType('application/pdf'); // returns 'pdf'`
  1056. *
  1057. * @param string|array $ctype Either a string content type to map, or an array of types.
  1058. * @return string|array|null Aliases for the types provided.
  1059. */
  1060. public function mapType($ctype)
  1061. {
  1062. if (is_array($ctype)) {
  1063. return array_map([$this, 'mapType'], $ctype);
  1064. }
  1065. foreach ($this->_mimeTypes as $alias => $types) {
  1066. if (in_array($ctype, (array)$types)) {
  1067. return $alias;
  1068. }
  1069. }
  1070. return null;
  1071. }
  1072. /**
  1073. * Sets the response charset
  1074. * if $charset is null the current charset is returned
  1075. *
  1076. * @param string|null $charset Character set string.
  1077. * @return string Current charset
  1078. * @deprecated 3.5.0 Use getCharset()/withCharset() instead.
  1079. */
  1080. public function charset($charset = null)
  1081. {
  1082. if ($charset === null) {
  1083. return $this->_charset;
  1084. }
  1085. $this->_charset = $charset;
  1086. $this->_setContentType();
  1087. return $this->_charset;
  1088. }
  1089. /**
  1090. * Retruns the current charset.
  1091. *
  1092. * @return string
  1093. */
  1094. public function getCharset()
  1095. {
  1096. return $this->_charset;
  1097. }
  1098. /**
  1099. * Get a new instance with an updated charset.
  1100. *
  1101. * @param string $charset Character set string.
  1102. * @return static
  1103. */
  1104. public function withCharset($charset)
  1105. {
  1106. $new = clone $this;
  1107. $new->_charset = $charset;
  1108. $new->_setContentType();
  1109. return $new;
  1110. }
  1111. /**
  1112. * Sets the correct headers to instruct the client to not cache the response
  1113. *
  1114. * @return void
  1115. * @deprecated 3.4.0 Use withDisabledCache() instead.
  1116. */
  1117. public function disableCache()
  1118. {
  1119. $this->_setHeader('Expires', 'Mon, 26 Jul 1997 05:00:00 GMT');
  1120. $this->_setHeader('Last-Modified', gmdate('D, d M Y H:i:s') . ' GMT');
  1121. $this->_setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
  1122. }
  1123. /**
  1124. * Create a new instance with headers to instruct the client to not cache the response
  1125. *
  1126. * @return static
  1127. */
  1128. public function withDisabledCache()
  1129. {
  1130. return $this->withHeader('Expires', 'Mon, 26 Jul 1997 05:00:00 GMT')
  1131. ->withHeader('Last-Modified', gmdate('D, d M Y H:i:s') . ' GMT')
  1132. ->withHeader('Cache-Control', 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
  1133. }
  1134. /**
  1135. * Sets the correct headers to instruct the client to cache the response.
  1136. *
  1137. * @param string $since a valid time since the response text has not been modified
  1138. * @param string $time a valid time for cache expiry
  1139. * @return void
  1140. * @deprecated 3.4.0 Use withCache() instead.
  1141. */
  1142. public function cache($since, $time = '+1 day')
  1143. {
  1144. if (!is_int($time)) {
  1145. $time = strtotime($time);
  1146. }
  1147. $this->_setHeader('Date', gmdate('D, j M Y G:i:s ', time()) . 'GMT');
  1148. $this->modified($since);
  1149. $this->expires($time);
  1150. $this->sharable(true);
  1151. $this->maxAge($time - time());
  1152. }
  1153. /**
  1154. * Create a new instance with the headers to enable client caching.
  1155. *
  1156. * @param string $since a valid time since the response text has not been modified
  1157. * @param string $time a valid time for cache expiry
  1158. * @return static
  1159. */
  1160. public function withCache($since, $time = '+1 day')
  1161. {
  1162. if (!is_int($time)) {
  1163. $time = strtotime($time);
  1164. }
  1165. return $this->withHeader('Date', gmdate('D, j M Y G:i:s ', time()) . 'GMT')
  1166. ->withModified($since)
  1167. ->withExpires($time)
  1168. ->withSharable(true)
  1169. ->withMaxAge($time - time());
  1170. }
  1171. /**
  1172. * Sets whether a response is eligible to be cached by intermediate proxies
  1173. * This method controls the `public` or `private` directive in the Cache-Control
  1174. * header
  1175. *
  1176. * @param bool|null $public If set to true, the Cache-Control header will be set as public
  1177. * if set to false, the response will be set to private
  1178. * if no value is provided, it will return whether the response is sharable or not
  1179. * @param int|null $time time in seconds after which the response should no longer be considered fresh
  1180. * @return bool|null
  1181. */
  1182. public function sharable($public = null, $time = null)
  1183. {
  1184. if ($public === null) {
  1185. $public = array_key_exists('public', $this->_cacheDirectives);
  1186. $private = array_key_exists('private', $this->_cacheDirectives);
  1187. $noCache = array_key_exists('no-cache', $this->_cacheDirectives);
  1188. if (!$public && !$private && !$noCache) {
  1189. return null;
  1190. }
  1191. return $public || !($private || $noCache);
  1192. }
  1193. if ($public) {
  1194. $this->_cacheDirectives['public'] = true;
  1195. unset($this->_cacheDirectives['private']);
  1196. } else {
  1197. $this->_cacheDirectives['private'] = true;
  1198. unset($this->_cacheDirectives['public']);
  1199. }
  1200. $this->maxAge($time);
  1201. if (!$time) {
  1202. $this->_setCacheControl();
  1203. }
  1204. return (bool)$public;
  1205. }
  1206. /**
  1207. * Create a new instace with the public/private Cache-Control directive set.
  1208. *
  1209. * @param bool $public If set to true, the Cache-Control header will be set as public
  1210. * if set to false, the response will be set to private.
  1211. * @param int|null $time time in seconds after which the response should no longer be considered fresh.
  1212. * @return static
  1213. */
  1214. public function withSharable($public, $time = null)
  1215. {
  1216. $new = clone $this;
  1217. unset($new->_cacheDirectives['private'], $new->_cacheDirectives['public']);
  1218. $key = $public ? 'public' : 'private';
  1219. $new->_cacheDirectives[$key] = true;
  1220. if ($time !== null) {
  1221. $new->_cacheDirectives['max-age'] = $time;
  1222. }
  1223. $new->_setCacheControl();
  1224. return $new;
  1225. }
  1226. /**
  1227. * Sets the Cache-Control s-maxage directive.
  1228. *
  1229. * The max-age is the number of seconds after which the response should no longer be considered
  1230. * a good candidate to be fetched from a shared cache (like in a proxy server).
  1231. * If called with no parameters, this function will return the current max-age value if any
  1232. *
  1233. * @param int|null $seconds if null, the method will return the current s-maxage value
  1234. * @return int|null
  1235. */
  1236. public function sharedMaxAge($seconds = null)
  1237. {
  1238. if ($seconds !== null) {
  1239. $this->_cacheDirectives['s-maxage'] = $seconds;
  1240. $this->_setCacheControl();
  1241. }
  1242. if (isset($this->_cacheDirectives['s-maxage'])) {
  1243. return $this->_cacheDirectives['s-maxage'];
  1244. }
  1245. return null;
  1246. }
  1247. /**
  1248. * Create a new instance with the Cache-Control s-maxage directive.
  1249. *
  1250. * The max-age is the number of seconds after which the response should no longer be considered
  1251. * a good candidate to be fetched from a shared cache (like in a proxy server).
  1252. *
  1253. * @param int $seconds The number of seconds for shared max-age
  1254. * @return static
  1255. */
  1256. public function withSharedMaxAge($seconds)
  1257. {
  1258. $new = clone $this;
  1259. $new->_cacheDirectives['s-maxage'] = $seconds;
  1260. $new->_setCacheControl();
  1261. return $new;
  1262. }
  1263. /**
  1264. * Sets the Cache-Control max-age directive.
  1265. * The max-age is the number of seconds after which the response should no longer be considered
  1266. * a good candidate to be fetched from the local (client) cache.
  1267. * If called with no parameters, this function will return the current max-age value if any
  1268. *
  1269. * @param int|null $seconds if null, the method will return the current max-age value
  1270. * @return int|null
  1271. */
  1272. public function maxAge($seconds = null)
  1273. {
  1274. if ($seconds !== null) {
  1275. $this->_cacheDirectives['max-age'] = $seconds;
  1276. $this->_setCacheControl();
  1277. }
  1278. if (isset($this->_cacheDirectives['max-age'])) {
  1279. return $this->_cacheDirectives['max-age'];
  1280. }
  1281. return null;
  1282. }
  1283. /**
  1284. * Create an instance with Cache-Control max-age directive set.
  1285. *
  1286. * The max-age is the number of seconds after which the response should no longer be considered
  1287. * a good candidate to be fetched from the local (client) cache.
  1288. *
  1289. * @param int $seconds The seconds a cached response can be considered valid
  1290. * @return static
  1291. */
  1292. public function withMaxAge($seconds)
  1293. {
  1294. $new = clone $this;
  1295. $new->_cacheDirectives['max-age'] = $seconds;
  1296. $new->_setCacheControl();
  1297. return $new;
  1298. }
  1299. /**
  1300. * Sets the Cache-Control must-revalidate directive.
  1301. * must-revalidate indicates that the response should not be served
  1302. * stale by a cache under any circumstance without first revalidating
  1303. * with the origin.
  1304. * If called with no parameters, this function will return whether must-revalidate is present.
  1305. *
  1306. * @param bool|null $enable if null, the method will return the current
  1307. * must-revalidate value. If boolean sets or unsets the directive.
  1308. * @return bool
  1309. * @deprecated 3.4.0 Use withMustRevalidate() instead.
  1310. */
  1311. public function mustRevalidate($enable = null)
  1312. {
  1313. if ($enable !== null) {
  1314. if ($enable) {
  1315. $this->_cacheDirectives['must-revalidate'] = true;
  1316. } else {
  1317. unset($this->_cacheDirectives['must-revalidate']);
  1318. }
  1319. $this->_setCacheControl();
  1320. }
  1321. return array_key_exists('must-revalidate', $this->_cacheDirectives);
  1322. }
  1323. /**
  1324. * Create an instance with Cache-Control must-revalidate directive set.
  1325. *
  1326. * Sets the Cache-Control must-revalidate directive.
  1327. * must-revalidate indicates that the response should not be served
  1328. * stale by a cache under any circumstance without first revalidating
  1329. * with the origin.
  1330. *
  1331. * @param bool $enable If boolean sets or unsets the directive.
  1332. * @return static
  1333. */
  1334. public function withMustRevalidate($enable)
  1335. {
  1336. $new = clone $this;
  1337. if ($enable) {
  1338. $new->_cacheDirectives['must-revalidate'] = true;
  1339. } else {
  1340. unset($new->_cacheDirectives['must-revalidate']);
  1341. }
  1342. $new->_setCacheControl();
  1343. return $new;
  1344. }
  1345. /**
  1346. * Helper method to generate a valid Cache-Control header from the options set
  1347. * in other methods
  1348. *
  1349. * @return void
  1350. */
  1351. protected function _setCacheControl()
  1352. {
  1353. $control = '';
  1354. foreach ($this->_cacheDirectives as $key => $val) {
  1355. $control .= $val === true ? $key : sprintf('%s=%s', $key, $val);
  1356. $control .= ', ';
  1357. }
  1358. $control = rtrim($control, ', ');
  1359. $this->_setHeader('Cache-Control', $control);
  1360. }
  1361. /**
  1362. * Sets the Expires header for the response by taking an expiration time
  1363. * If called with no parameters it will return the current Expires value
  1364. *
  1365. * ### Examples:
  1366. *
  1367. * `$response->expires('now')` Will Expire the response cache now
  1368. * `$response->expires(new DateTime('+1 day'))` Will set the expiration in next 24 hours
  1369. * `$response->expires()` Will return the current expiration header value
  1370. *
  1371. * @param string|\DateTime|null $time Valid time string or \DateTime instance.
  1372. * @return string|null
  1373. * @deprecated 3.4.0 Use withExpires() instead.
  1374. */
  1375. public function expires($time = null)
  1376. {
  1377. if ($time !== null) {
  1378. $date = $this->_getUTCDate($time);
  1379. $this->_setHeader('Expires', $date->format('D, j M Y H:i:s') . ' GMT');
  1380. }
  1381. if ($this->hasHeader('Expires')) {
  1382. return $this->getHeaderLine('Expires');
  1383. }
  1384. return null;
  1385. }
  1386. /**
  1387. * Create a new instance with the Expires header set.
  1388. *
  1389. * ### Examples:
  1390. *
  1391. * ```
  1392. * // Will Expire the response cache now
  1393. * $response->withExpires('now')
  1394. *
  1395. * // Will set the expiration in next 24 hours
  1396. * $response->withExpires(new DateTime('+1 day'))
  1397. * ```
  1398. *
  1399. * @param string|\DateTime $time Valid time string or \DateTime instance.
  1400. * @return static
  1401. */
  1402. public function withExpires($time)
  1403. {
  1404. $date = $this->_getUTCDate($time);
  1405. return $this->withHeader('Expires', $date->format('D, j M Y H:i:s') . ' GMT');
  1406. }
  1407. /**
  1408. * Sets the Last-Modified header for the response by taking a modification time
  1409. * If called with no parameters it will return the current Last-Modified value
  1410. *
  1411. * ### Examples:
  1412. *
  1413. * `$response->modified('now')` Will set the Last-Modified to the current time
  1414. * `$response->modified(new DateTime('+1 day'))` Will set the modification date in the past 24 hours
  1415. * `$response->modified()` Will return the current Last-Modified header value
  1416. *
  1417. * @param string|\DateTime|null $time Valid time string or \DateTime instance.
  1418. * @return string|null
  1419. * @deprecated 3.4.0 Use withModified() instead.
  1420. */
  1421. public function modified($time = null)
  1422. {
  1423. if ($time !== null) {
  1424. $date = $this->_getUTCDate($time);
  1425. $this->_setHeader('Last-Modified', $date->format('D, j M Y H:i:s') . ' GMT');
  1426. }
  1427. if ($this->hasHeader('Last-Modified')) {
  1428. return $this->getHeaderLine('Last-Modified');
  1429. }
  1430. return null;
  1431. }
  1432. /**
  1433. * Create a new instance with the Last-Modified header set.
  1434. *
  1435. * ### Examples:
  1436. *
  1437. * ```
  1438. * // Will Expire the response cache now
  1439. * $response->withModified('now')
  1440. *
  1441. * // Will set the expiration in next 24 hours
  1442. * $response->withModified(new DateTime('+1 day'))
  1443. * ```
  1444. *
  1445. * @param string|\DateTime $time Valid time string or \DateTime instance.
  1446. * @return static
  1447. */
  1448. public function withModified($time)
  1449. {
  1450. $date = $this->_getUTCDate($time);
  1451. return $this->withHeader('Last-Modified', $date->format('D, j M Y H:i:s') . ' GMT');
  1452. }
  1453. /**
  1454. * Sets the response as Not Modified by removing any body contents
  1455. * setting the status code to "304 Not Modified" and removing all
  1456. * conflicting headers
  1457. *
  1458. * @return void
  1459. */
  1460. public function notModified()
  1461. {
  1462. $this->statusCode(304);
  1463. $this->body('');
  1464. $remove = [
  1465. 'Allow',
  1466. 'Content-Encoding',
  1467. 'Content-Language',
  1468. 'Content-Length',
  1469. 'Content-MD5',
  1470. 'Content-Type',
  1471. 'Last-Modified'
  1472. ];
  1473. foreach ($remove as $header) {
  1474. unset($this->headers[$header]);
  1475. }
  1476. }
  1477. /**
  1478. * Create a new instance as 'not modified'
  1479. *
  1480. * This will remove any body contents set the status code
  1481. * to "304" and removing headers that describe
  1482. * a response body.
  1483. *
  1484. * @return static
  1485. */
  1486. public function withNotModified()
  1487. {
  1488. $new = $this->withStatus(304);
  1489. $new->_createStream();
  1490. $remove = [
  1491. 'Allow',
  1492. 'Content-Encoding',
  1493. 'Content-Language',
  1494. 'Content-Length',
  1495. 'Content-MD5',
  1496. 'Content-Type',
  1497. 'Last-Modified'
  1498. ];
  1499. foreach ($remove as $header) {
  1500. $new = $new->withoutHeader($header);
  1501. }
  1502. return $new;
  1503. }
  1504. /**
  1505. * Sets the Vary header for the response, if an array is passed,
  1506. * values will be imploded into a comma separated string. If no
  1507. * parameters are passed, then an array with the current Vary header
  1508. * value is returned
  1509. *
  1510. * @param string|array|null $cacheVariances A single Vary string or an array
  1511. * containing the list for variances.
  1512. * @return array|null
  1513. * @deprecated 3.4.0 Use withVary() instead.
  1514. */
  1515. public function vary($cacheVariances = null)
  1516. {
  1517. if ($cacheVariances !== null) {
  1518. $cacheVariances = (array)$cacheVariances;
  1519. $this->_setHeader('Vary', implode(', ', $cacheVariances));
  1520. }
  1521. if ($this->hasHeader('Vary')) {
  1522. return explode(', ', $this->getHeaderLine('Vary'));
  1523. }
  1524. return null;
  1525. }
  1526. /**
  1527. * Create a new instance with the Vary header set.
  1528. *
  1529. * If an array is passed values will be imploded into a comma
  1530. * separated string. If no parameters are passed, then an
  1531. * array with the current Vary header value is returned
  1532. *
  1533. * @param string|array $cacheVariances A single Vary string or an array
  1534. * containing the list for variances.
  1535. * @return static
  1536. */
  1537. public function withVary($cacheVariances)
  1538. {
  1539. return $this->withHeader('Vary', (array)$cacheVariances);
  1540. }
  1541. /**
  1542. * Sets the response Etag, Etags are a strong indicative that a response
  1543. * can be cached by a HTTP client. A bad way of generating Etags is
  1544. * creating a hash of the response output, instead generate a unique
  1545. * hash of the unique components that identifies a request, such as a
  1546. * modification time, a resource Id, and anything else you consider it
  1547. * makes it unique.
  1548. *
  1549. * Second parameter is used to instruct clients that the content has
  1550. * changed, but semantically, it can be used as the same thing. Think
  1551. * for instance of a page with a hit counter, two different page views
  1552. * are equivalent, but they differ by a few bytes. This leaves off to
  1553. * the Client the decision of using or not the cached page.
  1554. *
  1555. * If no parameters are passed, current Etag header is returned.
  1556. *
  1557. * @param string|null $hash The unique hash that identifies this response
  1558. * @param bool $weak Whether the response is semantically the same as
  1559. * other with the same hash or not
  1560. * @return string|null
  1561. * @deprecated 3.4.0 Use withEtag() instead.
  1562. */
  1563. public function etag($hash = null, $weak = false)
  1564. {
  1565. if ($hash !== null) {
  1566. $this->_setHeader('Etag', sprintf('%s"%s"', $weak ? 'W/' : null, $hash));
  1567. }
  1568. if ($this->hasHeader('Etag')) {
  1569. return $this->getHeaderLine('Etag');
  1570. }
  1571. return null;
  1572. }
  1573. /**
  1574. * Create a new instance with the Etag header set.
  1575. *
  1576. * Etags are a strong indicative that a response can be cached by a
  1577. * HTTP client. A bad way of generating Etags is creating a hash of
  1578. * the response output, instead generate a unique hash of the
  1579. * unique components that identifies a request, such as a
  1580. * modification time, a resource Id, and anything else you consider it
  1581. * that makes the response unique.
  1582. *
  1583. * The second parameter is used to inform clients that the content has
  1584. * changed, but semantically it is equivalent to existing cached values. Consider
  1585. * a page with a hit counter, two different page views are equivalent, but
  1586. * they differ by a few bytes. This permits the Client to decide whether they should
  1587. * use the cached data.
  1588. *
  1589. * @param string $hash The unique hash that identifies this response
  1590. * @param bool $weak Whether the response is semantically the same as
  1591. * other with the same hash or not. Defaults to false
  1592. * @return static
  1593. */
  1594. public function withEtag($hash, $weak = false)
  1595. {
  1596. $hash = sprintf('%s"%s"', $weak ? 'W/' : null, $hash);
  1597. return $this->withHeader('Etag', $hash);
  1598. }
  1599. /**
  1600. * Returns a DateTime object initialized at the $time param and using UTC
  1601. * as timezone
  1602. *
  1603. * @param string|int|\DateTime|null $time Valid time string or \DateTime instance.
  1604. * @return \DateTime
  1605. */
  1606. protected function _getUTCDate($time = null)
  1607. {
  1608. if ($time instanceof DateTime) {
  1609. $result = clone $time;
  1610. } elseif (is_int($time)) {
  1611. $result = new DateTime(date('Y-m-d H:i:s', $time));
  1612. } else {
  1613. $result = new DateTime($time);
  1614. }
  1615. $result->setTimezone(new DateTimeZone('UTC'));
  1616. return $result;
  1617. }
  1618. /**
  1619. * Sets the correct output buffering handler to send a compressed response. Responses will
  1620. * be compressed with zlib, if the extension is available.
  1621. *
  1622. * @return bool false if client does not accept compressed responses or no handler is available, true otherwise
  1623. */
  1624. public function compress()
  1625. {
  1626. $compressionEnabled = ini_get('zlib.output_compression') !== '1' &&
  1627. extension_loaded('zlib') &&
  1628. (strpos(env('HTTP_ACCEPT_ENCODING'), 'gzip') !== false);
  1629. return $compressionEnabled && ob_start('ob_gzhandler');
  1630. }
  1631. /**
  1632. * Returns whether the resulting output will be compressed by PHP
  1633. *
  1634. * @return bool
  1635. */
  1636. public function outputCompressed()
  1637. {
  1638. return strpos(env('HTTP_ACCEPT_ENCODING'), 'gzip') !== false
  1639. && (ini_get('zlib.output_compression') === '1' || in_array('ob_gzhandler', ob_list_handlers()));
  1640. }
  1641. /**
  1642. * Sets the correct headers to instruct the browser to download the response as a file.
  1643. *
  1644. * @param string $filename The name of the file as the browser will download the response
  1645. * @return void
  1646. * @deprecated 3.4.0 Use withDownload() instead.
  1647. */
  1648. public function download($filename)
  1649. {
  1650. $this->header('Content-Disposition', 'attachment; filename="' . $filename . '"');
  1651. }
  1652. /**
  1653. * Create a new instance with the Content-Disposition header set.
  1654. *
  1655. * @param string $filename The name of the file as the browser will download the response
  1656. * @return static
  1657. */
  1658. public function withDownload($filename)
  1659. {
  1660. return $this->withHeader('Content-Disposition', 'attachment; filename="' . $filename . '"');
  1661. }
  1662. /**
  1663. * Sets the protocol to be used when sending the response. Defaults to HTTP/1.1
  1664. * If called with no arguments, it will return the current configured protocol
  1665. *
  1666. * @param string|null $protocol Protocol to be used for sending response.
  1667. * @return string Protocol currently set
  1668. * @deprecated 3.4.0 Use getProtocolVersion() instead.
  1669. */
  1670. public function protocol($protocol = null)
  1671. {
  1672. if ($protocol !== null) {
  1673. $this->_protocol = $protocol;
  1674. }
  1675. return $this->_protocol;
  1676. }
  1677. /**
  1678. * Sets the Content-Length header for the response
  1679. * If called with no arguments returns the last Content-Length set
  1680. *
  1681. * @param int|null $bytes Number of bytes
  1682. * @return int|null
  1683. * @deprecated 3.4.0 Use withLength() to set length instead.
  1684. */
  1685. public function length($bytes = null)
  1686. {
  1687. if ($bytes !== null) {
  1688. $this->_setHeader('Content-Length', $bytes);
  1689. }
  1690. if ($this->hasHeader('Content-Length')) {
  1691. return $this->getHeaderLine('Content-Length');
  1692. }
  1693. return null;
  1694. }
  1695. /**
  1696. * Create a new response with the Content-Length header set.
  1697. *
  1698. * @param int|string $bytes Number of bytes
  1699. * @return static
  1700. */
  1701. public function withLength($bytes)
  1702. {
  1703. return $this->withHeader('Content-Length', (string)$bytes);
  1704. }
  1705. /**
  1706. * Checks whether a response has not been modified according to the 'If-None-Match'
  1707. * (Etags) and 'If-Modified-Since' (last modification date) request
  1708. * headers. If the response is detected to be not modified, it
  1709. * is marked as so accordingly so the client can be informed of that.
  1710. *
  1711. * In order to mark a response as not modified, you need to set at least
  1712. * the Last-Modified etag response header before calling this method. Otherwise
  1713. * a comparison will not be possible.
  1714. *
  1715. * @param \Cake\Http\ServerRequest $request Request object
  1716. * @return bool Whether the response was marked as not modified or not.
  1717. */
  1718. public function checkNotModified(ServerRequest $request)
  1719. {
  1720. $etags = preg_split('/\s*,\s*/', (string)$request->header('If-None-Match'), 0, PREG_SPLIT_NO_EMPTY);
  1721. $modifiedSince = $request->header('If-Modified-Since');
  1722. if ($responseTag = $this->etag()) {
  1723. $etagMatches = in_array('*', $etags) || in_array($responseTag, $etags);
  1724. }
  1725. if ($modifiedSince) {
  1726. $timeMatches = strtotime($this->modified()) === strtotime($modifiedSince);
  1727. }
  1728. $checks = compact('etagMatches', 'timeMatches');
  1729. if (empty($checks)) {
  1730. return false;
  1731. }
  1732. $notModified = !in_array(false, $checks, true);
  1733. if ($notModified) {
  1734. $this->notModified();
  1735. }
  1736. return $notModified;
  1737. }
  1738. /**
  1739. * String conversion. Fetches the response body as a string.
  1740. * Does *not* send headers.
  1741. * If body is a callable, a blank string is returned.
  1742. *
  1743. * @return string
  1744. */
  1745. public function __toString()
  1746. {
  1747. $this->stream->rewind();
  1748. return (string)$this->stream->getContents();
  1749. }
  1750. /**
  1751. * Getter/Setter for cookie configs
  1752. *
  1753. * This method acts as a setter/getter depending on the type of the argument.
  1754. * If the method is called with no arguments, it returns all configurations.
  1755. *
  1756. * If the method is called with a string as argument, it returns either the
  1757. * given configuration if it is set, or null, if it's not set.
  1758. *
  1759. * If the method is called with an array as argument, it will set the cookie
  1760. * configuration to the cookie container.
  1761. *
  1762. * ### Options (when setting a configuration)
  1763. * - name: The Cookie name
  1764. * - value: Value of the cookie
  1765. * - expire: Time the cookie expires in
  1766. * - path: Path the cookie applies to
  1767. * - domain: Domain the cookie is for.
  1768. * - secure: Is the cookie https?
  1769. * - httpOnly: Is the cookie available in the client?
  1770. *
  1771. * ### Examples
  1772. *
  1773. * ### Getting all cookies
  1774. *
  1775. * `$this->cookie()`
  1776. *
  1777. * ### Getting a certain cookie configuration
  1778. *
  1779. * `$this->cookie('MyCookie')`
  1780. *
  1781. * ### Setting a cookie configuration
  1782. *
  1783. * `$this->cookie((array) $options)`
  1784. *
  1785. * @param array|null $options Either null to get all cookies, string for a specific cookie
  1786. * or array to set cookie.
  1787. * @return mixed
  1788. * @deprecated 3.4.0 Use getCookie(), getCookies() and withCookie() instead.
  1789. */
  1790. public function cookie($options = null)
  1791. {
  1792. if ($options === null) {
  1793. return $this->getCookies();
  1794. }
  1795. if (is_string($options)) {
  1796. if (!$this->_cookies->has($options)) {
  1797. return null;
  1798. }
  1799. $cookie = $this->_cookies->get($options);
  1800. return $this->convertCookieToArray($cookie);
  1801. }
  1802. $options += [
  1803. 'name' => 'CakeCookie[default]',
  1804. 'value' => '',
  1805. 'expire' => 0,
  1806. 'path' => '/',
  1807. 'domain' => '',
  1808. 'secure' => false,
  1809. 'httpOnly' => false
  1810. ];
  1811. $expires = $options['expire'] ? new DateTime('@' . $options['expire']) : null;
  1812. $cookie = new Cookie(
  1813. $options['name'],
  1814. $options['value'],
  1815. $expires,
  1816. $options['path'],
  1817. $options['domain'],
  1818. $options['secure'],
  1819. $options['httpOnly']
  1820. );
  1821. $this->_cookies = $this->_cookies->add($cookie);
  1822. }
  1823. /**
  1824. * Create a new response with a cookie set.
  1825. *
  1826. * ### Options
  1827. *
  1828. * - `name`: The Cookie name
  1829. * - `value`: Value of the cookie
  1830. * - `expire`: Time the cookie expires in
  1831. * - `path`: Path the cookie applies to
  1832. * - `domain`: Domain the cookie is for.
  1833. * - `secure`: Is the cookie https?
  1834. * - `httpOnly`: Is the cookie available in the client?
  1835. *
  1836. * ### Examples
  1837. *
  1838. * ```
  1839. * // set scalar value with defaults
  1840. * $response = $response->withCookie('remember_me', 1);
  1841. *
  1842. * // customize cookie attributes
  1843. * $response = $response->withCookie('remember_me', ['path' => '/login']);
  1844. *
  1845. * // add a cookie object
  1846. * $response = $response->withCookie(new Cookie('remember_me', 1));
  1847. * ```
  1848. *
  1849. * @param string|\Cake\Http\Cookie\Cookie $name The name of the cookie to set, or a cookie object
  1850. * @param array|string $data Either a string value, or an array of cookie options.
  1851. * @return static
  1852. */
  1853. public function withCookie($name, $data = '')
  1854. {
  1855. if ($name instanceof Cookie) {
  1856. $cookie = $name;
  1857. } else {
  1858. if (!is_array($data)) {
  1859. $data = ['value' => $data];
  1860. }
  1861. $data += [
  1862. 'value' => '',
  1863. 'expire' => 0,
  1864. 'path' => '/',
  1865. 'domain' => '',
  1866. 'secure' => false,
  1867. 'httpOnly' => false
  1868. ];
  1869. $expires = $data['expire'] ? new DateTime('@' . $data['expire']) : null;
  1870. $cookie = new Cookie(
  1871. $name,
  1872. $data['value'],
  1873. $expires,
  1874. $data['path'],
  1875. $data['domain'],
  1876. $data['secure'],
  1877. $data['httpOnly']
  1878. );
  1879. }
  1880. $new = clone $this;
  1881. $new->_cookies = $new->_cookies->add($cookie);
  1882. return $new;
  1883. }
  1884. /**
  1885. * Create a new response with an expired cookie set.
  1886. *
  1887. * ### Options
  1888. *
  1889. * - `path`: Path the cookie applies to
  1890. * - `domain`: Domain the cookie is for.
  1891. * - `secure`: Is the cookie https?
  1892. * - `httpOnly`: Is the cookie available in the client?
  1893. *
  1894. * ### Examples
  1895. *
  1896. * ```
  1897. * // set scalar value with defaults
  1898. * $response = $response->withExpiredCookie('remember_me');
  1899. *
  1900. * // customize cookie attributes
  1901. * $response = $response->withExpiredCookie('remember_me', ['path' => '/login']);
  1902. *
  1903. * // add a cookie object
  1904. * $response = $response->withExpiredCookie(new Cookie('remember_me'));
  1905. * ```
  1906. *
  1907. * @param string|\Cake\Http\Cookie\CookieInterface $name The name of the cookie to expire, or a cookie object
  1908. * @param array $options An array of cookie options.
  1909. * @return static
  1910. */
  1911. public function withExpiredCookie($name, $options = [])
  1912. {
  1913. if ($name instanceof CookieInterface) {
  1914. $cookie = $name->withExpired();
  1915. } else {
  1916. $options += [
  1917. 'path' => '/',
  1918. 'domain' => '',
  1919. 'secure' => false,
  1920. 'httpOnly' => false
  1921. ];
  1922. $cookie = new Cookie(
  1923. $name,
  1924. '',
  1925. DateTime::createFromFormat('U', 1),
  1926. $options['path'],
  1927. $options['domain'],
  1928. $options['secure'],
  1929. $options['httpOnly']
  1930. );
  1931. }
  1932. $new = clone $this;
  1933. $new->_cookies = $new->_cookies->add($cookie);
  1934. return $new;
  1935. }
  1936. /**
  1937. * Read a single cookie from the response.
  1938. *
  1939. * This method provides read access to pending cookies. It will
  1940. * not read the `Set-Cookie` header if set.
  1941. *
  1942. * @param string $name The cookie name you want to read.
  1943. * @return array|null Either the cookie data or null
  1944. */
  1945. public function getCookie($name)
  1946. {
  1947. if (!$this->_cookies->has($name)) {
  1948. return null;
  1949. }
  1950. $cookie = $this->_cookies->get($name);
  1951. return $this->convertCookieToArray($cookie);
  1952. }
  1953. /**
  1954. * Get all cookies in the response.
  1955. *
  1956. * Returns an associative array of cookie name => cookie data.
  1957. *
  1958. * @return array
  1959. */
  1960. public function getCookies()
  1961. {
  1962. $out = [];
  1963. foreach ($this->_cookies as $cookie) {
  1964. $out[$cookie->getName()] = $this->convertCookieToArray($cookie);
  1965. }
  1966. return $out;
  1967. }
  1968. /**
  1969. * Convert the cookie into an array of its properties.
  1970. *
  1971. * This method is compatible with the historical behavior of Cake\Http\Response,
  1972. * where `httponly` is `httpOnly` and `expires` is `expire`
  1973. *
  1974. * @param \Cake\Http\Cookie\CookieInterface $cookie Cookie object.
  1975. * @return array
  1976. */
  1977. protected function convertCookieToArray(CookieInterface $cookie)
  1978. {
  1979. return [
  1980. 'name' => $cookie->getName(),
  1981. 'value' => $cookie->getStringValue(),
  1982. 'path' => $cookie->getPath(),
  1983. 'domain' => $cookie->getDomain(),
  1984. 'secure' => $cookie->isSecure(),
  1985. 'httpOnly' => $cookie->isHttpOnly(),
  1986. 'expire' => $cookie->getExpiresTimestamp()
  1987. ];
  1988. }
  1989. /**
  1990. * Get the CookieCollection from the response
  1991. *
  1992. * @return \Cake\Http\Cookie\CookieCollection
  1993. */
  1994. public function getCookieCollection()
  1995. {
  1996. return $this->_cookies;
  1997. }
  1998. /**
  1999. * Setup access for origin and methods on cross origin requests
  2000. *
  2001. * This method allow multiple ways to setup the domains, see the examples
  2002. *
  2003. * ### Full URI
  2004. * ```
  2005. * cors($request, 'https://www.cakephp.org');
  2006. * ```
  2007. *
  2008. * ### URI with wildcard
  2009. * ```
  2010. * cors($request, 'https://*.cakephp.org');
  2011. * ```
  2012. *
  2013. * ### Ignoring the requested protocol
  2014. * ```
  2015. * cors($request, 'www.cakephp.org');
  2016. * ```
  2017. *
  2018. * ### Any URI
  2019. * ```
  2020. * cors($request, '*');
  2021. * ```
  2022. *
  2023. * ### Whitelist of URIs
  2024. * ```
  2025. * cors($request, ['http://www.cakephp.org', '*.google.com', 'https://myproject.github.io']);
  2026. * ```
  2027. *
  2028. * *Note* The `$allowedDomains`, `$allowedMethods`, `$allowedHeaders` parameters are deprecated.
  2029. * Instead the builder object should be used.
  2030. *
  2031. * @param \Cake\Http\ServerRequest $request Request object
  2032. * @param string|array $allowedDomains List of allowed domains, see method description for more details
  2033. * @param string|array $allowedMethods List of HTTP verbs allowed
  2034. * @param string|array $allowedHeaders List of HTTP headers allowed
  2035. * @return \Cake\Network\CorsBuilder A builder object the provides a fluent interface for defining
  2036. * additional CORS headers.
  2037. */
  2038. public function cors(ServerRequest $request, $allowedDomains = [], $allowedMethods = [], $allowedHeaders = [])
  2039. {
  2040. $origin = $request->header('Origin');
  2041. $ssl = $request->is('ssl');
  2042. $builder = new CorsBuilder($this, $origin, $ssl);
  2043. if (!$origin) {
  2044. return $builder;
  2045. }
  2046. if (empty($allowedDomains) && empty($allowedMethods) && empty($allowedHeaders)) {
  2047. return $builder;
  2048. }
  2049. $builder->allowOrigin($allowedDomains)
  2050. ->allowMethods((array)$allowedMethods)
  2051. ->allowHeaders((array)$allowedHeaders)
  2052. ->build();
  2053. return $builder;
  2054. }
  2055. /**
  2056. * Setup for display or download the given file.
  2057. *
  2058. * If $_SERVER['HTTP_RANGE'] is set a slice of the file will be
  2059. * returned instead of the entire file.
  2060. *
  2061. * ### Options keys
  2062. *
  2063. * - name: Alternate download name
  2064. * - download: If `true` sets download header and forces file to be downloaded rather than displayed in browser
  2065. *
  2066. * @param string $path Path to file. If the path is not an absolute path that resolves
  2067. * to a file, `APP` will be prepended to the path.
  2068. * @param array $options Options See above.
  2069. * @return void
  2070. * @throws \Cake\Network\Exception\NotFoundException
  2071. * @deprecated 3.4.0 Use withFile() instead.
  2072. */
  2073. public function file($path, array $options = [])
  2074. {
  2075. $file = $this->validateFile($path);
  2076. $options += [
  2077. 'name' => null,
  2078. 'download' => null
  2079. ];
  2080. $extension = strtolower($file->ext());
  2081. $download = $options['download'];
  2082. if ((!$extension || $this->type($extension) === false) && $download === null) {
  2083. $download = true;
  2084. }
  2085. $fileSize = $file->size();
  2086. if ($download) {
  2087. $agent = env('HTTP_USER_AGENT');
  2088. if (preg_match('%Opera(/| )([0-9].[0-9]{1,2})%', $agent)) {
  2089. $contentType = 'application/octet-stream';
  2090. } elseif (preg_match('/MSIE ([0-9].[0-9]{1,2})/', $agent)) {
  2091. $contentType = 'application/force-download';
  2092. }
  2093. if (!empty($contentType)) {
  2094. $this->type($contentType);
  2095. }
  2096. if ($options['name'] === null) {
  2097. $name = $file->name;
  2098. } else {
  2099. $name = $options['name'];
  2100. }
  2101. $this->download($name);
  2102. $this->header('Content-Transfer-Encoding', 'binary');
  2103. }
  2104. $this->header('Accept-Ranges', 'bytes');
  2105. $httpRange = env('HTTP_RANGE');
  2106. if (isset($httpRange)) {
  2107. $this->_fileRange($file, $httpRange);
  2108. } else {
  2109. $this->header('Content-Length', $fileSize);
  2110. }
  2111. $this->_file = $file;
  2112. $this->stream = new Stream($file->path, 'rb');
  2113. }
  2114. /**
  2115. * Create a new instance that is based on a file.
  2116. *
  2117. * This method will augment both the body and a number of related headers.
  2118. *
  2119. * If `$_SERVER['HTTP_RANGE']` is set, a slice of the file will be
  2120. * returned instead of the entire file.
  2121. *
  2122. * ### Options keys
  2123. *
  2124. * - name: Alternate download name
  2125. * - download: If `true` sets download header and forces file to
  2126. * be downloaded rather than displayed inline.
  2127. *
  2128. * @param string $path Path to file. If the path is not an absolute path that resolves
  2129. * to a file, `APP` will be prepended to the path.
  2130. * @param array $options Options See above.
  2131. * @return static
  2132. * @throws \Cake\Network\Exception\NotFoundException
  2133. */
  2134. public function withFile($path, array $options = [])
  2135. {
  2136. $file = $this->validateFile($path);
  2137. $options += [
  2138. 'name' => null,
  2139. 'download' => null
  2140. ];
  2141. $extension = strtolower($file->ext());
  2142. $mapped = $this->getMimeType($extension);
  2143. if ((!$extension || !$mapped) && $options['download'] === null) {
  2144. $options['download'] = true;
  2145. }
  2146. $new = clone $this;
  2147. if ($mapped) {
  2148. $new = $new->withType($extension);
  2149. }
  2150. $fileSize = $file->size();
  2151. if ($options['download']) {
  2152. $agent = env('HTTP_USER_AGENT');
  2153. if (preg_match('%Opera(/| )([0-9].[0-9]{1,2})%', $agent)) {
  2154. $contentType = 'application/octet-stream';
  2155. } elseif (preg_match('/MSIE ([0-9].[0-9]{1,2})/', $agent)) {
  2156. $contentType = 'application/force-download';
  2157. }
  2158. if (isset($contentType)) {
  2159. $new = $new->withType($contentType);
  2160. }
  2161. $name = $options['name'] ?: $file->name;
  2162. $new = $new->withDownload($name)
  2163. ->withHeader('Content-Transfer-Encoding', 'binary');
  2164. }
  2165. $new = $new->withHeader('Accept-Ranges', 'bytes');
  2166. $httpRange = env('HTTP_RANGE');
  2167. if (isset($httpRange)) {
  2168. $new->_fileRange($file, $httpRange);
  2169. } else {
  2170. $new = $new->withHeader('Content-Length', (string)$fileSize);
  2171. }
  2172. $new->_file = $file;
  2173. $new->stream = new Stream($file->path, 'rb');
  2174. return $new;
  2175. }
  2176. /**
  2177. * Convenience method to set a string into the response body
  2178. *
  2179. * @param string $string The string to be sent
  2180. * @return static
  2181. */
  2182. public function withStringBody($string)
  2183. {
  2184. $new = clone $this;
  2185. $new->_createStream();
  2186. $new->stream->write((string)$string);
  2187. return $new;
  2188. }
  2189. /**
  2190. * Validate a file path is a valid response body.
  2191. *
  2192. * @param string $path The path to the file.
  2193. * @throws \Cake\Network\Exception\NotFoundException
  2194. * @return \Cake\Filesystem\File
  2195. */
  2196. protected function validateFile($path)
  2197. {
  2198. if (strpos($path, '../') !== false || strpos($path, '..\\') !== false) {
  2199. throw new NotFoundException(__d('cake', 'The requested file contains `..` and will not be read.'));
  2200. }
  2201. if (!is_file($path)) {
  2202. $path = APP . $path;
  2203. }
  2204. $file = new File($path);
  2205. if (!$file->exists() || !$file->readable()) {
  2206. if (Configure::read('debug')) {
  2207. throw new NotFoundException(sprintf('The requested file %s was not found or not readable', $path));
  2208. }
  2209. throw new NotFoundException(__d('cake', 'The requested file was not found'));
  2210. }
  2211. return $file;
  2212. }
  2213. /**
  2214. * Get the current file if one exists.
  2215. *
  2216. * @return \Cake\Filesystem\File|null The file to use in the response or null
  2217. */
  2218. public function getFile()
  2219. {
  2220. return $this->_file;
  2221. }
  2222. /**
  2223. * Apply a file range to a file and set the end offset.
  2224. *
  2225. * If an invalid range is requested a 416 Status code will be used
  2226. * in the response.
  2227. *
  2228. * @param \Cake\Filesystem\File $file The file to set a range on.
  2229. * @param string $httpRange The range to use.
  2230. * @return void
  2231. * @deprecated 3.4.0 Long term this needs to be refactored to follow immutable paradigms.
  2232. * However for now, it is simpler to leave this alone.
  2233. */
  2234. protected function _fileRange($file, $httpRange)
  2235. {
  2236. $fileSize = $file->size();
  2237. $lastByte = $fileSize - 1;
  2238. $start = 0;
  2239. $end = $lastByte;
  2240. preg_match('/^bytes\s*=\s*(\d+)?\s*-\s*(\d+)?$/', $httpRange, $matches);
  2241. if ($matches) {
  2242. $start = $matches[1];
  2243. $end = isset($matches[2]) ? $matches[2] : '';
  2244. }
  2245. if ($start === '') {
  2246. $start = $fileSize - $end;
  2247. $end = $lastByte;
  2248. }
  2249. if ($end === '') {
  2250. $end = $lastByte;
  2251. }
  2252. if ($start > $end || $end > $lastByte || $start > $lastByte) {
  2253. $this->statusCode(416);
  2254. $this->header([
  2255. 'Content-Range' => 'bytes 0-' . $lastByte . '/' . $fileSize
  2256. ]);
  2257. return;
  2258. }
  2259. $this->header([
  2260. 'Content-Length' => $end - $start + 1,
  2261. 'Content-Range' => 'bytes ' . $start . '-' . $end . '/' . $fileSize
  2262. ]);
  2263. $this->statusCode(206);
  2264. $this->_fileRange = [$start, $end];
  2265. }
  2266. /**
  2267. * Reads out a file, and echos the content to the client.
  2268. *
  2269. * @param \Cake\Filesystem\File $file File object
  2270. * @param array $range The range to read out of the file.
  2271. * @return bool True is whole file is echoed successfully or false if client connection is lost in between
  2272. * @deprecated 3.4.0 Will be removed in 4.0.0
  2273. */
  2274. protected function _sendFile($file, $range)
  2275. {
  2276. ob_implicit_flush(true);
  2277. $file->open('rb');
  2278. $end = $start = false;
  2279. if ($range) {
  2280. list($start, $end) = $range;
  2281. }
  2282. if ($start !== false) {
  2283. $file->offset($start);
  2284. }
  2285. $bufferSize = 8192;
  2286. set_time_limit(0);
  2287. session_write_close();
  2288. while (!feof($file->handle)) {
  2289. if (!$this->_isActive()) {
  2290. $file->close();
  2291. return false;
  2292. }
  2293. $offset = $file->offset();
  2294. if ($end && $offset >= $end) {
  2295. break;
  2296. }
  2297. if ($end && $offset + $bufferSize >= $end) {
  2298. $bufferSize = $end - $offset + 1;
  2299. }
  2300. echo fread($file->handle, $bufferSize);
  2301. }
  2302. $file->close();
  2303. return true;
  2304. }
  2305. /**
  2306. * Returns true if connection is still active
  2307. *
  2308. * @return bool
  2309. * @deprecated 3.4.0 Will be removed in 4.0.0
  2310. */
  2311. protected function _isActive()
  2312. {
  2313. return connection_status() === CONNECTION_NORMAL && !connection_aborted();
  2314. }
  2315. /**
  2316. * Clears the contents of the topmost output buffer and discards them
  2317. *
  2318. * @return bool
  2319. * @deprecated 3.2.4 This function is not needed anymore
  2320. */
  2321. protected function _clearBuffer()
  2322. {
  2323. //@codingStandardsIgnoreStart
  2324. return @ob_end_clean();
  2325. //@codingStandardsIgnoreEnd
  2326. }
  2327. /**
  2328. * Flushes the contents of the output buffer
  2329. *
  2330. * @return void
  2331. * @deprecated 3.2.4 This function is not needed anymore
  2332. */
  2333. protected function _flushBuffer()
  2334. {
  2335. //@codingStandardsIgnoreStart
  2336. @flush();
  2337. if (ob_get_level()) {
  2338. @ob_flush();
  2339. }
  2340. //@codingStandardsIgnoreEnd
  2341. }
  2342. /**
  2343. * Stop execution of the current script. Wraps exit() making
  2344. * testing easier.
  2345. *
  2346. * @param int|string $status See https://secure.php.net/exit for values
  2347. * @return void
  2348. * @deprecated 3.4.0 Will be removed in 4.0.0
  2349. */
  2350. public function stop($status = 0)
  2351. {
  2352. exit($status);
  2353. }
  2354. /**
  2355. * Returns an array that can be used to describe the internal state of this
  2356. * object.
  2357. *
  2358. * @return array
  2359. */
  2360. public function __debugInfo()
  2361. {
  2362. return [
  2363. 'status' => $this->_status,
  2364. 'contentType' => $this->_contentType,
  2365. 'headers' => $this->headers,
  2366. 'file' => $this->_file,
  2367. 'fileRange' => $this->_fileRange,
  2368. 'cookies' => $this->_cookies,
  2369. 'cacheDirectives' => $this->_cacheDirectives,
  2370. 'body' => $this->getBody()->getContents(),
  2371. ];
  2372. }
  2373. }
  2374. // @deprecated Add backwards compat alias.
  2375. class_alias('Cake\Http\Response', 'Cake\Network\Response');