Base for a static organization website

CakeResponse.php 44KB

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