PageRenderTime 25ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 1ms

/core/model/smarty/sysplugins/smarty_cacheresource_keyvaluestore.php

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