Drupal investigation

Response.php 34KB

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