ResponseHeaderBag.php 8.0 KB

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