You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

344 lines
9.9 KiB

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