CookieJar.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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 as 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. * @deprecated
  54. */
  55. public static function getCookieValue($value)
  56. {
  57. return $value;
  58. }
  59. /**
  60. * Evaluate if this cookie should be persisted to storage
  61. * that survives between requests.
  62. *
  63. * @param SetCookie $cookie Being evaluated.
  64. * @param bool $allowSessionCookies If we should persist session cookies
  65. * @return bool
  66. */
  67. public static function shouldPersist(
  68. SetCookie $cookie,
  69. $allowSessionCookies = false
  70. ) {
  71. if ($cookie->getExpires() || $allowSessionCookies) {
  72. if (!$cookie->getDiscard()) {
  73. return true;
  74. }
  75. }
  76. return false;
  77. }
  78. /**
  79. * Finds and returns the cookie based on the name
  80. *
  81. * @param string $name cookie name to search for
  82. * @return SetCookie|null cookie that was found or null if not found
  83. */
  84. public function getCookieByName($name)
  85. {
  86. // don't allow a non string name
  87. if ($name === null || !is_scalar($name)) {
  88. return null;
  89. }
  90. foreach ($this->cookies as $cookie) {
  91. if ($cookie->getName() !== null && strcasecmp($cookie->getName(), $name) === 0) {
  92. return $cookie;
  93. }
  94. }
  95. return null;
  96. }
  97. public function toArray()
  98. {
  99. return array_map(function (SetCookie $cookie) {
  100. return $cookie->toArray();
  101. }, $this->getIterator()->getArrayCopy());
  102. }
  103. public function clear($domain = null, $path = null, $name = null)
  104. {
  105. if (!$domain) {
  106. $this->cookies = [];
  107. return;
  108. } elseif (!$path) {
  109. $this->cookies = array_filter(
  110. $this->cookies,
  111. function (SetCookie $cookie) use ($domain) {
  112. return !$cookie->matchesDomain($domain);
  113. }
  114. );
  115. } elseif (!$name) {
  116. $this->cookies = array_filter(
  117. $this->cookies,
  118. function (SetCookie $cookie) use ($path, $domain) {
  119. return !($cookie->matchesPath($path) &&
  120. $cookie->matchesDomain($domain));
  121. }
  122. );
  123. } else {
  124. $this->cookies = array_filter(
  125. $this->cookies,
  126. function (SetCookie $cookie) use ($path, $domain, $name) {
  127. return !($cookie->getName() == $name &&
  128. $cookie->matchesPath($path) &&
  129. $cookie->matchesDomain($domain));
  130. }
  131. );
  132. }
  133. }
  134. public function clearSessionCookies()
  135. {
  136. $this->cookies = array_filter(
  137. $this->cookies,
  138. function (SetCookie $cookie) {
  139. return !$cookie->getDiscard() && $cookie->getExpires();
  140. }
  141. );
  142. }
  143. public function setCookie(SetCookie $cookie)
  144. {
  145. // If the name string is empty (but not 0), ignore the set-cookie
  146. // string entirely.
  147. $name = $cookie->getName();
  148. if (!$name && $name !== '0') {
  149. return false;
  150. }
  151. // Only allow cookies with set and valid domain, name, value
  152. $result = $cookie->validate();
  153. if ($result !== true) {
  154. if ($this->strictMode) {
  155. throw new \RuntimeException('Invalid cookie: ' . $result);
  156. } else {
  157. $this->removeCookieIfEmpty($cookie);
  158. return false;
  159. }
  160. }
  161. // Resolve conflicts with previously set cookies
  162. foreach ($this->cookies as $i => $c) {
  163. // Two cookies are identical, when their path, and domain are
  164. // identical.
  165. if ($c->getPath() != $cookie->getPath() ||
  166. $c->getDomain() != $cookie->getDomain() ||
  167. $c->getName() != $cookie->getName()
  168. ) {
  169. continue;
  170. }
  171. // The previously set cookie is a discard cookie and this one is
  172. // not so allow the new cookie to be set
  173. if (!$cookie->getDiscard() && $c->getDiscard()) {
  174. unset($this->cookies[$i]);
  175. continue;
  176. }
  177. // If the new cookie's expiration is further into the future, then
  178. // replace the old cookie
  179. if ($cookie->getExpires() > $c->getExpires()) {
  180. unset($this->cookies[$i]);
  181. continue;
  182. }
  183. // If the value has changed, we better change it
  184. if ($cookie->getValue() !== $c->getValue()) {
  185. unset($this->cookies[$i]);
  186. continue;
  187. }
  188. // The cookie exists, so no need to continue
  189. return false;
  190. }
  191. $this->cookies[] = $cookie;
  192. return true;
  193. }
  194. public function count()
  195. {
  196. return count($this->cookies);
  197. }
  198. public function getIterator()
  199. {
  200. return new \ArrayIterator(array_values($this->cookies));
  201. }
  202. public function extractCookies(
  203. RequestInterface $request,
  204. ResponseInterface $response
  205. ) {
  206. if ($cookieHeader = $response->getHeader('Set-Cookie')) {
  207. foreach ($cookieHeader as $cookie) {
  208. $sc = SetCookie::fromString($cookie);
  209. if (!$sc->getDomain()) {
  210. $sc->setDomain($request->getUri()->getHost());
  211. }
  212. if (0 !== strpos($sc->getPath(), '/')) {
  213. $sc->setPath($this->getCookiePathFromRequest($request));
  214. }
  215. $this->setCookie($sc);
  216. }
  217. }
  218. }
  219. /**
  220. * Computes cookie path following RFC 6265 section 5.1.4
  221. *
  222. * @link https://tools.ietf.org/html/rfc6265#section-5.1.4
  223. *
  224. * @param RequestInterface $request
  225. * @return string
  226. */
  227. private function getCookiePathFromRequest(RequestInterface $request)
  228. {
  229. $uriPath = $request->getUri()->getPath();
  230. if ('' === $uriPath) {
  231. return '/';
  232. }
  233. if (0 !== strpos($uriPath, '/')) {
  234. return '/';
  235. }
  236. if ('/' === $uriPath) {
  237. return '/';
  238. }
  239. if (0 === $lastSlashPos = strrpos($uriPath, '/')) {
  240. return '/';
  241. }
  242. return substr($uriPath, 0, $lastSlashPos);
  243. }
  244. public function withCookieHeader(RequestInterface $request)
  245. {
  246. $values = [];
  247. $uri = $request->getUri();
  248. $scheme = $uri->getScheme();
  249. $host = $uri->getHost();
  250. $path = $uri->getPath() ?: '/';
  251. foreach ($this->cookies as $cookie) {
  252. if ($cookie->matchesPath($path) &&
  253. $cookie->matchesDomain($host) &&
  254. !$cookie->isExpired() &&
  255. (!$cookie->getSecure() || $scheme === 'https')
  256. ) {
  257. $values[] = $cookie->getName() . '='
  258. . $cookie->getValue();
  259. }
  260. }
  261. return $values
  262. ? $request->withHeader('Cookie', implode('; ', $values))
  263. : $request;
  264. }
  265. /**
  266. * If a cookie already exists and the server asks to set it again with a
  267. * null value, the cookie must be deleted.
  268. *
  269. * @param SetCookie $cookie
  270. */
  271. private function removeCookieIfEmpty(SetCookie $cookie)
  272. {
  273. $cookieValue = $cookie->getValue();
  274. if ($cookieValue === null || $cookieValue === '') {
  275. $this->clear(
  276. $cookie->getDomain(),
  277. $cookie->getPath(),
  278. $cookie->getName()
  279. );
  280. }
  281. }
  282. }