Response.php 77 KB

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