CookieJar.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Http
  17. * @subpackage CookieJar
  18. * @version $Id$
  19. * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
  20. * @license http://framework.zend.com/license/new-bsd New BSD License
  21. */
  22. /**
  23. * @see Zend_Uri
  24. */
  25. require_once "Zend/Uri.php";
  26. /**
  27. * @see Zend_Http_Cookie
  28. */
  29. require_once "Zend/Http/Cookie.php";
  30. /**
  31. * @see Zend_Http_Response
  32. */
  33. require_once "Zend/Http/Response.php";
  34. /**
  35. * A Zend_Http_CookieJar object is designed to contain and maintain HTTP cookies, and should
  36. * be used along with Zend_Http_Client in order to manage cookies across HTTP requests and
  37. * responses.
  38. *
  39. * The class contains an array of Zend_Http_Cookie objects. Cookies can be added to the jar
  40. * automatically from a request or manually. Then, the jar can find and return the cookies
  41. * needed for a specific HTTP request.
  42. *
  43. * A special parameter can be passed to all methods of this class that return cookies: Cookies
  44. * can be returned either in their native form (as Zend_Http_Cookie objects) or as strings -
  45. * the later is suitable for sending as the value of the "Cookie" header in an HTTP request.
  46. * You can also choose, when returning more than one cookie, whether to get an array of strings
  47. * (by passing Zend_Http_CookieJar::COOKIE_STRING_ARRAY) or one unified string for all cookies
  48. * (by passing Zend_Http_CookieJar::COOKIE_STRING_CONCAT).
  49. *
  50. * @link http://wp.netscape.com/newsref/std/cookie_spec.html for some specs.
  51. *
  52. * @category Zend
  53. * @package Zend_Http
  54. * @subpackage CookieJar
  55. * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
  56. * @license http://framework.zend.com/license/new-bsd New BSD License
  57. */
  58. class Zend_Http_CookieJar implements Countable, IteratorAggregate
  59. {
  60. /**
  61. * Return cookie(s) as a Zend_Http_Cookie object
  62. *
  63. */
  64. const COOKIE_OBJECT = 0;
  65. /**
  66. * Return cookie(s) as a string (suitable for sending in an HTTP request)
  67. *
  68. */
  69. const COOKIE_STRING_ARRAY = 1;
  70. /**
  71. * Return all cookies as one long string (suitable for sending in an HTTP request)
  72. *
  73. */
  74. const COOKIE_STRING_CONCAT = 2;
  75. /**
  76. * Array storing cookies
  77. *
  78. * Cookies are stored according to domain and path:
  79. * $cookies
  80. * + www.mydomain.com
  81. * + /
  82. * - cookie1
  83. * - cookie2
  84. * + /somepath
  85. * - othercookie
  86. * + www.otherdomain.net
  87. * + /
  88. * - alsocookie
  89. *
  90. * @var array
  91. */
  92. protected $cookies = array();
  93. /**
  94. * The Zend_Http_Cookie array
  95. *
  96. * @var array
  97. */
  98. protected $_rawCookies = array();
  99. /**
  100. * Construct a new CookieJar object
  101. *
  102. */
  103. public function __construct()
  104. { }
  105. /**
  106. * Add a cookie to the jar. Cookie should be passed either as a Zend_Http_Cookie object
  107. * or as a string - in which case an object is created from the string.
  108. *
  109. * @param Zend_Http_Cookie|string $cookie
  110. * @param Zend_Uri_Http|string $ref_uri Optional reference URI (for domain, path, secure)
  111. */
  112. public function addCookie($cookie, $ref_uri = null)
  113. {
  114. if (is_string($cookie)) {
  115. $cookie = Zend_Http_Cookie::fromString($cookie, $ref_uri);
  116. }
  117. if ($cookie instanceof Zend_Http_Cookie) {
  118. $domain = $cookie->getDomain();
  119. $path = $cookie->getPath();
  120. if (! isset($this->cookies[$domain])) $this->cookies[$domain] = array();
  121. if (! isset($this->cookies[$domain][$path])) $this->cookies[$domain][$path] = array();
  122. $this->cookies[$domain][$path][$cookie->getName()] = $cookie;
  123. $this->_rawCookies[] = $cookie;
  124. } else {
  125. require_once 'Zend/Http/Exception.php';
  126. throw new Zend_Http_Exception('Supplient argument is not a valid cookie string or object');
  127. }
  128. }
  129. /**
  130. * Parse an HTTP response, adding all the cookies set in that response
  131. * to the cookie jar.
  132. *
  133. * @param Zend_Http_Response $response
  134. * @param Zend_Uri_Http|string $ref_uri Requested URI
  135. */
  136. public function addCookiesFromResponse($response, $ref_uri)
  137. {
  138. if (! $response instanceof Zend_Http_Response) {
  139. require_once 'Zend/Http/Exception.php';
  140. throw new Zend_Http_Exception('$response is expected to be a Response object, ' .
  141. gettype($response) . ' was passed');
  142. }
  143. $cookie_hdrs = $response->getHeader('Set-Cookie');
  144. if (is_array($cookie_hdrs)) {
  145. foreach ($cookie_hdrs as $cookie) {
  146. $this->addCookie($cookie, $ref_uri);
  147. }
  148. } elseif (is_string($cookie_hdrs)) {
  149. $this->addCookie($cookie_hdrs, $ref_uri);
  150. }
  151. }
  152. /**
  153. * Get all cookies in the cookie jar as an array
  154. *
  155. * @param int $ret_as Whether to return cookies as objects of Zend_Http_Cookie or as strings
  156. * @return array|string
  157. */
  158. public function getAllCookies($ret_as = self::COOKIE_OBJECT)
  159. {
  160. $cookies = $this->_flattenCookiesArray($this->cookies, $ret_as);
  161. return $cookies;
  162. }
  163. /**
  164. * Return an array of all cookies matching a specific request according to the request URI,
  165. * whether session cookies should be sent or not, and the time to consider as "now" when
  166. * checking cookie expiry time.
  167. *
  168. * @param string|Zend_Uri_Http $uri URI to check against (secure, domain, path)
  169. * @param boolean $matchSessionCookies Whether to send session cookies
  170. * @param int $ret_as Whether to return cookies as objects of Zend_Http_Cookie or as strings
  171. * @param int $now Override the current time when checking for expiry time
  172. * @return array|string
  173. */
  174. public function getMatchingCookies($uri, $matchSessionCookies = true,
  175. $ret_as = self::COOKIE_OBJECT, $now = null)
  176. {
  177. if (is_string($uri)) $uri = Zend_Uri::factory($uri);
  178. if (! $uri instanceof Zend_Uri_Http) {
  179. require_once 'Zend/Http/Exception.php';
  180. throw new Zend_Http_Exception("Invalid URI string or object passed");
  181. }
  182. // First, reduce the array of cookies to only those matching domain and path
  183. $cookies = $this->_matchDomain($uri->getHost());
  184. $cookies = $this->_matchPath($cookies, $uri->getPath());
  185. $cookies = $this->_flattenCookiesArray($cookies, self::COOKIE_OBJECT);
  186. // Next, run Cookie->match on all cookies to check secure, time and session mathcing
  187. $ret = array();
  188. foreach ($cookies as $cookie)
  189. if ($cookie->match($uri, $matchSessionCookies, $now))
  190. $ret[] = $cookie;
  191. // Now, use self::_flattenCookiesArray again - only to convert to the return format ;)
  192. $ret = $this->_flattenCookiesArray($ret, $ret_as);
  193. return $ret;
  194. }
  195. /**
  196. * Get a specific cookie according to a URI and name
  197. *
  198. * @param Zend_Uri_Http|string $uri The uri (domain and path) to match
  199. * @param string $cookie_name The cookie's name
  200. * @param int $ret_as Whether to return cookies as objects of Zend_Http_Cookie or as strings
  201. * @return Zend_Http_Cookie|string
  202. */
  203. public function getCookie($uri, $cookie_name, $ret_as = self::COOKIE_OBJECT)
  204. {
  205. if (is_string($uri)) {
  206. $uri = Zend_Uri::factory($uri);
  207. }
  208. if (! $uri instanceof Zend_Uri_Http) {
  209. require_once 'Zend/Http/Exception.php';
  210. throw new Zend_Http_Exception('Invalid URI specified');
  211. }
  212. // Get correct cookie path
  213. $path = $uri->getPath();
  214. $path = substr($path, 0, strrpos($path, '/'));
  215. if (! $path) $path = '/';
  216. if (isset($this->cookies[$uri->getHost()][$path][$cookie_name])) {
  217. $cookie = $this->cookies[$uri->getHost()][$path][$cookie_name];
  218. switch ($ret_as) {
  219. case self::COOKIE_OBJECT:
  220. return $cookie;
  221. break;
  222. case self::COOKIE_STRING_ARRAY:
  223. case self::COOKIE_STRING_CONCAT:
  224. return $cookie->__toString();
  225. break;
  226. default:
  227. require_once 'Zend/Http/Exception.php';
  228. throw new Zend_Http_Exception("Invalid value passed for \$ret_as: {$ret_as}");
  229. break;
  230. }
  231. } else {
  232. return false;
  233. }
  234. }
  235. /**
  236. * Helper function to recursivly flatten an array. Shoud be used when exporting the
  237. * cookies array (or parts of it)
  238. *
  239. * @param Zend_Http_Cookie|array $ptr
  240. * @param int $ret_as What value to return
  241. * @return array|string
  242. */
  243. protected function _flattenCookiesArray($ptr, $ret_as = self::COOKIE_OBJECT) {
  244. if (is_array($ptr)) {
  245. $ret = ($ret_as == self::COOKIE_STRING_CONCAT ? '' : array());
  246. foreach ($ptr as $item) {
  247. if ($ret_as == self::COOKIE_STRING_CONCAT) {
  248. $ret .= $this->_flattenCookiesArray($item, $ret_as);
  249. } else {
  250. $ret = array_merge($ret, $this->_flattenCookiesArray($item, $ret_as));
  251. }
  252. }
  253. return $ret;
  254. } elseif ($ptr instanceof Zend_Http_Cookie) {
  255. switch ($ret_as) {
  256. case self::COOKIE_STRING_ARRAY:
  257. return array($ptr->__toString());
  258. break;
  259. case self::COOKIE_STRING_CONCAT:
  260. return $ptr->__toString();
  261. break;
  262. case self::COOKIE_OBJECT:
  263. default:
  264. return array($ptr);
  265. break;
  266. }
  267. }
  268. return null;
  269. }
  270. /**
  271. * Return a subset of the cookies array matching a specific domain
  272. *
  273. * @param string $domain
  274. * @return array
  275. */
  276. protected function _matchDomain($domain)
  277. {
  278. $ret = array();
  279. foreach (array_keys($this->cookies) as $cdom) {
  280. if (Zend_Http_Cookie::matchCookieDomain($cdom, $domain)) {
  281. $ret[$cdom] = $this->cookies[$cdom];
  282. }
  283. }
  284. return $ret;
  285. }
  286. /**
  287. * Return a subset of a domain-matching cookies that also match a specified path
  288. *
  289. * @param array $dom_array
  290. * @param string $path
  291. * @return array
  292. */
  293. protected function _matchPath($domains, $path)
  294. {
  295. $ret = array();
  296. foreach ($domains as $dom => $paths_array) {
  297. foreach (array_keys($paths_array) as $cpath) {
  298. if (Zend_Http_Cookie::matchCookiePath($cpath, $path)) {
  299. if (! isset($ret[$dom])) {
  300. $ret[$dom] = array();
  301. }
  302. $ret[$dom][$cpath] = $paths_array[$cpath];
  303. }
  304. }
  305. }
  306. return $ret;
  307. }
  308. /**
  309. * Create a new CookieJar object and automatically load into it all the
  310. * cookies set in an Http_Response object. If $uri is set, it will be
  311. * considered as the requested URI for setting default domain and path
  312. * of the cookie.
  313. *
  314. * @param Zend_Http_Response $response HTTP Response object
  315. * @param Zend_Uri_Http|string $uri The requested URI
  316. * @return Zend_Http_CookieJar
  317. * @todo Add the $uri functionality.
  318. */
  319. public static function fromResponse(Zend_Http_Response $response, $ref_uri)
  320. {
  321. $jar = new self();
  322. $jar->addCookiesFromResponse($response, $ref_uri);
  323. return $jar;
  324. }
  325. /**
  326. * Required by Countable interface
  327. *
  328. * @return int
  329. */
  330. public function count()
  331. {
  332. return count($this->_rawCookies);
  333. }
  334. /**
  335. * Required by IteratorAggregate interface
  336. *
  337. * @return ArrayIterator
  338. */
  339. public function getIterator()
  340. {
  341. return new ArrayIterator($this->_rawCookies);
  342. }
  343. /**
  344. * Tells if the jar is empty of any cookie
  345. *
  346. * @return bool
  347. */
  348. public function isEmpty()
  349. {
  350. return count($this) == 0;
  351. }
  352. /**
  353. * Empties the cookieJar of any cookie
  354. *
  355. * @return Zend_Http_CookieJar
  356. */
  357. public function reset()
  358. {
  359. $this->cookies = $this->_rawCookies = array();
  360. return $this;
  361. }
  362. }