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.php 19KB

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