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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  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, $timestamp, $cached->source->uid)) {
  68. return;
  69. }
  70. $cached->content = $content;
  71. $cached->timestamp = (int) $timestamp;
  72. $cached->exists = $cached->timestamp;
  73. }
  74. /**
  75. * Read the cached template and process the header
  76. *
  77. * @param Smarty_Internal_Template $_template template object
  78. * @param Smarty_Template_Cached $cached cached object
  79. * @param bool $update flag if called because cache update
  80. *
  81. * @return boolean true or false if the cached content does not exist
  82. */
  83. public function process(Smarty_Internal_Template $_template, Smarty_Template_Cached $cached = null, $update = false)
  84. {
  85. if (!$cached) {
  86. $cached = $_template->cached;
  87. }
  88. $content = $cached->content ? $cached->content : null;
  89. $timestamp = $cached->timestamp ? $cached->timestamp : null;
  90. if ($content === null || !$timestamp) {
  91. if (!$this->fetch($_template->cached->filepath, $_template->source->name, $_template->cache_id, $_template->compile_id, $content, $timestamp, $_template->source->uid)) {
  92. return false;
  93. }
  94. }
  95. if (isset($content)) {
  96. /** @var Smarty_Internal_Template $_smarty_tpl
  97. * used in evaluated code
  98. */
  99. $_smarty_tpl = $_template;
  100. eval("?>" . $content);
  101. return true;
  102. }
  103. return false;
  104. }
  105. /**
  106. * Write the rendered template output to cache
  107. *
  108. * @param Smarty_Internal_Template $_template template object
  109. * @param string $content content to cache
  110. *
  111. * @return boolean success
  112. */
  113. public function writeCachedContent(Smarty_Internal_Template $_template, $content)
  114. {
  115. $this->addMetaTimestamp($content);
  116. return $this->write(array($_template->cached->filepath => $content), $_template->cache_lifetime);
  117. }
  118. /**
  119. * Read cached template from cache
  120. *
  121. * @param Smarty_Internal_Template $_template template object
  122. *
  123. * @return string content
  124. */
  125. public function readCachedContent(Smarty_Internal_Template $_template)
  126. {
  127. $content = $_template->cached->content ? $_template->cached->content : null;
  128. $timestamp = null;
  129. if ($content === null) {
  130. if (!$this->fetch($_template->cached->filepath, $_template->source->name, $_template->cache_id, $_template->compile_id, $content, $timestamp, $_template->source->uid)) {
  131. return false;
  132. }
  133. }
  134. if (isset($content)) {
  135. return $content;
  136. }
  137. return false;
  138. }
  139. /**
  140. * Empty cache
  141. * {@internal the $exp_time argument is ignored altogether }}
  142. *
  143. * @param Smarty $smarty Smarty object
  144. * @param integer $exp_time expiration time [being ignored]
  145. *
  146. * @return integer number of cache files deleted [always -1]
  147. * @uses purge() to clear the whole store
  148. * @uses invalidate() to mark everything outdated if purge() is inapplicable
  149. */
  150. public function clearAll(Smarty $smarty, $exp_time = null)
  151. {
  152. if (!$this->purge()) {
  153. $this->invalidate(null);
  154. }
  155. // remove from template cache
  156. if (isset($smarty->_cache['template_objects'])) {
  157. foreach ($smarty->_cache['template_objects'] as $key => $tpl) {
  158. if (isset($tpl->cached)) {
  159. unset($smarty->_cache['template_objects'][$key]);
  160. }
  161. }
  162. }
  163. return - 1;
  164. }
  165. /**
  166. * Empty cache for a specific template
  167. * {@internal the $exp_time argument is ignored altogether}}
  168. *
  169. * @param Smarty $smarty Smarty object
  170. * @param string $resource_name template name
  171. * @param string $cache_id cache id
  172. * @param string $compile_id compile id
  173. * @param integer $exp_time expiration time [being ignored]
  174. *
  175. * @return integer number of cache files deleted [always -1]
  176. * @uses buildCachedFilepath() to generate the CacheID
  177. * @uses invalidate() to mark CacheIDs parent chain as outdated
  178. * @uses delete() to remove CacheID from cache
  179. */
  180. public function clear(Smarty $smarty, $resource_name, $cache_id, $compile_id, $exp_time)
  181. {
  182. $uid = $this->getTemplateUid($smarty, $resource_name);
  183. $cid = $uid . '#' . $this->sanitize($resource_name) . '#' . $this->sanitize($cache_id) . '#' .
  184. $this->sanitize($compile_id);
  185. $this->delete(array($cid));
  186. $this->invalidate($cid, $resource_name, $cache_id, $compile_id, $uid);
  187. // remove from template cache
  188. if (isset($resource_name) && isset($smarty->_cache['template_objects'])) {
  189. if (isset($smarty->_cache['template_objects'])) {
  190. foreach ($smarty->_cache['template_objects'] as $key => $tpl) {
  191. if ($tpl->source->uid == $uid && isset($tpl->cached)) {
  192. unset($smarty->_cache['template_objects'][$key]);
  193. }
  194. }
  195. }
  196. }
  197. return - 1;
  198. }
  199. /**
  200. * Get template's unique ID
  201. *
  202. * @param Smarty $smarty Smarty object
  203. * @param string $resource_name template name
  204. *
  205. * @return string filepath of cache file
  206. * @throws \SmartyException
  207. *
  208. */
  209. protected function getTemplateUid(Smarty $smarty, $resource_name)
  210. {
  211. if (isset($resource_name)) {
  212. $source = Smarty_Template_Source::load(null, $smarty, $resource_name);
  213. if ($source->exists) {
  214. return $source->uid;
  215. }
  216. }
  217. return '';
  218. }
  219. /**
  220. * Sanitize CacheID components
  221. *
  222. * @param string $string CacheID component to sanitize
  223. *
  224. * @return string sanitized CacheID component
  225. */
  226. protected function sanitize($string)
  227. {
  228. $string = trim($string, '|');
  229. if (!$string) {
  230. return null;
  231. }
  232. return preg_replace('#[^\w\|]+#S', '_', $string);
  233. }
  234. /**
  235. * Fetch and prepare a cache object.
  236. *
  237. * @param string $cid CacheID to fetch
  238. * @param string $resource_name template name
  239. * @param string $cache_id cache id
  240. * @param string $compile_id compile id
  241. * @param string $content cached content
  242. * @param integer &$timestamp cached timestamp (epoch)
  243. * @param string $resource_uid resource's uid
  244. *
  245. * @return boolean success
  246. */
  247. protected function fetch($cid, $resource_name = null, $cache_id = null, $compile_id = null, &$content = null, &$timestamp = null, $resource_uid = null)
  248. {
  249. $t = $this->read(array($cid));
  250. $content = !empty($t[$cid]) ? $t[$cid] : null;
  251. $timestamp = null;
  252. if ($content && ($timestamp = $this->getMetaTimestamp($content))) {
  253. $invalidated = $this->getLatestInvalidationTimestamp($cid, $resource_name, $cache_id, $compile_id, $resource_uid);
  254. if ($invalidated > $timestamp) {
  255. $timestamp = null;
  256. $content = null;
  257. }
  258. }
  259. return !!$content;
  260. }
  261. /**
  262. * Add current microtime to the beginning of $cache_content
  263. * {@internal the header uses 8 Bytes, the first 4 Bytes are the seconds, the second 4 Bytes are the microseconds}}
  264. *
  265. * @param string &$content the content to be cached
  266. */
  267. protected function addMetaTimestamp(&$content)
  268. {
  269. $mt = explode(" ", microtime());
  270. $ts = pack("NN", $mt[1], (int) ($mt[0] * 100000000));
  271. $content = $ts . $content;
  272. }
  273. /**
  274. * Extract the timestamp the $content was cached
  275. *
  276. * @param string &$content the cached content
  277. *
  278. * @return float the microtime the content was cached
  279. */
  280. protected function getMetaTimestamp(&$content)
  281. {
  282. extract(unpack('N1s/N1m/a*content', $content));
  283. return $s + ($m / 100000000);
  284. }
  285. /**
  286. * Invalidate CacheID
  287. *
  288. * @param string $cid CacheID
  289. * @param string $resource_name template name
  290. * @param string $cache_id cache id
  291. * @param string $compile_id compile id
  292. * @param string $resource_uid source's uid
  293. *
  294. * @return void
  295. */
  296. protected function invalidate($cid = null, $resource_name = null, $cache_id = null, $compile_id = null, $resource_uid = null)
  297. {
  298. $now = microtime(true);
  299. $key = null;
  300. // invalidate everything
  301. if (!$resource_name && !$cache_id && !$compile_id) {
  302. $key = 'IVK#ALL';
  303. } // invalidate all caches by template
  304. else {
  305. if ($resource_name && !$cache_id && !$compile_id) {
  306. $key = 'IVK#TEMPLATE#' . $resource_uid . '#' . $this->sanitize($resource_name);
  307. } // invalidate all caches by cache group
  308. else {
  309. if (!$resource_name && $cache_id && !$compile_id) {
  310. $key = 'IVK#CACHE#' . $this->sanitize($cache_id);
  311. } // invalidate all caches by compile id
  312. else {
  313. if (!$resource_name && !$cache_id && $compile_id) {
  314. $key = 'IVK#COMPILE#' . $this->sanitize($compile_id);
  315. } // invalidate by combination
  316. else {
  317. $key = 'IVK#CID#' . $cid;
  318. }
  319. }
  320. }
  321. }
  322. $this->write(array($key => $now));
  323. }
  324. /**
  325. * Determine the latest timestamp known to the invalidation chain
  326. *
  327. * @param string $cid CacheID to determine latest invalidation timestamp of
  328. * @param string $resource_name template name
  329. * @param string $cache_id cache id
  330. * @param string $compile_id compile id
  331. * @param string $resource_uid source's filepath
  332. *
  333. * @return float the microtime the CacheID was invalidated
  334. */
  335. protected function getLatestInvalidationTimestamp($cid, $resource_name = null, $cache_id = null, $compile_id = null, $resource_uid = null)
  336. {
  337. // abort if there is no CacheID
  338. if (false && !$cid) {
  339. return 0;
  340. }
  341. // abort if there are no InvalidationKeys to check
  342. if (!($_cid = $this->listInvalidationKeys($cid, $resource_name, $cache_id, $compile_id, $resource_uid))) {
  343. return 0;
  344. }
  345. // there are no InValidationKeys
  346. if (!($values = $this->read($_cid))) {
  347. return 0;
  348. }
  349. // make sure we're dealing with floats
  350. $values = array_map('floatval', $values);
  351. return max($values);
  352. }
  353. /**
  354. * Translate a CacheID into the list of applicable InvalidationKeys.
  355. * Splits "some|chain|into|an|array" into array( '#clearAll#', 'some', 'some|chain', 'some|chain|into', ... )
  356. *
  357. * @param string $cid CacheID to translate
  358. * @param string $resource_name template name
  359. * @param string $cache_id cache id
  360. * @param string $compile_id compile id
  361. * @param string $resource_uid source's filepath
  362. *
  363. * @return array list of InvalidationKeys
  364. * @uses $invalidationKeyPrefix to prepend to each InvalidationKey
  365. */
  366. protected function listInvalidationKeys($cid, $resource_name = null, $cache_id = null, $compile_id = null, $resource_uid = null)
  367. {
  368. $t = array('IVK#ALL');
  369. $_name = $_compile = '#';
  370. if ($resource_name) {
  371. $_name .= $resource_uid . '#' . $this->sanitize($resource_name);
  372. $t[] = 'IVK#TEMPLATE' . $_name;
  373. }
  374. if ($compile_id) {
  375. $_compile .= $this->sanitize($compile_id);
  376. $t[] = 'IVK#COMPILE' . $_compile;
  377. }
  378. $_name .= '#';
  379. $cid = trim($cache_id, '|');
  380. if (!$cid) {
  381. return $t;
  382. }
  383. $i = 0;
  384. while (true) {
  385. // determine next delimiter position
  386. $i = strpos($cid, '|', $i);
  387. // add complete CacheID if there are no more delimiters
  388. if ($i === false) {
  389. $t[] = 'IVK#CACHE#' . $cid;
  390. $t[] = 'IVK#CID' . $_name . $cid . $_compile;
  391. $t[] = 'IVK#CID' . $_name . $_compile;
  392. break;
  393. }
  394. $part = substr($cid, 0, $i);
  395. // add slice to list
  396. $t[] = 'IVK#CACHE#' . $part;
  397. $t[] = 'IVK#CID' . $_name . $part . $_compile;
  398. // skip past delimiter position
  399. $i ++;
  400. }
  401. return $t;
  402. }
  403. /**
  404. * Check is cache is locked for this template
  405. *
  406. * @param Smarty $smarty Smarty object
  407. * @param Smarty_Template_Cached $cached cached object
  408. *
  409. * @return boolean true or false if cache is locked
  410. */
  411. public function hasLock(Smarty $smarty, Smarty_Template_Cached $cached)
  412. {
  413. $key = 'LOCK#' . $cached->filepath;
  414. $data = $this->read(array($key));
  415. return $data && time() - $data[$key] < $smarty->locking_timeout;
  416. }
  417. /**
  418. * Lock cache for this template
  419. *
  420. * @param Smarty $smarty Smarty object
  421. * @param Smarty_Template_Cached $cached cached object
  422. *
  423. * @return bool|void
  424. */
  425. public function acquireLock(Smarty $smarty, Smarty_Template_Cached $cached)
  426. {
  427. $cached->is_locked = true;
  428. $key = 'LOCK#' . $cached->filepath;
  429. $this->write(array($key => time()), $smarty->locking_timeout);
  430. }
  431. /**
  432. * Unlock cache for this template
  433. *
  434. * @param Smarty $smarty Smarty object
  435. * @param Smarty_Template_Cached $cached cached object
  436. *
  437. * @return bool|void
  438. */
  439. public function releaseLock(Smarty $smarty, Smarty_Template_Cached $cached)
  440. {
  441. $cached->is_locked = false;
  442. $key = 'LOCK#' . $cached->filepath;
  443. $this->delete(array($key));
  444. }
  445. /**
  446. * Read values for a set of keys from cache
  447. *
  448. * @param array $keys list of keys to fetch
  449. *
  450. * @return array list of values with the given keys used as indexes
  451. */
  452. abstract protected function read(array $keys);
  453. /**
  454. * Save values for a set of keys to cache
  455. *
  456. * @param array $keys list of values to save
  457. * @param int $expire expiration time
  458. *
  459. * @return boolean true on success, false on failure
  460. */
  461. abstract protected function write(array $keys, $expire = null);
  462. /**
  463. * Remove values from cache
  464. *
  465. * @param array $keys list of keys to delete
  466. *
  467. * @return boolean true on success, false on failure
  468. */
  469. abstract protected function delete(array $keys);
  470. /**
  471. * Remove *all* values from cache
  472. *
  473. * @return boolean true on success, false on failure
  474. */
  475. protected function purge()
  476. {
  477. return false;
  478. }
  479. }