ResponseHeaderBag.php 8.6 KB

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