Response.php 78 KB

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