Cache.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. <?php
  2. /**
  3. * HTTP Caching adaptor class that provides caching services to the
  4. * [Request_Client] class, using HTTP cache control logic as defined in
  5. * RFC 2616.
  6. *
  7. * @package Kohana
  8. * @category Base
  9. * @author Kohana Team
  10. * @copyright (c) Kohana Team
  11. * @license https://koseven.ga/LICENSE.md
  12. * @since 3.2.0
  13. */
  14. class Kohana_HTTP_Cache {
  15. const CACHE_STATUS_KEY = 'x-cache-status';
  16. const CACHE_STATUS_SAVED = 'SAVED';
  17. const CACHE_STATUS_HIT = 'HIT';
  18. const CACHE_STATUS_MISS = 'MISS';
  19. const CACHE_HIT_KEY = 'x-cache-hits';
  20. /**
  21. * Factory method for HTTP_Cache that provides a convenient dependency
  22. * injector for the Cache library.
  23. *
  24. * // Create HTTP_Cache with named cache engine
  25. * $http_cache = HTTP_Cache::factory('memcache', array(
  26. * 'allow_private_cache' => FALSE
  27. * )
  28. * );
  29. *
  30. * // Create HTTP_Cache with supplied cache engine
  31. * $http_cache = HTTP_Cache::factory(Cache::instance('memcache'),
  32. * array(
  33. * 'allow_private_cache' => FALSE
  34. * )
  35. * );
  36. *
  37. * @uses Cache
  38. * @param mixed $cache cache engine to use
  39. * @param array $options options to set to this class
  40. * @return HTTP_Cache
  41. */
  42. public static function factory($cache, array $options = [])
  43. {
  44. if ( ! $cache instanceof Cache)
  45. {
  46. $cache = Cache::instance($cache);
  47. }
  48. $options['cache'] = $cache;
  49. return new HTTP_Cache($options);
  50. }
  51. /**
  52. * Basic cache key generator that hashes the entire request and returns
  53. * it. This is fine for static content, or dynamic content where user
  54. * specific information is encoded into the request.
  55. *
  56. * // Generate cache key
  57. * $cache_key = HTTP_Cache::basic_cache_key_generator($request);
  58. *
  59. * @param Request $request
  60. * @return string
  61. */
  62. public static function basic_cache_key_generator(Request $request)
  63. {
  64. $uri = $request->uri();
  65. $query = $request->query();
  66. $headers = $request->headers()->getArrayCopy();
  67. $body = $request->body();
  68. return sha1($uri.'?'.http_build_query($query, NULL, '&').'~'.implode('~', $headers).'~'.$body);
  69. }
  70. /**
  71. * @var Cache cache driver to use for HTTP caching
  72. */
  73. protected $_cache;
  74. /**
  75. * @var callback Cache key generator callback
  76. */
  77. protected $_cache_key_callback;
  78. /**
  79. * @var boolean Defines whether this client should cache `private` cache directives
  80. * @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9
  81. */
  82. protected $_allow_private_cache = FALSE;
  83. /**
  84. * @var int The timestamp of the request
  85. */
  86. protected $_request_time;
  87. /**
  88. * @var int The timestamp of the response
  89. */
  90. protected $_response_time;
  91. /**
  92. * Constructor method for this class. Allows dependency injection of the
  93. * required components such as `Cache` and the cache key generator.
  94. *
  95. * @param array $options
  96. */
  97. public function __construct(array $options = [])
  98. {
  99. foreach ($options as $key => $value)
  100. {
  101. if (method_exists($this, $key))
  102. {
  103. $this->$key($value);
  104. }
  105. }
  106. if ($this->_cache_key_callback === NULL)
  107. {
  108. $this->cache_key_callback('HTTP_Cache::basic_cache_key_generator');
  109. }
  110. }
  111. /**
  112. * Executes the supplied [Request] with the supplied [Request_Client].
  113. * Before execution, the HTTP_Cache adapter checks the request type,
  114. * destructive requests such as `POST`, `PUT` and `DELETE` will bypass
  115. * cache completely and ensure the response is not cached. All other
  116. * Request methods will allow caching, if the rules are met.
  117. *
  118. * @param Request_Client $client client to execute with Cache-Control
  119. * @param Request $request request to execute with client
  120. * @return [Response]
  121. */
  122. public function execute(Request_Client $client, Request $request, Response $response)
  123. {
  124. if ( ! $this->_cache instanceof Cache)
  125. return $client->execute_request($request, $response);
  126. // If this is a destructive request, by-pass cache completely
  127. if (in_array($request->method(), [
  128. HTTP_Request::POST,
  129. HTTP_Request::PUT,
  130. HTTP_Request::DELETE]))
  131. {
  132. // Kill existing caches for this request
  133. $this->invalidate_cache($request);
  134. $response = $client->execute_request($request, $response);
  135. $cache_control = HTTP_Header::create_cache_control([
  136. 'no-cache',
  137. 'must-revalidate'
  138. ]);
  139. // Ensure client respects destructive action
  140. return $response->headers('cache-control', $cache_control);
  141. }
  142. // Create the cache key
  143. $cache_key = $this->create_cache_key($request, $this->_cache_key_callback);
  144. // Try and return cached version
  145. if (($cached_response = $this->cache_response($cache_key, $request)) instanceof Response)
  146. return $cached_response;
  147. // Start request time
  148. $this->_request_time = time();
  149. // Execute the request with the Request client
  150. $response = $client->execute_request($request, $response);
  151. // Stop response time
  152. $this->_response_time = (time() - $this->_request_time);
  153. // Cache the response
  154. $this->cache_response($cache_key, $request, $response);
  155. $response->headers(HTTP_Cache::CACHE_STATUS_KEY,
  156. HTTP_Cache::CACHE_STATUS_MISS);
  157. return $response;
  158. }
  159. /**
  160. * Invalidate a cached response for the [Request] supplied.
  161. * This has the effect of deleting the response from the
  162. * [Cache] entry.
  163. *
  164. * @param Request $request Response to remove from cache
  165. * @return void
  166. */
  167. public function invalidate_cache(Request $request)
  168. {
  169. if (($cache = $this->cache()) instanceof Cache)
  170. {
  171. $cache->delete($this->create_cache_key($request, $this->_cache_key_callback));
  172. }
  173. return;
  174. }
  175. /**
  176. * Getter and setter for the internal caching engine,
  177. * used to cache responses if available and valid.
  178. *
  179. * @param Kohana_Cache $cache engine to use for caching
  180. * @return Kohana_Cache
  181. * @return Kohana_Request_Client
  182. */
  183. public function cache(Cache $cache = NULL)
  184. {
  185. if ($cache === NULL)
  186. return $this->_cache;
  187. $this->_cache = $cache;
  188. return $this;
  189. }
  190. /**
  191. * Gets or sets the [Request_Client::allow_private_cache] setting.
  192. * If set to `TRUE`, the client will also cache cache-control directives
  193. * that have the `private` setting.
  194. *
  195. * @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9
  196. * @param boolean $setting allow caching of privately marked responses
  197. * @return boolean
  198. * @return [Request_Client]
  199. */
  200. public function allow_private_cache($setting = NULL)
  201. {
  202. if ($setting === NULL)
  203. return $this->_allow_private_cache;
  204. $this->_allow_private_cache = (bool) $setting;
  205. return $this;
  206. }
  207. /**
  208. * Sets or gets the cache key generator callback for this caching
  209. * class. The cache key generator provides a unique hash based on the
  210. * `Request` object passed to it.
  211. *
  212. * The default generator is [HTTP_Cache::basic_cache_key_generator()], which
  213. * serializes the entire `HTTP_Request` into a unique sha1 hash. This will
  214. * provide basic caching for static and simple dynamic pages. More complex
  215. * algorithms can be defined and then passed into `HTTP_Cache` using this
  216. * method.
  217. *
  218. * // Get the cache key callback
  219. * $callback = $http_cache->cache_key_callback();
  220. *
  221. * // Set the cache key callback
  222. * $http_cache->cache_key_callback('Foo::cache_key');
  223. *
  224. * // Alternatively, in PHP 5.3 use a closure
  225. * $http_cache->cache_key_callback(function (Request $request) {
  226. * return sha1($request->render());
  227. * });
  228. *
  229. * @param callback $callback
  230. * @return mixed
  231. * @throws HTTP_Exception
  232. */
  233. public function cache_key_callback($callback = NULL)
  234. {
  235. if ($callback === NULL)
  236. return $this->_cache_key_callback;
  237. if ( ! is_callable($callback))
  238. throw new Kohana_Exception('cache_key_callback must be callable!');
  239. $this->_cache_key_callback = $callback;
  240. return $this;
  241. }
  242. /**
  243. * Creates a cache key for the request to use for caching
  244. * [Kohana_Response] returned by [Request::execute].
  245. *
  246. * This is the default cache key generating logic, but can be overridden
  247. * by setting [HTTP_Cache::cache_key_callback()].
  248. *
  249. * @param Request $request request to create key for
  250. * @param callback $callback optional callback to use instead of built-in method
  251. * @return string
  252. */
  253. public function create_cache_key(Request $request, $callback = FALSE)
  254. {
  255. if (is_callable($callback))
  256. return call_user_func($callback, $request);
  257. else
  258. return HTTP_Cache::basic_cache_key_generator($request);
  259. }
  260. /**
  261. * Controls whether the response can be cached. Uses HTTP
  262. * protocol to determine whether the response can be cached.
  263. *
  264. * @link http://www.w3.org/Protocols/rfc2616/rfc2616.html RFC 2616
  265. * @param Response $response The Response
  266. * @return boolean
  267. */
  268. public function set_cache(Response $response)
  269. {
  270. $headers = $response->headers()->getArrayCopy();
  271. if ($cache_control = Arr::get($headers, 'cache-control'))
  272. {
  273. // Parse the cache control
  274. $cache_control = HTTP_Header::parse_cache_control($cache_control);
  275. // If the no-cache or no-store directive is set, return
  276. if (array_intersect($cache_control, ['no-cache', 'no-store']))
  277. return FALSE;
  278. // Check for private cache and get out of here if invalid
  279. if ( ! $this->_allow_private_cache AND in_array('private', $cache_control))
  280. {
  281. if ( ! isset($cache_control['s-maxage']))
  282. return FALSE;
  283. // If there is a s-maxage directive we can use that
  284. $cache_control['max-age'] = $cache_control['s-maxage'];
  285. }
  286. // Check that max-age has been set and if it is valid for caching
  287. if (isset($cache_control['max-age']) AND $cache_control['max-age'] < 1)
  288. return FALSE;
  289. }
  290. if ($expires = Arr::get($headers, 'expires') AND ! isset($cache_control['max-age']))
  291. {
  292. // Can't cache things that have expired already
  293. if (strtotime($expires) <= time())
  294. return FALSE;
  295. }
  296. return TRUE;
  297. }
  298. /**
  299. * Caches a [Response] using the supplied [Cache]
  300. * and the key generated by [Request_Client::_create_cache_key].
  301. *
  302. * If not response is supplied, the cache will be checked for an existing
  303. * one that is available.
  304. *
  305. * @param string $key the cache key to use
  306. * @param Request $request the HTTP Request
  307. * @param Response $response the HTTP Response
  308. * @return mixed
  309. */
  310. public function cache_response($key, Request $request, Response $response = NULL)
  311. {
  312. if ( ! $this->_cache instanceof Cache)
  313. return FALSE;
  314. // Check for Pragma: no-cache
  315. if ($pragma = $request->headers('pragma'))
  316. {
  317. if ($pragma == 'no-cache')
  318. return FALSE;
  319. elseif (is_array($pragma) AND in_array('no-cache', $pragma))
  320. return FALSE;
  321. }
  322. // If there is no response, lookup an existing cached response
  323. if ($response === NULL)
  324. {
  325. $response = $this->_cache->get($key);
  326. if ( ! $response instanceof Response)
  327. return FALSE;
  328. // Do cache hit arithmetic, using fast arithmetic if available
  329. if ($this->_cache instanceof Cache_Arithmetic)
  330. {
  331. $hit_count = $this->_cache->increment(HTTP_Cache::CACHE_HIT_KEY.$key);
  332. }
  333. else
  334. {
  335. $hit_count = $this->_cache->get(HTTP_Cache::CACHE_HIT_KEY.$key);
  336. $this->_cache->set(HTTP_Cache::CACHE_HIT_KEY.$key, ++$hit_count);
  337. }
  338. // Update the header to have correct HIT status and count
  339. $response->headers(HTTP_Cache::CACHE_STATUS_KEY,
  340. HTTP_Cache::CACHE_STATUS_HIT)
  341. ->headers(HTTP_Cache::CACHE_HIT_KEY, $hit_count);
  342. return $response;
  343. }
  344. else
  345. {
  346. if (($ttl = $this->cache_lifetime($response)) === FALSE)
  347. return FALSE;
  348. $response->headers(HTTP_Cache::CACHE_STATUS_KEY,
  349. HTTP_Cache::CACHE_STATUS_SAVED);
  350. // Set the hit count to zero
  351. $this->_cache->set(HTTP_Cache::CACHE_HIT_KEY.$key, 0);
  352. return $this->_cache->set($key, $response, $ttl);
  353. }
  354. }
  355. /**
  356. * Calculates the total Time To Live based on the specification
  357. * RFC 2616 cache lifetime rules.
  358. *
  359. * @param Response $response Response to evaluate
  360. * @return mixed TTL value or false if the response should not be cached
  361. */
  362. public function cache_lifetime(Response $response)
  363. {
  364. // Get out of here if this cannot be cached
  365. if ( ! $this->set_cache($response))
  366. return FALSE;
  367. // Calculate apparent age
  368. if ($date = $response->headers('date'))
  369. {
  370. $apparent_age = max(0, $this->_response_time - strtotime($date));
  371. }
  372. else
  373. {
  374. $apparent_age = max(0, $this->_response_time);
  375. }
  376. // Calculate corrected received age
  377. if ($age = $response->headers('age'))
  378. {
  379. $corrected_received_age = max($apparent_age, intval($age));
  380. }
  381. else
  382. {
  383. $corrected_received_age = $apparent_age;
  384. }
  385. // Corrected initial age
  386. $corrected_initial_age = $corrected_received_age + $this->request_execution_time();
  387. // Resident time
  388. $resident_time = time() - $this->_response_time;
  389. // Current age
  390. $current_age = $corrected_initial_age + $resident_time;
  391. // Prepare the cache freshness lifetime
  392. $ttl = NULL;
  393. // Cache control overrides
  394. if ($cache_control = $response->headers('cache-control'))
  395. {
  396. // Parse the cache control header
  397. $cache_control = HTTP_Header::parse_cache_control($cache_control);
  398. if (isset($cache_control['max-age']))
  399. {
  400. $ttl = $cache_control['max-age'];
  401. }
  402. if (isset($cache_control['s-maxage']) AND isset($cache_control['private']) AND $this->_allow_private_cache)
  403. {
  404. $ttl = $cache_control['s-maxage'];
  405. }
  406. if (isset($cache_control['max-stale']) AND ! isset($cache_control['must-revalidate']))
  407. {
  408. $ttl = $current_age + $cache_control['max-stale'];
  409. }
  410. }
  411. // If we have a TTL at this point, return
  412. if ($ttl !== NULL)
  413. return $ttl;
  414. if ($expires = $response->headers('expires'))
  415. return strtotime($expires) - $current_age;
  416. return FALSE;
  417. }
  418. /**
  419. * Returns the duration of the last request execution.
  420. * Either returns the time of completed requests or
  421. * `FALSE` if the request hasn't finished executing, or
  422. * is yet to be run.
  423. *
  424. * @return mixed
  425. */
  426. public function request_execution_time()
  427. {
  428. if ($this->_request_time === NULL OR $this->_response_time === NULL)
  429. return FALSE;
  430. return $this->_response_time - $this->_request_time;
  431. }
  432. } // End Kohana_HTTP_Cache