You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

smarty_cacheresource_keyvaluestore.php 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  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 int number of cache files deleted [always -1]
  171. * @throws \SmartyException
  172. * @uses buildCachedFilepath() to generate the CacheID
  173. * @uses invalidate() to mark CacheIDs parent chain as outdated
  174. * @uses delete() to remove CacheID from cache
  175. */
  176. public function clear(Smarty $smarty, $resource_name, $cache_id, $compile_id, $exp_time)
  177. {
  178. $uid = $this->getTemplateUid($smarty, $resource_name);
  179. $cid = $uid . '#' . $this->sanitize($resource_name) . '#' . $this->sanitize($cache_id) . '#' .
  180. $this->sanitize($compile_id);
  181. $this->delete(array($cid));
  182. $this->invalidate($cid, $resource_name, $cache_id, $compile_id, $uid);
  183. return - 1;
  184. }
  185. /**
  186. * Get template's unique ID
  187. *
  188. * @param Smarty $smarty Smarty object
  189. * @param string $resource_name template name
  190. *
  191. * @return string filepath of cache file
  192. * @throws \SmartyException
  193. *
  194. */
  195. protected function getTemplateUid(Smarty $smarty, $resource_name)
  196. {
  197. if (isset($resource_name)) {
  198. $source = Smarty_Template_Source::load(null, $smarty, $resource_name);
  199. if ($source->exists) {
  200. return $source->uid;
  201. }
  202. }
  203. return '';
  204. }
  205. /**
  206. * Sanitize CacheID components
  207. *
  208. * @param string $string CacheID component to sanitize
  209. *
  210. * @return string sanitized CacheID component
  211. */
  212. protected function sanitize($string)
  213. {
  214. $string = trim($string, '|');
  215. if (!$string) {
  216. return '';
  217. }
  218. return preg_replace('#[^\w\|]+#S', '_', $string);
  219. }
  220. /**
  221. * Fetch and prepare a cache object.
  222. *
  223. * @param string $cid CacheID to fetch
  224. * @param string $resource_name template name
  225. * @param string $cache_id cache id
  226. * @param string $compile_id compile id
  227. * @param string $content cached content
  228. * @param integer &$timestamp cached timestamp (epoch)
  229. * @param string $resource_uid resource's uid
  230. *
  231. * @return boolean success
  232. */
  233. protected function fetch($cid, $resource_name = null, $cache_id = null, $compile_id = null, &$content = null,
  234. &$timestamp = null, $resource_uid = null)
  235. {
  236. $t = $this->read(array($cid));
  237. $content = !empty($t[ $cid ]) ? $t[ $cid ] : null;
  238. $timestamp = null;
  239. if ($content && ($timestamp = $this->getMetaTimestamp($content))) {
  240. $invalidated =
  241. $this->getLatestInvalidationTimestamp($cid, $resource_name, $cache_id, $compile_id, $resource_uid);
  242. if ($invalidated > $timestamp) {
  243. $timestamp = null;
  244. $content = null;
  245. }
  246. }
  247. return !!$content;
  248. }
  249. /**
  250. * Add current microtime to the beginning of $cache_content
  251. * {@internal the header uses 8 Bytes, the first 4 Bytes are the seconds, the second 4 Bytes are the microseconds}}
  252. *
  253. * @param string &$content the content to be cached
  254. */
  255. protected function addMetaTimestamp(&$content)
  256. {
  257. $mt = explode(' ', microtime());
  258. $ts = pack('NN', $mt[ 1 ], (int) ($mt[ 0 ] * 100000000));
  259. $content = $ts . $content;
  260. }
  261. /**
  262. * Extract the timestamp the $content was cached
  263. *
  264. * @param string &$content the cached content
  265. *
  266. * @return float the microtime the content was cached
  267. */
  268. protected function getMetaTimestamp(&$content)
  269. {
  270. extract(unpack('N1s/N1m/a*content', $content));
  271. /**
  272. * @var int $s
  273. * @var int $m
  274. */
  275. return $s + ($m / 100000000);
  276. }
  277. /**
  278. * Invalidate CacheID
  279. *
  280. * @param string $cid CacheID
  281. * @param string $resource_name template name
  282. * @param string $cache_id cache id
  283. * @param string $compile_id compile id
  284. * @param string $resource_uid source's uid
  285. *
  286. * @return void
  287. */
  288. protected function invalidate($cid = null, $resource_name = null, $cache_id = null, $compile_id = null,
  289. $resource_uid = null)
  290. {
  291. $now = microtime(true);
  292. $key = null;
  293. // invalidate everything
  294. if (!$resource_name && !$cache_id && !$compile_id) {
  295. $key = 'IVK#ALL';
  296. } // invalidate all caches by template
  297. else {
  298. if ($resource_name && !$cache_id && !$compile_id) {
  299. $key = 'IVK#TEMPLATE#' . $resource_uid . '#' . $this->sanitize($resource_name);
  300. } // invalidate all caches by cache group
  301. else {
  302. if (!$resource_name && $cache_id && !$compile_id) {
  303. $key = 'IVK#CACHE#' . $this->sanitize($cache_id);
  304. } // invalidate all caches by compile id
  305. else {
  306. if (!$resource_name && !$cache_id && $compile_id) {
  307. $key = 'IVK#COMPILE#' . $this->sanitize($compile_id);
  308. } // invalidate by combination
  309. else {
  310. $key = 'IVK#CID#' . $cid;
  311. }
  312. }
  313. }
  314. }
  315. $this->write(array($key => $now));
  316. }
  317. /**
  318. * Determine the latest timestamp known to the invalidation chain
  319. *
  320. * @param string $cid CacheID to determine latest invalidation timestamp of
  321. * @param string $resource_name template name
  322. * @param string $cache_id cache id
  323. * @param string $compile_id compile id
  324. * @param string $resource_uid source's filepath
  325. *
  326. * @return float the microtime the CacheID was invalidated
  327. */
  328. protected function getLatestInvalidationTimestamp($cid, $resource_name = null, $cache_id = null, $compile_id = null,
  329. $resource_uid = null)
  330. {
  331. // abort if there is no CacheID
  332. if (false && !$cid) {
  333. return 0;
  334. }
  335. // abort if there are no InvalidationKeys to check
  336. if (!($_cid = $this->listInvalidationKeys($cid, $resource_name, $cache_id, $compile_id, $resource_uid))) {
  337. return 0;
  338. }
  339. // there are no InValidationKeys
  340. if (!($values = $this->read($_cid))) {
  341. return 0;
  342. }
  343. // make sure we're dealing with floats
  344. $values = array_map('floatval', $values);
  345. return max($values);
  346. }
  347. /**
  348. * Translate a CacheID into the list of applicable InvalidationKeys.
  349. * Splits 'some|chain|into|an|array' into array( '#clearAll#', 'some', 'some|chain', 'some|chain|into', ... )
  350. *
  351. * @param string $cid CacheID to translate
  352. * @param string $resource_name template name
  353. * @param string $cache_id cache id
  354. * @param string $compile_id compile id
  355. * @param string $resource_uid source's filepath
  356. *
  357. * @return array list of InvalidationKeys
  358. * @uses $invalidationKeyPrefix to prepend to each InvalidationKey
  359. */
  360. protected function listInvalidationKeys($cid, $resource_name = null, $cache_id = null, $compile_id = null,
  361. $resource_uid = null)
  362. {
  363. $t = array('IVK#ALL');
  364. $_name = $_compile = '#';
  365. if ($resource_name) {
  366. $_name .= $resource_uid . '#' . $this->sanitize($resource_name);
  367. $t[] = 'IVK#TEMPLATE' . $_name;
  368. }
  369. if ($compile_id) {
  370. $_compile .= $this->sanitize($compile_id);
  371. $t[] = 'IVK#COMPILE' . $_compile;
  372. }
  373. $_name .= '#';
  374. $cid = trim($cache_id, '|');
  375. if (!$cid) {
  376. return $t;
  377. }
  378. $i = 0;
  379. while (true) {
  380. // determine next delimiter position
  381. $i = strpos($cid, '|', $i);
  382. // add complete CacheID if there are no more delimiters
  383. if ($i === false) {
  384. $t[] = 'IVK#CACHE#' . $cid;
  385. $t[] = 'IVK#CID' . $_name . $cid . $_compile;
  386. $t[] = 'IVK#CID' . $_name . $_compile;
  387. break;
  388. }
  389. $part = substr($cid, 0, $i);
  390. // add slice to list
  391. $t[] = 'IVK#CACHE#' . $part;
  392. $t[] = 'IVK#CID' . $_name . $part . $_compile;
  393. // skip past delimiter position
  394. $i ++;
  395. }
  396. return $t;
  397. }
  398. /**
  399. * Check is cache is locked for this template
  400. *
  401. * @param Smarty $smarty Smarty object
  402. * @param Smarty_Template_Cached $cached cached object
  403. *
  404. * @return boolean true or false if cache is locked
  405. */
  406. public function hasLock(Smarty $smarty, Smarty_Template_Cached $cached)
  407. {
  408. $key = 'LOCK#' . $cached->filepath;
  409. $data = $this->read(array($key));
  410. return $data && time() - $data[ $key ] < $smarty->locking_timeout;
  411. }
  412. /**
  413. * Lock cache for this template
  414. *
  415. * @param Smarty $smarty Smarty object
  416. * @param Smarty_Template_Cached $cached cached object
  417. *
  418. * @return bool|void
  419. */
  420. public function acquireLock(Smarty $smarty, Smarty_Template_Cached $cached)
  421. {
  422. $cached->is_locked = true;
  423. $key = 'LOCK#' . $cached->filepath;
  424. $this->write(array($key => time()), $smarty->locking_timeout);
  425. }
  426. /**
  427. * Unlock cache for this template
  428. *
  429. * @param Smarty $smarty Smarty object
  430. * @param Smarty_Template_Cached $cached cached object
  431. *
  432. * @return bool|void
  433. */
  434. public function releaseLock(Smarty $smarty, Smarty_Template_Cached $cached)
  435. {
  436. $cached->is_locked = false;
  437. $key = 'LOCK#' . $cached->filepath;
  438. $this->delete(array($key));
  439. }
  440. /**
  441. * Read values for a set of keys from cache
  442. *
  443. * @param array $keys list of keys to fetch
  444. *
  445. * @return array list of values with the given keys used as indexes
  446. */
  447. abstract protected function read(array $keys);
  448. /**
  449. * Save values for a set of keys to cache
  450. *
  451. * @param array $keys list of values to save
  452. * @param int $expire expiration time
  453. *
  454. * @return boolean true on success, false on failure
  455. */
  456. abstract protected function write(array $keys, $expire = null);
  457. /**
  458. * Remove values from cache
  459. *
  460. * @param array $keys list of keys to delete
  461. *
  462. * @return boolean true on success, false on failure
  463. */
  464. abstract protected function delete(array $keys);
  465. /**
  466. * Remove *all* values from cache
  467. *
  468. * @return boolean true on success, false on failure
  469. */
  470. protected function purge()
  471. {
  472. return false;
  473. }
  474. }