ResponseHeaderBag.php 8.3 KB

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