No Description

ResponseHeaderBag.php 8.7KB

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