Response.php 89 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849
  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 setTypeMap(), 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. * Sets a content type definition into the map.
  1059. *
  1060. * E.g.: setTypeMap('xhtml', ['application/xhtml+xml', 'application/xhtml'])
  1061. *
  1062. * This is needed for RequestHandlerComponent and recognition of types.
  1063. *
  1064. * @param string $type Content type.
  1065. * @param string|array $mimeType Definition of the mime type.
  1066. * @return void
  1067. */
  1068. public function setTypeMap($type, $mimeType)
  1069. {
  1070. $this->_mimeTypes[$type] = $mimeType;
  1071. }
  1072. /**
  1073. * Returns the current content type.
  1074. *
  1075. * @return string
  1076. */
  1077. public function getType()
  1078. {
  1079. return $this->_contentType;
  1080. }
  1081. /**
  1082. * Get an updated response with the content type set.
  1083. *
  1084. * If you attempt to set the type on a 304 or 204 status code response, the
  1085. * content type will not take effect as these status codes do not have content-types.
  1086. *
  1087. * @param string $contentType Either a file extension which will be mapped to a mime-type or a concrete mime-type.
  1088. * @return static
  1089. */
  1090. public function withType($contentType)
  1091. {
  1092. $mappedType = $this->resolveType($contentType);
  1093. $new = clone $this;
  1094. $new->_contentType = $mappedType;
  1095. $new->_setContentType();
  1096. return $new;
  1097. }
  1098. /**
  1099. * Translate and validate content-types.
  1100. *
  1101. * @param string $contentType The content-type or type alias.
  1102. * @return string The resolved content-type
  1103. * @throws \InvalidArgumentException When an invalid content-type or alias is used.
  1104. */
  1105. protected function resolveType($contentType)
  1106. {
  1107. $mapped = $this->getMimeType($contentType);
  1108. if ($mapped) {
  1109. return is_array($mapped) ? current($mapped) : $mapped;
  1110. }
  1111. if (strpos($contentType, '/') === false) {
  1112. throw new InvalidArgumentException(sprintf('"%s" is an invalid content type.', $contentType));
  1113. }
  1114. return $contentType;
  1115. }
  1116. /**
  1117. * Returns the mime type definition for an alias
  1118. *
  1119. * e.g `getMimeType('pdf'); // returns 'application/pdf'`
  1120. *
  1121. * @param string $alias the content type alias to map
  1122. * @return mixed String mapped mime type or false if $alias is not mapped
  1123. */
  1124. public function getMimeType($alias)
  1125. {
  1126. if (isset($this->_mimeTypes[$alias])) {
  1127. return $this->_mimeTypes[$alias];
  1128. }
  1129. return false;
  1130. }
  1131. /**
  1132. * Maps a content-type back to an alias
  1133. *
  1134. * e.g `mapType('application/pdf'); // returns 'pdf'`
  1135. *
  1136. * @param string|array $ctype Either a string content type to map, or an array of types.
  1137. * @return string|array|null Aliases for the types provided.
  1138. */
  1139. public function mapType($ctype)
  1140. {
  1141. if (is_array($ctype)) {
  1142. return array_map([$this, 'mapType'], $ctype);
  1143. }
  1144. foreach ($this->_mimeTypes as $alias => $types) {
  1145. if (in_array($ctype, (array)$types)) {
  1146. return $alias;
  1147. }
  1148. }
  1149. return null;
  1150. }
  1151. /**
  1152. * Sets the response charset
  1153. * if $charset is null the current charset is returned
  1154. *
  1155. * @param string|null $charset Character set string.
  1156. * @return string Current charset
  1157. * @deprecated 3.5.0 Use getCharset()/withCharset() instead.
  1158. */
  1159. public function charset($charset = null)
  1160. {
  1161. deprecationWarning(
  1162. 'Response::charset() is deprecated. ' .
  1163. 'Use getCharset()/withCharset() instead.'
  1164. );
  1165. if ($charset === null) {
  1166. return $this->_charset;
  1167. }
  1168. $this->_charset = $charset;
  1169. $this->_setContentType();
  1170. return $this->_charset;
  1171. }
  1172. /**
  1173. * Returns the current charset.
  1174. *
  1175. * @return string
  1176. */
  1177. public function getCharset()
  1178. {
  1179. return $this->_charset;
  1180. }
  1181. /**
  1182. * Get a new instance with an updated charset.
  1183. *
  1184. * @param string $charset Character set string.
  1185. * @return static
  1186. */
  1187. public function withCharset($charset)
  1188. {
  1189. $new = clone $this;
  1190. $new->_charset = $charset;
  1191. $new->_setContentType();
  1192. return $new;
  1193. }
  1194. /**
  1195. * Sets the correct headers to instruct the client to not cache the response
  1196. *
  1197. * @return void
  1198. * @deprecated 3.4.0 Use withDisabledCache() instead.
  1199. */
  1200. public function disableCache()
  1201. {
  1202. deprecationWarning(
  1203. 'Response::disableCache() is deprecated. ' .
  1204. 'Use withDisabledCache() instead.'
  1205. );
  1206. $this->_setHeader('Expires', 'Mon, 26 Jul 1997 05:00:00 GMT');
  1207. $this->_setHeader('Last-Modified', gmdate('D, d M Y H:i:s') . ' GMT');
  1208. $this->_setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
  1209. }
  1210. /**
  1211. * Create a new instance with headers to instruct the client to not cache the response
  1212. *
  1213. * @return static
  1214. */
  1215. public function withDisabledCache()
  1216. {
  1217. return $this->withHeader('Expires', 'Mon, 26 Jul 1997 05:00:00 GMT')
  1218. ->withHeader('Last-Modified', gmdate('D, d M Y H:i:s') . ' GMT')
  1219. ->withHeader('Cache-Control', 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
  1220. }
  1221. /**
  1222. * Sets the correct headers to instruct the client to cache the response.
  1223. *
  1224. * @param string $since a valid time since the response text has not been modified
  1225. * @param string $time a valid time for cache expiry
  1226. * @return void
  1227. * @deprecated 3.4.0 Use withCache() instead.
  1228. */
  1229. public function cache($since, $time = '+1 day')
  1230. {
  1231. deprecationWarning(
  1232. 'Response::cache() is deprecated. ' .
  1233. 'Use withCache() instead.'
  1234. );
  1235. if (!is_int($time)) {
  1236. $time = strtotime($time);
  1237. }
  1238. $this->_setHeader('Date', gmdate('D, j M Y G:i:s ', time()) . 'GMT');
  1239. $this->modified($since);
  1240. $this->expires($time);
  1241. $this->sharable(true);
  1242. $this->maxAge($time - time());
  1243. }
  1244. /**
  1245. * Create a new instance with the headers to enable client caching.
  1246. *
  1247. * @param string $since a valid time since the response text has not been modified
  1248. * @param string $time a valid time for cache expiry
  1249. * @return static
  1250. */
  1251. public function withCache($since, $time = '+1 day')
  1252. {
  1253. if (!is_int($time)) {
  1254. $time = strtotime($time);
  1255. }
  1256. return $this->withHeader('Date', gmdate('D, j M Y G:i:s ', time()) . 'GMT')
  1257. ->withModified($since)
  1258. ->withExpires($time)
  1259. ->withSharable(true)
  1260. ->withMaxAge($time - time());
  1261. }
  1262. /**
  1263. * Sets whether a response is eligible to be cached by intermediate proxies
  1264. * This method controls the `public` or `private` directive in the Cache-Control
  1265. * header
  1266. *
  1267. * @param bool|null $public If set to true, the Cache-Control header will be set as public
  1268. * if set to false, the response will be set to private
  1269. * if no value is provided, it will return whether the response is sharable or not
  1270. * @param int|null $time time in seconds after which the response should no longer be considered fresh
  1271. * @return bool|null
  1272. */
  1273. public function sharable($public = null, $time = null)
  1274. {
  1275. deprecationWarning(
  1276. 'Response::sharable() is deprecated. ' .
  1277. 'Use withSharable() instead.'
  1278. );
  1279. if ($public === null) {
  1280. $public = array_key_exists('public', $this->_cacheDirectives);
  1281. $private = array_key_exists('private', $this->_cacheDirectives);
  1282. $noCache = array_key_exists('no-cache', $this->_cacheDirectives);
  1283. if (!$public && !$private && !$noCache) {
  1284. return null;
  1285. }
  1286. return $public || !($private || $noCache);
  1287. }
  1288. if ($public) {
  1289. $this->_cacheDirectives['public'] = true;
  1290. unset($this->_cacheDirectives['private']);
  1291. } else {
  1292. $this->_cacheDirectives['private'] = true;
  1293. unset($this->_cacheDirectives['public']);
  1294. }
  1295. $this->maxAge($time);
  1296. if (!$time) {
  1297. $this->_setCacheControl();
  1298. }
  1299. return (bool)$public;
  1300. }
  1301. /**
  1302. * Create a new instace with the public/private Cache-Control directive set.
  1303. *
  1304. * @param bool $public If set to true, the Cache-Control header will be set as public
  1305. * if set to false, the response will be set to private.
  1306. * @param int|null $time time in seconds after which the response should no longer be considered fresh.
  1307. * @return static
  1308. */
  1309. public function withSharable($public, $time = null)
  1310. {
  1311. $new = clone $this;
  1312. unset($new->_cacheDirectives['private'], $new->_cacheDirectives['public']);
  1313. $key = $public ? 'public' : 'private';
  1314. $new->_cacheDirectives[$key] = true;
  1315. if ($time !== null) {
  1316. $new->_cacheDirectives['max-age'] = $time;
  1317. }
  1318. $new->_setCacheControl();
  1319. return $new;
  1320. }
  1321. /**
  1322. * Sets the Cache-Control s-maxage directive.
  1323. *
  1324. * The max-age is the number of seconds after which the response should no longer be considered
  1325. * a good candidate to be fetched from a shared cache (like in a proxy server).
  1326. * If called with no parameters, this function will return the current max-age value if any
  1327. *
  1328. * @deprecated 3.6.5 Use withSharedMaxAge() instead.
  1329. * @param int|null $seconds if null, the method will return the current s-maxage value
  1330. * @return int|null
  1331. */
  1332. public function sharedMaxAge($seconds = null)
  1333. {
  1334. deprecationWarning(
  1335. 'Response::sharedMaxAge() is deprecated. ' .
  1336. 'Use withSharedMaxAge() instead.'
  1337. );
  1338. if ($seconds !== null) {
  1339. $this->_cacheDirectives['s-maxage'] = $seconds;
  1340. $this->_setCacheControl();
  1341. }
  1342. if (isset($this->_cacheDirectives['s-maxage'])) {
  1343. return $this->_cacheDirectives['s-maxage'];
  1344. }
  1345. return null;
  1346. }
  1347. /**
  1348. * Create a new instance with the Cache-Control s-maxage directive.
  1349. *
  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 a shared cache (like in a proxy server).
  1352. *
  1353. * @param int $seconds The number of seconds for shared max-age
  1354. * @return static
  1355. */
  1356. public function withSharedMaxAge($seconds)
  1357. {
  1358. $new = clone $this;
  1359. $new->_cacheDirectives['s-maxage'] = $seconds;
  1360. $new->_setCacheControl();
  1361. return $new;
  1362. }
  1363. /**
  1364. * Sets the Cache-Control max-age directive.
  1365. * The max-age is the number of seconds after which the response should no longer be considered
  1366. * a good candidate to be fetched from the local (client) cache.
  1367. * If called with no parameters, this function will return the current max-age value if any
  1368. *
  1369. * @deprecated 3.6.5 Use withMaxAge() instead.
  1370. * @param int|null $seconds if null, the method will return the current max-age value
  1371. * @return int|null
  1372. */
  1373. public function maxAge($seconds = null)
  1374. {
  1375. deprecationWarning(
  1376. 'Response::maxAge() is deprecated. ' .
  1377. 'Use withMaxAge() instead.'
  1378. );
  1379. if ($seconds !== null) {
  1380. $this->_cacheDirectives['max-age'] = $seconds;
  1381. $this->_setCacheControl();
  1382. }
  1383. if (isset($this->_cacheDirectives['max-age'])) {
  1384. return $this->_cacheDirectives['max-age'];
  1385. }
  1386. return null;
  1387. }
  1388. /**
  1389. * Create an instance with Cache-Control max-age directive set.
  1390. *
  1391. * The max-age is the number of seconds after which the response should no longer be considered
  1392. * a good candidate to be fetched from the local (client) cache.
  1393. *
  1394. * @param int $seconds The seconds a cached response can be considered valid
  1395. * @return static
  1396. */
  1397. public function withMaxAge($seconds)
  1398. {
  1399. $new = clone $this;
  1400. $new->_cacheDirectives['max-age'] = $seconds;
  1401. $new->_setCacheControl();
  1402. return $new;
  1403. }
  1404. /**
  1405. * Sets the Cache-Control must-revalidate directive.
  1406. * must-revalidate indicates that the response should not be served
  1407. * stale by a cache under any circumstance without first revalidating
  1408. * with the origin.
  1409. * If called with no parameters, this function will return whether must-revalidate is present.
  1410. *
  1411. * @param bool|null $enable if null, the method will return the current
  1412. * must-revalidate value. If boolean sets or unsets the directive.
  1413. * @return bool
  1414. * @deprecated 3.4.0 Use withMustRevalidate() instead.
  1415. */
  1416. public function mustRevalidate($enable = null)
  1417. {
  1418. deprecationWarning(
  1419. 'Response::mustRevalidate() is deprecated. ' .
  1420. 'Use withMustRevalidate() instead.'
  1421. );
  1422. if ($enable !== null) {
  1423. if ($enable) {
  1424. $this->_cacheDirectives['must-revalidate'] = true;
  1425. } else {
  1426. unset($this->_cacheDirectives['must-revalidate']);
  1427. }
  1428. $this->_setCacheControl();
  1429. }
  1430. return array_key_exists('must-revalidate', $this->_cacheDirectives);
  1431. }
  1432. /**
  1433. * Create an instance with Cache-Control must-revalidate directive set.
  1434. *
  1435. * Sets the Cache-Control must-revalidate directive.
  1436. * must-revalidate indicates that the response should not be served
  1437. * stale by a cache under any circumstance without first revalidating
  1438. * with the origin.
  1439. *
  1440. * @param bool $enable If boolean sets or unsets the directive.
  1441. * @return static
  1442. */
  1443. public function withMustRevalidate($enable)
  1444. {
  1445. $new = clone $this;
  1446. if ($enable) {
  1447. $new->_cacheDirectives['must-revalidate'] = true;
  1448. } else {
  1449. unset($new->_cacheDirectives['must-revalidate']);
  1450. }
  1451. $new->_setCacheControl();
  1452. return $new;
  1453. }
  1454. /**
  1455. * Helper method to generate a valid Cache-Control header from the options set
  1456. * in other methods
  1457. *
  1458. * @return void
  1459. */
  1460. protected function _setCacheControl()
  1461. {
  1462. $control = '';
  1463. foreach ($this->_cacheDirectives as $key => $val) {
  1464. $control .= $val === true ? $key : sprintf('%s=%s', $key, $val);
  1465. $control .= ', ';
  1466. }
  1467. $control = rtrim($control, ', ');
  1468. $this->_setHeader('Cache-Control', $control);
  1469. }
  1470. /**
  1471. * Sets the Expires header for the response by taking an expiration time
  1472. * If called with no parameters it will return the current Expires value
  1473. *
  1474. * ### Examples:
  1475. *
  1476. * `$response->expires('now')` Will Expire the response cache now
  1477. * `$response->expires(new DateTime('+1 day'))` Will set the expiration in next 24 hours
  1478. * `$response->expires()` Will return the current expiration header value
  1479. *
  1480. * @param string|\DateTime|null $time Valid time string or \DateTime instance.
  1481. * @return string|null
  1482. * @deprecated 3.4.0 Use withExpires() instead.
  1483. */
  1484. public function expires($time = null)
  1485. {
  1486. deprecationWarning(
  1487. 'Response::expires() is deprecated. ' .
  1488. 'Use withExpires() instead.'
  1489. );
  1490. if ($time !== null) {
  1491. $date = $this->_getUTCDate($time);
  1492. $this->_setHeader('Expires', $date->format('D, j M Y H:i:s') . ' GMT');
  1493. }
  1494. if ($this->hasHeader('Expires')) {
  1495. return $this->getHeaderLine('Expires');
  1496. }
  1497. return null;
  1498. }
  1499. /**
  1500. * Create a new instance with the Expires header set.
  1501. *
  1502. * ### Examples:
  1503. *
  1504. * ```
  1505. * // Will Expire the response cache now
  1506. * $response->withExpires('now')
  1507. *
  1508. * // Will set the expiration in next 24 hours
  1509. * $response->withExpires(new DateTime('+1 day'))
  1510. * ```
  1511. *
  1512. * @param string|\DateTime $time Valid time string or \DateTime instance.
  1513. * @return static
  1514. */
  1515. public function withExpires($time)
  1516. {
  1517. $date = $this->_getUTCDate($time);
  1518. return $this->withHeader('Expires', $date->format('D, j M Y H:i:s') . ' GMT');
  1519. }
  1520. /**
  1521. * Sets the Last-Modified header for the response by taking a modification time
  1522. * If called with no parameters it will return the current Last-Modified value
  1523. *
  1524. * ### Examples:
  1525. *
  1526. * `$response->modified('now')` Will set the Last-Modified to the current time
  1527. * `$response->modified(new DateTime('+1 day'))` Will set the modification date in the past 24 hours
  1528. * `$response->modified()` Will return the current Last-Modified header value
  1529. *
  1530. * @param string|\DateTime|null $time Valid time string or \DateTime instance.
  1531. * @return string|null
  1532. * @deprecated 3.4.0 Use withModified() instead.
  1533. */
  1534. public function modified($time = null)
  1535. {
  1536. deprecationWarning(
  1537. 'Response::modified() is deprecated. ' .
  1538. 'Use withModified() or getHeaderLine("Last-Modified") instead.'
  1539. );
  1540. if ($time !== null) {
  1541. $date = $this->_getUTCDate($time);
  1542. $this->_setHeader('Last-Modified', $date->format('D, j M Y H:i:s') . ' GMT');
  1543. }
  1544. if ($this->hasHeader('Last-Modified')) {
  1545. return $this->getHeaderLine('Last-Modified');
  1546. }
  1547. return null;
  1548. }
  1549. /**
  1550. * Create a new instance with the Last-Modified header set.
  1551. *
  1552. * ### Examples:
  1553. *
  1554. * ```
  1555. * // Will Expire the response cache now
  1556. * $response->withModified('now')
  1557. *
  1558. * // Will set the expiration in next 24 hours
  1559. * $response->withModified(new DateTime('+1 day'))
  1560. * ```
  1561. *
  1562. * @param string|\DateTime $time Valid time string or \DateTime instance.
  1563. * @return static
  1564. */
  1565. public function withModified($time)
  1566. {
  1567. $date = $this->_getUTCDate($time);
  1568. return $this->withHeader('Last-Modified', $date->format('D, j M Y H:i:s') . ' GMT');
  1569. }
  1570. /**
  1571. * Sets the response as Not Modified by removing any body contents
  1572. * setting the status code to "304 Not Modified" and removing all
  1573. * conflicting headers
  1574. *
  1575. * *Warning* This method mutates the response in-place and should be avoided.
  1576. *
  1577. * @return void
  1578. */
  1579. public function notModified()
  1580. {
  1581. $this->_createStream();
  1582. $this->_setStatus(304);
  1583. $remove = [
  1584. 'Allow',
  1585. 'Content-Encoding',
  1586. 'Content-Language',
  1587. 'Content-Length',
  1588. 'Content-MD5',
  1589. 'Content-Type',
  1590. 'Last-Modified'
  1591. ];
  1592. foreach ($remove as $header) {
  1593. $this->_clearHeader($header);
  1594. }
  1595. }
  1596. /**
  1597. * Create a new instance as 'not modified'
  1598. *
  1599. * This will remove any body contents set the status code
  1600. * to "304" and removing headers that describe
  1601. * a response body.
  1602. *
  1603. * @return static
  1604. */
  1605. public function withNotModified()
  1606. {
  1607. $new = $this->withStatus(304);
  1608. $new->_createStream();
  1609. $remove = [
  1610. 'Allow',
  1611. 'Content-Encoding',
  1612. 'Content-Language',
  1613. 'Content-Length',
  1614. 'Content-MD5',
  1615. 'Content-Type',
  1616. 'Last-Modified'
  1617. ];
  1618. foreach ($remove as $header) {
  1619. $new = $new->withoutHeader($header);
  1620. }
  1621. return $new;
  1622. }
  1623. /**
  1624. * Sets the Vary header for the response, if an array is passed,
  1625. * values will be imploded into a comma separated string. If no
  1626. * parameters are passed, then an array with the current Vary header
  1627. * value is returned
  1628. *
  1629. * @param string|array|null $cacheVariances A single Vary string or an array
  1630. * containing the list for variances.
  1631. * @return array|null
  1632. * @deprecated 3.4.0 Use withVary() instead.
  1633. */
  1634. public function vary($cacheVariances = null)
  1635. {
  1636. deprecationWarning(
  1637. 'Response::vary() is deprecated. ' .
  1638. 'Use withVary() instead.'
  1639. );
  1640. if ($cacheVariances !== null) {
  1641. $cacheVariances = (array)$cacheVariances;
  1642. $this->_setHeader('Vary', implode(', ', $cacheVariances));
  1643. }
  1644. if ($this->hasHeader('Vary')) {
  1645. return explode(', ', $this->getHeaderLine('Vary'));
  1646. }
  1647. return null;
  1648. }
  1649. /**
  1650. * Create a new instance with the Vary header set.
  1651. *
  1652. * If an array is passed values will be imploded into a comma
  1653. * separated string. If no parameters are passed, then an
  1654. * array with the current Vary header value is returned
  1655. *
  1656. * @param string|array $cacheVariances A single Vary string or an array
  1657. * containing the list for variances.
  1658. * @return static
  1659. */
  1660. public function withVary($cacheVariances)
  1661. {
  1662. return $this->withHeader('Vary', (array)$cacheVariances);
  1663. }
  1664. /**
  1665. * Sets the response Etag, Etags are a strong indicative that a response
  1666. * can be cached by a HTTP client. A bad way of generating Etags is
  1667. * creating a hash of the response output, instead generate a unique
  1668. * hash of the unique components that identifies a request, such as a
  1669. * modification time, a resource Id, and anything else you consider it
  1670. * makes it unique.
  1671. *
  1672. * Second parameter is used to instruct clients that the content has
  1673. * changed, but semantically, it can be used as the same thing. Think
  1674. * for instance of a page with a hit counter, two different page views
  1675. * are equivalent, but they differ by a few bytes. This leaves off to
  1676. * the Client the decision of using or not the cached page.
  1677. *
  1678. * If no parameters are passed, current Etag header is returned.
  1679. *
  1680. * @param string|null $hash The unique hash that identifies this response
  1681. * @param bool $weak Whether the response is semantically the same as
  1682. * other with the same hash or not
  1683. * @return string|null
  1684. * @deprecated 3.4.0 Use withEtag() instead.
  1685. */
  1686. public function etag($hash = null, $weak = false)
  1687. {
  1688. deprecationWarning(
  1689. 'Response::etag() is deprecated. ' .
  1690. 'Use withEtag() or getHeaderLine("Etag") instead.'
  1691. );
  1692. if ($hash !== null) {
  1693. $this->_setHeader('Etag', sprintf('%s"%s"', $weak ? 'W/' : null, $hash));
  1694. }
  1695. if ($this->hasHeader('Etag')) {
  1696. return $this->getHeaderLine('Etag');
  1697. }
  1698. return null;
  1699. }
  1700. /**
  1701. * Create a new instance with the Etag header set.
  1702. *
  1703. * Etags are a strong indicative that a response can be cached by a
  1704. * HTTP client. A bad way of generating Etags is creating a hash of
  1705. * the response output, instead generate a unique hash of the
  1706. * unique components that identifies a request, such as a
  1707. * modification time, a resource Id, and anything else you consider it
  1708. * that makes the response unique.
  1709. *
  1710. * The second parameter is used to inform clients that the content has
  1711. * changed, but semantically it is equivalent to existing cached values. Consider
  1712. * a page with a hit counter, two different page views are equivalent, but
  1713. * they differ by a few bytes. This permits the Client to decide whether they should
  1714. * use the cached data.
  1715. *
  1716. * @param string $hash The unique hash that identifies this response
  1717. * @param bool $weak Whether the response is semantically the same as
  1718. * other with the same hash or not. Defaults to false
  1719. * @return static
  1720. */
  1721. public function withEtag($hash, $weak = false)
  1722. {
  1723. $hash = sprintf('%s"%s"', $weak ? 'W/' : null, $hash);
  1724. return $this->withHeader('Etag', $hash);
  1725. }
  1726. /**
  1727. * Returns a DateTime object initialized at the $time param and using UTC
  1728. * as timezone
  1729. *
  1730. * @param string|int|\DateTime|null $time Valid time string or \DateTime instance.
  1731. * @return \DateTime
  1732. */
  1733. protected function _getUTCDate($time = null)
  1734. {
  1735. if ($time instanceof DateTime) {
  1736. $result = clone $time;
  1737. } elseif (is_int($time)) {
  1738. $result = new DateTime(date('Y-m-d H:i:s', $time));
  1739. } else {
  1740. $result = new DateTime($time);
  1741. }
  1742. $result->setTimezone(new DateTimeZone('UTC'));
  1743. return $result;
  1744. }
  1745. /**
  1746. * Sets the correct output buffering handler to send a compressed response. Responses will
  1747. * be compressed with zlib, if the extension is available.
  1748. *
  1749. * @return bool false if client does not accept compressed responses or no handler is available, true otherwise
  1750. */
  1751. public function compress()
  1752. {
  1753. $compressionEnabled = ini_get('zlib.output_compression') !== '1' &&
  1754. extension_loaded('zlib') &&
  1755. (strpos(env('HTTP_ACCEPT_ENCODING'), 'gzip') !== false);
  1756. return $compressionEnabled && ob_start('ob_gzhandler');
  1757. }
  1758. /**
  1759. * Returns whether the resulting output will be compressed by PHP
  1760. *
  1761. * @return bool
  1762. */
  1763. public function outputCompressed()
  1764. {
  1765. return strpos(env('HTTP_ACCEPT_ENCODING'), 'gzip') !== false
  1766. && (ini_get('zlib.output_compression') === '1' || in_array('ob_gzhandler', ob_list_handlers()));
  1767. }
  1768. /**
  1769. * Sets the correct headers to instruct the browser to download the response as a file.
  1770. *
  1771. * @param string $filename The name of the file as the browser will download the response
  1772. * @return void
  1773. * @deprecated 3.4.0 Use withDownload() instead.
  1774. */
  1775. public function download($filename)
  1776. {
  1777. deprecationWarning(
  1778. 'Response::download() is deprecated. ' .
  1779. 'Use withDownload() instead.'
  1780. );
  1781. $this->header('Content-Disposition', 'attachment; filename="' . $filename . '"');
  1782. }
  1783. /**
  1784. * Create a new instance with the Content-Disposition header set.
  1785. *
  1786. * @param string $filename The name of the file as the browser will download the response
  1787. * @return static
  1788. */
  1789. public function withDownload($filename)
  1790. {
  1791. return $this->withHeader('Content-Disposition', 'attachment; filename="' . $filename . '"');
  1792. }
  1793. /**
  1794. * Sets the protocol to be used when sending the response. Defaults to HTTP/1.1
  1795. * If called with no arguments, it will return the current configured protocol
  1796. *
  1797. * @param string|null $protocol Protocol to be used for sending response.
  1798. * @return string Protocol currently set
  1799. * @deprecated 3.4.0 Use getProtocolVersion() instead.
  1800. */
  1801. public function protocol($protocol = null)
  1802. {
  1803. deprecationWarning(
  1804. 'Response::protocol() is deprecated. ' .
  1805. 'Use getProtocolVersion() instead.'
  1806. );
  1807. if ($protocol !== null) {
  1808. $this->_protocol = $protocol;
  1809. }
  1810. return $this->_protocol;
  1811. }
  1812. /**
  1813. * Sets the Content-Length header for the response
  1814. * If called with no arguments returns the last Content-Length set
  1815. *
  1816. * @param int|null $bytes Number of bytes
  1817. * @return string|null
  1818. * @deprecated 3.4.0 Use withLength() to set length instead.
  1819. */
  1820. public function length($bytes = null)
  1821. {
  1822. deprecationWarning(
  1823. 'Response::length() is deprecated. ' .
  1824. 'Use withLength() instead.'
  1825. );
  1826. if ($bytes !== null) {
  1827. $this->_setHeader('Content-Length', $bytes);
  1828. }
  1829. if ($this->hasHeader('Content-Length')) {
  1830. return $this->getHeaderLine('Content-Length');
  1831. }
  1832. return null;
  1833. }
  1834. /**
  1835. * Create a new response with the Content-Length header set.
  1836. *
  1837. * @param int|string $bytes Number of bytes
  1838. * @return static
  1839. */
  1840. public function withLength($bytes)
  1841. {
  1842. return $this->withHeader('Content-Length', (string)$bytes);
  1843. }
  1844. /**
  1845. * Create a new response with the Link header set.
  1846. *
  1847. * ### Examples
  1848. *
  1849. * ```
  1850. * $response = $response->withAddedLink('http://example.com?page=1', ['rel' => 'prev'])
  1851. * ->withAddedLink('http://example.com?page=3', ['rel' => 'next']);
  1852. * ```
  1853. *
  1854. * Will generate:
  1855. *
  1856. * ```
  1857. * Link: <http://example.com?page=1>; rel="prev"
  1858. * Link: <http://example.com?page=3>; rel="next"
  1859. * ```
  1860. *
  1861. * @param string $url The LinkHeader url.
  1862. * @param array $options The LinkHeader params.
  1863. * @return static
  1864. * @since 3.6.0
  1865. */
  1866. public function withAddedLink($url, $options = [])
  1867. {
  1868. $params = [];
  1869. foreach ($options as $key => $option) {
  1870. $params[] = $key . '="' . $option . '"';
  1871. }
  1872. $param = '';
  1873. if ($params) {
  1874. $param = '; ' . implode('; ', $params);
  1875. }
  1876. return $this->withAddedHeader('Link', '<' . $url . '>' . $param);
  1877. }
  1878. /**
  1879. * Checks whether a response has not been modified according to the 'If-None-Match'
  1880. * (Etags) and 'If-Modified-Since' (last modification date) request
  1881. * headers. If the response is detected to be not modified, it
  1882. * is marked as so accordingly so the client can be informed of that.
  1883. *
  1884. * In order to mark a response as not modified, you need to set at least
  1885. * the Last-Modified etag response header before calling this method. Otherwise
  1886. * a comparison will not be possible.
  1887. *
  1888. * *Warning* This method mutates the response in-place and should be avoided.
  1889. *
  1890. * @param \Cake\Http\ServerRequest $request Request object
  1891. * @return bool Whether the response was marked as not modified or not.
  1892. */
  1893. public function checkNotModified(ServerRequest $request)
  1894. {
  1895. $etags = preg_split('/\s*,\s*/', (string)$request->getHeaderLine('If-None-Match'), 0, PREG_SPLIT_NO_EMPTY);
  1896. $responseTag = $this->getHeaderLine('Etag');
  1897. $etagMatches = null;
  1898. if ($responseTag) {
  1899. $etagMatches = in_array('*', $etags) || in_array($responseTag, $etags);
  1900. }
  1901. $modifiedSince = $request->getHeaderLine('If-Modified-Since');
  1902. $timeMatches = null;
  1903. if ($modifiedSince && $this->hasHeader('Last-Modified')) {
  1904. $timeMatches = strtotime($this->getHeaderLine('Last-Modified')) === strtotime($modifiedSince);
  1905. }
  1906. if ($etagMatches === null && $timeMatches === null) {
  1907. return false;
  1908. }
  1909. $notModified = $etagMatches !== false && $timeMatches !== false;
  1910. if ($notModified) {
  1911. $this->notModified();
  1912. }
  1913. return $notModified;
  1914. }
  1915. /**
  1916. * String conversion. Fetches the response body as a string.
  1917. * Does *not* send headers.
  1918. * If body is a callable, a blank string is returned.
  1919. *
  1920. * @return string
  1921. */
  1922. public function __toString()
  1923. {
  1924. $this->stream->rewind();
  1925. return (string)$this->stream->getContents();
  1926. }
  1927. /**
  1928. * Getter/Setter for cookie configs
  1929. *
  1930. * This method acts as a setter/getter depending on the type of the argument.
  1931. * If the method is called with no arguments, it returns all configurations.
  1932. *
  1933. * If the method is called with a string as argument, it returns either the
  1934. * given configuration if it is set, or null, if it's not set.
  1935. *
  1936. * If the method is called with an array as argument, it will set the cookie
  1937. * configuration to the cookie container.
  1938. *
  1939. * ### Options (when setting a configuration)
  1940. * - name: The Cookie name
  1941. * - value: Value of the cookie
  1942. * - expire: Time the cookie expires in
  1943. * - path: Path the cookie applies to
  1944. * - domain: Domain the cookie is for.
  1945. * - secure: Is the cookie https?
  1946. * - httpOnly: Is the cookie available in the client?
  1947. *
  1948. * ### Examples
  1949. *
  1950. * ### Getting all cookies
  1951. *
  1952. * `$this->cookie()`
  1953. *
  1954. * ### Getting a certain cookie configuration
  1955. *
  1956. * `$this->cookie('MyCookie')`
  1957. *
  1958. * ### Setting a cookie configuration
  1959. *
  1960. * `$this->cookie((array) $options)`
  1961. *
  1962. * @param array|null $options Either null to get all cookies, string for a specific cookie
  1963. * or array to set cookie.
  1964. * @return mixed
  1965. * @deprecated 3.4.0 Use getCookie(), getCookies() and withCookie() instead.
  1966. */
  1967. public function cookie($options = null)
  1968. {
  1969. deprecationWarning(
  1970. 'Response::cookie() is deprecated. ' .
  1971. 'Use getCookie(), getCookies() and withCookie() instead.'
  1972. );
  1973. if ($options === null) {
  1974. return $this->getCookies();
  1975. }
  1976. if (is_string($options)) {
  1977. if (!$this->_cookies->has($options)) {
  1978. return null;
  1979. }
  1980. $cookie = $this->_cookies->get($options);
  1981. return $this->convertCookieToArray($cookie);
  1982. }
  1983. $options += [
  1984. 'name' => 'CakeCookie[default]',
  1985. 'value' => '',
  1986. 'expire' => 0,
  1987. 'path' => '/',
  1988. 'domain' => '',
  1989. 'secure' => false,
  1990. 'httpOnly' => false
  1991. ];
  1992. $expires = $options['expire'] ? new DateTime('@' . $options['expire']) : null;
  1993. $cookie = new Cookie(
  1994. $options['name'],
  1995. $options['value'],
  1996. $expires,
  1997. $options['path'],
  1998. $options['domain'],
  1999. $options['secure'],
  2000. $options['httpOnly']
  2001. );
  2002. $this->_cookies = $this->_cookies->add($cookie);
  2003. }
  2004. /**
  2005. * Create a new response with a cookie set.
  2006. *
  2007. * ### Data
  2008. *
  2009. * - `value`: Value of the cookie
  2010. * - `expire`: Time the cookie expires in
  2011. * - `path`: Path the cookie applies to
  2012. * - `domain`: Domain the cookie is for.
  2013. * - `secure`: Is the cookie https?
  2014. * - `httpOnly`: Is the cookie available in the client?
  2015. *
  2016. * ### Examples
  2017. *
  2018. * ```
  2019. * // set scalar value with defaults
  2020. * $response = $response->withCookie('remember_me', 1);
  2021. *
  2022. * // customize cookie attributes
  2023. * $response = $response->withCookie('remember_me', ['path' => '/login']);
  2024. *
  2025. * // add a cookie object
  2026. * $response = $response->withCookie(new Cookie('remember_me', 1));
  2027. * ```
  2028. *
  2029. * @param string|\Cake\Http\Cookie\Cookie $name The name of the cookie to set, or a cookie object
  2030. * @param array|string $data Either a string value, or an array of cookie options.
  2031. * @return static
  2032. */
  2033. public function withCookie($name, $data = '')
  2034. {
  2035. if ($name instanceof Cookie) {
  2036. $cookie = $name;
  2037. } else {
  2038. deprecationWarning(
  2039. get_called_class() . '::withCookie(string $name, array $data) is deprecated. ' .
  2040. 'Pass an instance of \Cake\Http\Cookie\Cookie instead.'
  2041. );
  2042. if (!is_array($data)) {
  2043. $data = ['value' => $data];
  2044. }
  2045. $data += [
  2046. 'value' => '',
  2047. 'expire' => 0,
  2048. 'path' => '/',
  2049. 'domain' => '',
  2050. 'secure' => false,
  2051. 'httpOnly' => false
  2052. ];
  2053. $expires = $data['expire'] ? new DateTime('@' . $data['expire']) : null;
  2054. $cookie = new Cookie(
  2055. $name,
  2056. $data['value'],
  2057. $expires,
  2058. $data['path'],
  2059. $data['domain'],
  2060. $data['secure'],
  2061. $data['httpOnly']
  2062. );
  2063. }
  2064. $new = clone $this;
  2065. $new->_cookies = $new->_cookies->add($cookie);
  2066. return $new;
  2067. }
  2068. /**
  2069. * Create a new response with an expired cookie set.
  2070. *
  2071. * ### Options
  2072. *
  2073. * - `path`: Path the cookie applies to
  2074. * - `domain`: Domain the cookie is for.
  2075. * - `secure`: Is the cookie https?
  2076. * - `httpOnly`: Is the cookie available in the client?
  2077. *
  2078. * ### Examples
  2079. *
  2080. * ```
  2081. * // set scalar value with defaults
  2082. * $response = $response->withExpiredCookie('remember_me');
  2083. *
  2084. * // customize cookie attributes
  2085. * $response = $response->withExpiredCookie('remember_me', ['path' => '/login']);
  2086. *
  2087. * // add a cookie object
  2088. * $response = $response->withExpiredCookie(new Cookie('remember_me'));
  2089. * ```
  2090. *
  2091. * @param string|\Cake\Http\Cookie\CookieInterface $name The name of the cookie to expire, or a cookie object
  2092. * @param array $options An array of cookie options.
  2093. * @return static
  2094. */
  2095. public function withExpiredCookie($name, $options = [])
  2096. {
  2097. if ($name instanceof CookieInterface) {
  2098. $cookie = $name->withExpired();
  2099. } else {
  2100. deprecationWarning(
  2101. get_called_class() . '::withExpiredCookie(string $name, array $data) is deprecated. ' .
  2102. 'Pass an instance of \Cake\Http\Cookie\Cookie instead.'
  2103. );
  2104. $options += [
  2105. 'path' => '/',
  2106. 'domain' => '',
  2107. 'secure' => false,
  2108. 'httpOnly' => false
  2109. ];
  2110. $cookie = new Cookie(
  2111. $name,
  2112. '',
  2113. DateTime::createFromFormat('U', 1),
  2114. $options['path'],
  2115. $options['domain'],
  2116. $options['secure'],
  2117. $options['httpOnly']
  2118. );
  2119. }
  2120. $new = clone $this;
  2121. $new->_cookies = $new->_cookies->add($cookie);
  2122. return $new;
  2123. }
  2124. /**
  2125. * Read a single cookie from the response.
  2126. *
  2127. * This method provides read access to pending cookies. It will
  2128. * not read the `Set-Cookie` header if set.
  2129. *
  2130. * @param string $name The cookie name you want to read.
  2131. * @return array|null Either the cookie data or null
  2132. */
  2133. public function getCookie($name)
  2134. {
  2135. if (!$this->_cookies->has($name)) {
  2136. return null;
  2137. }
  2138. $cookie = $this->_cookies->get($name);
  2139. return $this->convertCookieToArray($cookie);
  2140. }
  2141. /**
  2142. * Get all cookies in the response.
  2143. *
  2144. * Returns an associative array of cookie name => cookie data.
  2145. *
  2146. * @return array
  2147. */
  2148. public function getCookies()
  2149. {
  2150. $out = [];
  2151. foreach ($this->_cookies as $cookie) {
  2152. $out[$cookie->getName()] = $this->convertCookieToArray($cookie);
  2153. }
  2154. return $out;
  2155. }
  2156. /**
  2157. * Convert the cookie into an array of its properties.
  2158. *
  2159. * This method is compatible with the historical behavior of Cake\Http\Response,
  2160. * where `httponly` is `httpOnly` and `expires` is `expire`
  2161. *
  2162. * @param \Cake\Http\Cookie\CookieInterface $cookie Cookie object.
  2163. * @return array
  2164. */
  2165. protected function convertCookieToArray(CookieInterface $cookie)
  2166. {
  2167. return [
  2168. 'name' => $cookie->getName(),
  2169. 'value' => $cookie->getStringValue(),
  2170. 'path' => $cookie->getPath(),
  2171. 'domain' => $cookie->getDomain(),
  2172. 'secure' => $cookie->isSecure(),
  2173. 'httpOnly' => $cookie->isHttpOnly(),
  2174. 'expire' => $cookie->getExpiresTimestamp()
  2175. ];
  2176. }
  2177. /**
  2178. * Get the CookieCollection from the response
  2179. *
  2180. * @return \Cake\Http\Cookie\CookieCollection
  2181. */
  2182. public function getCookieCollection()
  2183. {
  2184. return $this->_cookies;
  2185. }
  2186. /**
  2187. * Setup access for origin and methods on cross origin requests
  2188. *
  2189. * This method allow multiple ways to setup the domains, see the examples
  2190. *
  2191. * ### Full URI
  2192. * ```
  2193. * cors($request, 'https://www.cakephp.org');
  2194. * ```
  2195. *
  2196. * ### URI with wildcard
  2197. * ```
  2198. * cors($request, 'https://*.cakephp.org');
  2199. * ```
  2200. *
  2201. * ### Ignoring the requested protocol
  2202. * ```
  2203. * cors($request, 'www.cakephp.org');
  2204. * ```
  2205. *
  2206. * ### Any URI
  2207. * ```
  2208. * cors($request, '*');
  2209. * ```
  2210. *
  2211. * ### Whitelist of URIs
  2212. * ```
  2213. * cors($request, ['http://www.cakephp.org', '*.google.com', 'https://myproject.github.io']);
  2214. * ```
  2215. *
  2216. * *Note* The `$allowedDomains`, `$allowedMethods`, `$allowedHeaders` parameters are deprecated.
  2217. * Instead the builder object should be used.
  2218. *
  2219. * @param \Cake\Http\ServerRequest $request Request object
  2220. * @param string|array $allowedDomains List of allowed domains, see method description for more details
  2221. * @param string|array $allowedMethods List of HTTP verbs allowed
  2222. * @param string|array $allowedHeaders List of HTTP headers allowed
  2223. * @return \Cake\Http\CorsBuilder A builder object the provides a fluent interface for defining
  2224. * additional CORS headers.
  2225. */
  2226. public function cors(ServerRequest $request, $allowedDomains = [], $allowedMethods = [], $allowedHeaders = [])
  2227. {
  2228. $origin = $request->getHeaderLine('Origin');
  2229. $ssl = $request->is('ssl');
  2230. $builder = new CorsBuilder($this, $origin, $ssl);
  2231. if (!$origin) {
  2232. return $builder;
  2233. }
  2234. if (empty($allowedDomains) && empty($allowedMethods) && empty($allowedHeaders)) {
  2235. return $builder;
  2236. }
  2237. deprecationWarning(
  2238. 'The $allowedDomains, $allowedMethods, and $allowedHeaders parameters of Response::cors() ' .
  2239. 'are deprecated. Instead you should use the builder methods on the return of cors().'
  2240. );
  2241. $updated = $builder->allowOrigin($allowedDomains)
  2242. ->allowMethods((array)$allowedMethods)
  2243. ->allowHeaders((array)$allowedHeaders)
  2244. ->build();
  2245. // If $updated is a new instance, mutate this object in-place
  2246. // to retain existing behavior.
  2247. if ($updated !== $this) {
  2248. foreach ($updated->getHeaders() as $name => $values) {
  2249. if (!$this->hasHeader($name)) {
  2250. $this->_setHeader($name, $values[0]);
  2251. }
  2252. }
  2253. }
  2254. return $builder;
  2255. }
  2256. /**
  2257. * Setup for display or download the given file.
  2258. *
  2259. * If $_SERVER['HTTP_RANGE'] is set a slice of the file will be
  2260. * returned instead of the entire file.
  2261. *
  2262. * ### Options keys
  2263. *
  2264. * - name: Alternate download name
  2265. * - download: If `true` sets download header and forces file to be downloaded rather than displayed in browser
  2266. *
  2267. * @param string $path Path to file. If the path is not an absolute path that resolves
  2268. * to a file, `APP` will be prepended to the path (this behavior is deprecated).
  2269. * @param array $options Options See above.
  2270. * @return void
  2271. * @throws \Cake\Http\Exception\NotFoundException
  2272. * @deprecated 3.4.0 Use withFile() instead.
  2273. */
  2274. public function file($path, array $options = [])
  2275. {
  2276. deprecationWarning(
  2277. 'Response::file() is deprecated. ' .
  2278. 'Use withFile() instead.'
  2279. );
  2280. $file = $this->validateFile($path);
  2281. $options += [
  2282. 'name' => null,
  2283. 'download' => null
  2284. ];
  2285. $extension = strtolower($file->ext());
  2286. $download = $options['download'];
  2287. if ((!$extension || $this->type($extension) === false) && $download === null) {
  2288. $download = true;
  2289. }
  2290. $fileSize = $file->size();
  2291. if ($download) {
  2292. $agent = env('HTTP_USER_AGENT');
  2293. if (preg_match('%Opera(/| )([0-9].[0-9]{1,2})%', $agent)) {
  2294. $contentType = 'application/octet-stream';
  2295. } elseif (preg_match('/MSIE ([0-9].[0-9]{1,2})/', $agent)) {
  2296. $contentType = 'application/force-download';
  2297. }
  2298. if (!empty($contentType)) {
  2299. $this->type($contentType);
  2300. }
  2301. if ($options['name'] === null) {
  2302. $name = $file->name;
  2303. } else {
  2304. $name = $options['name'];
  2305. }
  2306. $this->download($name);
  2307. $this->header('Content-Transfer-Encoding', 'binary');
  2308. }
  2309. $this->header('Accept-Ranges', 'bytes');
  2310. $httpRange = env('HTTP_RANGE');
  2311. if (isset($httpRange)) {
  2312. $this->_fileRange($file, $httpRange);
  2313. } else {
  2314. $this->header('Content-Length', $fileSize);
  2315. }
  2316. $this->_file = $file;
  2317. $this->stream = new Stream($file->path, 'rb');
  2318. }
  2319. /**
  2320. * Create a new instance that is based on a file.
  2321. *
  2322. * This method will augment both the body and a number of related headers.
  2323. *
  2324. * If `$_SERVER['HTTP_RANGE']` is set, a slice of the file will be
  2325. * returned instead of the entire file.
  2326. *
  2327. * ### Options keys
  2328. *
  2329. * - name: Alternate download name
  2330. * - download: If `true` sets download header and forces file to
  2331. * be downloaded rather than displayed inline.
  2332. *
  2333. * @param string $path Path to file. If the path is not an absolute path that resolves
  2334. * to a file, `APP` will be prepended to the path (this behavior is deprecated).
  2335. * @param array $options Options See above.
  2336. * @return static
  2337. * @throws \Cake\Http\Exception\NotFoundException
  2338. */
  2339. public function withFile($path, array $options = [])
  2340. {
  2341. $file = $this->validateFile($path);
  2342. $options += [
  2343. 'name' => null,
  2344. 'download' => null
  2345. ];
  2346. $extension = strtolower($file->ext());
  2347. $mapped = $this->getMimeType($extension);
  2348. if ((!$extension || !$mapped) && $options['download'] === null) {
  2349. $options['download'] = true;
  2350. }
  2351. $new = clone $this;
  2352. if ($mapped) {
  2353. $new = $new->withType($extension);
  2354. }
  2355. $fileSize = $file->size();
  2356. if ($options['download']) {
  2357. $agent = env('HTTP_USER_AGENT');
  2358. if (preg_match('%Opera(/| )([0-9].[0-9]{1,2})%', $agent)) {
  2359. $contentType = 'application/octet-stream';
  2360. } elseif (preg_match('/MSIE ([0-9].[0-9]{1,2})/', $agent)) {
  2361. $contentType = 'application/force-download';
  2362. }
  2363. if (isset($contentType)) {
  2364. $new = $new->withType($contentType);
  2365. }
  2366. $name = $options['name'] ?: $file->name;
  2367. $new = $new->withDownload($name)
  2368. ->withHeader('Content-Transfer-Encoding', 'binary');
  2369. }
  2370. $new = $new->withHeader('Accept-Ranges', 'bytes');
  2371. $httpRange = env('HTTP_RANGE');
  2372. if (isset($httpRange)) {
  2373. $new->_fileRange($file, $httpRange);
  2374. } else {
  2375. $new = $new->withHeader('Content-Length', (string)$fileSize);
  2376. }
  2377. $new->_file = $file;
  2378. $new->stream = new Stream($file->path, 'rb');
  2379. return $new;
  2380. }
  2381. /**
  2382. * Convenience method to set a string into the response body
  2383. *
  2384. * @param string $string The string to be sent
  2385. * @return static
  2386. */
  2387. public function withStringBody($string)
  2388. {
  2389. $new = clone $this;
  2390. $new->_createStream();
  2391. $new->stream->write((string)$string);
  2392. return $new;
  2393. }
  2394. /**
  2395. * Validate a file path is a valid response body.
  2396. *
  2397. * @param string $path The path to the file.
  2398. * @throws \Cake\Http\Exception\NotFoundException
  2399. * @return \Cake\Filesystem\File
  2400. */
  2401. protected function validateFile($path)
  2402. {
  2403. if (strpos($path, '../') !== false || strpos($path, '..\\') !== false) {
  2404. throw new NotFoundException(__d('cake', 'The requested file contains `..` and will not be read.'));
  2405. }
  2406. if (!is_file($path)) {
  2407. deprecationWarning(
  2408. 'Automatic prefixing of paths with `APP` by `Response::file()` and `withFile()` is deprecated. ' .
  2409. 'Use absolute paths instead.'
  2410. );
  2411. $path = APP . $path;
  2412. }
  2413. if (!Folder::isAbsolute($path)) {
  2414. deprecationWarning(
  2415. 'Serving files via `file()` or `withFile()` using relative paths is deprecated.' .
  2416. 'Use an absolute path instead.'
  2417. );
  2418. }
  2419. $file = new File($path);
  2420. if (!$file->exists() || !$file->readable()) {
  2421. if (Configure::read('debug')) {
  2422. throw new NotFoundException(sprintf('The requested file %s was not found or not readable', $path));
  2423. }
  2424. throw new NotFoundException(__d('cake', 'The requested file was not found'));
  2425. }
  2426. return $file;
  2427. }
  2428. /**
  2429. * Get the current file if one exists.
  2430. *
  2431. * @return \Cake\Filesystem\File|null The file to use in the response or null
  2432. */
  2433. public function getFile()
  2434. {
  2435. return $this->_file;
  2436. }
  2437. /**
  2438. * Apply a file range to a file and set the end offset.
  2439. *
  2440. * If an invalid range is requested a 416 Status code will be used
  2441. * in the response.
  2442. *
  2443. * @param \Cake\Filesystem\File $file The file to set a range on.
  2444. * @param string $httpRange The range to use.
  2445. * @return void
  2446. * @deprecated 3.4.0 Long term this needs to be refactored to follow immutable paradigms.
  2447. * However for now, it is simpler to leave this alone.
  2448. */
  2449. protected function _fileRange($file, $httpRange)
  2450. {
  2451. $fileSize = $file->size();
  2452. $lastByte = $fileSize - 1;
  2453. $start = 0;
  2454. $end = $lastByte;
  2455. preg_match('/^bytes\s*=\s*(\d+)?\s*-\s*(\d+)?$/', $httpRange, $matches);
  2456. if ($matches) {
  2457. $start = $matches[1];
  2458. $end = isset($matches[2]) ? $matches[2] : '';
  2459. }
  2460. if ($start === '') {
  2461. $start = $fileSize - $end;
  2462. $end = $lastByte;
  2463. }
  2464. if ($end === '') {
  2465. $end = $lastByte;
  2466. }
  2467. if ($start > $end || $end > $lastByte || $start > $lastByte) {
  2468. $this->_setStatus(416);
  2469. $this->_setHeader('Content-Range', 'bytes 0-' . $lastByte . '/' . $fileSize);
  2470. return;
  2471. }
  2472. $this->_setHeader('Content-Length', $end - $start + 1);
  2473. $this->_setHeader('Content-Range', 'bytes ' . $start . '-' . $end . '/' . $fileSize);
  2474. $this->_setStatus(206);
  2475. $this->_fileRange = [$start, $end];
  2476. }
  2477. /**
  2478. * Reads out a file, and echos the content to the client.
  2479. *
  2480. * @param \Cake\Filesystem\File $file File object
  2481. * @param array $range The range to read out of the file.
  2482. * @return bool True is whole file is echoed successfully or false if client connection is lost in between
  2483. * @deprecated 3.4.0 Will be removed in 4.0.0
  2484. */
  2485. protected function _sendFile($file, $range)
  2486. {
  2487. deprecationWarning('Will be removed in 4.0.0');
  2488. ob_implicit_flush(true);
  2489. $file->open('rb');
  2490. $end = $start = false;
  2491. if ($range) {
  2492. list($start, $end) = $range;
  2493. }
  2494. if ($start !== false) {
  2495. $file->offset($start);
  2496. }
  2497. $bufferSize = 8192;
  2498. if (strpos(ini_get('disable_functions'), 'set_time_limit') === false) {
  2499. set_time_limit(0);
  2500. }
  2501. session_write_close();
  2502. while (!feof($file->handle)) {
  2503. if (!$this->_isActive()) {
  2504. $file->close();
  2505. return false;
  2506. }
  2507. $offset = $file->offset();
  2508. if ($end && $offset >= $end) {
  2509. break;
  2510. }
  2511. if ($end && $offset + $bufferSize >= $end) {
  2512. $bufferSize = $end - $offset + 1;
  2513. }
  2514. echo fread($file->handle, $bufferSize);
  2515. }
  2516. $file->close();
  2517. return true;
  2518. }
  2519. /**
  2520. * Returns true if connection is still active
  2521. *
  2522. * @return bool
  2523. * @deprecated 3.4.0 Will be removed in 4.0.0
  2524. */
  2525. protected function _isActive()
  2526. {
  2527. deprecationWarning('Will be removed in 4.0.0');
  2528. return connection_status() === CONNECTION_NORMAL && !connection_aborted();
  2529. }
  2530. /**
  2531. * Clears the contents of the topmost output buffer and discards them
  2532. *
  2533. * @return bool
  2534. * @deprecated 3.2.4 This function is not needed anymore
  2535. */
  2536. protected function _clearBuffer()
  2537. {
  2538. deprecationWarning(
  2539. 'This function is not needed anymore and will be removed.'
  2540. );
  2541. //@codingStandardsIgnoreStart
  2542. return @ob_end_clean();
  2543. //@codingStandardsIgnoreEnd
  2544. }
  2545. /**
  2546. * Flushes the contents of the output buffer
  2547. *
  2548. * @return void
  2549. * @deprecated 3.2.4 This function is not needed anymore
  2550. */
  2551. protected function _flushBuffer()
  2552. {
  2553. deprecationWarning(
  2554. 'This function is not needed anymore and will be removed.'
  2555. );
  2556. //@codingStandardsIgnoreStart
  2557. @flush();
  2558. if (ob_get_level()) {
  2559. @ob_flush();
  2560. }
  2561. //@codingStandardsIgnoreEnd
  2562. }
  2563. /**
  2564. * Stop execution of the current script. Wraps exit() making
  2565. * testing easier.
  2566. *
  2567. * @param int|string $status See https://secure.php.net/exit for values
  2568. * @return void
  2569. * @deprecated 3.4.0 Will be removed in 4.0.0
  2570. */
  2571. public function stop($status = 0)
  2572. {
  2573. deprecationWarning('Will be removed in 4.0.0');
  2574. exit($status);
  2575. }
  2576. /**
  2577. * Returns an array that can be used to describe the internal state of this
  2578. * object.
  2579. *
  2580. * @return array
  2581. */
  2582. public function __debugInfo()
  2583. {
  2584. return [
  2585. 'status' => $this->_status,
  2586. 'contentType' => $this->_contentType,
  2587. 'headers' => $this->headers,
  2588. 'file' => $this->_file,
  2589. 'fileRange' => $this->_fileRange,
  2590. 'cookies' => $this->_cookies,
  2591. 'cacheDirectives' => $this->_cacheDirectives,
  2592. 'body' => (string)$this->getBody(),
  2593. ];
  2594. }
  2595. }
  2596. // @deprecated 3.4.0 Add backwards compat alias.
  2597. class_alias('Cake\Http\Response', 'Cake\Network\Response');