Response.php 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430
  1. <?php
  2. /**
  3. * Cake Response
  4. *
  5. * PHP 5
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  9. *
  10. * Licensed under The MIT License
  11. * For full copyright and license information, please see the LICENSE.txt
  12. * Redistributions of files must retain the above copyright notice.
  13. *
  14. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  15. * @link http://cakephp.org CakePHP(tm) Project
  16. * @since CakePHP(tm) v 2.0
  17. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  18. */
  19. namespace Cake\Network;
  20. use Cake\Core\Configure;
  21. use Cake\Error;
  22. use Cake\Utility\File;
  23. /**
  24. * Cake Response is responsible for managing the response text, status and headers of a HTTP response.
  25. *
  26. * By default controllers will use this class to render their response. If you are going to use
  27. * a custom response class it should subclass this object in order to ensure compatibility.
  28. *
  29. */
  30. class Response {
  31. /**
  32. * Holds HTTP response statuses
  33. *
  34. * @var array
  35. */
  36. protected $_statusCodes = array(
  37. 100 => 'Continue',
  38. 101 => 'Switching Protocols',
  39. 200 => 'OK',
  40. 201 => 'Created',
  41. 202 => 'Accepted',
  42. 203 => 'Non-Authoritative Information',
  43. 204 => 'No Content',
  44. 205 => 'Reset Content',
  45. 206 => 'Partial Content',
  46. 300 => 'Multiple Choices',
  47. 301 => 'Moved Permanently',
  48. 302 => 'Found',
  49. 303 => 'See Other',
  50. 304 => 'Not Modified',
  51. 305 => 'Use Proxy',
  52. 307 => 'Temporary Redirect',
  53. 400 => 'Bad Request',
  54. 401 => 'Unauthorized',
  55. 402 => 'Payment Required',
  56. 403 => 'Forbidden',
  57. 404 => 'Not Found',
  58. 405 => 'Method Not Allowed',
  59. 406 => 'Not Acceptable',
  60. 407 => 'Proxy Authentication Required',
  61. 408 => 'Request Time-out',
  62. 409 => 'Conflict',
  63. 410 => 'Gone',
  64. 411 => 'Length Required',
  65. 412 => 'Precondition Failed',
  66. 413 => 'Request Entity Too Large',
  67. 414 => 'Request-URI Too Large',
  68. 415 => 'Unsupported Media Type',
  69. 416 => 'Requested range not satisfiable',
  70. 417 => 'Expectation Failed',
  71. 500 => 'Internal Server Error',
  72. 501 => 'Not Implemented',
  73. 502 => 'Bad Gateway',
  74. 503 => 'Service Unavailable',
  75. 504 => 'Gateway Time-out',
  76. 505 => 'Unsupported Version'
  77. );
  78. /**
  79. * Holds known mime type mappings
  80. *
  81. * @var array
  82. */
  83. protected $_mimeTypes = array(
  84. 'html' => array('text/html', '*/*'),
  85. 'json' => 'application/json',
  86. 'xml' => array('application/xml', 'text/xml'),
  87. 'rss' => 'application/rss+xml',
  88. 'ai' => 'application/postscript',
  89. 'bcpio' => 'application/x-bcpio',
  90. 'bin' => 'application/octet-stream',
  91. 'ccad' => 'application/clariscad',
  92. 'cdf' => 'application/x-netcdf',
  93. 'class' => 'application/octet-stream',
  94. 'cpio' => 'application/x-cpio',
  95. 'cpt' => 'application/mac-compactpro',
  96. 'csh' => 'application/x-csh',
  97. 'csv' => array('text/csv', 'application/vnd.ms-excel'),
  98. 'dcr' => 'application/x-director',
  99. 'dir' => 'application/x-director',
  100. 'dms' => 'application/octet-stream',
  101. 'doc' => 'application/msword',
  102. 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  103. 'drw' => 'application/drafting',
  104. 'dvi' => 'application/x-dvi',
  105. 'dwg' => 'application/acad',
  106. 'dxf' => 'application/dxf',
  107. 'dxr' => 'application/x-director',
  108. 'eot' => 'application/vnd.ms-fontobject',
  109. 'eps' => 'application/postscript',
  110. 'exe' => 'application/octet-stream',
  111. 'ez' => 'application/andrew-inset',
  112. 'flv' => 'video/x-flv',
  113. 'gtar' => 'application/x-gtar',
  114. 'gz' => 'application/x-gzip',
  115. 'bz2' => 'application/x-bzip',
  116. '7z' => 'application/x-7z-compressed',
  117. 'hdf' => 'application/x-hdf',
  118. 'hqx' => 'application/mac-binhex40',
  119. 'ico' => 'image/x-icon',
  120. 'ips' => 'application/x-ipscript',
  121. 'ipx' => 'application/x-ipix',
  122. 'js' => 'application/javascript',
  123. 'latex' => 'application/x-latex',
  124. 'lha' => 'application/octet-stream',
  125. 'lsp' => 'application/x-lisp',
  126. 'lzh' => 'application/octet-stream',
  127. 'man' => 'application/x-troff-man',
  128. 'me' => 'application/x-troff-me',
  129. 'mif' => 'application/vnd.mif',
  130. 'ms' => 'application/x-troff-ms',
  131. 'nc' => 'application/x-netcdf',
  132. 'oda' => 'application/oda',
  133. 'otf' => 'font/otf',
  134. 'pdf' => 'application/pdf',
  135. 'pgn' => 'application/x-chess-pgn',
  136. 'pot' => 'application/vnd.ms-powerpoint',
  137. 'pps' => 'application/vnd.ms-powerpoint',
  138. 'ppt' => 'application/vnd.ms-powerpoint',
  139. 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  140. 'ppz' => 'application/vnd.ms-powerpoint',
  141. 'pre' => 'application/x-freelance',
  142. 'prt' => 'application/pro_eng',
  143. 'ps' => 'application/postscript',
  144. 'roff' => 'application/x-troff',
  145. 'scm' => 'application/x-lotusscreencam',
  146. 'set' => 'application/set',
  147. 'sh' => 'application/x-sh',
  148. 'shar' => 'application/x-shar',
  149. 'sit' => 'application/x-stuffit',
  150. 'skd' => 'application/x-koan',
  151. 'skm' => 'application/x-koan',
  152. 'skp' => 'application/x-koan',
  153. 'skt' => 'application/x-koan',
  154. 'smi' => 'application/smil',
  155. 'smil' => 'application/smil',
  156. 'sol' => 'application/solids',
  157. 'spl' => 'application/x-futuresplash',
  158. 'src' => 'application/x-wais-source',
  159. 'step' => 'application/STEP',
  160. 'stl' => 'application/SLA',
  161. 'stp' => 'application/STEP',
  162. 'sv4cpio' => 'application/x-sv4cpio',
  163. 'sv4crc' => 'application/x-sv4crc',
  164. 'svg' => 'image/svg+xml',
  165. 'svgz' => 'image/svg+xml',
  166. 'swf' => 'application/x-shockwave-flash',
  167. 't' => 'application/x-troff',
  168. 'tar' => 'application/x-tar',
  169. 'tcl' => 'application/x-tcl',
  170. 'tex' => 'application/x-tex',
  171. 'texi' => 'application/x-texinfo',
  172. 'texinfo' => 'application/x-texinfo',
  173. 'tr' => 'application/x-troff',
  174. 'tsp' => 'application/dsptype',
  175. 'ttc' => 'font/ttf',
  176. 'ttf' => 'font/ttf',
  177. 'unv' => 'application/i-deas',
  178. 'ustar' => 'application/x-ustar',
  179. 'vcd' => 'application/x-cdlink',
  180. 'vda' => 'application/vda',
  181. 'xlc' => 'application/vnd.ms-excel',
  182. 'xll' => 'application/vnd.ms-excel',
  183. 'xlm' => 'application/vnd.ms-excel',
  184. 'xls' => 'application/vnd.ms-excel',
  185. 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  186. 'xlw' => 'application/vnd.ms-excel',
  187. 'zip' => 'application/zip',
  188. 'aif' => 'audio/x-aiff',
  189. 'aifc' => 'audio/x-aiff',
  190. 'aiff' => 'audio/x-aiff',
  191. 'au' => 'audio/basic',
  192. 'kar' => 'audio/midi',
  193. 'mid' => 'audio/midi',
  194. 'midi' => 'audio/midi',
  195. 'mp2' => 'audio/mpeg',
  196. 'mp3' => 'audio/mpeg',
  197. 'mpga' => 'audio/mpeg',
  198. 'ogg' => 'audio/ogg',
  199. 'oga' => 'audio/ogg',
  200. 'spx' => 'audio/ogg',
  201. 'ra' => 'audio/x-realaudio',
  202. 'ram' => 'audio/x-pn-realaudio',
  203. 'rm' => 'audio/x-pn-realaudio',
  204. 'rpm' => 'audio/x-pn-realaudio-plugin',
  205. 'snd' => 'audio/basic',
  206. 'tsi' => 'audio/TSP-audio',
  207. 'wav' => 'audio/x-wav',
  208. 'aac' => 'audio/aac',
  209. 'asc' => 'text/plain',
  210. 'c' => 'text/plain',
  211. 'cc' => 'text/plain',
  212. 'css' => 'text/css',
  213. 'etx' => 'text/x-setext',
  214. 'f' => 'text/plain',
  215. 'f90' => 'text/plain',
  216. 'h' => 'text/plain',
  217. 'hh' => 'text/plain',
  218. 'htm' => array('text/html', '*/*'),
  219. 'ics' => 'text/calendar',
  220. 'm' => 'text/plain',
  221. 'rtf' => 'text/rtf',
  222. 'rtx' => 'text/richtext',
  223. 'sgm' => 'text/sgml',
  224. 'sgml' => 'text/sgml',
  225. 'tsv' => 'text/tab-separated-values',
  226. 'tpl' => 'text/template',
  227. 'txt' => 'text/plain',
  228. 'text' => 'text/plain',
  229. 'avi' => 'video/x-msvideo',
  230. 'fli' => 'video/x-fli',
  231. 'mov' => 'video/quicktime',
  232. 'movie' => 'video/x-sgi-movie',
  233. 'mpe' => 'video/mpeg',
  234. 'mpeg' => 'video/mpeg',
  235. 'mpg' => 'video/mpeg',
  236. 'qt' => 'video/quicktime',
  237. 'viv' => 'video/vnd.vivo',
  238. 'vivo' => 'video/vnd.vivo',
  239. 'ogv' => 'video/ogg',
  240. 'webm' => 'video/webm',
  241. 'mp4' => 'video/mp4',
  242. 'm4v' => 'video/mp4',
  243. 'f4v' => 'video/mp4',
  244. 'f4p' => 'video/mp4',
  245. 'm4a' => 'audio/mp4',
  246. 'f4a' => 'audio/mp4',
  247. 'f4b' => 'audio/mp4',
  248. 'gif' => 'image/gif',
  249. 'ief' => 'image/ief',
  250. 'jpg' => 'image/jpeg',
  251. 'jpeg' => 'image/jpeg',
  252. 'jpe' => 'image/jpeg',
  253. 'pbm' => 'image/x-portable-bitmap',
  254. 'pgm' => 'image/x-portable-graymap',
  255. 'png' => 'image/png',
  256. 'pnm' => 'image/x-portable-anymap',
  257. 'ppm' => 'image/x-portable-pixmap',
  258. 'ras' => 'image/cmu-raster',
  259. 'rgb' => 'image/x-rgb',
  260. 'tif' => 'image/tiff',
  261. 'tiff' => 'image/tiff',
  262. 'xbm' => 'image/x-xbitmap',
  263. 'xpm' => 'image/x-xpixmap',
  264. 'xwd' => 'image/x-xwindowdump',
  265. 'ice' => 'x-conference/x-cooltalk',
  266. 'iges' => 'model/iges',
  267. 'igs' => 'model/iges',
  268. 'mesh' => 'model/mesh',
  269. 'msh' => 'model/mesh',
  270. 'silo' => 'model/mesh',
  271. 'vrml' => 'model/vrml',
  272. 'wrl' => 'model/vrml',
  273. 'mime' => 'www/mime',
  274. 'pdb' => 'chemical/x-pdb',
  275. 'xyz' => 'chemical/x-pdb',
  276. 'javascript' => 'application/javascript',
  277. 'form' => 'application/x-www-form-urlencoded',
  278. 'file' => 'multipart/form-data',
  279. 'xhtml' => array('application/xhtml+xml', 'application/xhtml', 'text/xhtml'),
  280. 'xhtml-mobile' => 'application/vnd.wap.xhtml+xml',
  281. 'atom' => 'application/atom+xml',
  282. 'amf' => 'application/x-amf',
  283. 'wap' => array('text/vnd.wap.wml', 'text/vnd.wap.wmlscript', 'image/vnd.wap.wbmp'),
  284. 'wml' => 'text/vnd.wap.wml',
  285. 'wmlscript' => 'text/vnd.wap.wmlscript',
  286. 'wbmp' => 'image/vnd.wap.wbmp',
  287. 'woff' => 'application/x-font-woff',
  288. 'webp' => 'image/webp',
  289. 'appcache' => 'text/cache-manifest',
  290. 'manifest' => 'text/cache-manifest',
  291. 'htc' => 'text/x-component',
  292. 'rdf' => 'application/xml',
  293. 'crx' => 'application/x-chrome-extension',
  294. 'oex' => 'application/x-opera-extension',
  295. 'xpi' => 'application/x-xpinstall',
  296. 'safariextz' => 'application/octet-stream',
  297. 'webapp' => 'application/x-web-app-manifest+json',
  298. 'vcf' => 'text/x-vcard',
  299. 'vtt' => 'text/vtt',
  300. );
  301. /**
  302. * Protocol header to send to the client
  303. *
  304. * @var string
  305. */
  306. protected $_protocol = 'HTTP/1.1';
  307. /**
  308. * Status code to send to the client
  309. *
  310. * @var integer
  311. */
  312. protected $_status = 200;
  313. /**
  314. * Content type to send. This can be an 'extension' that will be transformed using the $_mimetypes array
  315. * or a complete mime-type
  316. *
  317. * @var integer
  318. */
  319. protected $_contentType = 'text/html';
  320. /**
  321. * Buffer list of headers
  322. *
  323. * @var array
  324. */
  325. protected $_headers = array();
  326. /**
  327. * Buffer string for response message
  328. *
  329. * @var string
  330. */
  331. protected $_body = null;
  332. /**
  333. * File object for file to be read out as response
  334. *
  335. * @var File
  336. */
  337. protected $_file = null;
  338. /**
  339. * File range. Used for requesting ranges of files.
  340. *
  341. * @var array
  342. */
  343. protected $_fileRange = null;
  344. /**
  345. * The charset the response body is encoded with
  346. *
  347. * @var string
  348. */
  349. protected $_charset = 'UTF-8';
  350. /**
  351. * Holds all the cache directives that will be converted
  352. * into headers when sending the request
  353. *
  354. * @var string
  355. */
  356. protected $_cacheDirectives = array();
  357. /**
  358. * Holds cookies to be sent to the client
  359. *
  360. * @var array
  361. */
  362. protected $_cookies = array();
  363. /**
  364. * Class constructor
  365. *
  366. * @param array $options list of parameters to setup the response. Possible values are:
  367. * - body: the response text that should be sent to the client
  368. * - status: the HTTP status code to respond with
  369. * - type: a complete mime-type string or an extension mapped in this class
  370. * - charset: the charset for the response body
  371. */
  372. public function __construct(array $options = array()) {
  373. if (isset($options['body'])) {
  374. $this->body($options['body']);
  375. }
  376. if (isset($options['status'])) {
  377. $this->statusCode($options['status']);
  378. }
  379. if (isset($options['type'])) {
  380. $this->type($options['type']);
  381. }
  382. if (!isset($options['charset'])) {
  383. $options['charset'] = Configure::read('App.encoding');
  384. }
  385. $this->charset($options['charset']);
  386. }
  387. /**
  388. * Sends the complete response to the client including headers and message body.
  389. * Will echo out the content in the response body.
  390. *
  391. * @return void
  392. */
  393. public function send() {
  394. if (isset($this->_headers['Location']) && $this->_status === 200) {
  395. $this->statusCode(302);
  396. }
  397. $codeMessage = $this->_statusCodes[$this->_status];
  398. $this->_setCookies();
  399. $this->_sendHeader("{$this->_protocol} {$this->_status} {$codeMessage}");
  400. $this->_setContent();
  401. $this->_setContentLength();
  402. $this->_setContentType();
  403. foreach ($this->_headers as $header => $values) {
  404. foreach ((array)$values as $value) {
  405. $this->_sendHeader($header, $value);
  406. }
  407. }
  408. if ($this->_file) {
  409. $this->_sendFile($this->_file, $this->_fileRange);
  410. $this->_file = $this->_fileRange = null;
  411. } else {
  412. $this->_sendContent($this->_body);
  413. }
  414. }
  415. /**
  416. * Sets the cookies that have been added via static method Cake\Network\Response::addCookie()
  417. * before any other output is sent to the client.
  418. * Will set the cookies in the order they have been set.
  419. *
  420. * @return void
  421. */
  422. protected function _setCookies() {
  423. foreach ($this->_cookies as $name => $c) {
  424. setcookie(
  425. $name, $c['value'], $c['expire'], $c['path'],
  426. $c['domain'], $c['secure'], $c['httpOnly']
  427. );
  428. }
  429. }
  430. /**
  431. * Formats the Content-Type header based on the configured contentType and charset
  432. * the charset will only be set in the header if the response is of type text/*
  433. *
  434. * @return void
  435. */
  436. protected function _setContentType() {
  437. if (in_array($this->_status, array(304, 204))) {
  438. return;
  439. }
  440. $whitelist = array(
  441. 'application/javascript', 'application/json', 'application/xml', 'application/rss+xml'
  442. );
  443. $charset = false;
  444. if (
  445. $this->_charset &&
  446. (strpos($this->_contentType, 'text/') === 0 || in_array($this->_contentType, $whitelist))
  447. ) {
  448. $charset = true;
  449. }
  450. if ($charset) {
  451. $this->header('Content-Type', "{$this->_contentType}; charset={$this->_charset}");
  452. } else {
  453. $this->header('Content-Type', "{$this->_contentType}");
  454. }
  455. }
  456. /**
  457. * Sets the response body to an empty text if the status code is 204 or 304
  458. *
  459. * @return void
  460. */
  461. protected function _setContent() {
  462. if (in_array($this->_status, array(304, 204))) {
  463. $this->body('');
  464. }
  465. }
  466. /**
  467. * Calculates the correct Content-Length and sets it as a header in the response
  468. * Will not set the value if already set or if the output is compressed.
  469. *
  470. * @return void
  471. */
  472. protected function _setContentLength() {
  473. $shouldSetLength = !isset($this->_headers['Content-Length']) && !in_array($this->_status, range(301, 307));
  474. if (isset($this->_headers['Content-Length']) && $this->_headers['Content-Length'] === false) {
  475. unset($this->_headers['Content-Length']);
  476. return;
  477. }
  478. if ($shouldSetLength && !$this->outputCompressed()) {
  479. $offset = ob_get_level() ? ob_get_length() : 0;
  480. if (ini_get('mbstring.func_overload') & 2) {
  481. $this->length($offset + mb_strlen($this->_body, '8bit'));
  482. } else {
  483. $this->length($this->_headers['Content-Length'] = $offset + strlen($this->_body));
  484. }
  485. }
  486. }
  487. /**
  488. * Sends a header to the client.
  489. *
  490. * @param string $name the header name
  491. * @param string $value the header value
  492. * @return void
  493. */
  494. protected function _sendHeader($name, $value = null) {
  495. if (!headers_sent()) {
  496. if ($value === null) {
  497. header($name);
  498. } else {
  499. header("{$name}: {$value}");
  500. }
  501. }
  502. }
  503. /**
  504. * Sends a content string to the client.
  505. *
  506. * @param string $content string to send as response body
  507. * @return void
  508. */
  509. protected function _sendContent($content) {
  510. echo $content;
  511. }
  512. /**
  513. * Buffers a header string to be sent
  514. * Returns the complete list of buffered headers
  515. *
  516. * ### Single header
  517. * e.g `header('Location', 'http://example.com');`
  518. *
  519. * ### Multiple headers
  520. * e.g `header(array('Location' => 'http://example.com', 'X-Extra' => 'My header'));`
  521. *
  522. * ### String header
  523. * e.g `header('WWW-Authenticate: Negotiate');`
  524. *
  525. * ### Array of string headers
  526. * e.g `header(array('WWW-Authenticate: Negotiate', 'Content-type: application/pdf'));`
  527. *
  528. * Multiple calls for setting the same header name will have the same effect as setting the header once
  529. * with the last value sent for it
  530. * e.g `header('WWW-Authenticate: Negotiate'); header('WWW-Authenticate: Not-Negotiate');`
  531. * will have the same effect as only doing `header('WWW-Authenticate: Not-Negotiate');`
  532. *
  533. * @param string|array $header. An array of header strings or a single header string
  534. * - an associative array of "header name" => "header value" is also accepted
  535. * - an array of string headers is also accepted
  536. * @param string|array $value. The header value(s)
  537. * @return array list of headers to be sent
  538. */
  539. public function header($header = null, $value = null) {
  540. if ($header === null) {
  541. return $this->_headers;
  542. }
  543. $headers = is_array($header) ? $header : array($header => $value);
  544. foreach ($headers as $header => $value) {
  545. if (is_numeric($header)) {
  546. list($header, $value) = array($value, null);
  547. }
  548. if ($value === null) {
  549. list($header, $value) = explode(':', $header, 2);
  550. }
  551. $this->_headers[$header] = is_array($value) ? array_map('trim', $value) : trim($value);
  552. }
  553. return $this->_headers;
  554. }
  555. /**
  556. * Acccessor for the location header.
  557. *
  558. * Get/Set the Location header value.
  559. * @param null|string $url Either null to get the current location, or a string to set one.
  560. * @return string|null When setting the location null will be returned. When reading the location
  561. * a string of the current location header value (if any) will be returned.
  562. */
  563. public function location($url = null) {
  564. if ($url === null) {
  565. $headers = $this->header();
  566. return isset($headers['Location']) ? $headers['Location'] : null;
  567. }
  568. $this->header('Location', $url);
  569. }
  570. /**
  571. * Buffers the response message to be sent
  572. * if $content is null the current buffer is returned
  573. *
  574. * @param string $content the string message to be sent
  575. * @return string current message buffer if $content param is passed as null
  576. */
  577. public function body($content = null) {
  578. if ($content === null) {
  579. return $this->_body;
  580. }
  581. return $this->_body = $content;
  582. }
  583. /**
  584. * Sets the HTTP status code to be sent
  585. * if $code is null the current code is returned
  586. *
  587. * @param integer $code the HTTP status code
  588. * @return integer current status code
  589. * @throws Cake\Error\Exception When an unknown status code is reached.
  590. */
  591. public function statusCode($code = null) {
  592. if ($code === null) {
  593. return $this->_status;
  594. }
  595. if (!isset($this->_statusCodes[$code])) {
  596. throw new Error\Exception(__d('cake_dev', 'Unknown status code'));
  597. }
  598. return $this->_status = $code;
  599. }
  600. /**
  601. * Queries & sets valid HTTP response codes & messages.
  602. *
  603. * @param integer|array $code If $code is an integer, then the corresponding code/message is
  604. * returned if it exists, null if it does not exist. If $code is an array, then the
  605. * keys are used as codes and the values as messages to add to the default HTTP
  606. * codes. The codes must be integers greater than 99 and less than 1000. Keep in
  607. * mind that the HTTP specification outlines that status codes begin with a digit
  608. * between 1 and 5, which defines the class of response the client is to expect.
  609. * Example:
  610. *
  611. * httpCodes(404); // returns array(404 => 'Not Found')
  612. *
  613. * httpCodes(array(
  614. * 381 => 'Unicorn Moved',
  615. * 555 => 'Unexpected Minotaur'
  616. * )); // sets these new values, and returns true
  617. *
  618. * httpCodes(array(
  619. * 0 => 'Nothing Here',
  620. * -1 => 'Reverse Infinity',
  621. * 12345 => 'Universal Password',
  622. * 'Hello' => 'World'
  623. * )); // throws an exception due to invalid codes
  624. *
  625. * For more on HTTP status codes see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6.1
  626. *
  627. * @return mixed associative array of the HTTP codes as keys, and the message
  628. * strings as values, or null of the given $code does not exist.
  629. * @throws Cake\Error\Exception If an attempt is made to add an invalid status code
  630. */
  631. public function httpCodes($code = null) {
  632. if (empty($code)) {
  633. return $this->_statusCodes;
  634. }
  635. if (is_array($code)) {
  636. $codes = array_keys($code);
  637. $min = min($codes);
  638. if (!is_int($min) || $min < 100 || max($codes) > 999) {
  639. throw new Error\Exception(__d('cake_dev', 'Invalid status code'));
  640. }
  641. $this->_statusCodes = $code + $this->_statusCodes;
  642. return true;
  643. }
  644. if (!isset($this->_statusCodes[$code])) {
  645. return null;
  646. }
  647. return array($code => $this->_statusCodes[$code]);
  648. }
  649. /**
  650. * Sets the response content type. It can be either a file extension
  651. * which will be mapped internally to a mime-type or a string representing a mime-type
  652. * if $contentType is null the current content type is returned
  653. * if $contentType is an associative array, content type definitions will be stored/replaced
  654. *
  655. * ### Setting the content type
  656. *
  657. * e.g `type('jpg');`
  658. *
  659. * ### Returning the current content type
  660. *
  661. * e.g `type();`
  662. *
  663. * ### Storing content type definitions
  664. *
  665. * e.g `type(array('keynote' => 'application/keynote', 'bat' => 'application/bat'));`
  666. *
  667. * ### Replacing a content type definition
  668. *
  669. * e.g `type(array('jpg' => 'text/plain'));`
  670. *
  671. * @param string $contentType
  672. * @return mixed current content type or false if supplied an invalid content type
  673. */
  674. public function type($contentType = null) {
  675. if ($contentType === null) {
  676. return $this->_contentType;
  677. }
  678. if (is_array($contentType)) {
  679. foreach ($contentType as $type => $definition) {
  680. $this->_mimeTypes[$type] = $definition;
  681. }
  682. return $this->_contentType;
  683. }
  684. if (isset($this->_mimeTypes[$contentType])) {
  685. $contentType = $this->_mimeTypes[$contentType];
  686. $contentType = is_array($contentType) ? current($contentType) : $contentType;
  687. }
  688. if (strpos($contentType, '/') === false) {
  689. return false;
  690. }
  691. return $this->_contentType = $contentType;
  692. }
  693. /**
  694. * Returns the mime type definition for an alias
  695. *
  696. * e.g `getMimeType('pdf'); // returns 'application/pdf'`
  697. *
  698. * @param string $alias the content type alias to map
  699. * @return mixed string mapped mime type or false if $alias is not mapped
  700. */
  701. public function getMimeType($alias) {
  702. if (isset($this->_mimeTypes[$alias])) {
  703. return $this->_mimeTypes[$alias];
  704. }
  705. return false;
  706. }
  707. /**
  708. * Maps a content-type back to an alias
  709. *
  710. * e.g `mapType('application/pdf'); // returns 'pdf'`
  711. *
  712. * @param string|array $ctype Either a string content type to map, or an array of types.
  713. * @return mixed Aliases for the types provided.
  714. */
  715. public function mapType($ctype) {
  716. if (is_array($ctype)) {
  717. return array_map(array($this, 'mapType'), $ctype);
  718. }
  719. foreach ($this->_mimeTypes as $alias => $types) {
  720. if (in_array($ctype, (array)$types)) {
  721. return $alias;
  722. }
  723. }
  724. return null;
  725. }
  726. /**
  727. * Sets the response charset
  728. * if $charset is null the current charset is returned
  729. *
  730. * @param string $charset
  731. * @return string current charset
  732. */
  733. public function charset($charset = null) {
  734. if ($charset === null) {
  735. return $this->_charset;
  736. }
  737. return $this->_charset = $charset;
  738. }
  739. /**
  740. * Sets the correct headers to instruct the client to not cache the response
  741. *
  742. * @return void
  743. */
  744. public function disableCache() {
  745. $this->header(array(
  746. 'Expires' => 'Mon, 26 Jul 1997 05:00:00 GMT',
  747. 'Last-Modified' => gmdate("D, d M Y H:i:s") . " GMT",
  748. 'Cache-Control' => 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0'
  749. ));
  750. }
  751. /**
  752. * Sets the correct headers to instruct the client to cache the response.
  753. *
  754. * @param string $since a valid time since the response text has not been modified
  755. * @param string $time a valid time for cache expiry
  756. * @return void
  757. */
  758. public function cache($since, $time = '+1 day') {
  759. if (!is_int($time)) {
  760. $time = strtotime($time);
  761. }
  762. $this->header(array(
  763. 'Date' => gmdate("D, j M Y G:i:s ", time()) . 'GMT'
  764. ));
  765. $this->modified($since);
  766. $this->expires($time);
  767. $this->sharable(true);
  768. $this->maxAge($time - time());
  769. }
  770. /**
  771. * Sets whether a response is eligible to be cached by intermediate proxies
  772. * This method controls the `public` or `private` directive in the Cache-Control
  773. * header
  774. *
  775. * @param boolean $public If set to true, the Cache-Control header will be set as public
  776. * if set to false, the response will be set to private
  777. * if no value is provided, it will return whether the response is sharable or not
  778. * @param integer $time time in seconds after which the response should no longer be considered fresh
  779. * @return boolean
  780. */
  781. public function sharable($public = null, $time = null) {
  782. if ($public === null) {
  783. $public = array_key_exists('public', $this->_cacheDirectives);
  784. $private = array_key_exists('private', $this->_cacheDirectives);
  785. $noCache = array_key_exists('no-cache', $this->_cacheDirectives);
  786. if (!$public && !$private && !$noCache) {
  787. return null;
  788. }
  789. $sharable = $public || ! ($private || $noCache);
  790. return $sharable;
  791. }
  792. if ($public) {
  793. $this->_cacheDirectives['public'] = true;
  794. unset($this->_cacheDirectives['private']);
  795. $this->sharedMaxAge($time);
  796. } else {
  797. $this->_cacheDirectives['private'] = true;
  798. unset($this->_cacheDirectives['public']);
  799. $this->maxAge($time);
  800. }
  801. if (!$time) {
  802. $this->_setCacheControl();
  803. }
  804. return (bool)$public;
  805. }
  806. /**
  807. * Sets the Cache-Control s-maxage directive.
  808. * The max-age is the number of seconds after which the response should no longer be considered
  809. * a good candidate to be fetched from a shared cache (like in a proxy server).
  810. * If called with no parameters, this function will return the current max-age value if any
  811. *
  812. * @param integer $seconds if null, the method will return the current s-maxage value
  813. * @return integer
  814. */
  815. public function sharedMaxAge($seconds = null) {
  816. if ($seconds !== null) {
  817. $this->_cacheDirectives['s-maxage'] = $seconds;
  818. $this->_setCacheControl();
  819. }
  820. if (isset($this->_cacheDirectives['s-maxage'])) {
  821. return $this->_cacheDirectives['s-maxage'];
  822. }
  823. return null;
  824. }
  825. /**
  826. * Sets the Cache-Control max-age directive.
  827. * The max-age is the number of seconds after which the response should no longer be considered
  828. * a good candidate to be fetched from the local (client) cache.
  829. * If called with no parameters, this function will return the current max-age value if any
  830. *
  831. * @param integer $seconds if null, the method will return the current max-age value
  832. * @return integer
  833. */
  834. public function maxAge($seconds = null) {
  835. if ($seconds !== null) {
  836. $this->_cacheDirectives['max-age'] = $seconds;
  837. $this->_setCacheControl();
  838. }
  839. if (isset($this->_cacheDirectives['max-age'])) {
  840. return $this->_cacheDirectives['max-age'];
  841. }
  842. return null;
  843. }
  844. /**
  845. * Sets the Cache-Control must-revalidate directive.
  846. * must-revalidate indicates that the response should not be served
  847. * stale by a cache under any circumstance without first revalidating
  848. * with the origin.
  849. * If called with no parameters, this function will return whether must-revalidate is present.
  850. *
  851. * @param integer $seconds if null, the method will return the current
  852. * must-revalidate value
  853. * @return boolean
  854. */
  855. public function mustRevalidate($enable = null) {
  856. if ($enable !== null) {
  857. if ($enable) {
  858. $this->_cacheDirectives['must-revalidate'] = true;
  859. } else {
  860. unset($this->_cacheDirectives['must-revalidate']);
  861. }
  862. $this->_setCacheControl();
  863. }
  864. return array_key_exists('must-revalidate', $this->_cacheDirectives);
  865. }
  866. /**
  867. * Helper method to generate a valid Cache-Control header from the options set
  868. * in other methods
  869. *
  870. * @return void
  871. */
  872. protected function _setCacheControl() {
  873. $control = '';
  874. foreach ($this->_cacheDirectives as $key => $val) {
  875. $control .= $val === true ? $key : sprintf('%s=%s', $key, $val);
  876. $control .= ', ';
  877. }
  878. $control = rtrim($control, ', ');
  879. $this->header('Cache-Control', $control);
  880. }
  881. /**
  882. * Sets the Expires header for the response by taking an expiration time
  883. * If called with no parameters it will return the current Expires value
  884. *
  885. * ## Examples:
  886. *
  887. * `$response->expires('now')` Will Expire the response cache now
  888. * `$response->expires(new DateTime('+1 day'))` Will set the expiration in next 24 hours
  889. * `$response->expires()` Will return the current expiration header value
  890. *
  891. * @param string|DateTime $time
  892. * @return string
  893. */
  894. public function expires($time = null) {
  895. if ($time !== null) {
  896. $date = $this->_getUTCDate($time);
  897. $this->_headers['Expires'] = $date->format('D, j M Y H:i:s') . ' GMT';
  898. }
  899. if (isset($this->_headers['Expires'])) {
  900. return $this->_headers['Expires'];
  901. }
  902. return null;
  903. }
  904. /**
  905. * Sets the Last-Modified header for the response by taking an modification time
  906. * If called with no parameters it will return the current Last-Modified value
  907. *
  908. * ## Examples:
  909. *
  910. * `$response->modified('now')` Will set the Last-Modified to the current time
  911. * `$response->modified(new DateTime('+1 day'))` Will set the modification date in the past 24 hours
  912. * `$response->modified()` Will return the current Last-Modified header value
  913. *
  914. * @param string|DateTime $time
  915. * @return string
  916. */
  917. public function modified($time = null) {
  918. if ($time !== null) {
  919. $date = $this->_getUTCDate($time);
  920. $this->_headers['Last-Modified'] = $date->format('D, j M Y H:i:s') . ' GMT';
  921. }
  922. if (isset($this->_headers['Last-Modified'])) {
  923. return $this->_headers['Last-Modified'];
  924. }
  925. return null;
  926. }
  927. /**
  928. * Sets the response as Not Modified by removing any body contents
  929. * setting the status code to "304 Not Modified" and removing all
  930. * conflicting headers
  931. *
  932. * @return void
  933. */
  934. public function notModified() {
  935. $this->statusCode(304);
  936. $this->body('');
  937. $remove = array(
  938. 'Allow',
  939. 'Content-Encoding',
  940. 'Content-Language',
  941. 'Content-Length',
  942. 'Content-MD5',
  943. 'Content-Type',
  944. 'Last-Modified'
  945. );
  946. foreach ($remove as $header) {
  947. unset($this->_headers[$header]);
  948. }
  949. }
  950. /**
  951. * Sets the Vary header for the response, if an array is passed,
  952. * values will be imploded into a comma separated string. If no
  953. * parameters are passed, then an array with the current Vary header
  954. * value is returned
  955. *
  956. * @param string|array $cacheVariances a single Vary string or a array
  957. * containing the list for variances.
  958. * @return array
  959. */
  960. public function vary($cacheVariances = null) {
  961. if ($cacheVariances !== null) {
  962. $cacheVariances = (array)$cacheVariances;
  963. $this->_headers['Vary'] = implode(', ', $cacheVariances);
  964. }
  965. if (isset($this->_headers['Vary'])) {
  966. return explode(', ', $this->_headers['Vary']);
  967. }
  968. return null;
  969. }
  970. /**
  971. * Sets the response Etag, Etags are a strong indicative that a response
  972. * can be cached by a HTTP client. A bad way of generating Etags is
  973. * creating a hash of the response output, instead generate a unique
  974. * hash of the unique components that identifies a request, such as a
  975. * modification time, a resource Id, and anything else you consider it
  976. * makes it unique.
  977. *
  978. * Second parameter is used to instruct clients that the content has
  979. * changed, but sematicallly, it can be used as the same thing. Think
  980. * for instance of a page with a hit counter, two different page views
  981. * are equivalent, but they differ by a few bytes. This leaves off to
  982. * the Client the decision of using or not the cached page.
  983. *
  984. * If no parameters are passed, current Etag header is returned.
  985. *
  986. * @param string $hash the unique has that identifies this response
  987. * @param boolean $weak whether the response is semantically the same as
  988. * other with the same hash or not
  989. * @return string
  990. */
  991. public function etag($tag = null, $weak = false) {
  992. if ($tag !== null) {
  993. $this->_headers['Etag'] = sprintf('%s"%s"', ($weak) ? 'W/' : null, $tag);
  994. }
  995. if (isset($this->_headers['Etag'])) {
  996. return $this->_headers['Etag'];
  997. }
  998. return null;
  999. }
  1000. /**
  1001. * Returns a DateTime object initialized at the $time param and using UTC
  1002. * as timezone
  1003. *
  1004. * @param string|integer|DateTime $time
  1005. * @return DateTime
  1006. */
  1007. protected function _getUTCDate($time = null) {
  1008. if ($time instanceof \DateTime) {
  1009. $result = clone $time;
  1010. } elseif (is_int($time)) {
  1011. $result = new \DateTime(date('Y-m-d H:i:s', $time));
  1012. } else {
  1013. $result = new \DateTime($time);
  1014. }
  1015. $result->setTimeZone(new \DateTimeZone('UTC'));
  1016. return $result;
  1017. }
  1018. /**
  1019. * Sets the correct output buffering handler to send a compressed response. Responses will
  1020. * be compressed with zlib, if the extension is available.
  1021. *
  1022. * @return boolean false if client does not accept compressed responses or no handler is available, true otherwise
  1023. */
  1024. public function compress() {
  1025. $compressionEnabled = ini_get("zlib.output_compression") !== '1' &&
  1026. extension_loaded("zlib") &&
  1027. (strpos(env('HTTP_ACCEPT_ENCODING'), 'gzip') !== false);
  1028. return $compressionEnabled && ob_start('ob_gzhandler');
  1029. }
  1030. /**
  1031. * Returns whether the resulting output will be compressed by PHP
  1032. *
  1033. * @return boolean
  1034. */
  1035. public function outputCompressed() {
  1036. return strpos(env('HTTP_ACCEPT_ENCODING'), 'gzip') !== false
  1037. && (ini_get("zlib.output_compression") === '1' || in_array('ob_gzhandler', ob_list_handlers()));
  1038. }
  1039. /**
  1040. * Sets the correct headers to instruct the browser to download the response as a file.
  1041. *
  1042. * @param string $filename the name of the file as the browser will download the response
  1043. * @return void
  1044. */
  1045. public function download($filename) {
  1046. $this->header('Content-Disposition', 'attachment; filename="' . $filename . '"');
  1047. }
  1048. /**
  1049. * Sets the protocol to be used when sending the response. Defaults to HTTP/1.1
  1050. * If called with no arguments, it will return the current configured protocol
  1051. *
  1052. * @param string protocol to be used for sending response
  1053. * @return string protocol currently set
  1054. */
  1055. public function protocol($protocol = null) {
  1056. if ($protocol !== null) {
  1057. $this->_protocol = $protocol;
  1058. }
  1059. return $this->_protocol;
  1060. }
  1061. /**
  1062. * Sets the Content-Length header for the response
  1063. * If called with no arguments returns the last Content-Length set
  1064. *
  1065. * @param integer $bytes Number of bytes
  1066. * @return integer|null
  1067. */
  1068. public function length($bytes = null) {
  1069. if ($bytes !== null) {
  1070. $this->_headers['Content-Length'] = $bytes;
  1071. }
  1072. if (isset($this->_headers['Content-Length'])) {
  1073. return $this->_headers['Content-Length'];
  1074. }
  1075. return null;
  1076. }
  1077. /**
  1078. * Checks whether a response has not been modified according to the 'If-None-Match'
  1079. * (Etags) and 'If-Modified-Since' (last modification date) request
  1080. * headers headers. If the response is detected to be not modified, it
  1081. * is marked as so accordingly so the client can be informed of that.
  1082. *
  1083. * In order to mark a response as not modified, you need to set at least
  1084. * the Last-Modified etag response header before calling this method. Otherwise
  1085. * a comparison will not be possible.
  1086. *
  1087. * @param CakeRequest $request Request object
  1088. * @return boolean whether the response was marked as not modified or not.
  1089. */
  1090. public function checkNotModified(Request $request) {
  1091. $etags = preg_split('/\s*,\s*/', $request->header('If-None-Match'), null, PREG_SPLIT_NO_EMPTY);
  1092. $modifiedSince = $request->header('If-Modified-Since');
  1093. if ($responseTag = $this->etag()) {
  1094. $etagMatches = in_array('*', $etags) || in_array($responseTag, $etags);
  1095. }
  1096. if ($modifiedSince) {
  1097. $timeMatches = strtotime($this->modified()) == strtotime($modifiedSince);
  1098. }
  1099. $checks = compact('etagMatches', 'timeMatches');
  1100. if (empty($checks)) {
  1101. return false;
  1102. }
  1103. $notModified = !in_array(false, $checks, true);
  1104. if ($notModified) {
  1105. $this->notModified();
  1106. }
  1107. return $notModified;
  1108. }
  1109. /**
  1110. * String conversion. Fetches the response body as a string.
  1111. * Does *not* send headers.
  1112. *
  1113. * @return string
  1114. */
  1115. public function __toString() {
  1116. return (string)$this->_body;
  1117. }
  1118. /**
  1119. * Getter/Setter for cookie configs
  1120. *
  1121. * This method acts as a setter/getter depending on the type of the argument.
  1122. * If the method is called with no arguments, it returns all configurations.
  1123. *
  1124. * If the method is called with a string as argument, it returns either the
  1125. * given configuration if it is set, or null, if it's not set.
  1126. *
  1127. * If the method is called with an array as argument, it will set the cookie
  1128. * configuration to the cookie container.
  1129. *
  1130. * @param array $options Either null to get all cookies, string for a specific cookie
  1131. * or array to set cookie.
  1132. *
  1133. * ### Options (when setting a configuration)
  1134. * - name: The Cookie name
  1135. * - value: Value of the cookie
  1136. * - expire: Time the cookie expires in
  1137. * - path: Path the cookie applies to
  1138. * - domain: Domain the cookie is for.
  1139. * - secure: Is the cookie https?
  1140. * - httpOnly: Is the cookie available in the client?
  1141. *
  1142. * ## Examples
  1143. *
  1144. * ### Getting all cookies
  1145. *
  1146. * `$this->cookie()`
  1147. *
  1148. * ### Getting a certain cookie configuration
  1149. *
  1150. * `$this->cookie('MyCookie')`
  1151. *
  1152. * ### Setting a cookie configuration
  1153. *
  1154. * `$this->cookie((array) $options)`
  1155. *
  1156. * @return mixed
  1157. */
  1158. public function cookie($options = null) {
  1159. if ($options === null) {
  1160. return $this->_cookies;
  1161. }
  1162. if (is_string($options)) {
  1163. if (!isset($this->_cookies[$options])) {
  1164. return null;
  1165. }
  1166. return $this->_cookies[$options];
  1167. }
  1168. $defaults = array(
  1169. 'name' => 'CakeCookie[default]',
  1170. 'value' => '',
  1171. 'expire' => 0,
  1172. 'path' => '/',
  1173. 'domain' => '',
  1174. 'secure' => false,
  1175. 'httpOnly' => false
  1176. );
  1177. $options += $defaults;
  1178. $this->_cookies[$options['name']] = $options;
  1179. }
  1180. /**
  1181. * Setup for display or download the given file.
  1182. *
  1183. * If $_SERVER['HTTP_RANGE'] is set a slice of the file will be
  1184. * returned instead of the entire file.
  1185. *
  1186. * ### Options keys
  1187. *
  1188. * - name: Alternate download name
  1189. * - download: If `true` sets download header and forces file to be downloaded rather than displayed in browser
  1190. *
  1191. * @param string $path Path to file
  1192. * @param array $options Options See above.
  1193. * @return void
  1194. * @throws Cake\Error\NotFoundException
  1195. */
  1196. public function file($path, $options = array()) {
  1197. $options += array(
  1198. 'name' => null,
  1199. 'download' => null
  1200. );
  1201. if (!is_file($path)) {
  1202. $path = APP . $path;
  1203. }
  1204. $file = new File($path);
  1205. if (!$file->exists() || !$file->readable()) {
  1206. if (Configure::read('debug')) {
  1207. throw new Error\NotFoundException(__d('cake_dev', 'The requested file %s was not found or not readable', $path));
  1208. }
  1209. throw new Error\NotFoundException(__d('cake', 'The requested file was not found'));
  1210. }
  1211. $extension = strtolower($file->ext());
  1212. $download = $options['download'];
  1213. if ((!$extension || $this->type($extension) === false) && $download === null) {
  1214. $download = true;
  1215. }
  1216. $fileSize = $file->size();
  1217. if ($download) {
  1218. $agent = env('HTTP_USER_AGENT');
  1219. if (preg_match('%Opera(/| )([0-9].[0-9]{1,2})%', $agent)) {
  1220. $contentType = 'application/octetstream';
  1221. } elseif (preg_match('/MSIE ([0-9].[0-9]{1,2})/', $agent)) {
  1222. $contentType = 'application/force-download';
  1223. }
  1224. if (!empty($contentType)) {
  1225. $this->type($contentType);
  1226. }
  1227. if ($options['name'] === null) {
  1228. $name = $file->name;
  1229. } else {
  1230. $name = $options['name'];
  1231. }
  1232. $this->download($name);
  1233. $this->header('Accept-Ranges', 'bytes');
  1234. $httpRange = env('HTTP_RANGE');
  1235. if (isset($httpRange)) {
  1236. $this->_fileRange($file, $httpRange);
  1237. } else {
  1238. $this->header('Content-Length', $fileSize);
  1239. }
  1240. } else {
  1241. $this->header('Content-Length', $fileSize);
  1242. }
  1243. $this->_clearBuffer();
  1244. $this->_file = $file;
  1245. }
  1246. /**
  1247. * Apply a file range to a file and set the end offset.
  1248. *
  1249. * If an invalid range is requested a 416 Status code will be used
  1250. * in the response.
  1251. *
  1252. * @param File $file The file to set a range on.
  1253. * @param string $httpRange The range to use.
  1254. * @return void
  1255. */
  1256. protected function _fileRange($file, $httpRange) {
  1257. list(, $range) = explode('=', $httpRange);
  1258. list($start, $end) = explode('-', $range);
  1259. $fileSize = $file->size();
  1260. $lastByte = $fileSize - 1;
  1261. if ($start === '') {
  1262. $start = $fileSize - $end;
  1263. $end = $lastByte;
  1264. }
  1265. if ($end === '') {
  1266. $end = $lastByte;
  1267. }
  1268. if ($start > $end || $end > $lastByte || $start > $lastByte) {
  1269. $this->statusCode(416);
  1270. $this->header(array(
  1271. 'Content-Range' => 'bytes 0-' . $lastByte . '/' . $fileSize
  1272. ));
  1273. return;
  1274. }
  1275. $this->header(array(
  1276. 'Content-Length' => $end - $start + 1,
  1277. 'Content-Range' => 'bytes ' . $start . '-' . $end . '/' . $fileSize
  1278. ));
  1279. $this->statusCode(206);
  1280. $this->_fileRange = array($start, $end);
  1281. }
  1282. /**
  1283. * Reads out a file, and echos the content to the client.
  1284. *
  1285. * @param File $file File object
  1286. * @param array $range The range to read out of the file.
  1287. * @return boolean True is whole file is echoed successfully or false if client connection is lost in between
  1288. */
  1289. protected function _sendFile($file, $range) {
  1290. $compress = $this->outputCompressed();
  1291. $file->open('rb');
  1292. $end = $start = false;
  1293. if ($range) {
  1294. list($start, $end) = $range;
  1295. }
  1296. if ($start !== false) {
  1297. $file->offset($start);
  1298. }
  1299. $bufferSize = 8192;
  1300. set_time_limit(0);
  1301. while (!feof($file->handle)) {
  1302. if (!$this->_isActive()) {
  1303. $file->close();
  1304. return false;
  1305. }
  1306. $offset = $file->offset();
  1307. if ($end && $offset >= $end) {
  1308. break;
  1309. }
  1310. if ($end && $offset + $bufferSize >= $end) {
  1311. $bufferSize = $end - $offset + 1;
  1312. }
  1313. echo fread($file->handle, $bufferSize);
  1314. if (!$compress) {
  1315. $this->_flushBuffer();
  1316. }
  1317. }
  1318. $file->close();
  1319. return true;
  1320. }
  1321. /**
  1322. * Returns true if connection is still active
  1323. *
  1324. * @return boolean
  1325. */
  1326. protected function _isActive() {
  1327. return connection_status() === CONNECTION_NORMAL && !connection_aborted();
  1328. }
  1329. /**
  1330. * Clears the contents of the topmost output buffer and discards them
  1331. *
  1332. * @return boolean
  1333. */
  1334. protected function _clearBuffer() {
  1335. //@codingStandardsIgnoreStart
  1336. return @ob_end_clean();
  1337. //@codingStandardsIgnoreEnd
  1338. }
  1339. /**
  1340. * Flushes the contents of the output buffer
  1341. *
  1342. * @return void
  1343. */
  1344. protected function _flushBuffer() {
  1345. //@codingStandardsIgnoreStart
  1346. @flush();
  1347. @ob_flush();
  1348. //@codingStandardsIgnoreEnd
  1349. }
  1350. }