Namespaces

  • Latte
    • Loaders
    • Macros
    • Runtime
  • Nette
    • Application
      • Responses
      • Routers
      • UI
    • Bridges
      • ApplicationLatte
      • ApplicationTracy
      • CacheLatte
      • DatabaseDI
      • DatabaseTracy
      • DITracy
      • FormsLatte
      • Framework
      • HttpTracy
      • SecurityTracy
    • Caching
      • Storages
    • ComponentModel
    • Database
      • Drivers
      • Reflection
      • Table
    • DI
      • Config
        • Adapters
      • Extensions
    • Diagnostics
    • Forms
      • Controls
      • Rendering
    • Http
    • Iterators
    • Latte
    • Loaders
    • Localization
    • Mail
    • Neon
    • PhpGenerator
    • Reflection
    • Security
    • Templating
    • Utils
  • NetteModule
  • none
  • Tracy

Classes

  • Context
  • FileUpload
  • Helpers
  • Request
  • RequestFactory
  • Response
  • Session
  • SessionSection
  • Url
  • UrlScript
  • UserStorage

Interfaces

  • IRequest
  • IResponse
  • ISessionStorage
  • Overview
  • Namespace
  • Class
  • Tree
  • Deprecated
  1: <?php
  2: 
  3: /**
  4:  * This file is part of the Nette Framework (http://nette.org)
  5:  * Copyright (c) 2004 David Grudl (http://davidgrudl.com)
  6:  */
  7: 
  8: namespace Nette\Http;
  9: 
 10: use Nette,
 11:     Nette\Utils\DateTime;
 12: 
 13: 
 14: /**
 15:  * HttpResponse class.
 16:  *
 17:  * @author     David Grudl
 18:  *
 19:  * @property   int $code
 20:  * @property-read bool $sent
 21:  * @property-read array $headers
 22:  */
 23: class Response extends Nette\Object implements IResponse
 24: {
 25:     /** @var bool  Send invisible garbage for IE 6? */
 26:     private static $fixIE = TRUE;
 27: 
 28:     /** @var string The domain in which the cookie will be available */
 29:     public $cookieDomain = '';
 30: 
 31:     /** @var string The path in which the cookie will be available */
 32:     public $cookiePath = '/';
 33: 
 34:     /** @var string Whether the cookie is available only through HTTPS */
 35:     public $cookieSecure = FALSE;
 36: 
 37:     /** @var string Whether the cookie is hidden from client-side */
 38:     public $cookieHttpOnly = TRUE;
 39: 
 40:     /** @var bool Whether warn on possible problem with data in output buffer */
 41:     public $warnOnBuffer = TRUE;
 42: 
 43:     /** @var int HTTP response code */
 44:     private $code = self::S200_OK;
 45: 
 46: 
 47:     public function __construct()
 48:     {
 49:         if (PHP_VERSION_ID >= 50400) {
 50:             if (is_int($code = http_response_code())) {
 51:                 $this->code = $code;
 52:             }
 53:         }
 54: 
 55:         if (PHP_VERSION_ID >= 50401) { // PHP bug #61106
 56:             header_register_callback($this->removeDuplicateCookies); // requires closure due PHP bug #66375
 57:         }
 58:     }
 59: 
 60: 
 61:     /**
 62:      * Sets HTTP response code.
 63:      * @param  int
 64:      * @return self
 65:      * @throws Nette\InvalidArgumentException  if code is invalid
 66:      * @throws Nette\InvalidStateException  if HTTP headers have been sent
 67:      */
 68:     public function setCode($code)
 69:     {
 70:         $code = (int) $code;
 71:         if ($code < 100 || $code > 599) {
 72:             throw new Nette\InvalidArgumentException("Bad HTTP response '$code'.");
 73:         }
 74:         self::checkHeaders();
 75:         $this->code = $code;
 76:         $protocol = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1';
 77:         header($protocol . ' ' . $code, TRUE, $code);
 78:         return $this;
 79:     }
 80: 
 81: 
 82:     /**
 83:      * Returns HTTP response code.
 84:      * @return int
 85:      */
 86:     public function getCode()
 87:     {
 88:         return $this->code;
 89:     }
 90: 
 91: 
 92:     /**
 93:      * Sends a HTTP header and replaces a previous one.
 94:      * @param  string  header name
 95:      * @param  string  header value
 96:      * @return self
 97:      * @throws Nette\InvalidStateException  if HTTP headers have been sent
 98:      */
 99:     public function setHeader($name, $value)
100:     {
101:         self::checkHeaders();
102:         if ($value === NULL) {
103:             header_remove($name);
104:         } elseif (strcasecmp($name, 'Content-Length') === 0 && ini_get('zlib.output_compression')) {
105:             // ignore, PHP bug #44164
106:         } else {
107:             header($name . ': ' . $value, TRUE, $this->code);
108:         }
109:         return $this;
110:     }
111: 
112: 
113:     /**
114:      * Adds HTTP header.
115:      * @param  string  header name
116:      * @param  string  header value
117:      * @return self
118:      * @throws Nette\InvalidStateException  if HTTP headers have been sent
119:      */
120:     public function addHeader($name, $value)
121:     {
122:         self::checkHeaders();
123:         header($name . ': ' . $value, FALSE, $this->code);
124:         return $this;
125:     }
126: 
127: 
128:     /**
129:      * Sends a Content-type HTTP header.
130:      * @param  string  mime-type
131:      * @param  string  charset
132:      * @return self
133:      * @throws Nette\InvalidStateException  if HTTP headers have been sent
134:      */
135:     public function setContentType($type, $charset = NULL)
136:     {
137:         $this->setHeader('Content-Type', $type . ($charset ? '; charset=' . $charset : ''));
138:         return $this;
139:     }
140: 
141: 
142:     /**
143:      * Redirects to a new URL. Note: call exit() after it.
144:      * @param  string  URL
145:      * @param  int     HTTP code
146:      * @return void
147:      * @throws Nette\InvalidStateException  if HTTP headers have been sent
148:      */
149:     public function redirect($url, $code = self::S302_FOUND)
150:     {
151:         $this->setCode($code);
152:         $this->setHeader('Location', $url);
153:         if (preg_match('#^https?:|^\s*+[a-z0-9+.-]*+[^:]#i', $url)) {
154:             $escapedUrl = htmlSpecialChars($url, ENT_IGNORE | ENT_QUOTES);
155:             echo "<h1>Redirect</h1>\n\n<p><a href=\"$escapedUrl\">Please click here to continue</a>.</p>";
156:         }
157:     }
158: 
159: 
160:     /**
161:      * Sets the number of seconds before a page cached on a browser expires.
162:      * @param  string|int|\DateTime  time, value 0 means "until the browser is closed"
163:      * @return self
164:      * @throws Nette\InvalidStateException  if HTTP headers have been sent
165:      */
166:     public function setExpiration($time)
167:     {
168:         if (!$time) { // no cache
169:             $this->setHeader('Cache-Control', 's-maxage=0, max-age=0, must-revalidate');
170:             $this->setHeader('Expires', 'Mon, 23 Jan 1978 10:00:00 GMT');
171:             return $this;
172:         }
173: 
174:         $time = DateTime::from($time);
175:         $this->setHeader('Cache-Control', 'max-age=' . ($time->format('U') - time()));
176:         $this->setHeader('Expires', self::date($time));
177:         return $this;
178:     }
179: 
180: 
181:     /**
182:      * Checks if headers have been sent.
183:      * @return bool
184:      */
185:     public function isSent()
186:     {
187:         return headers_sent();
188:     }
189: 
190: 
191:     /**
192:      * Returns value of an HTTP header.
193:      * @param  string
194:      * @param  mixed
195:      * @return mixed
196:      */
197:     public function getHeader($header, $default = NULL)
198:     {
199:         $header .= ':';
200:         $len = strlen($header);
201:         foreach (headers_list() as $item) {
202:             if (strncasecmp($item, $header, $len) === 0) {
203:                 return ltrim(substr($item, $len));
204:             }
205:         }
206:         return $default;
207:     }
208: 
209: 
210:     /**
211:      * Returns a list of headers to sent.
212:      * @return array (name => value)
213:      */
214:     public function getHeaders()
215:     {
216:         $headers = array();
217:         foreach (headers_list() as $header) {
218:             $a = strpos($header, ':');
219:             $headers[substr($header, 0, $a)] = (string) substr($header, $a + 2);
220:         }
221:         return $headers;
222:     }
223: 
224: 
225:     /**
226:      * Returns HTTP valid date format.
227:      * @param  string|int|DateTime
228:      * @return string
229:      */
230:     public static function date($time = NULL)
231:     {
232:         $time = DateTime::from($time);
233:         $time->setTimezone(new \DateTimeZone('GMT'));
234:         return $time->format('D, d M Y H:i:s \G\M\T');
235:     }
236: 
237: 
238:     /**
239:      * @return void
240:      */
241:     public function __destruct()
242:     {
243:         if (self::$fixIE && isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE ') !== FALSE
244:             && in_array($this->code, array(400, 403, 404, 405, 406, 408, 409, 410, 500, 501, 505), TRUE)
245:             && preg_match('#^text/html(?:;|$)#', $this->getHeader('Content-Type', 'text/html'))
246:         ) {
247:             echo Nette\Utils\Random::generate(2e3, " \t\r\n"); // sends invisible garbage for IE
248:             self::$fixIE = FALSE;
249:         }
250:     }
251: 
252: 
253:     /**
254:      * Sends a cookie.
255:      * @param  string name of the cookie
256:      * @param  string value
257:      * @param  string|int|\DateTime  expiration time, value 0 means "until the browser is closed"
258:      * @param  string
259:      * @param  string
260:      * @param  bool
261:      * @param  bool
262:      * @return self
263:      * @throws Nette\InvalidStateException  if HTTP headers have been sent
264:      */
265:     public function setCookie($name, $value, $time, $path = NULL, $domain = NULL, $secure = NULL, $httpOnly = NULL)
266:     {
267:         self::checkHeaders();
268:         setcookie(
269:             $name,
270:             $value,
271:             $time ? DateTime::from($time)->format('U') : 0,
272:             $path === NULL ? $this->cookiePath : (string) $path,
273:             $domain === NULL ? $this->cookieDomain : (string) $domain,
274:             $secure === NULL ? $this->cookieSecure : (bool) $secure,
275:             $httpOnly === NULL ? $this->cookieHttpOnly : (bool) $httpOnly
276:         );
277:         $this->removeDuplicateCookies();
278:         return $this;
279:     }
280: 
281: 
282:     /**
283:      * Deletes a cookie.
284:      * @param  string name of the cookie.
285:      * @param  string
286:      * @param  string
287:      * @param  bool
288:      * @return void
289:      * @throws Nette\InvalidStateException  if HTTP headers have been sent
290:      */
291:     public function deleteCookie($name, $path = NULL, $domain = NULL, $secure = NULL)
292:     {
293:         $this->setCookie($name, FALSE, 0, $path, $domain, $secure);
294:     }
295: 
296: 
297:     /**
298:      * Removes duplicate cookies from response.
299:      * @return void
300:      * @internal
301:      */
302:     public function removeDuplicateCookies()
303:     {
304:         if (headers_sent($file, $line) || ini_get('suhosin.cookie.encrypt')) {
305:             return;
306:         }
307: 
308:         $flatten = array();
309:         foreach (headers_list() as $header) {
310:             if (preg_match('#^Set-Cookie: .+?=#', $header, $m)) {
311:                 $flatten[$m[0]] = $header;
312:                 header_remove('Set-Cookie');
313:             }
314:         }
315:         foreach (array_values($flatten) as $key => $header) {
316:             header($header, $key === 0);
317:         }
318:     }
319: 
320: 
321:     private function checkHeaders()
322:     {
323:         if (headers_sent($file, $line)) {
324:             throw new Nette\InvalidStateException('Cannot send header after HTTP headers have been sent' . ($file ? " (output started at $file:$line)." : '.'));
325: 
326:         } elseif ($this->warnOnBuffer && ob_get_length() && !array_filter(ob_get_status(TRUE), function($i) { return !$i['chunk_size']; })) {
327:             trigger_error('Possible problem: you are sending a HTTP header while already having some data in output buffer. Try Tracy\OutputDebugger or start session earlier.', E_USER_NOTICE);
328:         }
329:     }
330: 
331: }
332: 
Nette 2.2.6 API API documentation generated by ApiGen 2.8.0