CookieJar.php 13 KB

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