smarty_cacheresource_keyvaluestore.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. <?php
  2. /**
  3. * Smarty Internal Plugin
  4. *
  5. * @package Smarty
  6. * @subpackage Cacher
  7. */
  8. /**
  9. * Smarty Cache Handler Base for Key/Value Storage Implementations
  10. * This class implements the functionality required to use simple key/value stores
  11. * for hierarchical cache groups. key/value stores like memcache or APC do not support
  12. * wildcards in keys, therefore a cache group cannot be cleared like "a|*" - which
  13. * is no problem to filesystem and RDBMS implementations.
  14. * This implementation is based on the concept of invalidation. While one specific cache
  15. * can be identified and cleared, any range of caches cannot be identified. For this reason
  16. * each level of the cache group hierarchy can have its own value in the store. These values
  17. * are nothing but microtimes, telling us when a particular cache group was cleared for the
  18. * last time. These keys are evaluated for every cache read to determine if the cache has
  19. * been invalidated since it was created and should hence be treated as inexistent.
  20. * Although deep hierarchies are possible, they are not recommended. Try to keep your
  21. * cache groups as shallow as possible. Anything up 3-5 parents should be ok. So
  22. * »a|b|c« is a good depth where »a|b|c|d|e|f|g|h|i|j|k« isn't. Try to join correlating
  23. * cache groups: if your cache groups look somewhat like »a|b|$page|$items|$whatever«
  24. * consider using »a|b|c|$page-$items-$whatever« instead.
  25. *
  26. * @package Smarty
  27. * @subpackage Cacher
  28. * @author Rodney Rehm
  29. */
  30. abstract class Smarty_CacheResource_KeyValueStore extends Smarty_CacheResource
  31. {
  32. /**
  33. * cache for contents
  34. *
  35. * @var array
  36. */
  37. protected $contents = array();
  38. /**
  39. * cache for timestamps
  40. *
  41. * @var array
  42. */
  43. protected $timestamps = array();
  44. /**
  45. * populate Cached Object with meta data from Resource
  46. *
  47. * @param Smarty_Template_Cached $cached cached object
  48. * @param Smarty_Internal_Template $_template template object
  49. *
  50. * @return void
  51. */
  52. public function populate(Smarty_Template_Cached $cached, Smarty_Internal_Template $_template)
  53. {
  54. $cached->filepath = $_template->source->uid . '#' . $this->sanitize($cached->source->resource) . '#' .
  55. $this->sanitize($cached->cache_id) . '#' . $this->sanitize($cached->compile_id);
  56. $this->populateTimestamp($cached);
  57. }
  58. /**
  59. * populate Cached Object with timestamp and exists from Resource
  60. *
  61. * @param Smarty_Template_Cached $cached cached object
  62. *
  63. * @return void
  64. */
  65. public function populateTimestamp(Smarty_Template_Cached $cached)
  66. {
  67. if (!$this->fetch($cached->filepath, $cached->source->name, $cached->cache_id, $cached->compile_id, $content,
  68. $timestamp, $cached->source->uid)
  69. ) {
  70. return;
  71. }
  72. $cached->content = $content;
  73. $cached->timestamp = (int) $timestamp;
  74. $cached->exists = !!$cached->timestamp;
  75. }
  76. /**
  77. * Read the cached template and process the header
  78. *
  79. * @param \Smarty_Internal_Template $_smarty_tpl do not change variable name, is used by compiled template
  80. * @param Smarty_Template_Cached $cached cached object
  81. * @param boolean $update flag if called because cache update
  82. *
  83. * @return boolean true or false if the cached content does not exist
  84. */
  85. public function process(Smarty_Internal_Template $_smarty_tpl, Smarty_Template_Cached $cached = null,
  86. $update = false)
  87. {
  88. if (!$cached) {
  89. $cached = $_smarty_tpl->cached;
  90. }
  91. $content = $cached->content ? $cached->content : null;
  92. $timestamp = $cached->timestamp ? $cached->timestamp : null;
  93. if ($content === null || !$timestamp) {
  94. if (!$this->fetch($_smarty_tpl->cached->filepath, $_smarty_tpl->source->name, $_smarty_tpl->cache_id,
  95. $_smarty_tpl->compile_id, $content, $timestamp, $_smarty_tpl->source->uid)
  96. ) {
  97. return false;
  98. }
  99. }
  100. if (isset($content)) {
  101. eval("?>" . $content);
  102. return true;
  103. }
  104. return false;
  105. }
  106. /**
  107. * Write the rendered template output to cache
  108. *
  109. * @param Smarty_Internal_Template $_template template object
  110. * @param string $content content to cache
  111. *
  112. * @return boolean success
  113. */
  114. public function writeCachedContent(Smarty_Internal_Template $_template, $content)
  115. {
  116. $this->addMetaTimestamp($content);
  117. return $this->write(array($_template->cached->filepath => $content), $_template->cache_lifetime);
  118. }
  119. /**
  120. * Read cached template from cache
  121. *
  122. * @param Smarty_Internal_Template $_template template object
  123. *
  124. * @return string|false content
  125. */
  126. public function readCachedContent(Smarty_Internal_Template $_template)
  127. {
  128. $content = $_template->cached->content ? $_template->cached->content : null;
  129. $timestamp = null;
  130. if ($content === null) {
  131. if (!$this->fetch($_template->cached->filepath, $_template->source->name, $_template->cache_id,
  132. $_template->compile_id, $content, $timestamp, $_template->source->uid)
  133. ) {
  134. return false;
  135. }
  136. }
  137. if (isset($content)) {
  138. return $content;
  139. }
  140. return false;
  141. }
  142. /**
  143. * Empty cache
  144. * {@internal the $exp_time argument is ignored altogether }}
  145. *
  146. * @param Smarty $smarty Smarty object
  147. * @param integer $exp_time expiration time [being ignored]
  148. *
  149. * @return integer number of cache files deleted [always -1]
  150. * @uses purge() to clear the whole store
  151. * @uses invalidate() to mark everything outdated if purge() is inapplicable
  152. */
  153. public function clearAll(Smarty $smarty, $exp_time = null)
  154. {
  155. if (!$this->purge()) {
  156. $this->invalidate(null);
  157. }
  158. return - 1;
  159. }
  160. /**
  161. * Empty cache for a specific template
  162. * {@internal the $exp_time argument is ignored altogether}}
  163. *
  164. * @param Smarty $smarty Smarty object
  165. * @param string $resource_name template name
  166. * @param string $cache_id cache id
  167. * @param string $compile_id compile id
  168. * @param integer $exp_time expiration time [being ignored]
  169. *
  170. * @return integer number of cache files deleted [always -1]
  171. * @uses buildCachedFilepath() to generate the CacheID
  172. * @uses invalidate() to mark CacheIDs parent chain as outdated
  173. * @uses delete() to remove CacheID from cache
  174. */
  175. public function clear(Smarty $smarty, $resource_name, $cache_id, $compile_id, $exp_time)
  176. {
  177. $uid = $this->getTemplateUid($smarty, $resource_name);
  178. $cid = $uid . '#' . $this->sanitize($resource_name) . '#' . $this->sanitize($cache_id) . '#' .
  179. $this->sanitize($compile_id);
  180. $this->delete(array($cid));
  181. $this->invalidate($cid, $resource_name, $cache_id, $compile_id, $uid);
  182. return - 1;
  183. }
  184. /**
  185. * Get template's unique ID
  186. *
  187. * @param Smarty $smarty Smarty object
  188. * @param string $resource_name template name
  189. *
  190. * @return string filepath of cache file
  191. * @throws \SmartyException
  192. *
  193. */
  194. protected function getTemplateUid(Smarty $smarty, $resource_name)
  195. {
  196. if (isset($resource_name)) {
  197. $source = Smarty_Template_Source::load(null, $smarty, $resource_name);
  198. if ($source->exists) {
  199. return $source->uid;
  200. }
  201. }
  202. return '';
  203. }
  204. /**
  205. * Sanitize CacheID components
  206. *
  207. * @param string $string CacheID component to sanitize
  208. *
  209. * @return string sanitized CacheID component
  210. */
  211. protected function sanitize($string)
  212. {
  213. $string = trim($string, '|');
  214. if (!$string) {
  215. return '';
  216. }
  217. return preg_replace('#[^\w\|]+#S', '_', $string);
  218. }
  219. /**
  220. * Fetch and prepare a cache object.
  221. *
  222. * @param string $cid CacheID to fetch
  223. * @param string $resource_name template name
  224. * @param string $cache_id cache id
  225. * @param string $compile_id compile id
  226. * @param string $content cached content
  227. * @param integer &$timestamp cached timestamp (epoch)
  228. * @param string $resource_uid resource's uid
  229. *
  230. * @return boolean success
  231. */
  232. protected function fetch($cid, $resource_name = null, $cache_id = null, $compile_id = null, &$content = null,
  233. &$timestamp = null, $resource_uid = null)
  234. {
  235. $t = $this->read(array($cid));
  236. $content = !empty($t[ $cid ]) ? $t[ $cid ] : null;
  237. $timestamp = null;
  238. if ($content && ($timestamp = $this->getMetaTimestamp($content))) {
  239. $invalidated =
  240. $this->getLatestInvalidationTimestamp($cid, $resource_name, $cache_id, $compile_id, $resource_uid);
  241. if ($invalidated > $timestamp) {
  242. $timestamp = null;
  243. $content = null;
  244. }
  245. }
  246. return !!$content;
  247. }
  248. /**
  249. * Add current microtime to the beginning of $cache_content
  250. * {@internal the header uses 8 Bytes, the first 4 Bytes are the seconds, the second 4 Bytes are the microseconds}}
  251. *
  252. * @param string &$content the content to be cached
  253. */
  254. protected function addMetaTimestamp(&$content)
  255. {
  256. $mt = explode(" ", microtime());
  257. $ts = pack("NN", $mt[ 1 ], (int) ($mt[ 0 ] * 100000000));
  258. $content = $ts . $content;
  259. }
  260. /**
  261. * Extract the timestamp the $content was cached
  262. *
  263. * @param string &$content the cached content
  264. *
  265. * @return float the microtime the content was cached
  266. */
  267. protected function getMetaTimestamp(&$content)
  268. {
  269. extract(unpack('N1s/N1m/a*content', $content));
  270. /**
  271. * @var int $s
  272. * @var int $m
  273. */
  274. return $s + ($m / 100000000);
  275. }
  276. /**
  277. * Invalidate CacheID
  278. *
  279. * @param string $cid CacheID
  280. * @param string $resource_name template name
  281. * @param string $cache_id cache id
  282. * @param string $compile_id compile id
  283. * @param string $resource_uid source's uid
  284. *
  285. * @return void
  286. */
  287. protected function invalidate($cid = null, $resource_name = null, $cache_id = null, $compile_id = null,
  288. $resource_uid = null)
  289. {
  290. $now = microtime(true);
  291. $key = null;
  292. // invalidate everything
  293. if (!$resource_name && !$cache_id && !$compile_id) {
  294. $key = 'IVK#ALL';
  295. } // invalidate all caches by template
  296. else {
  297. if ($resource_name && !$cache_id && !$compile_id) {
  298. $key = 'IVK#TEMPLATE#' . $resource_uid . '#' . $this->sanitize($resource_name);
  299. } // invalidate all caches by cache group
  300. else {
  301. if (!$resource_name && $cache_id && !$compile_id) {
  302. $key = 'IVK#CACHE#' . $this->sanitize($cache_id);
  303. } // invalidate all caches by compile id
  304. else {
  305. if (!$resource_name && !$cache_id && $compile_id) {
  306. $key = 'IVK#COMPILE#' . $this->sanitize($compile_id);
  307. } // invalidate by combination
  308. else {
  309. $key = 'IVK#CID#' . $cid;
  310. }
  311. }
  312. }
  313. }
  314. $this->write(array($key => $now));
  315. }
  316. /**
  317. * Determine the latest timestamp known to the invalidation chain
  318. *
  319. * @param string $cid CacheID to determine latest invalidation timestamp of
  320. * @param string $resource_name template name
  321. * @param string $cache_id cache id
  322. * @param string $compile_id compile id
  323. * @param string $resource_uid source's filepath
  324. *
  325. * @return float the microtime the CacheID was invalidated
  326. */
  327. protected function getLatestInvalidationTimestamp($cid, $resource_name = null, $cache_id = null, $compile_id = null,
  328. $resource_uid = null)
  329. {
  330. // abort if there is no CacheID
  331. if (false && !$cid) {
  332. return 0;
  333. }
  334. // abort if there are no InvalidationKeys to check
  335. if (!($_cid = $this->listInvalidationKeys($cid, $resource_name, $cache_id, $compile_id, $resource_uid))) {
  336. return 0;
  337. }
  338. // there are no InValidationKeys
  339. if (!($values = $this->read($_cid))) {
  340. return 0;
  341. }
  342. // make sure we're dealing with floats
  343. $values = array_map('floatval', $values);
  344. return max($values);
  345. }
  346. /**
  347. * Translate a CacheID into the list of applicable InvalidationKeys.
  348. * Splits "some|chain|into|an|array" into array( '#clearAll#', 'some', 'some|chain', 'some|chain|into', ... )
  349. *
  350. * @param string $cid CacheID to translate
  351. * @param string $resource_name template name
  352. * @param string $cache_id cache id
  353. * @param string $compile_id compile id
  354. * @param string $resource_uid source's filepath
  355. *
  356. * @return array list of InvalidationKeys
  357. * @uses $invalidationKeyPrefix to prepend to each InvalidationKey
  358. */
  359. protected function listInvalidationKeys($cid, $resource_name = null, $cache_id = null, $compile_id = null,
  360. $resource_uid = null)
  361. {
  362. $t = array('IVK#ALL');
  363. $_name = $_compile = '#';
  364. if ($resource_name) {
  365. $_name .= $resource_uid . '#' . $this->sanitize($resource_name);
  366. $t[] = 'IVK#TEMPLATE' . $_name;
  367. }
  368. if ($compile_id) {
  369. $_compile .= $this->sanitize($compile_id);
  370. $t[] = 'IVK#COMPILE' . $_compile;
  371. }
  372. $_name .= '#';
  373. $cid = trim($cache_id, '|');
  374. if (!$cid) {
  375. return $t;
  376. }
  377. $i = 0;
  378. while (true) {
  379. // determine next delimiter position
  380. $i = strpos($cid, '|', $i);
  381. // add complete CacheID if there are no more delimiters
  382. if ($i === false) {
  383. $t[] = 'IVK#CACHE#' . $cid;
  384. $t[] = 'IVK#CID' . $_name . $cid . $_compile;
  385. $t[] = 'IVK#CID' . $_name . $_compile;
  386. break;
  387. }
  388. $part = substr($cid, 0, $i);
  389. // add slice to list
  390. $t[] = 'IVK#CACHE#' . $part;
  391. $t[] = 'IVK#CID' . $_name . $part . $_compile;
  392. // skip past delimiter position
  393. $i ++;
  394. }
  395. return $t;
  396. }
  397. /**
  398. * Check is cache is locked for this template
  399. *
  400. * @param Smarty $smarty Smarty object
  401. * @param Smarty_Template_Cached $cached cached object
  402. *
  403. * @return boolean true or false if cache is locked
  404. */
  405. public function hasLock(Smarty $smarty, Smarty_Template_Cached $cached)
  406. {
  407. $key = 'LOCK#' . $cached->filepath;
  408. $data = $this->read(array($key));
  409. return $data && time() - $data[ $key ] < $smarty->locking_timeout;
  410. }
  411. /**
  412. * Lock cache for this template
  413. *
  414. * @param Smarty $smarty Smarty object
  415. * @param Smarty_Template_Cached $cached cached object
  416. *
  417. * @return bool|void
  418. */
  419. public function acquireLock(Smarty $smarty, Smarty_Template_Cached $cached)
  420. {
  421. $cached->is_locked = true;
  422. $key = 'LOCK#' . $cached->filepath;
  423. $this->write(array($key => time()), $smarty->locking_timeout);
  424. }
  425. /**
  426. * Unlock cache for this template
  427. *
  428. * @param Smarty $smarty Smarty object
  429. * @param Smarty_Template_Cached $cached cached object
  430. *
  431. * @return bool|void
  432. */
  433. public function releaseLock(Smarty $smarty, Smarty_Template_Cached $cached)
  434. {
  435. $cached->is_locked = false;
  436. $key = 'LOCK#' . $cached->filepath;
  437. $this->delete(array($key));
  438. }
  439. /**
  440. * Read values for a set of keys from cache
  441. *
  442. * @param array $keys list of keys to fetch
  443. *
  444. * @return array list of values with the given keys used as indexes
  445. */
  446. abstract protected function read(array $keys);
  447. /**
  448. * Save values for a set of keys to cache
  449. *
  450. * @param array $keys list of values to save
  451. * @param int $expire expiration time
  452. *
  453. * @return boolean true on success, false on failure
  454. */
  455. abstract protected function write(array $keys, $expire = null);
  456. /**
  457. * Remove values from cache
  458. *
  459. * @param array $keys list of keys to delete
  460. *
  461. * @return boolean true on success, false on failure
  462. */
  463. abstract protected function delete(array $keys);
  464. /**
  465. * Remove *all* values from cache
  466. *
  467. * @return boolean true on success, false on failure
  468. */
  469. protected function purge()
  470. {
  471. return false;
  472. }
  473. }