Response.php 89 KB

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