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.

rcube_cache_shared.php 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  1. <?php
  2. /**
  3. +-----------------------------------------------------------------------+
  4. | This file is part of the Roundcube Webmail client |
  5. | Copyright (C) 2011-2013, The Roundcube Dev Team |
  6. | Copyright (C) 2011-2013, Kolab Systems AG |
  7. | |
  8. | Licensed under the GNU General Public License version 3 or |
  9. | any later version with exceptions for skins & plugins. |
  10. | See the README file for a full license statement. |
  11. | |
  12. | PURPOSE: |
  13. | Shared (cross-user) caching engine |
  14. +-----------------------------------------------------------------------+
  15. | Author: Thomas Bruederli <roundcube@gmail.com> |
  16. | Author: Aleksander Machniak <alec@alec.pl> |
  17. +-----------------------------------------------------------------------+
  18. */
  19. /**
  20. * Interface class for accessing Roundcube shared cache
  21. *
  22. * @package Framework
  23. * @subpackage Cache
  24. * @author Thomas Bruederli <roundcube@gmail.com>
  25. * @author Aleksander Machniak <alec@alec.pl>
  26. */
  27. class rcube_cache_shared
  28. {
  29. /**
  30. * Instance of database handler
  31. *
  32. * @var rcube_db|Memcache|bool
  33. */
  34. private $db;
  35. private $type;
  36. private $prefix;
  37. private $ttl;
  38. private $packed;
  39. private $index;
  40. private $table;
  41. private $debug;
  42. private $index_changed = false;
  43. private $cache = array();
  44. private $cache_changes = array();
  45. private $cache_sums = array();
  46. private $max_packet = -1;
  47. /**
  48. * Object constructor.
  49. *
  50. * @param string $type Engine type ('db' or 'memcache' or 'apc')
  51. * @param string $prefix Key name prefix
  52. * @param string $ttl Expiration time of memcache/apc items
  53. * @param bool $packed Enables/disabled data serialization.
  54. * It's possible to disable data serialization if you're sure
  55. * stored data will be always a safe string
  56. */
  57. function __construct($type, $prefix='', $ttl=0, $packed=true)
  58. {
  59. $rcube = rcube::get_instance();
  60. $type = strtolower($type);
  61. if ($type == 'memcache') {
  62. $this->type = 'memcache';
  63. $this->db = $rcube->get_memcache();
  64. $this->debug = $rcube->config->get('memcache_debug');
  65. }
  66. else if ($type == 'apc') {
  67. $this->type = 'apc';
  68. $this->db = function_exists('apc_exists'); // APC 3.1.4 required
  69. $this->debug = $rcube->config->get('apc_debug');
  70. }
  71. else {
  72. $this->type = 'db';
  73. $this->db = $rcube->get_dbh();
  74. $this->table = $this->db->table_name('cache_shared', true);
  75. }
  76. // convert ttl string to seconds
  77. $ttl = get_offset_sec($ttl);
  78. if ($ttl > 2592000) $ttl = 2592000;
  79. $this->ttl = $ttl;
  80. $this->packed = $packed;
  81. $this->prefix = $prefix;
  82. }
  83. /**
  84. * Returns cached value.
  85. *
  86. * @param string $key Cache key name
  87. *
  88. * @return mixed Cached value
  89. */
  90. function get($key)
  91. {
  92. if (!array_key_exists($key, $this->cache)) {
  93. return $this->read_record($key);
  94. }
  95. return $this->cache[$key];
  96. }
  97. /**
  98. * Sets (add/update) value in cache.
  99. *
  100. * @param string $key Cache key name
  101. * @param mixed $data Cache data
  102. */
  103. function set($key, $data)
  104. {
  105. $this->cache[$key] = $data;
  106. $this->cache_changes[$key] = true;
  107. }
  108. /**
  109. * Returns cached value without storing it in internal memory.
  110. *
  111. * @param string $key Cache key name
  112. *
  113. * @return mixed Cached value
  114. */
  115. function read($key)
  116. {
  117. if (array_key_exists($key, $this->cache)) {
  118. return $this->cache[$key];
  119. }
  120. return $this->read_record($key, true);
  121. }
  122. /**
  123. * Sets (add/update) value in cache and immediately saves
  124. * it in the backend, no internal memory will be used.
  125. *
  126. * @param string $key Cache key name
  127. * @param mixed $data Cache data
  128. *
  129. * @param boolean True on success, False on failure
  130. */
  131. function write($key, $data)
  132. {
  133. return $this->write_record($key, $this->serialize($data));
  134. }
  135. /**
  136. * Clears the cache.
  137. *
  138. * @param string $key Cache key name or pattern
  139. * @param boolean $prefix_mode Enable it to clear all keys starting
  140. * with prefix specified in $key
  141. */
  142. function remove($key=null, $prefix_mode=false)
  143. {
  144. // Remove all keys
  145. if ($key === null) {
  146. $this->cache = array();
  147. $this->cache_changes = array();
  148. $this->cache_sums = array();
  149. }
  150. // Remove keys by name prefix
  151. else if ($prefix_mode) {
  152. foreach (array_keys($this->cache) as $k) {
  153. if (strpos($k, $key) === 0) {
  154. $this->cache[$k] = null;
  155. $this->cache_changes[$k] = false;
  156. unset($this->cache_sums[$k]);
  157. }
  158. }
  159. }
  160. // Remove one key by name
  161. else {
  162. $this->cache[$key] = null;
  163. $this->cache_changes[$key] = false;
  164. unset($this->cache_sums[$key]);
  165. }
  166. // Remove record(s) from the backend
  167. $this->remove_record($key, $prefix_mode);
  168. }
  169. /**
  170. * Remove cache records older than ttl
  171. */
  172. function expunge()
  173. {
  174. if ($this->type == 'db' && $this->db && $this->ttl) {
  175. $this->db->query(
  176. "DELETE FROM {$this->table}"
  177. . " WHERE `cache_key` LIKE ?"
  178. . " AND `expires` < " . $this->db->now(),
  179. $this->prefix . '.%');
  180. }
  181. }
  182. /**
  183. * Remove expired records of all caches
  184. */
  185. static function gc()
  186. {
  187. $rcube = rcube::get_instance();
  188. $db = $rcube->get_dbh();
  189. $db->query("DELETE FROM " . $db->table_name('cache_shared', true) . " WHERE `expires` < " . $db->now());
  190. }
  191. /**
  192. * Writes the cache back to the DB.
  193. */
  194. function close()
  195. {
  196. foreach ($this->cache as $key => $data) {
  197. // The key has been used
  198. if ($this->cache_changes[$key]) {
  199. // Make sure we're not going to write unchanged data
  200. // by comparing current md5 sum with the sum calculated on DB read
  201. $data = $this->serialize($data);
  202. if (!$this->cache_sums[$key] || $this->cache_sums[$key] != md5($data)) {
  203. $this->write_record($key, $data);
  204. }
  205. }
  206. }
  207. if ($this->index_changed) {
  208. $this->write_index();
  209. }
  210. // reset internal cache index, thanks to this we can force index reload
  211. $this->index = null;
  212. $this->index_changed = false;
  213. $this->cache = array();
  214. $this->cache_sums = array();
  215. $this->cache_changes = array();
  216. }
  217. /**
  218. * Reads cache entry.
  219. *
  220. * @param string $key Cache key name
  221. * @param boolean $nostore Enable to skip in-memory store
  222. *
  223. * @return mixed Cached value
  224. */
  225. private function read_record($key, $nostore=false)
  226. {
  227. if (!$this->db) {
  228. return null;
  229. }
  230. if ($this->type != 'db') {
  231. $this->load_index();
  232. // Consistency check (#1490390)
  233. if (!in_array($key, $this->index)) {
  234. // we always check if the key exist in the index
  235. // to have data in consistent state. Keeping the index consistent
  236. // is needed for keys delete operation when we delete all keys or by prefix.
  237. }
  238. else {
  239. $ckey = $this->ckey($key);
  240. if ($this->type == 'memcache') {
  241. $data = $this->db->get($ckey);
  242. }
  243. else if ($this->type == 'apc') {
  244. $data = apc_fetch($ckey);
  245. }
  246. if ($this->debug) {
  247. $this->debug('get', $ckey, $data);
  248. }
  249. }
  250. if ($data !== false) {
  251. $md5sum = md5($data);
  252. $data = $this->unserialize($data);
  253. if ($nostore) {
  254. return $data;
  255. }
  256. $this->cache_sums[$key] = $md5sum;
  257. $this->cache[$key] = $data;
  258. }
  259. else {
  260. $this->cache[$key] = null;
  261. }
  262. }
  263. else {
  264. $sql_result = $this->db->query(
  265. "SELECT `data`, `cache_key` FROM {$this->table}"
  266. . " WHERE `cache_key` = ?",
  267. $this->prefix . '.' . $key);
  268. if ($sql_arr = $this->db->fetch_assoc($sql_result)) {
  269. if (strlen($sql_arr['data']) > 0) {
  270. $md5sum = md5($sql_arr['data']);
  271. $data = $this->unserialize($sql_arr['data']);
  272. }
  273. $this->db->reset();
  274. if ($nostore) {
  275. return $data;
  276. }
  277. $this->cache[$key] = $data;
  278. $this->cache_sums[$key] = $md5sum;
  279. }
  280. else {
  281. $this->cache[$key] = null;
  282. }
  283. }
  284. return $this->cache[$key];
  285. }
  286. /**
  287. * Writes single cache record into DB.
  288. *
  289. * @param string $key Cache key name
  290. * @param mixed $data Serialized cache data
  291. *
  292. * @param boolean True on success, False on failure
  293. */
  294. private function write_record($key, $data)
  295. {
  296. if (!$this->db) {
  297. return false;
  298. }
  299. // don't attempt to write too big data sets
  300. if (strlen($data) > $this->max_packet_size()) {
  301. trigger_error("rcube_cache: max_packet_size ($this->max_packet) exceeded for key $key. Tried to write " . strlen($data) . " bytes", E_USER_WARNING);
  302. return false;
  303. }
  304. if ($this->type == 'memcache' || $this->type == 'apc') {
  305. $result = $this->add_record($this->ckey($key), $data);
  306. // make sure index will be updated
  307. if ($result) {
  308. if (!array_key_exists($key, $this->cache_sums)) {
  309. $this->cache_sums[$key] = true;
  310. }
  311. $this->load_index();
  312. if (!$this->index_changed && !in_array($key, $this->index)) {
  313. $this->index_changed = true;
  314. }
  315. }
  316. return $result;
  317. }
  318. $db_key = $this->prefix . '.' . $key;
  319. // Remove NULL rows (here we don't need to check if the record exist)
  320. if ($data == 'N;') {
  321. $result = $this->db->query("DELETE FROM {$this->table} WHERE `cache_key` = ?", $db_key);
  322. return !$this->db->is_error($result);
  323. }
  324. $key_exists = array_key_exists($key, $this->cache_sums);
  325. $expires = $this->ttl ? $this->db->now($this->ttl) : 'NULL';
  326. if (!$key_exists) {
  327. // Try INSERT temporarily ignoring "duplicate key" errors
  328. $this->db->set_option('ignore_key_errors', true);
  329. $result = $this->db->query(
  330. "INSERT INTO {$this->table} (`expires`, `cache_key`, `data`)"
  331. . " VALUES ($expires, ?, ?)",
  332. $db_key, $data);
  333. $this->db->set_option('ignore_key_errors', false);
  334. }
  335. // otherwise try UPDATE
  336. if (!isset($result) || !($count = $this->db->affected_rows($result))) {
  337. $result = $this->db->query(
  338. "UPDATE {$this->table} SET `expires` = $expires, `data` = ?"
  339. . " WHERE `cache_key` = ?",
  340. $data, $db_key);
  341. $count = $this->db->affected_rows($result);
  342. }
  343. return $count > 0;
  344. }
  345. /**
  346. * Deletes the cache record(s).
  347. *
  348. * @param string $key Cache key name or pattern
  349. * @param boolean $prefix_mode Enable it to clear all keys starting
  350. * with prefix specified in $key
  351. */
  352. private function remove_record($key=null, $prefix_mode=false)
  353. {
  354. if (!$this->db) {
  355. return;
  356. }
  357. if ($this->type != 'db') {
  358. $this->load_index();
  359. // Remove all keys
  360. if ($key === null) {
  361. foreach ($this->index as $key) {
  362. $this->delete_record($this->ckey($key));
  363. }
  364. $this->index = array();
  365. }
  366. // Remove keys by name prefix
  367. else if ($prefix_mode) {
  368. foreach ($this->index as $idx => $k) {
  369. if (strpos($k, $key) === 0) {
  370. $this->delete_record($this->ckey($k));
  371. unset($this->index[$idx]);
  372. }
  373. }
  374. }
  375. // Remove one key by name
  376. else {
  377. $this->delete_record($this->ckey($key));
  378. if (($idx = array_search($key, $this->index)) !== false) {
  379. unset($this->index[$idx]);
  380. }
  381. }
  382. $this->index_changed = true;
  383. return;
  384. }
  385. // Remove all keys (in specified cache)
  386. if ($key === null) {
  387. $where = " WHERE `cache_key` LIKE " . $this->db->quote($this->prefix.'.%');
  388. }
  389. // Remove keys by name prefix
  390. else if ($prefix_mode) {
  391. $where = " WHERE `cache_key` LIKE " . $this->db->quote($this->prefix.'.'.$key.'%');
  392. }
  393. // Remove one key by name
  394. else {
  395. $where = " WHERE `cache_key` = " . $this->db->quote($this->prefix.'.'.$key);
  396. }
  397. $this->db->query("DELETE FROM " . $this->table . $where);
  398. }
  399. /**
  400. * Adds entry into memcache/apc DB.
  401. *
  402. * @param string $key Cache internal key name
  403. * @param mixed $data Serialized cache data
  404. *
  405. * @param boolean True on success, False on failure
  406. */
  407. private function add_record($key, $data)
  408. {
  409. if ($this->type == 'memcache') {
  410. $result = $this->db->replace($key, $data, MEMCACHE_COMPRESSED, $this->ttl);
  411. if (!$result) {
  412. $result = $this->db->set($key, $data, MEMCACHE_COMPRESSED, $this->ttl);
  413. }
  414. }
  415. else if ($this->type == 'apc') {
  416. if (apc_exists($key)) {
  417. apc_delete($key);
  418. }
  419. $result = apc_store($key, $data, $this->ttl);
  420. }
  421. if ($this->debug) {
  422. $this->debug('set', $key, $data, $result);
  423. }
  424. return $result;
  425. }
  426. /**
  427. * Deletes entry from memcache/apc DB.
  428. *
  429. * @param string $key Cache internal key name
  430. *
  431. * @param boolean True on success, False on failure
  432. */
  433. private function delete_record($key)
  434. {
  435. if ($this->type == 'memcache') {
  436. // #1488592: use 2nd argument
  437. $result = $this->db->delete($key, 0);
  438. }
  439. else {
  440. $result = apc_delete($key);
  441. }
  442. if ($this->debug) {
  443. $this->debug('delete', $key, null, $result);
  444. }
  445. return $result;
  446. }
  447. /**
  448. * Writes the index entry into memcache/apc DB.
  449. */
  450. private function write_index()
  451. {
  452. if (!$this->db || $this->type == 'db') {
  453. return;
  454. }
  455. $this->load_index();
  456. // Make sure index contains new keys
  457. foreach ($this->cache as $key => $value) {
  458. if ($value !== null && !in_array($key, $this->index)) {
  459. $this->index[] = $key;
  460. }
  461. }
  462. // new keys added using self::write()
  463. foreach ($this->cache_sums as $key => $value) {
  464. if ($value === true && !in_array($key, $this->index)) {
  465. $this->index[] = $key;
  466. }
  467. }
  468. $data = serialize($this->index);
  469. $this->add_record($this->ikey(), $data);
  470. }
  471. /**
  472. * Gets the index entry from memcache/apc DB.
  473. */
  474. private function load_index()
  475. {
  476. if (!$this->db || $this->type == 'db') {
  477. return;
  478. }
  479. if ($this->index !== null) {
  480. return;
  481. }
  482. $index_key = $this->ikey();
  483. if ($this->type == 'memcache') {
  484. $data = $this->db->get($index_key);
  485. }
  486. else if ($this->type == 'apc') {
  487. $data = apc_fetch($index_key);
  488. }
  489. if ($this->debug) {
  490. $this->debug('get', $index_key, $data);
  491. }
  492. $this->index = $data ? unserialize($data) : array();
  493. }
  494. /**
  495. * Creates cache key name (for memcache and apc)
  496. *
  497. * @param string $key Cache key name
  498. *
  499. * @return string Cache key
  500. */
  501. private function ckey($key)
  502. {
  503. return $this->prefix . ':' . $key;
  504. }
  505. /**
  506. * Creates index cache key name (for memcache and apc)
  507. *
  508. * @return string Cache key
  509. */
  510. private function ikey()
  511. {
  512. // This way each cache will have its own index
  513. return $this->prefix . 'INDEX';
  514. }
  515. /**
  516. * Serializes data for storing
  517. */
  518. private function serialize($data)
  519. {
  520. if ($this->type == 'db') {
  521. return $this->db->encode($data, $this->packed);
  522. }
  523. return $this->packed ? serialize($data) : $data;
  524. }
  525. /**
  526. * Unserializes serialized data
  527. */
  528. private function unserialize($data)
  529. {
  530. if ($this->type == 'db') {
  531. return $this->db->decode($data, $this->packed);
  532. }
  533. return $this->packed ? @unserialize($data) : $data;
  534. }
  535. /**
  536. * Determine the maximum size for cache data to be written
  537. */
  538. private function max_packet_size()
  539. {
  540. if ($this->max_packet < 0) {
  541. $this->max_packet = 2097152; // default/max is 2 MB
  542. if ($this->type == 'db') {
  543. if ($value = $this->db->get_variable('max_allowed_packet', $this->max_packet)) {
  544. $this->max_packet = $value;
  545. }
  546. $this->max_packet -= 2000;
  547. }
  548. else {
  549. $max_packet = rcube::get_instance()->config->get($this->type . '_max_allowed_packet');
  550. $this->max_packet = parse_bytes($max_packet) ?: $this->max_packet;
  551. }
  552. }
  553. return $this->max_packet;
  554. }
  555. /**
  556. * Write memcache/apc debug info to the log
  557. */
  558. private function debug($type, $key, $data = null, $result = null)
  559. {
  560. $line = strtoupper($type) . ' ' . $key;
  561. if ($data !== null) {
  562. $line .= ' ' . ($this->packed ? $data : serialize($data));
  563. }
  564. rcube::debug($this->type, $line, $result);
  565. }
  566. }