Geen omschrijving

CookieJar.php 8.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. <?php
  2. namespace GuzzleHttp\Cookie;
  3. use Psr\Http\Message\RequestInterface;
  4. use Psr\Http\Message\ResponseInterface;
  5. /**
  6. * Cookie jar that stores cookies an an array
  7. */
  8. class CookieJar implements CookieJarInterface
  9. {
  10. /** @var SetCookie[] Loaded cookie data */
  11. private $cookies = [];
  12. /** @var bool */
  13. private $strictMode;
  14. /**
  15. * @param bool $strictMode Set to true to throw exceptions when invalid
  16. * cookies are added to the cookie jar.
  17. * @param array $cookieArray Array of SetCookie objects or a hash of
  18. * arrays that can be used with the SetCookie
  19. * constructor
  20. */
  21. public function __construct($strictMode = false, $cookieArray = [])
  22. {
  23. $this->strictMode = $strictMode;
  24. foreach ($cookieArray as $cookie) {
  25. if (!($cookie instanceof SetCookie)) {
  26. $cookie = new SetCookie($cookie);
  27. }
  28. $this->setCookie($cookie);
  29. }
  30. }
  31. /**
  32. * Create a new Cookie jar from an associative array and domain.
  33. *
  34. * @param array $cookies Cookies to create the jar from
  35. * @param string $domain Domain to set the cookies to
  36. *
  37. * @return self
  38. */
  39. public static function fromArray(array $cookies, $domain)
  40. {
  41. $cookieJar = new self();
  42. foreach ($cookies as $name => $value) {
  43. $cookieJar->setCookie(new SetCookie([
  44. 'Domain' => $domain,
  45. 'Name' => $name,
  46. 'Value' => $value,
  47. 'Discard' => true
  48. ]));
  49. }
  50. return $cookieJar;
  51. }
  52. /**
  53. * Quote the cookie value if it is not already quoted and it contains
  54. * problematic characters.
  55. *
  56. * @param string $value Value that may or may not need to be quoted
  57. *
  58. * @return string
  59. */
  60. public static function getCookieValue($value)
  61. {
  62. if (substr($value, 0, 1) !== '"' &&
  63. substr($value, -1, 1) !== '"' &&
  64. strpbrk($value, ';,=')
  65. ) {
  66. $value = '"' . $value . '"';
  67. }
  68. return $value;
  69. }
  70. /**
  71. * Evaluate if this cookie should be persisted to storage
  72. * that survives between requests.
  73. *
  74. * @param SetCookie $cookie Being evaluated.
  75. * @param bool $allowSessionCookies If we should presist session cookies
  76. * @return bool
  77. */
  78. public static function shouldPersist(
  79. SetCookie $cookie,
  80. $allowSessionCookies = false
  81. ) {
  82. if ($cookie->getExpires() || $allowSessionCookies) {
  83. if (!$cookie->getDiscard()) {
  84. return true;
  85. }
  86. }
  87. return false;
  88. }
  89. public function toArray()
  90. {
  91. return array_map(function (SetCookie $cookie) {
  92. return $cookie->toArray();
  93. }, $this->getIterator()->getArrayCopy());
  94. }
  95. public function clear($domain = null, $path = null, $name = null)
  96. {
  97. if (!$domain) {
  98. $this->cookies = [];
  99. return;
  100. } elseif (!$path) {
  101. $this->cookies = array_filter(
  102. $this->cookies,
  103. function (SetCookie $cookie) use ($path, $domain) {
  104. return !$cookie->matchesDomain($domain);
  105. }
  106. );
  107. } elseif (!$name) {
  108. $this->cookies = array_filter(
  109. $this->cookies,
  110. function (SetCookie $cookie) use ($path, $domain) {
  111. return !($cookie->matchesPath($path) &&
  112. $cookie->matchesDomain($domain));
  113. }
  114. );
  115. } else {
  116. $this->cookies = array_filter(
  117. $this->cookies,
  118. function (SetCookie $cookie) use ($path, $domain, $name) {
  119. return !($cookie->getName() == $name &&
  120. $cookie->matchesPath($path) &&
  121. $cookie->matchesDomain($domain));
  122. }
  123. );
  124. }
  125. }
  126. public function clearSessionCookies()
  127. {
  128. $this->cookies = array_filter(
  129. $this->cookies,
  130. function (SetCookie $cookie) {
  131. return !$cookie->getDiscard() && $cookie->getExpires();
  132. }
  133. );
  134. }
  135. public function setCookie(SetCookie $cookie)
  136. {
  137. // If the name string is empty (but not 0), ignore the set-cookie
  138. // string entirely.
  139. $name = $cookie->getName();
  140. if (!$name && $name !== '0') {
  141. return false;
  142. }
  143. // Only allow cookies with set and valid domain, name, value
  144. $result = $cookie->validate();
  145. if ($result !== true) {
  146. if ($this->strictMode) {
  147. throw new \RuntimeException('Invalid cookie: ' . $result);
  148. } else {
  149. $this->removeCookieIfEmpty($cookie);
  150. return false;
  151. }
  152. }
  153. // Resolve conflicts with previously set cookies
  154. foreach ($this->cookies as $i => $c) {
  155. // Two cookies are identical, when their path, and domain are
  156. // identical.
  157. if ($c->getPath() != $cookie->getPath() ||
  158. $c->getDomain() != $cookie->getDomain() ||
  159. $c->getName() != $cookie->getName()
  160. ) {
  161. continue;
  162. }
  163. // The previously set cookie is a discard cookie and this one is
  164. // not so allow the new cookie to be set
  165. if (!$cookie->getDiscard() && $c->getDiscard()) {
  166. unset($this->cookies[$i]);
  167. continue;
  168. }
  169. // If the new cookie's expiration is further into the future, then
  170. // replace the old cookie
  171. if ($cookie->getExpires() > $c->getExpires()) {
  172. unset($this->cookies[$i]);
  173. continue;
  174. }
  175. // If the value has changed, we better change it
  176. if ($cookie->getValue() !== $c->getValue()) {
  177. unset($this->cookies[$i]);
  178. continue;
  179. }
  180. // The cookie exists, so no need to continue
  181. return false;
  182. }
  183. $this->cookies[] = $cookie;
  184. return true;
  185. }
  186. public function count()
  187. {
  188. return count($this->cookies);
  189. }
  190. public function getIterator()
  191. {
  192. return new \ArrayIterator(array_values($this->cookies));
  193. }
  194. public function extractCookies(
  195. RequestInterface $request,
  196. ResponseInterface $response
  197. ) {
  198. if ($cookieHeader = $response->getHeader('Set-Cookie')) {
  199. foreach ($cookieHeader as $cookie) {
  200. $sc = SetCookie::fromString($cookie);
  201. if (!$sc->getDomain()) {
  202. $sc->setDomain($request->getUri()->getHost());
  203. }
  204. $this->setCookie($sc);
  205. }
  206. }
  207. }
  208. public function withCookieHeader(RequestInterface $request)
  209. {
  210. $values = [];
  211. $uri = $request->getUri();
  212. $scheme = $uri->getScheme();
  213. $host = $uri->getHost();
  214. $path = $uri->getPath() ?: '/';
  215. foreach ($this->cookies as $cookie) {
  216. if ($cookie->matchesPath($path) &&
  217. $cookie->matchesDomain($host) &&
  218. !$cookie->isExpired() &&
  219. (!$cookie->getSecure() || $scheme == 'https')
  220. ) {
  221. $values[] = $cookie->getName() . '='
  222. . self::getCookieValue($cookie->getValue());
  223. }
  224. }
  225. return $values
  226. ? $request->withHeader('Cookie', implode('; ', $values))
  227. : $request;
  228. }
  229. /**
  230. * If a cookie already exists and the server asks to set it again with a
  231. * null value, the cookie must be deleted.
  232. *
  233. * @param SetCookie $cookie
  234. */
  235. private function removeCookieIfEmpty(SetCookie $cookie)
  236. {
  237. $cookieValue = $cookie->getValue();
  238. if ($cookieValue === null || $cookieValue === '') {
  239. $this->clear(
  240. $cookie->getDomain(),
  241. $cookie->getPath(),
  242. $cookie->getName()
  243. );
  244. }
  245. }
  246. }