ResponseHeaderBag.php 9.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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. * ResponseHeaderBag is a container for Response HTTP headers.
  13. *
  14. * @author Fabien Potencier <fabien@symfony.com>
  15. */
  16. class ResponseHeaderBag extends HeaderBag
  17. {
  18. const COOKIES_FLAT = 'flat';
  19. const COOKIES_ARRAY = 'array';
  20. const DISPOSITION_ATTACHMENT = 'attachment';
  21. const DISPOSITION_INLINE = 'inline';
  22. protected $computedCacheControl = array();
  23. protected $cookies = array();
  24. protected $headerNames = array();
  25. public function __construct(array $headers = array())
  26. {
  27. parent::__construct($headers);
  28. if (!isset($this->headers['cache-control'])) {
  29. $this->set('Cache-Control', '');
  30. }
  31. /* RFC2616 - 14.18 says all Responses need to have a Date */
  32. if (!isset($this->headers['date'])) {
  33. $this->initDate();
  34. }
  35. }
  36. /**
  37. * Returns the headers, with original capitalizations.
  38. *
  39. * @return array An array of headers
  40. */
  41. public function allPreserveCase()
  42. {
  43. $headers = array();
  44. foreach ($this->all() as $name => $value) {
  45. $headers[isset($this->headerNames[$name]) ? $this->headerNames[$name] : $name] = $value;
  46. }
  47. return $headers;
  48. }
  49. public function allPreserveCaseWithoutCookies()
  50. {
  51. $headers = $this->allPreserveCase();
  52. if (isset($this->headerNames['set-cookie'])) {
  53. unset($headers[$this->headerNames['set-cookie']]);
  54. }
  55. return $headers;
  56. }
  57. /**
  58. * {@inheritdoc}
  59. */
  60. public function replace(array $headers = array())
  61. {
  62. $this->headerNames = array();
  63. parent::replace($headers);
  64. if (!isset($this->headers['cache-control'])) {
  65. $this->set('Cache-Control', '');
  66. }
  67. if (!isset($this->headers['date'])) {
  68. $this->initDate();
  69. }
  70. }
  71. /**
  72. * {@inheritdoc}
  73. */
  74. public function all()
  75. {
  76. $headers = parent::all();
  77. foreach ($this->getCookies() as $cookie) {
  78. $headers['set-cookie'][] = (string) $cookie;
  79. }
  80. return $headers;
  81. }
  82. /**
  83. * {@inheritdoc}
  84. */
  85. public function set($key, $values, $replace = true)
  86. {
  87. $uniqueKey = str_replace('_', '-', strtolower($key));
  88. if ('set-cookie' === $uniqueKey) {
  89. if ($replace) {
  90. $this->cookies = array();
  91. }
  92. foreach ((array) $values as $cookie) {
  93. $this->setCookie(Cookie::fromString($cookie));
  94. }
  95. $this->headerNames[$uniqueKey] = $key;
  96. return;
  97. }
  98. $this->headerNames[$uniqueKey] = $key;
  99. parent::set($key, $values, $replace);
  100. // ensure the cache-control header has sensible defaults
  101. if (\in_array($uniqueKey, array('cache-control', 'etag', 'last-modified', 'expires'), true)) {
  102. $computed = $this->computeCacheControlValue();
  103. $this->headers['cache-control'] = array($computed);
  104. $this->headerNames['cache-control'] = 'Cache-Control';
  105. $this->computedCacheControl = $this->parseCacheControl($computed);
  106. }
  107. }
  108. /**
  109. * {@inheritdoc}
  110. */
  111. public function remove($key)
  112. {
  113. $uniqueKey = str_replace('_', '-', strtolower($key));
  114. unset($this->headerNames[$uniqueKey]);
  115. if ('set-cookie' === $uniqueKey) {
  116. $this->cookies = array();
  117. return;
  118. }
  119. parent::remove($key);
  120. if ('cache-control' === $uniqueKey) {
  121. $this->computedCacheControl = array();
  122. }
  123. if ('date' === $uniqueKey) {
  124. $this->initDate();
  125. }
  126. }
  127. /**
  128. * {@inheritdoc}
  129. */
  130. public function hasCacheControlDirective($key)
  131. {
  132. return array_key_exists($key, $this->computedCacheControl);
  133. }
  134. /**
  135. * {@inheritdoc}
  136. */
  137. public function getCacheControlDirective($key)
  138. {
  139. return array_key_exists($key, $this->computedCacheControl) ? $this->computedCacheControl[$key] : null;
  140. }
  141. public function setCookie(Cookie $cookie)
  142. {
  143. $this->cookies[$cookie->getDomain()][$cookie->getPath()][$cookie->getName()] = $cookie;
  144. $this->headerNames['set-cookie'] = 'Set-Cookie';
  145. }
  146. /**
  147. * Removes a cookie from the array, but does not unset it in the browser.
  148. *
  149. * @param string $name
  150. * @param string $path
  151. * @param string $domain
  152. */
  153. public function removeCookie($name, $path = '/', $domain = null)
  154. {
  155. if (null === $path) {
  156. $path = '/';
  157. }
  158. unset($this->cookies[$domain][$path][$name]);
  159. if (empty($this->cookies[$domain][$path])) {
  160. unset($this->cookies[$domain][$path]);
  161. if (empty($this->cookies[$domain])) {
  162. unset($this->cookies[$domain]);
  163. }
  164. }
  165. if (empty($this->cookies)) {
  166. unset($this->headerNames['set-cookie']);
  167. }
  168. }
  169. /**
  170. * Returns an array with all cookies.
  171. *
  172. * @param string $format
  173. *
  174. * @return array
  175. *
  176. * @throws \InvalidArgumentException When the $format is invalid
  177. */
  178. public function getCookies($format = self::COOKIES_FLAT)
  179. {
  180. if (!in_array($format, array(self::COOKIES_FLAT, self::COOKIES_ARRAY))) {
  181. throw new \InvalidArgumentException(sprintf('Format "%s" invalid (%s).', $format, implode(', ', array(self::COOKIES_FLAT, self::COOKIES_ARRAY))));
  182. }
  183. if (self::COOKIES_ARRAY === $format) {
  184. return $this->cookies;
  185. }
  186. $flattenedCookies = array();
  187. foreach ($this->cookies as $path) {
  188. foreach ($path as $cookies) {
  189. foreach ($cookies as $cookie) {
  190. $flattenedCookies[] = $cookie;
  191. }
  192. }
  193. }
  194. return $flattenedCookies;
  195. }
  196. /**
  197. * Clears a cookie in the browser.
  198. *
  199. * @param string $name
  200. * @param string $path
  201. * @param string $domain
  202. * @param bool $secure
  203. * @param bool $httpOnly
  204. */
  205. public function clearCookie($name, $path = '/', $domain = null, $secure = false, $httpOnly = true)
  206. {
  207. $this->setCookie(new Cookie($name, null, 1, $path, $domain, $secure, $httpOnly));
  208. }
  209. /**
  210. * Generates a HTTP Content-Disposition field-value.
  211. *
  212. * @param string $disposition One of "inline" or "attachment"
  213. * @param string $filename A unicode string
  214. * @param string $filenameFallback A string containing only ASCII characters that
  215. * is semantically equivalent to $filename. If the filename is already ASCII,
  216. * it can be omitted, or just copied from $filename
  217. *
  218. * @return string A string suitable for use as a Content-Disposition field-value
  219. *
  220. * @throws \InvalidArgumentException
  221. *
  222. * @see RFC 6266
  223. */
  224. public function makeDisposition($disposition, $filename, $filenameFallback = '')
  225. {
  226. if (!in_array($disposition, array(self::DISPOSITION_ATTACHMENT, self::DISPOSITION_INLINE))) {
  227. throw new \InvalidArgumentException(sprintf('The disposition must be either "%s" or "%s".', self::DISPOSITION_ATTACHMENT, self::DISPOSITION_INLINE));
  228. }
  229. if ('' == $filenameFallback) {
  230. $filenameFallback = $filename;
  231. }
  232. // filenameFallback is not ASCII.
  233. if (!preg_match('/^[\x20-\x7e]*$/', $filenameFallback)) {
  234. throw new \InvalidArgumentException('The filename fallback must only contain ASCII characters.');
  235. }
  236. // percent characters aren't safe in fallback.
  237. if (false !== strpos($filenameFallback, '%')) {
  238. throw new \InvalidArgumentException('The filename fallback cannot contain the "%" character.');
  239. }
  240. // path separators aren't allowed in either.
  241. if (false !== strpos($filename, '/') || false !== strpos($filename, '\\') || false !== strpos($filenameFallback, '/') || false !== strpos($filenameFallback, '\\')) {
  242. throw new \InvalidArgumentException('The filename and the fallback cannot contain the "/" and "\\" characters.');
  243. }
  244. $params = array('filename' => $filenameFallback);
  245. if ($filename !== $filenameFallback) {
  246. $params['filename*'] = "utf-8''".rawurlencode($filename);
  247. }
  248. return $disposition.'; '.HeaderUtils::toString($params, ';');
  249. }
  250. /**
  251. * Returns the calculated value of the cache-control header.
  252. *
  253. * This considers several other headers and calculates or modifies the
  254. * cache-control header to a sensible, conservative value.
  255. *
  256. * @return string
  257. */
  258. protected function computeCacheControlValue()
  259. {
  260. if (!$this->cacheControl && !$this->has('ETag') && !$this->has('Last-Modified') && !$this->has('Expires')) {
  261. return 'no-cache, private';
  262. }
  263. if (!$this->cacheControl) {
  264. // conservative by default
  265. return 'private, must-revalidate';
  266. }
  267. $header = $this->getCacheControlHeader();
  268. if (isset($this->cacheControl['public']) || isset($this->cacheControl['private'])) {
  269. return $header;
  270. }
  271. // public if s-maxage is defined, private otherwise
  272. if (!isset($this->cacheControl['s-maxage'])) {
  273. return $header.', private';
  274. }
  275. return $header;
  276. }
  277. private function initDate()
  278. {
  279. $now = \DateTime::createFromFormat('U', time());
  280. $now->setTimezone(new \DateTimeZone('UTC'));
  281. $this->set('Date', $now->format('D, d M Y H:i:s').' GMT');
  282. }
  283. }