菜谱项目

Response.php 37KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpFoundation;
  11. /**
  12. * Response represents an HTTP response.
  13. *
  14. * @author Fabien Potencier <fabien@symfony.com>
  15. */
  16. class Response
  17. {
  18. const HTTP_CONTINUE = 100;
  19. const HTTP_SWITCHING_PROTOCOLS = 101;
  20. const HTTP_PROCESSING = 102; // RFC2518
  21. const HTTP_OK = 200;
  22. const HTTP_CREATED = 201;
  23. const HTTP_ACCEPTED = 202;
  24. const HTTP_NON_AUTHORITATIVE_INFORMATION = 203;
  25. const HTTP_NO_CONTENT = 204;
  26. const HTTP_RESET_CONTENT = 205;
  27. const HTTP_PARTIAL_CONTENT = 206;
  28. const HTTP_MULTI_STATUS = 207; // RFC4918
  29. const HTTP_ALREADY_REPORTED = 208; // RFC5842
  30. const HTTP_IM_USED = 226; // RFC3229
  31. const HTTP_MULTIPLE_CHOICES = 300;
  32. const HTTP_MOVED_PERMANENTLY = 301;
  33. const HTTP_FOUND = 302;
  34. const HTTP_SEE_OTHER = 303;
  35. const HTTP_NOT_MODIFIED = 304;
  36. const HTTP_USE_PROXY = 305;
  37. const HTTP_RESERVED = 306;
  38. const HTTP_TEMPORARY_REDIRECT = 307;
  39. const HTTP_PERMANENTLY_REDIRECT = 308; // RFC7238
  40. const HTTP_BAD_REQUEST = 400;
  41. const HTTP_UNAUTHORIZED = 401;
  42. const HTTP_PAYMENT_REQUIRED = 402;
  43. const HTTP_FORBIDDEN = 403;
  44. const HTTP_NOT_FOUND = 404;
  45. const HTTP_METHOD_NOT_ALLOWED = 405;
  46. const HTTP_NOT_ACCEPTABLE = 406;
  47. const HTTP_PROXY_AUTHENTICATION_REQUIRED = 407;
  48. const HTTP_REQUEST_TIMEOUT = 408;
  49. const HTTP_CONFLICT = 409;
  50. const HTTP_GONE = 410;
  51. const HTTP_LENGTH_REQUIRED = 411;
  52. const HTTP_PRECONDITION_FAILED = 412;
  53. const HTTP_REQUEST_ENTITY_TOO_LARGE = 413;
  54. const HTTP_REQUEST_URI_TOO_LONG = 414;
  55. const HTTP_UNSUPPORTED_MEDIA_TYPE = 415;
  56. const HTTP_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
  57. const HTTP_EXPECTATION_FAILED = 417;
  58. const HTTP_I_AM_A_TEAPOT = 418; // RFC2324
  59. const HTTP_MISDIRECTED_REQUEST = 421; // RFC7540
  60. const HTTP_UNPROCESSABLE_ENTITY = 422; // RFC4918
  61. const HTTP_LOCKED = 423; // RFC4918
  62. const HTTP_FAILED_DEPENDENCY = 424; // RFC4918
  63. const HTTP_RESERVED_FOR_WEBDAV_ADVANCED_COLLECTIONS_EXPIRED_PROPOSAL = 425; // RFC2817
  64. const HTTP_UPGRADE_REQUIRED = 426; // RFC2817
  65. const HTTP_PRECONDITION_REQUIRED = 428; // RFC6585
  66. const HTTP_TOO_MANY_REQUESTS = 429; // RFC6585
  67. const HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE = 431; // RFC6585
  68. const HTTP_UNAVAILABLE_FOR_LEGAL_REASONS = 451;
  69. const HTTP_INTERNAL_SERVER_ERROR = 500;
  70. const HTTP_NOT_IMPLEMENTED = 501;
  71. const HTTP_BAD_GATEWAY = 502;
  72. const HTTP_SERVICE_UNAVAILABLE = 503;
  73. const HTTP_GATEWAY_TIMEOUT = 504;
  74. const HTTP_VERSION_NOT_SUPPORTED = 505;
  75. const HTTP_VARIANT_ALSO_NEGOTIATES_EXPERIMENTAL = 506; // RFC2295
  76. const HTTP_INSUFFICIENT_STORAGE = 507; // RFC4918
  77. const HTTP_LOOP_DETECTED = 508; // RFC5842
  78. const HTTP_NOT_EXTENDED = 510; // RFC2774
  79. const HTTP_NETWORK_AUTHENTICATION_REQUIRED = 511; // RFC6585
  80. /**
  81. * @var \Symfony\Component\HttpFoundation\ResponseHeaderBag
  82. */
  83. public $headers;
  84. /**
  85. * @var string
  86. */
  87. protected $content;
  88. /**
  89. * @var string
  90. */
  91. protected $version;
  92. /**
  93. * @var int
  94. */
  95. protected $statusCode;
  96. /**
  97. * @var string
  98. */
  99. protected $statusText;
  100. /**
  101. * @var string
  102. */
  103. protected $charset;
  104. /**
  105. * Status codes translation table.
  106. *
  107. * The list of codes is complete according to the
  108. * {@link http://www.iana.org/assignments/http-status-codes/ Hypertext Transfer Protocol (HTTP) Status Code Registry}
  109. * (last updated 2016-03-01).
  110. *
  111. * Unless otherwise noted, the status code is defined in RFC2616.
  112. *
  113. * @var array
  114. */
  115. public static $statusTexts = array(
  116. 100 => 'Continue',
  117. 101 => 'Switching Protocols',
  118. 102 => 'Processing', // RFC2518
  119. 103 => 'Early Hints',
  120. 200 => 'OK',
  121. 201 => 'Created',
  122. 202 => 'Accepted',
  123. 203 => 'Non-Authoritative Information',
  124. 204 => 'No Content',
  125. 205 => 'Reset Content',
  126. 206 => 'Partial Content',
  127. 207 => 'Multi-Status', // RFC4918
  128. 208 => 'Already Reported', // RFC5842
  129. 226 => 'IM Used', // RFC3229
  130. 300 => 'Multiple Choices',
  131. 301 => 'Moved Permanently',
  132. 302 => 'Found',
  133. 303 => 'See Other',
  134. 304 => 'Not Modified',
  135. 305 => 'Use Proxy',
  136. 307 => 'Temporary Redirect',
  137. 308 => 'Permanent Redirect', // RFC7238
  138. 400 => 'Bad Request',
  139. 401 => 'Unauthorized',
  140. 402 => 'Payment Required',
  141. 403 => 'Forbidden',
  142. 404 => 'Not Found',
  143. 405 => 'Method Not Allowed',
  144. 406 => 'Not Acceptable',
  145. 407 => 'Proxy Authentication Required',
  146. 408 => 'Request Timeout',
  147. 409 => 'Conflict',
  148. 410 => 'Gone',
  149. 411 => 'Length Required',
  150. 412 => 'Precondition Failed',
  151. 413 => 'Payload Too Large',
  152. 414 => 'URI Too Long',
  153. 415 => 'Unsupported Media Type',
  154. 416 => 'Range Not Satisfiable',
  155. 417 => 'Expectation Failed',
  156. 418 => 'I\'m a teapot', // RFC2324
  157. 421 => 'Misdirected Request', // RFC7540
  158. 422 => 'Unprocessable Entity', // RFC4918
  159. 423 => 'Locked', // RFC4918
  160. 424 => 'Failed Dependency', // RFC4918
  161. 425 => 'Reserved for WebDAV advanced collections expired proposal', // RFC2817
  162. 426 => 'Upgrade Required', // RFC2817
  163. 428 => 'Precondition Required', // RFC6585
  164. 429 => 'Too Many Requests', // RFC6585
  165. 431 => 'Request Header Fields Too Large', // RFC6585
  166. 451 => 'Unavailable For Legal Reasons', // RFC7725
  167. 500 => 'Internal Server Error',
  168. 501 => 'Not Implemented',
  169. 502 => 'Bad Gateway',
  170. 503 => 'Service Unavailable',
  171. 504 => 'Gateway Timeout',
  172. 505 => 'HTTP Version Not Supported',
  173. 506 => 'Variant Also Negotiates', // RFC2295
  174. 507 => 'Insufficient Storage', // RFC4918
  175. 508 => 'Loop Detected', // RFC5842
  176. 510 => 'Not Extended', // RFC2774
  177. 511 => 'Network Authentication Required', // RFC6585
  178. );
  179. /**
  180. * @param mixed $content The response content, see setContent()
  181. * @param int $status The response status code
  182. * @param array $headers An array of response headers
  183. *
  184. * @throws \InvalidArgumentException When the HTTP status code is not valid
  185. */
  186. public function __construct($content = '', $status = 200, $headers = array())
  187. {
  188. $this->headers = new ResponseHeaderBag($headers);
  189. $this->setContent($content);
  190. $this->setStatusCode($status);
  191. $this->setProtocolVersion('1.0');
  192. /* RFC2616 - 14.18 says all Responses need to have a Date */
  193. if (!$this->headers->has('Date')) {
  194. $this->setDate(\DateTime::createFromFormat('U', time()));
  195. }
  196. }
  197. /**
  198. * Factory method for chainability.
  199. *
  200. * Example:
  201. *
  202. * return Response::create($body, 200)
  203. * ->setSharedMaxAge(300);
  204. *
  205. * @param mixed $content The response content, see setContent()
  206. * @param int $status The response status code
  207. * @param array $headers An array of response headers
  208. *
  209. * @return static
  210. */
  211. public static function create($content = '', $status = 200, $headers = array())
  212. {
  213. return new static($content, $status, $headers);
  214. }
  215. /**
  216. * Returns the Response as an HTTP string.
  217. *
  218. * The string representation of the Response is the same as the
  219. * one that will be sent to the client only if the prepare() method
  220. * has been called before.
  221. *
  222. * @return string The Response as an HTTP string
  223. *
  224. * @see prepare()
  225. */
  226. public function __toString()
  227. {
  228. return
  229. sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText)."\r\n".
  230. $this->headers."\r\n".
  231. $this->getContent();
  232. }
  233. /**
  234. * Clones the current Response instance.
  235. */
  236. public function __clone()
  237. {
  238. $this->headers = clone $this->headers;
  239. }
  240. /**
  241. * Prepares the Response before it is sent to the client.
  242. *
  243. * This method tweaks the Response to ensure that it is
  244. * compliant with RFC 2616. Most of the changes are based on
  245. * the Request that is "associated" with this Response.
  246. *
  247. * @return $this
  248. */
  249. public function prepare(Request $request)
  250. {
  251. $headers = $this->headers;
  252. if ($this->isInformational() || $this->isEmpty()) {
  253. $this->setContent(null);
  254. $headers->remove('Content-Type');
  255. $headers->remove('Content-Length');
  256. } else {
  257. // Content-type based on the Request
  258. if (!$headers->has('Content-Type')) {
  259. $format = $request->getRequestFormat();
  260. if (null !== $format && $mimeType = $request->getMimeType($format)) {
  261. $headers->set('Content-Type', $mimeType);
  262. }
  263. }
  264. // Fix Content-Type
  265. $charset = $this->charset ?: 'UTF-8';
  266. if (!$headers->has('Content-Type')) {
  267. $headers->set('Content-Type', 'text/html; charset='.$charset);
  268. } elseif (0 === stripos($headers->get('Content-Type'), 'text/') && false === stripos($headers->get('Content-Type'), 'charset')) {
  269. // add the charset
  270. $headers->set('Content-Type', $headers->get('Content-Type').'; charset='.$charset);
  271. }
  272. // Fix Content-Length
  273. if ($headers->has('Transfer-Encoding')) {
  274. $headers->remove('Content-Length');
  275. }
  276. if ($request->isMethod('HEAD')) {
  277. // cf. RFC2616 14.13
  278. $length = $headers->get('Content-Length');
  279. $this->setContent(null);
  280. if ($length) {
  281. $headers->set('Content-Length', $length);
  282. }
  283. }
  284. }
  285. // Fix protocol
  286. if ('HTTP/1.0' != $request->server->get('SERVER_PROTOCOL')) {
  287. $this->setProtocolVersion('1.1');
  288. }
  289. // Check if we need to send extra expire info headers
  290. if ('1.0' == $this->getProtocolVersion() && false !== strpos($this->headers->get('Cache-Control'), 'no-cache')) {
  291. $this->headers->set('pragma', 'no-cache');
  292. $this->headers->set('expires', -1);
  293. }
  294. $this->ensureIEOverSSLCompatibility($request);
  295. return $this;
  296. }
  297. /**
  298. * Sends HTTP headers.
  299. *
  300. * @return $this
  301. */
  302. public function sendHeaders()
  303. {
  304. // headers have already been sent by the developer
  305. if (headers_sent()) {
  306. return $this;
  307. }
  308. /* RFC2616 - 14.18 says all Responses need to have a Date */
  309. if (!$this->headers->has('Date')) {
  310. $this->setDate(\DateTime::createFromFormat('U', time()));
  311. }
  312. // headers
  313. foreach ($this->headers->allPreserveCaseWithoutCookies() as $name => $values) {
  314. foreach ($values as $value) {
  315. header($name.': '.$value, false, $this->statusCode);
  316. }
  317. }
  318. // status
  319. header(sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText), true, $this->statusCode);
  320. // cookies
  321. foreach ($this->headers->getCookies() as $cookie) {
  322. if ($cookie->isRaw()) {
  323. setrawcookie($cookie->getName(), $cookie->getValue(), $cookie->getExpiresTime(), $cookie->getPath(), $cookie->getDomain(), $cookie->isSecure(), $cookie->isHttpOnly());
  324. } else {
  325. setcookie($cookie->getName(), $cookie->getValue(), $cookie->getExpiresTime(), $cookie->getPath(), $cookie->getDomain(), $cookie->isSecure(), $cookie->isHttpOnly());
  326. }
  327. }
  328. return $this;
  329. }
  330. /**
  331. * Sends content for the current web response.
  332. *
  333. * @return $this
  334. */
  335. public function sendContent()
  336. {
  337. echo $this->content;
  338. return $this;
  339. }
  340. /**
  341. * Sends HTTP headers and content.
  342. *
  343. * @return $this
  344. */
  345. public function send()
  346. {
  347. $this->sendHeaders();
  348. $this->sendContent();
  349. if (function_exists('fastcgi_finish_request')) {
  350. fastcgi_finish_request();
  351. } elseif ('cli' !== PHP_SAPI) {
  352. static::closeOutputBuffers(0, true);
  353. }
  354. return $this;
  355. }
  356. /**
  357. * Sets the response content.
  358. *
  359. * Valid types are strings, numbers, null, and objects that implement a __toString() method.
  360. *
  361. * @param mixed $content Content that can be cast to string
  362. *
  363. * @return $this
  364. *
  365. * @throws \UnexpectedValueException
  366. */
  367. public function setContent($content)
  368. {
  369. if (null !== $content && !is_string($content) && !is_numeric($content) && !is_callable(array($content, '__toString'))) {
  370. throw new \UnexpectedValueException(sprintf('The Response content must be a string or object implementing __toString(), "%s" given.', gettype($content)));
  371. }
  372. $this->content = (string) $content;
  373. return $this;
  374. }
  375. /**
  376. * Gets the current response content.
  377. *
  378. * @return string Content
  379. */
  380. public function getContent()
  381. {
  382. return $this->content;
  383. }
  384. /**
  385. * Sets the HTTP protocol version (1.0 or 1.1).
  386. *
  387. * @param string $version The HTTP protocol version
  388. *
  389. * @return $this
  390. *
  391. * @final since version 3.2
  392. */
  393. public function setProtocolVersion($version)
  394. {
  395. $this->version = $version;
  396. return $this;
  397. }
  398. /**
  399. * Gets the HTTP protocol version.
  400. *
  401. * @return string The HTTP protocol version
  402. *
  403. * @final since version 3.2
  404. */
  405. public function getProtocolVersion()
  406. {
  407. return $this->version;
  408. }
  409. /**
  410. * Sets the response status code.
  411. *
  412. * If the status text is null it will be automatically populated for the known
  413. * status codes and left empty otherwise.
  414. *
  415. * @param int $code HTTP status code
  416. * @param mixed $text HTTP status text
  417. *
  418. * @return $this
  419. *
  420. * @throws \InvalidArgumentException When the HTTP status code is not valid
  421. *
  422. * @final since version 3.2
  423. */
  424. public function setStatusCode($code, $text = null)
  425. {
  426. $this->statusCode = $code = (int) $code;
  427. if ($this->isInvalid()) {
  428. throw new \InvalidArgumentException(sprintf('The HTTP status code "%s" is not valid.', $code));
  429. }
  430. if (null === $text) {
  431. $this->statusText = isset(self::$statusTexts[$code]) ? self::$statusTexts[$code] : 'unknown status';
  432. return $this;
  433. }
  434. if (false === $text) {
  435. $this->statusText = '';
  436. return $this;
  437. }
  438. $this->statusText = $text;
  439. return $this;
  440. }
  441. /**
  442. * Retrieves the status code for the current web response.
  443. *
  444. * @return int Status code
  445. *
  446. * @final since version 3.2
  447. */
  448. public function getStatusCode()
  449. {
  450. return $this->statusCode;
  451. }
  452. /**
  453. * Sets the response charset.
  454. *
  455. * @param string $charset Character set
  456. *
  457. * @return $this
  458. *
  459. * @final since version 3.2
  460. */
  461. public function setCharset($charset)
  462. {
  463. $this->charset = $charset;
  464. return $this;
  465. }
  466. /**
  467. * Retrieves the response charset.
  468. *
  469. * @return string Character set
  470. *
  471. * @final since version 3.2
  472. */
  473. public function getCharset()
  474. {
  475. return $this->charset;
  476. }
  477. /**
  478. * Returns true if the response is worth caching under any circumstance.
  479. *
  480. * Responses marked "private" with an explicit Cache-Control directive are
  481. * considered uncacheable.
  482. *
  483. * Responses with neither a freshness lifetime (Expires, max-age) nor cache
  484. * validator (Last-Modified, ETag) are considered uncacheable.
  485. *
  486. * @return bool true if the response is worth caching, false otherwise
  487. *
  488. * @final since version 3.3
  489. */
  490. public function isCacheable()
  491. {
  492. if (!in_array($this->statusCode, array(200, 203, 300, 301, 302, 404, 410))) {
  493. return false;
  494. }
  495. if ($this->headers->hasCacheControlDirective('no-store') || $this->headers->getCacheControlDirective('private')) {
  496. return false;
  497. }
  498. return $this->isValidateable() || $this->isFresh();
  499. }
  500. /**
  501. * Returns true if the response is "fresh".
  502. *
  503. * Fresh responses may be served from cache without any interaction with the
  504. * origin. A response is considered fresh when it includes a Cache-Control/max-age
  505. * indicator or Expires header and the calculated age is less than the freshness lifetime.
  506. *
  507. * @return bool true if the response is fresh, false otherwise
  508. *
  509. * @final since version 3.3
  510. */
  511. public function isFresh()
  512. {
  513. return $this->getTtl() > 0;
  514. }
  515. /**
  516. * Returns true if the response includes headers that can be used to validate
  517. * the response with the origin server using a conditional GET request.
  518. *
  519. * @return bool true if the response is validateable, false otherwise
  520. *
  521. * @final since version 3.3
  522. */
  523. public function isValidateable()
  524. {
  525. return $this->headers->has('Last-Modified') || $this->headers->has('ETag');
  526. }
  527. /**
  528. * Marks the response as "private".
  529. *
  530. * It makes the response ineligible for serving other clients.
  531. *
  532. * @return $this
  533. *
  534. * @final since version 3.2
  535. */
  536. public function setPrivate()
  537. {
  538. $this->headers->removeCacheControlDirective('public');
  539. $this->headers->addCacheControlDirective('private');
  540. return $this;
  541. }
  542. /**
  543. * Marks the response as "public".
  544. *
  545. * It makes the response eligible for serving other clients.
  546. *
  547. * @return $this
  548. *
  549. * @final since version 3.2
  550. */
  551. public function setPublic()
  552. {
  553. $this->headers->addCacheControlDirective('public');
  554. $this->headers->removeCacheControlDirective('private');
  555. return $this;
  556. }
  557. /**
  558. * Returns true if the response must be revalidated by caches.
  559. *
  560. * This method indicates that the response must not be served stale by a
  561. * cache in any circumstance without first revalidating with the origin.
  562. * When present, the TTL of the response should not be overridden to be
  563. * greater than the value provided by the origin.
  564. *
  565. * @return bool true if the response must be revalidated by a cache, false otherwise
  566. *
  567. * @final since version 3.3
  568. */
  569. public function mustRevalidate()
  570. {
  571. return $this->headers->hasCacheControlDirective('must-revalidate') || $this->headers->hasCacheControlDirective('proxy-revalidate');
  572. }
  573. /**
  574. * Returns the Date header as a DateTime instance.
  575. *
  576. * @return \DateTime A \DateTime instance
  577. *
  578. * @throws \RuntimeException When the header is not parseable
  579. *
  580. * @final since version 3.2
  581. */
  582. public function getDate()
  583. {
  584. /*
  585. RFC2616 - 14.18 says all Responses need to have a Date.
  586. Make sure we provide one even if it the header
  587. has been removed in the meantime.
  588. */
  589. if (!$this->headers->has('Date')) {
  590. $this->setDate(\DateTime::createFromFormat('U', time()));
  591. }
  592. return $this->headers->getDate('Date');
  593. }
  594. /**
  595. * Sets the Date header.
  596. *
  597. * @return $this
  598. *
  599. * @final since version 3.2
  600. */
  601. public function setDate(\DateTime $date)
  602. {
  603. $date->setTimezone(new \DateTimeZone('UTC'));
  604. $this->headers->set('Date', $date->format('D, d M Y H:i:s').' GMT');
  605. return $this;
  606. }
  607. /**
  608. * Returns the age of the response.
  609. *
  610. * @return int The age of the response in seconds
  611. *
  612. * @final since version 3.2
  613. */
  614. public function getAge()
  615. {
  616. if (null !== $age = $this->headers->get('Age')) {
  617. return (int) $age;
  618. }
  619. return max(time() - $this->getDate()->format('U'), 0);
  620. }
  621. /**
  622. * Marks the response stale by setting the Age header to be equal to the maximum age of the response.
  623. *
  624. * @return $this
  625. */
  626. public function expire()
  627. {
  628. if ($this->isFresh()) {
  629. $this->headers->set('Age', $this->getMaxAge());
  630. }
  631. return $this;
  632. }
  633. /**
  634. * Returns the value of the Expires header as a DateTime instance.
  635. *
  636. * @return \DateTime|null A DateTime instance or null if the header does not exist
  637. *
  638. * @final since version 3.2
  639. */
  640. public function getExpires()
  641. {
  642. try {
  643. return $this->headers->getDate('Expires');
  644. } catch (\RuntimeException $e) {
  645. // according to RFC 2616 invalid date formats (e.g. "0" and "-1") must be treated as in the past
  646. return \DateTime::createFromFormat(DATE_RFC2822, 'Sat, 01 Jan 00 00:00:00 +0000');
  647. }
  648. }
  649. /**
  650. * Sets the Expires HTTP header with a DateTime instance.
  651. *
  652. * Passing null as value will remove the header.
  653. *
  654. * @param \DateTime|null $date A \DateTime instance or null to remove the header
  655. *
  656. * @return $this
  657. *
  658. * @final since version 3.2
  659. */
  660. public function setExpires(\DateTime $date = null)
  661. {
  662. if (null === $date) {
  663. $this->headers->remove('Expires');
  664. } else {
  665. $date = clone $date;
  666. $date->setTimezone(new \DateTimeZone('UTC'));
  667. $this->headers->set('Expires', $date->format('D, d M Y H:i:s').' GMT');
  668. }
  669. return $this;
  670. }
  671. /**
  672. * Returns the number of seconds after the time specified in the response's Date
  673. * header when the response should no longer be considered fresh.
  674. *
  675. * First, it checks for a s-maxage directive, then a max-age directive, and then it falls
  676. * back on an expires header. It returns null when no maximum age can be established.
  677. *
  678. * @return int|null Number of seconds
  679. *
  680. * @final since version 3.2
  681. */
  682. public function getMaxAge()
  683. {
  684. if ($this->headers->hasCacheControlDirective('s-maxage')) {
  685. return (int) $this->headers->getCacheControlDirective('s-maxage');
  686. }
  687. if ($this->headers->hasCacheControlDirective('max-age')) {
  688. return (int) $this->headers->getCacheControlDirective('max-age');
  689. }
  690. if (null !== $this->getExpires()) {
  691. return $this->getExpires()->format('U') - $this->getDate()->format('U');
  692. }
  693. }
  694. /**
  695. * Sets the number of seconds after which the response should no longer be considered fresh.
  696. *
  697. * This methods sets the Cache-Control max-age directive.
  698. *
  699. * @param int $value Number of seconds
  700. *
  701. * @return $this
  702. *
  703. * @final since version 3.2
  704. */
  705. public function setMaxAge($value)
  706. {
  707. $this->headers->addCacheControlDirective('max-age', $value);
  708. return $this;
  709. }
  710. /**
  711. * Sets the number of seconds after which the response should no longer be considered fresh by shared caches.
  712. *
  713. * This methods sets the Cache-Control s-maxage directive.
  714. *
  715. * @param int $value Number of seconds
  716. *
  717. * @return $this
  718. *
  719. * @final since version 3.2
  720. */
  721. public function setSharedMaxAge($value)
  722. {
  723. $this->setPublic();
  724. $this->headers->addCacheControlDirective('s-maxage', $value);
  725. return $this;
  726. }
  727. /**
  728. * Returns the response's time-to-live in seconds.
  729. *
  730. * It returns null when no freshness information is present in the response.
  731. *
  732. * When the responses TTL is <= 0, the response may not be served from cache without first
  733. * revalidating with the origin.
  734. *
  735. * @return int|null The TTL in seconds
  736. *
  737. * @final since version 3.2
  738. */
  739. public function getTtl()
  740. {
  741. if (null !== $maxAge = $this->getMaxAge()) {
  742. return $maxAge - $this->getAge();
  743. }
  744. }
  745. /**
  746. * Sets the response's time-to-live for shared caches.
  747. *
  748. * This method adjusts the Cache-Control/s-maxage directive.
  749. *
  750. * @param int $seconds Number of seconds
  751. *
  752. * @return $this
  753. *
  754. * @final since version 3.2
  755. */
  756. public function setTtl($seconds)
  757. {
  758. $this->setSharedMaxAge($this->getAge() + $seconds);
  759. return $this;
  760. }
  761. /**
  762. * Sets the response's time-to-live for private/client caches.
  763. *
  764. * This method adjusts the Cache-Control/max-age directive.
  765. *
  766. * @param int $seconds Number of seconds
  767. *
  768. * @return $this
  769. *
  770. * @final since version 3.2
  771. */
  772. public function setClientTtl($seconds)
  773. {
  774. $this->setMaxAge($this->getAge() + $seconds);
  775. return $this;
  776. }
  777. /**
  778. * Returns the Last-Modified HTTP header as a DateTime instance.
  779. *
  780. * @return \DateTime|null A DateTime instance or null if the header does not exist
  781. *
  782. * @throws \RuntimeException When the HTTP header is not parseable
  783. *
  784. * @final since version 3.2
  785. */
  786. public function getLastModified()
  787. {
  788. return $this->headers->getDate('Last-Modified');
  789. }
  790. /**
  791. * Sets the Last-Modified HTTP header with a DateTime instance.
  792. *
  793. * Passing null as value will remove the header.
  794. *
  795. * @param \DateTime|null $date A \DateTime instance or null to remove the header
  796. *
  797. * @return $this
  798. *
  799. * @final since version 3.2
  800. */
  801. public function setLastModified(\DateTime $date = null)
  802. {
  803. if (null === $date) {
  804. $this->headers->remove('Last-Modified');
  805. } else {
  806. $date = clone $date;
  807. $date->setTimezone(new \DateTimeZone('UTC'));
  808. $this->headers->set('Last-Modified', $date->format('D, d M Y H:i:s').' GMT');
  809. }
  810. return $this;
  811. }
  812. /**
  813. * Returns the literal value of the ETag HTTP header.
  814. *
  815. * @return string|null The ETag HTTP header or null if it does not exist
  816. *
  817. * @final since version 3.2
  818. */
  819. public function getEtag()
  820. {
  821. return $this->headers->get('ETag');
  822. }
  823. /**
  824. * Sets the ETag value.
  825. *
  826. * @param string|null $etag The ETag unique identifier or null to remove the header
  827. * @param bool $weak Whether you want a weak ETag or not
  828. *
  829. * @return $this
  830. *
  831. * @final since version 3.2
  832. */
  833. public function setEtag($etag = null, $weak = false)
  834. {
  835. if (null === $etag) {
  836. $this->headers->remove('Etag');
  837. } else {
  838. if (0 !== strpos($etag, '"')) {
  839. $etag = '"'.$etag.'"';
  840. }
  841. $this->headers->set('ETag', (true === $weak ? 'W/' : '').$etag);
  842. }
  843. return $this;
  844. }
  845. /**
  846. * Sets the response's cache headers (validation and/or expiration).
  847. *
  848. * Available options are: etag, last_modified, max_age, s_maxage, private, and public.
  849. *
  850. * @param array $options An array of cache options
  851. *
  852. * @return $this
  853. *
  854. * @throws \InvalidArgumentException
  855. *
  856. * @final since version 3.3
  857. */
  858. public function setCache(array $options)
  859. {
  860. if ($diff = array_diff(array_keys($options), array('etag', 'last_modified', 'max_age', 's_maxage', 'private', 'public'))) {
  861. throw new \InvalidArgumentException(sprintf('Response does not support the following options: "%s".', implode('", "', array_values($diff))));
  862. }
  863. if (isset($options['etag'])) {
  864. $this->setEtag($options['etag']);
  865. }
  866. if (isset($options['last_modified'])) {
  867. $this->setLastModified($options['last_modified']);
  868. }
  869. if (isset($options['max_age'])) {
  870. $this->setMaxAge($options['max_age']);
  871. }
  872. if (isset($options['s_maxage'])) {
  873. $this->setSharedMaxAge($options['s_maxage']);
  874. }
  875. if (isset($options['public'])) {
  876. if ($options['public']) {
  877. $this->setPublic();
  878. } else {
  879. $this->setPrivate();
  880. }
  881. }
  882. if (isset($options['private'])) {
  883. if ($options['private']) {
  884. $this->setPrivate();
  885. } else {
  886. $this->setPublic();
  887. }
  888. }
  889. return $this;
  890. }
  891. /**
  892. * Modifies the response so that it conforms to the rules defined for a 304 status code.
  893. *
  894. * This sets the status, removes the body, and discards any headers
  895. * that MUST NOT be included in 304 responses.
  896. *
  897. * @return $this
  898. *
  899. * @see http://tools.ietf.org/html/rfc2616#section-10.3.5
  900. *
  901. * @final since version 3.3
  902. */
  903. public function setNotModified()
  904. {
  905. $this->setStatusCode(304);
  906. $this->setContent(null);
  907. // remove headers that MUST NOT be included with 304 Not Modified responses
  908. foreach (array('Allow', 'Content-Encoding', 'Content-Language', 'Content-Length', 'Content-MD5', 'Content-Type', 'Last-Modified') as $header) {
  909. $this->headers->remove($header);
  910. }
  911. return $this;
  912. }
  913. /**
  914. * Returns true if the response includes a Vary header.
  915. *
  916. * @return bool true if the response includes a Vary header, false otherwise
  917. *
  918. * @final since version 3.2
  919. */
  920. public function hasVary()
  921. {
  922. return null !== $this->headers->get('Vary');
  923. }
  924. /**
  925. * Returns an array of header names given in the Vary header.
  926. *
  927. * @return array An array of Vary names
  928. *
  929. * @final since version 3.2
  930. */
  931. public function getVary()
  932. {
  933. if (!$vary = $this->headers->get('Vary', null, false)) {
  934. return array();
  935. }
  936. $ret = array();
  937. foreach ($vary as $item) {
  938. $ret = array_merge($ret, preg_split('/[\s,]+/', $item));
  939. }
  940. return $ret;
  941. }
  942. /**
  943. * Sets the Vary header.
  944. *
  945. * @param string|array $headers
  946. * @param bool $replace Whether to replace the actual value or not (true by default)
  947. *
  948. * @return $this
  949. *
  950. * @final since version 3.2
  951. */
  952. public function setVary($headers, $replace = true)
  953. {
  954. $this->headers->set('Vary', $headers, $replace);
  955. return $this;
  956. }
  957. /**
  958. * Determines if the Response validators (ETag, Last-Modified) match
  959. * a conditional value specified in the Request.
  960. *
  961. * If the Response is not modified, it sets the status code to 304 and
  962. * removes the actual content by calling the setNotModified() method.
  963. *
  964. * @return bool true if the Response validators match the Request, false otherwise
  965. *
  966. * @final since version 3.3
  967. */
  968. public function isNotModified(Request $request)
  969. {
  970. if (!$request->isMethodCacheable()) {
  971. return false;
  972. }
  973. $notModified = false;
  974. $lastModified = $this->headers->get('Last-Modified');
  975. $modifiedSince = $request->headers->get('If-Modified-Since');
  976. if ($etags = $request->getETags()) {
  977. $notModified = in_array($this->getEtag(), $etags) || in_array('*', $etags);
  978. }
  979. if ($modifiedSince && $lastModified) {
  980. $notModified = strtotime($modifiedSince) >= strtotime($lastModified) && (!$etags || $notModified);
  981. }
  982. if ($notModified) {
  983. $this->setNotModified();
  984. }
  985. return $notModified;
  986. }
  987. /**
  988. * Is response invalid?
  989. *
  990. * @return bool
  991. *
  992. * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
  993. *
  994. * @final since version 3.2
  995. */
  996. public function isInvalid()
  997. {
  998. return $this->statusCode < 100 || $this->statusCode >= 600;
  999. }
  1000. /**
  1001. * Is response informative?
  1002. *
  1003. * @return bool
  1004. *
  1005. * @final since version 3.3
  1006. */
  1007. public function isInformational()
  1008. {
  1009. return $this->statusCode >= 100 && $this->statusCode < 200;
  1010. }
  1011. /**
  1012. * Is response successful?
  1013. *
  1014. * @return bool
  1015. *
  1016. * @final since version 3.2
  1017. */
  1018. public function isSuccessful()
  1019. {
  1020. return $this->statusCode >= 200 && $this->statusCode < 300;
  1021. }
  1022. /**
  1023. * Is the response a redirect?
  1024. *
  1025. * @return bool
  1026. *
  1027. * @final since version 3.2
  1028. */
  1029. public function isRedirection()
  1030. {
  1031. return $this->statusCode >= 300 && $this->statusCode < 400;
  1032. }
  1033. /**
  1034. * Is there a client error?
  1035. *
  1036. * @return bool
  1037. *
  1038. * @final since version 3.2
  1039. */
  1040. public function isClientError()
  1041. {
  1042. return $this->statusCode >= 400 && $this->statusCode < 500;
  1043. }
  1044. /**
  1045. * Was there a server side error?
  1046. *
  1047. * @return bool
  1048. *
  1049. * @final since version 3.3
  1050. */
  1051. public function isServerError()
  1052. {
  1053. return $this->statusCode >= 500 && $this->statusCode < 600;
  1054. }
  1055. /**
  1056. * Is the response OK?
  1057. *
  1058. * @return bool
  1059. *
  1060. * @final since version 3.2
  1061. */
  1062. public function isOk()
  1063. {
  1064. return 200 === $this->statusCode;
  1065. }
  1066. /**
  1067. * Is the response forbidden?
  1068. *
  1069. * @return bool
  1070. *
  1071. * @final since version 3.2
  1072. */
  1073. public function isForbidden()
  1074. {
  1075. return 403 === $this->statusCode;
  1076. }
  1077. /**
  1078. * Is the response a not found error?
  1079. *
  1080. * @return bool
  1081. *
  1082. * @final since version 3.2
  1083. */
  1084. public function isNotFound()
  1085. {
  1086. return 404 === $this->statusCode;
  1087. }
  1088. /**
  1089. * Is the response a redirect of some form?
  1090. *
  1091. * @param string $location
  1092. *
  1093. * @return bool
  1094. *
  1095. * @final since version 3.2
  1096. */
  1097. public function isRedirect($location = null)
  1098. {
  1099. return in_array($this->statusCode, array(201, 301, 302, 303, 307, 308)) && (null === $location ?: $location == $this->headers->get('Location'));
  1100. }
  1101. /**
  1102. * Is the response empty?
  1103. *
  1104. * @return bool
  1105. *
  1106. * @final since version 3.2
  1107. */
  1108. public function isEmpty()
  1109. {
  1110. return in_array($this->statusCode, array(204, 304));
  1111. }
  1112. /**
  1113. * Cleans or flushes output buffers up to target level.
  1114. *
  1115. * Resulting level can be greater than target level if a non-removable buffer has been encountered.
  1116. *
  1117. * @param int $targetLevel The target output buffering level
  1118. * @param bool $flush Whether to flush or clean the buffers
  1119. *
  1120. * @final since version 3.3
  1121. */
  1122. public static function closeOutputBuffers($targetLevel, $flush)
  1123. {
  1124. $status = ob_get_status(true);
  1125. $level = count($status);
  1126. // PHP_OUTPUT_HANDLER_* are not defined on HHVM 3.3
  1127. $flags = defined('PHP_OUTPUT_HANDLER_REMOVABLE') ? PHP_OUTPUT_HANDLER_REMOVABLE | ($flush ? PHP_OUTPUT_HANDLER_FLUSHABLE : PHP_OUTPUT_HANDLER_CLEANABLE) : -1;
  1128. while ($level-- > $targetLevel && ($s = $status[$level]) && (!isset($s['del']) ? !isset($s['flags']) || ($s['flags'] & $flags) === $flags : $s['del'])) {
  1129. if ($flush) {
  1130. ob_end_flush();
  1131. } else {
  1132. ob_end_clean();
  1133. }
  1134. }
  1135. }
  1136. /**
  1137. * Checks if we need to remove Cache-Control for SSL encrypted downloads when using IE < 9.
  1138. *
  1139. * @see http://support.microsoft.com/kb/323308
  1140. *
  1141. * @final since version 3.3
  1142. */
  1143. protected function ensureIEOverSSLCompatibility(Request $request)
  1144. {
  1145. if (false !== stripos($this->headers->get('Content-Disposition'), 'attachment') && 1 == preg_match('/MSIE (.*?);/i', $request->server->get('HTTP_USER_AGENT'), $match) && true === $request->isSecure()) {
  1146. if ((int) preg_replace('/(MSIE )(.*?);/', '$2', $match[0]) < 9) {
  1147. $this->headers->remove('Cache-Control');
  1148. }
  1149. }
  1150. }
  1151. }