Sin descripción

CookieJar.php 9.1KB

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