CookieJar.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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-2012 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-2012 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. * @param boolean $encodeValue
  112. */
  113. public function addCookie($cookie, $ref_uri = null, $encodeValue = true)
  114. {
  115. if (is_string($cookie)) {
  116. $cookie = Zend_Http_Cookie::fromString($cookie, $ref_uri, $encodeValue);
  117. }
  118. if ($cookie instanceof Zend_Http_Cookie) {
  119. $domain = $cookie->getDomain();
  120. $path = $cookie->getPath();
  121. if (! isset($this->cookies[$domain])) $this->cookies[$domain] = array();
  122. if (! isset($this->cookies[$domain][$path])) $this->cookies[$domain][$path] = array();
  123. $this->cookies[$domain][$path][$cookie->getName()] = $cookie;
  124. $this->_rawCookies[] = $cookie;
  125. } else {
  126. require_once 'Zend/Http/Exception.php';
  127. throw new Zend_Http_Exception('Supplient argument is not a valid cookie string or object');
  128. }
  129. }
  130. /**
  131. * Parse an HTTP response, adding all the cookies set in that response
  132. * to the cookie jar.
  133. *
  134. * @param Zend_Http_Response $response
  135. * @param Zend_Uri_Http|string $ref_uri Requested URI
  136. * @param boolean $encodeValue
  137. */
  138. public function addCookiesFromResponse($response, $ref_uri, $encodeValue = true)
  139. {
  140. if (! $response instanceof Zend_Http_Response) {
  141. require_once 'Zend/Http/Exception.php';
  142. throw new Zend_Http_Exception('$response is expected to be a Response object, ' .
  143. gettype($response) . ' was passed');
  144. }
  145. $cookie_hdrs = $response->getHeader('Set-Cookie');
  146. if (is_array($cookie_hdrs)) {
  147. foreach ($cookie_hdrs as $cookie) {
  148. $this->addCookie($cookie, $ref_uri, $encodeValue);
  149. }
  150. } elseif (is_string($cookie_hdrs)) {
  151. $this->addCookie($cookie_hdrs, $ref_uri, $encodeValue);
  152. }
  153. }
  154. /**
  155. * Get all cookies in the cookie jar as an array
  156. *
  157. * @param int $ret_as Whether to return cookies as objects of Zend_Http_Cookie or as strings
  158. * @return array|string
  159. */
  160. public function getAllCookies($ret_as = self::COOKIE_OBJECT)
  161. {
  162. $cookies = $this->_flattenCookiesArray($this->cookies, $ret_as);
  163. return $cookies;
  164. }
  165. /**
  166. * Return an array of all cookies matching a specific request according to the request URI,
  167. * whether session cookies should be sent or not, and the time to consider as "now" when
  168. * checking cookie expiry time.
  169. *
  170. * @param string|Zend_Uri_Http $uri URI to check against (secure, domain, path)
  171. * @param boolean $matchSessionCookies Whether to send session cookies
  172. * @param int $ret_as Whether to return cookies as objects of Zend_Http_Cookie or as strings
  173. * @param int $now Override the current time when checking for expiry time
  174. * @return array|string
  175. */
  176. public function getMatchingCookies($uri, $matchSessionCookies = true,
  177. $ret_as = self::COOKIE_OBJECT, $now = null)
  178. {
  179. if (is_string($uri)) $uri = Zend_Uri::factory($uri);
  180. if (! $uri instanceof Zend_Uri_Http) {
  181. require_once 'Zend/Http/Exception.php';
  182. throw new Zend_Http_Exception("Invalid URI string or object passed");
  183. }
  184. // First, reduce the array of cookies to only those matching domain and path
  185. $cookies = $this->_matchDomain($uri->getHost());
  186. $cookies = $this->_matchPath($cookies, $uri->getPath());
  187. $cookies = $this->_flattenCookiesArray($cookies, self::COOKIE_OBJECT);
  188. // Next, run Cookie->match on all cookies to check secure, time and session mathcing
  189. $ret = array();
  190. foreach ($cookies as $cookie)
  191. if ($cookie->match($uri, $matchSessionCookies, $now))
  192. $ret[] = $cookie;
  193. // Now, use self::_flattenCookiesArray again - only to convert to the return format ;)
  194. $ret = $this->_flattenCookiesArray($ret, $ret_as);
  195. return $ret;
  196. }
  197. /**
  198. * Get a specific cookie according to a URI and name
  199. *
  200. * @param Zend_Uri_Http|string $uri The uri (domain and path) to match
  201. * @param string $cookie_name The cookie's name
  202. * @param int $ret_as Whether to return cookies as objects of Zend_Http_Cookie or as strings
  203. * @return Zend_Http_Cookie|string
  204. */
  205. public function getCookie($uri, $cookie_name, $ret_as = self::COOKIE_OBJECT)
  206. {
  207. if (is_string($uri)) {
  208. $uri = Zend_Uri::factory($uri);
  209. }
  210. if (! $uri instanceof Zend_Uri_Http) {
  211. require_once 'Zend/Http/Exception.php';
  212. throw new Zend_Http_Exception('Invalid URI specified');
  213. }
  214. // Get correct cookie path
  215. $path = $uri->getPath();
  216. $path = substr($path, 0, strrpos($path, '/'));
  217. if (! $path) $path = '/';
  218. if (isset($this->cookies[$uri->getHost()][$path][$cookie_name])) {
  219. $cookie = $this->cookies[$uri->getHost()][$path][$cookie_name];
  220. switch ($ret_as) {
  221. case self::COOKIE_OBJECT:
  222. return $cookie;
  223. break;
  224. case self::COOKIE_STRING_ARRAY:
  225. case self::COOKIE_STRING_CONCAT:
  226. return $cookie->__toString();
  227. break;
  228. default:
  229. require_once 'Zend/Http/Exception.php';
  230. throw new Zend_Http_Exception("Invalid value passed for \$ret_as: {$ret_as}");
  231. break;
  232. }
  233. } else {
  234. return false;
  235. }
  236. }
  237. /**
  238. * Helper function to recursivly flatten an array. Shoud be used when exporting the
  239. * cookies array (or parts of it)
  240. *
  241. * @param Zend_Http_Cookie|array $ptr
  242. * @param int $ret_as What value to return
  243. * @return array|string
  244. */
  245. protected function _flattenCookiesArray($ptr, $ret_as = self::COOKIE_OBJECT) {
  246. if (is_array($ptr)) {
  247. $ret = ($ret_as == self::COOKIE_STRING_CONCAT ? '' : array());
  248. foreach ($ptr as $item) {
  249. if ($ret_as == self::COOKIE_STRING_CONCAT) {
  250. $ret .= $this->_flattenCookiesArray($item, $ret_as);
  251. } else {
  252. $ret = array_merge($ret, $this->_flattenCookiesArray($item, $ret_as));
  253. }
  254. }
  255. return $ret;
  256. } elseif ($ptr instanceof Zend_Http_Cookie) {
  257. switch ($ret_as) {
  258. case self::COOKIE_STRING_ARRAY:
  259. return array($ptr->__toString());
  260. break;
  261. case self::COOKIE_STRING_CONCAT:
  262. return $ptr->__toString();
  263. break;
  264. case self::COOKIE_OBJECT:
  265. default:
  266. return array($ptr);
  267. break;
  268. }
  269. }
  270. return null;
  271. }
  272. /**
  273. * Return a subset of the cookies array matching a specific domain
  274. *
  275. * @param string $domain
  276. * @return array
  277. */
  278. protected function _matchDomain($domain)
  279. {
  280. $ret = array();
  281. foreach (array_keys($this->cookies) as $cdom) {
  282. if (Zend_Http_Cookie::matchCookieDomain($cdom, $domain)) {
  283. $ret[$cdom] = $this->cookies[$cdom];
  284. }
  285. }
  286. return $ret;
  287. }
  288. /**
  289. * Return a subset of a domain-matching cookies that also match a specified path
  290. *
  291. * @param array $dom_array
  292. * @param string $path
  293. * @return array
  294. */
  295. protected function _matchPath($domains, $path)
  296. {
  297. $ret = array();
  298. foreach ($domains as $dom => $paths_array) {
  299. foreach (array_keys($paths_array) as $cpath) {
  300. if (Zend_Http_Cookie::matchCookiePath($cpath, $path)) {
  301. if (! isset($ret[$dom])) {
  302. $ret[$dom] = array();
  303. }
  304. $ret[$dom][$cpath] = $paths_array[$cpath];
  305. }
  306. }
  307. }
  308. return $ret;
  309. }
  310. /**
  311. * Create a new CookieJar object and automatically load into it all the
  312. * cookies set in an Http_Response object. If $uri is set, it will be
  313. * considered as the requested URI for setting default domain and path
  314. * of the cookie.
  315. *
  316. * @param Zend_Http_Response $response HTTP Response object
  317. * @param Zend_Uri_Http|string $uri The requested URI
  318. * @return Zend_Http_CookieJar
  319. * @todo Add the $uri functionality.
  320. */
  321. public static function fromResponse(Zend_Http_Response $response, $ref_uri)
  322. {
  323. $jar = new self();
  324. $jar->addCookiesFromResponse($response, $ref_uri);
  325. return $jar;
  326. }
  327. /**
  328. * Required by Countable interface
  329. *
  330. * @return int
  331. */
  332. public function count()
  333. {
  334. return count($this->_rawCookies);
  335. }
  336. /**
  337. * Required by IteratorAggregate interface
  338. *
  339. * @return ArrayIterator
  340. */
  341. public function getIterator()
  342. {
  343. return new ArrayIterator($this->_rawCookies);
  344. }
  345. /**
  346. * Tells if the jar is empty of any cookie
  347. *
  348. * @return bool
  349. */
  350. public function isEmpty()
  351. {
  352. return count($this) == 0;
  353. }
  354. /**
  355. * Empties the cookieJar of any cookie
  356. *
  357. * @return Zend_Http_CookieJar
  358. */
  359. public function reset()
  360. {
  361. $this->cookies = $this->_rawCookies = array();
  362. return $this;
  363. }
  364. }