4 +-----------------------------------------------------------------------+
5 | program/include/rcube_imap.php |
7 | This file is part of the RoundCube Webmail client |
8 | Copyright (C) 2005-2008, RoundCube Dev. - Switzerland |
9 | Licensed under the GNU GPL |
12 | IMAP wrapper that implements the Iloha IMAP Library (IIL) |
13 | See http://ilohamail.org/ for details |
15 +-----------------------------------------------------------------------+
16 | Author: Thomas Bruederli <roundcube@gmail.com> |
17 +-----------------------------------------------------------------------+
19 $Id: rcube_imap.php 2189 2008-12-25 08:33:21Z alec $
25 * Obtain classes from the Iloha IMAP library
27 require_once('lib/imap.inc');
28 require_once('lib/mime.inc');
32 * Interface class for accessing an IMAP server
34 * This is a wrapper that implements the Iloha IMAP Library (IIL)
37 * @author Thomas Bruederli <roundcube@gmail.com>
39 * @link http://ilohamail.org
47 var $mailbox = 'INBOX';
50 var $sort_field = 'date';
51 var $sort_order = 'DESC';
52 var $delimiter = NULL;
53 var $caching_enabled = FALSE;
54 var $default_charset = 'ISO-8859-1';
55 var $default_folders = array('INBOX');
56 var $default_folders_lc = array('inbox');
58 var $cache_keys = array();
59 var $cache_changes = array();
60 var $uid_id_map = array();
61 var $msg_headers = array();
62 var $skip_deleted = FALSE;
63 var $search_set = NULL;
64 var $search_string = '';
65 var $search_charset = '';
66 var $search_sort_field = '';
69 var $options = array('imap' => 'check');
75 * @param object DB Database connection
77 function __construct($db_conn)
84 * Connect to an IMAP server
86 * @param string Host to connect
87 * @param string Username for IMAP account
88 * @param string Password for IMAP account
89 * @param number Port to connect to
90 * @param string SSL schema (either ssl or tls) or null if plain connection
91 * @return boolean TRUE on success, FALSE on failure
94 function connect($host, $user, $pass, $port=143, $use_ssl=null)
96 global $ICL_SSL, $ICL_PORT, $IMAP_USE_INTERNAL_DATE;
98 // check for Open-SSL support in PHP build
99 if ($use_ssl && in_array('openssl', get_loaded_extensions()))
100 $ICL_SSL = $use_ssl == 'imaps' ? 'ssl' : $use_ssl;
103 raise_error(array('code' => 403, 'type' => 'imap', 'file' => __FILE__,
104 'message' => 'Open SSL not available;'), TRUE, FALSE);
109 $IMAP_USE_INTERNAL_DATE = false;
111 $this->conn = iil_Connect($host, $user, $pass, $this->options);
116 $this->ssl = $use_ssl;
118 // print trace mesages
119 if ($this->conn && ($this->debug_level & 8))
120 console($this->conn->message);
123 else if (!$this->conn && $GLOBALS['iil_error'])
125 $this->error_code = $GLOBALS['iil_errornum'];
126 raise_error(array('code' => 403,
128 'message' => $GLOBALS['iil_error']), TRUE, FALSE);
131 // get server properties
134 if (!empty($this->conn->delimiter))
135 $this->delimiter = $this->conn->delimiter;
136 if (!empty($this->conn->rootdir))
138 $this->set_rootdir($this->conn->rootdir);
139 $this->root_ns = ereg_replace('[\.\/]$', '', $this->conn->rootdir);
143 return $this->conn ? TRUE : FALSE;
148 * Close IMAP connection
149 * Usually done on script shutdown
156 iil_Close($this->conn);
161 * Close IMAP connection and re-connect
162 * This is used to avoid some strange socket errors when talking to Courier IMAP
169 $this->connect($this->host, $this->user, $this->pass, $this->port, $this->ssl);
171 // issue SELECT command to restore connection status
173 iil_C_Select($this->conn, $this->mailbox);
177 * Set options to be used in iil_Connect()
179 function set_options($opt)
181 $this->options = array_merge($this->options, (array)$opt);
185 * Set a root folder for the IMAP connection.
187 * Only folders within this root folder will be displayed
188 * and all folder paths will be translated using this folder name
190 * @param string Root folder
193 function set_rootdir($root)
195 if (ereg('[\.\/]$', $root)) //(substr($root, -1, 1)==='/')
196 $root = substr($root, 0, -1);
198 $this->root_dir = $root;
199 $this->options['rootdir'] = $root;
201 if (empty($this->delimiter))
202 $this->get_hierarchy_delimiter();
207 * Set default message charset
209 * This will be used for message decoding if a charset specification is not available
211 * @param string Charset string
214 function set_charset($cs)
216 $this->default_charset = $cs;
221 * This list of folders will be listed above all other folders
223 * @param array Indexed list of folder names
226 function set_default_mailboxes($arr)
230 $this->default_folders = $arr;
231 $this->default_folders_lc = array();
233 // add inbox if not included
234 if (!in_array_nocase('INBOX', $this->default_folders))
235 array_unshift($this->default_folders, 'INBOX');
237 // create a second list with lower cased names
238 foreach ($this->default_folders as $mbox)
239 $this->default_folders_lc[] = strtolower($mbox);
245 * Set internal mailbox reference.
247 * All operations will be perfomed on this mailbox/folder
249 * @param string Mailbox/Folder name
252 function set_mailbox($new_mbox)
254 $mailbox = $this->_mod_mailbox($new_mbox);
256 if ($this->mailbox == $mailbox)
259 $this->mailbox = $mailbox;
261 // clear messagecount cache for this mailbox
262 $this->_clear_messagecount($mailbox);
267 * Set internal list page
269 * @param number Page number to list
272 function set_page($page)
274 $this->list_page = (int)$page;
279 * Set internal page size
281 * @param number Number of messages to display on one page
284 function set_pagesize($size)
286 $this->page_size = (int)$size;
291 * Save a set of message ids for future message listing methods
293 * @param string IMAP Search query
294 * @param array List of message ids or NULL if empty
295 * @param string Charset of search string
296 * @param string Sorting field
298 function set_search_set($str=null, $msgs=null, $charset=null, $sort_field=null)
300 if (is_array($str) && $msgs == null)
301 list($str, $msgs, $charset, $sort_field) = $str;
302 if ($msgs != null && !is_array($msgs))
303 $msgs = split(',', $msgs);
305 $this->search_string = $str;
306 $this->search_set = $msgs;
307 $this->search_charset = $charset;
308 $this->search_sort_field = $sort_field;
313 * Return the saved search set as hash array
314 * @return array Search set
316 function get_search_set()
318 return array($this->search_string, $this->search_set, $this->search_charset, $this->search_sort_field);
323 * Returns the currently used mailbox name
325 * @return string Name of the mailbox/folder
328 function get_mailbox_name()
330 return $this->conn ? $this->_mod_mailbox($this->mailbox, 'out') : '';
335 * Returns the IMAP server's capability
337 * @param string Capability name
338 * @return mixed Capability value or TRUE if supported, FALSE if not
341 function get_capability($cap)
343 return iil_C_GetCapability($this->conn, strtoupper($cap));
348 * Checks the PERMANENTFLAGS capability of the current mailbox
349 * and returns true if the given flag is supported by the IMAP server
351 * @param string Permanentflag name
352 * @return mixed True if this flag is supported
355 function check_permflag($flag)
357 $flagsmap = $GLOBALS['IMAP_FLAGS'];
358 return (($imap_flag = $flagsmap[strtoupper($flag)]) && in_array_nocase($imap_flag, $this->conn->permanentflags));
363 * Returns the delimiter that is used by the IMAP server for folder separation
365 * @return string Delimiter string
368 function get_hierarchy_delimiter()
370 if ($this->conn && empty($this->delimiter))
371 $this->delimiter = iil_C_GetHierarchyDelimiter($this->conn);
373 if (empty($this->delimiter))
374 $this->delimiter = '/';
376 return $this->delimiter;
381 * Public method for mailbox listing.
383 * Converts mailbox name with root dir first
385 * @param string Optional root folder
386 * @param string Optional filter for mailbox listing
387 * @return array List of mailboxes/folders
390 function list_mailboxes($root='', $filter='*')
393 $a_mboxes = $this->_list_mailboxes($root, $filter);
395 foreach ($a_mboxes as $mbox_row)
397 $name = $this->_mod_mailbox($mbox_row, 'out');
402 // INBOX should always be available
403 if (!in_array_nocase('INBOX', $a_out))
404 array_unshift($a_out, 'INBOX');
407 $a_out = $this->_sort_mailbox_list($a_out);
414 * Private method for mailbox listing
416 * @return array List of mailboxes/folders
417 * @see rcube_imap::list_mailboxes()
420 function _list_mailboxes($root='', $filter='*')
422 $a_defaults = $a_out = array();
424 // get cached folder list
425 $a_mboxes = $this->get_cache('mailboxes');
426 if (is_array($a_mboxes))
429 // retrieve list of folders from IMAP server
430 $a_folders = iil_C_ListSubscribed($this->conn, $this->_mod_mailbox($root), $filter);
432 if (!is_array($a_folders) || !sizeof($a_folders))
433 $a_folders = array();
435 // write mailboxlist to cache
436 $this->update_cache('mailboxes', $a_folders);
443 * Get message count for a specific mailbox
445 * @param string Mailbox/folder name
446 * @param string Mode for count [ALL|UNSEEN|RECENT]
447 * @param boolean Force reading from server and update cache
448 * @return int Number of messages
451 function messagecount($mbox_name='', $mode='ALL', $force=FALSE)
453 $mailbox = $mbox_name ? $this->_mod_mailbox($mbox_name) : $this->mailbox;
454 return $this->_messagecount($mailbox, $mode, $force);
459 * Private method for getting nr of messages
462 * @see rcube_imap::messagecount()
464 function _messagecount($mailbox='', $mode='ALL', $force=FALSE)
466 $a_mailbox_cache = FALSE;
467 $mode = strtoupper($mode);
470 $mailbox = $this->mailbox;
473 if ($this->search_string && $mailbox == $this->mailbox && $mode == 'ALL' && !$force)
474 return count((array)$this->search_set);
476 $a_mailbox_cache = $this->get_cache('messagecount');
478 // return cached value
479 if (!$force && is_array($a_mailbox_cache[$mailbox]) && isset($a_mailbox_cache[$mailbox][$mode]))
480 return $a_mailbox_cache[$mailbox][$mode];
482 // RECENT count is fetched a bit different
483 if ($mode == 'RECENT')
484 $count = iil_C_CheckForRecent($this->conn, $mailbox);
486 // use SEARCH for message counting
487 else if ($this->skip_deleted)
489 $search_str = "ALL UNDELETED";
491 // get message count and store in cache
492 if ($mode == 'UNSEEN')
493 $search_str .= " UNSEEN";
495 // get message count using SEARCH
496 // not very performant but more precise (using UNDELETED)
498 $index = $this->_search_index($mailbox, $search_str);
499 if (is_array($index))
501 $str = implode(",", $index);
503 $count = count($index);
508 if ($mode == 'UNSEEN')
509 $count = iil_C_CountUnseen($this->conn, $mailbox);
511 $count = iil_C_CountMessages($this->conn, $mailbox);
514 if (!is_array($a_mailbox_cache[$mailbox]))
515 $a_mailbox_cache[$mailbox] = array();
517 $a_mailbox_cache[$mailbox][$mode] = (int)$count;
519 // write back to cache
520 $this->update_cache('messagecount', $a_mailbox_cache);
527 * Public method for listing headers
528 * convert mailbox name with root dir first
530 * @param string Mailbox/folder name
531 * @param int Current page to list
532 * @param string Header field to sort by
533 * @param string Sort order [ASC|DESC]
534 * @return array Indexed array with message header objects
537 function list_headers($mbox_name='', $page=NULL, $sort_field=NULL, $sort_order=NULL)
539 $mailbox = $mbox_name ? $this->_mod_mailbox($mbox_name) : $this->mailbox;
540 return $this->_list_headers($mailbox, $page, $sort_field, $sort_order);
545 * Private method for listing message headers
548 * @see rcube_imap::list_headers
550 function _list_headers($mailbox='', $page=NULL, $sort_field=NULL, $sort_order=NULL, $recursive=FALSE)
552 if (!strlen($mailbox))
555 // use saved message set
556 if ($this->search_string && $mailbox == $this->mailbox)
557 return $this->_list_header_set($mailbox, $page, $sort_field, $sort_order);
559 $this->_set_sort_order($sort_field, $sort_order);
561 $max = $this->_messagecount($mailbox);
562 $start_msg = ($this->list_page-1) * $this->page_size;
564 list($begin, $end) = $this->_get_message_range($max, $page);
570 $headers_sorted = FALSE;
571 $cache_key = $mailbox.'.msg';
572 $cache_status = $this->check_cache_status($mailbox, $cache_key);
574 // cache is OK, we can get all messages from local cache
577 $a_msg_headers = $this->get_message_cache($cache_key, $start_msg, $start_msg+$this->page_size, $this->sort_field, $this->sort_order);
578 $headers_sorted = TRUE;
580 // cache is dirty, sync it
581 else if ($this->caching_enabled && $cache_status==-1 && !$recursive)
583 $this->sync_header_index($mailbox);
584 return $this->_list_headers($mailbox, $page, $this->sort_field, $this->sort_order, TRUE);
588 // retrieve headers from IMAP
589 if ($this->get_capability('sort') && ($msg_index = iil_C_Sort($this->conn, $mailbox, $this->sort_field, $this->skip_deleted ? 'UNDELETED' : '')))
591 $mymsgidx = array_slice ($msg_index, $begin, $end-$begin);
592 $msgs = join(",", $mymsgidx);
596 $msgs = sprintf("%d:%d", $begin+1, $end);
597 $msg_index = range($begin, $end);
601 // fetch reuested headers from server
602 $a_msg_headers = array();
603 $deleted_count = $this->_fetch_headers($mailbox, $msgs, $a_msg_headers, $cache_key);
605 // delete cached messages with a higher index than $max+1
606 // Changed $max to $max+1 to fix this bug : #1484295
607 $this->clear_message_cache($cache_key, $max + 1);
609 // kick child process to sync cache
613 // return empty array if no messages found
614 if (!is_array($a_msg_headers) || empty($a_msg_headers)) {
618 // if not already sorted
619 if (!$headers_sorted)
621 // use this class for message sorting
622 $sorter = new rcube_header_sorter();
623 $sorter->set_sequence_numbers($msg_index);
624 $sorter->sort_headers($a_msg_headers);
626 if ($this->sort_order == 'DESC')
627 $a_msg_headers = array_reverse($a_msg_headers);
630 return array_values($a_msg_headers);
635 * Private method for listing a set of message headers (search results)
637 * @param string Mailbox/folder name
638 * @param int Current page to list
639 * @param string Header field to sort by
640 * @param string Sort order [ASC|DESC]
641 * @return array Indexed array with message header objects
643 * @see rcube_imap::list_header_set()
645 function _list_header_set($mailbox, $page=NULL, $sort_field=NULL, $sort_order=NULL)
647 if (!strlen($mailbox) || empty($this->search_set))
650 $msgs = $this->search_set;
651 $a_msg_headers = array();
652 $start_msg = ($this->list_page-1) * $this->page_size;
654 $this->_set_sort_order($sort_field, $sort_order);
656 // sorted messages, so we can first slice array and then fetch only wanted headers
657 if ($this->get_capability('sort')) // SORT searching result
659 // reset search set if sorting field has been changed
660 if ($this->sort_field && $this->search_sort_field != $this->sort_field)
662 $msgs = $this->search('', $this->search_string, $this->search_charset, $this->sort_field);
665 // return empty array if no messages found
669 if ($sort_order == 'DESC')
670 $msgs = array_reverse($msgs);
672 // get messages uids for one page
673 $msgs = array_slice(array_values($msgs), $start_msg, min(count($msgs)-$start_msg, $this->page_size));
676 $this->_fetch_headers($mailbox, join(',',$msgs), $a_msg_headers, NULL);
678 $sorter = new rcube_header_sorter();
679 $sorter->set_sequence_numbers($msgs);
680 $sorter->sort_headers($a_msg_headers);
682 return array_values($a_msg_headers);
684 else { // SEARCH searching result, need sorting
686 if ($cnt > 300 && $cnt > $this->page_size) { // experimantal value for best result
687 // use memory less expensive (and quick) method for big result set
688 $a_index = $this->message_index($mailbox, $this->sort_field, $this->sort_order);
689 // get messages uids for one page...
690 $msgs = array_slice(array_keys($a_index), $start_msg, min($cnt-$start_msg, $this->page_size));
691 // ...and fetch headers
692 $this->_fetch_headers($mailbox, join(',', $msgs), $a_msg_headers, NULL);
694 // return empty array if no messages found
695 if (!is_array($a_msg_headers) || empty($a_msg_headers))
698 $sorter = new rcube_header_sorter();
699 $sorter->set_sequence_numbers($msgs);
700 $sorter->sort_headers($a_msg_headers);
702 return array_values($a_msg_headers);
705 // for small result set we can fetch all messages headers
706 $this->_fetch_headers($mailbox, join(',', $msgs), $a_msg_headers, NULL);
708 // return empty array if no messages found
709 if (!is_array($a_msg_headers) || empty($a_msg_headers))
712 // if not already sorted
713 $a_msg_headers = iil_SortHeaders($a_msg_headers, $this->sort_field, $this->sort_order);
715 // only return the requested part of the set
716 return array_slice(array_values($a_msg_headers), $start_msg, min($cnt-$start_msg, $this->page_size));
723 * Helper function to get first and last index of the requested set
725 * @param int message count
726 * @param mixed page number to show, or string 'all'
727 * @return array array with two values: first index, last index
730 function _get_message_range($max, $page)
732 $start_msg = ($this->list_page-1) * $this->page_size;
739 else if ($this->sort_order=='DESC')
741 $begin = $max - $this->page_size - $start_msg;
742 $end = $max - $start_msg;
747 $end = $start_msg + $this->page_size;
750 if ($begin < 0) $begin = 0;
751 if ($end < 0) $end = $max;
752 if ($end > $max) $end = $max;
754 return array($begin, $end);
760 * Fetches message headers
763 * @param string Mailbox name
764 * @param string Message index to fetch
765 * @param array Reference to message headers array
766 * @param array Array with cache index
767 * @return int Number of deleted messages
770 function _fetch_headers($mailbox, $msgs, &$a_msg_headers, $cache_key)
772 // cache is incomplete
773 $cache_index = $this->get_message_cache_index($cache_key);
775 // fetch reuested headers from server
776 $a_header_index = iil_C_FetchHeaders($this->conn, $mailbox, $msgs);
779 if (!empty($a_header_index))
781 foreach ($a_header_index as $i => $headers)
783 if ($headers->deleted && $this->skip_deleted)
786 if ($cache_index[$headers->id] && $cache_index[$headers->id] == $headers->uid)
787 $this->remove_message_cache($cache_key, $headers->id);
793 // add message to cache
794 if ($this->caching_enabled && $cache_index[$headers->id] != $headers->uid)
795 $this->add_message_cache($cache_key, $headers->id, $headers);
797 $a_msg_headers[$headers->uid] = $headers;
801 return $deleted_count;
806 * Return sorted array of message IDs (not UIDs)
808 * @param string Mailbox to get index from
809 * @param string Sort column
810 * @param string Sort order [ASC, DESC]
811 * @return array Indexed array with message ids
813 function message_index($mbox_name='', $sort_field=NULL, $sort_order=NULL)
815 $this->_set_sort_order($sort_field, $sort_order);
817 $mailbox = $mbox_name ? $this->_mod_mailbox($mbox_name) : $this->mailbox;
818 $key = "{$mailbox}:{$this->sort_field}:{$this->sort_order}:{$this->search_string}.msgi";
820 // we have a saved search result. get index from there
821 if (!isset($this->cache[$key]) && $this->search_string && $mailbox == $this->mailbox)
823 $this->cache[$key] = array();
825 if ($this->get_capability('sort'))
827 if ($this->sort_field && $this->search_sort_field != $this->sort_field)
828 $this->search('', $this->search_string, $this->search_charset, $this->sort_field);
830 if ($this->sort_order == 'DESC')
831 $this->cache[$key] = array_reverse($this->search_set);
833 $this->cache[$key] = $this->search_set;
837 $a_index = iil_C_FetchHeaderIndex($this->conn, $mailbox, join(',', $this->search_set), $this->sort_field);
839 if ($this->sort_order=="ASC")
841 else if ($this->sort_order=="DESC")
844 $this->cache[$key] = array_keys($a_index);
848 // have stored it in RAM
849 if (isset($this->cache[$key]))
850 return $this->cache[$key];
853 $cache_key = $mailbox.'.msg';
854 $cache_status = $this->check_cache_status($mailbox, $cache_key);
859 $a_index = $this->get_message_cache_index($cache_key, TRUE, $this->sort_field, $this->sort_order);
860 return array_keys($a_index);
863 // fetch complete message index
864 $msg_count = $this->_messagecount($mailbox);
865 if ($this->get_capability('sort') && ($a_index = iil_C_Sort($this->conn, $mailbox, $this->sort_field, '')))
867 if ($this->sort_order == 'DESC')
868 $a_index = array_reverse($a_index);
870 $this->cache[$key] = $a_index;
874 $a_index = iil_C_FetchHeaderIndex($this->conn, $mailbox, "1:$msg_count", $this->sort_field);
876 if ($this->sort_order=="ASC")
878 else if ($this->sort_order=="DESC")
881 $this->cache[$key] = array_keys($a_index);
884 return $this->cache[$key];
891 function sync_header_index($mailbox)
893 $cache_key = $mailbox.'.msg';
894 $cache_index = $this->get_message_cache_index($cache_key);
895 $msg_count = $this->_messagecount($mailbox);
897 // fetch complete message index
898 $a_message_index = iil_C_FetchHeaderIndex($this->conn, $mailbox, "1:$msg_count", 'UID');
900 foreach ($a_message_index as $id => $uid)
902 // message in cache at correct position
903 if ($cache_index[$id] == $uid)
905 unset($cache_index[$id]);
909 // message in cache but in wrong position
910 if (in_array((string)$uid, $cache_index, TRUE))
912 unset($cache_index[$id]);
915 // other message at this position
916 if (isset($cache_index[$id]))
918 $this->remove_message_cache($cache_key, $id);
919 unset($cache_index[$id]);
923 // fetch complete headers and add to cache
924 $headers = iil_C_FetchHeader($this->conn, $mailbox, $id);
925 $this->add_message_cache($cache_key, $headers->id, $headers);
928 // those ids that are still in cache_index have been deleted
929 if (!empty($cache_index))
931 foreach ($cache_index as $id => $uid)
932 $this->remove_message_cache($cache_key, $id);
938 * Invoke search request to IMAP server
940 * @param string mailbox name to search in
941 * @param string search string
942 * @param string search string charset
943 * @param string header field to sort by
944 * @return array search results as list of message ids
947 function search($mbox_name='', $str=NULL, $charset=NULL, $sort_field=NULL)
952 $mailbox = $mbox_name ? $this->_mod_mailbox($mbox_name) : $this->mailbox;
954 $results = $this->_search_index($mailbox, $str, $charset, $sort_field);
956 // try search with ISO charset (should be supported by server)
957 // only if UTF-8 search is not supported
958 if (empty($results) && !is_array($results) && !empty($charset) && $charset!='ISO-8859-1')
960 // convert strings to ISO-8859-1
961 if(preg_match_all('/\{([0-9]+)\}\r\n/', $str, $matches, PREG_OFFSET_CAPTURE))
963 $last = 0; $res = '';
964 foreach($matches[1] as $m)
966 $string_offset = $m[1] + strlen($m[0]) + 4; // {}\r\n
967 $string = substr($str, $string_offset - 1, $m[0]);
968 $string = rcube_charset_convert($string, $charset, 'ISO-8859-1');
969 $res .= sprintf("%s{%d}\r\n%s", substr($str, $last, $m[1] - $last - 1), strlen($string), $string);
970 $last = $m[0] + $string_offset - 1;
972 if ($last < strlen($str))
973 $res .= substr($str, $last, strlen($str)-$last);
975 else // strings for conversion not found
978 $results = $this->search($mbox_name, $res, 'ISO-8859-1', $sort_field);
981 $this->set_search_set($str, $results, $charset, $sort_field);
988 * Private search method
990 * @return array search results as list of message ids
992 * @see rcube_imap::search()
994 function _search_index($mailbox, $criteria='ALL', $charset=NULL, $sort_field=NULL)
996 if ($sort_field && $this->get_capability('sort'))
998 $charset = $charset ? $charset : $this->default_charset;
999 $a_messages = iil_C_Sort($this->conn, $mailbox, $sort_field, $criteria, FALSE, $charset);
1002 $a_messages = iil_C_Search($this->conn, $mailbox, ($charset ? "CHARSET $charset " : '') . $criteria);
1004 // clean message list (there might be some empty entries)
1005 if (is_array($a_messages))
1007 foreach ($a_messages as $i => $val)
1009 unset($a_messages[$i]);
1017 * Refresh saved search set
1019 * @return array Current search set
1021 function refresh_search()
1023 if (!empty($this->search_string))
1024 $this->search_set = $this->search('', $this->search_string, $this->search_charset, $this->search_sort_field);
1026 return $this->get_search_set();
1031 * Check if the given message ID is part of the current search set
1033 * @return boolean True on match or if no search request is stored
1035 function in_searchset($msgid)
1037 if (!empty($this->search_string))
1038 return in_array("$msgid", (array)$this->search_set, true);
1045 * Return message headers object of a specific message
1047 * @param int Message ID
1048 * @param string Mailbox to read from
1049 * @param boolean True if $id is the message UID
1050 * @return object Message headers representation
1052 function get_headers($id, $mbox_name=NULL, $is_uid=TRUE)
1054 $mailbox = $mbox_name ? $this->_mod_mailbox($mbox_name) : $this->mailbox;
1055 $uid = $is_uid ? $id : $this->_id2uid($id);
1057 // get cached headers
1058 if ($uid && ($headers = &$this->get_cached_message($mailbox.'.msg', $uid)))
1061 $headers = iil_C_FetchHeader($this->conn, $mailbox, $id, $is_uid);
1063 // write headers cache
1066 if ($headers->uid && $headers->id)
1067 $this->uid_id_map[$mailbox][$headers->uid] = $headers->id;
1069 $this->add_message_cache($mailbox.'.msg', $headers->id, $headers);
1077 * Fetch body structure from the IMAP server and build
1078 * an object structure similar to the one generated by PEAR::Mail_mimeDecode
1080 * @param int Message UID to fetch
1081 * @return object rcube_message_part Message part tree or False on failure
1083 function &get_structure($uid)
1085 $cache_key = $this->mailbox.'.msg';
1086 $headers = &$this->get_cached_message($cache_key, $uid, true);
1088 // return cached message structure
1089 if (is_object($headers) && is_object($headers->structure)) {
1090 return $headers->structure;
1093 // resolve message sequence number
1094 if (!($msg_id = $this->_uid2id($uid))) {
1098 $structure_str = iil_C_FetchStructureString($this->conn, $this->mailbox, $msg_id);
1099 $structure = iml_GetRawStructureArray($structure_str);
1102 // parse structure and add headers
1103 if (!empty($structure))
1105 $this->_msg_id = $msg_id;
1106 $headers = $this->get_headers($uid);
1108 $struct = &$this->_structure_part($structure);
1109 $struct->headers = get_object_vars($headers);
1111 // don't trust given content-type
1112 if (empty($struct->parts) && !empty($struct->headers['ctype']))
1114 $struct->mime_id = '1';
1115 $struct->mimetype = strtolower($struct->headers['ctype']);
1116 list($struct->ctype_primary, $struct->ctype_secondary) = explode('/', $struct->mimetype);
1119 // write structure to cache
1120 if ($this->caching_enabled)
1121 $this->add_message_cache($cache_key, $msg_id, $headers, $struct);
1129 * Build message part object
1133 function &_structure_part($part, $count=0, $parent='')
1135 $struct = new rcube_message_part;
1136 $struct->mime_id = empty($parent) ? (string)$count : "$parent.$count";
1139 if (is_array($part[0]))
1141 $struct->ctype_primary = 'multipart';
1143 // find first non-array entry
1144 for ($i=1; $i<count($part); $i++)
1145 if (!is_array($part[$i]))
1147 $struct->ctype_secondary = strtolower($part[$i]);
1151 $struct->mimetype = 'multipart/'.$struct->ctype_secondary;
1153 $struct->parts = array();
1154 for ($i=0, $count=0; $i<count($part); $i++)
1155 if (is_array($part[$i]) && count($part[$i]) > 3)
1156 $struct->parts[] = $this->_structure_part($part[$i], ++$count, $struct->mime_id);
1163 $struct->ctype_primary = strtolower($part[0]);
1164 $struct->ctype_secondary = strtolower($part[1]);
1165 $struct->mimetype = $struct->ctype_primary.'/'.$struct->ctype_secondary;
1167 // read content type parameters
1168 if (is_array($part[2]))
1170 $struct->ctype_parameters = array();
1171 for ($i=0; $i<count($part[2]); $i+=2)
1172 $struct->ctype_parameters[strtolower($part[2][$i])] = $part[2][$i+1];
1174 if (isset($struct->ctype_parameters['charset']))
1175 $struct->charset = $struct->ctype_parameters['charset'];
1178 // read content encoding
1179 if (!empty($part[5]) && $part[5]!='NIL')
1181 $struct->encoding = strtolower($part[5]);
1182 $struct->headers['content-transfer-encoding'] = $struct->encoding;
1186 if (!empty($part[6]) && $part[6]!='NIL')
1187 $struct->size = intval($part[6]);
1189 // read part disposition
1190 $di = count($part) - 2;
1191 if ((is_array($part[$di]) && count($part[$di]) == 2 && is_array($part[$di][1])) ||
1192 (is_array($part[--$di]) && count($part[$di]) == 2))
1194 $struct->disposition = strtolower($part[$di][0]);
1196 if (is_array($part[$di][1]))
1197 for ($n=0; $n<count($part[$di][1]); $n+=2)
1198 $struct->d_parameters[strtolower($part[$di][1][$n])] = $part[$di][1][$n+1];
1202 if (is_array($part[8]) && $di != 8)
1204 $struct->parts = array();
1205 for ($i=0, $count=0; $i<count($part[8]); $i++)
1206 if (is_array($part[8][$i]) && count($part[8][$i]) > 5)
1207 $struct->parts[] = $this->_structure_part($part[8][$i], ++$count, $struct->mime_id);
1211 if (!empty($part[3]) && $part[3]!='NIL')
1213 $struct->content_id = $part[3];
1214 $struct->headers['content-id'] = $part[3];
1216 if (empty($struct->disposition))
1217 $struct->disposition = 'inline';
1220 // fetch message headers if message/rfc822 or named part (could contain Content-Location header)
1221 if ($struct->ctype_primary == 'message' || ($struct->ctype_parameters['name'] && !$struct->content_id)) {
1222 $part_headers = iil_C_FetchPartHeader($this->conn, $this->mailbox, $this->_msg_id, $struct->mime_id);
1223 $struct->headers = $this->_parse_headers($part_headers) + $struct->headers;
1226 if ($struct->ctype_primary=='message') {
1227 if (is_array($part[8]) && empty($struct->parts))
1228 $struct->parts[] = $this->_structure_part($part[8], ++$count, $struct->mime_id);
1231 // normalize filename property
1232 $this->_set_part_filename($struct);
1239 * Set attachment filename from message part structure
1242 * @param object rcube_message_part Part object
1244 function _set_part_filename(&$part)
1246 if (!empty($part->d_parameters['filename']))
1247 $filename_mime = $part->d_parameters['filename'];
1248 else if (!empty($part->d_parameters['filename*']))
1249 $filename_encoded = $part->d_parameters['filename*'];
1250 else if (!empty($part->ctype_parameters['name*']))
1251 $filename_encoded = $part->ctype_parameters['name*'];
1252 // RFC2231 value continuations
1253 // TODO: this should be rewrited to support RFC2231 4.1 combinations
1254 else if (!empty($part->d_parameters['filename*0'])) {
1256 while (isset($part->d_parameters['filename*'.$i])) {
1257 $filename_mime .= $part->d_parameters['filename*'.$i];
1260 // some servers (eg. dovecot-1.x) have no support for parameter value continuations
1261 // we must fetch and parse headers "manually"
1262 //TODO: fetching headers for a second time is not effecient, this code should be moved somewhere earlier --tensor
1264 // TODO: fetch only Content-Type/Content-Disposition header
1265 $headers = iil_C_FetchPartHeader($this->conn, $this->mailbox, $this->_msg_id, $part->mime_id);
1266 $filename_mime = '';
1268 while (preg_match('/filename\*'.$i.'\s*=\s*"*([^"\n;]+)[";]*/', $headers, $matches)) {
1269 $filename_mime .= $matches[1];
1274 else if (!empty($part->d_parameters['filename*0*'])) {
1276 while (isset($part->d_parameters['filename*'.$i.'*'])) {
1277 $filename_encoded .= $part->d_parameters['filename*'.$i.'*'];
1281 $headers = iil_C_FetchPartHeader($this->conn, $this->mailbox, $this->_msg_id, $part->mime_id);
1282 $filename_encoded = '';
1283 $i = 0; $matches = array();
1284 while (preg_match('/filename\*'.$i.'\*\s*=\s*"*([^"\n;]+)[";]*/', $headers, $matches)) {
1285 $filename_encoded .= $matches[1];
1290 else if (!empty($part->ctype_parameters['name*0'])) {
1292 while (isset($part->ctype_parameters['name*'.$i])) {
1293 $filename_mime .= $part->ctype_parameters['name*'.$i];
1297 $headers = iil_C_FetchPartHeader($this->conn, $this->mailbox, $this->_msg_id, $part->mime_id);
1298 $filename_mime = '';
1299 $i = 0; $matches = array();
1300 while (preg_match('/\s+name\*'.$i.'\s*=\s*"*([^"\n;]+)[";]*/', $headers, $matches)) {
1301 $filename_mime .= $matches[1];
1306 else if (!empty($part->ctype_parameters['name*0*'])) {
1308 while (isset($part->ctype_parameters['name*'.$i.'*'])) {
1309 $filename_encoded .= $part->ctype_parameters['name*'.$i.'*'];
1313 $headers = iil_C_FetchPartHeader($this->conn, $this->mailbox, $this->_msg_id, $part->mime_id);
1314 $filename_encoded = '';
1315 $i = 0; $matches = array();
1316 while (preg_match('/\s+name\*'.$i.'\*\s*=\s*"*([^"\n;]+)[";]*/', $headers, $matches)) {
1317 $filename_encoded .= $matches[1];
1322 // read 'name' after rfc2231 parameters as it may contains truncated filename (from Thunderbird)
1323 else if (!empty($part->ctype_parameters['name']))
1324 $filename_mime = $part->ctype_parameters['name'];
1325 // Content-Disposition
1326 else if (!empty($part->headers['content-description']))
1327 $filename_mime = $part->headers['content-description'];
1332 if (!empty($filename_mime)) {
1333 $part->filename = rcube_imap::decode_mime_string($filename_mime,
1334 $part->charset ? $part->charset : rc_detect_encoding($filename_mime, $this->default_charset));
1336 else if (!empty($filename_encoded)) {
1337 // decode filename according to RFC 2231, Section 4
1338 if (preg_match("/^([^']*)'[^']*'(.*)$/", $filename_encoded, $fmatches)) {
1339 $filename_charset = $fmatches[1];
1340 $filename_encoded = $fmatches[2];
1342 $part->filename = rcube_charset_convert(urldecode($filename_encoded), $filename_charset);
1348 * Fetch message body of a specific message from the server
1350 * @param int Message UID
1351 * @param string Part number
1352 * @param object rcube_message_part Part object created by get_structure()
1353 * @param mixed True to print part, ressource to write part contents in
1354 * @param resource File pointer to save the message part
1355 * @return string Message/part body if not printed
1357 function &get_message_part($uid, $part=1, $o_part=NULL, $print=NULL, $fp=NULL)
1359 if (!($msg_id = $this->_uid2id($uid)))
1362 // get part encoding if not provided
1363 if (!is_object($o_part))
1365 $structure_str = iil_C_FetchStructureString($this->conn, $this->mailbox, $msg_id);
1366 $structure = iml_GetRawStructureArray($structure_str);
1367 $part_type = iml_GetPartTypeCode($structure, $part);
1368 $o_part = new rcube_message_part;
1369 $o_part->ctype_primary = $part_type==0 ? 'text' : ($part_type==2 ? 'message' : 'other');
1370 $o_part->encoding = strtolower(iml_GetPartEncodingString($structure, $part));
1371 $o_part->charset = iml_GetPartCharset($structure, $part);
1374 // TODO: Add caching for message parts
1376 if (!$part) $part = 'TEXT';
1380 $mode = $o_part->encoding == 'base64' ? 3 : ($o_part->encoding == 'quoted-printable' ? 1 : 2);
1381 $body = iil_C_HandlePartBody($this->conn, $this->mailbox, $msg_id, $part, $mode);
1383 // we have to decode the part manually before printing
1386 echo $this->mime_decode($body, $o_part->encoding);
1392 if ($fp && $o_part->encoding == 'base64')
1393 return iil_C_HandlePartBody($this->conn, $this->mailbox, $msg_id, $part, 3, $fp);
1395 $body = iil_C_HandlePartBody($this->conn, $this->mailbox, $msg_id, $part, 1);
1398 if ($o_part->encoding)
1399 $body = $this->mime_decode($body, $o_part->encoding);
1401 // convert charset (if text or message part)
1402 if ($o_part->ctype_primary=='text' || $o_part->ctype_primary=='message')
1404 // assume default if no charset specified
1405 if (empty($o_part->charset))
1406 $o_part->charset = $this->default_charset;
1408 $body = rcube_charset_convert($body, $o_part->charset);
1423 * Fetch message body of a specific message from the server
1425 * @param int Message UID
1426 * @return string Message/part body
1427 * @see rcube_imap::get_message_part()
1429 function &get_body($uid, $part=1)
1431 $headers = $this->get_headers($uid);
1432 return rcube_charset_convert(
1433 $this->mime_decode($this->get_message_part($uid, $part), 'quoted-printable'),
1434 $headers->charset ? $headers->charset : $this->default_charset);
1439 * Returns the whole message source as string
1441 * @param int Message UID
1442 * @return string Message source string
1444 function &get_raw_body($uid)
1446 if (!($msg_id = $this->_uid2id($uid)))
1449 return iil_C_HandlePartBody($this->conn, $this->mailbox, $msg_id);
1454 * Returns the message headers as string
1456 * @param int Message UID
1457 * @return string Message headers string
1459 function &get_raw_headers($uid)
1461 if (!($msg_id = $this->_uid2id($uid)))
1464 $headers = iil_C_FetchPartHeader($this->conn, $this->mailbox, $msg_id, NULL);
1471 * Sends the whole message source to stdout
1473 * @param int Message UID
1475 function print_raw_body($uid)
1477 if (!($msg_id = $this->_uid2id($uid)))
1480 iil_C_HandlePartBody($this->conn, $this->mailbox, $msg_id, NULL, 2);
1485 * Set message flag to one or several messages
1487 * @param mixed Message UIDs as array or as comma-separated string
1488 * @param string Flag to set: SEEN, UNDELETED, DELETED, RECENT, ANSWERED, DRAFT, MDNSENT
1489 * @return boolean True on success, False on failure
1491 function set_flag($uids, $flag)
1493 $flag = strtoupper($flag);
1495 if (!is_array($uids))
1496 $uids = explode(',',$uids);
1498 foreach ($uids as $uid) {
1499 $msg_ids[$uid] = $this->_uid2id($uid);
1502 if ($flag=='UNDELETED')
1503 $result = iil_C_Undelete($this->conn, $this->mailbox, join(',', array_values($msg_ids)));
1504 else if ($flag=='UNSEEN')
1505 $result = iil_C_Unseen($this->conn, $this->mailbox, join(',', array_values($msg_ids)));
1506 else if ($flag=='UNFLAGGED')
1507 $result = iil_C_UnFlag($this->conn, $this->mailbox, join(',', array_values($msg_ids)), 'FLAGGED');
1509 $result = iil_C_Flag($this->conn, $this->mailbox, join(',', array_values($msg_ids)), $flag);
1511 // reload message headers if cached
1512 $cache_key = $this->mailbox.'.msg';
1513 if ($this->caching_enabled)
1515 foreach ($msg_ids as $uid => $id)
1517 if ($cached_headers = $this->get_cached_message($cache_key, $uid))
1519 $this->remove_message_cache($cache_key, $id);
1520 //$this->get_headers($uid);
1524 // close and re-open connection
1525 // this prevents connection problems with Courier
1529 // set nr of messages that were flaged
1530 $count = count($msg_ids);
1532 // clear message count cache
1533 if ($result && $flag=='SEEN')
1534 $this->_set_messagecount($this->mailbox, 'UNSEEN', $count*(-1));
1535 else if ($result && $flag=='UNSEEN')
1536 $this->_set_messagecount($this->mailbox, 'UNSEEN', $count);
1537 else if ($result && $flag=='DELETED')
1538 $this->_set_messagecount($this->mailbox, 'ALL', $count*(-1));
1545 * Append a mail message (source) to a specific mailbox
1547 * @param string Target mailbox
1548 * @param string Message source
1549 * @return boolean True on success, False on error
1551 function save_message($mbox_name, &$message)
1553 $mbox_name = stripslashes($mbox_name);
1554 $mailbox = $this->_mod_mailbox($mbox_name);
1556 // make sure mailbox exists
1557 if (($mailbox == 'INBOX') || in_array($mailbox, $this->_list_mailboxes()))
1558 $saved = iil_C_Append($this->conn, $mailbox, $message);
1562 // increase messagecount of the target mailbox
1563 $this->_set_messagecount($mailbox, 'ALL', 1);
1571 * Move a message from one mailbox to another
1573 * @param string List of UIDs to move, separated by comma
1574 * @param string Target mailbox
1575 * @param string Source mailbox
1576 * @return boolean True on success, False on error
1578 function move_message($uids, $to_mbox, $from_mbox='')
1580 $to_mbox_in = stripslashes($to_mbox);
1581 $from_mbox = stripslashes($from_mbox);
1582 $to_mbox = $this->_mod_mailbox($to_mbox_in);
1583 $from_mbox = $from_mbox ? $this->_mod_mailbox($from_mbox) : $this->mailbox;
1585 // make sure mailbox exists
1586 if (!in_array($to_mbox, $this->_list_mailboxes()))
1588 if (in_array($to_mbox_in, $this->default_folders))
1589 $this->create_mailbox($to_mbox_in, TRUE);
1594 // convert the list of uids to array
1595 $a_uids = is_string($uids) ? explode(',', $uids) : (is_array($uids) ? $uids : NULL);
1597 // exit if no message uids are specified
1598 if (!is_array($a_uids))
1601 // convert uids to message ids
1603 foreach ($a_uids as $uid)
1604 $a_mids[] = $this->_uid2id($uid, $from_mbox);
1606 $iil_move = iil_C_Move($this->conn, join(',', $a_mids), $from_mbox, $to_mbox);
1607 $moved = !($iil_move === false || $iil_move < 0);
1609 // send expunge command in order to have the moved message
1610 // really deleted from the source mailbox
1612 // but only when flag_for_deletion is set to false
1613 if (!rcmail::get_instance()->config->get('flag_for_deletion', false))
1615 $this->_expunge($from_mbox, FALSE);
1616 $this->_clear_messagecount($from_mbox);
1617 $this->_clear_messagecount($to_mbox);
1621 else if (rcmail::get_instance()->config->get('delete_always', false)) {
1622 return iil_C_Delete($this->conn, $from_mbox, join(',', $a_mids));
1625 // remove message ids from search set
1626 if ($moved && $this->search_set && $from_mbox == $this->mailbox)
1627 $this->search_set = array_diff($this->search_set, $a_mids);
1629 // update cached message headers
1630 $cache_key = $from_mbox.'.msg';
1631 if ($moved && ($a_cache_index = $this->get_message_cache_index($cache_key)))
1633 $start_index = 100000;
1634 foreach ($a_uids as $uid)
1636 if (($index = array_search($uid, $a_cache_index)) !== FALSE)
1637 $start_index = min($index, $start_index);
1640 // clear cache from the lowest index on
1641 $this->clear_message_cache($cache_key, $start_index);
1649 * Mark messages as deleted and expunge mailbox
1651 * @param string List of UIDs to move, separated by comma
1652 * @param string Source mailbox
1653 * @return boolean True on success, False on error
1655 function delete_message($uids, $mbox_name='')
1657 $mbox_name = stripslashes($mbox_name);
1658 $mailbox = $mbox_name ? $this->_mod_mailbox($mbox_name) : $this->mailbox;
1660 // convert the list of uids to array
1661 $a_uids = is_string($uids) ? explode(',', $uids) : (is_array($uids) ? $uids : NULL);
1663 // exit if no message uids are specified
1664 if (!is_array($a_uids))
1667 // convert uids to message ids
1669 foreach ($a_uids as $uid)
1670 $a_mids[] = $this->_uid2id($uid, $mailbox);
1672 $deleted = iil_C_Delete($this->conn, $mailbox, join(',', $a_mids));
1674 // send expunge command in order to have the deleted message
1675 // really deleted from the mailbox
1678 $this->_expunge($mailbox, FALSE);
1679 $this->_clear_messagecount($mailbox);
1680 unset($this->uid_id_map[$mailbox]);
1683 // remove message ids from search set
1684 if ($deleted && $this->search_set && $mailbox == $this->mailbox)
1685 $this->search_set = array_diff($this->search_set, $a_mids);
1687 // remove deleted messages from cache
1688 $cache_key = $mailbox.'.msg';
1689 if ($deleted && ($a_cache_index = $this->get_message_cache_index($cache_key)))
1691 $start_index = 100000;
1692 foreach ($a_uids as $uid)
1694 if (($index = array_search($uid, $a_cache_index)) !== FALSE)
1695 $start_index = min($index, $start_index);
1698 // clear cache from the lowest index on
1699 $this->clear_message_cache($cache_key, $start_index);
1707 * Clear all messages in a specific mailbox
1709 * @param string Mailbox name
1710 * @return int Above 0 on success
1712 function clear_mailbox($mbox_name=NULL)
1714 $mbox_name = stripslashes($mbox_name);
1715 $mailbox = !empty($mbox_name) ? $this->_mod_mailbox($mbox_name) : $this->mailbox;
1716 $msg_count = $this->_messagecount($mailbox, 'ALL');
1720 $cleared = iil_C_ClearFolder($this->conn, $mailbox);
1722 // make sure the message count cache is cleared as well
1725 $this->clear_message_cache($mailbox.'.msg');
1726 $a_mailbox_cache = $this->get_cache('messagecount');
1727 unset($a_mailbox_cache[$mailbox]);
1728 $this->update_cache('messagecount', $a_mailbox_cache);
1739 * Send IMAP expunge command and clear cache
1741 * @param string Mailbox name
1742 * @param boolean False if cache should not be cleared
1743 * @return boolean True on success
1745 function expunge($mbox_name='', $clear_cache=TRUE)
1747 $mbox_name = stripslashes($mbox_name);
1748 $mailbox = $mbox_name ? $this->_mod_mailbox($mbox_name) : $this->mailbox;
1749 return $this->_expunge($mailbox, $clear_cache);
1754 * Send IMAP expunge command and clear cache
1756 * @see rcube_imap::expunge()
1759 function _expunge($mailbox, $clear_cache=TRUE)
1761 $result = iil_C_Expunge($this->conn, $mailbox);
1763 if ($result>=0 && $clear_cache)
1765 $this->clear_message_cache($mailbox.'.msg');
1766 $this->_clear_messagecount($mailbox);
1773 /* --------------------------------
1775 * --------------------------------*/
1779 * Get a list of all folders available on the IMAP server
1781 * @param string IMAP root dir
1782 * @return array Indexed array with folder names
1784 function list_unsubscribed($root='')
1786 static $sa_unsubscribed;
1788 if (is_array($sa_unsubscribed))
1789 return $sa_unsubscribed;
1791 // retrieve list of folders from IMAP server
1792 $a_mboxes = iil_C_ListMailboxes($this->conn, $this->_mod_mailbox($root), '*');
1794 // modify names with root dir
1795 foreach ($a_mboxes as $mbox_name)
1797 $name = $this->_mod_mailbox($mbox_name, 'out');
1799 $a_folders[] = $name;
1802 // filter folders and sort them
1803 $sa_unsubscribed = $this->_sort_mailbox_list($a_folders);
1804 return $sa_unsubscribed;
1809 * Get mailbox quota information
1812 * @return mixed Quota info or False if not supported
1814 function get_quota()
1816 if ($this->get_capability('QUOTA'))
1817 return iil_C_GetQuota($this->conn);
1824 * Subscribe to a specific mailbox(es)
1826 * @param array Mailbox name(s)
1827 * @return boolean True on success
1829 function subscribe($a_mboxes)
1831 if (!is_array($a_mboxes))
1832 $a_mboxes = array($a_mboxes);
1834 // let this common function do the main work
1835 return $this->_change_subscription($a_mboxes, 'subscribe');
1840 * Unsubscribe mailboxes
1842 * @param array Mailbox name(s)
1843 * @return boolean True on success
1845 function unsubscribe($a_mboxes)
1847 if (!is_array($a_mboxes))
1848 $a_mboxes = array($a_mboxes);
1850 // let this common function do the main work
1851 return $this->_change_subscription($a_mboxes, 'unsubscribe');
1856 * Create a new mailbox on the server and register it in local cache
1858 * @param string New mailbox name (as utf-7 string)
1859 * @param boolean True if the new mailbox should be subscribed
1860 * @param string Name of the created mailbox, false on error
1862 function create_mailbox($name, $subscribe=FALSE)
1866 // replace backslashes
1867 $name = preg_replace('/[\\\]+/', '-', $name);
1869 // reduce mailbox name to 100 chars
1870 $name = substr($name, 0, 100);
1872 $abs_name = $this->_mod_mailbox($name);
1873 $a_mailbox_cache = $this->get_cache('mailboxes');
1875 if (strlen($abs_name) && (!is_array($a_mailbox_cache) || !in_array($abs_name, $a_mailbox_cache)))
1876 $result = iil_C_CreateFolder($this->conn, $abs_name);
1878 // try to subscribe it
1879 if ($result && $subscribe)
1880 $this->subscribe($name);
1882 return $result ? $name : FALSE;
1887 * Set a new name to an existing mailbox
1889 * @param string Mailbox to rename (as utf-7 string)
1890 * @param string New mailbox name (as utf-7 string)
1891 * @return string Name of the renames mailbox, False on error
1893 function rename_mailbox($mbox_name, $new_name)
1897 // replace backslashes
1898 $name = preg_replace('/[\\\]+/', '-', $new_name);
1900 // encode mailbox name and reduce it to 100 chars
1901 $name = substr($new_name, 0, 100);
1903 // make absolute path
1904 $mailbox = $this->_mod_mailbox($mbox_name);
1905 $abs_name = $this->_mod_mailbox($name);
1907 // check if mailbox is subscribed
1908 $a_subscribed = $this->_list_mailboxes();
1909 $subscribed = in_array($mailbox, $a_subscribed);
1911 // unsubscribe folder
1913 iil_C_UnSubscribe($this->conn, $mailbox);
1915 if (strlen($abs_name))
1916 $result = iil_C_RenameFolder($this->conn, $mailbox, $abs_name);
1920 $delm = $this->get_hierarchy_delimiter();
1922 // check if mailbox children are subscribed
1923 foreach ($a_subscribed as $c_subscribed)
1924 if (preg_match('/^'.preg_quote($mailbox.$delm, '/').'/', $c_subscribed))
1926 iil_C_UnSubscribe($this->conn, $c_subscribed);
1927 iil_C_Subscribe($this->conn, preg_replace('/^'.preg_quote($mailbox, '/').'/', $abs_name, $c_subscribed));
1931 $this->clear_message_cache($mailbox.'.msg');
1932 $this->clear_cache('mailboxes');
1935 // try to subscribe it
1936 if ($result && $subscribed)
1937 iil_C_Subscribe($this->conn, $abs_name);
1939 return $result ? $name : FALSE;
1944 * Remove mailboxes from server
1946 * @param string Mailbox name
1947 * @return boolean True on success
1949 function delete_mailbox($mbox_name)
1953 if (is_array($mbox_name))
1954 $a_mboxes = $mbox_name;
1955 else if (is_string($mbox_name) && strlen($mbox_name))
1956 $a_mboxes = explode(',', $mbox_name);
1958 $all_mboxes = iil_C_ListMailboxes($this->conn, $this->_mod_mailbox($root), '*');
1960 if (is_array($a_mboxes))
1961 foreach ($a_mboxes as $mbox_name)
1963 $mailbox = $this->_mod_mailbox($mbox_name);
1965 // unsubscribe mailbox before deleting
1966 iil_C_UnSubscribe($this->conn, $mailbox);
1968 // send delete command to server
1969 $result = iil_C_DeleteFolder($this->conn, $mailbox);
1973 foreach ($all_mboxes as $c_mbox)
1975 $regex = preg_quote($mailbox . $this->delimiter, '/');
1976 $regex = '/^' . $regex . '/';
1977 if (preg_match($regex, $c_mbox))
1979 iil_C_UnSubscribe($this->conn, $c_mbox);
1980 $result = iil_C_DeleteFolder($this->conn, $c_mbox);
1987 // clear mailboxlist cache
1990 $this->clear_message_cache($mailbox.'.msg');
1991 $this->clear_cache('mailboxes');
1999 * Create all folders specified as default
2001 function create_default_folders()
2003 $a_folders = iil_C_ListMailboxes($this->conn, $this->_mod_mailbox(''), '*');
2004 $a_subscribed = iil_C_ListSubscribed($this->conn, $this->_mod_mailbox(''), '*');
2006 // create default folders if they do not exist
2007 foreach ($this->default_folders as $folder)
2009 $abs_name = $this->_mod_mailbox($folder);
2010 if (!in_array_nocase($abs_name, $a_folders))
2011 $this->create_mailbox($folder, TRUE);
2012 else if (!in_array_nocase($abs_name, $a_subscribed))
2013 $this->subscribe($folder);
2019 /* --------------------------------
2020 * internal caching methods
2021 * --------------------------------*/
2026 function set_caching($set)
2028 if ($set && is_object($this->db))
2029 $this->caching_enabled = TRUE;
2031 $this->caching_enabled = FALSE;
2037 function get_cache($key)
2040 if (!isset($this->cache[$key]) && $this->caching_enabled)
2042 $cache_data = $this->_read_cache_record('IMAP.'.$key);
2043 $this->cache[$key] = strlen($cache_data) ? unserialize($cache_data) : FALSE;
2046 return $this->cache[$key];
2052 function update_cache($key, $data)
2054 $this->cache[$key] = $data;
2055 $this->cache_changed = TRUE;
2056 $this->cache_changes[$key] = TRUE;
2062 function write_cache()
2064 if ($this->caching_enabled && $this->cache_changed)
2066 foreach ($this->cache as $key => $data)
2068 if ($this->cache_changes[$key])
2069 $this->_write_cache_record('IMAP.'.$key, serialize($data));
2077 function clear_cache($key=NULL)
2079 if (!$this->caching_enabled)
2084 foreach ($this->cache as $key => $data)
2085 $this->_clear_cache_record('IMAP.'.$key);
2087 $this->cache = array();
2088 $this->cache_changed = FALSE;
2089 $this->cache_changes = array();
2093 $this->_clear_cache_record('IMAP.'.$key);
2094 $this->cache_changes[$key] = FALSE;
2095 unset($this->cache[$key]);
2102 function _read_cache_record($key)
2104 $cache_data = FALSE;
2108 // get cached data from DB
2109 $sql_result = $this->db->query(
2110 "SELECT cache_id, data
2111 FROM ".get_table_name('cache')."
2114 $_SESSION['user_id'],
2117 if ($sql_arr = $this->db->fetch_assoc($sql_result))
2119 $cache_data = $sql_arr['data'];
2120 $this->cache_keys[$key] = $sql_arr['cache_id'];
2130 function _write_cache_record($key, $data)
2135 // check if we already have a cache entry for this key
2136 if (!isset($this->cache_keys[$key]))
2138 $sql_result = $this->db->query(
2140 FROM ".get_table_name('cache')."
2143 $_SESSION['user_id'],
2146 if ($sql_arr = $this->db->fetch_assoc($sql_result))
2147 $this->cache_keys[$key] = $sql_arr['cache_id'];
2149 $this->cache_keys[$key] = FALSE;
2152 // update existing cache record
2153 if ($this->cache_keys[$key])
2156 "UPDATE ".get_table_name('cache')."
2157 SET created=". $this->db->now().", data=?
2161 $_SESSION['user_id'],
2164 // add new cache record
2168 "INSERT INTO ".get_table_name('cache')."
2169 (created, user_id, cache_key, data)
2170 VALUES (".$this->db->now().", ?, ?, ?)",
2171 $_SESSION['user_id'],
2180 function _clear_cache_record($key)
2183 "DELETE FROM ".get_table_name('cache')."
2186 $_SESSION['user_id'],
2192 /* --------------------------------
2193 * message caching methods
2194 * --------------------------------*/
2198 * Checks if the cache is up-to-date
2200 * @param string Mailbox name
2201 * @param string Internal cache key
2202 * @return int -3 = off, -2 = incomplete, -1 = dirty
2204 function check_cache_status($mailbox, $cache_key)
2206 if (!$this->caching_enabled)
2209 $cache_index = $this->get_message_cache_index($cache_key, TRUE);
2210 $msg_count = $this->_messagecount($mailbox);
2211 $cache_count = count($cache_index);
2213 // console("Cache check: $msg_count !== ".count($cache_index));
2215 if ($cache_count==$msg_count)
2217 // get highest index
2218 $header = iil_C_FetchHeader($this->conn, $mailbox, "$msg_count");
2219 $cache_uid = array_pop($cache_index);
2221 // uids of highest message matches -> cache seems OK
2222 if ($cache_uid == $header->uid)
2228 // if cache count differs less than 10% report as dirty
2229 else if (abs($msg_count - $cache_count) < $msg_count/10)
2238 function get_message_cache($key, $from, $to, $sort_field, $sort_order)
2240 $cache_key = "$key:$from:$to:$sort_field:$sort_order";
2241 $db_header_fields = array('idx', 'uid', 'subject', 'from', 'to', 'cc', 'date', 'size');
2243 if (!in_array($sort_field, $db_header_fields))
2244 $sort_field = 'idx';
2246 if ($this->caching_enabled && !isset($this->cache[$cache_key]))
2248 $this->cache[$cache_key] = array();
2249 $sql_result = $this->db->limitquery(
2250 "SELECT idx, uid, headers
2251 FROM ".get_table_name('messages')."
2254 ORDER BY ".$this->db->quoteIdentifier($sort_field)." ".
2255 strtoupper($sort_order),
2258 $_SESSION['user_id'],
2261 while ($sql_arr = $this->db->fetch_assoc($sql_result))
2263 $uid = $sql_arr['uid'];
2264 $this->cache[$cache_key][$uid] = unserialize($sql_arr['headers']);
2266 // featch headers if unserialize failed
2267 if (empty($this->cache[$cache_key][$uid]))
2268 $this->cache[$cache_key][$uid] = iil_C_FetchHeader($this->conn, preg_replace('/.msg$/', '', $key), $uid, true);
2272 return $this->cache[$cache_key];
2278 function &get_cached_message($key, $uid, $struct=false)
2280 $internal_key = '__single_msg';
2282 if ($this->caching_enabled && (!isset($this->cache[$internal_key][$uid]) ||
2283 ($struct && empty($this->cache[$internal_key][$uid]->structure))))
2285 $sql_select = "idx, uid, headers" . ($struct ? ", structure" : '');
2286 $sql_result = $this->db->query(
2288 FROM ".get_table_name('messages')."
2292 $_SESSION['user_id'],
2296 if ($sql_arr = $this->db->fetch_assoc($sql_result))
2298 $this->cache[$internal_key][$uid] = unserialize($sql_arr['headers']);
2299 if (is_object($this->cache[$internal_key][$uid]) && !empty($sql_arr['structure']))
2300 $this->cache[$internal_key][$uid]->structure = unserialize($sql_arr['structure']);
2304 return $this->cache[$internal_key][$uid];
2310 function get_message_cache_index($key, $force=FALSE, $sort_field='idx', $sort_order='ASC')
2312 static $sa_message_index = array();
2314 // empty key -> empty array
2315 if (!$this->caching_enabled || empty($key))
2318 if (!empty($sa_message_index[$key]) && !$force)
2319 return $sa_message_index[$key];
2321 $sa_message_index[$key] = array();
2322 $sql_result = $this->db->query(
2324 FROM ".get_table_name('messages')."
2327 ORDER BY ".$this->db->quote_identifier($sort_field)." ".$sort_order,
2328 $_SESSION['user_id'],
2331 while ($sql_arr = $this->db->fetch_assoc($sql_result))
2332 $sa_message_index[$key][$sql_arr['idx']] = $sql_arr['uid'];
2334 return $sa_message_index[$key];
2340 function add_message_cache($key, $index, $headers, $struct=null)
2342 if (empty($key) || !is_object($headers) || empty($headers->uid))
2345 // add to internal (fast) cache
2346 $this->cache['__single_msg'][$headers->uid] = $headers;
2347 $this->cache['__single_msg'][$headers->uid]->structure = $struct;
2349 // no further caching
2350 if (!$this->caching_enabled)
2353 // check for an existing record (probly headers are cached but structure not)
2354 $sql_result = $this->db->query(
2356 FROM ".get_table_name('messages')."
2361 $_SESSION['user_id'],
2365 // update cache record
2366 if ($sql_arr = $this->db->fetch_assoc($sql_result))
2369 "UPDATE ".get_table_name('messages')."
2370 SET idx=?, headers=?, structure=?
2371 WHERE message_id=?",
2373 serialize($headers),
2374 is_object($struct) ? serialize($struct) : NULL,
2375 $sql_arr['message_id']
2378 else // insert new record
2381 "INSERT INTO ".get_table_name('messages')."
2382 (user_id, del, cache_key, created, idx, uid, subject, ".$this->db->quoteIdentifier('from').", ".$this->db->quoteIdentifier('to').", cc, date, size, headers, structure)
2383 VALUES (?, 0, ?, ".$this->db->now().", ?, ?, ?, ?, ?, ?, ".$this->db->fromunixtime($headers->timestamp).", ?, ?, ?)",
2384 $_SESSION['user_id'],
2388 (string)substr($this->decode_header($headers->subject, TRUE), 0, 128),
2389 (string)substr($this->decode_header($headers->from, TRUE), 0, 128),
2390 (string)substr($this->decode_header($headers->to, TRUE), 0, 128),
2391 (string)substr($this->decode_header($headers->cc, TRUE), 0, 128),
2392 (int)$headers->size,
2393 serialize($headers),
2394 is_object($struct) ? serialize($struct) : NULL
2402 function remove_message_cache($key, $index)
2404 if (!$this->caching_enabled)
2408 "DELETE FROM ".get_table_name('messages')."
2412 $_SESSION['user_id'],
2420 function clear_message_cache($key, $start_index=1)
2422 if (!$this->caching_enabled)
2426 "DELETE FROM ".get_table_name('messages')."
2430 $_SESSION['user_id'],
2438 /* --------------------------------
2439 * encoding/decoding methods
2440 * --------------------------------*/
2443 * Split an address list into a structured array list
2445 * @param string Input string
2446 * @param int List only this number of addresses
2447 * @param boolean Decode address strings
2448 * @return array Indexed list of addresses
2450 function decode_address_list($input, $max=null, $decode=true)
2452 $a = $this->_parse_address_list($input, $decode);
2454 // Special chars as defined by RFC 822 need to in quoted string (or escaped).
2455 $special_chars = '[\(\)\<\>\\\.\[\]@,;:"]';
2463 foreach ($a as $val)
2466 $address = $val['address'];
2467 $name = preg_replace(array('/^[\'"]/', '/[\'"]$/'), '', trim($val['name']));
2468 if ($name && $address && $name != $address)
2469 $string = sprintf('%s <%s>', preg_match("/$special_chars/", $name) ? '"'.addcslashes($name, '"').'"' : $name, $address);
2475 $out[$j] = array('name' => $name,
2476 'mailto' => $address,
2477 'string' => $string);
2479 if ($max && $j==$max)
2488 * Decode a message header value
2490 * @param string Header value
2491 * @param boolean Remove quotes if necessary
2492 * @return string Decoded string
2494 function decode_header($input, $remove_quotes=FALSE)
2496 $str = rcube_imap::decode_mime_string((string)$input, $this->default_charset);
2497 if ($str{0}=='"' && $remove_quotes)
2498 $str = str_replace('"', '', $str);
2505 * Decode a mime-encoded string to internal charset
2507 * @param string $input Header value
2508 * @param string $fallback Fallback charset if none specified
2510 * @return string Decoded string
2513 public static function decode_mime_string($input, $fallback=null)
2515 // Initialize variable
2518 // Iterate instead of recursing, this way if there are too many values we don't have stack overflows
2519 // rfc: all line breaks or other characters not found
2520 // in the Base64 Alphabet must be ignored by decoding software
2521 // delete all blanks between MIME-lines, differently we can
2522 // receive unnecessary blanks and broken utf-8 symbols
2523 $input = preg_replace("/\?=\s+=\?/", '?==?', $input);
2525 // Check if there is stuff to decode
2526 if (strpos($input, '=?') !== false) {
2527 // Loop through the string to decode all occurences of =? ?= into the variable $out
2528 while(($pos = strpos($input, '=?')) !== false) {
2529 // Append everything that is before the text to be decoded
2530 $out .= substr($input, 0, $pos);
2532 // Get the location of the text to decode
2533 $end_cs_pos = strpos($input, "?", $pos+2);
2534 $end_en_pos = strpos($input, "?", $end_cs_pos+1);
2535 $end_pos = strpos($input, "?=", $end_en_pos+1);
2537 // Extract the encoded string
2538 $encstr = substr($input, $pos+2, ($end_pos-$pos-2));
2539 // Extract the remaining string
2540 $input = substr($input, $end_pos+2);
2542 // Decode the string fragement
2543 $out .= rcube_imap::_decode_mime_string_part($encstr);
2546 // Deocde the rest (if any)
2547 if (strlen($input) != 0)
2548 $out .= rcube_imap::decode_mime_string($input, $fallback);
2550 // return the results
2554 // no encoding information, use fallback
2555 return rcube_charset_convert($input,
2556 !empty($fallback) ? $fallback : rcmail::get_instance()->config->get('default_charset', 'ISO-8859-1'));
2561 * Decode a part of a mime-encoded string
2565 function _decode_mime_string_part($str)
2567 $a = explode('?', $str);
2570 // should be in format "charset?encoding?base64_string"
2573 for ($i=2; $i<$count; $i++)
2576 if (($a[1]=="B")||($a[1]=="b"))
2577 $rest = base64_decode($rest);
2578 else if (($a[1]=="Q")||($a[1]=="q"))
2580 $rest = str_replace("_", " ", $rest);
2581 $rest = quoted_printable_decode($rest);
2584 return rcube_charset_convert($rest, $a[0]);
2587 return $str; // we dont' know what to do with this
2592 * Decode a mime part
2594 * @param string Input string
2595 * @param string Part encoding
2596 * @return string Decoded string
2599 function mime_decode($input, $encoding='7bit')
2601 switch (strtolower($encoding))
2607 case 'quoted-printable':
2608 return quoted_printable_decode($input);
2612 return base64_decode($input);
2622 * Convert body charset to UTF-8 according to the ctype_parameters
2624 * @param string Part body to decode
2625 * @param string Charset to convert from
2626 * @return string Content converted to internal charset
2628 function charset_decode($body, $ctype_param)
2630 if (is_array($ctype_param) && !empty($ctype_param['charset']))
2631 return rcube_charset_convert($body, $ctype_param['charset']);
2633 // defaults to what is specified in the class header
2634 return rcube_charset_convert($body, $this->default_charset);
2639 * Translate UID to message ID
2641 * @param int Message UID
2642 * @param string Mailbox name
2643 * @return int Message ID
2645 function get_id($uid, $mbox_name=NULL)
2647 $mailbox = $mbox_name ? $this->_mod_mailbox($mbox_name) : $this->mailbox;
2648 return $this->_uid2id($uid, $mailbox);
2653 * Translate message number to UID
2655 * @param int Message ID
2656 * @param string Mailbox name
2657 * @return int Message UID
2659 function get_uid($id,$mbox_name=NULL)
2661 $mailbox = $mbox_name ? $this->_mod_mailbox($mbox_name) : $this->mailbox;
2662 return $this->_id2uid($id, $mailbox);
2667 /* --------------------------------
2669 * --------------------------------*/
2675 function _mod_mailbox($mbox_name, $mode='in')
2677 if ((!empty($this->root_ns) && $this->root_ns == $mbox_name) || $mbox_name == 'INBOX')
2680 if (!empty($this->root_dir) && $mode=='in')
2681 $mbox_name = $this->root_dir.$this->delimiter.$mbox_name;
2682 else if (strlen($this->root_dir) && $mode=='out')
2683 $mbox_name = substr($mbox_name, strlen($this->root_dir)+1);
2689 * Validate the given input and save to local properties
2692 function _set_sort_order($sort_field, $sort_order)
2694 if ($sort_field != null)
2695 $this->sort_field = asciiwords($sort_field);
2696 if ($sort_order != null)
2697 $this->sort_order = strtoupper($sort_order) == 'DESC' ? 'DESC' : 'ASC';
2701 * Sort mailboxes first by default folders and then in alphabethical order
2704 function _sort_mailbox_list($a_folders)
2706 $a_out = $a_defaults = $folders = array();
2708 $delimiter = $this->get_hierarchy_delimiter();
2710 // find default folders and skip folders starting with '.'
2711 foreach ($a_folders as $i => $folder)
2713 if ($folder{0}=='.')
2716 if (($p = array_search(strtolower($folder), $this->default_folders_lc)) !== false && !$a_defaults[$p])
2717 $a_defaults[$p] = $folder;
2719 $folders[$folder] = rc_strtolower(rcube_charset_convert($folder, 'UTF-7'));
2722 // sort folders and place defaults on the top
2723 asort($folders, SORT_LOCALE_STRING);
2725 $folders = array_merge($a_defaults, array_keys($folders));
2727 // finally we must rebuild the list to move
2728 // subfolders of default folders to their place...
2729 // ...also do this for the rest of folders because
2730 // asort() is not properly sorting case sensitive names
2731 while (list($key, $folder) = each($folders)) {
2732 // set the type of folder name variable (#1485527)
2733 $a_out[] = (string) $folder;
2734 unset($folders[$key]);
2735 $this->_rsort($folder, $delimiter, $folders, $a_out);
2745 function _rsort($folder, $delimiter, &$list, &$out)
2747 while (list($key, $name) = each($list)) {
2748 if (strpos($name, $folder.$delimiter) === 0) {
2749 // set the type of folder name variable (#1485527)
2750 $out[] = (string) $name;
2752 $this->_rsort($name, $delimiter, $list, $out);
2762 function _uid2id($uid, $mbox_name=NULL)
2765 $mbox_name = $this->mailbox;
2767 if (!isset($this->uid_id_map[$mbox_name][$uid]))
2768 $this->uid_id_map[$mbox_name][$uid] = iil_C_UID2ID($this->conn, $mbox_name, $uid);
2770 return $this->uid_id_map[$mbox_name][$uid];
2776 function _id2uid($id, $mbox_name=NULL)
2779 $mbox_name = $this->mailbox;
2781 $index = array_flip((array)$this->uid_id_map[$mbox_name]);
2782 if (isset($index[$id]))
2786 $uid = iil_C_ID2UID($this->conn, $mbox_name, $id);
2787 $this->uid_id_map[$mbox_name][$uid] = $id;
2795 * Subscribe/unsubscribe a list of mailboxes and update local cache
2798 function _change_subscription($a_mboxes, $mode)
2802 if (is_array($a_mboxes))
2803 foreach ($a_mboxes as $i => $mbox_name)
2805 $mailbox = $this->_mod_mailbox($mbox_name);
2806 $a_mboxes[$i] = $mailbox;
2808 if ($mode=='subscribe')
2809 $result = iil_C_Subscribe($this->conn, $mailbox);
2810 else if ($mode=='unsubscribe')
2811 $result = iil_C_UnSubscribe($this->conn, $mailbox);
2817 // get cached mailbox list
2820 $a_mailbox_cache = $this->get_cache('mailboxes');
2821 if (!is_array($a_mailbox_cache))
2824 // modify cached list
2825 if ($mode=='subscribe')
2826 $a_mailbox_cache = array_merge($a_mailbox_cache, $a_mboxes);
2827 else if ($mode=='unsubscribe')
2828 $a_mailbox_cache = array_diff($a_mailbox_cache, $a_mboxes);
2830 // write mailboxlist to cache
2831 $this->update_cache('mailboxes', $this->_sort_mailbox_list($a_mailbox_cache));
2839 * Increde/decrese messagecount for a specific mailbox
2842 function _set_messagecount($mbox_name, $mode, $increment)
2844 $a_mailbox_cache = FALSE;
2845 $mailbox = $mbox_name ? $mbox_name : $this->mailbox;
2846 $mode = strtoupper($mode);
2848 $a_mailbox_cache = $this->get_cache('messagecount');
2850 if (!is_array($a_mailbox_cache[$mailbox]) || !isset($a_mailbox_cache[$mailbox][$mode]) || !is_numeric($increment))
2853 // add incremental value to messagecount
2854 $a_mailbox_cache[$mailbox][$mode] += $increment;
2856 // there's something wrong, delete from cache
2857 if ($a_mailbox_cache[$mailbox][$mode] < 0)
2858 unset($a_mailbox_cache[$mailbox][$mode]);
2860 // write back to cache
2861 $this->update_cache('messagecount', $a_mailbox_cache);
2868 * Remove messagecount of a specific mailbox from cache
2871 function _clear_messagecount($mbox_name='')
2873 $a_mailbox_cache = FALSE;
2874 $mailbox = $mbox_name ? $mbox_name : $this->mailbox;
2876 $a_mailbox_cache = $this->get_cache('messagecount');
2878 if (is_array($a_mailbox_cache[$mailbox]))
2880 unset($a_mailbox_cache[$mailbox]);
2881 $this->update_cache('messagecount', $a_mailbox_cache);
2887 * Split RFC822 header string into an associative array
2890 function _parse_headers($headers)
2892 $a_headers = array();
2893 $lines = explode("\n", $headers);
2895 for ($i=0; $i<$c; $i++)
2897 if ($p = strpos($lines[$i], ': '))
2899 $field = strtolower(substr($lines[$i], 0, $p));
2900 $value = trim(substr($lines[$i], $p+1));
2902 $a_headers[$field] = $value;
2913 function _parse_address_list($str, $decode=true)
2915 // remove any newlines and carriage returns before
2916 $a = $this->_explode_quoted_string('[,;]', preg_replace( "/[\r\n]/", " ", $str));
2919 foreach ($a as $key => $val)
2921 $val = preg_replace("/([\"\w])</", "$1 <", $val);
2922 $sub_a = $this->_explode_quoted_string(' ', $decode ? $this->decode_header($val) : $val);
2923 $result[$key]['name'] = '';
2925 foreach ($sub_a as $k => $v)
2927 if (strpos($v, '@') > 0)
2928 $result[$key]['address'] = str_replace('<', '', str_replace('>', '', $v));
2930 $result[$key]['name'] .= (empty($result[$key]['name'])?'':' ').str_replace("\"",'',stripslashes($v));
2933 if (empty($result[$key]['name']))
2934 $result[$key]['name'] = $result[$key]['address'];
2944 function _explode_quoted_string($delimiter, $string)
2947 $strlen = strlen($string);
2948 for ($q=$p=$i=0; $i < $strlen; $i++)
2950 if ($string{$i} == "\"" && $string{$i-1} != "\\")
2951 $q = $q ? false : true;
2952 else if (!$q && preg_match("/$delimiter/", $string{$i}))
2954 $result[] = substr($string, $p, $i - $p);
2959 $result[] = substr($string, $p);
2963 } // end class rcube_imap
2967 * Class representing a message part
2971 class rcube_message_part
2974 var $ctype_primary = 'text';
2975 var $ctype_secondary = 'plain';
2976 var $mimetype = 'text/plain';
2977 var $disposition = '';
2979 var $encoding = '8bit';
2982 var $headers = array();
2983 var $d_parameters = array();
2984 var $ctype_parameters = array();
2990 * Class for sorting an array of iilBasicHeader objects in a predetermined order.
2993 * @author Eric Stadtherr
2995 class rcube_header_sorter
2997 var $sequence_numbers = array();
3000 * Set the predetermined sort order.
3002 * @param array Numerically indexed array of IMAP message sequence numbers
3004 function set_sequence_numbers($seqnums)
3006 $this->sequence_numbers = array_flip($seqnums);
3010 * Sort the array of header objects
3012 * @param array Array of iilBasicHeader objects indexed by UID
3014 function sort_headers(&$headers)
3017 * uksort would work if the keys were the sequence number, but unfortunately
3018 * the keys are the UIDs. We'll use uasort instead and dereference the value
3019 * to get the sequence number (in the "id" field).
3021 * uksort($headers, array($this, "compare_seqnums"));
3023 uasort($headers, array($this, "compare_seqnums"));
3027 * Sort method called by uasort()
3029 function compare_seqnums($a, $b)
3031 // First get the sequence number from the header object (the 'id' field).
3035 // then find each sequence number in my ordered list
3036 $posa = isset($this->sequence_numbers[$seqa]) ? intval($this->sequence_numbers[$seqa]) : -1;
3037 $posb = isset($this->sequence_numbers[$seqb]) ? intval($this->sequence_numbers[$seqb]) : -1;
3039 // return the relative position as the comparison value
3040 return $posa - $posb;
3046 * Add quoted-printable encoding to a given string
3048 * @param string String to encode
3049 * @param int Add new line after this number of characters
3050 * @param boolean True if spaces should be converted into =20
3051 * @return string Encoded string
3053 function quoted_printable_encode($input, $line_max=76, $space_conv=false)
3055 $hex = array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');
3056 $lines = preg_split("/(?:\r\n|\r|\n)/", $input);
3061 while( list(, $line) = each($lines))
3063 //$line = rtrim($line); // remove trailing white space -> no =20\r\n necessary
3064 $linlen = strlen($line);
3066 for($i = 0; $i < $linlen; $i++)
3068 $c = substr( $line, $i, 1 );
3070 if ( ( $i == 0 ) && ( $dec == 46 ) ) // convert first point in the line into =2E
3076 if ( $i == ( $linlen - 1 ) ) // convert space at eol only
3080 else if ( $space_conv )
3085 else if ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) ) // always encode "\t", which is *not* required
3087 $h2 = floor($dec/16);
3088 $h1 = floor($dec%16);
3089 $c = $escape.$hex["$h2"].$hex["$h1"];
3092 if ( (strlen($newline) + strlen($c)) >= $line_max ) // CRLF is not counted
3094 $output .= $newline.$escape.$eol; // soft line break; " =\r\n" is okay
3096 // check if newline first character will be point or not
3104 $output .= $newline.$eol;
3107 return trim($output);