4 +-----------------------------------------------------------------------+
5 | program/include/rcube_imap.php |
7 | This file is part of the RoundCube Webmail client |
8 | Copyright (C) 2005-2009, 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 3048 2009-10-19 07:47:10Z alec $
25 * Obtain classes from the Iloha IMAP library
27 require_once('lib/imap.inc');
28 require_once('lib/mime.inc');
29 require_once('lib/tnef_decoder.inc');
33 * Interface class for accessing an IMAP server
35 * This is a wrapper that implements the Iloha IMAP Library (IIL)
38 * @author Thomas Bruederli <roundcube@gmail.com>
40 * @link http://ilohamail.org
48 var $mailbox = 'INBOX';
51 var $sort_field = 'date';
52 var $sort_order = 'DESC';
53 var $index_sort = true;
54 var $delimiter = NULL;
55 var $caching_enabled = FALSE;
56 var $default_charset = 'ISO-8859-1';
57 var $struct_charset = NULL;
58 var $default_folders = array('INBOX');
59 var $default_folders_lc = array('inbox');
60 var $fetch_add_headers = '';
62 var $cache_keys = array();
63 var $cache_changes = array();
64 var $uid_id_map = array();
65 var $msg_headers = array();
66 var $skip_deleted = FALSE;
67 var $search_set = NULL;
68 var $search_string = '';
69 var $search_charset = '';
70 var $search_sort_field = '';
73 var $options = array('auth_method' => 'check');
75 private $host, $user, $pass, $port, $ssl;
81 * @param object DB Database connection
83 function __construct($db_conn)
90 * Connect to an IMAP server
92 * @param string Host to connect
93 * @param string Username for IMAP account
94 * @param string Password for IMAP account
95 * @param number Port to connect to
96 * @param string SSL schema (either ssl or tls) or null if plain connection
97 * @return boolean TRUE on success, FALSE on failure
100 function connect($host, $user, $pass, $port=143, $use_ssl=null)
102 global $ICL_SSL, $ICL_PORT, $IMAP_USE_INTERNAL_DATE;
104 // check for Open-SSL support in PHP build
105 if ($use_ssl && extension_loaded('openssl'))
106 $ICL_SSL = $use_ssl == 'imaps' ? 'ssl' : $use_ssl;
108 raise_error(array('code' => 403, 'type' => 'imap', 'file' => __FILE__,
109 'message' => 'Open SSL not available;'), TRUE, FALSE);
114 $IMAP_USE_INTERNAL_DATE = false;
118 $data = rcmail::get_instance()->plugins->exec_hook('imap_connect', array('host' => $host, 'user' => $user, 'attempt' => ++$attempt));
119 if (!empty($data['pass']))
120 $pass = $data['pass'];
122 $this->conn = iil_Connect($data['host'], $data['user'], $pass, $this->options);
123 } while(!$this->conn && $data['retry']);
125 $this->host = $data['host'];
126 $this->user = $data['user'];
129 $this->ssl = $use_ssl;
131 // print trace messages
132 if ($this->conn && ($this->debug_level & 8))
133 console($this->conn->message);
136 else if (!$this->conn && $GLOBALS['iil_error'])
138 $this->error_code = $GLOBALS['iil_errornum'];
139 raise_error(array('code' => 403,
141 'message' => $GLOBALS['iil_error']), TRUE, FALSE);
144 // get server properties
147 if (!empty($this->conn->rootdir))
149 $this->set_rootdir($this->conn->rootdir);
150 $this->root_ns = preg_replace('/[.\/]$/', '', $this->conn->rootdir);
152 if (empty($this->delimiter))
153 $this->get_hierarchy_delimiter();
156 return $this->conn ? TRUE : FALSE;
161 * Close IMAP connection
162 * Usually done on script shutdown
169 iil_Close($this->conn);
174 * Close IMAP connection and re-connect
175 * This is used to avoid some strange socket errors when talking to Courier IMAP
182 $this->connect($this->host, $this->user, $this->pass, $this->port, $this->ssl);
184 // issue SELECT command to restore connection status
186 iil_C_Select($this->conn, $this->mailbox);
190 * Set options to be used in iil_Connect()
192 function set_options($opt)
194 $this->options = array_merge($this->options, (array)$opt);
198 * Set a root folder for the IMAP connection.
200 * Only folders within this root folder will be displayed
201 * and all folder paths will be translated using this folder name
203 * @param string Root folder
206 function set_rootdir($root)
208 if (preg_match('/[.\/]$/', $root)) //(substr($root, -1, 1)==='/')
209 $root = substr($root, 0, -1);
211 $this->root_dir = $root;
212 $this->options['rootdir'] = $root;
214 if (empty($this->delimiter))
215 $this->get_hierarchy_delimiter();
220 * Set default message charset
222 * This will be used for message decoding if a charset specification is not available
224 * @param string Charset string
227 function set_charset($cs)
229 $this->default_charset = $cs;
234 * This list of folders will be listed above all other folders
236 * @param array Indexed list of folder names
239 function set_default_mailboxes($arr)
243 $this->default_folders = $arr;
244 $this->default_folders_lc = array();
246 // add inbox if not included
247 if (!in_array_nocase('INBOX', $this->default_folders))
248 array_unshift($this->default_folders, 'INBOX');
250 // create a second list with lower cased names
251 foreach ($this->default_folders as $mbox)
252 $this->default_folders_lc[] = strtolower($mbox);
258 * Set internal mailbox reference.
260 * All operations will be perfomed on this mailbox/folder
262 * @param string Mailbox/Folder name
265 function set_mailbox($new_mbox)
267 $mailbox = $this->mod_mailbox($new_mbox);
269 if ($this->mailbox == $mailbox)
272 $this->mailbox = $mailbox;
274 // clear messagecount cache for this mailbox
275 $this->_clear_messagecount($mailbox);
280 * Set internal list page
282 * @param number Page number to list
285 function set_page($page)
287 $this->list_page = (int)$page;
292 * Set internal page size
294 * @param number Number of messages to display on one page
297 function set_pagesize($size)
299 $this->page_size = (int)$size;
304 * Save a set of message ids for future message listing methods
306 * @param string IMAP Search query
307 * @param array List of message ids or NULL if empty
308 * @param string Charset of search string
309 * @param string Sorting field
311 function set_search_set($str=null, $msgs=null, $charset=null, $sort_field=null)
313 if (is_array($str) && $msgs == null)
314 list($str, $msgs, $charset, $sort_field) = $str;
315 if ($msgs != null && !is_array($msgs))
316 $msgs = explode(',', $msgs);
318 $this->search_string = $str;
319 $this->search_set = $msgs;
320 $this->search_charset = $charset;
321 $this->search_sort_field = $sort_field;
326 * Return the saved search set as hash array
327 * @return array Search set
329 function get_search_set()
331 return array($this->search_string, $this->search_set, $this->search_charset, $this->search_sort_field);
336 * Returns the currently used mailbox name
338 * @return string Name of the mailbox/folder
341 function get_mailbox_name()
343 return $this->conn ? $this->mod_mailbox($this->mailbox, 'out') : '';
348 * Returns the IMAP server's capability
350 * @param string Capability name
351 * @return mixed Capability value or TRUE if supported, FALSE if not
354 function get_capability($cap)
356 return iil_C_GetCapability($this->conn, strtoupper($cap));
361 * Checks the PERMANENTFLAGS capability of the current mailbox
362 * and returns true if the given flag is supported by the IMAP server
364 * @param string Permanentflag name
365 * @return mixed True if this flag is supported
368 function check_permflag($flag)
370 $flag = strtoupper($flag);
371 $imap_flag = $GLOBALS['IMAP_FLAGS'][$flag];
372 return (in_array_nocase($imap_flag, $this->conn->permanentflags));
377 * Returns the delimiter that is used by the IMAP server for folder separation
379 * @return string Delimiter string
382 function get_hierarchy_delimiter()
384 if ($this->conn && empty($this->delimiter))
385 $this->delimiter = iil_C_GetHierarchyDelimiter($this->conn);
387 if (empty($this->delimiter))
388 $this->delimiter = '/';
390 return $this->delimiter;
395 * Public method for mailbox listing.
397 * Converts mailbox name with root dir first
399 * @param string Optional root folder
400 * @param string Optional filter for mailbox listing
401 * @return array List of mailboxes/folders
404 function list_mailboxes($root='', $filter='*')
407 $a_mboxes = $this->_list_mailboxes($root, $filter);
409 foreach ($a_mboxes as $mbox_row)
411 $name = $this->mod_mailbox($mbox_row, 'out');
416 // INBOX should always be available
417 if (!in_array_nocase('INBOX', $a_out))
418 array_unshift($a_out, 'INBOX');
421 $a_out = $this->_sort_mailbox_list($a_out);
428 * Private method for mailbox listing
430 * @return array List of mailboxes/folders
431 * @see rcube_imap::list_mailboxes()
434 private function _list_mailboxes($root='', $filter='*')
436 $a_defaults = $a_out = array();
438 // get cached folder list
439 $a_mboxes = $this->get_cache('mailboxes');
440 if (is_array($a_mboxes))
443 // Give plugins a chance to provide a list of mailboxes
444 $data = rcmail::get_instance()->plugins->exec_hook('list_mailboxes',array('root'=>$root,'filter'=>$filter));
445 if (isset($data['folders'])) {
446 $a_folders = $data['folders'];
449 // retrieve list of folders from IMAP server
450 $a_folders = iil_C_ListSubscribed($this->conn, $this->mod_mailbox($root), $filter);
454 if (!is_array($a_folders) || !sizeof($a_folders))
455 $a_folders = array();
457 // write mailboxlist to cache
458 $this->update_cache('mailboxes', $a_folders);
465 * Get message count for a specific mailbox
467 * @param string Mailbox/folder name
468 * @param string Mode for count [ALL|UNSEEN|RECENT]
469 * @param boolean Force reading from server and update cache
470 * @return int Number of messages
473 function messagecount($mbox_name='', $mode='ALL', $force=FALSE)
475 $mailbox = $mbox_name ? $this->mod_mailbox($mbox_name) : $this->mailbox;
476 return $this->_messagecount($mailbox, $mode, $force);
481 * Private method for getting nr of messages
484 * @see rcube_imap::messagecount()
486 private function _messagecount($mailbox='', $mode='ALL', $force=FALSE)
488 $mode = strtoupper($mode);
491 $mailbox = $this->mailbox;
494 if ($this->search_string && $mailbox == $this->mailbox && $mode == 'ALL' && !$force)
495 return count((array)$this->search_set);
497 $a_mailbox_cache = $this->get_cache('messagecount');
499 // return cached value
500 if (!$force && is_array($a_mailbox_cache[$mailbox]) && isset($a_mailbox_cache[$mailbox][$mode]))
501 return $a_mailbox_cache[$mailbox][$mode];
503 // RECENT count is fetched a bit different
504 if ($mode == 'RECENT')
505 $count = iil_C_CheckForRecent($this->conn, $mailbox);
507 // use SEARCH for message counting
508 else if ($this->skip_deleted)
510 $search_str = "ALL UNDELETED";
512 // get message count and store in cache
513 if ($mode == 'UNSEEN')
514 $search_str .= " UNSEEN";
516 // get message count using SEARCH
517 // not very performant but more precise (using UNDELETED)
518 $index = $this->_search_index($mailbox, $search_str);
519 $count = is_array($index) ? count($index) : 0;
523 if ($mode == 'UNSEEN')
524 $count = iil_C_CountUnseen($this->conn, $mailbox);
526 $count = iil_C_CountMessages($this->conn, $mailbox);
529 if (!is_array($a_mailbox_cache[$mailbox]))
530 $a_mailbox_cache[$mailbox] = array();
532 $a_mailbox_cache[$mailbox][$mode] = (int)$count;
534 // write back to cache
535 $this->update_cache('messagecount', $a_mailbox_cache);
542 * Public method for listing headers
543 * convert mailbox name with root dir first
545 * @param string Mailbox/folder name
546 * @param int Current page to list
547 * @param string Header field to sort by
548 * @param string Sort order [ASC|DESC]
549 * @param boolean Number of slice items to extract from result array
550 * @return array Indexed array with message header objects
553 function list_headers($mbox_name='', $page=NULL, $sort_field=NULL, $sort_order=NULL, $slice=0)
555 $mailbox = $mbox_name ? $this->mod_mailbox($mbox_name) : $this->mailbox;
556 return $this->_list_headers($mailbox, $page, $sort_field, $sort_order, false, $slice);
561 * Private method for listing message headers
564 * @see rcube_imap::list_headers
566 private function _list_headers($mailbox='', $page=NULL, $sort_field=NULL, $sort_order=NULL, $recursive=FALSE, $slice=0)
568 if (!strlen($mailbox))
571 // use saved message set
572 if ($this->search_string && $mailbox == $this->mailbox)
573 return $this->_list_header_set($mailbox, $page, $sort_field, $sort_order, $slice);
575 $this->_set_sort_order($sort_field, $sort_order);
577 $page = $page ? $page : $this->list_page;
578 $cache_key = $mailbox.'.msg';
579 $cache_status = $this->check_cache_status($mailbox, $cache_key);
581 // cache is OK, we can get all messages from local cache
584 $start_msg = ($page-1) * $this->page_size;
585 $a_msg_headers = $this->get_message_cache($cache_key, $start_msg, $start_msg+$this->page_size, $this->sort_field, $this->sort_order);
586 $result = array_values($a_msg_headers);
588 $result = array_slice($result, -$slice, $slice);
591 // cache is dirty, sync it
592 else if ($this->caching_enabled && $cache_status==-1 && !$recursive)
594 $this->sync_header_index($mailbox);
595 return $this->_list_headers($mailbox, $page, $this->sort_field, $this->sort_order, TRUE, $slice);
598 // retrieve headers from IMAP
599 $a_msg_headers = array();
601 // use message index sort for sorting by Date (for better performance)
602 if ($this->index_sort && $this->sort_field == 'date')
604 if ($this->skip_deleted) {
605 // @TODO: this could be cached
606 if ($msg_index = $this->_search_index($mailbox, 'ALL UNDELETED')) {
607 $max = max($msg_index);
608 list($begin, $end) = $this->_get_message_range(count($msg_index), $page);
609 $msg_index = array_slice($msg_index, $begin, $end-$begin);
611 } else if ($max = iil_C_CountMessages($this->conn, $mailbox)) {
612 list($begin, $end) = $this->_get_message_range($max, $page);
613 $msg_index = range($begin+1, $end);
615 $msg_index = array();
618 $msg_index = array_slice($msg_index, ($this->sort_order == 'DESC' ? 0 : -$slice), $slice);
620 // fetch reqested headers from server
622 $this->_fetch_headers($mailbox, join(",", $msg_index), $a_msg_headers, $cache_key);
625 else if ($this->get_capability('sort') && ($msg_index = iil_C_Sort($this->conn, $mailbox, $this->sort_field, $this->skip_deleted ? 'UNDELETED' : '')))
627 list($begin, $end) = $this->_get_message_range(count($msg_index), $page);
628 $max = max($msg_index);
629 $msg_index = array_slice($msg_index, $begin, $end-$begin);
632 $msg_index = array_slice($msg_index, ($this->sort_order == 'DESC' ? 0 : -$slice), $slice);
634 // fetch reqested headers from server
635 $this->_fetch_headers($mailbox, join(',', $msg_index), $a_msg_headers, $cache_key);
637 // fetch specified header for all messages and sort
638 else if ($a_index = iil_C_FetchHeaderIndex($this->conn, $mailbox, "1:*", $this->sort_field, $this->skip_deleted))
640 asort($a_index); // ASC
641 $msg_index = array_keys($a_index);
642 $max = max($msg_index);
643 list($begin, $end) = $this->_get_message_range(count($msg_index), $page);
644 $msg_index = array_slice($msg_index, $begin, $end-$begin);
647 $msg_index = array_slice($msg_index, ($this->sort_order == 'DESC' ? 0 : -$slice), $slice);
649 // fetch reqested headers from server
650 $this->_fetch_headers($mailbox, join(",", $msg_index), $a_msg_headers, $cache_key);
653 // delete cached messages with a higher index than $max+1
654 // Changed $max to $max+1 to fix this bug : #1484295
655 $this->clear_message_cache($cache_key, $max + 1);
657 // kick child process to sync cache
660 // return empty array if no messages found
661 if (!is_array($a_msg_headers) || empty($a_msg_headers))
664 // use this class for message sorting
665 $sorter = new rcube_header_sorter();
666 $sorter->set_sequence_numbers($msg_index);
667 $sorter->sort_headers($a_msg_headers);
669 if ($this->sort_order == 'DESC')
670 $a_msg_headers = array_reverse($a_msg_headers);
672 return array_values($a_msg_headers);
677 * Private method for listing a set of message headers (search results)
679 * @param string Mailbox/folder name
680 * @param int Current page to list
681 * @param string Header field to sort by
682 * @param string Sort order [ASC|DESC]
683 * @param boolean Number of slice items to extract from result array
684 * @return array Indexed array with message header objects
686 * @see rcube_imap::list_header_set()
688 private function _list_header_set($mailbox, $page=NULL, $sort_field=NULL, $sort_order=NULL, $slice=0)
690 if (!strlen($mailbox) || empty($this->search_set))
693 $msgs = $this->search_set;
694 $a_msg_headers = array();
695 $page = $page ? $page : $this->list_page;
696 $start_msg = ($page-1) * $this->page_size;
698 $this->_set_sort_order($sort_field, $sort_order);
701 if ($this->index_sort && $this->search_sort_field == 'date' && $this->sort_field == 'date')
703 if ($sort_order == 'DESC')
704 $msgs = array_reverse($msgs);
706 // get messages uids for one page
707 $msgs = array_slice(array_values($msgs), $start_msg, min(count($msgs)-$start_msg, $this->page_size));
710 $msgs = array_slice($msgs, -$slice, $slice);
713 $this->_fetch_headers($mailbox, join(',',$msgs), $a_msg_headers, NULL);
715 // I didn't found in RFC that FETCH always returns messages sorted by index
716 $sorter = new rcube_header_sorter();
717 $sorter->set_sequence_numbers($msgs);
718 $sorter->sort_headers($a_msg_headers);
720 return array_values($a_msg_headers);
722 // sorted messages, so we can first slice array and then fetch only wanted headers
723 if ($this->get_capability('sort') && (!$this->index_sort || $this->sort_field != 'date')) // SORT searching result
725 // reset search set if sorting field has been changed
726 if ($this->sort_field && $this->search_sort_field != $this->sort_field)
727 $msgs = $this->search('', $this->search_string, $this->search_charset, $this->sort_field);
729 // return empty array if no messages found
733 if ($sort_order == 'DESC')
734 $msgs = array_reverse($msgs);
736 // get messages uids for one page
737 $msgs = array_slice(array_values($msgs), $start_msg, min(count($msgs)-$start_msg, $this->page_size));
740 $msgs = array_slice($msgs, -$slice, $slice);
743 $this->_fetch_headers($mailbox, join(',',$msgs), $a_msg_headers, NULL);
745 $sorter = new rcube_header_sorter();
746 $sorter->set_sequence_numbers($msgs);
747 $sorter->sort_headers($a_msg_headers);
749 return array_values($a_msg_headers);
751 else { // SEARCH searching result, need sorting
753 // 300: experimantal value for best result
754 if (($cnt > 300 && $cnt > $this->page_size) || ($this->index_sort && $this->sort_field == 'date')) {
755 // use memory less expensive (and quick) method for big result set
756 $a_index = $this->message_index('', $this->sort_field, $this->sort_order);
757 // get messages uids for one page...
758 $msgs = array_slice($a_index, $start_msg, min($cnt-$start_msg, $this->page_size));
760 $msgs = array_slice($msgs, -$slice, $slice);
761 // ...and fetch headers
762 $this->_fetch_headers($mailbox, join(',', $msgs), $a_msg_headers, NULL);
764 // return empty array if no messages found
765 if (!is_array($a_msg_headers) || empty($a_msg_headers))
768 $sorter = new rcube_header_sorter();
769 $sorter->set_sequence_numbers($msgs);
770 $sorter->sort_headers($a_msg_headers);
772 return array_values($a_msg_headers);
775 // for small result set we can fetch all messages headers
776 $this->_fetch_headers($mailbox, join(',', $msgs), $a_msg_headers, NULL);
778 // return empty array if no messages found
779 if (!is_array($a_msg_headers) || empty($a_msg_headers))
782 // if not already sorted
783 $a_msg_headers = iil_SortHeaders($a_msg_headers, $this->sort_field, $this->sort_order);
785 // only return the requested part of the set
786 $a_msg_headers = array_slice(array_values($a_msg_headers), $start_msg, min($cnt-$start_msg, $this->page_size));
788 $a_msg_headers = array_slice($a_msg_headers, -$slice, $slice);
790 return $a_msg_headers;
797 * Helper function to get first and last index of the requested set
799 * @param int message count
800 * @param mixed page number to show, or string 'all'
801 * @return array array with two values: first index, last index
804 private function _get_message_range($max, $page)
806 $start_msg = ($page-1) * $this->page_size;
813 else if ($this->sort_order=='DESC')
815 $begin = $max - $this->page_size - $start_msg;
816 $end = $max - $start_msg;
821 $end = $start_msg + $this->page_size;
824 if ($begin < 0) $begin = 0;
825 if ($end < 0) $end = $max;
826 if ($end > $max) $end = $max;
828 return array($begin, $end);
833 * Fetches message headers
836 * @param string Mailbox name
837 * @param string Message index to fetch
838 * @param array Reference to message headers array
839 * @param array Array with cache index
840 * @return int Messages count
843 private function _fetch_headers($mailbox, $msgs, &$a_msg_headers, $cache_key)
845 // fetch reqested headers from server
846 $a_header_index = iil_C_FetchHeaders($this->conn, $mailbox, $msgs, false, false, $this->fetch_add_headers);
848 if (!empty($a_header_index))
850 // cache is incomplete
851 $cache_index = $this->get_message_cache_index($cache_key);
853 foreach ($a_header_index as $i => $headers) {
854 if ($this->caching_enabled && $cache_index[$headers->id] != $headers->uid) {
855 // prevent index duplicates
856 if ($cache_index[$headers->id]) {
857 $this->remove_message_cache($cache_key, $headers->id, true);
858 unset($cache_index[$headers->id]);
860 // add message to cache
861 $this->add_message_cache($cache_key, $headers->id, $headers, NULL,
862 !in_array($headers->uid, $cache_index));
865 $a_msg_headers[$headers->uid] = $headers;
869 return count($a_msg_headers);
874 * Return sorted array of message IDs (not UIDs)
876 * @param string Mailbox to get index from
877 * @param string Sort column
878 * @param string Sort order [ASC, DESC]
879 * @return array Indexed array with message ids
881 function message_index($mbox_name='', $sort_field=NULL, $sort_order=NULL)
883 $this->_set_sort_order($sort_field, $sort_order);
885 $mailbox = $mbox_name ? $this->mod_mailbox($mbox_name) : $this->mailbox;
886 $key = "{$mailbox}:{$this->sort_field}:{$this->sort_order}:{$this->search_string}.msgi";
888 // we have a saved search result, get index from there
889 if (!isset($this->cache[$key]) && $this->search_string && $mailbox == $this->mailbox)
891 $this->cache[$key] = array();
893 // use message index sort for sorting by Date
894 if ($this->index_sort && $this->sort_field == 'date')
896 $msgs = $this->search_set;
898 if ($this->search_sort_field != 'date')
901 if ($this->sort_order == 'DESC')
902 $this->cache[$key] = array_reverse($msgs);
904 $this->cache[$key] = $msgs;
906 // sort with SORT command
907 else if ($this->get_capability('sort'))
909 if ($this->sort_field && $this->search_sort_field != $this->sort_field)
910 $this->search('', $this->search_string, $this->search_charset, $this->sort_field);
912 if ($this->sort_order == 'DESC')
913 $this->cache[$key] = array_reverse($this->search_set);
915 $this->cache[$key] = $this->search_set;
919 $a_index = iil_C_FetchHeaderIndex($this->conn, $mailbox, join(',', $this->search_set), $this->sort_field, $this->skip_deleted);
921 if ($this->sort_order=="ASC")
923 else if ($this->sort_order=="DESC")
926 $this->cache[$key] = array_keys($a_index);
930 // have stored it in RAM
931 if (isset($this->cache[$key]))
932 return $this->cache[$key];
935 $cache_key = $mailbox.'.msg';
936 $cache_status = $this->check_cache_status($mailbox, $cache_key);
941 $a_index = $this->get_message_cache_index($cache_key, TRUE, $this->sort_field, $this->sort_order);
942 return array_keys($a_index);
945 // use message index sort for sorting by Date
946 if ($this->index_sort && $this->sort_field == 'date')
948 if ($this->skip_deleted) {
949 $a_index = $this->_search_index($mailbox, 'ALL');
950 } else if ($max = $this->_messagecount($mailbox)) {
951 $a_index = range(1, $max);
954 if ($this->sort_order == 'DESC')
955 $a_index = array_reverse($a_index);
957 $this->cache[$key] = $a_index;
959 // fetch complete message index
960 else if ($this->get_capability('sort') && ($a_index = iil_C_Sort($this->conn, $mailbox, $this->sort_field, $this->skip_deleted ? 'UNDELETED' : '')))
962 if ($this->sort_order == 'DESC')
963 $a_index = array_reverse($a_index);
965 $this->cache[$key] = $a_index;
969 $a_index = iil_C_FetchHeaderIndex($this->conn, $mailbox, "1:*", $this->sort_field, $this->skip_deleted);
971 if ($this->sort_order=="ASC")
973 else if ($this->sort_order=="DESC")
976 $this->cache[$key] = array_keys($a_index);
979 return $this->cache[$key];
986 function sync_header_index($mailbox)
988 $cache_key = $mailbox.'.msg';
989 $cache_index = $this->get_message_cache_index($cache_key);
991 // fetch complete message index
992 $a_message_index = iil_C_FetchHeaderIndex($this->conn, $mailbox, "1:*", 'UID', $this->skip_deleted);
994 if ($a_message_index === false)
997 foreach ($a_message_index as $id => $uid)
999 // message in cache at correct position
1000 if ($cache_index[$id] == $uid)
1002 unset($cache_index[$id]);
1006 // message in cache but in wrong position
1007 if (in_array((string)$uid, $cache_index, TRUE))
1009 unset($cache_index[$id]);
1012 // other message at this position
1013 if (isset($cache_index[$id]))
1015 $for_remove[] = $cache_index[$id];
1016 unset($cache_index[$id]);
1019 $for_update[] = $id;
1022 // clear messages at wrong positions and those deleted that are still in cache_index
1023 if (!empty($for_remove))
1024 $cache_index = array_merge($cache_index, $for_remove);
1026 if (!empty($cache_index))
1027 $this->remove_message_cache($cache_key, $cache_index);
1029 // fetch complete headers and add to cache
1030 if (!empty($for_update)) {
1031 if ($headers = iil_C_FetchHeader($this->conn, $mailbox, join(',', $for_update), false, $this->fetch_add_headers))
1032 foreach ($headers as $header)
1033 $this->add_message_cache($cache_key, $header->id, $header, NULL,
1034 in_array($header->uid, (array)$for_remove));
1040 * Invoke search request to IMAP server
1042 * @param string mailbox name to search in
1043 * @param string search string
1044 * @param string search string charset
1045 * @param string header field to sort by
1046 * @return array search results as list of message ids
1049 function search($mbox_name='', $str=NULL, $charset=NULL, $sort_field=NULL)
1054 $mailbox = $mbox_name ? $this->mod_mailbox($mbox_name) : $this->mailbox;
1056 $results = $this->_search_index($mailbox, $str, $charset, $sort_field);
1058 // try search with US-ASCII charset (should be supported by server)
1059 // only if UTF-8 search is not supported
1060 if (empty($results) && !is_array($results) && !empty($charset) && $charset != 'US-ASCII')
1062 // convert strings to US_ASCII
1063 if(preg_match_all('/\{([0-9]+)\}\r\n/', $str, $matches, PREG_OFFSET_CAPTURE))
1065 $last = 0; $res = '';
1066 foreach($matches[1] as $m)
1068 $string_offset = $m[1] + strlen($m[0]) + 4; // {}\r\n
1069 $string = substr($str, $string_offset - 1, $m[0]);
1070 $string = rcube_charset_convert($string, $charset, 'US-ASCII');
1071 if (!$string) continue;
1072 $res .= sprintf("%s{%d}\r\n%s", substr($str, $last, $m[1] - $last - 1), strlen($string), $string);
1073 $last = $m[0] + $string_offset - 1;
1075 if ($last < strlen($str))
1076 $res .= substr($str, $last, strlen($str)-$last);
1078 else // strings for conversion not found
1081 $results = $this->search($mbox_name, $res, NULL, $sort_field);
1084 $this->set_search_set($str, $results, $charset, $sort_field);
1091 * Private search method
1093 * @return array search results as list of message ids
1095 * @see rcube_imap::search()
1097 private function _search_index($mailbox, $criteria='ALL', $charset=NULL, $sort_field=NULL)
1099 $orig_criteria = $criteria;
1101 if ($this->skip_deleted && !preg_match('/UNDELETED/', $criteria))
1102 $criteria = 'UNDELETED '.$criteria;
1104 if ($sort_field && $this->get_capability('sort') && (!$this->index_sort || $sort_field != 'date')) {
1105 $charset = $charset ? $charset : $this->default_charset;
1106 $a_messages = iil_C_Sort($this->conn, $mailbox, $sort_field, $criteria, FALSE, $charset);
1109 if ($orig_criteria == 'ALL') {
1110 $max = $this->_messagecount($mailbox);
1111 $a_messages = $max ? range(1, $max) : array();
1114 $a_messages = iil_C_Search($this->conn, $mailbox, ($charset ? "CHARSET $charset " : '') . $criteria);
1116 // I didn't found that SEARCH always returns sorted IDs
1117 if ($this->index_sort && $this->sort_field == 'date')
1121 // update messagecount cache ?
1122 // $a_mailbox_cache = get_cache('messagecount');
1123 // $a_mailbox_cache[$mailbox][$criteria] = sizeof($a_messages);
1124 // $this->update_cache('messagecount', $a_mailbox_cache);
1131 * Refresh saved search set
1133 * @return array Current search set
1135 function refresh_search()
1137 if (!empty($this->search_string))
1138 $this->search_set = $this->search('', $this->search_string, $this->search_charset, $this->search_sort_field);
1140 return $this->get_search_set();
1145 * Check if the given message ID is part of the current search set
1147 * @return boolean True on match or if no search request is stored
1149 function in_searchset($msgid)
1151 if (!empty($this->search_string))
1152 return in_array("$msgid", (array)$this->search_set, true);
1159 * Return message headers object of a specific message
1161 * @param int Message ID
1162 * @param string Mailbox to read from
1163 * @param boolean True if $id is the message UID
1164 * @param boolean True if we need also BODYSTRUCTURE in headers
1165 * @return object Message headers representation
1167 function get_headers($id, $mbox_name=NULL, $is_uid=TRUE, $bodystr=FALSE)
1169 $mailbox = $mbox_name ? $this->mod_mailbox($mbox_name) : $this->mailbox;
1170 $uid = $is_uid ? $id : $this->_id2uid($id);
1172 // get cached headers
1173 if ($uid && ($headers = &$this->get_cached_message($mailbox.'.msg', $uid)))
1176 $headers = iil_C_FetchHeader($this->conn, $mailbox, $id, $is_uid, $bodystr, $this->fetch_add_headers);
1178 // write headers cache
1181 if ($headers->uid && $headers->id)
1182 $this->uid_id_map[$mailbox][$headers->uid] = $headers->id;
1184 $this->add_message_cache($mailbox.'.msg', $headers->id, $headers, NULL, true);
1192 * Fetch body structure from the IMAP server and build
1193 * an object structure similar to the one generated by PEAR::Mail_mimeDecode
1195 * @param int Message UID to fetch
1196 * @param string Message BODYSTRUCTURE string (optional)
1197 * @return object rcube_message_part Message part tree or False on failure
1199 function &get_structure($uid, $structure_str='')
1201 $cache_key = $this->mailbox.'.msg';
1202 $headers = &$this->get_cached_message($cache_key, $uid);
1204 // return cached message structure
1205 if (is_object($headers) && is_object($headers->structure)) {
1206 return $headers->structure;
1209 if (!$structure_str)
1210 $structure_str = iil_C_FetchStructureString($this->conn, $this->mailbox, $uid, true);
1211 $structure = iml_GetRawStructureArray($structure_str);
1214 // parse structure and add headers
1215 if (!empty($structure))
1217 $headers = $this->get_headers($uid);
1218 $this->_msg_id = $headers->id;
1220 // set message charset from message headers
1221 if ($headers->charset)
1222 $this->struct_charset = $headers->charset;
1224 $this->struct_charset = $this->_structure_charset($structure);
1226 // Here we can recognize malformed BODYSTRUCTURE and
1227 // 1. [@TODO] parse the message in other way to create our own message structure
1228 // 2. or just show the raw message body.
1229 // Example of structure for malformed MIME message:
1230 // ("text" "plain" ("charset" "us-ascii") NIL NIL "7bit" 2154 70 NIL NIL NIL)
1231 if ($headers->ctype && $headers->ctype != 'text/plain'
1232 && $structure[0] == 'text' && $structure[1] == 'plain') {
1236 $struct = &$this->_structure_part($structure);
1237 $struct->headers = get_object_vars($headers);
1239 // don't trust given content-type
1240 if (empty($struct->parts) && !empty($struct->headers['ctype']))
1242 $struct->mime_id = '1';
1243 $struct->mimetype = strtolower($struct->headers['ctype']);
1244 list($struct->ctype_primary, $struct->ctype_secondary) = explode('/', $struct->mimetype);
1247 // write structure to cache
1248 if ($this->caching_enabled)
1249 $this->add_message_cache($cache_key, $this->_msg_id, $headers, $struct);
1257 * Build message part object
1261 function &_structure_part($part, $count=0, $parent='', $raw_headers=null)
1263 $struct = new rcube_message_part;
1264 $struct->mime_id = empty($parent) ? (string)$count : "$parent.$count";
1267 if (is_array($part[0]))
1269 $struct->ctype_primary = 'multipart';
1271 // find first non-array entry
1272 for ($i=1; $i<count($part); $i++)
1273 if (!is_array($part[$i]))
1275 $struct->ctype_secondary = strtolower($part[$i]);
1279 $struct->mimetype = 'multipart/'.$struct->ctype_secondary;
1281 // build parts list for headers pre-fetching
1282 for ($i=0, $count=0; $i<count($part); $i++)
1283 if (is_array($part[$i]) && count($part[$i]) > 3)
1284 // fetch message headers if message/rfc822 or named part (could contain Content-Location header)
1285 if (strtolower($part[$i][0]) == 'message' ||
1286 (in_array('name', (array)$part[$i][2]) && (empty($part[$i][3]) || $part[$i][3]=='NIL'))) {
1287 $part_headers[] = $struct->mime_id ? $struct->mime_id.'.'.($i+1) : $i+1;
1290 // pre-fetch headers of all parts (in one command for better performance)
1292 $part_headers = iil_C_FetchMIMEHeaders($this->conn, $this->mailbox, $this->_msg_id, $part_headers);
1294 $struct->parts = array();
1295 for ($i=0, $count=0; $i<count($part); $i++)
1296 if (is_array($part[$i]) && count($part[$i]) > 3) {
1297 $struct->parts[] = $this->_structure_part($part[$i], ++$count, $struct->mime_id,
1298 $part_headers[$struct->mime_id ? $struct->mime_id.'.'.($i+1) : $i+1]);
1306 $struct->ctype_primary = strtolower($part[0]);
1307 $struct->ctype_secondary = strtolower($part[1]);
1308 $struct->mimetype = $struct->ctype_primary.'/'.$struct->ctype_secondary;
1310 // read content type parameters
1311 if (is_array($part[2]))
1313 $struct->ctype_parameters = array();
1314 for ($i=0; $i<count($part[2]); $i+=2)
1315 $struct->ctype_parameters[strtolower($part[2][$i])] = $part[2][$i+1];
1317 if (isset($struct->ctype_parameters['charset']))
1318 $struct->charset = $struct->ctype_parameters['charset'];
1321 // read content encoding
1322 if (!empty($part[5]) && $part[5]!='NIL')
1324 $struct->encoding = strtolower($part[5]);
1325 $struct->headers['content-transfer-encoding'] = $struct->encoding;
1329 if (!empty($part[6]) && $part[6]!='NIL')
1330 $struct->size = intval($part[6]);
1332 // read part disposition
1333 $di = count($part) - 2;
1334 if ((is_array($part[$di]) && count($part[$di]) == 2 && is_array($part[$di][1])) ||
1335 (is_array($part[--$di]) && count($part[$di]) == 2))
1337 $struct->disposition = strtolower($part[$di][0]);
1339 if (is_array($part[$di][1]))
1340 for ($n=0; $n<count($part[$di][1]); $n+=2)
1341 $struct->d_parameters[strtolower($part[$di][1][$n])] = $part[$di][1][$n+1];
1345 if (is_array($part[8]) && $di != 8)
1347 $struct->parts = array();
1348 for ($i=0, $count=0; $i<count($part[8]); $i++)
1349 if (is_array($part[8][$i]) && count($part[8][$i]) > 5)
1350 $struct->parts[] = $this->_structure_part($part[8][$i], ++$count, $struct->mime_id);
1354 if (!empty($part[3]) && $part[3]!='NIL')
1356 $struct->content_id = $part[3];
1357 $struct->headers['content-id'] = $part[3];
1359 if (empty($struct->disposition))
1360 $struct->disposition = 'inline';
1363 // fetch message headers if message/rfc822 or named part (could contain Content-Location header)
1364 if ($struct->ctype_primary == 'message' || ($struct->ctype_parameters['name'] && !$struct->content_id)) {
1365 if (empty($raw_headers))
1366 $raw_headers = iil_C_FetchPartHeader($this->conn, $this->mailbox, $this->_msg_id, false, $struct->mime_id);
1367 $struct->headers = $this->_parse_headers($raw_headers) + $struct->headers;
1370 if ($struct->ctype_primary=='message') {
1371 if (is_array($part[8]) && empty($struct->parts))
1372 $struct->parts[] = $this->_structure_part($part[8], ++$count, $struct->mime_id);
1375 // normalize filename property
1376 $this->_set_part_filename($struct, $raw_headers);
1383 * Set attachment filename from message part structure
1386 * @param object rcube_message_part Part object
1387 * @param string Part's raw headers
1389 private function _set_part_filename(&$part, $headers=null)
1391 if (!empty($part->d_parameters['filename']))
1392 $filename_mime = $part->d_parameters['filename'];
1393 else if (!empty($part->d_parameters['filename*']))
1394 $filename_encoded = $part->d_parameters['filename*'];
1395 else if (!empty($part->ctype_parameters['name*']))
1396 $filename_encoded = $part->ctype_parameters['name*'];
1397 // RFC2231 value continuations
1398 // TODO: this should be rewrited to support RFC2231 4.1 combinations
1399 else if (!empty($part->d_parameters['filename*0'])) {
1401 while (isset($part->d_parameters['filename*'.$i])) {
1402 $filename_mime .= $part->d_parameters['filename*'.$i];
1405 // some servers (eg. dovecot-1.x) have no support for parameter value continuations
1406 // we must fetch and parse headers "manually"
1409 $headers = iil_C_FetchPartHeader($this->conn, $this->mailbox, $this->_msg_id, false, $part->mime_id);
1410 $filename_mime = '';
1412 while (preg_match('/filename\*'.$i.'\s*=\s*"*([^"\n;]+)[";]*/', $headers, $matches)) {
1413 $filename_mime .= $matches[1];
1418 else if (!empty($part->d_parameters['filename*0*'])) {
1420 while (isset($part->d_parameters['filename*'.$i.'*'])) {
1421 $filename_encoded .= $part->d_parameters['filename*'.$i.'*'];
1426 $headers = iil_C_FetchPartHeader($this->conn, $this->mailbox, $this->_msg_id, false, $part->mime_id);
1427 $filename_encoded = '';
1428 $i = 0; $matches = array();
1429 while (preg_match('/filename\*'.$i.'\*\s*=\s*"*([^"\n;]+)[";]*/', $headers, $matches)) {
1430 $filename_encoded .= $matches[1];
1435 else if (!empty($part->ctype_parameters['name*0'])) {
1437 while (isset($part->ctype_parameters['name*'.$i])) {
1438 $filename_mime .= $part->ctype_parameters['name*'.$i];
1443 $headers = iil_C_FetchPartHeader($this->conn, $this->mailbox, $this->_msg_id, false, $part->mime_id);
1444 $filename_mime = '';
1445 $i = 0; $matches = array();
1446 while (preg_match('/\s+name\*'.$i.'\s*=\s*"*([^"\n;]+)[";]*/', $headers, $matches)) {
1447 $filename_mime .= $matches[1];
1452 else if (!empty($part->ctype_parameters['name*0*'])) {
1454 while (isset($part->ctype_parameters['name*'.$i.'*'])) {
1455 $filename_encoded .= $part->ctype_parameters['name*'.$i.'*'];
1460 $headers = iil_C_FetchPartHeader($this->conn, $this->mailbox, $this->_msg_id, false, $part->mime_id);
1461 $filename_encoded = '';
1462 $i = 0; $matches = array();
1463 while (preg_match('/\s+name\*'.$i.'\*\s*=\s*"*([^"\n;]+)[";]*/', $headers, $matches)) {
1464 $filename_encoded .= $matches[1];
1469 // read 'name' after rfc2231 parameters as it may contains truncated filename (from Thunderbird)
1470 else if (!empty($part->ctype_parameters['name']))
1471 $filename_mime = $part->ctype_parameters['name'];
1472 // Content-Disposition
1473 else if (!empty($part->headers['content-description']))
1474 $filename_mime = $part->headers['content-description'];
1479 if (!empty($filename_mime)) {
1480 $part->filename = rcube_imap::decode_mime_string($filename_mime,
1481 $part->charset ? $part->charset : $this->struct_charset ? $this->struct_charset :
1482 rc_detect_encoding($filename_mime, $this->default_charset));
1484 else if (!empty($filename_encoded)) {
1485 // decode filename according to RFC 2231, Section 4
1486 if (preg_match("/^([^']*)'[^']*'(.*)$/", $filename_encoded, $fmatches)) {
1487 $filename_charset = $fmatches[1];
1488 $filename_encoded = $fmatches[2];
1490 $part->filename = rcube_charset_convert(urldecode($filename_encoded), $filename_charset);
1496 * Get charset name from message structure (first part)
1499 * @param array Message structure
1500 * @return string Charset name
1502 function _structure_charset($structure)
1504 while (is_array($structure)) {
1505 if (is_array($structure[2]) && $structure[2][0] == 'charset')
1506 return $structure[2][1];
1507 $structure = $structure[0];
1513 * Fetch message body of a specific message from the server
1515 * @param int Message UID
1516 * @param string Part number
1517 * @param object rcube_message_part Part object created by get_structure()
1518 * @param mixed True to print part, ressource to write part contents in
1519 * @param resource File pointer to save the message part
1520 * @return string Message/part body if not printed
1522 function &get_message_part($uid, $part=1, $o_part=NULL, $print=NULL, $fp=NULL)
1524 // get part encoding if not provided
1525 if (!is_object($o_part))
1527 $structure_str = iil_C_FetchStructureString($this->conn, $this->mailbox, $uid, true);
1528 $structure = iml_GetRawStructureArray($structure_str);
1529 // error or message not found
1530 if (empty($structure))
1533 $part_type = iml_GetPartTypeCode($structure, $part);
1534 $o_part = new rcube_message_part;
1535 $o_part->ctype_primary = $part_type==0 ? 'text' : ($part_type==2 ? 'message' : 'other');
1536 $o_part->encoding = strtolower(iml_GetPartEncodingString($structure, $part));
1537 $o_part->charset = iml_GetPartCharset($structure, $part);
1540 // TODO: Add caching for message parts
1542 if (!$part) $part = 'TEXT';
1544 $body = iil_C_HandlePartBody($this->conn, $this->mailbox, $uid, true, $part,
1545 $o_part->encoding, $print, $fp);
1550 // convert charset (if text or message part)
1551 if ($o_part->ctype_primary=='text' || $o_part->ctype_primary=='message') {
1552 // assume default if no charset specified
1553 if (empty($o_part->charset) || strtolower($o_part->charset) == 'us-ascii')
1554 $o_part->charset = $this->default_charset;
1556 $body = rcube_charset_convert($body, $o_part->charset);
1564 * Fetch message body of a specific message from the server
1566 * @param int Message UID
1567 * @return string Message/part body
1568 * @see rcube_imap::get_message_part()
1570 function &get_body($uid, $part=1)
1572 $headers = $this->get_headers($uid);
1573 return rcube_charset_convert($this->get_message_part($uid, $part, NULL),
1574 $headers->charset ? $headers->charset : $this->default_charset);
1579 * Returns the whole message source as string
1581 * @param int Message UID
1582 * @return string Message source string
1584 function &get_raw_body($uid)
1586 return iil_C_HandlePartBody($this->conn, $this->mailbox, $uid, true);
1591 * Returns the message headers as string
1593 * @param int Message UID
1594 * @return string Message headers string
1596 function &get_raw_headers($uid)
1598 return iil_C_FetchPartHeader($this->conn, $this->mailbox, $uid, true);
1603 * Sends the whole message source to stdout
1605 * @param int Message UID
1607 function print_raw_body($uid)
1609 iil_C_HandlePartBody($this->conn, $this->mailbox, $uid, true, NULL, NULL, true);
1614 * Set message flag to one or several messages
1616 * @param mixed Message UIDs as array or as comma-separated string
1617 * @param string Flag to set: SEEN, UNDELETED, DELETED, RECENT, ANSWERED, DRAFT, MDNSENT
1618 * @param string Folder name
1619 * @param boolean True to skip message cache clean up
1620 * @return boolean True on success, False on failure
1622 function set_flag($uids, $flag, $mbox_name=NULL, $skip_cache=false)
1624 $mailbox = $mbox_name ? $this->mod_mailbox($mbox_name) : $this->mailbox;
1626 $flag = strtoupper($flag);
1627 if (!is_array($uids))
1628 $uids = explode(',',$uids);
1630 if (strpos($flag, 'UN') === 0)
1631 $result = iil_C_UnFlag($this->conn, $mailbox, join(',', $uids), substr($flag, 2));
1633 $result = iil_C_Flag($this->conn, $mailbox, join(',', $uids), $flag);
1635 // reload message headers if cached
1636 if ($this->caching_enabled && !$skip_cache) {
1637 $cache_key = $mailbox.'.msg';
1638 $this->remove_message_cache($cache_key, $uids);
1641 // set nr of messages that were flaged
1642 $count = count($uids);
1644 // clear message count cache
1645 if ($result && $flag=='SEEN')
1646 $this->_set_messagecount($mailbox, 'UNSEEN', $count*(-1));
1647 else if ($result && $flag=='UNSEEN')
1648 $this->_set_messagecount($mailbox, 'UNSEEN', $count);
1649 else if ($result && $flag=='DELETED')
1650 $this->_set_messagecount($mailbox, 'ALL', $count*(-1));
1657 * Remove message flag for one or several messages
1659 * @param mixed Message UIDs as array or as comma-separated string
1660 * @param string Flag to unset: SEEN, DELETED, RECENT, ANSWERED, DRAFT, MDNSENT
1661 * @param string Folder name
1662 * @return boolean True on success, False on failure
1665 function unset_flag($uids, $flag, $mbox_name=NULL)
1667 return $this->set_flag($uids, 'UN'.$flag, $mbox_name);
1672 * Append a mail message (source) to a specific mailbox
1674 * @param string Target mailbox
1675 * @param string Message source
1676 * @return boolean True on success, False on error
1678 function save_message($mbox_name, &$message)
1680 $mailbox = $this->mod_mailbox($mbox_name);
1682 // make sure mailbox exists
1683 if (($mailbox == 'INBOX') || in_array($mailbox, $this->_list_mailboxes()))
1684 $saved = iil_C_Append($this->conn, $mailbox, $message);
1688 // increase messagecount of the target mailbox
1689 $this->_set_messagecount($mailbox, 'ALL', 1);
1697 * Move a message from one mailbox to another
1699 * @param string List of UIDs to move, separated by comma
1700 * @param string Target mailbox
1701 * @param string Source mailbox
1702 * @return boolean True on success, False on error
1704 function move_message($uids, $to_mbox, $from_mbox='')
1708 $to_mbox = $this->mod_mailbox($to_mbox);
1709 $from_mbox = $from_mbox ? $this->mod_mailbox($from_mbox) : $this->mailbox;
1711 // make sure mailbox exists
1712 if ($to_mbox != 'INBOX' && !in_array($to_mbox, $this->_list_mailboxes()))
1714 if (in_array($to_mbox_in, $this->default_folders))
1715 $this->create_mailbox($to_mbox_in, TRUE);
1720 // convert the list of uids to array
1721 $a_uids = is_string($uids) ? explode(',', $uids) : (is_array($uids) ? $uids : NULL);
1723 // exit if no message uids are specified
1724 if (!is_array($a_uids) || empty($a_uids))
1727 // flag messages as read before moving them
1728 $config = rcmail::get_instance()->config;
1729 if ($config->get('read_when_deleted') && $tbox == $config->get('trash_mbox')) {
1730 // don't flush cache (4th argument)
1731 $this->set_flag($uids, 'SEEN', $fbox, true);
1735 $iil_move = iil_C_Move($this->conn, join(',', $a_uids), $from_mbox, $to_mbox);
1736 $moved = !($iil_move === false || $iil_move < 0);
1738 // send expunge command in order to have the moved message
1739 // really deleted from the source mailbox
1741 $this->_expunge($from_mbox, FALSE, $a_uids);
1742 $this->_clear_messagecount($from_mbox);
1743 $this->_clear_messagecount($to_mbox);
1746 else if (rcmail::get_instance()->config->get('delete_always', false)) {
1747 return iil_C_Delete($this->conn, $from_mbox, join(',', $a_uids));
1750 // remove message ids from search set
1751 if ($moved && $this->search_set && $from_mbox == $this->mailbox) {
1752 foreach ($a_uids as $uid)
1753 $a_mids[] = $this->_uid2id($uid, $from_mbox);
1754 $this->search_set = array_diff($this->search_set, $a_mids);
1757 // update cached message headers
1758 $cache_key = $from_mbox.'.msg';
1759 if ($moved && $start_index = $this->get_message_cache_index_min($cache_key, $a_uids)) {
1760 // clear cache from the lowest index on
1761 $this->clear_message_cache($cache_key, $start_index);
1769 * Mark messages as deleted and expunge mailbox
1771 * @param string List of UIDs to move, separated by comma
1772 * @param string Source mailbox
1773 * @return boolean True on success, False on error
1775 function delete_message($uids, $mbox_name='')
1777 $mailbox = $mbox_name ? $this->mod_mailbox($mbox_name) : $this->mailbox;
1779 // convert the list of uids to array
1780 $a_uids = is_string($uids) ? explode(',', $uids) : (is_array($uids) ? $uids : NULL);
1782 // exit if no message uids are specified
1783 if (!is_array($a_uids) || empty($a_uids))
1786 $deleted = iil_C_Delete($this->conn, $mailbox, join(',', $a_uids));
1788 // send expunge command in order to have the deleted message
1789 // really deleted from the mailbox
1792 $this->_expunge($mailbox, FALSE, $a_uids);
1793 $this->_clear_messagecount($mailbox);
1794 unset($this->uid_id_map[$mailbox]);
1797 // remove message ids from search set
1798 if ($deleted && $this->search_set && $mailbox == $this->mailbox) {
1799 foreach ($a_uids as $uid)
1800 $a_mids[] = $this->_uid2id($uid, $mailbox);
1801 $this->search_set = array_diff($this->search_set, $a_mids);
1804 // remove deleted messages from cache
1805 $cache_key = $mailbox.'.msg';
1806 if ($deleted && $start_index = $this->get_message_cache_index_min($cache_key, $a_uids)) {
1807 // clear cache from the lowest index on
1808 $this->clear_message_cache($cache_key, $start_index);
1816 * Clear all messages in a specific mailbox
1818 * @param string Mailbox name
1819 * @return int Above 0 on success
1821 function clear_mailbox($mbox_name=NULL)
1823 $mailbox = !empty($mbox_name) ? $this->mod_mailbox($mbox_name) : $this->mailbox;
1824 $msg_count = $this->_messagecount($mailbox, 'ALL');
1828 $cleared = iil_C_ClearFolder($this->conn, $mailbox);
1830 // make sure the message count cache is cleared as well
1833 $this->clear_message_cache($mailbox.'.msg');
1834 $a_mailbox_cache = $this->get_cache('messagecount');
1835 unset($a_mailbox_cache[$mailbox]);
1836 $this->update_cache('messagecount', $a_mailbox_cache);
1847 * Send IMAP expunge command and clear cache
1849 * @param string Mailbox name
1850 * @param boolean False if cache should not be cleared
1851 * @return boolean True on success
1853 function expunge($mbox_name='', $clear_cache=TRUE)
1855 $mailbox = $mbox_name ? $this->mod_mailbox($mbox_name) : $this->mailbox;
1856 return $this->_expunge($mailbox, $clear_cache);
1861 * Send IMAP expunge command and clear cache
1863 * @see rcube_imap::expunge()
1864 * @param string Mailbox name
1865 * @param boolean False if cache should not be cleared
1866 * @param string List of UIDs to remove, separated by comma
1867 * @return boolean True on success
1870 private function _expunge($mailbox, $clear_cache=TRUE, $uids=NULL)
1872 if ($uids && $this->get_capability('UIDPLUS'))
1873 $a_uids = is_array($uids) ? join(',', $uids) : $uids;
1877 $result = iil_C_Expunge($this->conn, $mailbox, $a_uids);
1879 if ($result>=0 && $clear_cache)
1881 $this->clear_message_cache($mailbox.'.msg');
1882 $this->_clear_messagecount($mailbox);
1889 /* --------------------------------
1891 * --------------------------------*/
1895 * Get a list of all folders available on the IMAP server
1897 * @param string IMAP root dir
1898 * @return array Indexed array with folder names
1900 function list_unsubscribed($root='')
1902 static $sa_unsubscribed;
1904 if (is_array($sa_unsubscribed))
1905 return $sa_unsubscribed;
1907 // retrieve list of folders from IMAP server
1908 $a_mboxes = iil_C_ListMailboxes($this->conn, $this->mod_mailbox($root), '*');
1910 // modify names with root dir
1911 foreach ($a_mboxes as $mbox_name)
1913 $name = $this->mod_mailbox($mbox_name, 'out');
1915 $a_folders[] = $name;
1918 // filter folders and sort them
1919 $sa_unsubscribed = $this->_sort_mailbox_list($a_folders);
1920 return $sa_unsubscribed;
1925 * Get mailbox quota information
1928 * @return mixed Quota info or False if not supported
1930 function get_quota()
1932 if ($this->get_capability('QUOTA'))
1933 return iil_C_GetQuota($this->conn);
1940 * Subscribe to a specific mailbox(es)
1942 * @param array Mailbox name(s)
1943 * @return boolean True on success
1945 function subscribe($a_mboxes)
1947 if (!is_array($a_mboxes))
1948 $a_mboxes = array($a_mboxes);
1950 // let this common function do the main work
1951 return $this->_change_subscription($a_mboxes, 'subscribe');
1956 * Unsubscribe mailboxes
1958 * @param array Mailbox name(s)
1959 * @return boolean True on success
1961 function unsubscribe($a_mboxes)
1963 if (!is_array($a_mboxes))
1964 $a_mboxes = array($a_mboxes);
1966 // let this common function do the main work
1967 return $this->_change_subscription($a_mboxes, 'unsubscribe');
1972 * Create a new mailbox on the server and register it in local cache
1974 * @param string New mailbox name (as utf-7 string)
1975 * @param boolean True if the new mailbox should be subscribed
1976 * @param string Name of the created mailbox, false on error
1978 function create_mailbox($name, $subscribe=FALSE)
1982 // reduce mailbox name to 100 chars
1983 $name = substr($name, 0, 100);
1985 $abs_name = $this->mod_mailbox($name);
1986 $a_mailbox_cache = $this->get_cache('mailboxes');
1988 if (strlen($abs_name) && (!is_array($a_mailbox_cache) || !in_array($abs_name, $a_mailbox_cache)))
1989 $result = iil_C_CreateFolder($this->conn, $abs_name);
1991 // try to subscribe it
1992 if ($result && $subscribe)
1993 $this->subscribe($name);
1995 return $result ? $name : FALSE;
2000 * Set a new name to an existing mailbox
2002 * @param string Mailbox to rename (as utf-7 string)
2003 * @param string New mailbox name (as utf-7 string)
2004 * @return string Name of the renames mailbox, False on error
2006 function rename_mailbox($mbox_name, $new_name)
2010 // encode mailbox name and reduce it to 100 chars
2011 $name = substr($new_name, 0, 100);
2013 // make absolute path
2014 $mailbox = $this->mod_mailbox($mbox_name);
2015 $abs_name = $this->mod_mailbox($name);
2017 // check if mailbox is subscribed
2018 $a_subscribed = $this->_list_mailboxes();
2019 $subscribed = in_array($mailbox, $a_subscribed);
2021 // unsubscribe folder
2023 iil_C_UnSubscribe($this->conn, $mailbox);
2025 if (strlen($abs_name))
2026 $result = iil_C_RenameFolder($this->conn, $mailbox, $abs_name);
2030 $delm = $this->get_hierarchy_delimiter();
2032 // check if mailbox children are subscribed
2033 foreach ($a_subscribed as $c_subscribed)
2034 if (preg_match('/^'.preg_quote($mailbox.$delm, '/').'/', $c_subscribed))
2036 iil_C_UnSubscribe($this->conn, $c_subscribed);
2037 iil_C_Subscribe($this->conn, preg_replace('/^'.preg_quote($mailbox, '/').'/', $abs_name, $c_subscribed));
2041 $this->clear_message_cache($mailbox.'.msg');
2042 $this->clear_cache('mailboxes');
2045 // try to subscribe it
2046 if ($result && $subscribed)
2047 iil_C_Subscribe($this->conn, $abs_name);
2049 return $result ? $name : FALSE;
2054 * Remove mailboxes from server
2056 * @param string Mailbox name(s) string/array
2057 * @return boolean True on success
2059 function delete_mailbox($mbox_name)
2063 if (is_array($mbox_name))
2064 $a_mboxes = $mbox_name;
2065 else if (is_string($mbox_name) && strlen($mbox_name))
2066 $a_mboxes = explode(',', $mbox_name);
2068 $all_mboxes = iil_C_ListMailboxes($this->conn, $this->mod_mailbox($root), '*');
2070 if (is_array($a_mboxes))
2071 foreach ($a_mboxes as $mbox_name)
2073 $mailbox = $this->mod_mailbox($mbox_name);
2075 // unsubscribe mailbox before deleting
2076 iil_C_UnSubscribe($this->conn, $mailbox);
2078 // send delete command to server
2079 $result = iil_C_DeleteFolder($this->conn, $mailbox);
2082 $this->clear_message_cache($mailbox.'.msg');
2085 foreach ($all_mboxes as $c_mbox)
2087 $regex = preg_quote($mailbox . $this->delimiter, '/');
2088 $regex = '/^' . $regex . '/';
2089 if (preg_match($regex, $c_mbox))
2091 iil_C_UnSubscribe($this->conn, $c_mbox);
2092 $result = iil_C_DeleteFolder($this->conn, $c_mbox);
2095 $this->clear_message_cache($c_mbox.'.msg');
2101 // clear mailboxlist cache
2103 $this->clear_cache('mailboxes');
2110 * Create all folders specified as default
2112 function create_default_folders()
2114 $a_folders = iil_C_ListMailboxes($this->conn, $this->mod_mailbox(''), '*');
2115 $a_subscribed = iil_C_ListSubscribed($this->conn, $this->mod_mailbox(''), '*');
2117 // create default folders if they do not exist
2118 foreach ($this->default_folders as $folder)
2120 $abs_name = $this->mod_mailbox($folder);
2121 if (!in_array_nocase($abs_name, $a_folders))
2122 $this->create_mailbox($folder, TRUE);
2123 else if (!in_array_nocase($abs_name, $a_subscribed))
2124 $this->subscribe($folder);
2130 /* --------------------------------
2131 * internal caching methods
2132 * --------------------------------*/
2137 function set_caching($set)
2139 if ($set && is_object($this->db))
2140 $this->caching_enabled = TRUE;
2142 $this->caching_enabled = FALSE;
2148 function get_cache($key)
2150 // read cache (if it was not read before)
2151 if (!count($this->cache) && $this->caching_enabled)
2153 return $this->_read_cache_record($key);
2156 return $this->cache[$key];
2162 function update_cache($key, $data)
2164 $this->cache[$key] = $data;
2165 $this->cache_changed = TRUE;
2166 $this->cache_changes[$key] = TRUE;
2172 function write_cache()
2174 if ($this->caching_enabled && $this->cache_changed)
2176 foreach ($this->cache as $key => $data)
2178 if ($this->cache_changes[$key])
2179 $this->_write_cache_record($key, serialize($data));
2187 function clear_cache($key=NULL)
2189 if (!$this->caching_enabled)
2194 foreach ($this->cache as $key => $data)
2195 $this->_clear_cache_record($key);
2197 $this->cache = array();
2198 $this->cache_changed = FALSE;
2199 $this->cache_changes = array();
2203 $this->_clear_cache_record($key);
2204 $this->cache_changes[$key] = FALSE;
2205 unset($this->cache[$key]);
2212 private function _read_cache_record($key)
2216 // get cached data from DB
2217 $sql_result = $this->db->query(
2218 "SELECT cache_id, data, cache_key
2219 FROM ".get_table_name('cache')."
2221 AND cache_key LIKE 'IMAP.%'",
2222 $_SESSION['user_id']);
2224 while ($sql_arr = $this->db->fetch_assoc($sql_result))
2226 $sql_key = preg_replace('/^IMAP\./', '', $sql_arr['cache_key']);
2227 $this->cache_keys[$sql_key] = $sql_arr['cache_id'];
2228 if (!isset($this->cache[$sql_key]))
2229 $this->cache[$sql_key] = $sql_arr['data'] ? unserialize($sql_arr['data']) : FALSE;
2233 return $this->cache[$key];
2239 private function _write_cache_record($key, $data)
2244 // update existing cache record
2245 if ($this->cache_keys[$key])
2248 "UPDATE ".get_table_name('cache')."
2249 SET created=". $this->db->now().", data=?
2253 $_SESSION['user_id'],
2256 // add new cache record
2260 "INSERT INTO ".get_table_name('cache')."
2261 (created, user_id, cache_key, data)
2262 VALUES (".$this->db->now().", ?, ?, ?)",
2263 $_SESSION['user_id'],
2267 // get cache entry ID for this key
2268 $sql_result = $this->db->query(
2270 FROM ".get_table_name('cache')."
2273 $_SESSION['user_id'],
2276 if ($sql_arr = $this->db->fetch_assoc($sql_result))
2277 $this->cache_keys[$key] = $sql_arr['cache_id'];
2284 private function _clear_cache_record($key)
2287 "DELETE FROM ".get_table_name('cache')."
2290 $_SESSION['user_id'],
2293 unset($this->cache_keys[$key]);
2298 /* --------------------------------
2299 * message caching methods
2300 * --------------------------------*/
2304 * Checks if the cache is up-to-date
2306 * @param string Mailbox name
2307 * @param string Internal cache key
2308 * @return int Cache status: -3 = off, -2 = incomplete, -1 = dirty
2310 private function check_cache_status($mailbox, $cache_key)
2312 if (!$this->caching_enabled)
2315 $cache_index = $this->get_message_cache_index($cache_key);
2316 $msg_count = $this->_messagecount($mailbox);
2317 $cache_count = count($cache_index);
2321 return $cache_count ? -2 : 1;
2323 // @TODO: We've got one big performance problem in cache status checking method
2324 // E.g. mailbox contains 1000 messages, in cache table we've got first 100
2325 // of them. Now if we want to display only that 100 (which we've got)
2326 // check_cache_status returns 'incomplete' and messages are fetched
2327 // from IMAP instead of DB.
2329 if ($cache_count==$msg_count) {
2330 if ($this->skip_deleted) {
2331 $h_index = iil_C_FetchHeaderIndex($this->conn, $mailbox, "1:*", 'UID', $this->skip_deleted);
2333 if (sizeof($h_index) == $cache_count) {
2334 $cache_index = array_flip($cache_index);
2335 foreach ($h_index as $idx => $uid)
2336 unset($cache_index[$uid]);
2338 if (empty($cache_index))
2343 // get UID of message with highest index
2344 $uid = iil_C_ID2UID($this->conn, $mailbox, $msg_count);
2345 $cache_uid = array_pop($cache_index);
2347 // uids of highest message matches -> cache seems OK
2348 if ($cache_uid == $uid)
2354 // if cache count differs less than 10% report as dirty
2355 else if (abs($msg_count - $cache_count) < $msg_count/10)
2364 private function get_message_cache($key, $from, $to, $sort_field, $sort_order)
2366 $cache_key = "$key:$from:$to:$sort_field:$sort_order";
2367 $db_header_fields = array('idx', 'uid', 'subject', 'from', 'to', 'cc', 'date', 'size');
2369 $config = rcmail::get_instance()->config;
2371 // use idx sort for sorting by Date with index_sort=true or for unknown field
2372 if (($sort_field == 'date' && $this->index_sort)
2373 || !in_array($sort_field, $db_header_fields)) {
2374 $sort_field = 'idx';
2377 if ($this->caching_enabled && !isset($this->cache[$cache_key]))
2379 $this->cache[$cache_key] = array();
2380 $sql_result = $this->db->limitquery(
2381 "SELECT idx, uid, headers
2382 FROM ".get_table_name('messages')."
2385 ORDER BY ".$this->db->quoteIdentifier($sort_field)." ".strtoupper($sort_order),
2388 $_SESSION['user_id'],
2391 while ($sql_arr = $this->db->fetch_assoc($sql_result))
2393 $uid = $sql_arr['uid'];
2394 $this->cache[$cache_key][$uid] = $this->db->decode(unserialize($sql_arr['headers']));
2396 // featch headers if unserialize failed
2397 if (empty($this->cache[$cache_key][$uid]))
2398 $this->cache[$cache_key][$uid] = iil_C_FetchHeader($this->conn, preg_replace('/.msg$/', '', $key), $uid, true, $this->fetch_add_headers);
2402 return $this->cache[$cache_key];
2408 private function &get_cached_message($key, $uid)
2410 $internal_key = '__single_msg';
2412 if ($this->caching_enabled && !isset($this->cache[$internal_key][$uid]))
2414 $sql_result = $this->db->query(
2415 "SELECT idx, headers, structure
2416 FROM ".get_table_name('messages')."
2420 $_SESSION['user_id'],
2424 if ($sql_arr = $this->db->fetch_assoc($sql_result))
2426 $this->uid_id_map[preg_replace('/\.msg$/', '', $key)][$uid] = $sql_arr['idx'];
2427 $this->cache[$internal_key][$uid] = $this->db->decode(unserialize($sql_arr['headers']));
2428 if (is_object($this->cache[$internal_key][$uid]) && !empty($sql_arr['structure']))
2429 $this->cache[$internal_key][$uid]->structure = $this->db->decode(unserialize($sql_arr['structure']));
2433 return $this->cache[$internal_key][$uid];
2439 private function get_message_cache_index($key, $force=FALSE, $sort_field='idx', $sort_order='ASC')
2441 static $sa_message_index = array();
2443 // empty key -> empty array
2444 if (!$this->caching_enabled || empty($key))
2447 if (!empty($sa_message_index[$key]) && !$force)
2448 return $sa_message_index[$key];
2450 // use idx sort for sorting by Date with index_sort=true
2451 if ($sort_field == 'date' && $this->index_sort)
2452 $sort_field = 'idx';
2454 $sa_message_index[$key] = array();
2455 $sql_result = $this->db->query(
2457 FROM ".get_table_name('messages')."
2460 ORDER BY ".$this->db->quote_identifier($sort_field)." ".$sort_order,
2461 $_SESSION['user_id'],
2464 while ($sql_arr = $this->db->fetch_assoc($sql_result))
2465 $sa_message_index[$key][$sql_arr['idx']] = $sql_arr['uid'];
2467 return $sa_message_index[$key];
2473 private function add_message_cache($key, $index, $headers, $struct=null, $force=false)
2475 if (empty($key) || !is_object($headers) || empty($headers->uid))
2478 // add to internal (fast) cache
2479 $this->cache['__single_msg'][$headers->uid] = clone $headers;
2480 $this->cache['__single_msg'][$headers->uid]->structure = $struct;
2482 // no further caching
2483 if (!$this->caching_enabled)
2486 // check for an existing record (probly headers are cached but structure not)
2488 $sql_result = $this->db->query(
2490 FROM ".get_table_name('messages')."
2494 $_SESSION['user_id'],
2497 if ($sql_arr = $this->db->fetch_assoc($sql_result))
2498 $message_id = $sql_arr['message_id'];
2501 // update cache record
2505 "UPDATE ".get_table_name('messages')."
2506 SET idx=?, headers=?, structure=?
2507 WHERE message_id=?",
2509 serialize($this->db->encode(clone $headers)),
2510 is_object($struct) ? serialize($this->db->encode(clone $struct)) : NULL,
2514 else // insert new record
2517 "INSERT INTO ".get_table_name('messages')."
2518 (user_id, del, cache_key, created, idx, uid, subject, ".$this->db->quoteIdentifier('from').", ".$this->db->quoteIdentifier('to').", cc, date, size, headers, structure)
2519 VALUES (?, 0, ?, ".$this->db->now().", ?, ?, ?, ?, ?, ?, ".$this->db->fromunixtime($headers->timestamp).", ?, ?, ?)",
2520 $_SESSION['user_id'],
2524 (string)mb_substr($this->db->encode($this->decode_header($headers->subject, TRUE)), 0, 128),
2525 (string)mb_substr($this->db->encode($this->decode_header($headers->from, TRUE)), 0, 128),
2526 (string)mb_substr($this->db->encode($this->decode_header($headers->to, TRUE)), 0, 128),
2527 (string)mb_substr($this->db->encode($this->decode_header($headers->cc, TRUE)), 0, 128),
2528 (int)$headers->size,
2529 serialize($this->db->encode(clone $headers)),
2530 is_object($struct) ? serialize($this->db->encode(clone $struct)) : NULL
2538 private function remove_message_cache($key, $ids, $idx=false)
2540 if (!$this->caching_enabled)
2544 "DELETE FROM ".get_table_name('messages')."
2547 AND ".($idx ? "idx" : "uid")." IN (".$this->db->array2list($ids, 'integer').")",
2548 $_SESSION['user_id'],
2555 private function clear_message_cache($key, $start_index=1)
2557 if (!$this->caching_enabled)
2561 "DELETE FROM ".get_table_name('messages')."
2565 $_SESSION['user_id'], $key, $start_index);
2571 private function get_message_cache_index_min($key, $uids=NULL)
2573 if (!$this->caching_enabled)
2576 $sql_result = $this->db->query(
2577 "SELECT MIN(idx) AS minidx
2578 FROM ".get_table_name('messages')."
2581 .(!empty($uids) ? " AND uid IN (".$this->db->array2list($uids, 'integer').")" : ''),
2582 $_SESSION['user_id'],
2585 if ($sql_arr = $this->db->fetch_assoc($sql_result))
2586 return $sql_arr['minidx'];
2592 /* --------------------------------
2593 * encoding/decoding methods
2594 * --------------------------------*/
2597 * Split an address list into a structured array list
2599 * @param string Input string
2600 * @param int List only this number of addresses
2601 * @param boolean Decode address strings
2602 * @return array Indexed list of addresses
2604 function decode_address_list($input, $max=null, $decode=true)
2606 $a = $this->_parse_address_list($input, $decode);
2608 // Special chars as defined by RFC 822 need to in quoted string (or escaped).
2609 $special_chars = '[\(\)\<\>\\\.\[\]@,;:"]';
2617 foreach ($a as $val)
2620 $address = $val['address'];
2621 $name = preg_replace(array('/^[\'"]/', '/[\'"]$/'), '', trim($val['name']));
2622 if ($name && $address && $name != $address)
2623 $string = sprintf('%s <%s>', preg_match("/$special_chars/", $name) ? '"'.addcslashes($name, '"').'"' : $name, $address);
2629 $out[$j] = array('name' => $name,
2630 'mailto' => $address,
2631 'string' => $string);
2633 if ($max && $j==$max)
2642 * Decode a Microsoft Outlook TNEF part (winmail.dat)
2644 * @param object rcube_message_part Message part to decode
2645 * @param string UID of the message
2646 * @return array List of rcube_message_parts extracted from windmail.dat
2648 function tnef_decode(&$part, $uid)
2650 if (!isset($part->body))
2651 $part->body = $this->get_message_part($uid, $part->mime_id, $part);
2654 $tnef_parts = array();
2655 $tnef_arr = tnef_decode($part->body);
2656 foreach ($tnef_arr as $winatt) {
2657 $tpart = new rcube_message_part;
2658 $tpart->filename = $winatt["name"];
2659 $tpart->encoding = 'stream';
2660 $tpart->ctype_primary = $winatt["type0"];
2661 $tpart->ctype_secondary = $winatt["type1"];
2662 $tpart->mimetype = strtolower($winatt["type0"] . "/" . $winatt["type1"]);
2663 $tpart->mime_id = "winmail." . $part->mime_id . ".$pid";
2664 $tpart->size = $winatt["size"];
2665 $tpart->body = $winatt['stream'];
2667 $tnef_parts[] = $tpart;
2676 * Decode a message header value
2678 * @param string Header value
2679 * @param boolean Remove quotes if necessary
2680 * @return string Decoded string
2682 function decode_header($input, $remove_quotes=FALSE)
2684 $str = rcube_imap::decode_mime_string((string)$input, $this->default_charset);
2685 if ($str{0}=='"' && $remove_quotes)
2686 $str = str_replace('"', '', $str);
2693 * Decode a mime-encoded string to internal charset
2695 * @param string $input Header value
2696 * @param string $fallback Fallback charset if none specified
2698 * @return string Decoded string
2701 public static function decode_mime_string($input, $fallback=null)
2703 // Initialize variable
2706 // Iterate instead of recursing, this way if there are too many values we don't have stack overflows
2707 // rfc: all line breaks or other characters not found
2708 // in the Base64 Alphabet must be ignored by decoding software
2709 // delete all blanks between MIME-lines, differently we can
2710 // receive unnecessary blanks and broken utf-8 symbols
2711 $input = preg_replace("/\?=\s+=\?/", '?==?', $input);
2713 // Check if there is stuff to decode
2714 if (strpos($input, '=?') !== false) {
2715 // Loop through the string to decode all occurences of =? ?= into the variable $out
2716 while(($pos = strpos($input, '=?')) !== false) {
2717 // Append everything that is before the text to be decoded
2718 $out .= substr($input, 0, $pos);
2720 // Get the location of the text to decode
2721 $end_cs_pos = strpos($input, "?", $pos+2);
2722 $end_en_pos = strpos($input, "?", $end_cs_pos+1);
2723 $end_pos = strpos($input, "?=", $end_en_pos+1);
2725 // Extract the encoded string
2726 $encstr = substr($input, $pos+2, ($end_pos-$pos-2));
2727 // Extract the remaining string
2728 $input = substr($input, $end_pos+2);
2730 // Decode the string fragement
2731 $out .= rcube_imap::_decode_mime_string_part($encstr);
2734 // Deocde the rest (if any)
2735 if (strlen($input) != 0)
2736 $out .= rcube_imap::decode_mime_string($input, $fallback);
2738 // return the results
2742 // no encoding information, use fallback
2743 return rcube_charset_convert($input,
2744 !empty($fallback) ? $fallback : rcmail::get_instance()->config->get('default_charset', 'ISO-8859-1'));
2749 * Decode a part of a mime-encoded string
2753 private function _decode_mime_string_part($str)
2755 $a = explode('?', $str);
2758 // should be in format "charset?encoding?base64_string"
2761 for ($i=2; $i<$count; $i++)
2764 if (($a[1]=="B")||($a[1]=="b"))
2765 $rest = base64_decode($rest);
2766 else if (($a[1]=="Q")||($a[1]=="q"))
2768 $rest = str_replace("_", " ", $rest);
2769 $rest = quoted_printable_decode($rest);
2772 return rcube_charset_convert($rest, $a[0]);
2775 return $str; // we dont' know what to do with this
2780 * Decode a mime part
2782 * @param string Input string
2783 * @param string Part encoding
2784 * @return string Decoded string
2786 function mime_decode($input, $encoding='7bit')
2788 switch (strtolower($encoding))
2790 case 'quoted-printable':
2791 return quoted_printable_decode($input);
2795 return base64_decode($input);
2802 return convert_uudecode($input);
2813 * Convert body charset to RCMAIL_CHARSET according to the ctype_parameters
2815 * @param string Part body to decode
2816 * @param string Charset to convert from
2817 * @return string Content converted to internal charset
2819 function charset_decode($body, $ctype_param)
2821 if (is_array($ctype_param) && !empty($ctype_param['charset']))
2822 return rcube_charset_convert($body, $ctype_param['charset']);
2824 // defaults to what is specified in the class header
2825 return rcube_charset_convert($body, $this->default_charset);
2830 * Translate UID to message ID
2832 * @param int Message UID
2833 * @param string Mailbox name
2834 * @return int Message ID
2836 function get_id($uid, $mbox_name=NULL)
2838 $mailbox = $mbox_name ? $this->mod_mailbox($mbox_name) : $this->mailbox;
2839 return $this->_uid2id($uid, $mailbox);
2844 * Translate message number to UID
2846 * @param int Message ID
2847 * @param string Mailbox name
2848 * @return int Message UID
2850 function get_uid($id,$mbox_name=NULL)
2852 $mailbox = $mbox_name ? $this->mod_mailbox($mbox_name) : $this->mailbox;
2853 return $this->_id2uid($id, $mailbox);
2858 * Modify folder name for input/output according to root dir and namespace
2860 * @param string Folder name
2861 * @param string Mode
2862 * @return string Folder name
2864 function mod_mailbox($mbox_name, $mode='in')
2866 if ((!empty($this->root_ns) && $this->root_ns == $mbox_name) || $mbox_name == 'INBOX')
2869 if (!empty($this->root_dir) && $mode=='in')
2870 $mbox_name = $this->root_dir.$this->delimiter.$mbox_name;
2871 else if (strlen($this->root_dir) && $mode=='out')
2872 $mbox_name = substr($mbox_name, strlen($this->root_dir)+1);
2878 /* --------------------------------
2880 * --------------------------------*/
2883 * Validate the given input and save to local properties
2886 private function _set_sort_order($sort_field, $sort_order)
2888 if ($sort_field != null)
2889 $this->sort_field = asciiwords($sort_field);
2890 if ($sort_order != null)
2891 $this->sort_order = strtoupper($sort_order) == 'DESC' ? 'DESC' : 'ASC';
2895 * Sort mailboxes first by default folders and then in alphabethical order
2898 private function _sort_mailbox_list($a_folders)
2900 $a_out = $a_defaults = $folders = array();
2902 $delimiter = $this->get_hierarchy_delimiter();
2904 // find default folders and skip folders starting with '.'
2905 foreach ($a_folders as $i => $folder)
2907 if ($folder{0}=='.')
2910 if (($p = array_search(strtolower($folder), $this->default_folders_lc)) !== false && !$a_defaults[$p])
2911 $a_defaults[$p] = $folder;
2913 $folders[$folder] = mb_strtolower(rcube_charset_convert($folder, 'UTF7-IMAP'));
2916 // sort folders and place defaults on the top
2917 asort($folders, SORT_LOCALE_STRING);
2919 $folders = array_merge($a_defaults, array_keys($folders));
2921 // finally we must rebuild the list to move
2922 // subfolders of default folders to their place...
2923 // ...also do this for the rest of folders because
2924 // asort() is not properly sorting case sensitive names
2925 while (list($key, $folder) = each($folders)) {
2926 // set the type of folder name variable (#1485527)
2927 $a_out[] = (string) $folder;
2928 unset($folders[$key]);
2929 $this->_rsort($folder, $delimiter, $folders, $a_out);
2939 private function _rsort($folder, $delimiter, &$list, &$out)
2941 while (list($key, $name) = each($list)) {
2942 if (strpos($name, $folder.$delimiter) === 0) {
2943 // set the type of folder name variable (#1485527)
2944 $out[] = (string) $name;
2946 $this->_rsort($name, $delimiter, $list, $out);
2956 private function _uid2id($uid, $mbox_name=NULL)
2959 $mbox_name = $this->mailbox;
2961 if (!isset($this->uid_id_map[$mbox_name][$uid]))
2962 $this->uid_id_map[$mbox_name][$uid] = iil_C_UID2ID($this->conn, $mbox_name, $uid);
2964 return $this->uid_id_map[$mbox_name][$uid];
2970 private function _id2uid($id, $mbox_name=NULL)
2973 $mbox_name = $this->mailbox;
2975 $index = array_flip((array)$this->uid_id_map[$mbox_name]);
2976 if (isset($index[$id]))
2980 $uid = iil_C_ID2UID($this->conn, $mbox_name, $id);
2981 $this->uid_id_map[$mbox_name][$uid] = $id;
2989 * Subscribe/unsubscribe a list of mailboxes and update local cache
2992 private function _change_subscription($a_mboxes, $mode)
2996 if (is_array($a_mboxes))
2997 foreach ($a_mboxes as $i => $mbox_name)
2999 $mailbox = $this->mod_mailbox($mbox_name);
3000 $a_mboxes[$i] = $mailbox;
3002 if ($mode=='subscribe')
3003 $updated = iil_C_Subscribe($this->conn, $mailbox);
3004 else if ($mode=='unsubscribe')
3005 $updated = iil_C_UnSubscribe($this->conn, $mailbox);
3008 // get cached mailbox list
3011 $a_mailbox_cache = $this->get_cache('mailboxes');
3012 if (!is_array($a_mailbox_cache))
3015 // modify cached list
3016 if ($mode=='subscribe')
3017 $a_mailbox_cache = array_merge($a_mailbox_cache, $a_mboxes);
3018 else if ($mode=='unsubscribe')
3019 $a_mailbox_cache = array_diff($a_mailbox_cache, $a_mboxes);
3021 // write mailboxlist to cache
3022 $this->update_cache('mailboxes', $this->_sort_mailbox_list($a_mailbox_cache));
3030 * Increde/decrese messagecount for a specific mailbox
3033 private function _set_messagecount($mbox_name, $mode, $increment)
3035 $a_mailbox_cache = FALSE;
3036 $mailbox = $mbox_name ? $mbox_name : $this->mailbox;
3037 $mode = strtoupper($mode);
3039 $a_mailbox_cache = $this->get_cache('messagecount');
3041 if (!is_array($a_mailbox_cache[$mailbox]) || !isset($a_mailbox_cache[$mailbox][$mode]) || !is_numeric($increment))
3044 // add incremental value to messagecount
3045 $a_mailbox_cache[$mailbox][$mode] += $increment;
3047 // there's something wrong, delete from cache
3048 if ($a_mailbox_cache[$mailbox][$mode] < 0)
3049 unset($a_mailbox_cache[$mailbox][$mode]);
3051 // write back to cache
3052 $this->update_cache('messagecount', $a_mailbox_cache);
3059 * Remove messagecount of a specific mailbox from cache
3062 private function _clear_messagecount($mbox_name='')
3064 $a_mailbox_cache = FALSE;
3065 $mailbox = $mbox_name ? $mbox_name : $this->mailbox;
3067 $a_mailbox_cache = $this->get_cache('messagecount');
3069 if (is_array($a_mailbox_cache[$mailbox]))
3071 unset($a_mailbox_cache[$mailbox]);
3072 $this->update_cache('messagecount', $a_mailbox_cache);
3078 * Split RFC822 header string into an associative array
3081 private function _parse_headers($headers)
3083 $a_headers = array();
3084 $lines = explode("\n", $headers);
3086 for ($i=0; $i<$c; $i++)
3088 if ($p = strpos($lines[$i], ': '))
3090 $field = strtolower(substr($lines[$i], 0, $p));
3091 $value = trim(substr($lines[$i], $p+1));
3093 $a_headers[$field] = $value;
3104 private function _parse_address_list($str, $decode=true)
3106 // remove any newlines and carriage returns before
3107 $a = rcube_explode_quoted_string('[,;]', preg_replace( "/[\r\n]/", " ", $str));
3110 foreach ($a as $key => $val)
3112 $val = preg_replace("/([\"\w])</", "$1 <", $val);
3113 $sub_a = rcube_explode_quoted_string(' ', $decode ? $this->decode_header($val) : $val);
3114 $result[$key]['name'] = '';
3116 foreach ($sub_a as $k => $v)
3118 // use angle brackets in regexp to not handle names with @ sign
3119 if (preg_match('/^<\S+@\S+>$/', $v))
3120 $result[$key]['address'] = trim($v, '<>');
3122 $result[$key]['name'] .= (empty($result[$key]['name'])?'':' ').str_replace("\"",'',stripslashes($v));
3125 if (empty($result[$key]['name']))
3126 $result[$key]['name'] = $result[$key]['address'];
3127 elseif (empty($result[$key]['address']))
3128 $result[$key]['address'] = $result[$key]['name'];
3134 } // end class rcube_imap
3138 * Class representing a message part
3142 class rcube_message_part
3145 var $ctype_primary = 'text';
3146 var $ctype_secondary = 'plain';
3147 var $mimetype = 'text/plain';
3148 var $disposition = '';
3150 var $encoding = '8bit';
3153 var $headers = array();
3154 var $d_parameters = array();
3155 var $ctype_parameters = array();
3159 if (isset($this->parts))
3160 foreach ($this->parts as $idx => $part)
3161 if (is_object($part))
3162 $this->parts[$idx] = clone $part;
3168 * Class for sorting an array of iilBasicHeader objects in a predetermined order.
3171 * @author Eric Stadtherr
3173 class rcube_header_sorter
3175 var $sequence_numbers = array();
3178 * Set the predetermined sort order.
3180 * @param array Numerically indexed array of IMAP message sequence numbers
3182 function set_sequence_numbers($seqnums)
3184 $this->sequence_numbers = array_flip($seqnums);
3188 * Sort the array of header objects
3190 * @param array Array of iilBasicHeader objects indexed by UID
3192 function sort_headers(&$headers)
3195 * uksort would work if the keys were the sequence number, but unfortunately
3196 * the keys are the UIDs. We'll use uasort instead and dereference the value
3197 * to get the sequence number (in the "id" field).
3199 * uksort($headers, array($this, "compare_seqnums"));
3201 uasort($headers, array($this, "compare_seqnums"));
3205 * Sort method called by uasort()
3207 function compare_seqnums($a, $b)
3209 // First get the sequence number from the header object (the 'id' field).
3213 // then find each sequence number in my ordered list
3214 $posa = isset($this->sequence_numbers[$seqa]) ? intval($this->sequence_numbers[$seqa]) : -1;
3215 $posb = isset($this->sequence_numbers[$seqb]) ? intval($this->sequence_numbers[$seqb]) : -1;
3217 // return the relative position as the comparison value
3218 return $posa - $posb;