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 4389 2011-01-04 11:16:54Z 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'));
156 $data = rcmail::get_instance()->plugins->exec_hook('imap_connect',
157 array('host' => $host, 'user' => $user, 'attempt' => ++$attempt));
159 if (!empty($data['pass']))
160 $pass = $data['pass'];
162 $this->conn->connect($data['host'], $data['user'], $pass, $this->options);
163 } while(!$this->conn->connected() && $data['retry']);
165 $this->host = $data['host'];
166 $this->user = $data['user'];
169 $this->ssl = $use_ssl;
171 if ($this->conn->connected()) {
172 // get namespace and delimiter
177 else if ($this->conn->error) {
178 if ($pass && $user) {
179 $message = sprintf("Login failed for %s from %s. %s",
180 $user, rcmail_remote_ip(), $this->conn->error);
182 raise_error(array('code' => 403, 'type' => 'imap',
183 'file' => __FILE__, 'line' => __LINE__,
184 'message' => $message), true, false);
193 * Close IMAP connection
194 * Usually done on script shutdown
200 $this->conn->closeConnection();
201 $this->write_cache();
206 * Close IMAP connection and re-connect
207 * This is used to avoid some strange socket errors when talking to Courier IMAP
213 $this->conn->closeConnection();
214 $connected = $this->connect($this->host, $this->user, $this->pass, $this->port, $this->ssl);
216 // issue SELECT command to restore connection status
217 if ($connected && strlen($this->mailbox))
218 $this->conn->select($this->mailbox);
223 * Returns code of last error
225 * @return int Error code
227 function get_error_code()
229 return $this->conn->errornum;
234 * Returns message of last error
236 * @return string Error message
238 function get_error_str()
240 return $this->conn->error;
245 * Returns code of last command response
247 * @return int Response code
249 function get_response_code()
251 switch ($this->conn->resultcode) {
255 return self::READONLY;
257 return self::TRYCREATE;
261 return self::OVERQUOTA;
262 case 'ALREADYEXISTS':
263 return self::ALREADYEXISTS;
265 return self::NONEXISTENT;
267 return self::CONTACTADMIN;
269 return self::UNKNOWN;
275 * Returns last command response
277 * @return string Response
279 function get_response_str()
281 return $this->conn->result;
286 * Set options to be used in rcube_imap_generic::connect()
288 * @param array $opt Options array
290 function set_options($opt)
292 $this->options = array_merge($this->options, (array)$opt);
297 * Set default message charset
299 * This will be used for message decoding if a charset specification is not available
301 * @param string $cs Charset string
304 function set_charset($cs)
306 $this->default_charset = $cs;
311 * This list of folders will be listed above all other folders
313 * @param array $arr Indexed list of folder names
316 function set_default_mailboxes($arr)
318 if (is_array($arr)) {
319 $this->default_folders = $arr;
321 // add inbox if not included
322 if (!in_array('INBOX', $this->default_folders))
323 array_unshift($this->default_folders, 'INBOX');
329 * Set internal mailbox reference.
331 * All operations will be perfomed on this mailbox/folder
333 * @param string $new_mbox Mailbox/Folder name
336 function set_mailbox($new_mbox)
338 $mailbox = $this->mod_mailbox($new_mbox);
340 if ($this->mailbox == $mailbox)
343 $this->mailbox = $mailbox;
345 // clear messagecount cache for this mailbox
346 $this->_clear_messagecount($mailbox);
351 * Forces selection of a mailbox
353 * @param string $mailbox Mailbox/Folder name
356 function select_mailbox($mailbox=null)
358 $mailbox = strlen($mailbox) ? $this->mod_mailbox($mailbox) : $this->mailbox;
360 $selected = $this->conn->select($mailbox);
362 if ($selected && $this->mailbox != $mailbox) {
363 // clear messagecount cache for this mailbox
364 $this->_clear_messagecount($mailbox);
365 $this->mailbox = $mailbox;
371 * Set internal list page
373 * @param number $page Page number to list
376 function set_page($page)
378 $this->list_page = (int)$page;
383 * Set internal page size
385 * @param number $size Number of messages to display on one page
388 function set_pagesize($size)
390 $this->page_size = (int)$size;
395 * Save a set of message ids for future message listing methods
397 * @param string IMAP Search query
398 * @param array List of message ids or NULL if empty
399 * @param string Charset of search string
400 * @param string Sorting field
401 * @param string True if set is sorted (SORT was used for searching)
403 function set_search_set($str=null, $msgs=null, $charset=null, $sort_field=null, $threads=false, $sorted=false)
405 if (is_array($str) && $msgs == null)
406 list($str, $msgs, $charset, $sort_field, $threads) = $str;
409 else if ($msgs != null && !is_array($msgs))
410 $msgs = explode(',', $msgs);
412 $this->search_string = $str;
413 $this->search_set = $msgs;
414 $this->search_charset = $charset;
415 $this->search_sort_field = $sort_field;
416 $this->search_threads = $threads;
417 $this->search_sorted = $sorted;
422 * Return the saved search set as hash array
423 * @return array Search set
425 function get_search_set()
427 return array($this->search_string,
429 $this->search_charset,
430 $this->search_sort_field,
431 $this->search_threads,
432 $this->search_sorted,
438 * Returns the currently used mailbox name
440 * @return string Name of the mailbox/folder
443 function get_mailbox_name()
445 return $this->conn->connected() ? $this->mod_mailbox($this->mailbox, 'out') : '';
450 * Returns the IMAP server's capability
452 * @param string $cap Capability name
453 * @return mixed Capability value or TRUE if supported, FALSE if not
456 function get_capability($cap)
458 return $this->conn->getCapability(strtoupper($cap));
463 * Sets threading flag to the best supported THREAD algorithm
465 * @param boolean $enable TRUE to enable and FALSE
466 * @return string Algorithm or false if THREAD is not supported
469 function set_threading($enable=false)
471 $this->threading = false;
473 if ($enable && ($caps = $this->get_capability('THREAD'))) {
474 if (in_array('REFS', $caps))
475 $this->threading = 'REFS';
476 else if (in_array('REFERENCES', $caps))
477 $this->threading = 'REFERENCES';
478 else if (in_array('ORDEREDSUBJECT', $caps))
479 $this->threading = 'ORDEREDSUBJECT';
482 return $this->threading;
487 * Checks the PERMANENTFLAGS capability of the current mailbox
488 * and returns true if the given flag is supported by the IMAP server
490 * @param string $flag Permanentflag name
491 * @return boolean True if this flag is supported
494 function check_permflag($flag)
496 $flag = strtoupper($flag);
497 $imap_flag = $this->conn->flags[$flag];
498 return (in_array_nocase($imap_flag, $this->conn->data['PERMANENTFLAGS']));
503 * Returns the delimiter that is used by the IMAP server for folder separation
505 * @return string Delimiter string
508 function get_hierarchy_delimiter()
510 return $this->delimiter;
517 * @return array Namespace data
520 function get_namespace()
522 return $this->namespace;
527 * Sets delimiter and namespaces
531 private function set_env()
533 if ($this->delimiter !== null && $this->namespace !== null) {
537 if (isset($_SESSION['imap_namespace']) && isset($_SESSION['imap_delimiter'])) {
538 $this->namespace = $_SESSION['imap_namespace'];
539 $this->delimiter = $_SESSION['imap_delimiter'];
543 $config = rcmail::get_instance()->config;
544 $imap_personal = $config->get('imap_ns_personal');
545 $imap_other = $config->get('imap_ns_other');
546 $imap_shared = $config->get('imap_ns_shared');
547 $imap_delimiter = $config->get('imap_delimiter');
549 if (!$this->conn->connected())
552 $ns = $this->conn->getNamespace();
554 // Set namespaces (NAMESPACE supported)
556 $this->namespace = $ns;
559 $this->namespace = array(
566 if ($imap_delimiter) {
567 $this->delimiter = $imap_delimiter;
569 if (empty($this->delimiter)) {
570 $this->delimiter = $this->namespace['personal'][0][1];
572 if (empty($this->delimiter)) {
573 $this->delimiter = $this->conn->getHierarchyDelimiter();
575 if (empty($this->delimiter)) {
576 $this->delimiter = '/';
579 // Overwrite namespaces
580 if ($imap_personal !== null) {
581 $this->namespace['personal'] = NULL;
582 foreach ((array)$imap_personal as $dir) {
583 $this->namespace['personal'][] = array($dir, $this->delimiter);
586 if ($imap_other !== null) {
587 $this->namespace['other'] = NULL;
588 foreach ((array)$imap_other as $dir) {
590 $this->namespace['other'][] = array($dir, $this->delimiter);
594 if ($imap_shared !== null) {
595 $this->namespace['shared'] = NULL;
596 foreach ((array)$imap_shared as $dir) {
598 $this->namespace['shared'][] = array($dir, $this->delimiter);
603 $_SESSION['imap_namespace'] = $this->namespace;
604 $_SESSION['imap_delimiter'] = $this->delimiter;
609 * Get message count for a specific mailbox
611 * @param string $mbox_name Mailbox/folder name
612 * @param string $mode Mode for count [ALL|THREADS|UNSEEN|RECENT]
613 * @param boolean $force Force reading from server and update cache
614 * @param boolean $status Enables storing folder status info (max UID/count),
615 * required for mailbox_status()
616 * @return int Number of messages
619 function messagecount($mbox_name='', $mode='ALL', $force=false, $status=true)
621 $mailbox = strlen($mbox_name) ? $this->mod_mailbox($mbox_name) : $this->mailbox;
622 return $this->_messagecount($mailbox, $mode, $force, $status);
627 * Private method for getting nr of messages
629 * @param string $mailbox Mailbox name
630 * @param string $mode Mode for count [ALL|THREADS|UNSEEN|RECENT]
631 * @param boolean $force Force reading from server and update cache
632 * @param boolean $status Enables storing folder status info (max UID/count),
633 * required for mailbox_status()
634 * @return int Number of messages
636 * @see rcube_imap::messagecount()
638 private function _messagecount($mailbox='', $mode='ALL', $force=false, $status=true)
640 $mode = strtoupper($mode);
642 if (!strlen($mailbox))
643 $mailbox = $this->mailbox;
646 if ($this->search_string && $mailbox == $this->mailbox && ($mode == 'ALL' || $mode == 'THREADS') && !$force) {
647 if ($this->search_threads)
648 return $mode == 'ALL' ? count((array)$this->search_set['depth']) : count((array)$this->search_set['tree']);
650 return count((array)$this->search_set);
653 $a_mailbox_cache = $this->get_cache('messagecount');
655 // return cached value
656 if (!$force && is_array($a_mailbox_cache[$mailbox]) && isset($a_mailbox_cache[$mailbox][$mode]))
657 return $a_mailbox_cache[$mailbox][$mode];
659 if (!is_array($a_mailbox_cache[$mailbox]))
660 $a_mailbox_cache[$mailbox] = array();
662 if ($mode == 'THREADS') {
663 $res = $this->_threadcount($mailbox, $msg_count);
664 $count = $res['count'];
667 $this->set_folder_stats($mailbox, 'cnt', $res['msgcount']);
668 $this->set_folder_stats($mailbox, 'maxuid', $res['maxuid'] ? $this->_id2uid($res['maxuid'], $mailbox) : 0);
671 // RECENT count is fetched a bit different
672 else if ($mode == 'RECENT') {
673 $count = $this->conn->countRecent($mailbox);
675 // use SEARCH for message counting
676 else if ($this->skip_deleted) {
677 $search_str = "ALL UNDELETED";
678 $keys = array('COUNT');
681 if ($mode == 'UNSEEN') {
682 $search_str .= " UNSEEN";
685 if ($this->caching_enabled) {
694 // get message count using (E)SEARCH
695 // not very performant but more precise (using UNDELETED)
696 $index = $this->conn->search($mailbox, $search_str, $need_uid, $keys);
698 $count = is_array($index) ? $index['COUNT'] : 0;
700 if ($mode == 'ALL') {
701 if ($need_uid && $this->caching_enabled) {
702 // Save messages index for check_cache_status()
703 $this->icache['all_undeleted_idx'] = $index['ALL'];
706 $this->set_folder_stats($mailbox, 'cnt', $count);
707 $this->set_folder_stats($mailbox, 'maxuid', is_array($index) ? $index['MAX'] : 0);
712 if ($mode == 'UNSEEN')
713 $count = $this->conn->countUnseen($mailbox);
715 $count = $this->conn->countMessages($mailbox);
717 $this->set_folder_stats($mailbox,'cnt', $count);
718 $this->set_folder_stats($mailbox, 'maxuid', $count ? $this->_id2uid($count, $mailbox) : 0);
723 $a_mailbox_cache[$mailbox][$mode] = (int)$count;
725 // write back to cache
726 $this->update_cache('messagecount', $a_mailbox_cache);
733 * Private method for getting nr of threads
735 * @param string $mailbox Folder name
737 * @returns array Array containing items: 'count' - threads count,
738 * 'msgcount' = messages count, 'maxuid' = max. UID in the set
741 private function _threadcount($mailbox)
745 if (!empty($this->icache['threads'])) {
746 $dcount = count($this->icache['threads']['depth']);
748 'count' => count($this->icache['threads']['tree']),
749 'msgcount' => $dcount,
750 'maxuid' => $dcount ? max(array_keys($this->icache['threads']['depth'])) : 0,
753 else if (is_array($result = $this->_fetch_threads($mailbox))) {
754 $dcount = count($result[1]);
756 'count' => count($result[0]),
757 'msgcount' => $dcount,
758 'maxuid' => $dcount ? max(array_keys($result[1])) : 0,
767 * Public method for listing headers
768 * convert mailbox name with root dir first
770 * @param string $mbox_name Mailbox/folder name
771 * @param int $page Current page to list
772 * @param string $sort_field Header field to sort by
773 * @param string $sort_order Sort order [ASC|DESC]
774 * @param int $slice Number of slice items to extract from result array
775 * @return array Indexed array with message header objects
778 function list_headers($mbox_name='', $page=NULL, $sort_field=NULL, $sort_order=NULL, $slice=0)
780 $mailbox = strlen($mbox_name) ? $this->mod_mailbox($mbox_name) : $this->mailbox;
781 return $this->_list_headers($mailbox, $page, $sort_field, $sort_order, false, $slice);
786 * Private method for listing message headers
788 * @param string $mailbox Mailbox name
789 * @param int $page Current page to list
790 * @param string $sort_field Header field to sort by
791 * @param string $sort_order Sort order [ASC|DESC]
792 * @param int $slice Number of slice items to extract from result array
793 * @return array Indexed array with message header objects
795 * @see rcube_imap::list_headers
797 private function _list_headers($mailbox='', $page=NULL, $sort_field=NULL, $sort_order=NULL, $recursive=false, $slice=0)
799 if (!strlen($mailbox))
802 // use saved message set
803 if ($this->search_string && $mailbox == $this->mailbox)
804 return $this->_list_header_set($mailbox, $page, $sort_field, $sort_order, $slice);
806 if ($this->threading)
807 return $this->_list_thread_headers($mailbox, $page, $sort_field, $sort_order, $recursive, $slice);
809 $this->_set_sort_order($sort_field, $sort_order);
811 $page = $page ? $page : $this->list_page;
812 $cache_key = $mailbox.'.msg';
814 if ($this->caching_enabled) {
815 // cache is OK, we can get messages from local cache
816 // (assume cache is in sync when in recursive mode)
817 if ($recursive || $this->check_cache_status($mailbox, $cache_key)>0) {
818 $start_msg = ($page-1) * $this->page_size;
819 $a_msg_headers = $this->get_message_cache($cache_key, $start_msg,
820 $start_msg+$this->page_size, $this->sort_field, $this->sort_order);
821 $result = array_values($a_msg_headers);
823 $result = array_slice($result, -$slice, $slice);
826 // cache is incomplete, sync it (all messages in the folder)
827 else if (!$recursive) {
828 $this->sync_header_index($mailbox);
829 return $this->_list_headers($mailbox, $page, $this->sort_field, $this->sort_order, true, $slice);
833 // retrieve headers from IMAP
834 $a_msg_headers = array();
836 // use message index sort as default sorting (for better performance)
837 if (!$this->sort_field) {
838 if ($this->skip_deleted) {
839 // @TODO: this could be cached
840 if ($msg_index = $this->_search_index($mailbox, 'ALL UNDELETED')) {
841 $max = max($msg_index);
842 list($begin, $end) = $this->_get_message_range(count($msg_index), $page);
843 $msg_index = array_slice($msg_index, $begin, $end-$begin);
846 else if ($max = $this->conn->countMessages($mailbox)) {
847 list($begin, $end) = $this->_get_message_range($max, $page);
848 $msg_index = range($begin+1, $end);
851 $msg_index = array();
853 if ($slice && $msg_index)
854 $msg_index = array_slice($msg_index, ($this->sort_order == 'DESC' ? 0 : -$slice), $slice);
856 // fetch reqested headers from server
858 $this->_fetch_headers($mailbox, join(",", $msg_index), $a_msg_headers, $cache_key);
861 else if ($this->get_capability('SORT') &&
862 // Courier-IMAP provides SORT capability but allows to disable it by admin (#1486959)
863 ($msg_index = $this->conn->sort($mailbox, $this->sort_field, $this->skip_deleted ? 'UNDELETED' : '')) !== false
865 if (!empty($msg_index)) {
866 list($begin, $end) = $this->_get_message_range(count($msg_index), $page);
867 $max = max($msg_index);
868 $msg_index = array_slice($msg_index, $begin, $end-$begin);
871 $msg_index = array_slice($msg_index, ($this->sort_order == 'DESC' ? 0 : -$slice), $slice);
873 // fetch reqested headers from server
874 $this->_fetch_headers($mailbox, join(',', $msg_index), $a_msg_headers, $cache_key);
877 // fetch specified header for all messages and sort
878 else if ($a_index = $this->conn->fetchHeaderIndex($mailbox, "1:*", $this->sort_field, $this->skip_deleted)) {
879 asort($a_index); // ASC
880 $msg_index = array_keys($a_index);
881 $max = max($msg_index);
882 list($begin, $end) = $this->_get_message_range(count($msg_index), $page);
883 $msg_index = array_slice($msg_index, $begin, $end-$begin);
886 $msg_index = array_slice($msg_index, ($this->sort_order == 'DESC' ? 0 : -$slice), $slice);
888 // fetch reqested headers from server
889 $this->_fetch_headers($mailbox, join(",", $msg_index), $a_msg_headers, $cache_key);
892 // delete cached messages with a higher index than $max+1
893 // Changed $max to $max+1 to fix this bug : #1484295
894 $this->clear_message_cache($cache_key, $max + 1);
896 // kick child process to sync cache
899 // return empty array if no messages found
900 if (!is_array($a_msg_headers) || empty($a_msg_headers))
903 // use this class for message sorting
904 $sorter = new rcube_header_sorter();
905 $sorter->set_sequence_numbers($msg_index);
906 $sorter->sort_headers($a_msg_headers);
908 if ($this->sort_order == 'DESC')
909 $a_msg_headers = array_reverse($a_msg_headers);
911 return array_values($a_msg_headers);
916 * Private method for listing message headers using threads
918 * @param string $mailbox Mailbox/folder name
919 * @param int $page Current page to list
920 * @param string $sort_field Header field to sort by
921 * @param string $sort_order Sort order [ASC|DESC]
922 * @param boolean $recursive True if called recursively
923 * @param int $slice Number of slice items to extract from result array
924 * @return array Indexed array with message header objects
926 * @see rcube_imap::list_headers
928 private function _list_thread_headers($mailbox, $page=NULL, $sort_field=NULL, $sort_order=NULL, $recursive=false, $slice=0)
930 $this->_set_sort_order($sort_field, $sort_order);
932 $page = $page ? $page : $this->list_page;
933 // $cache_key = $mailbox.'.msg';
934 // $cache_status = $this->check_cache_status($mailbox, $cache_key);
936 // get all threads (default sort order)
937 list ($thread_tree, $msg_depth, $has_children) = $this->_fetch_threads($mailbox);
939 if (empty($thread_tree))
942 $msg_index = $this->_sort_threads($mailbox, $thread_tree);
944 return $this->_fetch_thread_headers($mailbox,
945 $thread_tree, $msg_depth, $has_children, $msg_index, $page, $slice);
950 * Private method for fetching threads data
952 * @param string $mailbox Mailbox/folder name
953 * @return array Array with thread data
956 private function _fetch_threads($mailbox)
958 if (empty($this->icache['threads'])) {
960 $result = $this->conn->thread($mailbox, $this->threading,
961 $this->skip_deleted ? 'UNDELETED' : '');
963 // add to internal (fast) cache
964 $this->icache['threads'] = array();
965 $this->icache['threads']['tree'] = is_array($result) ? $result[0] : array();
966 $this->icache['threads']['depth'] = is_array($result) ? $result[1] : array();
967 $this->icache['threads']['has_children'] = is_array($result) ? $result[2] : array();
971 $this->icache['threads']['tree'],
972 $this->icache['threads']['depth'],
973 $this->icache['threads']['has_children'],
979 * Private method for fetching threaded messages headers
981 * @param string $mailbox Mailbox name
982 * @param array $thread_tree Thread tree data
983 * @param array $msg_depth Thread depth data
984 * @param array $has_children Thread children data
985 * @param array $msg_index Messages index
986 * @param int $page List page number
987 * @param int $slice Number of threads to slice
988 * @return array Messages headers
991 private function _fetch_thread_headers($mailbox, $thread_tree, $msg_depth, $has_children, $msg_index, $page, $slice=0)
993 $cache_key = $mailbox.'.msg';
994 // now get IDs for current page
995 list($begin, $end) = $this->_get_message_range(count($msg_index), $page);
996 $msg_index = array_slice($msg_index, $begin, $end-$begin);
999 $msg_index = array_slice($msg_index, ($this->sort_order == 'DESC' ? 0 : -$slice), $slice);
1001 if ($this->sort_order == 'DESC')
1002 $msg_index = array_reverse($msg_index);
1004 // flatten threads array
1005 // @TODO: fetch children only in expanded mode (?)
1007 foreach ($msg_index as $root) {
1009 if (!empty($thread_tree[$root]))
1010 $all_ids = array_merge($all_ids, array_keys_recursive($thread_tree[$root]));
1013 // fetch reqested headers from server
1014 $this->_fetch_headers($mailbox, $all_ids, $a_msg_headers, $cache_key);
1016 // return empty array if no messages found
1017 if (!is_array($a_msg_headers) || empty($a_msg_headers))
1020 // use this class for message sorting
1021 $sorter = new rcube_header_sorter();
1022 $sorter->set_sequence_numbers($all_ids);
1023 $sorter->sort_headers($a_msg_headers);
1025 // Set depth, has_children and unread_children fields in headers
1026 $this->_set_thread_flags($a_msg_headers, $msg_depth, $has_children);
1028 return array_values($a_msg_headers);
1033 * Private method for setting threaded messages flags:
1034 * depth, has_children and unread_children
1036 * @param array $headers Reference to headers array indexed by message ID
1037 * @param array $msg_depth Array of messages depth indexed by message ID
1038 * @param array $msg_children Array of messages children flags indexed by message ID
1039 * @return array Message headers array indexed by message ID
1042 private function _set_thread_flags(&$headers, $msg_depth, $msg_children)
1046 foreach ($headers as $idx => $header) {
1048 $depth = $msg_depth[$id];
1049 $parents = array_slice($parents, 0, $depth);
1051 if (!empty($parents)) {
1052 $headers[$idx]->parent_uid = end($parents);
1054 $headers[$parents[0]]->unread_children++;
1056 array_push($parents, $header->uid);
1058 $headers[$idx]->depth = $depth;
1059 $headers[$idx]->has_children = $msg_children[$id];
1065 * Private method for listing a set of message headers (search results)
1067 * @param string $mailbox Mailbox/folder name
1068 * @param int $page Current page to list
1069 * @param string $sort_field Header field to sort by
1070 * @param string $sort_order Sort order [ASC|DESC]
1071 * @param int $slice Number of slice items to extract from result array
1072 * @return array Indexed array with message header objects
1074 * @see rcube_imap::list_header_set()
1076 private function _list_header_set($mailbox, $page=NULL, $sort_field=NULL, $sort_order=NULL, $slice=0)
1078 if (!strlen($mailbox) || empty($this->search_set))
1081 // use saved messages from searching
1082 if ($this->threading)
1083 return $this->_list_thread_header_set($mailbox, $page, $sort_field, $sort_order, $slice);
1085 // search set is threaded, we need a new one
1086 if ($this->search_threads) {
1087 if (empty($this->search_set['tree']))
1089 $this->search('', $this->search_string, $this->search_charset, $sort_field);
1092 $msgs = $this->search_set;
1093 $a_msg_headers = array();
1094 $page = $page ? $page : $this->list_page;
1095 $start_msg = ($page-1) * $this->page_size;
1097 $this->_set_sort_order($sort_field, $sort_order);
1099 // quickest method (default sorting)
1100 if (!$this->search_sort_field && !$this->sort_field) {
1101 if ($sort_order == 'DESC')
1102 $msgs = array_reverse($msgs);
1104 // get messages uids for one page
1105 $msgs = array_slice(array_values($msgs), $start_msg, min(count($msgs)-$start_msg, $this->page_size));
1108 $msgs = array_slice($msgs, -$slice, $slice);
1111 $this->_fetch_headers($mailbox, join(',',$msgs), $a_msg_headers, NULL);
1113 // I didn't found in RFC that FETCH always returns messages sorted by index
1114 $sorter = new rcube_header_sorter();
1115 $sorter->set_sequence_numbers($msgs);
1116 $sorter->sort_headers($a_msg_headers);
1118 return array_values($a_msg_headers);
1121 // sorted messages, so we can first slice array and then fetch only wanted headers
1122 if ($this->search_sorted) { // SORT searching result
1123 // reset search set if sorting field has been changed
1124 if ($this->sort_field && $this->search_sort_field != $this->sort_field)
1125 $msgs = $this->search('', $this->search_string, $this->search_charset, $this->sort_field);
1127 // return empty array if no messages found
1131 if ($sort_order == 'DESC')
1132 $msgs = array_reverse($msgs);
1134 // get messages uids for one page
1135 $msgs = array_slice(array_values($msgs), $start_msg, min(count($msgs)-$start_msg, $this->page_size));
1138 $msgs = array_slice($msgs, -$slice, $slice);
1141 $this->_fetch_headers($mailbox, join(',',$msgs), $a_msg_headers, NULL);
1143 $sorter = new rcube_header_sorter();
1144 $sorter->set_sequence_numbers($msgs);
1145 $sorter->sort_headers($a_msg_headers);
1147 return array_values($a_msg_headers);
1149 else { // SEARCH result, need sorting
1150 $cnt = count($msgs);
1151 // 300: experimantal value for best result
1152 if (($cnt > 300 && $cnt > $this->page_size) || !$this->sort_field) {
1153 // use memory less expensive (and quick) method for big result set
1154 $a_index = $this->message_index('', $this->sort_field, $this->sort_order);
1155 // get messages uids for one page...
1156 $msgs = array_slice($a_index, $start_msg, min($cnt-$start_msg, $this->page_size));
1158 $msgs = array_slice($msgs, -$slice, $slice);
1159 // ...and fetch headers
1160 $this->_fetch_headers($mailbox, join(',', $msgs), $a_msg_headers, NULL);
1162 // return empty array if no messages found
1163 if (!is_array($a_msg_headers) || empty($a_msg_headers))
1166 $sorter = new rcube_header_sorter();
1167 $sorter->set_sequence_numbers($msgs);
1168 $sorter->sort_headers($a_msg_headers);
1170 return array_values($a_msg_headers);
1173 // for small result set we can fetch all messages headers
1174 $this->_fetch_headers($mailbox, join(',', $msgs), $a_msg_headers, NULL);
1176 // return empty array if no messages found
1177 if (!is_array($a_msg_headers) || empty($a_msg_headers))
1180 // if not already sorted
1181 $a_msg_headers = $this->conn->sortHeaders(
1182 $a_msg_headers, $this->sort_field, $this->sort_order);
1184 // only return the requested part of the set
1185 $a_msg_headers = array_slice(array_values($a_msg_headers),
1186 $start_msg, min($cnt-$start_msg, $this->page_size));
1189 $a_msg_headers = array_slice($a_msg_headers, -$slice, $slice);
1191 return $a_msg_headers;
1198 * Private method for listing a set of threaded message headers (search results)
1200 * @param string $mailbox Mailbox/folder name
1201 * @param int $page Current page to list
1202 * @param string $sort_field Header field to sort by
1203 * @param string $sort_order Sort order [ASC|DESC]
1204 * @param int $slice Number of slice items to extract from result array
1205 * @return array Indexed array with message header objects
1207 * @see rcube_imap::list_header_set()
1209 private function _list_thread_header_set($mailbox, $page=NULL, $sort_field=NULL, $sort_order=NULL, $slice=0)
1211 // update search_set if previous data was fetched with disabled threading
1212 if (!$this->search_threads) {
1213 if (empty($this->search_set))
1215 $this->search('', $this->search_string, $this->search_charset, $sort_field);
1219 if (empty($this->search_set['tree']))
1222 $thread_tree = $this->search_set['tree'];
1223 $msg_depth = $this->search_set['depth'];
1224 $has_children = $this->search_set['children'];
1225 $a_msg_headers = array();
1227 $page = $page ? $page : $this->list_page;
1228 $start_msg = ($page-1) * $this->page_size;
1230 $this->_set_sort_order($sort_field, $sort_order);
1232 $msg_index = $this->_sort_threads($mailbox, $thread_tree, array_keys($msg_depth));
1234 return $this->_fetch_thread_headers($mailbox,
1235 $thread_tree, $msg_depth, $has_children, $msg_index, $page, $slice=0);
1240 * Helper function to get first and last index of the requested set
1242 * @param int $max Messages count
1243 * @param mixed $page Page number to show, or string 'all'
1244 * @return array Array with two values: first index, last index
1247 private function _get_message_range($max, $page)
1249 $start_msg = ($page-1) * $this->page_size;
1255 else if ($this->sort_order=='DESC') {
1256 $begin = $max - $this->page_size - $start_msg;
1257 $end = $max - $start_msg;
1260 $begin = $start_msg;
1261 $end = $start_msg + $this->page_size;
1264 if ($begin < 0) $begin = 0;
1265 if ($end < 0) $end = $max;
1266 if ($end > $max) $end = $max;
1268 return array($begin, $end);
1273 * Fetches message headers (used for loop)
1275 * @param string $mailbox Mailbox name
1276 * @param string $msgs Message index to fetch
1277 * @param array $a_msg_headers Reference to message headers array
1278 * @param string $cache_key Cache index key
1279 * @return int Messages count
1282 private function _fetch_headers($mailbox, $msgs, &$a_msg_headers, $cache_key)
1284 // fetch reqested headers from server
1285 $a_header_index = $this->conn->fetchHeaders(
1286 $mailbox, $msgs, false, false, $this->get_fetch_headers());
1288 if (empty($a_header_index))
1291 foreach ($a_header_index as $i => $headers) {
1292 $a_msg_headers[$headers->uid] = $headers;
1296 if ($this->caching_enabled && $cache_key) {
1297 // cache is incomplete?
1298 $cache_index = $this->get_message_cache_index($cache_key);
1300 foreach ($a_header_index as $headers) {
1302 if ($cache_index[$headers->id] == $headers->uid) {
1303 unset($cache_index[$headers->id]);
1306 // wrong UID at this position
1307 if ($cache_index[$headers->id]) {
1308 $for_remove[] = $cache_index[$headers->id];
1309 unset($cache_index[$headers->id]);
1311 // message UID in cache but at wrong position
1312 if (is_int($key = array_search($headers->uid, $cache_index))) {
1313 $for_remove[] = $cache_index[$key];
1314 unset($cache_index[$key]);
1317 $for_create[] = $headers->uid;
1321 $this->remove_message_cache($cache_key, $for_remove);
1323 // add messages to cache
1324 foreach ((array)$for_create as $uid) {
1325 $headers = $a_msg_headers[$uid];
1326 $this->add_message_cache($cache_key, $headers->id, $headers, NULL, true);
1330 return count($a_msg_headers);
1335 * Returns current status of mailbox
1337 * We compare the maximum UID to determine the number of
1338 * new messages because the RECENT flag is not reliable.
1340 * @param string $mbox_name Mailbox/folder name
1341 * @return int Folder status
1343 function mailbox_status($mbox_name = null)
1345 $mailbox = strlen($mbox_name) ? $this->mod_mailbox($mbox_name) : $this->mailbox;
1346 $old = $this->get_folder_stats($mailbox);
1348 // refresh message count -> will update
1349 $this->_messagecount($mailbox, 'ALL', true);
1352 $new = $this->get_folder_stats($mailbox);
1355 if ($new['maxuid'] > $old['maxuid'])
1357 // some messages has been deleted
1358 if ($new['cnt'] < $old['cnt'])
1361 // @TODO: optional checking for messages flags changes (?)
1362 // @TODO: UIDVALIDITY checking
1369 * Stores folder statistic data in session
1370 * @TODO: move to separate DB table (cache?)
1372 * @param string $mbox_name Mailbox name
1373 * @param string $name Data name
1374 * @param mixed $data Data value
1376 private function set_folder_stats($mbox_name, $name, $data)
1378 $_SESSION['folders'][$mbox_name][$name] = $data;
1383 * Gets folder statistic data
1385 * @param string $mbox_name Mailbox name
1386 * @return array Stats data
1388 private function get_folder_stats($mbox_name)
1390 if ($_SESSION['folders'][$mbox_name])
1391 return (array) $_SESSION['folders'][$mbox_name];
1398 * Return sorted array of message IDs (not UIDs)
1400 * @param string $mbox_name Mailbox to get index from
1401 * @param string $sort_field Sort column
1402 * @param string $sort_order Sort order [ASC, DESC]
1403 * @return array Indexed array with message IDs
1405 function message_index($mbox_name='', $sort_field=NULL, $sort_order=NULL)
1407 if ($this->threading)
1408 return $this->thread_index($mbox_name, $sort_field, $sort_order);
1410 $this->_set_sort_order($sort_field, $sort_order);
1412 $mailbox = strlen($mbox_name) ? $this->mod_mailbox($mbox_name) : $this->mailbox;
1413 $key = "{$mailbox}:{$this->sort_field}:{$this->sort_order}:{$this->search_string}.msgi";
1415 // we have a saved search result, get index from there
1416 if (!isset($this->icache[$key]) && $this->search_string
1417 && !$this->search_threads && $mailbox == $this->mailbox) {
1418 // use message index sort as default sorting
1419 if (!$this->sort_field) {
1420 $msgs = $this->search_set;
1422 if ($this->search_sort_field != 'date')
1425 if ($this->sort_order == 'DESC')
1426 $this->icache[$key] = array_reverse($msgs);
1428 $this->icache[$key] = $msgs;
1430 // sort with SORT command
1431 else if ($this->search_sorted) {
1432 if ($this->sort_field && $this->search_sort_field != $this->sort_field)
1433 $this->search('', $this->search_string, $this->search_charset, $this->sort_field);
1435 if ($this->sort_order == 'DESC')
1436 $this->icache[$key] = array_reverse($this->search_set);
1438 $this->icache[$key] = $this->search_set;
1441 $a_index = $this->conn->fetchHeaderIndex($mailbox,
1442 join(',', $this->search_set), $this->sort_field, $this->skip_deleted);
1444 if (is_array($a_index)) {
1445 if ($this->sort_order=="ASC")
1447 else if ($this->sort_order=="DESC")
1450 $this->icache[$key] = array_keys($a_index);
1453 $this->icache[$key] = array();
1458 // have stored it in RAM
1459 if (isset($this->icache[$key]))
1460 return $this->icache[$key];
1462 // check local cache
1463 $cache_key = $mailbox.'.msg';
1464 $cache_status = $this->check_cache_status($mailbox, $cache_key);
1467 if ($cache_status>0) {
1468 $a_index = $this->get_message_cache_index($cache_key,
1469 $this->sort_field, $this->sort_order);
1470 return array_keys($a_index);
1473 // use message index sort as default sorting
1474 if (!$this->sort_field) {
1475 if ($this->skip_deleted) {
1476 $a_index = $this->_search_index($mailbox, 'ALL');
1477 } else if ($max = $this->_messagecount($mailbox)) {
1478 $a_index = range(1, $max);
1481 if ($a_index !== false && $this->sort_order == 'DESC')
1482 $a_index = array_reverse($a_index);
1484 $this->icache[$key] = $a_index;
1486 // fetch complete message index
1487 else if ($this->get_capability('SORT') &&
1488 ($a_index = $this->conn->sort($mailbox,
1489 $this->sort_field, $this->skip_deleted ? 'UNDELETED' : '')) !== false
1491 if ($this->sort_order == 'DESC')
1492 $a_index = array_reverse($a_index);
1494 $this->icache[$key] = $a_index;
1496 else if ($a_index = $this->conn->fetchHeaderIndex(
1497 $mailbox, "1:*", $this->sort_field, $this->skip_deleted)) {
1498 if ($this->sort_order=="ASC")
1500 else if ($this->sort_order=="DESC")
1503 $this->icache[$key] = array_keys($a_index);
1506 return $this->icache[$key] !== false ? $this->icache[$key] : array();
1511 * Return sorted array of threaded message IDs (not UIDs)
1513 * @param string $mbox_name Mailbox to get index from
1514 * @param string $sort_field Sort column
1515 * @param string $sort_order Sort order [ASC, DESC]
1516 * @return array Indexed array with message IDs
1518 function thread_index($mbox_name='', $sort_field=NULL, $sort_order=NULL)
1520 $this->_set_sort_order($sort_field, $sort_order);
1522 $mailbox = strlen($mbox_name) ? $this->mod_mailbox($mbox_name) : $this->mailbox;
1523 $key = "{$mailbox}:{$this->sort_field}:{$this->sort_order}:{$this->search_string}.thi";
1525 // we have a saved search result, get index from there
1526 if (!isset($this->icache[$key]) && $this->search_string
1527 && $this->search_threads && $mailbox == $this->mailbox) {
1528 // use message IDs for better performance
1529 $ids = array_keys_recursive($this->search_set['tree']);
1530 $this->icache[$key] = $this->_flatten_threads($mailbox, $this->search_set['tree'], $ids);
1533 // have stored it in RAM
1534 if (isset($this->icache[$key]))
1535 return $this->icache[$key];
1537 // check local cache
1538 $cache_key = $mailbox.'.msg';
1539 $cache_status = $this->check_cache_status($mailbox, $cache_key);
1542 if ($cache_status>0) {
1543 $a_index = $this->get_message_cache_index($cache_key, $this->sort_field, $this->sort_order);
1544 return array_keys($a_index);
1547 // get all threads (default sort order)
1548 list ($thread_tree) = $this->_fetch_threads($mailbox);
1550 $this->icache[$key] = $this->_flatten_threads($mailbox, $thread_tree);
1552 return $this->icache[$key];
1557 * Return array of threaded messages (all, not only roots)
1559 * @param string $mailbox Mailbox to get index from
1560 * @param array $thread_tree Threaded messages array (see _fetch_threads())
1561 * @param array $ids Message IDs if we know what we need (e.g. search result)
1562 * for better performance
1563 * @return array Indexed array with message IDs
1567 private function _flatten_threads($mailbox, $thread_tree, $ids=null)
1569 if (empty($thread_tree))
1572 $msg_index = $this->_sort_threads($mailbox, $thread_tree, $ids);
1574 if ($this->sort_order == 'DESC')
1575 $msg_index = array_reverse($msg_index);
1577 // flatten threads array
1579 foreach ($msg_index as $root) {
1581 if (!empty($thread_tree[$root])) {
1582 foreach (array_keys_recursive($thread_tree[$root]) as $val)
1592 * @param string $mailbox Mailbox name
1595 private function sync_header_index($mailbox)
1597 $cache_key = $mailbox.'.msg';
1598 $cache_index = $this->get_message_cache_index($cache_key);
1601 // cache is empty, get all messages
1602 if (is_array($cache_index) && empty($cache_index)) {
1603 $max = $this->_messagecount($mailbox);
1604 // syncing a big folder maybe slow
1607 $end = min($chunk_size, $max);
1609 // do this in loop to save memory (1000 msgs ~= 10 MB)
1610 if ($headers = $this->conn->fetchHeaders($mailbox,
1611 "$start:$end", false, false, $this->get_fetch_headers())
1613 foreach ($headers as $header) {
1614 $this->add_message_cache($cache_key, $header->id, $header, NULL, true);
1617 if ($end - $start < $chunk_size - 1)
1620 $end = min($end+$chunk_size, $max);
1621 $start += $chunk_size;
1626 // fetch complete message index
1627 if (isset($this->icache['folder_index']))
1628 $a_message_index = &$this->icache['folder_index'];
1630 $a_message_index = $this->conn->fetchHeaderIndex($mailbox, "1:*", 'UID', $this->skip_deleted);
1632 if ($a_message_index === false || $cache_index === null)
1635 // compare cache index with real index
1636 foreach ($a_message_index as $id => $uid) {
1637 // message in cache at correct position
1638 if ($cache_index[$id] == $uid) {
1639 unset($cache_index[$id]);
1643 // other message at this position
1644 if (isset($cache_index[$id])) {
1645 $for_remove[] = $cache_index[$id];
1646 unset($cache_index[$id]);
1649 // message in cache but at wrong position
1650 if (is_int($key = array_search($uid, $cache_index))) {
1651 $for_remove[] = $uid;
1652 unset($cache_index[$key]);
1655 $for_update[] = $id;
1658 // remove messages at wrong positions and those deleted that are still in cache_index
1659 if (!empty($for_remove))
1660 $cache_index = array_merge($cache_index, $for_remove);
1662 if (!empty($cache_index))
1663 $this->remove_message_cache($cache_key, $cache_index);
1665 // fetch complete headers and add to cache
1666 if (!empty($for_update)) {
1667 // syncing a big folder maybe slow
1669 // To save memory do this in chunks
1670 $for_update = array_chunk($for_update, $chunk_size);
1671 foreach ($for_update as $uids) {
1672 if ($headers = $this->conn->fetchHeaders($mailbox,
1673 $uids, false, false, $this->get_fetch_headers())
1675 foreach ($headers as $header) {
1676 $this->add_message_cache($cache_key, $header->id, $header, NULL, true);
1685 * Invoke search request to IMAP server
1687 * @param string $mbox_name Mailbox name to search in
1688 * @param string $str Search criteria
1689 * @param string $charset Search charset
1690 * @param string $sort_field Header field to sort by
1691 * @return array search results as list of message IDs
1694 function search($mbox_name='', $str=NULL, $charset=NULL, $sort_field=NULL)
1699 $mailbox = strlen($mbox_name) ? $this->mod_mailbox($mbox_name) : $this->mailbox;
1701 $results = $this->_search_index($mailbox, $str, $charset, $sort_field);
1703 $this->set_search_set($str, $results, $charset, $sort_field, (bool)$this->threading,
1704 $this->threading || $this->search_sorted ? true : false);
1711 * Private search method
1713 * @param string $mailbox Mailbox name
1714 * @param string $criteria Search criteria
1715 * @param string $charset Charset
1716 * @param string $sort_field Sorting field
1717 * @return array search results as list of message ids
1719 * @see rcube_imap::search()
1721 private function _search_index($mailbox, $criteria='ALL', $charset=NULL, $sort_field=NULL)
1723 $orig_criteria = $criteria;
1725 if ($this->skip_deleted && !preg_match('/UNDELETED/', $criteria))
1726 $criteria = 'UNDELETED '.$criteria;
1728 if ($this->threading) {
1729 $a_messages = $this->conn->thread($mailbox, $this->threading, $criteria, $charset);
1731 // Error, try with US-ASCII (RFC5256: SORT/THREAD must support US-ASCII and UTF-8,
1732 // but I've seen that Courier doesn't support UTF-8)
1733 if ($a_messages === false && $charset && $charset != 'US-ASCII')
1734 $a_messages = $this->conn->thread($mailbox, $this->threading,
1735 $this->convert_criteria($criteria, $charset), 'US-ASCII');
1737 if ($a_messages !== false) {
1738 list ($thread_tree, $msg_depth, $has_children) = $a_messages;
1739 $a_messages = array(
1740 'tree' => $thread_tree,
1741 'depth' => $msg_depth,
1742 'children' => $has_children
1749 if ($sort_field && $this->get_capability('SORT')) {
1750 $charset = $charset ? $charset : $this->default_charset;
1751 $a_messages = $this->conn->sort($mailbox, $sort_field, $criteria, false, $charset);
1753 // Error, try with US-ASCII (RFC5256: SORT/THREAD must support US-ASCII and UTF-8,
1754 // but I've seen that Courier doesn't support UTF-8)
1755 if ($a_messages === false && $charset && $charset != 'US-ASCII')
1756 $a_messages = $this->conn->sort($mailbox, $sort_field,
1757 $this->convert_criteria($criteria, $charset), false, 'US-ASCII');
1759 if ($a_messages !== false) {
1760 $this->search_sorted = true;
1765 if ($orig_criteria == 'ALL') {
1766 $max = $this->_messagecount($mailbox);
1767 $a_messages = $max ? range(1, $max) : array();
1770 $a_messages = $this->conn->search($mailbox,
1771 ($charset ? "CHARSET $charset " : '') . $criteria);
1773 // Error, try with US-ASCII (some servers may support only US-ASCII)
1774 if ($a_messages === false && $charset && $charset != 'US-ASCII')
1775 $a_messages = $this->conn->search($mailbox,
1776 'CHARSET US-ASCII ' . $this->convert_criteria($criteria, $charset));
1778 // I didn't found that SEARCH should return sorted IDs
1779 if (is_array($a_messages) && !$this->sort_field)
1783 $this->search_sorted = false;
1790 * Direct (real and simple) SEARCH request to IMAP server,
1791 * without result sorting and caching
1793 * @param string $mbox_name Mailbox name to search in
1794 * @param string $str Search string
1795 * @param boolean $ret_uid True if UIDs should be returned
1796 * @return array Search results as list of message IDs or UIDs
1799 function search_once($mbox_name='', $str=NULL, $ret_uid=false)
1804 $mailbox = strlen($mbox_name) ? $this->mod_mailbox($mbox_name) : $this->mailbox;
1806 return $this->conn->search($mailbox, $str, $ret_uid);
1811 * Converts charset of search criteria string
1813 * @param string $str Search string
1814 * @param string $charset Original charset
1815 * @param string $dest_charset Destination charset (default US-ASCII)
1816 * @return string Search string
1819 private function convert_criteria($str, $charset, $dest_charset='US-ASCII')
1821 // convert strings to US_ASCII
1822 if (preg_match_all('/\{([0-9]+)\}\r\n/', $str, $matches, PREG_OFFSET_CAPTURE)) {
1823 $last = 0; $res = '';
1824 foreach ($matches[1] as $m) {
1825 $string_offset = $m[1] + strlen($m[0]) + 4; // {}\r\n
1826 $string = substr($str, $string_offset - 1, $m[0]);
1827 $string = rcube_charset_convert($string, $charset, $dest_charset);
1830 $res .= sprintf("%s{%d}\r\n%s", substr($str, $last, $m[1] - $last - 1), strlen($string), $string);
1831 $last = $m[0] + $string_offset - 1;
1833 if ($last < strlen($str))
1834 $res .= substr($str, $last, strlen($str)-$last);
1836 else // strings for conversion not found
1846 * @param string $mailbox Mailbox name
1847 * @param array $thread_tree Unsorted thread tree (rcube_imap_generic::thread() result)
1848 * @param array $ids Message IDs if we know what we need (e.g. search result)
1849 * @return array Sorted roots IDs
1852 private function _sort_threads($mailbox, $thread_tree, $ids=NULL)
1854 // THREAD=ORDEREDSUBJECT: sorting by sent date of root message
1855 // THREAD=REFERENCES: sorting by sent date of root message
1856 // THREAD=REFS: sorting by the most recent date in each thread
1858 if (!$this->sort_field || ($this->sort_field == 'date' && $this->threading == 'REFS')) {
1859 return array_keys((array)$thread_tree);
1861 // here we'll implement REFS sorting, for performance reason
1862 else { // ($sort_field == 'date' && $this->threading != 'REFS')
1864 if ($this->get_capability('SORT') &&
1865 ($a_index = $this->conn->sort($mailbox, $this->sort_field,
1866 !empty($ids) ? $ids : ($this->skip_deleted ? 'UNDELETED' : ''))) !== false
1868 // return unsorted tree if we've got no index data
1870 return array_keys((array)$thread_tree);
1873 // fetch specified headers for all messages and sort them
1874 $a_index = $this->conn->fetchHeaderIndex($mailbox, !empty($ids) ? $ids : "1:*",
1875 $this->sort_field, $this->skip_deleted);
1877 // return unsorted tree if we've got no index data
1879 return array_keys((array)$thread_tree);
1881 asort($a_index); // ASC
1882 $a_index = array_values($a_index);
1885 return $this->_sort_thread_refs($thread_tree, $a_index);
1891 * THREAD=REFS sorting implementation
1893 * @param array $tree Thread tree array (message identifiers as keys)
1894 * @param array $index Array of sorted message identifiers
1895 * @return array Array of sorted roots messages
1898 private function _sort_thread_refs($tree, $index)
1903 $index = array_combine(array_values($index), $index);
1906 foreach ($tree as $idx => $val) {
1907 $index[$idx] = $idx;
1909 $idx_arr = array_keys_recursive($tree[$idx]);
1910 foreach ($idx_arr as $subidx)
1911 $index[$subidx] = $idx;
1915 $index = array_values($index);
1917 // create sorted array of roots
1918 $msg_index = array();
1919 if ($this->sort_order != 'DESC') {
1920 foreach ($index as $idx)
1921 if (!isset($msg_index[$idx]))
1922 $msg_index[$idx] = $idx;
1923 $msg_index = array_values($msg_index);
1926 for ($x=count($index)-1; $x>=0; $x--)
1927 if (!isset($msg_index[$index[$x]]))
1928 $msg_index[$index[$x]] = $index[$x];
1929 $msg_index = array_reverse($msg_index);
1937 * Refresh saved search set
1939 * @return array Current search set
1941 function refresh_search()
1943 if (!empty($this->search_string))
1944 $this->search_set = $this->search('', $this->search_string, $this->search_charset,
1945 $this->search_sort_field, $this->search_threads, $this->search_sorted);
1947 return $this->get_search_set();
1952 * Check if the given message ID is part of the current search set
1954 * @param string $msgid Message id
1955 * @return boolean True on match or if no search request is stored
1957 function in_searchset($msgid)
1959 if (!empty($this->search_string)) {
1960 if ($this->search_threads)
1961 return isset($this->search_set['depth']["$msgid"]);
1963 return in_array("$msgid", (array)$this->search_set, true);
1971 * Return message headers object of a specific message
1973 * @param int $id Message ID
1974 * @param string $mbox_name Mailbox to read from
1975 * @param boolean $is_uid True if $id is the message UID
1976 * @param boolean $bodystr True if we need also BODYSTRUCTURE in headers
1977 * @return object Message headers representation
1979 function get_headers($id, $mbox_name=NULL, $is_uid=true, $bodystr=false)
1981 $mailbox = strlen($mbox_name) ? $this->mod_mailbox($mbox_name) : $this->mailbox;
1982 $uid = $is_uid ? $id : $this->_id2uid($id, $mailbox);
1984 // get cached headers
1985 if ($uid && ($headers = &$this->get_cached_message($mailbox.'.msg', $uid)))
1988 $headers = $this->conn->fetchHeader(
1989 $mailbox, $id, $is_uid, $bodystr, $this->get_fetch_headers());
1991 // write headers cache
1993 if ($headers->uid && $headers->id)
1994 $this->uid_id_map[$mailbox][$headers->uid] = $headers->id;
1996 $this->add_message_cache($mailbox.'.msg', $headers->id, $headers, NULL, false, true);
2004 * Fetch body structure from the IMAP server and build
2005 * an object structure similar to the one generated by PEAR::Mail_mimeDecode
2007 * @param int $uid Message UID to fetch
2008 * @param string $structure_str Message BODYSTRUCTURE string (optional)
2009 * @return object rcube_message_part Message part tree or False on failure
2011 function &get_structure($uid, $structure_str='')
2013 $cache_key = $this->mailbox.'.msg';
2014 $headers = &$this->get_cached_message($cache_key, $uid);
2016 // return cached message structure
2017 if (is_object($headers) && is_object($headers->structure)) {
2018 return $headers->structure;
2021 if (!$structure_str) {
2022 $structure_str = $this->conn->fetchStructureString($this->mailbox, $uid, true);
2024 $structure = rcube_mime_struct::parseStructure($structure_str);
2027 // parse structure and add headers
2028 if (!empty($structure)) {
2029 $headers = $this->get_headers($uid);
2030 $this->_msg_id = $headers->id;
2032 // set message charset from message headers
2033 if ($headers->charset)
2034 $this->struct_charset = $headers->charset;
2036 $this->struct_charset = $this->_structure_charset($structure);
2038 $headers->ctype = strtolower($headers->ctype);
2040 // Here we can recognize malformed BODYSTRUCTURE and
2041 // 1. [@TODO] parse the message in other way to create our own message structure
2042 // 2. or just show the raw message body.
2043 // Example of structure for malformed MIME message:
2044 // ("text" "plain" NIL NIL NIL "7bit" 2154 70 NIL NIL NIL)
2045 if ($headers->ctype && !is_array($structure[0]) && $headers->ctype != 'text/plain'
2046 && strtolower($structure[0].'/'.$structure[1]) == 'text/plain') {
2047 // we can handle single-part messages, by simple fix in structure (#1486898)
2048 if (preg_match('/^(text|application)\/(.*)/', $headers->ctype, $m)) {
2049 $structure[0] = $m[1];
2050 $structure[1] = $m[2];
2056 $struct = &$this->_structure_part($structure);
2057 $struct->headers = get_object_vars($headers);
2059 // don't trust given content-type
2060 if (empty($struct->parts) && !empty($struct->headers['ctype'])) {
2061 $struct->mime_id = '1';
2062 $struct->mimetype = strtolower($struct->headers['ctype']);
2063 list($struct->ctype_primary, $struct->ctype_secondary) = explode('/', $struct->mimetype);
2066 // write structure to cache
2067 if ($this->caching_enabled)
2068 $this->add_message_cache($cache_key, $this->_msg_id, $headers, $struct,
2069 $this->icache['message.id'][$uid], true);
2077 * Build message part object
2079 * @param array $part
2081 * @param string $parent
2084 function &_structure_part($part, $count=0, $parent='', $mime_headers=null)
2086 $struct = new rcube_message_part;
2087 $struct->mime_id = empty($parent) ? (string)$count : "$parent.$count";
2090 if (is_array($part[0])) {
2091 $struct->ctype_primary = 'multipart';
2093 /* RFC3501: BODYSTRUCTURE fields of multipart part
2099 2. parameters (optional)
2100 3. description (optional)
2101 4. language (optional)
2102 5. location (optional)
2105 // find first non-array entry
2106 for ($i=1; $i<count($part); $i++) {
2107 if (!is_array($part[$i])) {
2108 $struct->ctype_secondary = strtolower($part[$i]);
2113 $struct->mimetype = 'multipart/'.$struct->ctype_secondary;
2115 // build parts list for headers pre-fetching
2116 for ($i=0; $i<count($part); $i++) {
2117 if (!is_array($part[$i]))
2119 // fetch message headers if message/rfc822
2120 // or named part (could contain Content-Location header)
2121 if (!is_array($part[$i][0])) {
2122 $tmp_part_id = $struct->mime_id ? $struct->mime_id.'.'.($i+1) : $i+1;
2123 if (strtolower($part[$i][0]) == 'message' && strtolower($part[$i][1]) == 'rfc822') {
2124 $mime_part_headers[] = $tmp_part_id;
2126 else if (in_array('name', (array)$part[$i][2]) && (empty($part[$i][3]) || $part[$i][3]=='NIL')) {
2127 $mime_part_headers[] = $tmp_part_id;
2132 // pre-fetch headers of all parts (in one command for better performance)
2133 // @TODO: we could do this before _structure_part() call, to fetch
2134 // headers for parts on all levels
2135 if ($mime_part_headers) {
2136 $mime_part_headers = $this->conn->fetchMIMEHeaders($this->mailbox,
2137 $this->_msg_id, $mime_part_headers);
2140 $struct->parts = array();
2141 for ($i=0, $count=0; $i<count($part); $i++) {
2142 if (!is_array($part[$i]))
2144 $tmp_part_id = $struct->mime_id ? $struct->mime_id.'.'.($i+1) : $i+1;
2145 $struct->parts[] = $this->_structure_part($part[$i], ++$count, $struct->mime_id,
2146 $mime_part_headers[$tmp_part_id]);
2152 /* RFC3501: BODYSTRUCTURE fields of non-multipart part
2163 7. envelope structure
2168 x. disposition (optional)
2169 x. language (optional)
2170 x. location (optional)
2174 $struct->ctype_primary = strtolower($part[0]);
2175 $struct->ctype_secondary = strtolower($part[1]);
2176 $struct->mimetype = $struct->ctype_primary.'/'.$struct->ctype_secondary;
2178 // read content type parameters
2179 if (is_array($part[2])) {
2180 $struct->ctype_parameters = array();
2181 for ($i=0; $i<count($part[2]); $i+=2)
2182 $struct->ctype_parameters[strtolower($part[2][$i])] = $part[2][$i+1];
2184 if (isset($struct->ctype_parameters['charset']))
2185 $struct->charset = $struct->ctype_parameters['charset'];
2188 // read content encoding
2189 if (!empty($part[5]) && $part[5]!='NIL') {
2190 $struct->encoding = strtolower($part[5]);
2191 $struct->headers['content-transfer-encoding'] = $struct->encoding;
2195 if (!empty($part[6]) && $part[6]!='NIL')
2196 $struct->size = intval($part[6]);
2198 // read part disposition
2200 if ($struct->ctype_primary == 'text') $di += 1;
2201 else if ($struct->mimetype == 'message/rfc822') $di += 3;
2203 if (is_array($part[$di]) && count($part[$di]) == 2) {
2204 $struct->disposition = strtolower($part[$di][0]);
2206 if (is_array($part[$di][1]))
2207 for ($n=0; $n<count($part[$di][1]); $n+=2)
2208 $struct->d_parameters[strtolower($part[$di][1][$n])] = $part[$di][1][$n+1];
2211 // get message/rfc822's child-parts
2212 if (is_array($part[8]) && $di != 8) {
2213 $struct->parts = array();
2214 for ($i=0, $count=0; $i<count($part[8]); $i++) {
2215 if (!is_array($part[8][$i]))
2217 $struct->parts[] = $this->_structure_part($part[8][$i], ++$count, $struct->mime_id);
2222 if (!empty($part[3]) && $part[3]!='NIL') {
2223 $struct->content_id = $part[3];
2224 $struct->headers['content-id'] = $part[3];
2226 if (empty($struct->disposition))
2227 $struct->disposition = 'inline';
2230 // fetch message headers if message/rfc822 or named part (could contain Content-Location header)
2231 if ($struct->ctype_primary == 'message' || ($struct->ctype_parameters['name'] && !$struct->content_id)) {
2232 if (empty($mime_headers)) {
2233 $mime_headers = $this->conn->fetchPartHeader(
2234 $this->mailbox, $this->_msg_id, false, $struct->mime_id);
2236 $struct->headers = $this->_parse_headers($mime_headers) + $struct->headers;
2238 // get real content-type of message/rfc822
2239 if ($struct->mimetype == 'message/rfc822') {
2241 if (!is_array($part[8][0]))
2242 $struct->real_mimetype = strtolower($part[8][0] . '/' . $part[8][1]);
2245 for ($n=0; $n<count($part[8]); $n++)
2246 if (!is_array($part[8][$n]))
2248 $struct->real_mimetype = 'multipart/' . strtolower($part[8][$n]);
2252 if ($struct->ctype_primary == 'message' && empty($struct->parts)) {
2253 if (is_array($part[8]) && $di != 8)
2254 $struct->parts[] = $this->_structure_part($part[8], ++$count, $struct->mime_id);
2258 // normalize filename property
2259 $this->_set_part_filename($struct, $mime_headers);
2266 * Set attachment filename from message part structure
2268 * @param rcube_message_part $part Part object
2269 * @param string $headers Part's raw headers
2272 private function _set_part_filename(&$part, $headers=null)
2274 if (!empty($part->d_parameters['filename']))
2275 $filename_mime = $part->d_parameters['filename'];
2276 else if (!empty($part->d_parameters['filename*']))
2277 $filename_encoded = $part->d_parameters['filename*'];
2278 else if (!empty($part->ctype_parameters['name*']))
2279 $filename_encoded = $part->ctype_parameters['name*'];
2280 // RFC2231 value continuations
2281 // TODO: this should be rewrited to support RFC2231 4.1 combinations
2282 else if (!empty($part->d_parameters['filename*0'])) {
2284 while (isset($part->d_parameters['filename*'.$i])) {
2285 $filename_mime .= $part->d_parameters['filename*'.$i];
2288 // some servers (eg. dovecot-1.x) have no support for parameter value continuations
2289 // we must fetch and parse headers "manually"
2292 $headers = $this->conn->fetchPartHeader(
2293 $this->mailbox, $this->_msg_id, false, $part->mime_id);
2295 $filename_mime = '';
2297 while (preg_match('/filename\*'.$i.'\s*=\s*"*([^"\n;]+)[";]*/', $headers, $matches)) {
2298 $filename_mime .= $matches[1];
2303 else if (!empty($part->d_parameters['filename*0*'])) {
2305 while (isset($part->d_parameters['filename*'.$i.'*'])) {
2306 $filename_encoded .= $part->d_parameters['filename*'.$i.'*'];
2311 $headers = $this->conn->fetchPartHeader(
2312 $this->mailbox, $this->_msg_id, false, $part->mime_id);
2314 $filename_encoded = '';
2315 $i = 0; $matches = array();
2316 while (preg_match('/filename\*'.$i.'\*\s*=\s*"*([^"\n;]+)[";]*/', $headers, $matches)) {
2317 $filename_encoded .= $matches[1];
2322 else if (!empty($part->ctype_parameters['name*0'])) {
2324 while (isset($part->ctype_parameters['name*'.$i])) {
2325 $filename_mime .= $part->ctype_parameters['name*'.$i];
2330 $headers = $this->conn->fetchPartHeader(
2331 $this->mailbox, $this->_msg_id, false, $part->mime_id);
2333 $filename_mime = '';
2334 $i = 0; $matches = array();
2335 while (preg_match('/\s+name\*'.$i.'\s*=\s*"*([^"\n;]+)[";]*/', $headers, $matches)) {
2336 $filename_mime .= $matches[1];
2341 else if (!empty($part->ctype_parameters['name*0*'])) {
2343 while (isset($part->ctype_parameters['name*'.$i.'*'])) {
2344 $filename_encoded .= $part->ctype_parameters['name*'.$i.'*'];
2349 $headers = $this->conn->fetchPartHeader(
2350 $this->mailbox, $this->_msg_id, false, $part->mime_id);
2352 $filename_encoded = '';
2353 $i = 0; $matches = array();
2354 while (preg_match('/\s+name\*'.$i.'\*\s*=\s*"*([^"\n;]+)[";]*/', $headers, $matches)) {
2355 $filename_encoded .= $matches[1];
2360 // read 'name' after rfc2231 parameters as it may contains truncated filename (from Thunderbird)
2361 else if (!empty($part->ctype_parameters['name']))
2362 $filename_mime = $part->ctype_parameters['name'];
2363 // Content-Disposition
2364 else if (!empty($part->headers['content-description']))
2365 $filename_mime = $part->headers['content-description'];
2370 if (!empty($filename_mime)) {
2371 $part->filename = rcube_imap::decode_mime_string($filename_mime,
2372 $part->charset ? $part->charset : ($this->struct_charset ? $this->struct_charset :
2373 rc_detect_encoding($filename_mime, $this->default_charset)));
2375 else if (!empty($filename_encoded)) {
2376 // decode filename according to RFC 2231, Section 4
2377 if (preg_match("/^([^']*)'[^']*'(.*)$/", $filename_encoded, $fmatches)) {
2378 $filename_charset = $fmatches[1];
2379 $filename_encoded = $fmatches[2];
2381 $part->filename = rcube_charset_convert(urldecode($filename_encoded), $filename_charset);
2387 * Get charset name from message structure (first part)
2389 * @param array $structure Message structure
2390 * @return string Charset name
2393 private function _structure_charset($structure)
2395 while (is_array($structure)) {
2396 if (is_array($structure[2]) && $structure[2][0] == 'charset')
2397 return $structure[2][1];
2398 $structure = $structure[0];
2404 * Fetch message body of a specific message from the server
2406 * @param int $uid Message UID
2407 * @param string $part Part number
2408 * @param rcube_message_part $o_part Part object created by get_structure()
2409 * @param mixed $print True to print part, ressource to write part contents in
2410 * @param resource $fp File pointer to save the message part
2411 * @return string Message/part body if not printed
2413 function &get_message_part($uid, $part=1, $o_part=NULL, $print=NULL, $fp=NULL)
2415 // get part encoding if not provided
2416 if (!is_object($o_part)) {
2417 $structure_str = $this->conn->fetchStructureString($this->mailbox, $uid, true);
2418 $structure = new rcube_mime_struct();
2419 // error or message not found
2420 if (!$structure->loadStructure($structure_str)) {
2424 $o_part = new rcube_message_part;
2425 $o_part->ctype_primary = strtolower($structure->getPartType($part));
2426 $o_part->encoding = strtolower($structure->getPartEncoding($part));
2427 $o_part->charset = $structure->getPartCharset($part);
2430 // TODO: Add caching for message parts
2436 $body = $this->conn->handlePartBody($this->mailbox, $uid, true, $part,
2437 $o_part->encoding, $print, $fp);
2439 if ($fp || $print) {
2443 // convert charset (if text or message part) and part's charset is specified
2444 if ($body && $o_part->charset
2445 && preg_match('/^(text|message)$/', $o_part->ctype_primary)
2447 $body = rcube_charset_convert($body, $o_part->charset);
2455 * Fetch message body of a specific message from the server
2457 * @param int $uid Message UID
2458 * @return string $part Message/part body
2459 * @see rcube_imap::get_message_part()
2461 function &get_body($uid, $part=1)
2463 $headers = $this->get_headers($uid);
2464 return rcube_charset_convert($this->get_message_part($uid, $part, NULL),
2465 $headers->charset ? $headers->charset : $this->default_charset);
2470 * Returns the whole message source as string
2472 * @param int $uid Message UID
2473 * @return string Message source string
2475 function &get_raw_body($uid)
2477 return $this->conn->handlePartBody($this->mailbox, $uid, true);
2482 * Returns the message headers as string
2484 * @param int $uid Message UID
2485 * @return string Message headers string
2487 function &get_raw_headers($uid)
2489 return $this->conn->fetchPartHeader($this->mailbox, $uid, true);
2494 * Sends the whole message source to stdout
2496 * @param int $uid Message UID
2498 function print_raw_body($uid)
2500 $this->conn->handlePartBody($this->mailbox, $uid, true, NULL, NULL, true);
2505 * Set message flag to one or several messages
2507 * @param mixed $uids Message UIDs as array or comma-separated string, or '*'
2508 * @param string $flag Flag to set: SEEN, UNDELETED, DELETED, RECENT, ANSWERED, DRAFT, MDNSENT
2509 * @param string $mbox_name Folder name
2510 * @param boolean $skip_cache True to skip message cache clean up
2511 * @return boolean Operation status
2513 function set_flag($uids, $flag, $mbox_name=NULL, $skip_cache=false)
2515 $mailbox = strlen($mbox_name) ? $this->mod_mailbox($mbox_name) : $this->mailbox;
2517 $flag = strtoupper($flag);
2518 list($uids, $all_mode) = $this->_parse_uids($uids, $mailbox);
2520 if (strpos($flag, 'UN') === 0)
2521 $result = $this->conn->unflag($mailbox, $uids, substr($flag, 2));
2523 $result = $this->conn->flag($mailbox, $uids, $flag);
2526 // reload message headers if cached
2527 if ($this->caching_enabled && !$skip_cache) {
2528 $cache_key = $mailbox.'.msg';
2530 $this->clear_message_cache($cache_key);
2532 $this->remove_message_cache($cache_key, explode(',', $uids));
2535 // clear cached counters
2536 if ($flag == 'SEEN' || $flag == 'UNSEEN') {
2537 $this->_clear_messagecount($mailbox, 'SEEN');
2538 $this->_clear_messagecount($mailbox, 'UNSEEN');
2540 else if ($flag == 'DELETED') {
2541 $this->_clear_messagecount($mailbox, 'DELETED');
2550 * Remove message flag for one or several messages
2552 * @param mixed $uids Message UIDs as array or comma-separated string, or '*'
2553 * @param string $flag Flag to unset: SEEN, DELETED, RECENT, ANSWERED, DRAFT, MDNSENT
2554 * @param string $mbox_name Folder name
2555 * @return int Number of flagged messages, -1 on failure
2558 function unset_flag($uids, $flag, $mbox_name=NULL)
2560 return $this->set_flag($uids, 'UN'.$flag, $mbox_name);
2565 * Append a mail message (source) to a specific mailbox
2567 * @param string $mbox_name Target mailbox
2568 * @param string $message The message source string or filename
2569 * @param string $headers Headers string if $message contains only the body
2570 * @param boolean $is_file True if $message is a filename
2572 * @return boolean True on success, False on error
2574 function save_message($mbox_name, &$message, $headers='', $is_file=false)
2576 $mailbox = $this->mod_mailbox($mbox_name);
2578 // make sure mailbox exists
2579 if ($this->mailbox_exists($mbox_name)) {
2581 $saved = $this->conn->appendFromFile($mailbox, $message, $headers);
2583 $saved = $this->conn->append($mailbox, $message);
2587 // increase messagecount of the target mailbox
2588 $this->_set_messagecount($mailbox, 'ALL', 1);
2596 * Move a message from one mailbox to another
2598 * @param mixed $uids Message UIDs as array or comma-separated string, or '*'
2599 * @param string $to_mbox Target mailbox
2600 * @param string $from_mbox Source mailbox
2601 * @return boolean True on success, False on error
2603 function move_message($uids, $to_mbox, $from_mbox='')
2607 $to_mbox = $this->mod_mailbox($to_mbox);
2608 $from_mbox = strlen($from_mbox) ? $this->mod_mailbox($from_mbox) : $this->mailbox;
2610 if ($to_mbox === $from_mbox)
2613 list($uids, $all_mode) = $this->_parse_uids($uids, $from_mbox);
2615 // exit if no message uids are specified
2619 // make sure mailbox exists
2620 if ($to_mbox != 'INBOX' && !$this->mailbox_exists($tbox)) {
2621 if (in_array($tbox, $this->default_folders))
2622 $this->create_mailbox($tbox, true);
2627 // flag messages as read before moving them
2628 $config = rcmail::get_instance()->config;
2629 if ($config->get('read_when_deleted') && $tbox == $config->get('trash_mbox')) {
2630 // don't flush cache (4th argument)
2631 $this->set_flag($uids, 'SEEN', $fbox, true);
2635 $moved = $this->conn->move($uids, $from_mbox, $to_mbox);
2637 // send expunge command in order to have the moved message
2638 // really deleted from the source mailbox
2640 $this->_expunge($from_mbox, false, $uids);
2641 $this->_clear_messagecount($from_mbox);
2642 $this->_clear_messagecount($to_mbox);
2645 else if ($config->get('delete_always', false) && $tbox == $config->get('trash_mbox')) {
2646 $moved = $this->delete_message($uids, $fbox);
2650 // unset threads internal cache
2651 unset($this->icache['threads']);
2653 // remove message ids from search set
2654 if ($this->search_set && $from_mbox == $this->mailbox) {
2655 // threads are too complicated to just remove messages from set
2656 if ($this->search_threads || $all_mode)
2657 $this->refresh_search();
2659 $uids = explode(',', $uids);
2660 foreach ($uids as $uid)
2661 $a_mids[] = $this->_uid2id($uid, $from_mbox);
2662 $this->search_set = array_diff($this->search_set, $a_mids);
2666 // update cached message headers
2667 $cache_key = $from_mbox.'.msg';
2668 if ($all_mode || ($start_index = $this->get_message_cache_index_min($cache_key, $uids))) {
2669 // clear cache from the lowest index on
2670 $this->clear_message_cache($cache_key, $all_mode ? 1 : $start_index);
2679 * Copy a message from one mailbox to another
2681 * @param mixed $uids Message UIDs as array or comma-separated string, or '*'
2682 * @param string $to_mbox Target mailbox
2683 * @param string $from_mbox Source mailbox
2684 * @return boolean True on success, False on error
2686 function copy_message($uids, $to_mbox, $from_mbox='')
2690 $to_mbox = $this->mod_mailbox($to_mbox);
2691 $from_mbox = $from_mbox ? $this->mod_mailbox($from_mbox) : $this->mailbox;
2693 list($uids, $all_mode) = $this->_parse_uids($uids, $from_mbox);
2695 // exit if no message uids are specified
2700 // make sure mailbox exists
2701 if ($to_mbox != 'INBOX' && !$this->mailbox_exists($tbox)) {
2702 if (in_array($tbox, $this->default_folders))
2703 $this->create_mailbox($tbox, true);
2709 $copied = $this->conn->copy($uids, $from_mbox, $to_mbox);
2712 $this->_clear_messagecount($to_mbox);
2720 * Mark messages as deleted and expunge mailbox
2722 * @param mixed $uids Message UIDs as array or comma-separated string, or '*'
2723 * @param string $mbox_name Source mailbox
2724 * @return boolean True on success, False on error
2726 function delete_message($uids, $mbox_name='')
2728 $mailbox = strlen($mbox_name) ? $this->mod_mailbox($mbox_name) : $this->mailbox;
2730 list($uids, $all_mode) = $this->_parse_uids($uids, $mailbox);
2732 // exit if no message uids are specified
2736 $deleted = $this->conn->delete($mailbox, $uids);
2739 // send expunge command in order to have the deleted message
2740 // really deleted from the mailbox
2741 $this->_expunge($mailbox, false, $uids);
2742 $this->_clear_messagecount($mailbox);
2743 unset($this->uid_id_map[$mailbox]);
2745 // unset threads internal cache
2746 unset($this->icache['threads']);
2748 // remove message ids from search set
2749 if ($this->search_set && $mailbox == $this->mailbox) {
2750 // threads are too complicated to just remove messages from set
2751 if ($this->search_threads || $all_mode)
2752 $this->refresh_search();
2754 $uids = explode(',', $uids);
2755 foreach ($uids as $uid)
2756 $a_mids[] = $this->_uid2id($uid, $mailbox);
2757 $this->search_set = array_diff($this->search_set, $a_mids);
2761 // remove deleted messages from cache
2762 $cache_key = $mailbox.'.msg';
2763 if ($all_mode || ($start_index = $this->get_message_cache_index_min($cache_key, $uids))) {
2764 // clear cache from the lowest index on
2765 $this->clear_message_cache($cache_key, $all_mode ? 1 : $start_index);
2774 * Clear all messages in a specific mailbox
2776 * @param string $mbox_name Mailbox name
2777 * @return int Above 0 on success
2779 function clear_mailbox($mbox_name=NULL)
2781 $mailbox = strlen($mbox_name) ? $this->mod_mailbox($mbox_name) : $this->mailbox;
2783 // SELECT will set messages count for clearFolder()
2784 if ($this->conn->select($mailbox)) {
2785 $cleared = $this->conn->clearFolder($mailbox);
2788 // make sure the message count cache is cleared as well
2790 $this->clear_message_cache($mailbox.'.msg');
2791 $a_mailbox_cache = $this->get_cache('messagecount');
2792 unset($a_mailbox_cache[$mailbox]);
2793 $this->update_cache('messagecount', $a_mailbox_cache);
2801 * Send IMAP expunge command and clear cache
2803 * @param string $mbox_name Mailbox name
2804 * @param boolean $clear_cache False if cache should not be cleared
2805 * @return boolean True on success
2807 function expunge($mbox_name='', $clear_cache=true)
2809 $mailbox = strlen($mbox_name) ? $this->mod_mailbox($mbox_name) : $this->mailbox;
2810 return $this->_expunge($mailbox, $clear_cache);
2815 * Send IMAP expunge command and clear cache
2817 * @param string $mailbox Mailbox name
2818 * @param boolean $clear_cache False if cache should not be cleared
2819 * @param mixed $uids Message UIDs as array or comma-separated string, or '*'
2820 * @return boolean True on success
2822 * @see rcube_imap::expunge()
2824 private function _expunge($mailbox, $clear_cache=true, $uids=NULL)
2826 if ($uids && $this->get_capability('UIDPLUS'))
2827 $a_uids = is_array($uids) ? join(',', $uids) : $uids;
2831 // force mailbox selection and check if mailbox is writeable
2832 // to prevent a situation when CLOSE is executed on closed
2833 // or EXPUNGE on read-only mailbox
2834 $result = $this->conn->select($mailbox);
2838 if (!$this->conn->data['READ-WRITE']) {
2839 $this->conn->setError(rcube_imap_generic::ERROR_READONLY, "Mailbox is read-only");
2843 // CLOSE(+SELECT) should be faster than EXPUNGE
2844 if (empty($a_uids) || $a_uids == '1:*')
2845 $result = $this->conn->close();
2847 $result = $this->conn->expunge($mailbox, $a_uids);
2849 if ($result && $clear_cache) {
2850 $this->clear_message_cache($mailbox.'.msg');
2851 $this->_clear_messagecount($mailbox);
2859 * Parse message UIDs input
2861 * @param mixed $uids UIDs array or comma-separated list or '*' or '1:*'
2862 * @param string $mailbox Mailbox name
2863 * @return array Two elements array with UIDs converted to list and ALL flag
2866 private function _parse_uids($uids, $mailbox)
2868 if ($uids === '*' || $uids === '1:*') {
2869 if (empty($this->search_set)) {
2873 // get UIDs from current search set
2874 // @TODO: skip fetchUIDs() and work with IDs instead of UIDs (?)
2876 if ($this->search_threads)
2877 $uids = $this->conn->fetchUIDs($mailbox, array_keys($this->search_set['depth']));
2879 $uids = $this->conn->fetchUIDs($mailbox, $this->search_set);
2881 // save ID-to-UID mapping in local cache
2882 if (is_array($uids))
2883 foreach ($uids as $id => $uid)
2884 $this->uid_id_map[$mailbox][$uid] = $id;
2886 $uids = join(',', $uids);
2890 if (is_array($uids))
2891 $uids = join(',', $uids);
2893 if (preg_match('/[^0-9,]/', $uids))
2897 return array($uids, (bool) $all);
2902 * Translate UID to message ID
2904 * @param int $uid Message UID
2905 * @param string $mbox_name Mailbox name
2906 * @return int Message ID
2908 function get_id($uid, $mbox_name=NULL)
2910 $mailbox = strlen($mbox_name) ? $this->mod_mailbox($mbox_name) : $this->mailbox;
2911 return $this->_uid2id($uid, $mailbox);
2916 * Translate message number to UID
2918 * @param int $id Message ID
2919 * @param string $mbox_name Mailbox name
2920 * @return int Message UID
2922 function get_uid($id, $mbox_name=NULL)
2924 $mailbox = strlen($mbox_name) ? $this->mod_mailbox($mbox_name) : $this->mailbox;
2925 return $this->_id2uid($id, $mailbox);
2930 /* --------------------------------
2932 * --------------------------------*/
2935 * Public method for listing subscribed folders
2937 * Converts mailbox name with root dir first
2939 * @param string $root Optional root folder
2940 * @param string $filter Optional filter for mailbox listing
2941 * @return array List of mailboxes/folders
2944 function list_mailboxes($root='', $filter='*')
2947 $a_mboxes = $this->_list_mailboxes($root, $filter);
2949 foreach ($a_mboxes as $idx => $mbox_row) {
2950 if (strlen($name = $this->mod_mailbox($mbox_row, 'out')))
2952 unset($a_mboxes[$idx]);
2955 // INBOX should always be available
2956 if (!in_array('INBOX', $a_out))
2957 array_unshift($a_out, 'INBOX');
2960 $a_out = $this->_sort_mailbox_list($a_out);
2967 * Private method for mailbox listing
2969 * @param string $root Optional root folder
2970 * @param string $filter Optional filter for mailbox listing
2971 * @return array List of mailboxes/folders
2972 * @see rcube_imap::list_mailboxes()
2975 private function _list_mailboxes($root='', $filter='*')
2977 // get cached folder list
2978 $a_mboxes = $this->get_cache('mailboxes');
2979 if (is_array($a_mboxes))
2982 $a_defaults = $a_out = array();
2984 // Give plugins a chance to provide a list of mailboxes
2985 $data = rcmail::get_instance()->plugins->exec_hook('mailboxes_list',
2986 array('root' => $root, 'filter' => $filter, 'mode' => 'LSUB'));
2988 if (isset($data['folders'])) {
2989 $a_folders = $data['folders'];
2992 // Server supports LIST-EXTENDED, we can use selection options
2993 $config = rcmail::get_instance()->config;
2994 // #1486225: Some dovecot versions returns wrong result using LIST-EXTENDED
2995 if (!$config->get('imap_force_lsub') && $this->get_capability('LIST-EXTENDED')) {
2996 // This will also set mailbox options, LSUB doesn't do that
2997 $a_folders = $this->conn->listMailboxes($this->mod_mailbox($root), $filter,
2998 NULL, array('SUBSCRIBED'));
3000 // remove non-existent folders
3001 if (is_array($a_folders)) {
3002 foreach ($a_folders as $idx => $folder) {
3003 if ($this->conn->data['LIST'] && ($opts = $this->conn->data['LIST'][$folder])
3004 && in_array('\\NonExistent', $opts)
3006 unset($a_folders[$idx]);
3011 // retrieve list of folders from IMAP server using LSUB
3013 $a_folders = $this->conn->listSubscribed($this->mod_mailbox($root), $filter);
3017 if (!is_array($a_folders) || !sizeof($a_folders))
3018 $a_folders = array();
3020 // write mailboxlist to cache
3021 $this->update_cache('mailboxes', $a_folders);
3028 * Get a list of all folders available on the IMAP server
3030 * @param string $root IMAP root dir
3031 * @param string $filter Optional filter for mailbox listing
3032 * @return array Indexed array with folder names
3034 function list_unsubscribed($root='', $filter='*')
3036 // Give plugins a chance to provide a list of mailboxes
3037 $data = rcmail::get_instance()->plugins->exec_hook('mailboxes_list',
3038 array('root' => $root, 'filter' => $filter, 'mode' => 'LIST'));
3040 if (isset($data['folders'])) {
3041 $a_mboxes = $data['folders'];
3044 // retrieve list of folders from IMAP server
3045 $a_mboxes = $this->conn->listMailboxes($this->mod_mailbox($root), $filter);
3048 $a_folders = array();
3049 if (!is_array($a_mboxes))
3050 $a_mboxes = array();
3052 // modify names with root dir
3053 foreach ($a_mboxes as $idx => $mbox_name) {
3054 if (strlen($name = $this->mod_mailbox($mbox_name, 'out')))
3055 $a_folders[] = $name;
3056 unset($a_mboxes[$idx]);
3059 // INBOX should always be available
3060 if (!in_array('INBOX', $a_folders))
3061 array_unshift($a_folders, 'INBOX');
3063 // filter folders and sort them
3064 $a_folders = $this->_sort_mailbox_list($a_folders);
3070 * Get mailbox quota information
3073 * @return mixed Quota info or False if not supported
3075 function get_quota()
3077 if ($this->get_capability('QUOTA'))
3078 return $this->conn->getQuota();
3085 * Get mailbox size (size of all messages in a mailbox)
3087 * @param string $name Mailbox name
3088 * @return int Mailbox size in bytes, False on error
3090 function get_mailbox_size($name)
3092 $name = $this->mod_mailbox($name);
3094 // @TODO: could we try to use QUOTA here?
3095 $result = $this->conn->fetchHeaderIndex($name, '1:*', 'SIZE', false);
3097 if (is_array($result))
3098 $result = array_sum($result);
3105 * Subscribe to a specific mailbox(es)
3107 * @param array $a_mboxes Mailbox name(s)
3108 * @return boolean True on success
3110 function subscribe($a_mboxes)
3112 if (!is_array($a_mboxes))
3113 $a_mboxes = array($a_mboxes);
3115 // let this common function do the main work
3116 return $this->_change_subscription($a_mboxes, 'subscribe');
3121 * Unsubscribe mailboxes
3123 * @param array $a_mboxes Mailbox name(s)
3124 * @return boolean True on success
3126 function unsubscribe($a_mboxes)
3128 if (!is_array($a_mboxes))
3129 $a_mboxes = array($a_mboxes);
3131 // let this common function do the main work
3132 return $this->_change_subscription($a_mboxes, 'unsubscribe');
3137 * Create a new mailbox on the server and register it in local cache
3139 * @param string $name New mailbox name
3140 * @param boolean $subscribe True if the new mailbox should be subscribed
3141 * @param boolean True on success
3143 function create_mailbox($name, $subscribe=false)
3146 $abs_name = $this->mod_mailbox($name);
3147 $result = $this->conn->createFolder($abs_name);
3149 // try to subscribe it
3150 if ($result && $subscribe)
3151 $this->subscribe($name);
3158 * Set a new name to an existing mailbox
3160 * @param string $mbox_name Mailbox to rename
3161 * @param string $new_name New mailbox name
3163 * @return boolean True on success
3165 function rename_mailbox($mbox_name, $new_name)
3169 // make absolute path
3170 $mailbox = $this->mod_mailbox($mbox_name);
3171 $abs_name = $this->mod_mailbox($new_name);
3172 $delm = $this->get_hierarchy_delimiter();
3174 // get list of subscribed folders
3175 if ((strpos($mailbox, '%') === false) && (strpos($mailbox, '*') === false)) {
3176 $a_subscribed = $this->_list_mailboxes('', $mbox_name . $delm . '*');
3177 $subscribed = $this->mailbox_exists($mbox_name, true);
3180 $a_subscribed = $this->_list_mailboxes();
3181 $subscribed = in_array($mailbox, $a_subscribed);
3184 if (strlen($abs_name))
3185 $result = $this->conn->renameFolder($mailbox, $abs_name);
3188 // unsubscribe the old folder, subscribe the new one
3190 $this->conn->unsubscribe($mailbox);
3191 $this->conn->subscribe($abs_name);
3194 // check if mailbox children are subscribed
3195 foreach ($a_subscribed as $c_subscribed) {
3196 if (preg_match('/^'.preg_quote($mailbox.$delm, '/').'/', $c_subscribed)) {
3197 $this->conn->unsubscribe($c_subscribed);
3198 $this->conn->subscribe(preg_replace('/^'.preg_quote($mailbox, '/').'/',
3199 $abs_name, $c_subscribed));
3204 $this->clear_message_cache($mailbox.'.msg');
3205 $this->clear_cache('mailboxes');
3213 * Remove mailbox from server
3215 * @param string $mbox_name Mailbox name
3217 * @return boolean True on success
3219 function delete_mailbox($mbox_name)
3222 $mailbox = $this->mod_mailbox($mbox_name);
3223 $delm = $this->get_hierarchy_delimiter();
3225 // get list of folders
3226 if ((strpos($mailbox, '%') === false) && (strpos($mailbox, '*') === false))
3227 $sub_mboxes = $this->list_unsubscribed('', $mailbox . $delm . '*');
3229 $sub_mboxes = $this->list_unsubscribed();
3231 // send delete command to server
3232 $result = $this->conn->deleteFolder($mailbox);
3235 // unsubscribe mailbox
3236 $this->conn->unsubscribe($mailbox);
3238 foreach ($sub_mboxes as $c_mbox) {
3239 if (preg_match('/^'.preg_quote($mailbox.$delm, '/').'/', $c_mbox)) {
3240 $this->conn->unsubscribe($c_mbox);
3241 if ($this->conn->deleteFolder($c_mbox)) {
3242 $this->clear_message_cache($c_mbox.'.msg');
3247 // clear mailbox-related cache
3248 $this->clear_message_cache($mailbox.'.msg');
3249 $this->clear_cache('mailboxes');
3257 * Create all folders specified as default
3259 function create_default_folders()
3261 // create default folders if they do not exist
3262 foreach ($this->default_folders as $folder) {
3263 if (!$this->mailbox_exists($folder))
3264 $this->create_mailbox($folder, true);
3265 else if (!$this->mailbox_exists($folder, true))
3266 $this->subscribe($folder);
3272 * Checks if folder exists and is subscribed
3274 * @param string $mbox_name Folder name
3275 * @param boolean $subscription Enable subscription checking
3276 * @return boolean TRUE or FALSE
3278 function mailbox_exists($mbox_name, $subscription=false)
3280 if ($mbox_name == 'INBOX')
3283 $key = $subscription ? 'subscribed' : 'existing';
3284 $mbox = $this->mod_mailbox($mbox_name);
3286 if (is_array($this->icache[$key]) && in_array($mbox, $this->icache[$key]))
3289 if ($subscription) {
3290 $a_folders = $this->conn->listSubscribed('', $mbox);
3293 $a_folders = $this->conn->listMailboxes('', $mbox);
3296 if (is_array($a_folders) && in_array($mbox, $a_folders)) {
3297 $this->icache[$key][] = $mbox;
3306 * Modify folder name for input/output according to root dir and namespace
3308 * @param string $mbox_name Folder name
3309 * @param string $mode Mode
3310 * @return string Folder name
3312 function mod_mailbox($mbox_name, $mode='in')
3314 if (!strlen($mbox_name))
3317 if ($mode == 'in') {
3318 // If folder contains namespace prefix, don't modify it
3319 if (is_array($this->namespace['shared'])) {
3320 foreach ($this->namespace['shared'] as $ns) {
3321 if ($ns[0] && strpos($mbox_name, $ns[0]) === 0) {
3326 if (is_array($this->namespace['other'])) {
3327 foreach ($this->namespace['other'] as $ns) {
3328 if ($ns[0] && strpos($mbox_name, $ns[0]) === 0) {
3333 if (is_array($this->namespace['personal'])) {
3334 foreach ($this->namespace['personal'] as $ns) {
3335 if ($ns[0] && strpos($mbox_name, $ns[0]) === 0) {
3339 // Add prefix if first personal namespace is non-empty
3340 if ($mbox_name != 'INBOX' && $this->namespace['personal'][0][0]) {
3341 return $this->namespace['personal'][0][0].$mbox_name;
3346 // Remove prefix if folder is from first ("non-empty") personal namespace
3347 if (is_array($this->namespace['personal'])) {
3348 if ($prefix = $this->namespace['personal'][0][0]) {
3349 if (strpos($mbox_name, $prefix) === 0) {
3350 return substr($mbox_name, strlen($prefix));
3361 * Gets folder options from LIST response, e.g. \Noselect, \Noinferiors
3363 * @param string $mbox_name Folder name
3364 * @param bool $force Set to True if options should be refreshed
3365 * Options are available after LIST command only
3367 * @return array Options list
3369 function mailbox_options($mbox_name, $force=false)
3371 $mbox = $this->mod_mailbox($mbox_name);
3373 if ($mbox == 'INBOX') {
3377 if (!is_array($this->conn->data['LIST']) || !is_array($this->conn->data['LIST'][$mbox])) {
3379 $this->conn->listMailboxes('', $mbox_name);
3386 $opts = $this->conn->data['LIST'][$mbox];
3388 return is_array($opts) ? $opts : array();
3393 * Get message header names for rcube_imap_generic::fetchHeader(s)
3395 * @return string Space-separated list of header names
3397 private function get_fetch_headers()
3399 $headers = explode(' ', $this->fetch_add_headers);
3400 $headers = array_map('strtoupper', $headers);
3402 if ($this->caching_enabled || $this->get_all_headers)
3403 $headers = array_merge($headers, $this->all_headers);
3405 return implode(' ', array_unique($headers));
3409 /* -----------------------------------------
3410 * ACL and METADATA/ANNOTATEMORE methods
3411 * ----------------------------------------*/
3414 * Changes the ACL on the specified mailbox (SETACL)
3416 * @param string $mailbox Mailbox name
3417 * @param string $user User name
3418 * @param string $acl ACL string
3420 * @return boolean True on success, False on failure
3425 function set_acl($mailbox, $user, $acl)
3427 $mailbox = $this->mod_mailbox($mailbox);
3429 if ($this->get_capability('ACL'))
3430 return $this->conn->setACL($mailbox, $user, $acl);
3437 * Removes any <identifier,rights> pair for the
3438 * specified user from the ACL for the specified
3439 * mailbox (DELETEACL)
3441 * @param string $mailbox Mailbox name
3442 * @param string $user User name
3444 * @return boolean True on success, False on failure
3449 function delete_acl($mailbox, $user)
3451 $mailbox = $this->mod_mailbox($mailbox);
3453 if ($this->get_capability('ACL'))
3454 return $this->conn->deleteACL($mailbox, $user);
3461 * Returns the access control list for mailbox (GETACL)
3463 * @param string $mailbox Mailbox name
3465 * @return array User-rights array on success, NULL on error
3469 function get_acl($mailbox)
3471 $mailbox = $this->mod_mailbox($mailbox);
3473 if ($this->get_capability('ACL'))
3474 return $this->conn->getACL($mailbox);
3481 * Returns information about what rights can be granted to the
3482 * user (identifier) in the ACL for the mailbox (LISTRIGHTS)
3484 * @param string $mailbox Mailbox name
3485 * @param string $user User name
3487 * @return array List of user rights
3491 function list_rights($mailbox, $user)
3493 $mailbox = $this->mod_mailbox($mailbox);
3495 if ($this->get_capability('ACL'))
3496 return $this->conn->listRights($mailbox, $user);
3503 * Returns the set of rights that the current user has to
3504 * mailbox (MYRIGHTS)
3506 * @param string $mailbox Mailbox name
3508 * @return array MYRIGHTS response on success, NULL on error
3512 function my_rights($mailbox)
3514 $mailbox = $this->mod_mailbox($mailbox);
3516 if ($this->get_capability('ACL'))
3517 return $this->conn->myRights($mailbox);
3524 * Sets IMAP metadata/annotations (SETMETADATA/SETANNOTATION)
3526 * @param string $mailbox Mailbox name (empty for server metadata)
3527 * @param array $entries Entry-value array (use NULL value as NIL)
3529 * @return boolean True on success, False on failure
3533 function set_metadata($mailbox, $entries)
3536 $mailbox = $this->mod_mailbox($mailbox);
3538 if ($this->get_capability('METADATA') ||
3539 (!strlen($mailbox) && $this->get_capability('METADATA-SERVER'))
3541 return $this->conn->setMetadata($mailbox, $entries);
3543 else if ($this->get_capability('ANNOTATEMORE') || $this->get_capability('ANNOTATEMORE2')) {
3544 foreach ($entries as $entry => $value) {
3545 list($ent, $attr) = $this->md2annotate($entry);
3546 $entries[$entry] = array($ent, $attr, $value);
3548 return $this->conn->setAnnotation($mailbox, $entries);
3556 * Unsets IMAP metadata/annotations (SETMETADATA/SETANNOTATION)
3558 * @param string $mailbox Mailbox name (empty for server metadata)
3559 * @param array $entries Entry names array
3561 * @return boolean True on success, False on failure
3566 function delete_metadata($mailbox, $entries)
3569 $mailbox = $this->mod_mailbox($mailbox);
3571 if ($this->get_capability('METADATA') ||
3572 (!strlen($mailbox) && $this->get_capability('METADATA-SERVER'))
3574 return $this->conn->deleteMetadata($mailbox, $entries);
3576 else if ($this->get_capability('ANNOTATEMORE') || $this->get_capability('ANNOTATEMORE2')) {
3577 foreach ($entries as $idx => $entry) {
3578 list($ent, $attr) = $this->md2annotate($entry);
3579 $entries[$idx] = array($ent, $attr, NULL);
3581 return $this->conn->setAnnotation($mailbox, $entries);
3589 * Returns IMAP metadata/annotations (GETMETADATA/GETANNOTATION)
3591 * @param string $mailbox Mailbox name (empty for server metadata)
3592 * @param array $entries Entries
3593 * @param array $options Command options (with MAXSIZE and DEPTH keys)
3595 * @return array Metadata entry-value hash array on success, NULL on error
3600 function get_metadata($mailbox, $entries, $options=array())
3603 $mailbox = $this->mod_mailbox($mailbox);
3605 if ($this->get_capability('METADATA') ||
3606 !strlen(($mailbox) && $this->get_capability('METADATA-SERVER'))
3608 return $this->conn->getMetadata($mailbox, $entries, $options);
3610 else if ($this->get_capability('ANNOTATEMORE') || $this->get_capability('ANNOTATEMORE2')) {
3614 // Convert entry names
3615 foreach ($entries as $entry) {
3616 list($ent, $attr) = $this->md2annotate($entry);
3617 $queries[$attr][] = $ent;
3620 // @TODO: Honor MAXSIZE and DEPTH options
3621 foreach ($queries as $attrib => $entry)
3622 if ($result = $this->conn->getAnnotation($mailbox, $entry, $attrib))
3623 $res = array_merge($res, $result);
3633 * Converts the METADATA extension entry name into the correct
3634 * entry-attrib names for older ANNOTATEMORE version.
3636 * @param string Entry name
3638 * @return array Entry-attribute list, NULL if not supported (?)
3640 private function md2annotate($name)
3642 if (substr($entry, 0, 7) == '/shared') {
3643 return array(substr($entry, 7), 'value.shared');
3645 else if (substr($entry, 0, 8) == '/private') {
3646 return array(substr($entry, 8), 'value.priv');
3654 /* --------------------------------
3655 * internal caching methods
3656 * --------------------------------*/
3659 * Enable or disable caching
3661 * @param boolean $set Flag
3664 function set_caching($set)
3666 if ($set && is_object($this->db))
3667 $this->caching_enabled = true;
3669 $this->caching_enabled = false;
3674 * Returns cached value
3676 * @param string $key Cache key
3680 function get_cache($key)
3682 // read cache (if it was not read before)
3683 if (!count($this->cache) && $this->caching_enabled) {
3684 return $this->_read_cache_record($key);
3687 return $this->cache[$key];
3694 * @param string $key Cache key
3695 * @param mixed $data Data
3698 private function update_cache($key, $data)
3700 $this->cache[$key] = $data;
3701 $this->cache_changed = true;
3702 $this->cache_changes[$key] = true;
3711 private function write_cache()
3713 if ($this->caching_enabled && $this->cache_changed) {
3714 foreach ($this->cache as $key => $data) {
3715 if ($this->cache_changes[$key])
3716 $this->_write_cache_record($key, serialize($data));
3725 * @param string $key Cache key
3728 function clear_cache($key=NULL)
3730 if (!$this->caching_enabled)
3734 foreach ($this->cache as $key => $data)
3735 $this->_clear_cache_record($key);
3737 $this->cache = array();
3738 $this->cache_changed = false;
3739 $this->cache_changes = array();
3742 $this->_clear_cache_record($key);
3743 $this->cache_changes[$key] = false;
3744 unset($this->cache[$key]);
3750 * Returns cached entry
3752 * @param string $key Cache key
3753 * @return mixed Cached value
3756 private function _read_cache_record($key)
3759 // get cached data from DB
3760 $sql_result = $this->db->query(
3761 "SELECT cache_id, data, cache_key ".
3762 "FROM ".get_table_name('cache').
3763 " WHERE user_id=? ".
3764 "AND cache_key LIKE 'IMAP.%'",
3765 $_SESSION['user_id']);
3767 while ($sql_arr = $this->db->fetch_assoc($sql_result)) {
3768 $sql_key = preg_replace('/^IMAP\./', '', $sql_arr['cache_key']);
3769 $this->cache_keys[$sql_key] = $sql_arr['cache_id'];
3770 if (!isset($this->cache[$sql_key]))
3771 $this->cache[$sql_key] = $sql_arr['data'] ? unserialize($sql_arr['data']) : false;
3775 return $this->cache[$key];
3780 * Writes single cache record
3782 * @param string $key Cache key
3783 * @param mxied $data Cache value
3786 private function _write_cache_record($key, $data)
3791 // update existing cache record
3792 if ($this->cache_keys[$key]) {
3794 "UPDATE ".get_table_name('cache').
3795 " SET created=". $this->db->now().", data=? ".
3799 $_SESSION['user_id'],
3802 // add new cache record
3805 "INSERT INTO ".get_table_name('cache').
3806 " (created, user_id, cache_key, data) ".
3807 "VALUES (".$this->db->now().", ?, ?, ?)",
3808 $_SESSION['user_id'],
3812 // get cache entry ID for this key
3813 $sql_result = $this->db->query(
3815 "FROM ".get_table_name('cache').
3816 " WHERE user_id=? ".
3818 $_SESSION['user_id'],
3821 if ($sql_arr = $this->db->fetch_assoc($sql_result))
3822 $this->cache_keys[$key] = $sql_arr['cache_id'];
3828 * Clears cache for single record
3830 * @param string $ket Cache key
3833 private function _clear_cache_record($key)
3836 "DELETE FROM ".get_table_name('cache').
3837 " WHERE user_id=? ".
3839 $_SESSION['user_id'],
3842 unset($this->cache_keys[$key]);
3847 /* --------------------------------
3848 * message caching methods
3849 * --------------------------------*/
3852 * Checks if the cache is up-to-date
3854 * @param string $mailbox Mailbox name
3855 * @param string $cache_key Internal cache key
3856 * @return int Cache status: -3 = off, -2 = incomplete, -1 = dirty, 1 = OK
3858 private function check_cache_status($mailbox, $cache_key)
3860 if (!$this->caching_enabled)
3863 $cache_index = $this->get_message_cache_index($cache_key);
3864 $msg_count = $this->_messagecount($mailbox);
3865 $cache_count = count($cache_index);
3869 return $cache_count ? -2 : 1;
3872 if ($cache_count == $msg_count) {
3873 if ($this->skip_deleted) {
3874 if (!empty($this->icache['all_undeleted_idx'])) {
3875 $uids = rcube_imap_generic::uncompressMessageSet($this->icache['all_undeleted_idx']);
3876 $uids = array_flip($uids);
3877 foreach ($cache_index as $uid) {
3882 // get all undeleted messages excluding cached UIDs
3883 $uids = $this->search_once($mailbox, 'ALL UNDELETED NOT UID '.
3884 rcube_imap_generic::compressMessageSet($cache_index));
3890 // get UID of the message with highest index
3891 $uid = $this->_id2uid($msg_count, $mailbox);
3892 $cache_uid = array_pop($cache_index);
3894 // uids of highest message matches -> cache seems OK
3895 if ($cache_uid == $uid) {
3903 // if cache count differs less than 10% report as dirty
3904 return (abs($msg_count - $cache_count) < $msg_count/10) ? -1 : -2;
3909 * @param string $key Cache key
3910 * @param string $from
3912 * @param string $sort_field
3913 * @param string $sort_order
3916 private function get_message_cache($key, $from, $to, $sort_field, $sort_order)
3918 if (!$this->caching_enabled)
3921 // use idx sort as default sorting
3922 if (!$sort_field || !in_array($sort_field, $this->db_header_fields)) {
3923 $sort_field = 'idx';
3928 $sql_result = $this->db->limitquery(
3929 "SELECT idx, uid, headers".
3930 " FROM ".get_table_name('messages').
3933 " ORDER BY ".$this->db->quoteIdentifier($sort_field)." ".strtoupper($sort_order),
3936 $_SESSION['user_id'],
3939 while ($sql_arr = $this->db->fetch_assoc($sql_result)) {
3940 $uid = intval($sql_arr['uid']);
3941 $result[$uid] = $this->db->decode(unserialize($sql_arr['headers']));
3943 // featch headers if unserialize failed
3944 if (empty($result[$uid]))
3945 $result[$uid] = $this->conn->fetchHeader(
3946 preg_replace('/.msg$/', '', $key), $uid, true, false, $this->get_fetch_headers());
3954 * @param string $key Cache key
3955 * @param int $uid Message UID
3959 private function &get_cached_message($key, $uid)
3961 $internal_key = 'message';
3963 if ($this->caching_enabled && !isset($this->icache[$internal_key][$uid])) {
3964 $sql_result = $this->db->query(
3965 "SELECT idx, headers, structure, message_id".
3966 " FROM ".get_table_name('messages').
3970 $_SESSION['user_id'],
3974 if ($sql_arr = $this->db->fetch_assoc($sql_result)) {
3975 $this->icache['message.id'][$uid] = intval($sql_arr['message_id']);
3976 $this->uid_id_map[preg_replace('/\.msg$/', '', $key)][$uid] = intval($sql_arr['idx']);
3977 $this->icache[$internal_key][$uid] = $this->db->decode(unserialize($sql_arr['headers']));
3979 if (is_object($this->icache[$internal_key][$uid]) && !empty($sql_arr['structure']))
3980 $this->icache[$internal_key][$uid]->structure = $this->db->decode(unserialize($sql_arr['structure']));
3984 return $this->icache[$internal_key][$uid];
3989 * @param string $key Cache key
3990 * @param string $sort_field Sorting column
3991 * @param string $sort_order Sorting order
3992 * @return array Messages index
3995 private function get_message_cache_index($key, $sort_field='idx', $sort_order='ASC')
3997 if (!$this->caching_enabled || empty($key))
4000 // use idx sort as default
4001 if (!$sort_field || !in_array($sort_field, $this->db_header_fields))
4002 $sort_field = 'idx';
4004 if (array_key_exists('index', $this->icache)
4005 && $this->icache['index']['key'] == $key
4006 && $this->icache['index']['sort_field'] == $sort_field
4008 if ($this->icache['index']['sort_order'] == $sort_order)
4009 return $this->icache['index']['result'];
4011 return array_reverse($this->icache['index']['result'], true);
4014 $this->icache['index'] = array(
4015 'result' => array(),
4017 'sort_field' => $sort_field,
4018 'sort_order' => $sort_order,
4021 $sql_result = $this->db->query(
4023 " FROM ".get_table_name('messages').
4026 " ORDER BY ".$this->db->quote_identifier($sort_field)." ".$sort_order,
4027 $_SESSION['user_id'],
4030 while ($sql_arr = $this->db->fetch_assoc($sql_result))
4031 $this->icache['index']['result'][$sql_arr['idx']] = intval($sql_arr['uid']);
4033 return $this->icache['index']['result'];
4040 private function add_message_cache($key, $index, $headers, $struct=null, $force=false, $internal_cache=false)
4042 if (empty($key) || !is_object($headers) || empty($headers->uid))
4045 // add to internal (fast) cache
4046 if ($internal_cache) {
4047 $this->icache['message'][$headers->uid] = clone $headers;
4048 $this->icache['message'][$headers->uid]->structure = $struct;
4051 // no further caching
4052 if (!$this->caching_enabled)
4056 if (is_int($force) && $force > 0) {
4057 $message_id = $force;
4059 // check for an existing record (probably headers are cached but structure not)
4061 $sql_result = $this->db->query(
4062 "SELECT message_id".
4063 " FROM ".get_table_name('messages').
4067 $_SESSION['user_id'],
4071 if ($sql_arr = $this->db->fetch_assoc($sql_result))
4072 $message_id = $sql_arr['message_id'];
4075 // update cache record
4078 "UPDATE ".get_table_name('messages').
4079 " SET idx=?, headers=?, structure=?".
4080 " WHERE message_id=?",
4082 serialize($this->db->encode(clone $headers)),
4083 is_object($struct) ? serialize($this->db->encode(clone $struct)) : NULL,
4087 else { // insert new record
4089 "INSERT INTO ".get_table_name('messages').
4090 " (user_id, del, cache_key, created, idx, uid, subject, ".
4091 $this->db->quoteIdentifier('from').", ".
4092 $this->db->quoteIdentifier('to').", ".
4093 "cc, date, size, headers, structure)".
4094 " VALUES (?, 0, ?, ".$this->db->now().", ?, ?, ?, ?, ?, ?, ".
4095 $this->db->fromunixtime($headers->timestamp).", ?, ?, ?)",
4096 $_SESSION['user_id'],
4100 (string)mb_substr($this->db->encode($this->decode_header($headers->subject, true)), 0, 128),
4101 (string)mb_substr($this->db->encode($this->decode_header($headers->from, true)), 0, 128),
4102 (string)mb_substr($this->db->encode($this->decode_header($headers->to, true)), 0, 128),
4103 (string)mb_substr($this->db->encode($this->decode_header($headers->cc, true)), 0, 128),
4104 (int)$headers->size,
4105 serialize($this->db->encode(clone $headers)),
4106 is_object($struct) ? serialize($this->db->encode(clone $struct)) : NULL
4110 unset($this->icache['index']);
4117 private function remove_message_cache($key, $ids, $idx=false)
4119 if (!$this->caching_enabled)
4123 "DELETE FROM ".get_table_name('messages').
4126 " AND ".($idx ? "idx" : "uid")." IN (".$this->db->array2list($ids, 'integer').")",
4127 $_SESSION['user_id'],
4130 unset($this->icache['index']);
4135 * @param string $key Cache key
4136 * @param int $start_index Start index
4139 private function clear_message_cache($key, $start_index=1)
4141 if (!$this->caching_enabled)
4145 "DELETE FROM ".get_table_name('messages').
4149 $_SESSION['user_id'], $key, $start_index);
4151 unset($this->icache['index']);
4158 private function get_message_cache_index_min($key, $uids=NULL)
4160 if (!$this->caching_enabled)
4163 if (!empty($uids) && !is_array($uids)) {
4164 if ($uids == '*' || $uids == '1:*')
4167 $uids = explode(',', $uids);
4170 $sql_result = $this->db->query(
4171 "SELECT MIN(idx) AS minidx".
4172 " FROM ".get_table_name('messages').
4175 .(!empty($uids) ? " AND uid IN (".$this->db->array2list($uids, 'integer').")" : ''),
4176 $_SESSION['user_id'],
4179 if ($sql_arr = $this->db->fetch_assoc($sql_result))
4180 return $sql_arr['minidx'];
4187 * @param string $key Cache key
4188 * @param int $id Message (sequence) ID
4189 * @return int Message UID
4192 private function get_cache_id2uid($key, $id)
4194 if (!$this->caching_enabled)
4197 if (array_key_exists('index', $this->icache)
4198 && $this->icache['index']['key'] == $key
4200 return $this->icache['index']['result'][$id];
4203 $sql_result = $this->db->query(
4205 " FROM ".get_table_name('messages').
4209 $_SESSION['user_id'], $key, $id);
4211 if ($sql_arr = $this->db->fetch_assoc($sql_result))
4212 return intval($sql_arr['uid']);
4219 * @param string $key Cache key
4220 * @param int $uid Message UID
4221 * @return int Message (sequence) ID
4224 private function get_cache_uid2id($key, $uid)
4226 if (!$this->caching_enabled)
4229 if (array_key_exists('index', $this->icache)
4230 && $this->icache['index']['key'] == $key
4232 return array_search($uid, $this->icache['index']['result']);
4235 $sql_result = $this->db->query(
4237 " FROM ".get_table_name('messages').
4241 $_SESSION['user_id'], $key, $uid);
4243 if ($sql_arr = $this->db->fetch_assoc($sql_result))
4244 return intval($sql_arr['idx']);
4250 /* --------------------------------
4251 * encoding/decoding methods
4252 * --------------------------------*/
4255 * Split an address list into a structured array list
4257 * @param string $input Input string
4258 * @param int $max List only this number of addresses
4259 * @param boolean $decode Decode address strings
4260 * @return array Indexed list of addresses
4262 function decode_address_list($input, $max=null, $decode=true)
4264 $a = $this->_parse_address_list($input, $decode);
4266 // Special chars as defined by RFC 822 need to in quoted string (or escaped).
4267 $special_chars = '[\(\)\<\>\\\.\[\]@,;:"]';
4275 foreach ($a as $val) {
4277 $address = trim($val['address']);
4278 $name = trim($val['name']);
4280 if ($name && $address && $name != $address)
4281 $string = sprintf('%s <%s>', preg_match("/$special_chars/", $name) ? '"'.addcslashes($name, '"').'"' : $name, $address);
4289 'mailto' => $address,
4293 if ($max && $j==$max)
4302 * Decode a message header value
4304 * @param string $input Header value
4305 * @param boolean $remove_quotas Remove quotes if necessary
4306 * @return string Decoded string
4308 function decode_header($input, $remove_quotes=false)
4310 $str = rcube_imap::decode_mime_string((string)$input, $this->default_charset);
4311 if ($str[0] == '"' && $remove_quotes)
4312 $str = str_replace('"', '', $str);
4319 * Decode a mime-encoded string to internal charset
4321 * @param string $input Header value
4322 * @param string $fallback Fallback charset if none specified
4324 * @return string Decoded string
4327 public static function decode_mime_string($input, $fallback=null)
4329 // Initialize variable
4332 // Iterate instead of recursing, this way if there are too many values we don't have stack overflows
4333 // rfc: all line breaks or other characters not found
4334 // in the Base64 Alphabet must be ignored by decoding software
4335 // delete all blanks between MIME-lines, differently we can
4336 // receive unnecessary blanks and broken utf-8 symbols
4337 $input = preg_replace("/\?=\s+=\?/", '?==?', $input);
4339 // Check if there is stuff to decode
4340 if (strpos($input, '=?') !== false) {
4341 // Loop through the string to decode all occurences of =? ?= into the variable $out
4342 while(($pos = strpos($input, '=?')) !== false) {
4343 // Append everything that is before the text to be decoded
4344 $out .= substr($input, 0, $pos);
4346 // Get the location of the text to decode
4347 $end_cs_pos = strpos($input, "?", $pos+2);
4348 $end_en_pos = strpos($input, "?", $end_cs_pos+1);
4349 $end_pos = strpos($input, "?=", $end_en_pos+1);
4351 // Extract the encoded string
4352 $encstr = substr($input, $pos+2, ($end_pos-$pos-2));
4353 // Extract the remaining string
4354 $input = substr($input, $end_pos+2);
4356 // Decode the string fragement
4357 $out .= rcube_imap::_decode_mime_string_part($encstr);
4360 // Deocde the rest (if any)
4361 if (strlen($input) != 0)
4362 $out .= rcube_imap::decode_mime_string($input, $fallback);
4364 // return the results
4368 // no encoding information, use fallback
4369 return rcube_charset_convert($input,
4370 !empty($fallback) ? $fallback : rcmail::get_instance()->config->get('default_charset', 'ISO-8859-1'));
4375 * Decode a part of a mime-encoded string
4377 * @param string $str String to decode
4378 * @return string Decoded string
4381 private function _decode_mime_string_part($str)
4383 $a = explode('?', $str);
4386 // should be in format "charset?encoding?base64_string"
4388 for ($i=2; $i<$count; $i++)
4391 if (($a[1]=='B') || ($a[1]=='b'))
4392 $rest = base64_decode($rest);
4393 else if (($a[1]=='Q') || ($a[1]=='q')) {
4394 $rest = str_replace('_', ' ', $rest);
4395 $rest = quoted_printable_decode($rest);
4398 return rcube_charset_convert($rest, $a[0]);
4401 // we dont' know what to do with this
4407 * Decode a mime part
4409 * @param string $input Input string
4410 * @param string $encoding Part encoding
4411 * @return string Decoded string
4413 function mime_decode($input, $encoding='7bit')
4415 switch (strtolower($encoding)) {
4416 case 'quoted-printable':
4417 return quoted_printable_decode($input);
4419 return base64_decode($input);
4424 return convert_uudecode($input);
4433 * Convert body charset to RCMAIL_CHARSET according to the ctype_parameters
4435 * @param string $body Part body to decode
4436 * @param string $ctype_param Charset to convert from
4437 * @return string Content converted to internal charset
4439 function charset_decode($body, $ctype_param)
4441 if (is_array($ctype_param) && !empty($ctype_param['charset']))
4442 return rcube_charset_convert($body, $ctype_param['charset']);
4444 // defaults to what is specified in the class header
4445 return rcube_charset_convert($body, $this->default_charset);
4449 /* --------------------------------
4451 * --------------------------------*/
4454 * Validate the given input and save to local properties
4456 * @param string $sort_field Sort column
4457 * @param string $sort_order Sort order
4460 private function _set_sort_order($sort_field, $sort_order)
4462 if ($sort_field != null)
4463 $this->sort_field = asciiwords($sort_field);
4464 if ($sort_order != null)
4465 $this->sort_order = strtoupper($sort_order) == 'DESC' ? 'DESC' : 'ASC';
4470 * Sort mailboxes first by default folders and then in alphabethical order
4472 * @param array $a_folders Mailboxes list
4475 private function _sort_mailbox_list($a_folders)
4477 $a_out = $a_defaults = $folders = array();
4479 $delimiter = $this->get_hierarchy_delimiter();
4481 // find default folders and skip folders starting with '.'
4482 foreach ($a_folders as $i => $folder) {
4483 if ($folder[0] == '.')
4486 if (($p = array_search($folder, $this->default_folders)) !== false && !$a_defaults[$p])
4487 $a_defaults[$p] = $folder;
4489 $folders[$folder] = rcube_charset_convert($folder, 'UTF7-IMAP');
4492 // sort folders and place defaults on the top
4493 asort($folders, SORT_LOCALE_STRING);
4495 $folders = array_merge($a_defaults, array_keys($folders));
4497 // finally we must rebuild the list to move
4498 // subfolders of default folders to their place...
4499 // ...also do this for the rest of folders because
4500 // asort() is not properly sorting case sensitive names
4501 while (list($key, $folder) = each($folders)) {
4502 // set the type of folder name variable (#1485527)
4503 $a_out[] = (string) $folder;
4504 unset($folders[$key]);
4505 $this->_rsort($folder, $delimiter, $folders, $a_out);
4515 private function _rsort($folder, $delimiter, &$list, &$out)
4517 while (list($key, $name) = each($list)) {
4518 if (strpos($name, $folder.$delimiter) === 0) {
4519 // set the type of folder name variable (#1485527)
4520 $out[] = (string) $name;
4522 $this->_rsort($name, $delimiter, $list, $out);
4530 * @param int $uid Message UID
4531 * @param string $mbox_name Mailbox name
4532 * @return int Message (sequence) ID
4535 private function _uid2id($uid, $mbox_name=NULL)
4537 if (!strlen($mbox_name))
4538 $mbox_name = $this->mailbox;
4540 if (!isset($this->uid_id_map[$mbox_name][$uid])) {
4541 if (!($id = $this->get_cache_uid2id($mbox_name.'.msg', $uid)))
4542 $id = $this->conn->UID2ID($mbox_name, $uid);
4544 $this->uid_id_map[$mbox_name][$uid] = $id;
4547 return $this->uid_id_map[$mbox_name][$uid];
4552 * @param int $id Message (sequence) ID
4553 * @param string $mbox_name Mailbox name
4554 * @return int Message UID
4557 private function _id2uid($id, $mbox_name=NULL)
4559 if (!strlen($mbox_name))
4560 $mbox_name = $this->mailbox;
4562 if ($uid = array_search($id, (array)$this->uid_id_map[$mbox_name]))
4565 if (!($uid = $this->get_cache_id2uid($mbox_name.'.msg', $id)))
4566 $uid = $this->conn->ID2UID($mbox_name, $id);
4568 $this->uid_id_map[$mbox_name][$uid] = $id;
4575 * Subscribe/unsubscribe a list of mailboxes and update local cache
4578 private function _change_subscription($a_mboxes, $mode)
4582 if (is_array($a_mboxes))
4583 foreach ($a_mboxes as $i => $mbox_name) {
4584 $mailbox = $this->mod_mailbox($mbox_name);
4585 $a_mboxes[$i] = $mailbox;
4587 if ($mode=='subscribe')
4588 $updated = $this->conn->subscribe($mailbox);
4589 else if ($mode=='unsubscribe')
4590 $updated = $this->conn->unsubscribe($mailbox);
4593 // get cached mailbox list
4595 $a_mailbox_cache = $this->get_cache('mailboxes');
4596 if (!is_array($a_mailbox_cache))
4599 // modify cached list
4600 if ($mode=='subscribe')
4601 $a_mailbox_cache = array_merge($a_mailbox_cache, $a_mboxes);
4602 else if ($mode=='unsubscribe')
4603 $a_mailbox_cache = array_diff($a_mailbox_cache, $a_mboxes);
4605 // write mailboxlist to cache
4606 $this->update_cache('mailboxes', $this->_sort_mailbox_list($a_mailbox_cache));
4614 * Increde/decrese messagecount for a specific mailbox
4617 private function _set_messagecount($mbox_name, $mode, $increment)
4619 $a_mailbox_cache = false;
4620 $mailbox = strlen($mbox_name) ? $mbox_name : $this->mailbox;
4621 $mode = strtoupper($mode);
4623 $a_mailbox_cache = $this->get_cache('messagecount');
4625 if (!is_array($a_mailbox_cache[$mailbox]) || !isset($a_mailbox_cache[$mailbox][$mode]) || !is_numeric($increment))
4628 // add incremental value to messagecount
4629 $a_mailbox_cache[$mailbox][$mode] += $increment;
4631 // there's something wrong, delete from cache
4632 if ($a_mailbox_cache[$mailbox][$mode] < 0)
4633 unset($a_mailbox_cache[$mailbox][$mode]);
4635 // write back to cache
4636 $this->update_cache('messagecount', $a_mailbox_cache);
4643 * Remove messagecount of a specific mailbox from cache
4646 private function _clear_messagecount($mbox_name='', $mode=null)
4648 $mailbox = strlen($mbox_name) ? $mbox_name : $this->mailbox;
4650 $a_mailbox_cache = $this->get_cache('messagecount');
4652 if (is_array($a_mailbox_cache[$mailbox])) {
4654 unset($a_mailbox_cache[$mailbox][$mode]);
4657 unset($a_mailbox_cache[$mailbox]);
4659 $this->update_cache('messagecount', $a_mailbox_cache);
4665 * Split RFC822 header string into an associative array
4668 private function _parse_headers($headers)
4670 $a_headers = array();
4671 $headers = preg_replace('/\r?\n(\t| )+/', ' ', $headers);
4672 $lines = explode("\n", $headers);
4675 for ($i=0; $i<$c; $i++) {
4676 if ($p = strpos($lines[$i], ': ')) {
4677 $field = strtolower(substr($lines[$i], 0, $p));
4678 $value = trim(substr($lines[$i], $p+1));
4680 $a_headers[$field] = $value;
4691 private function _parse_address_list($str, $decode=true)
4693 // remove any newlines and carriage returns before
4694 $a = rcube_explode_quoted_string('[,;]', preg_replace( "/[\r\n]/", " ", $str));
4697 foreach ($a as $key => $val) {
4702 if (preg_match('/(.*)<(\S+@\S+)>$/', $val, $m)) {
4704 $name = trim($m[1]);
4706 else if (preg_match('/^(\S+@\S+)$/', $val, $m)) {
4714 // dequote and/or decode name
4716 if ($name[0] == '"') {
4717 $name = substr($name, 1, -1);
4718 $name = stripslashes($name);
4721 $name = $this->decode_header($name);
4725 if (!$address && $name) {
4730 $result[$key] = array('name' => $name, 'address' => $address);
4739 * This is our own debug handler for the IMAP connection
4742 public function debug_handler(&$imap, $message)
4744 write_log('imap', $message);
4747 } // end class rcube_imap
4751 * Class representing a message part
4755 class rcube_message_part
4758 var $ctype_primary = 'text';
4759 var $ctype_secondary = 'plain';
4760 var $mimetype = 'text/plain';
4761 var $disposition = '';
4763 var $encoding = '8bit';
4766 var $headers = array();
4767 var $d_parameters = array();
4768 var $ctype_parameters = array();
4772 if (isset($this->parts))
4773 foreach ($this->parts as $idx => $part)
4774 if (is_object($part))
4775 $this->parts[$idx] = clone $part;
4781 * Class for sorting an array of rcube_mail_header objects in a predetermined order.
4784 * @author Eric Stadtherr
4786 class rcube_header_sorter
4788 var $sequence_numbers = array();
4791 * Set the predetermined sort order.
4793 * @param array $seqnums Numerically indexed array of IMAP message sequence numbers
4795 function set_sequence_numbers($seqnums)
4797 $this->sequence_numbers = array_flip($seqnums);
4801 * Sort the array of header objects
4803 * @param array $headers Array of rcube_mail_header objects indexed by UID
4805 function sort_headers(&$headers)
4808 * uksort would work if the keys were the sequence number, but unfortunately
4809 * the keys are the UIDs. We'll use uasort instead and dereference the value
4810 * to get the sequence number (in the "id" field).
4812 * uksort($headers, array($this, "compare_seqnums"));
4814 uasort($headers, array($this, "compare_seqnums"));
4818 * Sort method called by uasort()
4820 * @param rcube_mail_header $a
4821 * @param rcube_mail_header $b
4823 function compare_seqnums($a, $b)
4825 // First get the sequence number from the header object (the 'id' field).
4829 // then find each sequence number in my ordered list
4830 $posa = isset($this->sequence_numbers[$seqa]) ? intval($this->sequence_numbers[$seqa]) : -1;
4831 $posb = isset($this->sequence_numbers[$seqb]) ? intval($this->sequence_numbers[$seqb]) : -1;
4833 // return the relative position as the comparison value
4834 return $posa - $posb;