CakePHP
  • Documentation
    • Book
    • API
    • Videos
    • Reporting Security Issues
    • Privacy Policy
    • Logos & Trademarks
  • Business Solutions
  • Swag
  • Road Trip
  • Team
  • Community
    • Community
    • Get Involved
    • Issues (GitHub)
    • Bakery
    • Featured Resources
    • Training
    • Meetups
    • My CakePHP
    • CakeFest
    • Newsletter
    • Linkedin
    • YouTube
    • Facebook
    • Twitter
    • Mastodon
    • Help & Support
    • Forum
    • Stack Overflow
    • Slack
    • Paid Support
CakePHP

C CakePHP 2.1 API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.1
      • 4.2
      • 4.1
      • 4.0
      • 3.9
      • 3.8
      • 3.7
      • 3.6
      • 3.5
      • 3.4
      • 3.3
      • 3.2
      • 3.1
      • 3.0
      • 2.10
      • 2.9
      • 2.8
      • 2.7
      • 2.6
      • 2.5
      • 2.4
      • 2.3
      • 2.2
      • 2.1
      • 2.0
      • 1.3
      • 1.2

Packages

  • Cake
    • Cache
      • Engine
    • Configure
    • Console
      • Command
        • Task
    • Controller
      • Component
        • Acl
        • Auth
    • Core
    • Error
    • Event
    • I18n
    • Log
      • Engine
    • Model
      • Behavior
      • Datasource
        • Database
        • Session
    • Network
      • Email
      • Http
    • Routing
      • Route
    • TestSuite
      • Coverage
      • Fixture
      • Reporter
    • Utility
    • View
      • Helper

Classes

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

Generated using CakePHP API Docs