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 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  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) {
  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->limitquery(
  270. "SELECT `data`, `cache_key`".
  271. " FROM {$this->table}".
  272. " WHERE `user_id` = ? AND `cache_key` = ?".
  273. // for better performance we allow more records for one key
  274. // get the newer one
  275. " ORDER BY `created` DESC",
  276. 0, 1, $this->userid, $this->prefix.'.'.$key);
  277. if ($sql_arr = $this->db->fetch_assoc($sql_result)) {
  278. $key = substr($sql_arr['cache_key'], strlen($this->prefix)+1);
  279. $md5sum = $sql_arr['data'] ? md5($sql_arr['data']) : null;
  280. if ($sql_arr['data']) {
  281. $data = $this->unserialize($sql_arr['data']);
  282. }
  283. if ($nostore) {
  284. return $data;
  285. }
  286. $this->cache[$key] = $data;
  287. $this->cache_sums[$key] = $md5sum;
  288. }
  289. else {
  290. $this->cache[$key] = null;
  291. }
  292. }
  293. return $this->cache[$key];
  294. }
  295. /**
  296. * Writes single cache record into DB.
  297. *
  298. * @param string $key Cache key name
  299. * @param mixed $data Serialized cache data
  300. *
  301. * @param boolean True on success, False on failure
  302. */
  303. private function write_record($key, $data)
  304. {
  305. if (!$this->db) {
  306. return false;
  307. }
  308. // don't attempt to write too big data sets
  309. if (strlen($data) > $this->max_packet_size()) {
  310. trigger_error("rcube_cache: max_packet_size ($this->max_packet) exceeded for key $key. Tried to write " . strlen($data) . " bytes", E_USER_WARNING);
  311. return false;
  312. }
  313. if ($this->type == 'memcache' || $this->type == 'apc') {
  314. $result = $this->add_record($this->ckey($key), $data);
  315. // make sure index will be updated
  316. if ($result) {
  317. if (!array_key_exists($key, $this->cache_sums)) {
  318. $this->cache_sums[$key] = true;
  319. }
  320. $this->load_index();
  321. if (!$this->index_changed && !in_array($key, $this->index)) {
  322. $this->index_changed = true;
  323. }
  324. }
  325. return $result;
  326. }
  327. $key_exists = array_key_exists($key, $this->cache_sums);
  328. $key = $this->prefix . '.' . $key;
  329. // Remove NULL rows (here we don't need to check if the record exist)
  330. if ($data == 'N;') {
  331. $this->db->query(
  332. "DELETE FROM {$this->table}".
  333. " WHERE `user_id` = ? AND `cache_key` = ?",
  334. $this->userid, $key);
  335. return true;
  336. }
  337. // update existing cache record
  338. if ($key_exists) {
  339. $result = $this->db->query(
  340. "UPDATE {$this->table}".
  341. " SET `created` = " . $this->db->now().
  342. ", `expires` = " . ($this->ttl ? $this->db->now($this->ttl) : 'NULL').
  343. ", `data` = ?".
  344. " WHERE `user_id` = ?".
  345. " AND `cache_key` = ?",
  346. $data, $this->userid, $key);
  347. }
  348. // add new cache record
  349. else {
  350. // for better performance we allow more records for one key
  351. // so, no need to check if record exist (see rcube_cache::read_record())
  352. $result = $this->db->query(
  353. "INSERT INTO {$this->table}".
  354. " (`created`, `expires`, `user_id`, `cache_key`, `data`)".
  355. " VALUES (" . $this->db->now() . ", " . ($this->ttl ? $this->db->now($this->ttl) : 'NULL') . ", ?, ?, ?)",
  356. $this->userid, $key, $data);
  357. }
  358. return $this->db->affected_rows($result);
  359. }
  360. /**
  361. * Deletes the cache record(s).
  362. *
  363. * @param string $key Cache key name or pattern
  364. * @param boolean $prefix_mode Enable it to clear all keys starting
  365. * with prefix specified in $key
  366. */
  367. private function remove_record($key=null, $prefix_mode=false)
  368. {
  369. if (!$this->db) {
  370. return;
  371. }
  372. if ($this->type != 'db') {
  373. $this->load_index();
  374. // Remove all keys
  375. if ($key === null) {
  376. foreach ($this->index as $key) {
  377. $this->delete_record($this->ckey($key));
  378. }
  379. $this->index = array();
  380. }
  381. // Remove keys by name prefix
  382. else if ($prefix_mode) {
  383. foreach ($this->index as $idx => $k) {
  384. if (strpos($k, $key) === 0) {
  385. $this->delete_record($this->ckey($k));
  386. unset($this->index[$idx]);
  387. }
  388. }
  389. }
  390. // Remove one key by name
  391. else {
  392. $this->delete_record($this->ckey($key));
  393. if (($idx = array_search($key, $this->index)) !== false) {
  394. unset($this->index[$idx]);
  395. }
  396. }
  397. $this->index_changed = true;
  398. return;
  399. }
  400. // Remove all keys (in specified cache)
  401. if ($key === null) {
  402. $where = " AND `cache_key` LIKE " . $this->db->quote($this->prefix.'.%');
  403. }
  404. // Remove keys by name prefix
  405. else if ($prefix_mode) {
  406. $where = " AND `cache_key` LIKE " . $this->db->quote($this->prefix.'.'.$key.'%');
  407. }
  408. // Remove one key by name
  409. else {
  410. $where = " AND `cache_key` = " . $this->db->quote($this->prefix.'.'.$key);
  411. }
  412. $this->db->query(
  413. "DELETE FROM {$this->table} WHERE `user_id` = ?" . $where,
  414. $this->userid);
  415. }
  416. /**
  417. * Adds entry into memcache/apc DB.
  418. *
  419. * @param string $key Cache key name
  420. * @param mixed $data Serialized cache data
  421. *
  422. * @param boolean True on success, False on failure
  423. */
  424. private function add_record($key, $data)
  425. {
  426. if ($this->type == 'memcache') {
  427. $result = $this->db->replace($key, $data, MEMCACHE_COMPRESSED, $this->ttl);
  428. if (!$result) {
  429. $result = $this->db->set($key, $data, MEMCACHE_COMPRESSED, $this->ttl);
  430. }
  431. }
  432. else if ($this->type == 'apc') {
  433. if (apc_exists($key)) {
  434. apc_delete($key);
  435. }
  436. $result = apc_store($key, $data, $this->ttl);
  437. }
  438. if ($this->debug) {
  439. $this->debug('set', $key, $data, $result);
  440. }
  441. return $result;
  442. }
  443. /**
  444. * Deletes entry from memcache/apc DB.
  445. *
  446. * @param string $key Cache key name
  447. *
  448. * @param boolean True on success, False on failure
  449. */
  450. private function delete_record($key)
  451. {
  452. if ($this->type == 'memcache') {
  453. // #1488592: use 2nd argument
  454. $result = $this->db->delete($key, 0);
  455. }
  456. else {
  457. $result = apc_delete($key);
  458. }
  459. if ($this->debug) {
  460. $this->debug('delete', $key, null, $result);
  461. }
  462. return $result;
  463. }
  464. /**
  465. * Writes the index entry into memcache/apc DB.
  466. */
  467. private function write_index()
  468. {
  469. if (!$this->db || $this->type == 'db') {
  470. return;
  471. }
  472. $this->load_index();
  473. // Make sure index contains new keys
  474. foreach ($this->cache as $key => $value) {
  475. if ($value !== null && !in_array($key, $this->index)) {
  476. $this->index[] = $key;
  477. }
  478. }
  479. // new keys added using self::write()
  480. foreach ($this->cache_sums as $key => $value) {
  481. if ($value === true && !in_array($key, $this->index)) {
  482. $this->index[] = $key;
  483. }
  484. }
  485. $data = serialize($this->index);
  486. $this->add_record($this->ikey(), $data);
  487. }
  488. /**
  489. * Gets the index entry from memcache/apc DB.
  490. */
  491. private function load_index()
  492. {
  493. if (!$this->db || $this->type == 'db') {
  494. return;
  495. }
  496. if ($this->index !== null) {
  497. return;
  498. }
  499. $index_key = $this->ikey();
  500. if ($this->type == 'memcache') {
  501. $data = $this->db->get($index_key);
  502. }
  503. else if ($this->type == 'apc') {
  504. $data = apc_fetch($index_key);
  505. }
  506. if ($this->debug) {
  507. $this->debug('get', $index_key, $data);
  508. }
  509. $this->index = $data ? unserialize($data) : array();
  510. }
  511. /**
  512. * Creates per-user cache key name (for memcache and apc)
  513. *
  514. * @param string $key Cache key name
  515. *
  516. * @return string Cache key
  517. */
  518. private function ckey($key)
  519. {
  520. return sprintf('%d:%s:%s', $this->userid, $this->prefix, $key);
  521. }
  522. /**
  523. * Creates per-user index cache key name (for memcache and apc)
  524. *
  525. * @return string Cache key
  526. */
  527. private function ikey()
  528. {
  529. // This way each cache will have its own index
  530. return sprintf('%d:%s%s', $this->userid, $this->prefix, 'INDEX');
  531. }
  532. /**
  533. * Serializes data for storing
  534. */
  535. private function serialize($data)
  536. {
  537. if ($this->type == 'db') {
  538. return $this->db->encode($data, $this->packed);
  539. }
  540. return $this->packed ? serialize($data) : $data;
  541. }
  542. /**
  543. * Unserializes serialized data
  544. */
  545. private function unserialize($data)
  546. {
  547. if ($this->type == 'db') {
  548. return $this->db->decode($data, $this->packed);
  549. }
  550. return $this->packed ? @unserialize($data) : $data;
  551. }
  552. /**
  553. * Determine the maximum size for cache data to be written
  554. */
  555. private function max_packet_size()
  556. {
  557. if ($this->max_packet < 0) {
  558. $this->max_packet = 2097152; // default/max is 2 MB
  559. if ($this->type == 'db') {
  560. if ($value = $this->db->get_variable('max_allowed_packet', $this->max_packet)) {
  561. $this->max_packet = $value;
  562. }
  563. $this->max_packet -= 2000;
  564. }
  565. else if ($this->type == 'memcache') {
  566. if ($stats = $this->db->getStats()) {
  567. $remaining = $stats['limit_maxbytes'] - $stats['bytes'];
  568. $this->max_packet = min($remaining / 5, $this->max_packet);
  569. }
  570. }
  571. else if ($this->type == 'apc' && function_exists('apc_sma_info')) {
  572. if ($stats = apc_sma_info()) {
  573. $this->max_packet = min($stats['avail_mem'] / 5, $this->max_packet);
  574. }
  575. }
  576. }
  577. return $this->max_packet;
  578. }
  579. /**
  580. * Write memcache/apc debug info to the log
  581. */
  582. private function debug($type, $key, $data = null, $result = null)
  583. {
  584. $line = strtoupper($type) . ' ' . $key;
  585. if ($data !== null) {
  586. $line .= ' ' . ($this->packed ? $data : serialize($data));
  587. }
  588. rcube::debug($this->type, $line, $result);
  589. }
  590. }