source: subversion/branches/devel-mcache/roundcubemail/program/include/rcube_imap_cache.php @ 5193

Last change on this file since 5193 was 5193, checked in by alec, 21 months ago
  • Merge r5192 from trunk, I'll continue QRESYNC implementation here
  • Property svn:keywords set to Id Date Author
File size: 29.7 KB
Line 
1<?php
2
3/*
4 +-----------------------------------------------------------------------+
5 | program/include/rcube_imap_cache.php                                  |
6 |                                                                       |
7 | This file is part of the Roundcube Webmail client                     |
8 | Copyright (C) 2005-2011, The Roundcube Dev Team                       |
9 | Licensed under the GNU GPL                                            |
10 |                                                                       |
11 | PURPOSE:                                                              |
12 |   Caching of IMAP folder contents (messages and index)                |
13 |                                                                       |
14 +-----------------------------------------------------------------------+
15 | Author: Thomas Bruederli <roundcube@gmail.com>                        |
16 | Author: Aleksander Machniak <alec@alec.pl>                            |
17 +-----------------------------------------------------------------------+
18
19 $Id$
20
21*/
22
23
24/**
25 * Interface class for accessing Roundcube messages cache
26 *
27 * @package    Cache
28 * @author     Thomas Bruederli <roundcube@gmail.com>
29 * @author     Aleksander Machniak <alec@alec.pl>
30 * @version    1.0
31 */
32class rcube_imap_cache
33{
34    /**
35     * Instance of rcube_imap
36     *
37     * @var rcube_imap
38     */
39    private $imap;
40
41    /**
42     * Instance of rcube_mdb2
43     *
44     * @var rcube_mdb2
45     */
46    private $db;
47
48    /**
49     * User ID
50     *
51     * @var int
52     */
53    private $userid;
54
55    /**
56     * Internal (in-memory) cache
57     *
58     * @var array
59     */
60    private $icache = array();
61
62    private $skip_deleted = false;
63
64    public $flag_fields = array('seen', 'deleted', 'answered', 'forwarded', 'flagged', 'mdnsent');
65
66
67    /**
68     * Object constructor.
69     */
70    function __construct($db, $imap, $userid, $skip_deleted)
71    {
72        $this->db           = $db;
73        $this->imap         = $imap;
74        $this->userid       = (int)$userid;
75        $this->skip_deleted = $skip_deleted;
76    }
77
78
79    /**
80     * Cleanup actions (on shutdown).
81     */
82    public function close()
83    {
84        $this->save_icache();
85        $this->icache = null;
86    }
87
88
89    /**
90     * Return (sorted) messages index.
91     * If index doesn't exist or is invalid, will be updated.
92     *
93     * @param string  $mailbox     Folder name
94     * @param string  $sort_field  Sorting column
95     * @param string  $sort_order  Sorting order (ASC|DESC)
96     * @param bool    $exiting     Skip index initialization if it doesn't exist in DB
97     *
98     * @return array Messages index
99     */
100    function get_index($mailbox, $sort_field = null, $sort_order = null, $existing = false)
101    {
102        if (empty($this->icache[$mailbox]))
103            $this->icache[$mailbox] = array();
104
105        $sort_order = strtoupper($sort_order) == 'ASC' ? 'ASC' : 'DESC';
106
107        // Seek in internal cache
108        if (array_key_exists('index', $this->icache[$mailbox])
109            && ($sort_field == 'ANY' || $this->icache[$mailbox]['index']['sort_field'] == $sort_field)
110        ) {
111            if ($this->icache[$mailbox]['index']['sort_order'] == $sort_order)
112                return $this->icache[$mailbox]['index']['result'];
113            else
114                return array_reverse($this->icache[$mailbox]['index']['result'], true);
115        }
116
117        // Get index from DB (if DB wasn't already queried)
118        if (empty($this->icache[$mailbox]['index_queried'])) {
119            $index = $this->get_index_row($mailbox);
120
121            // set the flag that DB was already queried for index
122            // this way we'll be able to skip one SELECT, when
123            // get_index() is called more than once
124            $this->icache[$mailbox]['index_queried'] = true;
125        }
126        $data  = null;
127
128        // @TODO: Think about skipping validation checks.
129        // If we could check only every 10 minutes, we would be able to skip
130        // expensive checks, mailbox selection or even IMAP connection, this would require
131        // additional logic to force cache invalidation in some cases
132        // and many rcube_imap changes to connect when needed
133
134        // Entry exist, check cache status
135        if (!empty($index)) {
136            $exists = true;
137
138            if ($sort_field == 'ANY') {
139                $sort_field = $index['sort_field'];
140            }
141
142            if ($sort_field != $index['sort_field']) {
143                $is_valid = false;
144            }
145            else {
146                $is_valid = $this->validate($mailbox, $index, $exists);
147            }
148
149            if ($is_valid) {
150                // build index, assign sequence IDs to unique IDs
151                $data = array_combine($index['seq'], $index['uid']);
152                // revert the order if needed
153                if ($index['sort_order'] != $sort_order)
154                    $data = array_reverse($data, true);
155            }
156        }
157        else {
158            // Got it in internal cache, so the row already exist
159            $exists = array_key_exists('index', $this->icache[$mailbox]);
160
161            if ($existing) {
162                return null;
163            }
164            else if ($sort_field == 'ANY') {
165                $sort_field = '';
166            }
167        }
168
169        // Index not found, not valid or sort field changed, get index from IMAP server
170        if ($data === null) {
171            // Get mailbox data (UIDVALIDITY, counters, etc.) for status check
172            $mbox_data = $this->imap->mailbox_data($mailbox);
173            $data      = array();
174
175            // Prevent infinite loop.
176            // It happens when rcube_imap::message_index_direct() is called.
177            // There id2uid() is called which will again call get_index() and so on.
178            if (!$sort_field && !$this->skip_deleted)
179                $this->icache['pending_index_update'] = true;
180
181            if ($mbox_data['EXISTS']) {
182                // fetch sorted sequence numbers
183                $data_seq = $this->imap->message_index_direct($mailbox, $sort_field, $sort_order);
184                // fetch UIDs
185                if (!empty($data_seq)) {
186                    // Seek in internal cache
187                    if (array_key_exists('index', (array)$this->icache[$mailbox]))
188                        $data_uid = $this->icache[$mailbox]['index']['result'];
189                    else
190                        $data_uid = $this->imap->conn->fetchUIDs($mailbox, $data_seq);
191
192                    // build index
193                    if (!empty($data_uid)) {
194                        foreach ($data_seq as $seq)
195                            if ($uid = $data_uid[$seq])
196                                $data[$seq] = $uid;
197                    }
198                }
199            }
200
201            // Reset internal flags
202            $this->icache['pending_index_update'] = false;
203
204            // insert/update
205            $this->add_index_row($mailbox, $sort_field, $sort_order, $data, $mbox_data, $exists);
206        }
207
208        $this->icache[$mailbox]['index'] = array(
209            'result'     => $data,
210            'sort_field' => $sort_field,
211            'sort_order' => $sort_order,
212        );
213
214        return $data;
215    }
216
217
218    /**
219     * Return messages thread.
220     * If threaded index doesn't exist or is invalid, will be updated.
221     *
222     * @param string  $mailbox     Folder name
223     * @param string  $sort_field  Sorting column
224     * @param string  $sort_order  Sorting order (ASC|DESC)
225     *
226     * @return array Messages threaded index
227     */
228    function get_thread($mailbox)
229    {
230        if (empty($this->icache[$mailbox]))
231            $this->icache[$mailbox] = array();
232
233        // Seek in internal cache
234        if (array_key_exists('thread', $this->icache[$mailbox])) {
235            return array(
236                $this->icache[$mailbox]['thread']['tree'],
237                $this->icache[$mailbox]['thread']['depth'],
238                $this->icache[$mailbox]['thread']['children'],
239            );
240        }
241
242        // Get index from DB
243        $index = $this->get_thread_row($mailbox);
244        $data  = null;
245
246        // Entry exist, check cache status
247        if (!empty($index)) {
248            $exists   = true;
249            $is_valid = $this->validate($mailbox, $index, $exists);
250
251            if (!$is_valid) {
252                $index = null;
253            }
254        }
255
256        // Index not found or not valid, get index from IMAP server
257        if ($index === null) {
258            // Get mailbox data (UIDVALIDITY, counters, etc.) for status check
259            $mbox_data = $this->imap->mailbox_data($mailbox);
260
261            if ($mbox_data['EXISTS']) {
262                // get all threads (default sort order)
263                list ($thread_tree, $msg_depth, $has_children) = $this->imap->fetch_threads($mailbox, true);
264            }
265
266            $index = array(
267                'tree'     => !empty($thread_tree) ? $thread_tree : array(),
268                'depth'    => !empty($msg_depth) ? $msg_depth : array(),
269                'children' => !empty($has_children) ? $has_children : array(),
270            );
271
272            // insert/update
273            $this->add_thread_row($mailbox, $index, $mbox_data, $exists);
274        }
275
276        $this->icache[$mailbox]['thread'] = $index;
277
278        return array($index['tree'], $index['depth'], $index['children']);
279    }
280
281
282    /**
283     * Returns list of messages (headers). See rcube_imap::fetch_headers().
284     *
285     * @param string $mailbox  Folder name
286     * @param array  $msgs     Message sequence numbers
287     * @param bool   $is_uid   True if $msgs contains message UIDs
288     *
289     * @return array The list of messages (rcube_mail_header) indexed by UID
290     */
291    function get_messages($mailbox, $msgs = array(), $is_uid = true)
292    {
293        if (empty($msgs)) {
294            return array();
295        }
296
297        // Convert IDs to UIDs
298        // @TODO: it would be nice if we could work with UIDs only
299        // then, e.g. when fetching search result, index would be not needed
300        if (!$is_uid) {
301            $index = $this->get_index($mailbox, 'ANY');
302            foreach ($msgs as $idx => $msgid)
303                if ($uid = $index[$msgid])
304                    $msgs[$idx] = $uid;
305        }
306
307        $flag_fields = implode(', ', array_map(array($this->db, 'quoteIdentifier'), $this->flag_fields));
308
309        // Fetch messages from cache
310        $sql_result = $this->db->query(
311            "SELECT uid, data, ".$flag_fields
312            ." FROM ".get_table_name('cache_messages')
313            ." WHERE user_id = ?"
314                ." AND mailbox = ?"
315                ." AND uid IN (".$this->db->array2list($msgs, 'integer').")",
316            $this->userid, $mailbox);
317
318        $msgs   = array_flip($msgs);
319        $result = array();
320
321        while ($sql_arr = $this->db->fetch_assoc($sql_result)) {
322            $uid          = intval($sql_arr['uid']);
323            $result[$uid] = $this->build_message($sql_arr);
324            // save memory, we don't need a body here
325            $result[$uid]->body = null;
326//@TODO: update message ID according to index data?
327
328            if (!empty($result[$uid])) {
329                unset($msgs[$uid]);
330            }
331        }
332
333        // Fetch not found messages from IMAP server
334        if (!empty($msgs)) {
335            $messages = $this->imap->fetch_headers($mailbox, array_keys($msgs), true, true);
336
337            // Insert to DB and add to result list
338            if (!empty($messages)) {
339                foreach ($messages as $msg) {
340                    $this->add_message($mailbox, $msg, !array_key_exists($msg->uid, $result));
341                    $result[$msg->uid] = $msg;
342                }
343            }
344        }
345
346        return $result;
347    }
348
349
350    /**
351     * Returns message data.
352     *
353     * @param string $mailbox  Folder name
354     * @param int    $uid      Message UID
355     *
356     * @return rcube_mail_header Message data
357     */
358    function get_message($mailbox, $uid)
359    {
360        // Check internal cache
361        if (($message = $this->icache['message'])
362            && $message['mailbox'] == $mailbox && $message['object']->uid == $uid
363        ) {
364            return $this->icache['message']['object'];
365        }
366
367        $flag_fields = implode(', ', array_map(array($this->db, 'quoteIdentifier'), $this->flag_fields));
368
369        $sql_result = $this->db->query(
370            "SELECT data, ".$flag_fields
371            ." FROM ".get_table_name('cache_messages')
372            ." WHERE user_id = ?"
373                ." AND mailbox = ?"
374                ." AND uid = ?",
375                $this->userid, $mailbox, (int)$uid);
376
377        if ($sql_arr = $this->db->fetch_assoc($sql_result)) {
378            $message = $this->build_message($sql_arr);
379            $found   = true;
380
381//@TODO: update message ID according to index data?
382        }
383
384        // Get the message from IMAP server
385        if (empty($message)) {
386            $message = $this->imap->get_headers($uid, $mailbox, true);
387            // cache will be updated in close(), see below
388        }
389
390        // Save the message in internal cache, will be written to DB in close()
391        // Common scenario: user opens unseen message
392        // - get message (SELECT)
393        // - set message headers/structure (INSERT or UPDATE)
394        // - set \Seen flag (UPDATE)
395        // This way we can skip one UPDATE
396        if (!empty($message)) {
397            // Save current message from internal cache
398            $this->save_icache();
399
400            $this->icache['message'] = array(
401                'object'  => $message,
402                'mailbox' => $mailbox,
403                'exists'  => $found,
404                'md5sum'  => md5(serialize($message)),
405            );
406        }
407
408        return $message;
409    }
410
411
412    /**
413     * Saves the message in cache.
414     *
415     * @param string            $mailbox  Folder name
416     * @param rcube_mail_header $message  Message data
417     * @param bool              $force    Skips message in-cache existance check
418     */
419    function add_message($mailbox, $message, $force = false)
420    {
421        if (!is_object($message) || empty($message->uid))
422            return;
423
424        $msg = serialize($this->db->encode(clone $message));
425
426        $flag_fields = array_map(array($this->db, 'quoteIdentifier'), $this->flag_fields);
427        $flag_values = array();
428
429        foreach ($this->flag_fields as $flag)
430            $flag_values[] = (int) $message->$flag;
431
432        // update cache record (even if it exists, the update
433        // here will work as select, assume row exist if affected_rows=0)
434        if (!$force) {
435            foreach ($flag_fields as $key => $val)
436                $flag_data[] = $val . " = " . $flag_values[$key];
437
438            $res = $this->db->query(
439                "UPDATE ".get_table_name('cache_messages')
440                ." SET data = ?, changed = ".$this->db->now()
441                .", " . implode(', ', $flag_data)
442                ." WHERE user_id = ?"
443                    ." AND mailbox = ?"
444                    ." AND uid = ?",
445                $msg, $this->userid, $mailbox, (int) $message->uid);
446
447            if ($this->db->affected_rows())
448                return;
449        }
450
451        // insert new record
452        $this->db->query(
453            "INSERT INTO ".get_table_name('cache_messages')
454            ." (user_id, mailbox, uid, changed, data, " . implode(', ', $flag_fields) . ")"
455            ." VALUES (?, ?, ?, ".$this->db->now().", ?, " . implode(', ', $flag_values) . ")",
456            $this->userid, $mailbox, (int) $message->uid, $msg);
457    }
458
459
460    /**
461     * Sets the flag for specified message.
462     *
463     * @param string  $mailbox  Folder name
464     * @param array   $uids     Message UIDs or null to change flag
465     *                          of all messages in a folder
466     * @param string  $flag     The name of the flag
467     * @param bool    $enabled  Flag state
468     */
469    function change_flag($mailbox, $uids, $flag, $enabled = false)
470    {
471        $flag = strtolower($flag);
472
473        if (in_array($flag, $this->flag_fields)) {
474            // Internal cache update
475            if ($uids && count($uids) == 1 && ($uid = current($uids))
476                && ($message = $this->icache['message'])
477                && $message['mailbox'] == $mailbox && $message['object']->uid == $uid
478            ) {
479                $message['object']->$flag = $enabled;
480                return;
481            }
482
483            $this->db->query(
484                "UPDATE ".get_table_name('cache_messages')
485                ." SET changed = ".$this->db->now()
486                .", " .$this->db->quoteIdentifier($flag) . " = " . intval($enabled)
487                ." WHERE user_id = ?"
488                    ." AND mailbox = ?"
489                    .($uids !== null ? " AND uid IN (".$this->db->array2list((array)$uids, 'integer').")" : ""),
490                $this->userid, $mailbox);
491        }
492        else {
493            // @TODO: SELECT+UPDATE?
494            $this->remove_message($mailbox, $uids);
495        }
496    }
497
498
499    /**
500     * Removes message(s) from cache.
501     *
502     * @param string $mailbox  Folder name
503     * @param array  $uids     Message UIDs, NULL removes all messages
504     */
505    function remove_message($mailbox = null, $uids = null)
506    {
507        if (!strlen($mailbox)) {
508            $this->db->query(
509                "DELETE FROM ".get_table_name('cache_messages')
510                ." WHERE user_id = ?",
511                $this->userid);
512        }
513        else {
514            // Remove the message from internal cache
515            if (!empty($uids) && !is_array($uids) && ($message = $this->icache['message'])
516                && $message['mailbox'] == $mailbox && $message['object']->uid == $uids
517            ) {
518                $this->icache['message'] = null;
519            }
520
521            $this->db->query(
522                "DELETE FROM ".get_table_name('cache_messages')
523                ." WHERE user_id = ?"
524                    ." AND mailbox = ".$this->db->quote($mailbox)
525                    .($uids !== null ? " AND uid IN (".$this->db->array2list((array)$uids, 'integer').")" : ""),
526                $this->userid);
527        }
528
529    }
530
531
532    /**
533     * Clears index cache.
534     *
535     * @param string  $mailbox     Folder name
536     */
537    function remove_index($mailbox = null)
538    {
539        $this->db->query(
540            "DELETE FROM ".get_table_name('cache_index')
541            ." WHERE user_id = ".intval($this->userid)
542                .(strlen($mailbox) ? " AND mailbox = ".$this->db->quote($mailbox) : "")
543        );
544
545        if (strlen($mailbox))
546            unset($this->icache[$mailbox]['index']);
547        else
548            $this->icache = array();
549    }
550
551
552    /**
553     * Clears thread cache.
554     *
555     * @param string  $mailbox     Folder name
556     */
557    function remove_thread($mailbox = null)
558    {
559        $this->db->query(
560            "DELETE FROM ".get_table_name('cache_thread')
561            ." WHERE user_id = ".intval($this->userid)
562                .(strlen($mailbox) ? " AND mailbox = ".$this->db->quote($mailbox) : "")
563        );
564
565        if (strlen($mailbox))
566            unset($this->icache[$mailbox]['thread']);
567        else
568            $this->icache = array();
569    }
570
571
572    /**
573     * Clears the cache.
574     *
575     * @param string $mailbox  Folder name
576     * @param array  $uids     Message UIDs, NULL removes all messages in a folder
577     */
578    function clear($mailbox = null, $uids = null)
579    {
580        $this->remove_index($mailbox);
581        $this->remove_thread($mailbox);
582        $this->remove_message($mailbox, $uids);
583    }
584
585
586    /**
587     * @param string $mailbox Folder name
588     * @param int    $id      Message (sequence) ID
589     *
590     * @return int Message UID
591     */
592    function id2uid($mailbox, $id)
593    {
594        if (!empty($this->icache['pending_index_update']))
595            return null;
596
597        // get index if it exists
598        $index = $this->get_index($mailbox, 'ANY', null, true);
599
600        return $index[$id];
601    }
602
603
604    /**
605     * @param string $mailbox Folder name
606     * @param int    $uid     Message UID
607     *
608     * @return int Message (sequence) ID
609     */
610    function uid2id($mailbox, $uid)
611    {
612        if (!empty($this->icache['pending_index_update']))
613            return null;
614
615        // get index if it exists
616        $index = $this->get_index($mailbox, 'ANY', null, true);
617
618        return array_search($uid, (array)$index);
619    }
620
621
622    /**
623     * Fetches index data from database
624     */
625    private function get_index_row($mailbox)
626    {
627        // Get index from DB
628        $sql_result = $this->db->query(
629            "SELECT data"
630            ." FROM ".get_table_name('cache_index')
631            ." WHERE user_id = ?"
632                ." AND mailbox = ?",
633            $this->userid, $mailbox);
634
635        if ($sql_arr = $this->db->fetch_assoc($sql_result)) {
636            $data = explode('@', $sql_arr['data']);
637
638            return array(
639                'seq'        => explode(',', $data[0]),
640                'uid'        => explode(',', $data[1]),
641                'sort_field' => $data[2],
642                'sort_order' => $data[3],
643                'deleted'    => $data[4],
644                'validity'   => $data[5],
645                'uidnext'    => $data[6],
646            );
647        }
648
649        return null;
650    }
651
652
653    /**
654     * Fetches thread data from database
655     */
656    private function get_thread_row($mailbox)
657    {
658        // Get thread from DB
659        $sql_result = $this->db->query(
660            "SELECT data"
661            ." FROM ".get_table_name('cache_thread')
662            ." WHERE user_id = ?"
663                ." AND mailbox = ?",
664            $this->userid, $mailbox);
665
666        if ($sql_arr = $this->db->fetch_assoc($sql_result)) {
667            $data = explode('@', $sql_arr['data']);
668
669            $data[0] = unserialize($data[0]);
670            // build 'depth' and 'children' arrays
671            $depth = $children = array();
672            $this->build_thread_data($data[0], $depth, $children);
673
674            return array(
675                'tree'     => $data[0],
676                'depth'    => $depth,
677                'children' => $children,
678                'deleted'  => $data[1],
679                'validity' => $data[2],
680                'uidnext'  => $data[3],
681            );
682        }
683
684        return null;
685    }
686
687
688    /**
689     * Saves index data into database
690     */
691    private function add_index_row($mailbox, $sort_field, $sort_order,
692        $data = array(), $mbox_data = array(), $exists = false)
693    {
694        $data = array(
695            implode(',', array_keys($data)),
696            implode(',', array_values($data)),
697            $sort_field,
698            $sort_order,
699            (int) $this->skip_deleted,
700            (int) $mbox_data['UIDVALIDITY'],
701            (int) $mbox_data['UIDNEXT'],
702        );
703        $data = implode('@', $data);
704
705        if ($exists)
706            $sql_result = $this->db->query(
707                "UPDATE ".get_table_name('cache_index')
708                ." SET data = ?, changed = ".$this->db->now()
709                ." WHERE user_id = ?"
710                    ." AND mailbox = ?",
711                $data, $this->userid, $mailbox);
712        else
713            $sql_result = $this->db->query(
714                "INSERT INTO ".get_table_name('cache_index')
715                ." (user_id, mailbox, data, changed)"
716                ." VALUES (?, ?, ?, ".$this->db->now().")",
717                $this->userid, $mailbox, $data);
718    }
719
720
721    /**
722     * Saves thread data into database
723     */
724    private function add_thread_row($mailbox, $data = array(), $mbox_data = array(), $exists = false)
725    {
726        $data = array(
727            serialize($data['tree']),
728            (int) $this->skip_deleted,
729            (int) $mbox_data['UIDVALIDITY'],
730            (int) $mbox_data['UIDNEXT'],
731        );
732        $data = implode('@', $data);
733
734        if ($exists)
735            $sql_result = $this->db->query(
736                "UPDATE ".get_table_name('cache_thread')
737                ." SET data = ?, changed = ".$this->db->now()
738                ." WHERE user_id = ?"
739                    ." AND mailbox = ?",
740                $data, $this->userid, $mailbox);
741        else
742            $sql_result = $this->db->query(
743                "INSERT INTO ".get_table_name('cache_thread')
744                ." (user_id, mailbox, data, changed)"
745                ." VALUES (?, ?, ?, ".$this->db->now().")",
746                $this->userid, $mailbox, $data);
747    }
748
749
750    /**
751     * Checks index/thread validity
752     */
753    private function validate($mailbox, $index, &$exists = true)
754    {
755        $is_thread = isset($index['tree']);
756
757        // Get mailbox data (UIDVALIDITY, counters, etc.) for status check
758        $mbox_data = $this->imap->mailbox_data($mailbox);
759
760        // @TODO: Think about skipping validation checks.
761        // If we could check only every 10 minutes, we would be able to skip
762        // expensive checks, mailbox selection or even IMAP connection, this would require
763        // additional logic to force cache invalidation in some cases
764        // and many rcube_imap changes to connect when needed
765
766        // Check UIDVALIDITY
767        // @TODO: while we're storing message sequence numbers in thread
768        //        index, should UIDVALIDITY invalidate the thread data?
769        if ($index['validity'] != $mbox_data['UIDVALIDITY']) {
770            // the whole cache (all folders) is invalid
771            $this->clear();
772            $exists = false;
773            return false;
774        }
775
776        // Folder is empty but cache isn't
777        if (empty($mbox_data['EXISTS']) && (!empty($index['seq']) || !empty($index['tree']))) {
778            $this->clear($mailbox);
779            $exists = false;
780            return false;
781        }
782
783        // Check UIDNEXT
784        if ($index['uidnext'] != $mbox_data['UIDNEXT']) {
785            unset($this->icache[$mailbox][$is_thread ? 'thread' : 'index']);
786            return false;
787        }
788
789        // Index was created with different skip_deleted setting
790        if ($this->skip_deleted != $index['deleted']) {
791            return false;
792        }
793
794        // @TODO: find better validity check for threaded index
795        if ($is_thread) {
796            // check messages number...
797            if ($mbox_data['EXISTS'] != max(array_keys($index['depth']))) {
798                return false;
799            }
800            return true;
801        }
802
803        // The rest of checks, more expensive
804        if (!empty($this->skip_deleted)) {
805            // compare counts if available
806            if ($mbox_data['COUNT_UNDELETED'] != null
807                && $mbox_data['COUNT_UNDELETED'] != count($index['uid'])) {
808                return false;
809            }
810            // compare UID sets
811            if ($mbox_data['ALL_UNDELETED'] != null) {
812                $uids_new = rcube_imap_generic::uncompressMessageSet($mbox_data['ALL_UNDELETED']);
813                $uids_old = $index['uid'];
814
815                if (count($uids_new) != count($uids_old)) {
816                    return false;
817                }
818
819                sort($uids_new, SORT_NUMERIC);
820                sort($uids_old, SORT_NUMERIC);
821
822                if ($uids_old != $uids_new)
823                    return false;
824            }
825            else {
826                // get all undeleted messages excluding cached UIDs
827                $ids = $this->imap->search_once($mailbox, 'ALL UNDELETED NOT UID '.
828                    rcube_imap_generic::compressMessageSet($index['uid']));
829
830                if (!empty($ids)) {
831                    $index = null; // cache invalid
832                }
833            }
834        }
835        else {
836            // check messages number...
837            if ($mbox_data['EXISTS'] != max($index['seq'])) {
838                return false;
839            }
840            // ... and max UID
841            if (max($index['uid']) != $this->imap->id2uid($mbox_data['EXISTS'], $mailbox, true)) {
842                return false;
843            }
844        }
845
846        return true;
847    }
848
849
850    /**
851     * Converts cache row into message object.
852     *
853     * @param array $sql_arr Message row data
854     *
855     * @return rcube_mail_header Message object
856     */
857    private function build_message($sql_arr)
858    {
859        $message = $this->db->decode(unserialize($sql_arr['data']));
860
861        if ($message) {
862            foreach ($this->flag_fields as $field)
863                $message->$field = (bool) $sql_arr[$field];
864        }
865
866        return $message;
867    }
868
869
870    /**
871     * Creates 'depth' and 'children' arrays from stored thread 'tree' data.
872     */
873    private function build_thread_data($data, &$depth, &$children, $level = 0)
874    {
875        foreach ((array)$data as $key => $val) {
876            $children[$key] = !empty($val);
877            $depth[$key] = $level;
878            if (!empty($val))
879                $this->build_thread_data($val, $depth, $children, $level + 1);
880        }
881    }
882
883
884    /**
885     * Saves message stored in internal cache
886     */
887    private function save_icache()
888    {
889        // Save current message from internal cache
890        if ($message = $this->icache['message']) {
891            // clean up some object's data
892            $object = $this->message_object_prepare($message['object']);
893
894            // calculate current md5 sum
895            $md5sum = md5(serialize($object));
896
897            if ($message['md5sum'] != $md5sum) {
898                $this->add_message($message['mailbox'], $object, !$message['exists']);
899            }
900
901            $this->icache['message']['md5sum'] = $md5sum;
902        }
903    }
904
905
906    /**
907     * Prepares message object to be stored in database.
908     */
909    private function message_object_prepare($msg, $recursive = false)
910    {
911        // Remove body too big (>500kB)
912        if ($recursive || ($msg->body && strlen($msg->body) > 500 * 1024)) {
913            unset($msg->body);
914        }
915
916        // Fix mimetype which might be broken by some code when message is displayed
917        // Another solution would be to use object's copy in rcube_message class
918        // to prevent related issues, however I'm not sure which is better
919        if ($msg->mimetype) {
920            list($msg->ctype_primary, $msg->ctype_secondary) = explode('/', $msg->mimetype);
921        }
922
923        if (is_array($msg->structure->parts)) {
924            foreach ($msg->structure->parts as $idx => $part) {
925                $msg->structure->parts[$idx] = $this->message_object_prepare($part, true);
926            }
927        }
928
929        return $msg;
930    }
931}
Note: See TracBrowser for help on using the repository browser.