4 +-----------------------------------------------------------------------+
5 | program/include/rcube_imap.php |
7 | This file is part of the Roundcube Webmail client |
8 | Copyright (C) 2005-2010, Roundcube Dev. - Switzerland |
9 | Licensed under the GNU GPL |
14 +-----------------------------------------------------------------------+
15 | Author: Thomas Bruederli <roundcube@gmail.com> |
16 | Author: Aleksander Machniak <alec@alec.pl> |
17 +-----------------------------------------------------------------------+
19 $Id: rcube_imap.php 4643 2011-04-11 12:24:00Z alec $
25 * Interface class for accessing an IMAP server
28 * @author Thomas Bruederli <roundcube@gmail.com>
29 * @author Aleksander Machniak <alec@alec.pl>
34 public $debug_level = 1;
35 public $skip_deleted = false;
36 public $page_size = 10;
37 public $list_page = 1;
38 public $threading = false;
39 public $fetch_add_headers = '';
40 public $get_all_headers = false;
43 * Instance of rcube_imap_generic
45 * @var rcube_imap_generic
50 * Instance of rcube_mdb2
55 private $mailbox = 'INBOX';
56 private $delimiter = NULL;
57 private $namespace = NULL;
58 private $sort_field = '';
59 private $sort_order = 'DESC';
60 private $caching_enabled = false;
61 private $default_charset = 'ISO-8859-1';
62 private $struct_charset = NULL;
63 private $default_folders = array('INBOX');
64 private $icache = array();
65 private $cache = array();
66 private $cache_keys = array();
67 private $cache_changes = array();
68 private $uid_id_map = array();
69 private $msg_headers = array();
70 public $search_set = NULL;
71 public $search_string = '';
72 private $search_charset = '';
73 private $search_sort_field = '';
74 private $search_threads = false;
75 private $search_sorted = false;
76 private $db_header_fields = array('idx', 'uid', 'subject', 'from', 'to', 'cc', 'date', 'size');
77 private $options = array('auth_method' => 'check');
78 private $host, $user, $pass, $port, $ssl;
81 * All (additional) headers used (in any way) by Roundcube
82 * Not listed here: DATE, FROM, TO, SUBJECT, CONTENT-TYPE, LIST-POST
83 * (used for messages listing) are hardcoded in rcube_imap_generic::fetchHeaders()
86 * @see rcube_imap::fetch_add_headers
88 private $all_headers = array(
94 'CONTENT-TRANSFER-ENCODING',
109 const ALREADYEXISTS = 6;
110 const NONEXISTENT = 7;
111 const CONTACTADMIN = 8;
117 * @param object DB Database connection
119 function __construct($db_conn)
121 $this->db = $db_conn;
122 $this->conn = new rcube_imap_generic();
127 * Connect to an IMAP server
129 * @param string $host Host to connect
130 * @param string $user Username for IMAP account
131 * @param string $pass Password for IMAP account
132 * @param integer $port Port to connect to
133 * @param string $use_ssl SSL schema (either ssl or tls) or null if plain connection
134 * @return boolean TRUE on success, FALSE on failure
137 function connect($host, $user, $pass, $port=143, $use_ssl=null)
139 // check for OpenSSL support in PHP build
140 if ($use_ssl && extension_loaded('openssl'))
141 $this->options['ssl_mode'] = $use_ssl == 'imaps' ? 'ssl' : $use_ssl;
143 raise_error(array('code' => 403, 'type' => 'imap',
144 'file' => __FILE__, 'line' => __LINE__,
145 'message' => "OpenSSL not available"), true, false);
149 $this->options['port'] = $port;
151 if ($this->options['debug']) {
152 $this->conn->setDebug(true, array($this, 'debug_handler'));
154 $this->options['ident'] = array(
155 'name' => 'Roundcube Webmail',
156 'version' => RCMAIL_VERSION,
157 'php' => PHP_VERSION,
159 'command' => $_SERVER['REQUEST_URI'],
165 $data = rcmail::get_instance()->plugins->exec_hook('imap_connect',
166 array('host' => $host, 'user' => $user, 'attempt' => ++$attempt));
168 if (!empty($data['pass']))
169 $pass = $data['pass'];
171 $this->conn->connect($data['host'], $data['user'], $pass, $this->options);
172 } while(!$this->conn->connected() && $data['retry']);
174 $this->host = $data['host'];
175 $this->user = $data['user'];
178 $this->ssl = $use_ssl;
180 if ($this->conn->connected()) {
181 // get namespace and delimiter
186 else if ($this->conn->error) {
187 if ($pass && $user) {
188 $message = sprintf("Login failed for %s from %s. %s",
189 $user, rcmail_remote_ip(), $this->conn->error);
191 raise_error(array('code' => 403, 'type' => 'imap',
192 'file' => __FILE__, 'line' => __LINE__,
193 'message' => $message), true, false);
202 * Close IMAP connection
203 * Usually done on script shutdown
209 $this->conn->closeConnection();
210 $this->write_cache();
215 * Close IMAP connection and re-connect
216 * This is used to avoid some strange socket errors when talking to Courier IMAP
222 $this->conn->closeConnection();
223 $connected = $this->connect($this->host, $this->user, $this->pass, $this->port, $this->ssl);
225 // issue SELECT command to restore connection status
226 if ($connected && strlen($this->mailbox))
227 $this->conn->select($this->mailbox);
232 * Returns code of last error
234 * @return int Error code
236 function get_error_code()
238 return $this->conn->errornum;
243 * Returns message of last error
245 * @return string Error message
247 function get_error_str()
249 return $this->conn->error;
254 * Returns code of last command response
256 * @return int Response code
258 function get_response_code()
260 switch ($this->conn->resultcode) {
264 return self::READONLY;
266 return self::TRYCREATE;
270 return self::OVERQUOTA;
271 case 'ALREADYEXISTS':
272 return self::ALREADYEXISTS;
274 return self::NONEXISTENT;
276 return self::CONTACTADMIN;
278 return self::UNKNOWN;
284 * Returns last command response
286 * @return string Response
288 function get_response_str()
290 return $this->conn->result;
295 * Set options to be used in rcube_imap_generic::connect()
297 * @param array $opt Options array
299 function set_options($opt)
301 $this->options = array_merge($this->options, (array)$opt);
306 * Set default message charset
308 * This will be used for message decoding if a charset specification is not available
310 * @param string $cs Charset string
313 function set_charset($cs)
315 $this->default_charset = $cs;
320 * This list of folders will be listed above all other folders
322 * @param array $arr Indexed list of folder names
325 function set_default_mailboxes($arr)
327 if (is_array($arr)) {
328 $this->default_folders = $arr;
330 // add inbox if not included
331 if (!in_array('INBOX', $this->default_folders))
332 array_unshift($this->default_folders, 'INBOX');
338 * Set internal mailbox reference.
340 * All operations will be perfomed on this mailbox/folder
342 * @param string $new_mbox Mailbox/Folder name
345 function set_mailbox($new_mbox)
347 $mailbox = $this->mod_mailbox($new_mbox);
349 if ($this->mailbox == $mailbox)
352 $this->mailbox = $mailbox;
354 // clear messagecount cache for this mailbox
355 $this->_clear_messagecount($mailbox);
360 * Forces selection of a mailbox
362 * @param string $mailbox Mailbox/Folder name
365 function select_mailbox($mailbox=null)
367 $mailbox = strlen($mailbox) ? $this->mod_mailbox($mailbox) : $this->mailbox;
369 $selected = $this->conn->select($mailbox);
371 if ($selected && $this->mailbox != $mailbox) {
372 // clear messagecount cache for this mailbox
373 $this->_clear_messagecount($mailbox);
374 $this->mailbox = $mailbox;
380 * Set internal list page
382 * @param number $page Page number to list
385 function set_page($page)
387 $this->list_page = (int)$page;
392 * Set internal page size
394 * @param number $size Number of messages to display on one page
397 function set_pagesize($size)
399 $this->page_size = (int)$size;
404 * Save a set of message ids for future message listing methods
406 * @param string IMAP Search query
407 * @param array List of message ids or NULL if empty
408 * @param string Charset of search string
409 * @param string Sorting field
410 * @param string True if set is sorted (SORT was used for searching)
412 function set_search_set($str=null, $msgs=null, $charset=null, $sort_field=null, $threads=false, $sorted=false)
414 if (is_array($str) && $msgs == null)
415 list($str, $msgs, $charset, $sort_field, $threads) = $str;
418 else if ($msgs != null && !is_array($msgs))
419 $msgs = explode(',', $msgs);
421 $this->search_string = $str;
422 $this->search_set = $msgs;
423 $this->search_charset = $charset;
424 $this->search_sort_field = $sort_field;
425 $this->search_threads = $threads;
426 $this->search_sorted = $sorted;
431 * Return the saved search set as hash array
432 * @return array Search set
434 function get_search_set()
436 return array($this->search_string,
438 $this->search_charset,
439 $this->search_sort_field,
440 $this->search_threads,
441 $this->search_sorted,
447 * Returns the currently used mailbox name
449 * @return string Name of the mailbox/folder
452 function get_mailbox_name()
454 return $this->conn->connected() ? $this->mod_mailbox($this->mailbox, 'out') : '';
459 * Returns the IMAP server's capability
461 * @param string $cap Capability name
462 * @return mixed Capability value or TRUE if supported, FALSE if not
465 function get_capability($cap)
467 return $this->conn->getCapability(strtoupper($cap));
472 * Sets threading flag to the best supported THREAD algorithm
474 * @param boolean $enable TRUE to enable and FALSE
475 * @return string Algorithm or false if THREAD is not supported
478 function set_threading($enable=false)
480 $this->threading = false;
482 if ($enable && ($caps = $this->get_capability('THREAD'))) {
483 if (in_array('REFS', $caps))
484 $this->threading = 'REFS';
485 else if (in_array('REFERENCES', $caps))
486 $this->threading = 'REFERENCES';
487 else if (in_array('ORDEREDSUBJECT', $caps))
488 $this->threading = 'ORDEREDSUBJECT';
491 return $this->threading;
496 * Checks the PERMANENTFLAGS capability of the current mailbox
497 * and returns true if the given flag is supported by the IMAP server
499 * @param string $flag Permanentflag name
500 * @return boolean True if this flag is supported
503 function check_permflag($flag)
505 $flag = strtoupper($flag);
506 $imap_flag = $this->conn->flags[$flag];
507 return (in_array_nocase($imap_flag, $this->conn->data['PERMANENTFLAGS']));
512 * Returns the delimiter that is used by the IMAP server for folder separation
514 * @return string Delimiter string
517 function get_hierarchy_delimiter()
519 return $this->delimiter;
526 * @return array Namespace data
529 function get_namespace()
531 return $this->namespace;
536 * Sets delimiter and namespaces
540 private function set_env()
542 if ($this->delimiter !== null && $this->namespace !== null) {
546 if (isset($_SESSION['imap_namespace']) && isset($_SESSION['imap_delimiter'])) {
547 $this->namespace = $_SESSION['imap_namespace'];
548 $this->delimiter = $_SESSION['imap_delimiter'];
552 $config = rcmail::get_instance()->config;
553 $imap_personal = $config->get('imap_ns_personal');
554 $imap_other = $config->get('imap_ns_other');
555 $imap_shared = $config->get('imap_ns_shared');
556 $imap_delimiter = $config->get('imap_delimiter');
558 if (!$this->conn->connected())
561 $ns = $this->conn->getNamespace();
563 // Set namespaces (NAMESPACE supported)
565 $this->namespace = $ns;
568 $this->namespace = array(
575 if ($imap_delimiter) {
576 $this->delimiter = $imap_delimiter;
578 if (empty($this->delimiter)) {
579 $this->delimiter = $this->namespace['personal'][0][1];
581 if (empty($this->delimiter)) {
582 $this->delimiter = $this->conn->getHierarchyDelimiter();
584 if (empty($this->delimiter)) {
585 $this->delimiter = '/';
588 // Overwrite namespaces
589 if ($imap_personal !== null) {
590 $this->namespace['personal'] = NULL;
591 foreach ((array)$imap_personal as $dir) {
592 $this->namespace['personal'][] = array($dir, $this->delimiter);
595 if ($imap_other !== null) {
596 $this->namespace['other'] = NULL;
597 foreach ((array)$imap_other as $dir) {
599 $this->namespace['other'][] = array($dir, $this->delimiter);
603 if ($imap_shared !== null) {
604 $this->namespace['shared'] = NULL;
605 foreach ((array)$imap_shared as $dir) {
607 $this->namespace['shared'][] = array($dir, $this->delimiter);
612 $_SESSION['imap_namespace'] = $this->namespace;
613 $_SESSION['imap_delimiter'] = $this->delimiter;
618 * Get message count for a specific mailbox
620 * @param string $mbox_name Mailbox/folder name
621 * @param string $mode Mode for count [ALL|THREADS|UNSEEN|RECENT]
622 * @param boolean $force Force reading from server and update cache
623 * @param boolean $status Enables storing folder status info (max UID/count),
624 * required for mailbox_status()
625 * @return int Number of messages
628 function messagecount($mbox_name='', $mode='ALL', $force=false, $status=true)
630 $mailbox = strlen($mbox_name) ? $this->mod_mailbox($mbox_name) : $this->mailbox;
631 return $this->_messagecount($mailbox, $mode, $force, $status);
636 * Private method for getting nr of messages
638 * @param string $mailbox Mailbox name
639 * @param string $mode Mode for count [ALL|THREADS|UNSEEN|RECENT]
640 * @param boolean $force Force reading from server and update cache
641 * @param boolean $status Enables storing folder status info (max UID/count),
642 * required for mailbox_status()
643 * @return int Number of messages
645 * @see rcube_imap::messagecount()
647 private function _messagecount($mailbox='', $mode='ALL', $force=false, $status=true)
649 $mode = strtoupper($mode);
651 if (!strlen($mailbox))
652 $mailbox = $this->mailbox;
655 if ($this->search_string && $mailbox == $this->mailbox && ($mode == 'ALL' || $mode == 'THREADS') && !$force) {
656 if ($this->search_threads)
657 return $mode == 'ALL' ? count((array)$this->search_set['depth']) : count((array)$this->search_set['tree']);
659 return count((array)$this->search_set);
662 $a_mailbox_cache = $this->get_cache('messagecount');
664 // return cached value
665 if (!$force && is_array($a_mailbox_cache[$mailbox]) && isset($a_mailbox_cache[$mailbox][$mode]))
666 return $a_mailbox_cache[$mailbox][$mode];
668 if (!is_array($a_mailbox_cache[$mailbox]))
669 $a_mailbox_cache[$mailbox] = array();
671 if ($mode == 'THREADS') {
672 $res = $this->_threadcount($mailbox, $msg_count);
673 $count = $res['count'];
676 $this->set_folder_stats($mailbox, 'cnt', $res['msgcount']);
677 $this->set_folder_stats($mailbox, 'maxuid', $res['maxuid'] ? $this->_id2uid($res['maxuid'], $mailbox) : 0);
680 // RECENT count is fetched a bit different
681 else if ($mode == 'RECENT') {
682 $count = $this->conn->countRecent($mailbox);
684 // use SEARCH for message counting
685 else if ($this->skip_deleted) {
686 $search_str = "ALL UNDELETED";
687 $keys = array('COUNT');
690 if ($mode == 'UNSEEN') {
691 $search_str .= " UNSEEN";
694 if ($this->caching_enabled) {
703 // get message count using (E)SEARCH
704 // not very performant but more precise (using UNDELETED)
705 $index = $this->conn->search($mailbox, $search_str, $need_uid, $keys);
707 $count = is_array($index) ? $index['COUNT'] : 0;
709 if ($mode == 'ALL') {
710 if ($need_uid && $this->caching_enabled) {
711 // Save messages index for check_cache_status()
712 $this->icache['all_undeleted_idx'] = $index['ALL'];
715 $this->set_folder_stats($mailbox, 'cnt', $count);
716 $this->set_folder_stats($mailbox, 'maxuid', is_array($index) ? $index['MAX'] : 0);
721 if ($mode == 'UNSEEN')
722 $count = $this->conn->countUnseen($mailbox);
724 $count = $this->conn->countMessages($mailbox);
726 $this->set_folder_stats($mailbox,'cnt', $count);
727 $this->set_folder_stats($mailbox, 'maxuid', $count ? $this->_id2uid($count, $mailbox) : 0);
732 $a_mailbox_cache[$mailbox][$mode] = (int)$count;
734 // write back to cache
735 $this->update_cache('messagecount', $a_mailbox_cache);
742 * Private method for getting nr of threads
744 * @param string $mailbox Folder name
746 * @returns array Array containing items: 'count' - threads count,
747 * 'msgcount' = messages count, 'maxuid' = max. UID in the set
750 private function _threadcount($mailbox)
754 if (!empty($this->icache['threads'])) {
755 $dcount = count($this->icache['threads']['depth']);
757 'count' => count($this->icache['threads']['tree']),
758 'msgcount' => $dcount,
759 'maxuid' => $dcount ? max(array_keys($this->icache['threads']['depth'])) : 0,
762 else if (is_array($result = $this->_fetch_threads($mailbox))) {
763 $dcount = count($result[1]);
765 'count' => count($result[0]),
766 'msgcount' => $dcount,
767 'maxuid' => $dcount ? max(array_keys($result[1])) : 0,
776 * Public method for listing headers
777 * convert mailbox name with root dir first
779 * @param string $mbox_name Mailbox/folder name
780 * @param int $page Current page to list
781 * @param string $sort_field Header field to sort by
782 * @param string $sort_order Sort order [ASC|DESC]
783 * @param int $slice Number of slice items to extract from result array
784 * @return array Indexed array with message header objects
787 function list_headers($mbox_name='', $page=NULL, $sort_field=NULL, $sort_order=NULL, $slice=0)
789 $mailbox = strlen($mbox_name) ? $this->mod_mailbox($mbox_name) : $this->mailbox;
790 return $this->_list_headers($mailbox, $page, $sort_field, $sort_order, false, $slice);
795 * Private method for listing message headers
797 * @param string $mailbox Mailbox name
798 * @param int $page Current page to list
799 * @param string $sort_field Header field to sort by
800 * @param string $sort_order Sort order [ASC|DESC]
801 * @param int $slice Number of slice items to extract from result array
802 * @return array Indexed array with message header objects
804 * @see rcube_imap::list_headers
806 private function _list_headers($mailbox='', $page=NULL, $sort_field=NULL, $sort_order=NULL, $recursive=false, $slice=0)
808 if (!strlen($mailbox))
811 // use saved message set
812 if ($this->search_string && $mailbox == $this->mailbox)
813 return $this->_list_header_set($mailbox, $page, $sort_field, $sort_order, $slice);
815 if ($this->threading)
816 return $this->_list_thread_headers($mailbox, $page, $sort_field, $sort_order, $recursive, $slice);
818 $this->_set_sort_order($sort_field, $sort_order);
820 $page = $page ? $page : $this->list_page;
821 $cache_key = $mailbox.'.msg';
823 if ($this->caching_enabled) {
824 // cache is OK, we can get messages from local cache
825 // (assume cache is in sync when in recursive mode)
826 if ($recursive || $this->check_cache_status($mailbox, $cache_key)>0) {
827 $start_msg = ($page-1) * $this->page_size;
828 $a_msg_headers = $this->get_message_cache($cache_key, $start_msg,
829 $start_msg+$this->page_size, $this->sort_field, $this->sort_order);
830 $result = array_values($a_msg_headers);
832 $result = array_slice($result, -$slice, $slice);
835 // cache is incomplete, sync it (all messages in the folder)
836 else if (!$recursive) {
837 $this->sync_header_index($mailbox);
838 return $this->_list_headers($mailbox, $page, $this->sort_field, $this->sort_order, true, $slice);
842 // retrieve headers from IMAP
843 $a_msg_headers = array();
845 // use message index sort as default sorting (for better performance)
846 if (!$this->sort_field) {
847 if ($this->skip_deleted) {
848 // @TODO: this could be cached
849 if ($msg_index = $this->_search_index($mailbox, 'ALL UNDELETED')) {
850 $max = max($msg_index);
851 list($begin, $end) = $this->_get_message_range(count($msg_index), $page);
852 $msg_index = array_slice($msg_index, $begin, $end-$begin);
855 else if ($max = $this->conn->countMessages($mailbox)) {
856 list($begin, $end) = $this->_get_message_range($max, $page);
857 $msg_index = range($begin+1, $end);
860 $msg_index = array();
862 if ($slice && $msg_index)
863 $msg_index = array_slice($msg_index, ($this->sort_order == 'DESC' ? 0 : -$slice), $slice);
865 // fetch reqested headers from server
867 $this->_fetch_headers($mailbox, join(",", $msg_index), $a_msg_headers, $cache_key);
870 else if ($this->get_capability('SORT') &&
871 // Courier-IMAP provides SORT capability but allows to disable it by admin (#1486959)
872 ($msg_index = $this->conn->sort($mailbox, $this->sort_field, $this->skip_deleted ? 'UNDELETED' : '')) !== false
874 if (!empty($msg_index)) {
875 list($begin, $end) = $this->_get_message_range(count($msg_index), $page);
876 $max = max($msg_index);
877 $msg_index = array_slice($msg_index, $begin, $end-$begin);
880 $msg_index = array_slice($msg_index, ($this->sort_order == 'DESC' ? 0 : -$slice), $slice);
882 // fetch reqested headers from server
883 $this->_fetch_headers($mailbox, join(',', $msg_index), $a_msg_headers, $cache_key);
886 // fetch specified header for all messages and sort
887 else if ($a_index = $this->conn->fetchHeaderIndex($mailbox, "1:*", $this->sort_field, $this->skip_deleted)) {
888 asort($a_index); // ASC
889 $msg_index = array_keys($a_index);
890 $max = max($msg_index);
891 list($begin, $end) = $this->_get_message_range(count($msg_index), $page);
892 $msg_index = array_slice($msg_index, $begin, $end-$begin);
895 $msg_index = array_slice($msg_index, ($this->sort_order == 'DESC' ? 0 : -$slice), $slice);
897 // fetch reqested headers from server
898 $this->_fetch_headers($mailbox, join(",", $msg_index), $a_msg_headers, $cache_key);
901 // delete cached messages with a higher index than $max+1
902 // Changed $max to $max+1 to fix this bug : #1484295
903 $this->clear_message_cache($cache_key, $max + 1);
905 // kick child process to sync cache
908 // return empty array if no messages found
909 if (!is_array($a_msg_headers) || empty($a_msg_headers))
912 // use this class for message sorting
913 $sorter = new rcube_header_sorter();
914 $sorter->set_sequence_numbers($msg_index);
915 $sorter->sort_headers($a_msg_headers);
917 if ($this->sort_order == 'DESC')
918 $a_msg_headers = array_reverse($a_msg_headers);
920 return array_values($a_msg_headers);
925 * Private method for listing message headers using threads
927 * @param string $mailbox Mailbox/folder name
928 * @param int $page Current page to list
929 * @param string $sort_field Header field to sort by
930 * @param string $sort_order Sort order [ASC|DESC]
931 * @param boolean $recursive True if called recursively
932 * @param int $slice Number of slice items to extract from result array
933 * @return array Indexed array with message header objects
935 * @see rcube_imap::list_headers
937 private function _list_thread_headers($mailbox, $page=NULL, $sort_field=NULL, $sort_order=NULL, $recursive=false, $slice=0)
939 $this->_set_sort_order($sort_field, $sort_order);
941 $page = $page ? $page : $this->list_page;
942 // $cache_key = $mailbox.'.msg';
943 // $cache_status = $this->check_cache_status($mailbox, $cache_key);
945 // get all threads (default sort order)
946 list ($thread_tree, $msg_depth, $has_children) = $this->_fetch_threads($mailbox);
948 if (empty($thread_tree))
951 $msg_index = $this->_sort_threads($mailbox, $thread_tree);
953 return $this->_fetch_thread_headers($mailbox,
954 $thread_tree, $msg_depth, $has_children, $msg_index, $page, $slice);
959 * Private method for fetching threads data
961 * @param string $mailbox Mailbox/folder name
962 * @return array Array with thread data
965 private function _fetch_threads($mailbox)
967 if (empty($this->icache['threads'])) {
969 $result = $this->conn->thread($mailbox, $this->threading,
970 $this->skip_deleted ? 'UNDELETED' : '');
972 // add to internal (fast) cache
973 $this->icache['threads'] = array();
974 $this->icache['threads']['tree'] = is_array($result) ? $result[0] : array();
975 $this->icache['threads']['depth'] = is_array($result) ? $result[1] : array();
976 $this->icache['threads']['has_children'] = is_array($result) ? $result[2] : array();
980 $this->icache['threads']['tree'],
981 $this->icache['threads']['depth'],
982 $this->icache['threads']['has_children'],
988 * Private method for fetching threaded messages headers
990 * @param string $mailbox Mailbox name
991 * @param array $thread_tree Thread tree data
992 * @param array $msg_depth Thread depth data
993 * @param array $has_children Thread children data
994 * @param array $msg_index Messages index
995 * @param int $page List page number
996 * @param int $slice Number of threads to slice
997 * @return array Messages headers
1000 private function _fetch_thread_headers($mailbox, $thread_tree, $msg_depth, $has_children, $msg_index, $page, $slice=0)
1002 $cache_key = $mailbox.'.msg';
1003 // now get IDs for current page
1004 list($begin, $end) = $this->_get_message_range(count($msg_index), $page);
1005 $msg_index = array_slice($msg_index, $begin, $end-$begin);
1008 $msg_index = array_slice($msg_index, ($this->sort_order == 'DESC' ? 0 : -$slice), $slice);
1010 if ($this->sort_order == 'DESC')
1011 $msg_index = array_reverse($msg_index);
1013 // flatten threads array
1014 // @TODO: fetch children only in expanded mode (?)
1016 foreach ($msg_index as $root) {
1018 if (!empty($thread_tree[$root]))
1019 $all_ids = array_merge($all_ids, array_keys_recursive($thread_tree[$root]));
1022 // fetch reqested headers from server
1023 $this->_fetch_headers($mailbox, $all_ids, $a_msg_headers, $cache_key);
1025 // return empty array if no messages found
1026 if (!is_array($a_msg_headers) || empty($a_msg_headers))
1029 // use this class for message sorting
1030 $sorter = new rcube_header_sorter();
1031 $sorter->set_sequence_numbers($all_ids);
1032 $sorter->sort_headers($a_msg_headers);
1034 // Set depth, has_children and unread_children fields in headers
1035 $this->_set_thread_flags($a_msg_headers, $msg_depth, $has_children);
1037 return array_values($a_msg_headers);
1042 * Private method for setting threaded messages flags:
1043 * depth, has_children and unread_children
1045 * @param array $headers Reference to headers array indexed by message ID
1046 * @param array $msg_depth Array of messages depth indexed by message ID
1047 * @param array $msg_children Array of messages children flags indexed by message ID
1048 * @return array Message headers array indexed by message ID
1051 private function _set_thread_flags(&$headers, $msg_depth, $msg_children)
1055 foreach ($headers as $idx => $header) {
1057 $depth = $msg_depth[$id];
1058 $parents = array_slice($parents, 0, $depth);
1060 if (!empty($parents)) {
1061 $headers[$idx]->parent_uid = end($parents);
1063 $headers[$parents[0]]->unread_children++;
1065 array_push($parents, $header->uid);
1067 $headers[$idx]->depth = $depth;
1068 $headers[$idx]->has_children = $msg_children[$id];
1074 * Private method for listing a set of message headers (search results)
1076 * @param string $mailbox Mailbox/folder name
1077 * @param int $page Current page to list
1078 * @param string $sort_field Header field to sort by
1079 * @param string $sort_order Sort order [ASC|DESC]
1080 * @param int $slice Number of slice items to extract from result array
1081 * @return array Indexed array with message header objects
1083 * @see rcube_imap::list_header_set()
1085 private function _list_header_set($mailbox, $page=NULL, $sort_field=NULL, $sort_order=NULL, $slice=0)
1087 if (!strlen($mailbox) || empty($this->search_set))
1090 // use saved messages from searching
1091 if ($this->threading)
1092 return $this->_list_thread_header_set($mailbox, $page, $sort_field, $sort_order, $slice);
1094 // search set is threaded, we need a new one
1095 if ($this->search_threads) {
1096 if (empty($this->search_set['tree']))
1098 $this->search('', $this->search_string, $this->search_charset, $sort_field);
1101 $msgs = $this->search_set;
1102 $a_msg_headers = array();
1103 $page = $page ? $page : $this->list_page;
1104 $start_msg = ($page-1) * $this->page_size;
1106 $this->_set_sort_order($sort_field, $sort_order);
1108 // quickest method (default sorting)
1109 if (!$this->search_sort_field && !$this->sort_field) {
1110 if ($sort_order == 'DESC')
1111 $msgs = array_reverse($msgs);
1113 // get messages uids for one page
1114 $msgs = array_slice(array_values($msgs), $start_msg, min(count($msgs)-$start_msg, $this->page_size));
1117 $msgs = array_slice($msgs, -$slice, $slice);
1120 $this->_fetch_headers($mailbox, join(',',$msgs), $a_msg_headers, NULL);
1122 // I didn't found in RFC that FETCH always returns messages sorted by index
1123 $sorter = new rcube_header_sorter();
1124 $sorter->set_sequence_numbers($msgs);
1125 $sorter->sort_headers($a_msg_headers);
1127 return array_values($a_msg_headers);
1130 // sorted messages, so we can first slice array and then fetch only wanted headers
1131 if ($this->search_sorted) { // SORT searching result
1132 // reset search set if sorting field has been changed
1133 if ($this->sort_field && $this->search_sort_field != $this->sort_field)
1134 $msgs = $this->search('', $this->search_string, $this->search_charset, $this->sort_field);
1136 // return empty array if no messages found
1140 if ($sort_order == 'DESC')
1141 $msgs = array_reverse($msgs);
1143 // get messages uids for one page
1144 $msgs = array_slice(array_values($msgs), $start_msg, min(count($msgs)-$start_msg, $this->page_size));
1147 $msgs = array_slice($msgs, -$slice, $slice);
1150 $this->_fetch_headers($mailbox, join(',',$msgs), $a_msg_headers, NULL);
1152 $sorter = new rcube_header_sorter();
1153 $sorter->set_sequence_numbers($msgs);
1154 $sorter->sort_headers($a_msg_headers);
1156 return array_values($a_msg_headers);
1158 else { // SEARCH result, need sorting
1159 $cnt = count($msgs);
1160 // 300: experimantal value for best result
1161 if (($cnt > 300 && $cnt > $this->page_size) || !$this->sort_field) {
1162 // use memory less expensive (and quick) method for big result set
1163 $a_index = $this->message_index('', $this->sort_field, $this->sort_order);
1164 // get messages uids for one page...
1165 $msgs = array_slice($a_index, $start_msg, min($cnt-$start_msg, $this->page_size));
1167 $msgs = array_slice($msgs, -$slice, $slice);
1168 // ...and fetch headers
1169 $this->_fetch_headers($mailbox, join(',', $msgs), $a_msg_headers, NULL);
1171 // return empty array if no messages found
1172 if (!is_array($a_msg_headers) || empty($a_msg_headers))
1175 $sorter = new rcube_header_sorter();
1176 $sorter->set_sequence_numbers($msgs);
1177 $sorter->sort_headers($a_msg_headers);
1179 return array_values($a_msg_headers);
1182 // for small result set we can fetch all messages headers
1183 $this->_fetch_headers($mailbox, join(',', $msgs), $a_msg_headers, NULL);
1185 // return empty array if no messages found
1186 if (!is_array($a_msg_headers) || empty($a_msg_headers))
1189 // if not already sorted
1190 $a_msg_headers = $this->conn->sortHeaders(
1191 $a_msg_headers, $this->sort_field, $this->sort_order);
1193 // only return the requested part of the set
1194 $a_msg_headers = array_slice(array_values($a_msg_headers),
1195 $start_msg, min($cnt-$start_msg, $this->page_size));
1198 $a_msg_headers = array_slice($a_msg_headers, -$slice, $slice);
1200 return $a_msg_headers;
1207 * Private method for listing a set of threaded message headers (search results)
1209 * @param string $mailbox Mailbox/folder name
1210 * @param int $page Current page to list
1211 * @param string $sort_field Header field to sort by
1212 * @param string $sort_order Sort order [ASC|DESC]
1213 * @param int $slice Number of slice items to extract from result array
1214 * @return array Indexed array with message header objects
1216 * @see rcube_imap::list_header_set()
1218 private function _list_thread_header_set($mailbox, $page=NULL, $sort_field=NULL, $sort_order=NULL, $slice=0)
1220 // update search_set if previous data was fetched with disabled threading
1221 if (!$this->search_threads) {
1222 if (empty($this->search_set))
1224 $this->search('', $this->search_string, $this->search_charset, $sort_field);
1228 if (empty($this->search_set['tree']))
1231 $thread_tree = $this->search_set['tree'];
1232 $msg_depth = $this->search_set['depth'];
1233 $has_children = $this->search_set['children'];
1234 $a_msg_headers = array();
1236 $page = $page ? $page : $this->list_page;
1237 $start_msg = ($page-1) * $this->page_size;
1239 $this->_set_sort_order($sort_field, $sort_order);
1241 $msg_index = $this->_sort_threads($mailbox, $thread_tree, array_keys($msg_depth));
1243 return $this->_fetch_thread_headers($mailbox,
1244 $thread_tree, $msg_depth, $has_children, $msg_index, $page, $slice=0);
1249 * Helper function to get first and last index of the requested set
1251 * @param int $max Messages count
1252 * @param mixed $page Page number to show, or string 'all'
1253 * @return array Array with two values: first index, last index
1256 private function _get_message_range($max, $page)
1258 $start_msg = ($page-1) * $this->page_size;
1264 else if ($this->sort_order=='DESC') {
1265 $begin = $max - $this->page_size - $start_msg;
1266 $end = $max - $start_msg;
1269 $begin = $start_msg;
1270 $end = $start_msg + $this->page_size;
1273 if ($begin < 0) $begin = 0;
1274 if ($end < 0) $end = $max;
1275 if ($end > $max) $end = $max;
1277 return array($begin, $end);
1282 * Fetches message headers (used for loop)
1284 * @param string $mailbox Mailbox name
1285 * @param string $msgs Message index to fetch
1286 * @param array $a_msg_headers Reference to message headers array
1287 * @param string $cache_key Cache index key
1288 * @return int Messages count
1291 private function _fetch_headers($mailbox, $msgs, &$a_msg_headers, $cache_key)
1293 // fetch reqested headers from server
1294 $a_header_index = $this->conn->fetchHeaders(
1295 $mailbox, $msgs, false, false, $this->get_fetch_headers());
1297 if (empty($a_header_index))
1300 foreach ($a_header_index as $i => $headers) {
1301 $a_msg_headers[$headers->uid] = $headers;
1305 if ($this->caching_enabled && $cache_key) {
1306 // cache is incomplete?
1307 $cache_index = $this->get_message_cache_index($cache_key);
1309 foreach ($a_header_index as $headers) {
1311 if ($cache_index[$headers->id] == $headers->uid) {
1312 unset($cache_index[$headers->id]);
1315 // wrong UID at this position
1316 if ($cache_index[$headers->id]) {
1317 $for_remove[] = $cache_index[$headers->id];
1318 unset($cache_index[$headers->id]);
1320 // message UID in cache but at wrong position
1321 if (is_int($key = array_search($headers->uid, $cache_index))) {
1322 $for_remove[] = $cache_index[$key];
1323 unset($cache_index[$key]);
1326 $for_create[] = $headers->uid;
1330 $this->remove_message_cache($cache_key, $for_remove);
1332 // add messages to cache
1333 foreach ((array)$for_create as $uid) {
1334 $headers = $a_msg_headers[$uid];
1335 $this->add_message_cache($cache_key, $headers->id, $headers, NULL, true);
1339 return count($a_msg_headers);
1344 * Returns current status of mailbox
1346 * We compare the maximum UID to determine the number of
1347 * new messages because the RECENT flag is not reliable.
1349 * @param string $mbox_name Mailbox/folder name
1350 * @return int Folder status
1352 function mailbox_status($mbox_name = null)
1354 $mailbox = strlen($mbox_name) ? $this->mod_mailbox($mbox_name) : $this->mailbox;
1355 $old = $this->get_folder_stats($mailbox);
1357 // refresh message count -> will update
1358 $this->_messagecount($mailbox, 'ALL', true);
1361 $new = $this->get_folder_stats($mailbox);
1364 if ($new['maxuid'] > $old['maxuid'])
1366 // some messages has been deleted
1367 if ($new['cnt'] < $old['cnt'])
1370 // @TODO: optional checking for messages flags changes (?)
1371 // @TODO: UIDVALIDITY checking
1378 * Stores folder statistic data in session
1379 * @TODO: move to separate DB table (cache?)
1381 * @param string $mbox_name Mailbox name
1382 * @param string $name Data name
1383 * @param mixed $data Data value
1385 private function set_folder_stats($mbox_name, $name, $data)
1387 $_SESSION['folders'][$mbox_name][$name] = $data;
1392 * Gets folder statistic data
1394 * @param string $mbox_name Mailbox name
1395 * @return array Stats data
1397 private function get_folder_stats($mbox_name)
1399 if ($_SESSION['folders'][$mbox_name])
1400 return (array) $_SESSION['folders'][$mbox_name];
1407 * Return sorted array of message IDs (not UIDs)
1409 * @param string $mbox_name Mailbox to get index from
1410 * @param string $sort_field Sort column
1411 * @param string $sort_order Sort order [ASC, DESC]
1412 * @return array Indexed array with message IDs
1414 function message_index($mbox_name='', $sort_field=NULL, $sort_order=NULL)
1416 if ($this->threading)
1417 return $this->thread_index($mbox_name, $sort_field, $sort_order);
1419 $this->_set_sort_order($sort_field, $sort_order);
1421 $mailbox = strlen($mbox_name) ? $this->mod_mailbox($mbox_name) : $this->mailbox;
1422 $key = "{$mailbox}:{$this->sort_field}:{$this->sort_order}:{$this->search_string}.msgi";
1424 // we have a saved search result, get index from there
1425 if (!isset($this->icache[$key]) && $this->search_string
1426 && !$this->search_threads && $mailbox == $this->mailbox) {
1427 // use message index sort as default sorting
1428 if (!$this->sort_field) {
1429 $msgs = $this->search_set;
1431 if ($this->search_sort_field != 'date')
1434 if ($this->sort_order == 'DESC')
1435 $this->icache[$key] = array_reverse($msgs);
1437 $this->icache[$key] = $msgs;
1439 // sort with SORT command
1440 else if ($this->search_sorted) {
1441 if ($this->sort_field && $this->search_sort_field != $this->sort_field)
1442 $this->search('', $this->search_string, $this->search_charset, $this->sort_field);
1444 if ($this->sort_order == 'DESC')
1445 $this->icache[$key] = array_reverse($this->search_set);
1447 $this->icache[$key] = $this->search_set;
1450 $a_index = $this->conn->fetchHeaderIndex($mailbox,
1451 join(',', $this->search_set), $this->sort_field, $this->skip_deleted);
1453 if (is_array($a_index)) {
1454 if ($this->sort_order=="ASC")
1456 else if ($this->sort_order=="DESC")
1459 $this->icache[$key] = array_keys($a_index);
1462 $this->icache[$key] = array();
1467 // have stored it in RAM
1468 if (isset($this->icache[$key]))
1469 return $this->icache[$key];
1471 // check local cache
1472 $cache_key = $mailbox.'.msg';
1473 $cache_status = $this->check_cache_status($mailbox, $cache_key);
1476 if ($cache_status>0) {
1477 $a_index = $this->get_message_cache_index($cache_key,
1478 $this->sort_field, $this->sort_order);
1479 return array_keys($a_index);
1482 // use message index sort as default sorting
1483 if (!$this->sort_field) {
1484 if ($this->skip_deleted) {
1485 $a_index = $this->_search_index($mailbox, 'ALL');
1486 } else if ($max = $this->_messagecount($mailbox)) {
1487 $a_index = range(1, $max);
1490 if ($a_index !== false && $this->sort_order == 'DESC')
1491 $a_index = array_reverse($a_index);
1493 $this->icache[$key] = $a_index;
1495 // fetch complete message index
1496 else if ($this->get_capability('SORT') &&
1497 ($a_index = $this->conn->sort($mailbox,
1498 $this->sort_field, $this->skip_deleted ? 'UNDELETED' : '')) !== false
1500 if ($this->sort_order == 'DESC')
1501 $a_index = array_reverse($a_index);
1503 $this->icache[$key] = $a_index;
1505 else if ($a_index = $this->conn->fetchHeaderIndex(
1506 $mailbox, "1:*", $this->sort_field, $this->skip_deleted)) {
1507 if ($this->sort_order=="ASC")
1509 else if ($this->sort_order=="DESC")
1512 $this->icache[$key] = array_keys($a_index);
1515 return $this->icache[$key] !== false ? $this->icache[$key] : array();
1520 * Return sorted array of threaded message IDs (not UIDs)
1522 * @param string $mbox_name Mailbox to get index from
1523 * @param string $sort_field Sort column
1524 * @param string $sort_order Sort order [ASC, DESC]
1525 * @return array Indexed array with message IDs
1527 function thread_index($mbox_name='', $sort_field=NULL, $sort_order=NULL)
1529 $this->_set_sort_order($sort_field, $sort_order);
1531 $mailbox = strlen($mbox_name) ? $this->mod_mailbox($mbox_name) : $this->mailbox;
1532 $key = "{$mailbox}:{$this->sort_field}:{$this->sort_order}:{$this->search_string}.thi";
1534 // we have a saved search result, get index from there
1535 if (!isset($this->icache[$key]) && $this->search_string
1536 && $this->search_threads && $mailbox == $this->mailbox) {
1537 // use message IDs for better performance
1538 $ids = array_keys_recursive($this->search_set['tree']);
1539 $this->icache[$key] = $this->_flatten_threads($mailbox, $this->search_set['tree'], $ids);
1542 // have stored it in RAM
1543 if (isset($this->icache[$key]))
1544 return $this->icache[$key];
1546 // check local cache
1547 $cache_key = $mailbox.'.msg';
1548 $cache_status = $this->check_cache_status($mailbox, $cache_key);
1551 if ($cache_status>0) {
1552 $a_index = $this->get_message_cache_index($cache_key, $this->sort_field, $this->sort_order);
1553 return array_keys($a_index);
1556 // get all threads (default sort order)
1557 list ($thread_tree) = $this->_fetch_threads($mailbox);
1559 $this->icache[$key] = $this->_flatten_threads($mailbox, $thread_tree);
1561 return $this->icache[$key];
1566 * Return array of threaded messages (all, not only roots)
1568 * @param string $mailbox Mailbox to get index from
1569 * @param array $thread_tree Threaded messages array (see _fetch_threads())
1570 * @param array $ids Message IDs if we know what we need (e.g. search result)
1571 * for better performance
1572 * @return array Indexed array with message IDs
1576 private function _flatten_threads($mailbox, $thread_tree, $ids=null)
1578 if (empty($thread_tree))
1581 $msg_index = $this->_sort_threads($mailbox, $thread_tree, $ids);
1583 if ($this->sort_order == 'DESC')
1584 $msg_index = array_reverse($msg_index);
1586 // flatten threads array
1588 foreach ($msg_index as $root) {
1590 if (!empty($thread_tree[$root])) {
1591 foreach (array_keys_recursive($thread_tree[$root]) as $val)
1601 * @param string $mailbox Mailbox name
1604 private function sync_header_index($mailbox)
1606 $cache_key = $mailbox.'.msg';
1607 $cache_index = $this->get_message_cache_index($cache_key);
1610 // cache is empty, get all messages
1611 if (is_array($cache_index) && empty($cache_index)) {
1612 $max = $this->_messagecount($mailbox);
1613 // syncing a big folder maybe slow
1616 $end = min($chunk_size, $max);
1618 // do this in loop to save memory (1000 msgs ~= 10 MB)
1619 if ($headers = $this->conn->fetchHeaders($mailbox,
1620 "$start:$end", false, false, $this->get_fetch_headers())
1622 foreach ($headers as $header) {
1623 $this->add_message_cache($cache_key, $header->id, $header, NULL, true);
1626 if ($end - $start < $chunk_size - 1)
1629 $end = min($end+$chunk_size, $max);
1630 $start += $chunk_size;
1635 // fetch complete message index
1636 if (isset($this->icache['folder_index']))
1637 $a_message_index = &$this->icache['folder_index'];
1639 $a_message_index = $this->conn->fetchHeaderIndex($mailbox, "1:*", 'UID', $this->skip_deleted);
1641 if ($a_message_index === false || $cache_index === null)
1644 // compare cache index with real index
1645 foreach ($a_message_index as $id => $uid) {
1646 // message in cache at correct position
1647 if ($cache_index[$id] == $uid) {
1648 unset($cache_index[$id]);
1652 // other message at this position
1653 if (isset($cache_index[$id])) {
1654 $for_remove[] = $cache_index[$id];
1655 unset($cache_index[$id]);
1658 // message in cache but at wrong position
1659 if (is_int($key = array_search($uid, $cache_index))) {
1660 $for_remove[] = $uid;
1661 unset($cache_index[$key]);
1664 $for_update[] = $id;
1667 // remove messages at wrong positions and those deleted that are still in cache_index
1668 if (!empty($for_remove))
1669 $cache_index = array_merge($cache_index, $for_remove);
1671 if (!empty($cache_index))
1672 $this->remove_message_cache($cache_key, $cache_index);
1674 // fetch complete headers and add to cache
1675 if (!empty($for_update)) {
1676 // syncing a big folder maybe slow
1678 // To save memory do this in chunks
1679 $for_update = array_chunk($for_update, $chunk_size);
1680 foreach ($for_update as $uids) {
1681 if ($headers = $this->conn->fetchHeaders($mailbox,
1682 $uids, false, false, $this->get_fetch_headers())
1684 foreach ($headers as $header) {
1685 $this->add_message_cache($cache_key, $header->id, $header, NULL, true);
1694 * Invoke search request to IMAP server
1696 * @param string $mbox_name Mailbox name to search in
1697 * @param string $str Search criteria
1698 * @param string $charset Search charset
1699 * @param string $sort_field Header field to sort by
1700 * @return array search results as list of message IDs
1703 function search($mbox_name='', $str=NULL, $charset=NULL, $sort_field=NULL)
1708 $mailbox = strlen($mbox_name) ? $this->mod_mailbox($mbox_name) : $this->mailbox;
1710 $results = $this->_search_index($mailbox, $str, $charset, $sort_field);
1712 $this->set_search_set($str, $results, $charset, $sort_field, (bool)$this->threading,
1713 $this->threading || $this->search_sorted ? true : false);
1720 * Private search method
1722 * @param string $mailbox Mailbox name
1723 * @param string $criteria Search criteria
1724 * @param string $charset Charset
1725 * @param string $sort_field Sorting field
1726 * @return array search results as list of message ids
1728 * @see rcube_imap::search()
1730 private function _search_index($mailbox, $criteria='ALL', $charset=NULL, $sort_field=NULL)
1732 $orig_criteria = $criteria;
1734 if ($this->skip_deleted && !preg_match('/UNDELETED/', $criteria))
1735 $criteria = 'UNDELETED '.$criteria;
1737 if ($this->threading) {
1738 $a_messages = $this->conn->thread($mailbox, $this->threading, $criteria, $charset);
1740 // Error, try with US-ASCII (RFC5256: SORT/THREAD must support US-ASCII and UTF-8,
1741 // but I've seen that Courier doesn't support UTF-8)
1742 if ($a_messages === false && $charset && $charset != 'US-ASCII')
1743 $a_messages = $this->conn->thread($mailbox, $this->threading,
1744 $this->convert_criteria($criteria, $charset), 'US-ASCII');
1746 if ($a_messages !== false) {
1747 list ($thread_tree, $msg_depth, $has_children) = $a_messages;
1748 $a_messages = array(
1749 'tree' => $thread_tree,
1750 'depth' => $msg_depth,
1751 'children' => $has_children
1758 if ($sort_field && $this->get_capability('SORT')) {
1759 $charset = $charset ? $charset : $this->default_charset;
1760 $a_messages = $this->conn->sort($mailbox, $sort_field, $criteria, false, $charset);
1762 // Error, try with US-ASCII (RFC5256: SORT/THREAD must support US-ASCII and UTF-8,
1763 // but I've seen that Courier doesn't support UTF-8)
1764 if ($a_messages === false && $charset && $charset != 'US-ASCII')
1765 $a_messages = $this->conn->sort($mailbox, $sort_field,
1766 $this->convert_criteria($criteria, $charset), false, 'US-ASCII');
1768 if ($a_messages !== false) {
1769 $this->search_sorted = true;
1774 if ($orig_criteria == 'ALL') {
1775 $max = $this->_messagecount($mailbox);
1776 $a_messages = $max ? range(1, $max) : array();
1779 $a_messages = $this->conn->search($mailbox,
1780 ($charset ? "CHARSET $charset " : '') . $criteria);
1782 // Error, try with US-ASCII (some servers may support only US-ASCII)
1783 if ($a_messages === false && $charset && $charset != 'US-ASCII')
1784 $a_messages = $this->conn->search($mailbox,
1785 'CHARSET US-ASCII ' . $this->convert_criteria($criteria, $charset));
1787 // I didn't found that SEARCH should return sorted IDs
1788 if (is_array($a_messages) && !$this->sort_field)
1792 $this->search_sorted = false;
1799 * Direct (real and simple) SEARCH request to IMAP server,
1800 * without result sorting and caching
1802 * @param string $mbox_name Mailbox name to search in
1803 * @param string $str Search string
1804 * @param boolean $ret_uid True if UIDs should be returned
1805 * @return array Search results as list of message IDs or UIDs
1808 function search_once($mbox_name='', $str=NULL, $ret_uid=false)
1813 $mailbox = strlen($mbox_name) ? $this->mod_mailbox($mbox_name) : $this->mailbox;
1815 return $this->conn->search($mailbox, $str, $ret_uid);
1820 * Converts charset of search criteria string
1822 * @param string $str Search string
1823 * @param string $charset Original charset
1824 * @param string $dest_charset Destination charset (default US-ASCII)
1825 * @return string Search string
1828 private function convert_criteria($str, $charset, $dest_charset='US-ASCII')
1830 // convert strings to US_ASCII
1831 if (preg_match_all('/\{([0-9]+)\}\r\n/', $str, $matches, PREG_OFFSET_CAPTURE)) {
1832 $last = 0; $res = '';
1833 foreach ($matches[1] as $m) {
1834 $string_offset = $m[1] + strlen($m[0]) + 4; // {}\r\n
1835 $string = substr($str, $string_offset - 1, $m[0]);
1836 $string = rcube_charset_convert($string, $charset, $dest_charset);
1839 $res .= sprintf("%s{%d}\r\n%s", substr($str, $last, $m[1] - $last - 1), strlen($string), $string);
1840 $last = $m[0] + $string_offset - 1;
1842 if ($last < strlen($str))
1843 $res .= substr($str, $last, strlen($str)-$last);
1845 else // strings for conversion not found
1855 * @param string $mailbox Mailbox name
1856 * @param array $thread_tree Unsorted thread tree (rcube_imap_generic::thread() result)
1857 * @param array $ids Message IDs if we know what we need (e.g. search result)
1858 * @return array Sorted roots IDs
1861 private function _sort_threads($mailbox, $thread_tree, $ids=NULL)
1863 // THREAD=ORDEREDSUBJECT: sorting by sent date of root message
1864 // THREAD=REFERENCES: sorting by sent date of root message
1865 // THREAD=REFS: sorting by the most recent date in each thread
1867 if (!$this->sort_field || ($this->sort_field == 'date' && $this->threading == 'REFS')) {
1868 return array_keys((array)$thread_tree);
1870 // here we'll implement REFS sorting, for performance reason
1871 else { // ($sort_field == 'date' && $this->threading != 'REFS')
1873 if ($this->get_capability('SORT') &&
1874 ($a_index = $this->conn->sort($mailbox, $this->sort_field,
1875 !empty($ids) ? $ids : ($this->skip_deleted ? 'UNDELETED' : ''))) !== false
1877 // return unsorted tree if we've got no index data
1879 return array_keys((array)$thread_tree);
1882 // fetch specified headers for all messages and sort them
1883 $a_index = $this->conn->fetchHeaderIndex($mailbox, !empty($ids) ? $ids : "1:*",
1884 $this->sort_field, $this->skip_deleted);
1886 // return unsorted tree if we've got no index data
1888 return array_keys((array)$thread_tree);
1890 asort($a_index); // ASC
1891 $a_index = array_values($a_index);
1894 return $this->_sort_thread_refs($thread_tree, $a_index);
1900 * THREAD=REFS sorting implementation
1902 * @param array $tree Thread tree array (message identifiers as keys)
1903 * @param array $index Array of sorted message identifiers
1904 * @return array Array of sorted roots messages
1907 private function _sort_thread_refs($tree, $index)
1912 $index = array_combine(array_values($index), $index);
1915 foreach ($tree as $idx => $val) {
1916 $index[$idx] = $idx;
1918 $idx_arr = array_keys_recursive($tree[$idx]);
1919 foreach ($idx_arr as $subidx)
1920 $index[$subidx] = $idx;
1924 $index = array_values($index);
1926 // create sorted array of roots
1927 $msg_index = array();
1928 if ($this->sort_order != 'DESC') {
1929 foreach ($index as $idx)
1930 if (!isset($msg_index[$idx]))
1931 $msg_index[$idx] = $idx;
1932 $msg_index = array_values($msg_index);
1935 for ($x=count($index)-1; $x>=0; $x--)
1936 if (!isset($msg_index[$index[$x]]))
1937 $msg_index[$index[$x]] = $index[$x];
1938 $msg_index = array_reverse($msg_index);
1946 * Refresh saved search set
1948 * @return array Current search set
1950 function refresh_search()
1952 if (!empty($this->search_string))
1953 $this->search_set = $this->search('', $this->search_string, $this->search_charset,
1954 $this->search_sort_field, $this->search_threads, $this->search_sorted);
1956 return $this->get_search_set();
1961 * Check if the given message ID is part of the current search set
1963 * @param string $msgid Message id
1964 * @return boolean True on match or if no search request is stored
1966 function in_searchset($msgid)
1968 if (!empty($this->search_string)) {
1969 if ($this->search_threads)
1970 return isset($this->search_set['depth']["$msgid"]);
1972 return in_array("$msgid", (array)$this->search_set, true);
1980 * Return message headers object of a specific message
1982 * @param int $id Message ID
1983 * @param string $mbox_name Mailbox to read from
1984 * @param boolean $is_uid True if $id is the message UID
1985 * @param boolean $bodystr True if we need also BODYSTRUCTURE in headers
1986 * @return object Message headers representation
1988 function get_headers($id, $mbox_name=NULL, $is_uid=true, $bodystr=false)
1990 $mailbox = strlen($mbox_name) ? $this->mod_mailbox($mbox_name) : $this->mailbox;
1991 $uid = $is_uid ? $id : $this->_id2uid($id, $mailbox);
1993 // get cached headers
1994 if ($uid && ($headers = &$this->get_cached_message($mailbox.'.msg', $uid)))
1997 $headers = $this->conn->fetchHeader(
1998 $mailbox, $id, $is_uid, $bodystr, $this->get_fetch_headers());
2000 // write headers cache
2002 if ($headers->uid && $headers->id)
2003 $this->uid_id_map[$mailbox][$headers->uid] = $headers->id;
2005 $this->add_message_cache($mailbox.'.msg', $headers->id, $headers, NULL, false, true);
2013 * Fetch body structure from the IMAP server and build
2014 * an object structure similar to the one generated by PEAR::Mail_mimeDecode
2016 * @param int $uid Message UID to fetch
2017 * @param string $structure_str Message BODYSTRUCTURE string (optional)
2018 * @return object rcube_message_part Message part tree or False on failure
2020 function &get_structure($uid, $structure_str='')
2022 $cache_key = $this->mailbox.'.msg';
2023 $headers = &$this->get_cached_message($cache_key, $uid);
2025 // return cached message structure
2026 if (is_object($headers) && is_object($headers->structure)) {
2027 return $headers->structure;
2030 if (!$structure_str) {
2031 $structure_str = $this->conn->fetchStructureString($this->mailbox, $uid, true);
2033 $structure = rcube_mime_struct::parseStructure($structure_str);
2036 // parse structure and add headers
2037 if (!empty($structure)) {
2038 $headers = $this->get_headers($uid);
2039 $this->_msg_id = $headers->id;
2041 // set message charset from message headers
2042 if ($headers->charset)
2043 $this->struct_charset = $headers->charset;
2045 $this->struct_charset = $this->_structure_charset($structure);
2047 $headers->ctype = strtolower($headers->ctype);
2049 // Here we can recognize malformed BODYSTRUCTURE and
2050 // 1. [@TODO] parse the message in other way to create our own message structure
2051 // 2. or just show the raw message body.
2052 // Example of structure for malformed MIME message:
2053 // ("text" "plain" NIL NIL NIL "7bit" 2154 70 NIL NIL NIL)
2054 if ($headers->ctype && !is_array($structure[0]) && $headers->ctype != 'text/plain'
2055 && strtolower($structure[0].'/'.$structure[1]) == 'text/plain') {
2056 // we can handle single-part messages, by simple fix in structure (#1486898)
2057 if (preg_match('/^(text|application)\/(.*)/', $headers->ctype, $m)) {
2058 $structure[0] = $m[1];
2059 $structure[1] = $m[2];
2065 $struct = &$this->_structure_part($structure, 0, '', $headers);
2066 $struct->headers = get_object_vars($headers);
2068 // don't trust given content-type
2069 if (empty($struct->parts) && !empty($struct->headers['ctype'])) {
2070 $struct->mime_id = '1';
2071 $struct->mimetype = strtolower($struct->headers['ctype']);
2072 list($struct->ctype_primary, $struct->ctype_secondary) = explode('/', $struct->mimetype);
2075 // write structure to cache
2076 if ($this->caching_enabled)
2077 $this->add_message_cache($cache_key, $this->_msg_id, $headers, $struct,
2078 $this->icache['message.id'][$uid], true);
2086 * Build message part object
2088 * @param array $part
2090 * @param string $parent
2093 function &_structure_part($part, $count=0, $parent='', $mime_headers=null)
2095 $struct = new rcube_message_part;
2096 $struct->mime_id = empty($parent) ? (string)$count : "$parent.$count";
2099 if (is_array($part[0])) {
2100 $struct->ctype_primary = 'multipart';
2102 /* RFC3501: BODYSTRUCTURE fields of multipart part
2108 2. parameters (optional)
2109 3. description (optional)
2110 4. language (optional)
2111 5. location (optional)
2114 // find first non-array entry
2115 for ($i=1; $i<count($part); $i++) {
2116 if (!is_array($part[$i])) {
2117 $struct->ctype_secondary = strtolower($part[$i]);
2122 $struct->mimetype = 'multipart/'.$struct->ctype_secondary;
2124 // build parts list for headers pre-fetching
2125 for ($i=0; $i<count($part); $i++) {
2126 if (!is_array($part[$i]))
2128 // fetch message headers if message/rfc822
2129 // or named part (could contain Content-Location header)
2130 if (!is_array($part[$i][0])) {
2131 $tmp_part_id = $struct->mime_id ? $struct->mime_id.'.'.($i+1) : $i+1;
2132 if (strtolower($part[$i][0]) == 'message' && strtolower($part[$i][1]) == 'rfc822') {
2133 $mime_part_headers[] = $tmp_part_id;
2135 else if (in_array('name', (array)$part[$i][2]) && (empty($part[$i][3]) || $part[$i][3]=='NIL')) {
2136 $mime_part_headers[] = $tmp_part_id;
2141 // pre-fetch headers of all parts (in one command for better performance)
2142 // @TODO: we could do this before _structure_part() call, to fetch
2143 // headers for parts on all levels
2144 if ($mime_part_headers) {
2145 $mime_part_headers = $this->conn->fetchMIMEHeaders($this->mailbox,
2146 $this->_msg_id, $mime_part_headers);
2149 $struct->parts = array();
2150 for ($i=0, $count=0; $i<count($part); $i++) {
2151 if (!is_array($part[$i]))
2153 $tmp_part_id = $struct->mime_id ? $struct->mime_id.'.'.($i+1) : $i+1;
2154 $struct->parts[] = $this->_structure_part($part[$i], ++$count, $struct->mime_id,
2155 $mime_part_headers[$tmp_part_id]);
2161 /* RFC3501: BODYSTRUCTURE fields of non-multipart part
2172 7. envelope structure
2177 x. disposition (optional)
2178 x. language (optional)
2179 x. location (optional)
2183 $struct->ctype_primary = strtolower($part[0]);
2184 $struct->ctype_secondary = strtolower($part[1]);
2185 $struct->mimetype = $struct->ctype_primary.'/'.$struct->ctype_secondary;
2187 // read content type parameters
2188 if (is_array($part[2])) {
2189 $struct->ctype_parameters = array();
2190 for ($i=0; $i<count($part[2]); $i+=2)
2191 $struct->ctype_parameters[strtolower($part[2][$i])] = $part[2][$i+1];
2193 if (isset($struct->ctype_parameters['charset']))
2194 $struct->charset = $struct->ctype_parameters['charset'];
2197 // #1487700: workaround for lack of charset in malformed structure
2198 if (empty($struct->charset) && !empty($mime_headers) && $mime_headers->charset) {
2199 $struct->charset = $mime_headers->charset;
2202 // read content encoding
2203 if (!empty($part[5]) && $part[5]!='NIL') {
2204 $struct->encoding = strtolower($part[5]);
2205 $struct->headers['content-transfer-encoding'] = $struct->encoding;
2209 if (!empty($part[6]) && $part[6]!='NIL')
2210 $struct->size = intval($part[6]);
2212 // read part disposition
2214 if ($struct->ctype_primary == 'text') $di += 1;
2215 else if ($struct->mimetype == 'message/rfc822') $di += 3;
2217 if (is_array($part[$di]) && count($part[$di]) == 2) {
2218 $struct->disposition = strtolower($part[$di][0]);
2220 if (is_array($part[$di][1]))
2221 for ($n=0; $n<count($part[$di][1]); $n+=2)
2222 $struct->d_parameters[strtolower($part[$di][1][$n])] = $part[$di][1][$n+1];
2225 // get message/rfc822's child-parts
2226 if (is_array($part[8]) && $di != 8) {
2227 $struct->parts = array();
2228 for ($i=0, $count=0; $i<count($part[8]); $i++) {
2229 if (!is_array($part[8][$i]))
2231 $struct->parts[] = $this->_structure_part($part[8][$i], ++$count, $struct->mime_id);
2236 if (!empty($part[3]) && $part[3]!='NIL') {
2237 $struct->content_id = $part[3];
2238 $struct->headers['content-id'] = $part[3];
2240 if (empty($struct->disposition))
2241 $struct->disposition = 'inline';
2244 // fetch message headers if message/rfc822 or named part (could contain Content-Location header)
2245 if ($struct->ctype_primary == 'message' || ($struct->ctype_parameters['name'] && !$struct->content_id)) {
2246 if (empty($mime_headers)) {
2247 $mime_headers = $this->conn->fetchPartHeader(
2248 $this->mailbox, $this->_msg_id, false, $struct->mime_id);
2251 if (is_string($mime_headers))
2252 $struct->headers = $this->_parse_headers($mime_headers) + $struct->headers;
2253 else if (is_object($mime_headers))
2254 $struct->headers = get_object_vars($mime_headers) + $struct->headers;
2256 // get real content-type of message/rfc822
2257 if ($struct->mimetype == 'message/rfc822') {
2259 if (!is_array($part[8][0]))
2260 $struct->real_mimetype = strtolower($part[8][0] . '/' . $part[8][1]);
2263 for ($n=0; $n<count($part[8]); $n++)
2264 if (!is_array($part[8][$n]))
2266 $struct->real_mimetype = 'multipart/' . strtolower($part[8][$n]);
2270 if ($struct->ctype_primary == 'message' && empty($struct->parts)) {
2271 if (is_array($part[8]) && $di != 8)
2272 $struct->parts[] = $this->_structure_part($part[8], ++$count, $struct->mime_id);
2276 // normalize filename property
2277 $this->_set_part_filename($struct, $mime_headers);
2284 * Set attachment filename from message part structure
2286 * @param rcube_message_part $part Part object
2287 * @param string $headers Part's raw headers
2290 private function _set_part_filename(&$part, $headers=null)
2292 if (!empty($part->d_parameters['filename']))
2293 $filename_mime = $part->d_parameters['filename'];
2294 else if (!empty($part->d_parameters['filename*']))
2295 $filename_encoded = $part->d_parameters['filename*'];
2296 else if (!empty($part->ctype_parameters['name*']))
2297 $filename_encoded = $part->ctype_parameters['name*'];
2298 // RFC2231 value continuations
2299 // TODO: this should be rewrited to support RFC2231 4.1 combinations
2300 else if (!empty($part->d_parameters['filename*0'])) {
2302 while (isset($part->d_parameters['filename*'.$i])) {
2303 $filename_mime .= $part->d_parameters['filename*'.$i];
2306 // some servers (eg. dovecot-1.x) have no support for parameter value continuations
2307 // we must fetch and parse headers "manually"
2310 $headers = $this->conn->fetchPartHeader(
2311 $this->mailbox, $this->_msg_id, false, $part->mime_id);
2313 $filename_mime = '';
2315 while (preg_match('/filename\*'.$i.'\s*=\s*"*([^"\n;]+)[";]*/', $headers, $matches)) {
2316 $filename_mime .= $matches[1];
2321 else if (!empty($part->d_parameters['filename*0*'])) {
2323 while (isset($part->d_parameters['filename*'.$i.'*'])) {
2324 $filename_encoded .= $part->d_parameters['filename*'.$i.'*'];
2329 $headers = $this->conn->fetchPartHeader(
2330 $this->mailbox, $this->_msg_id, false, $part->mime_id);
2332 $filename_encoded = '';
2333 $i = 0; $matches = array();
2334 while (preg_match('/filename\*'.$i.'\*\s*=\s*"*([^"\n;]+)[";]*/', $headers, $matches)) {
2335 $filename_encoded .= $matches[1];
2340 else if (!empty($part->ctype_parameters['name*0'])) {
2342 while (isset($part->ctype_parameters['name*'.$i])) {
2343 $filename_mime .= $part->ctype_parameters['name*'.$i];
2348 $headers = $this->conn->fetchPartHeader(
2349 $this->mailbox, $this->_msg_id, false, $part->mime_id);
2351 $filename_mime = '';
2352 $i = 0; $matches = array();
2353 while (preg_match('/\s+name\*'.$i.'\s*=\s*"*([^"\n;]+)[";]*/', $headers, $matches)) {
2354 $filename_mime .= $matches[1];
2359 else if (!empty($part->ctype_parameters['name*0*'])) {
2361 while (isset($part->ctype_parameters['name*'.$i.'*'])) {
2362 $filename_encoded .= $part->ctype_parameters['name*'.$i.'*'];
2367 $headers = $this->conn->fetchPartHeader(
2368 $this->mailbox, $this->_msg_id, false, $part->mime_id);
2370 $filename_encoded = '';
2371 $i = 0; $matches = array();
2372 while (preg_match('/\s+name\*'.$i.'\*\s*=\s*"*([^"\n;]+)[";]*/', $headers, $matches)) {
2373 $filename_encoded .= $matches[1];
2378 // read 'name' after rfc2231 parameters as it may contains truncated filename (from Thunderbird)
2379 else if (!empty($part->ctype_parameters['name']))
2380 $filename_mime = $part->ctype_parameters['name'];
2381 // Content-Disposition
2382 else if (!empty($part->headers['content-description']))
2383 $filename_mime = $part->headers['content-description'];
2388 if (!empty($filename_mime)) {
2389 $part->filename = rcube_imap::decode_mime_string($filename_mime,
2390 $part->charset ? $part->charset : ($this->struct_charset ? $this->struct_charset :
2391 rc_detect_encoding($filename_mime, $this->default_charset)));
2393 else if (!empty($filename_encoded)) {
2394 // decode filename according to RFC 2231, Section 4
2395 if (preg_match("/^([^']*)'[^']*'(.*)$/", $filename_encoded, $fmatches)) {
2396 $filename_charset = $fmatches[1];
2397 $filename_encoded = $fmatches[2];
2399 $part->filename = rcube_charset_convert(urldecode($filename_encoded), $filename_charset);
2405 * Get charset name from message structure (first part)
2407 * @param array $structure Message structure
2408 * @return string Charset name
2411 private function _structure_charset($structure)
2413 while (is_array($structure)) {
2414 if (is_array($structure[2]) && $structure[2][0] == 'charset')
2415 return $structure[2][1];
2416 $structure = $structure[0];
2422 * Fetch message body of a specific message from the server
2424 * @param int $uid Message UID
2425 * @param string $part Part number
2426 * @param rcube_message_part $o_part Part object created by get_structure()
2427 * @param mixed $print True to print part, ressource to write part contents in
2428 * @param resource $fp File pointer to save the message part
2429 * @param boolean $skip_charset_conv Disables charset conversion
2431 * @return string Message/part body if not printed
2433 function &get_message_part($uid, $part=1, $o_part=NULL, $print=NULL, $fp=NULL, $skip_charset_conv=false)
2435 // get part encoding if not provided
2436 if (!is_object($o_part)) {
2437 $structure_str = $this->conn->fetchStructureString($this->mailbox, $uid, true);
2438 $structure = new rcube_mime_struct();
2439 // error or message not found
2440 if (!$structure->loadStructure($structure_str)) {
2444 $o_part = new rcube_message_part;
2445 $o_part->ctype_primary = strtolower($structure->getPartType($part));
2446 $o_part->encoding = strtolower($structure->getPartEncoding($part));
2447 $o_part->charset = $structure->getPartCharset($part);
2450 // TODO: Add caching for message parts
2456 $body = $this->conn->handlePartBody($this->mailbox, $uid, true, $part,
2457 $o_part->encoding, $print, $fp);
2459 if ($fp || $print) {
2463 // convert charset (if text or message part)
2464 if ($body && !$skip_charset_conv &&
2465 preg_match('/^(text|message)$/', $o_part->ctype_primary)
2467 if (!$o_part->charset || strtoupper($o_part->charset) == 'US-ASCII') {
2468 $o_part->charset = $this->default_charset;
2470 $body = rcube_charset_convert($body, $o_part->charset);
2478 * Fetch message body of a specific message from the server
2480 * @param int $uid Message UID
2481 * @return string $part Message/part body
2482 * @see rcube_imap::get_message_part()
2484 function &get_body($uid, $part=1)
2486 $headers = $this->get_headers($uid);
2487 return rcube_charset_convert($this->get_message_part($uid, $part, NULL),
2488 $headers->charset ? $headers->charset : $this->default_charset);
2493 * Returns the whole message source as string
2495 * @param int $uid Message UID
2496 * @return string Message source string
2498 function &get_raw_body($uid)
2500 return $this->conn->handlePartBody($this->mailbox, $uid, true);
2505 * Returns the message headers as string
2507 * @param int $uid Message UID
2508 * @return string Message headers string
2510 function &get_raw_headers($uid)
2512 return $this->conn->fetchPartHeader($this->mailbox, $uid, true);
2517 * Sends the whole message source to stdout
2519 * @param int $uid Message UID
2521 function print_raw_body($uid)
2523 $this->conn->handlePartBody($this->mailbox, $uid, true, NULL, NULL, true);
2528 * Set message flag to one or several messages
2530 * @param mixed $uids Message UIDs as array or comma-separated string, or '*'
2531 * @param string $flag Flag to set: SEEN, UNDELETED, DELETED, RECENT, ANSWERED, DRAFT, MDNSENT
2532 * @param string $mbox_name Folder name
2533 * @param boolean $skip_cache True to skip message cache clean up
2534 * @return boolean Operation status
2536 function set_flag($uids, $flag, $mbox_name=NULL, $skip_cache=false)
2538 $mailbox = strlen($mbox_name) ? $this->mod_mailbox($mbox_name) : $this->mailbox;
2540 $flag = strtoupper($flag);
2541 list($uids, $all_mode) = $this->_parse_uids($uids, $mailbox);
2543 if (strpos($flag, 'UN') === 0)
2544 $result = $this->conn->unflag($mailbox, $uids, substr($flag, 2));
2546 $result = $this->conn->flag($mailbox, $uids, $flag);
2549 // reload message headers if cached
2550 if ($this->caching_enabled && !$skip_cache) {
2551 $cache_key = $mailbox.'.msg';
2553 $this->clear_message_cache($cache_key);
2555 $this->remove_message_cache($cache_key, explode(',', $uids));
2558 // clear cached counters
2559 if ($flag == 'SEEN' || $flag == 'UNSEEN') {
2560 $this->_clear_messagecount($mailbox, 'SEEN');
2561 $this->_clear_messagecount($mailbox, 'UNSEEN');
2563 else if ($flag == 'DELETED') {
2564 $this->_clear_messagecount($mailbox, 'DELETED');
2573 * Remove message flag for one or several messages
2575 * @param mixed $uids Message UIDs as array or comma-separated string, or '*'
2576 * @param string $flag Flag to unset: SEEN, DELETED, RECENT, ANSWERED, DRAFT, MDNSENT
2577 * @param string $mbox_name Folder name
2578 * @return int Number of flagged messages, -1 on failure
2581 function unset_flag($uids, $flag, $mbox_name=NULL)
2583 return $this->set_flag($uids, 'UN'.$flag, $mbox_name);
2588 * Append a mail message (source) to a specific mailbox
2590 * @param string $mbox_name Target mailbox
2591 * @param string $message The message source string or filename
2592 * @param string $headers Headers string if $message contains only the body
2593 * @param boolean $is_file True if $message is a filename
2595 * @return boolean True on success, False on error
2597 function save_message($mbox_name, &$message, $headers='', $is_file=false)
2599 $mailbox = $this->mod_mailbox($mbox_name);
2601 // make sure mailbox exists
2602 if ($this->mailbox_exists($mbox_name)) {
2604 $saved = $this->conn->appendFromFile($mailbox, $message, $headers);
2606 $saved = $this->conn->append($mailbox, $message);
2610 // increase messagecount of the target mailbox
2611 $this->_set_messagecount($mailbox, 'ALL', 1);
2619 * Move a message from one mailbox to another
2621 * @param mixed $uids Message UIDs as array or comma-separated string, or '*'
2622 * @param string $to_mbox Target mailbox
2623 * @param string $from_mbox Source mailbox
2624 * @return boolean True on success, False on error
2626 function move_message($uids, $to_mbox, $from_mbox='')
2630 $to_mbox = $this->mod_mailbox($to_mbox);
2631 $from_mbox = strlen($from_mbox) ? $this->mod_mailbox($from_mbox) : $this->mailbox;
2633 if ($to_mbox === $from_mbox)
2636 list($uids, $all_mode) = $this->_parse_uids($uids, $from_mbox);
2638 // exit if no message uids are specified
2642 // make sure mailbox exists
2643 if ($to_mbox != 'INBOX' && !$this->mailbox_exists($tbox)) {
2644 if (in_array($tbox, $this->default_folders))
2645 $this->create_mailbox($tbox, true);
2650 // flag messages as read before moving them
2651 $config = rcmail::get_instance()->config;
2652 if ($config->get('read_when_deleted') && $tbox == $config->get('trash_mbox')) {
2653 // don't flush cache (4th argument)
2654 $this->set_flag($uids, 'SEEN', $fbox, true);
2658 $moved = $this->conn->move($uids, $from_mbox, $to_mbox);
2660 // send expunge command in order to have the moved message
2661 // really deleted from the source mailbox
2663 $this->_expunge($from_mbox, false, $uids);
2664 $this->_clear_messagecount($from_mbox);
2665 $this->_clear_messagecount($to_mbox);
2668 else if ($config->get('delete_always', false) && $tbox == $config->get('trash_mbox')) {
2669 $moved = $this->delete_message($uids, $fbox);
2673 // unset threads internal cache
2674 unset($this->icache['threads']);
2676 // remove message ids from search set
2677 if ($this->search_set && $from_mbox == $this->mailbox) {
2678 // threads are too complicated to just remove messages from set
2679 if ($this->search_threads || $all_mode)
2680 $this->refresh_search();
2682 $uids = explode(',', $uids);
2683 foreach ($uids as $uid)
2684 $a_mids[] = $this->_uid2id($uid, $from_mbox);
2685 $this->search_set = array_diff($this->search_set, $a_mids);
2689 // update cached message headers
2690 $cache_key = $from_mbox.'.msg';
2691 if ($all_mode || ($start_index = $this->get_message_cache_index_min($cache_key, $uids))) {
2692 // clear cache from the lowest index on
2693 $this->clear_message_cache($cache_key, $all_mode ? 1 : $start_index);
2702 * Copy a message from one mailbox to another
2704 * @param mixed $uids Message UIDs as array or comma-separated string, or '*'
2705 * @param string $to_mbox Target mailbox
2706 * @param string $from_mbox Source mailbox
2707 * @return boolean True on success, False on error
2709 function copy_message($uids, $to_mbox, $from_mbox='')
2713 $to_mbox = $this->mod_mailbox($to_mbox);
2714 $from_mbox = $from_mbox ? $this->mod_mailbox($from_mbox) : $this->mailbox;
2716 list($uids, $all_mode) = $this->_parse_uids($uids, $from_mbox);
2718 // exit if no message uids are specified
2723 // make sure mailbox exists
2724 if ($to_mbox != 'INBOX' && !$this->mailbox_exists($tbox)) {
2725 if (in_array($tbox, $this->default_folders))
2726 $this->create_mailbox($tbox, true);
2732 $copied = $this->conn->copy($uids, $from_mbox, $to_mbox);
2735 $this->_clear_messagecount($to_mbox);
2743 * Mark messages as deleted and expunge mailbox
2745 * @param mixed $uids Message UIDs as array or comma-separated string, or '*'
2746 * @param string $mbox_name Source mailbox
2747 * @return boolean True on success, False on error
2749 function delete_message($uids, $mbox_name='')
2751 $mailbox = strlen($mbox_name) ? $this->mod_mailbox($mbox_name) : $this->mailbox;
2753 list($uids, $all_mode) = $this->_parse_uids($uids, $mailbox);
2755 // exit if no message uids are specified
2759 $deleted = $this->conn->delete($mailbox, $uids);
2762 // send expunge command in order to have the deleted message
2763 // really deleted from the mailbox
2764 $this->_expunge($mailbox, false, $uids);
2765 $this->_clear_messagecount($mailbox);
2766 unset($this->uid_id_map[$mailbox]);
2768 // unset threads internal cache
2769 unset($this->icache['threads']);
2771 // remove message ids from search set
2772 if ($this->search_set && $mailbox == $this->mailbox) {
2773 // threads are too complicated to just remove messages from set
2774 if ($this->search_threads || $all_mode)
2775 $this->refresh_search();
2777 $uids = explode(',', $uids);
2778 foreach ($uids as $uid)
2779 $a_mids[] = $this->_uid2id($uid, $mailbox);
2780 $this->search_set = array_diff($this->search_set, $a_mids);
2784 // remove deleted messages from cache
2785 $cache_key = $mailbox.'.msg';
2786 if ($all_mode || ($start_index = $this->get_message_cache_index_min($cache_key, $uids))) {
2787 // clear cache from the lowest index on
2788 $this->clear_message_cache($cache_key, $all_mode ? 1 : $start_index);
2797 * Clear all messages in a specific mailbox
2799 * @param string $mbox_name Mailbox name
2800 * @return int Above 0 on success
2802 function clear_mailbox($mbox_name=NULL)
2804 $mailbox = strlen($mbox_name) ? $this->mod_mailbox($mbox_name) : $this->mailbox;
2806 // SELECT will set messages count for clearFolder()
2807 if ($this->conn->select($mailbox)) {
2808 $cleared = $this->conn->clearFolder($mailbox);
2811 // make sure the message count cache is cleared as well
2813 $this->clear_message_cache($mailbox.'.msg');
2814 $a_mailbox_cache = $this->get_cache('messagecount');
2815 unset($a_mailbox_cache[$mailbox]);
2816 $this->update_cache('messagecount', $a_mailbox_cache);
2824 * Send IMAP expunge command and clear cache
2826 * @param string $mbox_name Mailbox name
2827 * @param boolean $clear_cache False if cache should not be cleared
2828 * @return boolean True on success
2830 function expunge($mbox_name='', $clear_cache=true)
2832 $mailbox = strlen($mbox_name) ? $this->mod_mailbox($mbox_name) : $this->mailbox;
2833 return $this->_expunge($mailbox, $clear_cache);
2838 * Send IMAP expunge command and clear cache
2840 * @param string $mailbox Mailbox name
2841 * @param boolean $clear_cache False if cache should not be cleared
2842 * @param mixed $uids Message UIDs as array or comma-separated string, or '*'
2843 * @return boolean True on success
2845 * @see rcube_imap::expunge()
2847 private function _expunge($mailbox, $clear_cache=true, $uids=NULL)
2849 if ($uids && $this->get_capability('UIDPLUS'))
2850 $a_uids = is_array($uids) ? join(',', $uids) : $uids;
2854 // force mailbox selection and check if mailbox is writeable
2855 // to prevent a situation when CLOSE is executed on closed
2856 // or EXPUNGE on read-only mailbox
2857 $result = $this->conn->select($mailbox);
2861 if (!$this->conn->data['READ-WRITE']) {
2862 $this->conn->setError(rcube_imap_generic::ERROR_READONLY, "Mailbox is read-only");
2866 // CLOSE(+SELECT) should be faster than EXPUNGE
2867 if (empty($a_uids) || $a_uids == '1:*')
2868 $result = $this->conn->close();
2870 $result = $this->conn->expunge($mailbox, $a_uids);
2872 if ($result && $clear_cache) {
2873 $this->clear_message_cache($mailbox.'.msg');
2874 $this->_clear_messagecount($mailbox);
2882 * Parse message UIDs input
2884 * @param mixed $uids UIDs array or comma-separated list or '*' or '1:*'
2885 * @param string $mailbox Mailbox name
2886 * @return array Two elements array with UIDs converted to list and ALL flag
2889 private function _parse_uids($uids, $mailbox)
2891 if ($uids === '*' || $uids === '1:*') {
2892 if (empty($this->search_set)) {
2896 // get UIDs from current search set
2897 // @TODO: skip fetchUIDs() and work with IDs instead of UIDs (?)
2899 if ($this->search_threads)
2900 $uids = $this->conn->fetchUIDs($mailbox, array_keys($this->search_set['depth']));
2902 $uids = $this->conn->fetchUIDs($mailbox, $this->search_set);
2904 // save ID-to-UID mapping in local cache
2905 if (is_array($uids))
2906 foreach ($uids as $id => $uid)
2907 $this->uid_id_map[$mailbox][$uid] = $id;
2909 $uids = join(',', $uids);
2913 if (is_array($uids))
2914 $uids = join(',', $uids);
2916 if (preg_match('/[^0-9,]/', $uids))
2920 return array($uids, (bool) $all);
2925 * Translate UID to message ID
2927 * @param int $uid Message UID
2928 * @param string $mbox_name Mailbox name
2929 * @return int Message ID
2931 function get_id($uid, $mbox_name=NULL)
2933 $mailbox = strlen($mbox_name) ? $this->mod_mailbox($mbox_name) : $this->mailbox;
2934 return $this->_uid2id($uid, $mailbox);
2939 * Translate message number to UID
2941 * @param int $id Message ID
2942 * @param string $mbox_name Mailbox name
2943 * @return int Message UID
2945 function get_uid($id, $mbox_name=NULL)
2947 $mailbox = strlen($mbox_name) ? $this->mod_mailbox($mbox_name) : $this->mailbox;
2948 return $this->_id2uid($id, $mailbox);
2953 /* --------------------------------
2955 * --------------------------------*/
2958 * Public method for listing subscribed folders
2960 * Converts mailbox name with root dir first
2962 * @param string $root Optional root folder
2963 * @param string $filter Optional filter for mailbox listing
2964 * @return array List of mailboxes/folders
2967 function list_mailboxes($root='', $filter='*')
2970 $a_mboxes = $this->_list_mailboxes($root, $filter);
2972 foreach ($a_mboxes as $idx => $mbox_row) {
2973 if (strlen($name = $this->mod_mailbox($mbox_row, 'out')))
2975 unset($a_mboxes[$idx]);
2978 // INBOX should always be available
2979 if (!in_array('INBOX', $a_out))
2980 array_unshift($a_out, 'INBOX');
2983 $a_out = $this->_sort_mailbox_list($a_out);
2990 * Private method for mailbox listing
2992 * @param string $root Optional root folder
2993 * @param string $filter Optional filter for mailbox listing
2994 * @return array List of mailboxes/folders
2995 * @see rcube_imap::list_mailboxes()
2998 private function _list_mailboxes($root='', $filter='*')
3000 // get cached folder list
3001 $a_mboxes = $this->get_cache('mailboxes');
3002 if (is_array($a_mboxes))
3005 $a_defaults = $a_out = array();
3007 // Give plugins a chance to provide a list of mailboxes
3008 $data = rcmail::get_instance()->plugins->exec_hook('mailboxes_list',
3009 array('root' => $root, 'filter' => $filter, 'mode' => 'LSUB'));
3011 if (isset($data['folders'])) {
3012 $a_folders = $data['folders'];
3015 // Server supports LIST-EXTENDED, we can use selection options
3016 $config = rcmail::get_instance()->config;
3017 // #1486225: Some dovecot versions returns wrong result using LIST-EXTENDED
3018 if (!$config->get('imap_force_lsub') && $this->get_capability('LIST-EXTENDED')) {
3019 // This will also set mailbox options, LSUB doesn't do that
3020 $a_folders = $this->conn->listMailboxes($this->mod_mailbox($root), $filter,
3021 NULL, array('SUBSCRIBED'));
3023 // remove non-existent folders
3024 if (is_array($a_folders)) {
3025 foreach ($a_folders as $idx => $folder) {
3026 if ($this->conn->data['LIST'] && ($opts = $this->conn->data['LIST'][$folder])
3027 && in_array('\\NonExistent', $opts)
3029 unset($a_folders[$idx]);
3034 // retrieve list of folders from IMAP server using LSUB
3036 $a_folders = $this->conn->listSubscribed($this->mod_mailbox($root), $filter);
3040 if (!is_array($a_folders) || !sizeof($a_folders))
3041 $a_folders = array();
3043 // write mailboxlist to cache
3044 $this->update_cache('mailboxes', $a_folders);
3051 * Get a list of all folders available on the IMAP server
3053 * @param string $root IMAP root dir
3054 * @param string $filter Optional filter for mailbox listing
3055 * @return array Indexed array with folder names
3057 function list_unsubscribed($root='', $filter='*')
3059 // Give plugins a chance to provide a list of mailboxes
3060 $data = rcmail::get_instance()->plugins->exec_hook('mailboxes_list',
3061 array('root' => $root, 'filter' => $filter, 'mode' => 'LIST'));
3063 if (isset($data['folders'])) {
3064 $a_mboxes = $data['folders'];
3067 // retrieve list of folders from IMAP server
3068 $a_mboxes = $this->conn->listMailboxes($this->mod_mailbox($root), $filter);
3071 $a_folders = array();
3072 if (!is_array($a_mboxes))
3073 $a_mboxes = array();
3075 // modify names with root dir
3076 foreach ($a_mboxes as $idx => $mbox_name) {
3077 if (strlen($name = $this->mod_mailbox($mbox_name, 'out')))
3078 $a_folders[] = $name;
3079 unset($a_mboxes[$idx]);
3082 // INBOX should always be available
3083 if (!in_array('INBOX', $a_folders))
3084 array_unshift($a_folders, 'INBOX');
3086 // filter folders and sort them
3087 $a_folders = $this->_sort_mailbox_list($a_folders);
3093 * Get mailbox quota information
3096 * @return mixed Quota info or False if not supported
3098 function get_quota()
3100 if ($this->get_capability('QUOTA'))
3101 return $this->conn->getQuota();
3108 * Get mailbox size (size of all messages in a mailbox)
3110 * @param string $name Mailbox name
3111 * @return int Mailbox size in bytes, False on error
3113 function get_mailbox_size($name)
3115 $name = $this->mod_mailbox($name);
3117 // @TODO: could we try to use QUOTA here?
3118 $result = $this->conn->fetchHeaderIndex($name, '1:*', 'SIZE', false);
3120 if (is_array($result))
3121 $result = array_sum($result);
3128 * Subscribe to a specific mailbox(es)
3130 * @param array $a_mboxes Mailbox name(s)
3131 * @return boolean True on success
3133 function subscribe($a_mboxes)
3135 if (!is_array($a_mboxes))
3136 $a_mboxes = array($a_mboxes);
3138 // let this common function do the main work
3139 return $this->_change_subscription($a_mboxes, 'subscribe');
3144 * Unsubscribe mailboxes
3146 * @param array $a_mboxes Mailbox name(s)
3147 * @return boolean True on success
3149 function unsubscribe($a_mboxes)
3151 if (!is_array($a_mboxes))
3152 $a_mboxes = array($a_mboxes);
3154 // let this common function do the main work
3155 return $this->_change_subscription($a_mboxes, 'unsubscribe');
3160 * Create a new mailbox on the server and register it in local cache
3162 * @param string $name New mailbox name
3163 * @param boolean $subscribe True if the new mailbox should be subscribed
3164 * @param boolean True on success
3166 function create_mailbox($name, $subscribe=false)
3169 $abs_name = $this->mod_mailbox($name);
3170 $result = $this->conn->createFolder($abs_name);
3172 // try to subscribe it
3173 if ($result && $subscribe)
3174 $this->subscribe($name);
3181 * Set a new name to an existing mailbox
3183 * @param string $mbox_name Mailbox to rename
3184 * @param string $new_name New mailbox name
3186 * @return boolean True on success
3188 function rename_mailbox($mbox_name, $new_name)
3192 // make absolute path
3193 $mailbox = $this->mod_mailbox($mbox_name);
3194 $abs_name = $this->mod_mailbox($new_name);
3195 $delm = $this->get_hierarchy_delimiter();
3197 // get list of subscribed folders
3198 if ((strpos($mailbox, '%') === false) && (strpos($mailbox, '*') === false)) {
3199 $a_subscribed = $this->_list_mailboxes('', $mbox_name . $delm . '*');
3200 $subscribed = $this->mailbox_exists($mbox_name, true);
3203 $a_subscribed = $this->_list_mailboxes();
3204 $subscribed = in_array($mailbox, $a_subscribed);
3207 if (strlen($abs_name))
3208 $result = $this->conn->renameFolder($mailbox, $abs_name);
3211 // unsubscribe the old folder, subscribe the new one
3213 $this->conn->unsubscribe($mailbox);
3214 $this->conn->subscribe($abs_name);
3217 // check if mailbox children are subscribed
3218 foreach ($a_subscribed as $c_subscribed) {
3219 if (preg_match('/^'.preg_quote($mailbox.$delm, '/').'/', $c_subscribed)) {
3220 $this->conn->unsubscribe($c_subscribed);
3221 $this->conn->subscribe(preg_replace('/^'.preg_quote($mailbox, '/').'/',
3222 $abs_name, $c_subscribed));
3227 $this->clear_message_cache($mailbox.'.msg');
3228 $this->clear_cache('mailboxes');
3236 * Remove mailbox from server
3238 * @param string $mbox_name Mailbox name
3240 * @return boolean True on success
3242 function delete_mailbox($mbox_name)
3245 $mailbox = $this->mod_mailbox($mbox_name);
3246 $delm = $this->get_hierarchy_delimiter();
3248 // get list of folders
3249 if ((strpos($mailbox, '%') === false) && (strpos($mailbox, '*') === false))
3250 $sub_mboxes = $this->list_unsubscribed('', $mailbox . $delm . '*');
3252 $sub_mboxes = $this->list_unsubscribed();
3254 // send delete command to server
3255 $result = $this->conn->deleteFolder($mailbox);
3258 // unsubscribe mailbox
3259 $this->conn->unsubscribe($mailbox);
3261 foreach ($sub_mboxes as $c_mbox) {
3262 if (preg_match('/^'.preg_quote($mailbox.$delm, '/').'/', $c_mbox)) {
3263 $this->conn->unsubscribe($c_mbox);
3264 if ($this->conn->deleteFolder($c_mbox)) {
3265 $this->clear_message_cache($c_mbox.'.msg');
3270 // clear mailbox-related cache
3271 $this->clear_message_cache($mailbox.'.msg');
3272 $this->clear_cache('mailboxes');
3280 * Create all folders specified as default
3282 function create_default_folders()
3284 // create default folders if they do not exist
3285 foreach ($this->default_folders as $folder) {
3286 if (!$this->mailbox_exists($folder))
3287 $this->create_mailbox($folder, true);
3288 else if (!$this->mailbox_exists($folder, true))
3289 $this->subscribe($folder);
3295 * Checks if folder exists and is subscribed
3297 * @param string $mbox_name Folder name
3298 * @param boolean $subscription Enable subscription checking
3299 * @return boolean TRUE or FALSE
3301 function mailbox_exists($mbox_name, $subscription=false)
3303 if ($mbox_name == 'INBOX')
3306 $key = $subscription ? 'subscribed' : 'existing';
3307 $mbox = $this->mod_mailbox($mbox_name);
3309 if (is_array($this->icache[$key]) && in_array($mbox, $this->icache[$key]))
3312 if ($subscription) {
3313 $a_folders = $this->conn->listSubscribed('', $mbox);
3316 $a_folders = $this->conn->listMailboxes('', $mbox);
3319 if (is_array($a_folders) && in_array($mbox, $a_folders)) {
3320 $this->icache[$key][] = $mbox;
3329 * Modify folder name for input/output according to root dir and namespace
3331 * @param string $mbox_name Folder name
3332 * @param string $mode Mode
3333 * @return string Folder name
3335 function mod_mailbox($mbox_name, $mode='in')
3337 if (!strlen($mbox_name))
3340 if ($mode == 'in') {
3341 // If folder contains namespace prefix, don't modify it
3342 if (is_array($this->namespace['shared'])) {
3343 foreach ($this->namespace['shared'] as $ns) {
3344 if ($ns[0] && strpos($mbox_name, $ns[0]) === 0) {
3349 if (is_array($this->namespace['other'])) {
3350 foreach ($this->namespace['other'] as $ns) {
3351 if ($ns[0] && strpos($mbox_name, $ns[0]) === 0) {
3356 if (is_array($this->namespace['personal'])) {
3357 foreach ($this->namespace['personal'] as $ns) {
3358 if ($ns[0] && strpos($mbox_name, $ns[0]) === 0) {
3362 // Add prefix if first personal namespace is non-empty
3363 if ($mbox_name != 'INBOX' && $this->namespace['personal'][0][0]) {
3364 return $this->namespace['personal'][0][0].$mbox_name;
3369 // Remove prefix if folder is from first ("non-empty") personal namespace
3370 if (is_array($this->namespace['personal'])) {
3371 if ($prefix = $this->namespace['personal'][0][0]) {
3372 if (strpos($mbox_name, $prefix) === 0) {
3373 return substr($mbox_name, strlen($prefix));
3384 * Gets folder options from LIST response, e.g. \Noselect, \Noinferiors
3386 * @param string $mbox_name Folder name
3387 * @param bool $force Set to True if options should be refreshed
3388 * Options are available after LIST command only
3390 * @return array Options list
3392 function mailbox_options($mbox_name, $force=false)
3394 $mbox = $this->mod_mailbox($mbox_name);
3396 if ($mbox == 'INBOX') {
3400 if (!is_array($this->conn->data['LIST']) || !is_array($this->conn->data['LIST'][$mbox])) {
3402 $this->conn->listMailboxes('', $mbox_name);
3409 $opts = $this->conn->data['LIST'][$mbox];
3411 return is_array($opts) ? $opts : array();
3416 * Get message header names for rcube_imap_generic::fetchHeader(s)
3418 * @return string Space-separated list of header names
3420 private function get_fetch_headers()
3422 $headers = explode(' ', $this->fetch_add_headers);
3423 $headers = array_map('strtoupper', $headers);
3425 if ($this->caching_enabled || $this->get_all_headers)
3426 $headers = array_merge($headers, $this->all_headers);
3428 return implode(' ', array_unique($headers));
3432 /* -----------------------------------------
3433 * ACL and METADATA/ANNOTATEMORE methods
3434 * ----------------------------------------*/
3437 * Changes the ACL on the specified mailbox (SETACL)
3439 * @param string $mailbox Mailbox name
3440 * @param string $user User name
3441 * @param string $acl ACL string
3443 * @return boolean True on success, False on failure
3448 function set_acl($mailbox, $user, $acl)
3450 $mailbox = $this->mod_mailbox($mailbox);
3452 if ($this->get_capability('ACL'))
3453 return $this->conn->setACL($mailbox, $user, $acl);
3460 * Removes any <identifier,rights> pair for the
3461 * specified user from the ACL for the specified
3462 * mailbox (DELETEACL)
3464 * @param string $mailbox Mailbox name
3465 * @param string $user User name
3467 * @return boolean True on success, False on failure
3472 function delete_acl($mailbox, $user)
3474 $mailbox = $this->mod_mailbox($mailbox);
3476 if ($this->get_capability('ACL'))
3477 return $this->conn->deleteACL($mailbox, $user);
3484 * Returns the access control list for mailbox (GETACL)
3486 * @param string $mailbox Mailbox name
3488 * @return array User-rights array on success, NULL on error
3492 function get_acl($mailbox)
3494 $mailbox = $this->mod_mailbox($mailbox);
3496 if ($this->get_capability('ACL'))
3497 return $this->conn->getACL($mailbox);
3504 * Returns information about what rights can be granted to the
3505 * user (identifier) in the ACL for the mailbox (LISTRIGHTS)
3507 * @param string $mailbox Mailbox name
3508 * @param string $user User name
3510 * @return array List of user rights
3514 function list_rights($mailbox, $user)
3516 $mailbox = $this->mod_mailbox($mailbox);
3518 if ($this->get_capability('ACL'))
3519 return $this->conn->listRights($mailbox, $user);
3526 * Returns the set of rights that the current user has to
3527 * mailbox (MYRIGHTS)
3529 * @param string $mailbox Mailbox name
3531 * @return array MYRIGHTS response on success, NULL on error
3535 function my_rights($mailbox)
3537 $mailbox = $this->mod_mailbox($mailbox);
3539 if ($this->get_capability('ACL'))
3540 return $this->conn->myRights($mailbox);
3547 * Sets IMAP metadata/annotations (SETMETADATA/SETANNOTATION)
3549 * @param string $mailbox Mailbox name (empty for server metadata)
3550 * @param array $entries Entry-value array (use NULL value as NIL)
3552 * @return boolean True on success, False on failure
3556 function set_metadata($mailbox, $entries)
3559 $mailbox = $this->mod_mailbox($mailbox);
3561 if ($this->get_capability('METADATA') ||
3562 (!strlen($mailbox) && $this->get_capability('METADATA-SERVER'))
3564 return $this->conn->setMetadata($mailbox, $entries);
3566 else if ($this->get_capability('ANNOTATEMORE') || $this->get_capability('ANNOTATEMORE2')) {
3567 foreach ($entries as $entry => $value) {
3568 list($ent, $attr) = $this->md2annotate($entry);
3569 $entries[$entry] = array($ent, $attr, $value);
3571 return $this->conn->setAnnotation($mailbox, $entries);
3579 * Unsets IMAP metadata/annotations (SETMETADATA/SETANNOTATION)
3581 * @param string $mailbox Mailbox name (empty for server metadata)
3582 * @param array $entries Entry names array
3584 * @return boolean True on success, False on failure
3589 function delete_metadata($mailbox, $entries)
3592 $mailbox = $this->mod_mailbox($mailbox);
3594 if ($this->get_capability('METADATA') ||
3595 (!strlen($mailbox) && $this->get_capability('METADATA-SERVER'))
3597 return $this->conn->deleteMetadata($mailbox, $entries);
3599 else if ($this->get_capability('ANNOTATEMORE') || $this->get_capability('ANNOTATEMORE2')) {
3600 foreach ($entries as $idx => $entry) {
3601 list($ent, $attr) = $this->md2annotate($entry);
3602 $entries[$idx] = array($ent, $attr, NULL);
3604 return $this->conn->setAnnotation($mailbox, $entries);
3612 * Returns IMAP metadata/annotations (GETMETADATA/GETANNOTATION)
3614 * @param string $mailbox Mailbox name (empty for server metadata)
3615 * @param array $entries Entries
3616 * @param array $options Command options (with MAXSIZE and DEPTH keys)
3618 * @return array Metadata entry-value hash array on success, NULL on error
3623 function get_metadata($mailbox, $entries, $options=array())
3626 $mailbox = $this->mod_mailbox($mailbox);
3628 if ($this->get_capability('METADATA') ||
3629 !strlen(($mailbox) && $this->get_capability('METADATA-SERVER'))
3631 return $this->conn->getMetadata($mailbox, $entries, $options);
3633 else if ($this->get_capability('ANNOTATEMORE') || $this->get_capability('ANNOTATEMORE2')) {
3637 // Convert entry names
3638 foreach ($entries as $entry) {
3639 list($ent, $attr) = $this->md2annotate($entry);
3640 $queries[$attr][] = $ent;
3643 // @TODO: Honor MAXSIZE and DEPTH options
3644 foreach ($queries as $attrib => $entry)
3645 if ($result = $this->conn->getAnnotation($mailbox, $entry, $attrib))
3646 $res = array_merge($res, $result);
3656 * Converts the METADATA extension entry name into the correct
3657 * entry-attrib names for older ANNOTATEMORE version.
3659 * @param string Entry name
3661 * @return array Entry-attribute list, NULL if not supported (?)
3663 private function md2annotate($name)
3665 if (substr($entry, 0, 7) == '/shared') {
3666 return array(substr($entry, 7), 'value.shared');
3668 else if (substr($entry, 0, 8) == '/private') {
3669 return array(substr($entry, 8), 'value.priv');
3677 /* --------------------------------
3678 * internal caching methods
3679 * --------------------------------*/
3682 * Enable or disable caching
3684 * @param boolean $set Flag
3687 function set_caching($set)
3689 if ($set && is_object($this->db))
3690 $this->caching_enabled = true;
3692 $this->caching_enabled = false;
3697 * Returns cached value
3699 * @param string $key Cache key
3703 function get_cache($key)
3705 // read cache (if it was not read before)
3706 if (!count($this->cache) && $this->caching_enabled) {
3707 return $this->_read_cache_record($key);
3710 return $this->cache[$key];
3717 * @param string $key Cache key
3718 * @param mixed $data Data
3721 private function update_cache($key, $data)
3723 $this->cache[$key] = $data;
3724 $this->cache_changed = true;
3725 $this->cache_changes[$key] = true;
3734 private function write_cache()
3736 if ($this->caching_enabled && $this->cache_changed) {
3737 foreach ($this->cache as $key => $data) {
3738 if ($this->cache_changes[$key])
3739 $this->_write_cache_record($key, serialize($data));
3748 * @param string $key Cache key
3751 function clear_cache($key=NULL)
3753 if (!$this->caching_enabled)
3757 foreach ($this->cache as $key => $data)
3758 $this->_clear_cache_record($key);
3760 $this->cache = array();
3761 $this->cache_changed = false;
3762 $this->cache_changes = array();
3765 $this->_clear_cache_record($key);
3766 $this->cache_changes[$key] = false;
3767 unset($this->cache[$key]);
3773 * Returns cached entry
3775 * @param string $key Cache key
3776 * @return mixed Cached value
3779 private function _read_cache_record($key)
3782 // get cached data from DB
3783 $sql_result = $this->db->query(
3784 "SELECT cache_id, data, cache_key ".
3785 "FROM ".get_table_name('cache').
3786 " WHERE user_id=? ".
3787 "AND cache_key LIKE 'IMAP.%'",
3788 $_SESSION['user_id']);
3790 while ($sql_arr = $this->db->fetch_assoc($sql_result)) {
3791 $sql_key = preg_replace('/^IMAP\./', '', $sql_arr['cache_key']);
3792 $this->cache_keys[$sql_key] = $sql_arr['cache_id'];
3793 if (!isset($this->cache[$sql_key]))
3794 $this->cache[$sql_key] = $sql_arr['data'] ? unserialize($sql_arr['data']) : false;
3798 return $this->cache[$key];
3803 * Writes single cache record
3805 * @param string $key Cache key
3806 * @param mxied $data Cache value
3809 private function _write_cache_record($key, $data)
3814 // update existing cache record
3815 if ($this->cache_keys[$key]) {
3817 "UPDATE ".get_table_name('cache').
3818 " SET created=". $this->db->now().", data=? ".
3822 $_SESSION['user_id'],
3825 // add new cache record
3828 "INSERT INTO ".get_table_name('cache').
3829 " (created, user_id, cache_key, data) ".
3830 "VALUES (".$this->db->now().", ?, ?, ?)",
3831 $_SESSION['user_id'],
3835 // get cache entry ID for this key
3836 $sql_result = $this->db->query(
3838 "FROM ".get_table_name('cache').
3839 " WHERE user_id=? ".
3841 $_SESSION['user_id'],
3844 if ($sql_arr = $this->db->fetch_assoc($sql_result))
3845 $this->cache_keys[$key] = $sql_arr['cache_id'];
3851 * Clears cache for single record
3853 * @param string $ket Cache key
3856 private function _clear_cache_record($key)
3859 "DELETE FROM ".get_table_name('cache').
3860 " WHERE user_id=? ".
3862 $_SESSION['user_id'],
3865 unset($this->cache_keys[$key]);
3870 /* --------------------------------
3871 * message caching methods
3872 * --------------------------------*/
3875 * Checks if the cache is up-to-date
3877 * @param string $mailbox Mailbox name
3878 * @param string $cache_key Internal cache key
3879 * @return int Cache status: -3 = off, -2 = incomplete, -1 = dirty, 1 = OK
3881 private function check_cache_status($mailbox, $cache_key)
3883 if (!$this->caching_enabled)
3886 $cache_index = $this->get_message_cache_index($cache_key);
3887 $msg_count = $this->_messagecount($mailbox);
3888 $cache_count = count($cache_index);
3892 return $cache_count ? -2 : 1;
3895 if ($cache_count == $msg_count) {
3896 if ($this->skip_deleted) {
3897 if (!empty($this->icache['all_undeleted_idx'])) {
3898 $uids = rcube_imap_generic::uncompressMessageSet($this->icache['all_undeleted_idx']);
3899 $uids = array_flip($uids);
3900 foreach ($cache_index as $uid) {
3905 // get all undeleted messages excluding cached UIDs
3906 $uids = $this->search_once($mailbox, 'ALL UNDELETED NOT UID '.
3907 rcube_imap_generic::compressMessageSet($cache_index));
3913 // get UID of the message with highest index
3914 $uid = $this->_id2uid($msg_count, $mailbox);
3915 $cache_uid = array_pop($cache_index);
3917 // uids of highest message matches -> cache seems OK
3918 if ($cache_uid == $uid) {
3926 // if cache count differs less than 10% report as dirty
3927 return (abs($msg_count - $cache_count) < $msg_count/10) ? -1 : -2;
3932 * @param string $key Cache key
3933 * @param string $from
3935 * @param string $sort_field
3936 * @param string $sort_order
3939 private function get_message_cache($key, $from, $to, $sort_field, $sort_order)
3941 if (!$this->caching_enabled)
3944 // use idx sort as default sorting
3945 if (!$sort_field || !in_array($sort_field, $this->db_header_fields)) {
3946 $sort_field = 'idx';
3951 $sql_result = $this->db->limitquery(
3952 "SELECT idx, uid, headers".
3953 " FROM ".get_table_name('messages').
3956 " ORDER BY ".$this->db->quoteIdentifier($sort_field)." ".strtoupper($sort_order),
3959 $_SESSION['user_id'],
3962 while ($sql_arr = $this->db->fetch_assoc($sql_result)) {
3963 $uid = intval($sql_arr['uid']);
3964 $result[$uid] = $this->db->decode(unserialize($sql_arr['headers']));
3966 // featch headers if unserialize failed
3967 if (empty($result[$uid]))
3968 $result[$uid] = $this->conn->fetchHeader(
3969 preg_replace('/.msg$/', '', $key), $uid, true, false, $this->get_fetch_headers());
3977 * @param string $key Cache key
3978 * @param int $uid Message UID
3982 private function &get_cached_message($key, $uid)
3984 $internal_key = 'message';
3986 if ($this->caching_enabled && !isset($this->icache[$internal_key][$uid])) {
3987 $sql_result = $this->db->query(
3988 "SELECT idx, headers, structure, message_id".
3989 " FROM ".get_table_name('messages').
3993 $_SESSION['user_id'],
3997 if ($sql_arr = $this->db->fetch_assoc($sql_result)) {
3998 $this->icache['message.id'][$uid] = intval($sql_arr['message_id']);
3999 $this->uid_id_map[preg_replace('/\.msg$/', '', $key)][$uid] = intval($sql_arr['idx']);
4000 $this->icache[$internal_key][$uid] = $this->db->decode(unserialize($sql_arr['headers']));
4002 if (is_object($this->icache[$internal_key][$uid]) && !empty($sql_arr['structure']))
4003 $this->icache[$internal_key][$uid]->structure = $this->db->decode(unserialize($sql_arr['structure']));
4007 return $this->icache[$internal_key][$uid];
4012 * @param string $key Cache key
4013 * @param string $sort_field Sorting column
4014 * @param string $sort_order Sorting order
4015 * @return array Messages index
4018 private function get_message_cache_index($key, $sort_field='idx', $sort_order='ASC')
4020 if (!$this->caching_enabled || empty($key))
4023 // use idx sort as default
4024 if (!$sort_field || !in_array($sort_field, $this->db_header_fields))
4025 $sort_field = 'idx';
4027 if (array_key_exists('index', $this->icache)
4028 && $this->icache['index']['key'] == $key
4029 && $this->icache['index']['sort_field'] == $sort_field
4031 if ($this->icache['index']['sort_order'] == $sort_order)
4032 return $this->icache['index']['result'];
4034 return array_reverse($this->icache['index']['result'], true);
4037 $this->icache['index'] = array(
4038 'result' => array(),
4040 'sort_field' => $sort_field,
4041 'sort_order' => $sort_order,
4044 $sql_result = $this->db->query(
4046 " FROM ".get_table_name('messages').
4049 " ORDER BY ".$this->db->quote_identifier($sort_field)." ".$sort_order,
4050 $_SESSION['user_id'],
4053 while ($sql_arr = $this->db->fetch_assoc($sql_result))
4054 $this->icache['index']['result'][$sql_arr['idx']] = intval($sql_arr['uid']);
4056 return $this->icache['index']['result'];
4063 private function add_message_cache($key, $index, $headers, $struct=null, $force=false, $internal_cache=false)
4065 if (empty($key) || !is_object($headers) || empty($headers->uid))
4068 // add to internal (fast) cache
4069 if ($internal_cache) {
4070 $this->icache['message'][$headers->uid] = clone $headers;
4071 $this->icache['message'][$headers->uid]->structure = $struct;
4074 // no further caching
4075 if (!$this->caching_enabled)
4079 if (is_int($force) && $force > 0) {
4080 $message_id = $force;
4082 // check for an existing record (probably headers are cached but structure not)
4084 $sql_result = $this->db->query(
4085 "SELECT message_id".
4086 " FROM ".get_table_name('messages').
4090 $_SESSION['user_id'],
4094 if ($sql_arr = $this->db->fetch_assoc($sql_result))
4095 $message_id = $sql_arr['message_id'];
4098 // update cache record
4101 "UPDATE ".get_table_name('messages').
4102 " SET idx=?, headers=?, structure=?".
4103 " WHERE message_id=?",
4105 serialize($this->db->encode(clone $headers)),
4106 is_object($struct) ? serialize($this->db->encode(clone $struct)) : NULL,
4110 else { // insert new record
4112 "INSERT INTO ".get_table_name('messages').
4113 " (user_id, del, cache_key, created, idx, uid, subject, ".
4114 $this->db->quoteIdentifier('from').", ".
4115 $this->db->quoteIdentifier('to').", ".
4116 "cc, date, size, headers, structure)".
4117 " VALUES (?, 0, ?, ".$this->db->now().", ?, ?, ?, ?, ?, ?, ".
4118 $this->db->fromunixtime($headers->timestamp).", ?, ?, ?)",
4119 $_SESSION['user_id'],
4123 (string)mb_substr($this->db->encode($this->decode_header($headers->subject, true)), 0, 128),
4124 (string)mb_substr($this->db->encode($this->decode_header($headers->from, true)), 0, 128),
4125 (string)mb_substr($this->db->encode($this->decode_header($headers->to, true)), 0, 128),
4126 (string)mb_substr($this->db->encode($this->decode_header($headers->cc, true)), 0, 128),
4127 (int)$headers->size,
4128 serialize($this->db->encode(clone $headers)),
4129 is_object($struct) ? serialize($this->db->encode(clone $struct)) : NULL
4133 unset($this->icache['index']);
4140 private function remove_message_cache($key, $ids, $idx=false)
4142 if (!$this->caching_enabled)
4146 "DELETE FROM ".get_table_name('messages').
4149 " AND ".($idx ? "idx" : "uid")." IN (".$this->db->array2list($ids, 'integer').")",
4150 $_SESSION['user_id'],
4153 unset($this->icache['index']);
4158 * @param string $key Cache key
4159 * @param int $start_index Start index
4162 private function clear_message_cache($key, $start_index=1)
4164 if (!$this->caching_enabled)
4168 "DELETE FROM ".get_table_name('messages').
4172 $_SESSION['user_id'], $key, $start_index);
4174 unset($this->icache['index']);
4181 private function get_message_cache_index_min($key, $uids=NULL)
4183 if (!$this->caching_enabled)
4186 if (!empty($uids) && !is_array($uids)) {
4187 if ($uids == '*' || $uids == '1:*')
4190 $uids = explode(',', $uids);
4193 $sql_result = $this->db->query(
4194 "SELECT MIN(idx) AS minidx".
4195 " FROM ".get_table_name('messages').
4198 .(!empty($uids) ? " AND uid IN (".$this->db->array2list($uids, 'integer').")" : ''),
4199 $_SESSION['user_id'],
4202 if ($sql_arr = $this->db->fetch_assoc($sql_result))
4203 return $sql_arr['minidx'];
4210 * @param string $key Cache key
4211 * @param int $id Message (sequence) ID
4212 * @return int Message UID
4215 private function get_cache_id2uid($key, $id)
4217 if (!$this->caching_enabled)
4220 if (array_key_exists('index', $this->icache)
4221 && $this->icache['index']['key'] == $key
4223 return $this->icache['index']['result'][$id];
4226 $sql_result = $this->db->query(
4228 " FROM ".get_table_name('messages').
4232 $_SESSION['user_id'], $key, $id);
4234 if ($sql_arr = $this->db->fetch_assoc($sql_result))
4235 return intval($sql_arr['uid']);
4242 * @param string $key Cache key
4243 * @param int $uid Message UID
4244 * @return int Message (sequence) ID
4247 private function get_cache_uid2id($key, $uid)
4249 if (!$this->caching_enabled)
4252 if (array_key_exists('index', $this->icache)
4253 && $this->icache['index']['key'] == $key
4255 return array_search($uid, $this->icache['index']['result']);
4258 $sql_result = $this->db->query(
4260 " FROM ".get_table_name('messages').
4264 $_SESSION['user_id'], $key, $uid);
4266 if ($sql_arr = $this->db->fetch_assoc($sql_result))
4267 return intval($sql_arr['idx']);
4273 /* --------------------------------
4274 * encoding/decoding methods
4275 * --------------------------------*/
4278 * Split an address list into a structured array list
4280 * @param string $input Input string
4281 * @param int $max List only this number of addresses
4282 * @param boolean $decode Decode address strings
4283 * @return array Indexed list of addresses
4285 function decode_address_list($input, $max=null, $decode=true)
4287 $a = $this->_parse_address_list($input, $decode);
4289 // Special chars as defined by RFC 822 need to in quoted string (or escaped).
4290 $special_chars = '[\(\)\<\>\\\.\[\]@,;:"]';
4298 foreach ($a as $val) {
4300 $address = trim($val['address']);
4301 $name = trim($val['name']);
4303 if ($name && $address && $name != $address)
4304 $string = sprintf('%s <%s>', preg_match("/$special_chars/", $name) ? '"'.addcslashes($name, '"').'"' : $name, $address);
4312 'mailto' => $address,
4316 if ($max && $j==$max)
4325 * Decode a message header value
4327 * @param string $input Header value
4328 * @param boolean $remove_quotas Remove quotes if necessary
4329 * @return string Decoded string
4331 function decode_header($input, $remove_quotes=false)
4333 $str = rcube_imap::decode_mime_string((string)$input, $this->default_charset);
4334 if ($str[0] == '"' && $remove_quotes)
4335 $str = str_replace('"', '', $str);
4342 * Decode a mime-encoded string to internal charset
4344 * @param string $input Header value
4345 * @param string $fallback Fallback charset if none specified
4347 * @return string Decoded string
4350 public static function decode_mime_string($input, $fallback=null)
4352 if (!empty($fallback)) {
4353 $default_charset = $fallback;
4356 $default_charset = rcmail::get_instance()->config->get('default_charset', 'ISO-8859-1');
4359 // rfc: all line breaks or other characters not found
4360 // in the Base64 Alphabet must be ignored by decoding software
4361 // delete all blanks between MIME-lines, differently we can
4362 // receive unnecessary blanks and broken utf-8 symbols
4363 $input = preg_replace("/\?=\s+=\?/", '?==?', $input);
4365 // encoded-word regexp
4366 $re = '/=\?([^?]+)\?([BbQq])\?([^?\n]*)\?=/';
4368 // Find all RFC2047's encoded words
4369 if (preg_match_all($re, $input, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) {
4370 // Initialize variables
4375 foreach ($matches as $idx => $m) {
4377 $charset = $m[1][0];
4378 $encoding = $m[2][0];
4380 $length = strlen($m[0][0]);
4382 // Append everything that is before the text to be decoded
4383 if ($start != $pos) {
4384 $substr = substr($input, $start, $pos-$start);
4385 $out .= rcube_charset_convert($substr, $default_charset);
4390 // Per RFC2047, each string part "MUST represent an integral number
4391 // of characters . A multi-octet character may not be split across
4392 // adjacent encoded-words." However, some mailers break this, so we
4393 // try to handle characters spanned across parts anyway by iterating
4394 // through and aggregating sequential encoded parts with the same
4395 // character set and encoding, then perform the decoding on the
4396 // aggregation as a whole.
4399 if ($next_match = $matches[$idx+1]) {
4400 if ($next_match[0][1] == $start
4401 && $next_match[1][0] == $charset
4402 && $next_match[2][0] == $encoding
4408 $count = count($tmp);
4411 // Decode and join encoded-word's chunks
4412 if ($encoding == 'B' || $encoding == 'b') {
4413 // base64 must be decoded a segment at a time
4414 for ($i=0; $i<$count; $i++)
4415 $text .= base64_decode($tmp[$i]);
4417 else { //if ($encoding == 'Q' || $encoding == 'q') {
4418 // quoted printable can be combined and processed at once
4419 for ($i=0; $i<$count; $i++)
4422 $text = str_replace('_', ' ', $text);
4423 $text = quoted_printable_decode($text);
4426 $out .= rcube_charset_convert($text, $charset);
4430 // add the last part of the input string
4431 if ($start != strlen($input)) {
4432 $out .= rcube_charset_convert(substr($input, $start), $default_charset);
4435 // return the results
4439 // no encoding information, use fallback
4440 return rcube_charset_convert($input, $default_charset);
4445 * Decode a mime part
4447 * @param string $input Input string
4448 * @param string $encoding Part encoding
4449 * @return string Decoded string
4451 function mime_decode($input, $encoding='7bit')
4453 switch (strtolower($encoding)) {
4454 case 'quoted-printable':
4455 return quoted_printable_decode($input);
4457 return base64_decode($input);
4462 return convert_uudecode($input);
4471 * Convert body charset to RCMAIL_CHARSET according to the ctype_parameters
4473 * @param string $body Part body to decode
4474 * @param string $ctype_param Charset to convert from
4475 * @return string Content converted to internal charset
4477 function charset_decode($body, $ctype_param)
4479 if (is_array($ctype_param) && !empty($ctype_param['charset']))
4480 return rcube_charset_convert($body, $ctype_param['charset']);
4482 // defaults to what is specified in the class header
4483 return rcube_charset_convert($body, $this->default_charset);
4487 /* --------------------------------
4489 * --------------------------------*/
4492 * Validate the given input and save to local properties
4494 * @param string $sort_field Sort column
4495 * @param string $sort_order Sort order
4498 private function _set_sort_order($sort_field, $sort_order)
4500 if ($sort_field != null)
4501 $this->sort_field = asciiwords($sort_field);
4502 if ($sort_order != null)
4503 $this->sort_order = strtoupper($sort_order) == 'DESC' ? 'DESC' : 'ASC';
4508 * Sort mailboxes first by default folders and then in alphabethical order
4510 * @param array $a_folders Mailboxes list
4513 private function _sort_mailbox_list($a_folders)
4515 $a_out = $a_defaults = $folders = array();
4517 $delimiter = $this->get_hierarchy_delimiter();
4519 // find default folders and skip folders starting with '.'
4520 foreach ($a_folders as $i => $folder) {
4521 if ($folder[0] == '.')
4524 if (($p = array_search($folder, $this->default_folders)) !== false && !$a_defaults[$p])
4525 $a_defaults[$p] = $folder;
4527 $folders[$folder] = rcube_charset_convert($folder, 'UTF7-IMAP');
4530 // sort folders and place defaults on the top
4531 asort($folders, SORT_LOCALE_STRING);
4533 $folders = array_merge($a_defaults, array_keys($folders));
4535 // finally we must rebuild the list to move
4536 // subfolders of default folders to their place...
4537 // ...also do this for the rest of folders because
4538 // asort() is not properly sorting case sensitive names
4539 while (list($key, $folder) = each($folders)) {
4540 // set the type of folder name variable (#1485527)
4541 $a_out[] = (string) $folder;
4542 unset($folders[$key]);
4543 $this->_rsort($folder, $delimiter, $folders, $a_out);
4553 private function _rsort($folder, $delimiter, &$list, &$out)
4555 while (list($key, $name) = each($list)) {
4556 if (strpos($name, $folder.$delimiter) === 0) {
4557 // set the type of folder name variable (#1485527)
4558 $out[] = (string) $name;
4560 $this->_rsort($name, $delimiter, $list, $out);
4568 * @param int $uid Message UID
4569 * @param string $mbox_name Mailbox name
4570 * @return int Message (sequence) ID
4573 private function _uid2id($uid, $mbox_name=NULL)
4575 if (!strlen($mbox_name))
4576 $mbox_name = $this->mailbox;
4578 if (!isset($this->uid_id_map[$mbox_name][$uid])) {
4579 if (!($id = $this->get_cache_uid2id($mbox_name.'.msg', $uid)))
4580 $id = $this->conn->UID2ID($mbox_name, $uid);
4582 $this->uid_id_map[$mbox_name][$uid] = $id;
4585 return $this->uid_id_map[$mbox_name][$uid];
4590 * @param int $id Message (sequence) ID
4591 * @param string $mbox_name Mailbox name
4592 * @return int Message UID
4595 private function _id2uid($id, $mbox_name=NULL)
4597 if (!strlen($mbox_name))
4598 $mbox_name = $this->mailbox;
4600 if ($uid = array_search($id, (array)$this->uid_id_map[$mbox_name]))
4603 if (!($uid = $this->get_cache_id2uid($mbox_name.'.msg', $id)))
4604 $uid = $this->conn->ID2UID($mbox_name, $id);
4606 $this->uid_id_map[$mbox_name][$uid] = $id;
4613 * Subscribe/unsubscribe a list of mailboxes and update local cache
4616 private function _change_subscription($a_mboxes, $mode)
4620 if (is_array($a_mboxes))
4621 foreach ($a_mboxes as $i => $mbox_name) {
4622 $mailbox = $this->mod_mailbox($mbox_name);
4623 $a_mboxes[$i] = $mailbox;
4625 if ($mode=='subscribe')
4626 $updated = $this->conn->subscribe($mailbox);
4627 else if ($mode=='unsubscribe')
4628 $updated = $this->conn->unsubscribe($mailbox);
4631 // get cached mailbox list
4633 $a_mailbox_cache = $this->get_cache('mailboxes');
4634 if (!is_array($a_mailbox_cache))
4637 // modify cached list
4638 if ($mode=='subscribe')
4639 $a_mailbox_cache = array_merge($a_mailbox_cache, $a_mboxes);
4640 else if ($mode=='unsubscribe')
4641 $a_mailbox_cache = array_diff($a_mailbox_cache, $a_mboxes);
4643 // write mailboxlist to cache
4644 $this->update_cache('mailboxes', $this->_sort_mailbox_list($a_mailbox_cache));
4652 * Increde/decrese messagecount for a specific mailbox
4655 private function _set_messagecount($mbox_name, $mode, $increment)
4657 $a_mailbox_cache = false;
4658 $mailbox = strlen($mbox_name) ? $mbox_name : $this->mailbox;
4659 $mode = strtoupper($mode);
4661 $a_mailbox_cache = $this->get_cache('messagecount');
4663 if (!is_array($a_mailbox_cache[$mailbox]) || !isset($a_mailbox_cache[$mailbox][$mode]) || !is_numeric($increment))
4666 // add incremental value to messagecount
4667 $a_mailbox_cache[$mailbox][$mode] += $increment;
4669 // there's something wrong, delete from cache
4670 if ($a_mailbox_cache[$mailbox][$mode] < 0)
4671 unset($a_mailbox_cache[$mailbox][$mode]);
4673 // write back to cache
4674 $this->update_cache('messagecount', $a_mailbox_cache);
4681 * Remove messagecount of a specific mailbox from cache
4684 private function _clear_messagecount($mbox_name='', $mode=null)
4686 $mailbox = strlen($mbox_name) ? $mbox_name : $this->mailbox;
4688 $a_mailbox_cache = $this->get_cache('messagecount');
4690 if (is_array($a_mailbox_cache[$mailbox])) {
4692 unset($a_mailbox_cache[$mailbox][$mode]);
4695 unset($a_mailbox_cache[$mailbox]);
4697 $this->update_cache('messagecount', $a_mailbox_cache);
4703 * Split RFC822 header string into an associative array
4706 private function _parse_headers($headers)
4708 $a_headers = array();
4709 $headers = preg_replace('/\r?\n(\t| )+/', ' ', $headers);
4710 $lines = explode("\n", $headers);
4713 for ($i=0; $i<$c; $i++) {
4714 if ($p = strpos($lines[$i], ': ')) {
4715 $field = strtolower(substr($lines[$i], 0, $p));
4716 $value = trim(substr($lines[$i], $p+1));
4718 $a_headers[$field] = $value;
4729 private function _parse_address_list($str, $decode=true)
4731 // remove any newlines and carriage returns before
4732 $str = preg_replace('/\r?\n(\s|\t)?/', ' ', $str);
4734 // extract list items, remove comments
4735 $str = self::explode_header_string(',;', $str, true);
4738 foreach ($str as $key => $val) {
4743 if (preg_match('/(.*)<(\S+@\S+)>$/', $val, $m)) {
4745 $name = trim($m[1]);
4747 else if (preg_match('/^(\S+@\S+)$/', $val, $m)) {
4755 // dequote and/or decode name
4757 if ($name[0] == '"') {
4758 $name = substr($name, 1, -1);
4759 $name = stripslashes($name);
4762 $name = $this->decode_header($name);
4766 if (!$address && $name) {
4771 $result[$key] = array('name' => $name, 'address' => $address);
4780 * Explodes header (e.g. address-list) string into array of strings
4781 * using specified separator characters with proper handling
4782 * of quoted-strings and comments (RFC2822)
4784 * @param string $separator String containing separator characters
4785 * @param string $str Header string
4786 * @param bool $remove_comments Enable to remove comments
4788 * @return array Header items
4790 static function explode_header_string($separator, $str, $remove_comments=false)
4792 $length = strlen($str);
4798 for ($i=0; $i<$length; $i++) {
4799 // we're inside a quoted string
4801 if ($str[$i] == '"') {
4804 else if ($str[$i] == '\\') {
4805 if ($comment <= 0) {
4811 // we're inside a comment string
4812 else if ($comment > 0) {
4813 if ($str[$i] == ')') {
4816 else if ($str[$i] == '(') {
4819 else if ($str[$i] == '\\') {
4824 // separator, add to result array
4825 else if (strpos($separator, $str[$i]) !== false) {
4832 // start of quoted string
4833 else if ($str[$i] == '"') {
4837 else if ($remove_comments && $str[$i] == '(') {
4841 if ($comment <= 0) {
4846 if ($out && $comment <= 0) {
4855 * This is our own debug handler for the IMAP connection
4858 public function debug_handler(&$imap, $message)
4860 write_log('imap', $message);
4863 } // end class rcube_imap
4867 * Class representing a message part
4871 class rcube_message_part
4874 var $ctype_primary = 'text';
4875 var $ctype_secondary = 'plain';
4876 var $mimetype = 'text/plain';
4877 var $disposition = '';
4879 var $encoding = '8bit';
4882 var $headers = array();
4883 var $d_parameters = array();
4884 var $ctype_parameters = array();
4888 if (isset($this->parts))
4889 foreach ($this->parts as $idx => $part)
4890 if (is_object($part))
4891 $this->parts[$idx] = clone $part;
4897 * Class for sorting an array of rcube_mail_header objects in a predetermined order.
4900 * @author Eric Stadtherr
4902 class rcube_header_sorter
4904 var $sequence_numbers = array();
4907 * Set the predetermined sort order.
4909 * @param array $seqnums Numerically indexed array of IMAP message sequence numbers
4911 function set_sequence_numbers($seqnums)
4913 $this->sequence_numbers = array_flip($seqnums);
4917 * Sort the array of header objects
4919 * @param array $headers Array of rcube_mail_header objects indexed by UID
4921 function sort_headers(&$headers)
4924 * uksort would work if the keys were the sequence number, but unfortunately
4925 * the keys are the UIDs. We'll use uasort instead and dereference the value
4926 * to get the sequence number (in the "id" field).
4928 * uksort($headers, array($this, "compare_seqnums"));
4930 uasort($headers, array($this, "compare_seqnums"));
4934 * Sort method called by uasort()
4936 * @param rcube_mail_header $a
4937 * @param rcube_mail_header $b
4939 function compare_seqnums($a, $b)
4941 // First get the sequence number from the header object (the 'id' field).
4945 // then find each sequence number in my ordered list
4946 $posa = isset($this->sequence_numbers[$seqa]) ? intval($this->sequence_numbers[$seqa]) : -1;
4947 $posb = isset($this->sequence_numbers[$seqb]) ? intval($this->sequence_numbers[$seqb]) : -1;
4949 // return the relative position as the comparison value
4950 return $posa - $posb;