ResponseHeaderBag.php 9.3 KB

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