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