ResponseHeaderBag.php 9.5 KB

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