From e70d6ea64e711096af36b1234f8545b870ea5f45 Mon Sep 17 00:00:00 2001 From: thomascube <thomas@roundcube.net> Date: Sat, 05 Apr 2008 08:49:21 -0400 Subject: [PATCH] Apply changes from trunk to 0.1-stable --- program/include/rcube_imap.inc | 1222 +++++++++++++++++++++++++++++++++++++++++++++------------ 1 files changed, 963 insertions(+), 259 deletions(-) diff --git a/program/include/rcube_imap.inc b/program/include/rcube_imap.inc index 7f74eb7..9a59485 100644 --- a/program/include/rcube_imap.inc +++ b/program/include/rcube_imap.inc @@ -5,7 +5,7 @@ | program/include/rcube_imap.inc | | | | This file is part of the RoundCube Webmail client | - | Copyright (C) 2005, RoundCube Dev. - Switzerland | + | Copyright (C) 2005-2007, RoundCube Dev. - Switzerland | | Licensed under the GNU GPL | | | | PURPOSE: | @@ -21,12 +21,11 @@ */ -/** +/* * Obtain classes from the Iloha IMAP library */ require_once('lib/imap.inc'); require_once('lib/mime.inc'); -require_once('lib/utf7.inc'); /** @@ -34,13 +33,13 @@ * * This is a wrapper that implements the Iloha IMAP Library (IIL) * - * @package RoundCube Webmail + * @package Mail * @author Thomas Bruederli <roundcube@gmail.com> - * @version 1.31 + * @version 1.40 * @link http://ilohamail.org */ class rcube_imap - { +{ var $db; var $conn; var $root_ns = ''; @@ -52,6 +51,7 @@ var $sort_order = 'DESC'; var $delimiter = NULL; var $caching_enabled = FALSE; + var $default_charset = 'ISO-8859-1'; var $default_folders = array('INBOX'); var $default_folders_lc = array('inbox'); var $cache = array(); @@ -61,13 +61,18 @@ var $msg_headers = array(); var $capabilities = array(); var $skip_deleted = FALSE; + var $search_set = NULL; + var $search_subject = ''; + var $search_string = ''; + var $search_charset = ''; var $debug_level = 1; + var $error_code = 0; /** * Object constructor * - * @param object Database connection + * @param object DB Database connection */ function __construct($db_conn) { @@ -93,17 +98,17 @@ * @param string Username for IMAP account * @param string Password for IMAP account * @param number Port to connect to - * @param boolean Use SSL connection + * @param string SSL schema (either ssl or tls) or null if plain connection * @return boolean TRUE on success, FALSE on failure * @access public */ - function connect($host, $user, $pass, $port=143, $use_ssl=FALSE) + function connect($host, $user, $pass, $port=143, $use_ssl=null) { global $ICL_SSL, $ICL_PORT, $IMAP_USE_INTERNAL_DATE; // check for Open-SSL support in PHP build if ($use_ssl && in_array('openssl', get_loaded_extensions())) - $ICL_SSL = TRUE; + $ICL_SSL = $use_ssl == 'imaps' ? 'ssl' : $use_ssl; else if ($use_ssl) { raise_error(array('code' => 403, 'type' => 'imap', 'file' => __FILE__, @@ -128,16 +133,16 @@ // write error log else if (!$this->conn && $GLOBALS['iil_error']) { + $this->error_code = $GLOBALS['iil_errornum']; raise_error(array('code' => 403, 'type' => 'imap', 'message' => $GLOBALS['iil_error']), TRUE, FALSE); } - // get account namespace + // get server properties if ($this->conn) { $this->_parse_capability($this->conn->capability); - iil_C_NameSpace($this->conn); if (!empty($this->conn->delimiter)) $this->delimiter = $this->conn->delimiter; @@ -196,6 +201,20 @@ if (empty($this->delimiter)) $this->get_hierarchy_delimiter(); + } + + + /** + * Set default message charset + * + * This will be used for message decoding if a charset specification is not available + * + * @param string Charset string + * @access public + */ + function set_charset($cs) + { + $this->default_charset = $ch; } @@ -266,6 +285,37 @@ function set_pagesize($size) { $this->page_size = (int)$size; + } + + + /** + * Save a set of message ids for future message listing methods + * + * @param array List of IMAP fields to search in + * @param string Search string + * @param array List of message ids or NULL if empty + */ + function set_search_set($subject, $str=null, $msgs=null, $charset=null) + { + if (is_array($subject) && $str == null && $msgs == null) + list($subject, $str, $msgs, $charset) = $subject; + if ($msgs != null && !is_array($msgs)) + $msgs = split(',', $msgs); + + $this->search_subject = $subject; + $this->search_string = $str; + $this->search_set = (array)$msgs; + $this->search_charset = $charset; + } + + + /** + * Return the saved search set as hash array + * @return array Search set + */ + function get_search_set() + { + return array($this->search_subject, $this->search_string, $this->search_set, $this->search_charset); } @@ -350,8 +400,8 @@ * Private method for mailbox listing * * @return array List of mailboxes/folders + * @see rcube_imap::list_mailboxes() * @access private - * @see rcube_imap::list_mailboxes */ function _list_mailboxes($root='', $filter='*') { @@ -381,8 +431,8 @@ * @param string Mailbox/folder name * @param string Mode for count [ALL|UNSEEN|RECENT] * @param boolean Force reading from server and update cache - * @return number Number of messages - * @access public + * @return int Number of messages + * @access public */ function messagecount($mbox_name='', $mode='ALL', $force=FALSE) { @@ -395,7 +445,7 @@ * Private method for getting nr of messages * * @access private - * @see rcube_imap::messagecount + * @see rcube_imap::messagecount() */ function _messagecount($mailbox='', $mode='ALL', $force=FALSE) { @@ -404,6 +454,10 @@ if (empty($mailbox)) $mailbox = $this->mailbox; + + // count search set + if ($this->search_string && $mailbox == $this->mailbox && $mode == 'ALL' && !$force) + return count((array)$this->search_set); $a_mailbox_cache = $this->get_cache('messagecount'); @@ -460,7 +514,7 @@ * convert mailbox name with root dir first * * @param string Mailbox/folder name - * @param number Current page to list + * @param int Current page to list * @param string Header field to sort by * @param string Sort order [ASC|DESC] * @return array Indexed array with message header objects @@ -483,21 +537,22 @@ { if (!strlen($mailbox)) return array(); - - if ($sort_field!=NULL) - $this->sort_field = $sort_field; - if ($sort_order!=NULL) - $this->sort_order = strtoupper($sort_order); + + // use saved message set + if ($this->search_string && $mailbox == $this->mailbox) + return $this->_list_header_set($mailbox, $this->search_set, $page, $sort_field, $sort_order); + + $this->_set_sort_order($sort_field, $sort_order); $max = $this->_messagecount($mailbox); $start_msg = ($this->list_page-1) * $this->page_size; list($begin, $end) = $this->_get_message_range($max, $page); - // mailbox is empty + // mailbox is empty if ($begin >= $end) return array(); - + $headers_sorted = FALSE; $cache_key = $mailbox.'.msg'; $cache_status = $this->check_cache_status($mailbox, $cache_key); @@ -540,8 +595,9 @@ $a_msg_headers = array(); $deleted_count = $this->_fetch_headers($mailbox, $msgs, $a_msg_headers, $cache_key); - // delete cached messages with a higher index than $max - $this->clear_message_cache($cache_key, $max); + // delete cached messages with a higher index than $max+1 + // Changed $max to $max+1 to fix this bug : #1484295 + $this->clear_message_cache($cache_key, $max + 1); // kick child process to sync cache @@ -575,7 +631,7 @@ * * @param string Mailbox/folder name * @param array List of message ids to list - * @param number Current page to list + * @param int Current page to list * @param string Header field to sort by * @param string Sort order [ASC|DESC] * @return array Indexed array with message header objects @@ -592,7 +648,7 @@ * Private method for listing a set of message headers * * @access private - * @see rcube_imap::list_header_set + * @see rcube_imap::list_header_set() */ function _list_header_set($mailbox, $msgs, $page=NULL, $sort_field=NULL, $sort_order=NULL) { @@ -603,10 +659,7 @@ if (!strlen($mailbox) || empty($msgs)) return array(); - if ($sort_field!=NULL) - $this->sort_field = $sort_field; - if ($sort_order!=NULL) - $this->sort_order = strtoupper($sort_order); + $this->_set_sort_order($sort_field, $sort_order); $max = count($msgs); $start_msg = ($this->list_page-1) * $this->page_size; @@ -616,21 +669,21 @@ $this->_fetch_headers($mailbox, join(',', $msgs), $a_msg_headers, NULL); // return empty array if no messages found - if (!is_array($a_msg_headers) || empty($a_msg_headers)) - return array(); + if (!is_array($a_msg_headers) || empty($a_msg_headers)) + return array(); // if not already sorted $a_msg_headers = iil_SortHeaders($a_msg_headers, $this->sort_field, $this->sort_order); - // only return the requested part of the set - return array_slice(array_values($a_msg_headers), $start_msg, min($max-$start_msg, $this->page_size)); + // only return the requested part of the set + return array_slice(array_values($a_msg_headers), $start_msg, min($max-$start_msg, $this->page_size)); } /** * Helper function to get first and last index of the requested set * - * @param number message count + * @param int message count * @param mixed page number to show, or string 'all' * @return array array with two values: first index, last index * @access private @@ -672,7 +725,7 @@ * @param string Message index to fetch * @param array Reference to message headers array * @param array Array with cache index - * @return number Number of deleted messages + * @return int Number of deleted messages * @access private */ function _fetch_headers($mailbox, $msgs, &$a_msg_headers, $cache_key) @@ -710,16 +763,30 @@ } - // return sorted array of message UIDs + /** + * Return sorted array of message UIDs + * + * @param string Mailbox to get index from + * @param string Sort column + * @param string Sort order [ASC, DESC] + * @return array Indexed array with message ids + */ function message_index($mbox_name='', $sort_field=NULL, $sort_order=NULL) { - if ($sort_field!=NULL) - $this->sort_field = $sort_field; - if ($sort_order!=NULL) - $this->sort_order = strtoupper($sort_order); + $this->_set_sort_order($sort_field, $sort_order); $mailbox = $mbox_name ? $this->_mod_mailbox($mbox_name) : $this->mailbox; - $key = "$mbox:".$this->sort_field.":".$this->sort_order.".msgi"; + $key = "{$mailbox}:{$this->sort_field}:{$this->sort_order}:{$this->search_string}.msgi"; + + // we have a saved search result. get index from there + if (!isset($this->cache[$key]) && $this->search_string && $mailbox == $this->mailbox) + { + $this->cache[$key] = $a_msg_headers = array(); + $this->_fetch_headers($mailbox, join(',', $this->search_set), $a_msg_headers, NULL); + + foreach (iil_SortHeaders($a_msg_headers, $this->sort_field, $this->sort_order) as $i => $msg) + $this->cache[$key][] = $msg->uid; + } // have stored it in RAM if (isset($this->cache[$key])) @@ -767,6 +834,9 @@ } + /** + * @access private + */ function sync_header_index($mailbox) { $cache_key = $mailbox.'.msg'; @@ -781,7 +851,6 @@ // message in cache at correct position if ($cache_index[$id] == $uid) { -// console("$id / $uid: OK"); unset($cache_index[$id]); continue; } @@ -789,20 +858,16 @@ // message in cache but in wrong position if (in_array((string)$uid, $cache_index, TRUE)) { -// console("$id / $uid: Moved"); unset($cache_index[$id]); } // other message at this position if (isset($cache_index[$id])) { -// console("$id / $uid: Delete"); $this->remove_message_cache($cache_key, $id); unset($cache_index[$id]); } - -// console("$id / $uid: Add"); // fetch complete headers and add to cache $headers = iil_C_FetchHeader($this->conn, $mailbox, $id); @@ -830,15 +895,29 @@ function search($mbox_name='', $criteria='ALL', $str=NULL, $charset=NULL) { $mailbox = $mbox_name ? $this->_mod_mailbox($mbox_name) : $this->mailbox; - if ($str && $criteria) + + // have an array of criterias => execute multiple searches + if (is_array($criteria) && $str) + { + $results = array(); + foreach ($criteria as $crit) + if ($search_result = $this->search($mbox_name, $crit, $str, $charset)) + $results = array_merge($results, $search_result); + + $results = array_unique($results); + $this->set_search_set($criteria, $str, $results, $charset); + return $results; + } + else if ($str && $criteria) { $search = (!empty($charset) ? "CHARSET $charset " : '') . sprintf("%s {%d}\r\n%s", $criteria, strlen($str), $str); $results = $this->_search_index($mailbox, $search); - // try search without charset (probably not supported by server) - if (empty($results)) - $results = $this->_search_index($mailbox, "$criteria $str"); + // try search with ISO charset (should be supported by server) + if (empty($results) && !empty($charset) && $charset!='ISO-8859-1') + $results = $this->search($mbox_name, $criteria, rcube_charset_convert($str, $charset, 'ISO-8859-1'), 'ISO-8859-1'); + $this->set_search_set($criteria, $str, $results, $charset); return $results; } else @@ -866,59 +945,383 @@ return $a_messages; } + + + /** + * Refresh saved search set + * + * @return array Current search set + */ + function refresh_search() + { + if (!empty($this->search_subject) && !empty($this->search_string)) + $this->search_set = $this->search('', $this->search_subject, $this->search_string, $this->search_charset); + + return $this->get_search_set(); + } + + + /** + * Check if the given message ID is part of the current search set + * + * @return boolean True on match or if no search request is stored + */ + function in_searchset($msgid) + { + if (!empty($this->search_string)) + return in_array("$msgid", (array)$this->search_set, true); + else + return true; + } + /** + * Return message headers object of a specific message + * + * @param int Message ID + * @param string Mailbox to read from + * @param boolean True if $id is the message UID + * @return object Message headers representation + */ function get_headers($id, $mbox_name=NULL, $is_uid=TRUE) { $mailbox = $mbox_name ? $this->_mod_mailbox($mbox_name) : $this->mailbox; + $uid = $is_uid ? $id : $this->_id2uid($id); // get cached headers - if ($is_uid && ($headers = $this->get_cached_message($mailbox.'.msg', $id))) + if ($uid && ($headers = &$this->get_cached_message($mailbox.'.msg', $uid))) return $headers; - $msg_id = $is_uid ? $this->_uid2id($id) : $id; - $headers = iil_C_FetchHeader($this->conn, $mailbox, $msg_id); + $headers = iil_C_FetchHeader($this->conn, $mailbox, $id, $is_uid); // write headers cache if ($headers) - $this->add_message_cache($mailbox.'.msg', $msg_id, $headers); + { + if ($headers->uid && $headers->id) + $this->uid_id_map[$mailbox][$headers->uid] = $headers->id; + + $this->add_message_cache($mailbox.'.msg', $headers->id, $headers); + } return $headers; } - function get_body($uid, $part=1) + /** + * Fetch body structure from the IMAP server and build + * an object structure similar to the one generated by PEAR::Mail_mimeDecode + * + * @param int Message UID to fetch + * @return object stdClass Message part tree or False on failure + */ + function &get_structure($uid) { + $cache_key = $this->mailbox.'.msg'; + $headers = &$this->get_cached_message($cache_key, $uid, true); + + // return cached message structure + if (is_object($headers) && is_object($headers->structure)) + return $headers->structure; + + // resolve message sequence number if (!($msg_id = $this->_uid2id($uid))) return FALSE; - $structure_str = iil_C_FetchStructureString($this->conn, $this->mailbox, $msg_id); - $structure = iml_GetRawStructureArray($structure_str); - $body = iil_C_FetchPartBody($this->conn, $this->mailbox, $msg_id, $part); + $structure_str = iil_C_FetchStructureString($this->conn, $this->mailbox, $msg_id); + $structure = iml_GetRawStructureArray($structure_str); + $struct = false; - $encoding = iml_GetPartEncodingCode($structure, $part); + // parse structure and add headers + if (!empty($structure)) + { + $this->_msg_id = $msg_id; + $headers = $this->get_headers($uid); + + $struct = &$this->_structure_part($structure); + $struct->headers = get_object_vars($headers); + + // don't trust given content-type + if (empty($struct->parts) && !empty($struct->headers['ctype'])) + { + $struct->mime_id = '1'; + $struct->mimetype = strtolower($struct->headers['ctype']); + list($struct->ctype_primary, $struct->ctype_secondary) = explode('/', $struct->mimetype); + } + + // write structure to cache + if ($this->caching_enabled) + $this->add_message_cache($cache_key, $msg_id, $headers, $struct); + } + + return $struct; + } + + + /** + * Build message part object + * + * @access private + */ + function &_structure_part($part, $count=0, $parent='') + { + $struct = new rcube_message_part; + $struct->mime_id = empty($parent) ? (string)$count : "$parent.$count"; - if ($encoding==3) $body = $this->mime_decode($body, 'base64'); - else if ($encoding==4) $body = $this->mime_decode($body, 'quoted-printable'); + // multipart + if (is_array($part[0])) + { + $struct->ctype_primary = 'multipart'; + + // find first non-array entry + for ($i=1; count($part); $i++) + if (!is_array($part[$i])) + { + $struct->ctype_secondary = strtolower($part[$i]); + break; + } + + $struct->mimetype = 'multipart/'.$struct->ctype_secondary; + + $struct->parts = array(); + for ($i=0, $count=0; $i<count($part); $i++) + if (is_array($part[$i]) && count($part[$i]) > 5) + $struct->parts[] = $this->_structure_part($part[$i], ++$count, $struct->mime_id); + + return $struct; + } + + + // regular part + $struct->ctype_primary = strtolower($part[0]); + $struct->ctype_secondary = strtolower($part[1]); + $struct->mimetype = $struct->ctype_primary.'/'.$struct->ctype_secondary; + + // read content type parameters + if (is_array($part[2])) + { + $struct->ctype_parameters = array(); + for ($i=0; $i<count($part[2]); $i+=2) + $struct->ctype_parameters[strtolower($part[2][$i])] = $part[2][$i+1]; + + if (isset($struct->ctype_parameters['charset'])) + $struct->charset = $struct->ctype_parameters['charset']; + } + + // read content encoding + if (!empty($part[5]) && $part[5]!='NIL') + { + $struct->encoding = strtolower($part[5]); + $struct->headers['content-transfer-encoding'] = $struct->encoding; + } + + // get part size + if (!empty($part[6]) && $part[6]!='NIL') + $struct->size = intval($part[6]); + + // read part disposition + $di = count($part) - 2; + if ((is_array($part[$di]) && count($part[$di]) == 2 && is_array($part[$di][1])) || + (is_array($part[--$di]) && count($part[$di]) == 2)) + { + $struct->disposition = strtolower($part[$di][0]); + + if (is_array($part[$di][1])) + for ($n=0; $n<count($part[$di][1]); $n+=2) + $struct->d_parameters[strtolower($part[$di][1][$n])] = $part[$di][1][$n+1]; + } + + // get child parts + if (is_array($part[8]) && $di != 8) + { + $struct->parts = array(); + for ($i=0, $count=0; $i<count($part[8]); $i++) + if (is_array($part[8][$i]) && count($part[8][$i]) > 5) + $struct->parts[] = $this->_structure_part($part[8][$i], ++$count, $struct->mime_id); + } + + // get part ID + if (!empty($part[3]) && $part[3]!='NIL') + { + $struct->content_id = $part[3]; + $struct->headers['content-id'] = $part[3]; + + if (empty($struct->disposition)) + $struct->disposition = 'inline'; + } + + // fetch message headers if message/rfc822 + if ($struct->ctype_primary=='message') + { + $headers = iil_C_FetchPartBody($this->conn, $this->mailbox, $this->_msg_id, $struct->mime_id.'.HEADER'); + $struct->headers = $this->_parse_headers($headers); + + if (is_array($part[8]) && empty($struct->parts)) + $struct->parts[] = $this->_structure_part($part[8], ++$count, $struct->mime_id); + } + + // normalize filename property + if ($filename_mime = $struct->d_parameters['filename'] ? $struct->d_parameters['filename'] : $struct->ctype_parameters['name']) + $struct->filename = rcube_imap::decode_mime_string($filename_mime, $this->default_charset); + else if ($filename_encoded = $struct->d_parameters['filename*'] ? $struct->d_parameters['filename*'] : $struct->ctype_parameters['name*']) + { + // decode filename according to RFC 2231, Section 4 + list($filename_charset,, $filename_urlencoded) = split('\'', $filename_encoded); + $struct->filename = rcube_charset_convert(urldecode($filename_urlencoded), $filename_charset); + } + else if (!empty($struct->headers['content-description'])) + $struct->filename = rcube_imap::decode_mime_string($struct->headers['content-description'], $this->default_charset); + + return $struct; + } + + + /** + * Return a flat array with references to all parts, indexed by part numbers + * + * @param object rcube_message_part Message body structure + * @return Array with part number -> object pairs + */ + function get_mime_numbers(&$structure) + { + $a_parts = array(); + $this->_get_part_numbers($structure, $a_parts); + return $a_parts; + } + + + /** + * Helper method for recursive calls + * + * @access private + */ + function _get_part_numbers(&$part, &$a_parts) + { + if ($part->mime_id) + $a_parts[$part->mime_id] = &$part; + + if (is_array($part->parts)) + for ($i=0; $i<count($part->parts); $i++) + $this->_get_part_numbers($part->parts[$i], $a_parts); + } + + + /** + * Fetch message body of a specific message from the server + * + * @param int Message UID + * @param string Part number + * @param object rcube_message_part Part object created by get_structure() + * @param mixed True to print part, ressource to write part contents in + * @return string Message/part body if not printed + */ + function &get_message_part($uid, $part=1, $o_part=NULL, $print=NULL) + { + if (!($msg_id = $this->_uid2id($uid))) + return FALSE; + + // get part encoding if not provided + if (!is_object($o_part)) + { + $structure_str = iil_C_FetchStructureString($this->conn, $this->mailbox, $msg_id); + $structure = iml_GetRawStructureArray($structure_str); + $part_type = iml_GetPartTypeCode($structure, $part); + $o_part = new rcube_message_part; + $o_part->ctype_primary = $part_type==0 ? 'text' : ($part_type==2 ? 'message' : 'other'); + $o_part->encoding = strtolower(iml_GetPartEncodingString($structure, $part)); + $o_part->charset = iml_GetPartCharset($structure, $part); + } + + // TODO: Add caching for message parts + + if ($print) + { + $mode = $o_part->encoding == 'base64' ? 3 : ($o_part->encoding == 'quoted-printable' ? 1 : 2); + $body = iil_C_HandlePartBody($this->conn, $this->mailbox, $msg_id, $part, $mode); + + // we have to decode the part manually before printing + if ($mode == 1) + { + echo $this->mime_decode($body, $o_part->encoding); + $body = true; + } + } + else + { + $body = iil_C_HandlePartBody($this->conn, $this->mailbox, $msg_id, $part, 1); + + // decode part body + if ($o_part->encoding) + $body = $this->mime_decode($body, $o_part->encoding); + + // convert charset (if text or message part) + if ($o_part->ctype_primary=='text' || $o_part->ctype_primary=='message') + { + // assume default if no charset specified + if (empty($o_part->charset)) + $o_part->charset = $this->default_charset; + + $body = rcube_charset_convert($body, $o_part->charset); + } + } return $body; } - function get_raw_body($uid) + /** + * Fetch message body of a specific message from the server + * + * @param int Message UID + * @return string Message/part body + * @see rcube_imap::get_message_part() + */ + function &get_body($uid, $part=1) + { + return $this->get_message_part($uid, $part); + } + + + /** + * Returns the whole message source as string + * + * @param int Message UID + * @return string Message source string + */ + function &get_raw_body($uid) { if (!($msg_id = $this->_uid2id($uid))) return FALSE; - $body = iil_C_FetchPartHeader($this->conn, $this->mailbox, $msg_id, NULL); - $body .= iil_C_HandlePartBody($this->conn, $this->mailbox, $msg_id, NULL, 1); + $body = iil_C_FetchPartHeader($this->conn, $this->mailbox, $msg_id, NULL); + $body .= iil_C_HandlePartBody($this->conn, $this->mailbox, $msg_id, NULL, 1); return $body; } + + + /** + * Sends the whole message source to stdout + * + * @param int Message UID + */ + function print_raw_body($uid) + { + if (!($msg_id = $this->_uid2id($uid))) + return FALSE; + + print iil_C_FetchPartHeader($this->conn, $this->mailbox, $msg_id, NULL); + flush(); + iil_C_HandlePartBody($this->conn, $this->mailbox, $msg_id, NULL, 2); + } - // set message flag to one or several messages - // possible flags are: SEEN, UNDELETED, DELETED, RECENT, ANSWERED, DRAFT + /** + * Set message flag to one or several messages + * + * @param mixed Message UIDs as array or as comma-separated string + * @param string Flag to set: SEEN, UNDELETED, DELETED, RECENT, ANSWERED, DRAFT, MDNSENT + * @return boolean True on success, False on failure + */ function set_flag($uids, $flag) { $flag = strtoupper($flag); @@ -970,7 +1373,13 @@ } - // append a mail message (source) to a specific mailbox + /** + * Append a mail message (source) to a specific mailbox + * + * @param string Target mailbox + * @param string Message source + * @return boolean True on success, False on error + */ function save_message($mbox_name, &$message) { $mbox_name = stripslashes($mbox_name); @@ -990,7 +1399,14 @@ } - // move a message from one mailbox to another + /** + * Move a message from one mailbox to another + * + * @param string List of UIDs to move, separated by comma + * @param string Target mailbox + * @param string Source mailbox + * @return boolean True on success, False on error + */ function move_message($uids, $to_mbox, $from_mbox='') { $to_mbox = stripslashes($to_mbox); @@ -1001,7 +1417,7 @@ // make sure mailbox exists if (!in_array($to_mbox, $this->_list_mailboxes())) { - if (in_array(strtolower($to_mbox), $this->default_folders)) + if (in_array($to_mbox, $this->default_folders)) $this->create_mailbox($to_mbox, TRUE); else return FALSE; @@ -1019,7 +1435,8 @@ foreach ($a_uids as $uid) $a_mids[] = $this->_uid2id($uid, $from_mbox); - $moved = iil_C_Move($this->conn, join(',', $a_mids), $from_mbox, $to_mbox); + $iil_move = iil_C_Move($this->conn, join(',', $a_mids), $from_mbox, $to_mbox); + $moved = !($iil_move === false || $iil_move < 0); // send expunge command in order to have the moved message // really deleted from the source mailbox @@ -1029,6 +1446,10 @@ $this->_clear_messagecount($from_mbox); $this->_clear_messagecount($to_mbox); } + + // remove message ids from search set + if ($moved && $this->search_set && $from_mbox == $this->mailbox) + $this->search_set = array_diff($this->search_set, $a_mids); // update cached message headers $cache_key = $from_mbox.'.msg'; @@ -1037,8 +1458,8 @@ $start_index = 100000; foreach ($a_uids as $uid) { - if(($index = array_search($uid, $a_cache_index)) !== FALSE) - $start_index = min($index, $start_index); + if (($index = array_search($uid, $a_cache_index)) !== FALSE) + $start_index = min($index, $start_index); } // clear cache from the lowest index on @@ -1049,7 +1470,13 @@ } - // mark messages as deleted and expunge mailbox + /** + * Mark messages as deleted and expunge mailbox + * + * @param string List of UIDs to move, separated by comma + * @param string Source mailbox + * @return boolean True on success, False on error + */ function delete_message($uids, $mbox_name='') { $mbox_name = stripslashes($mbox_name); @@ -1078,6 +1505,10 @@ $this->_clear_messagecount($mailbox); } + // remove message ids from search set + if ($moved && $this->search_set && $mailbox == $this->mailbox) + $this->search_set = array_diff($this->search_set, $a_mids); + // remove deleted messages from cache $cache_key = $mailbox.'.msg'; if ($deleted && ($a_cache_index = $this->get_message_cache_index($cache_key))) @@ -1085,8 +1516,8 @@ $start_index = 100000; foreach ($a_uids as $uid) { - $index = array_search($uid, $a_cache_index); - $start_index = min($index, $start_index); + if (($index = array_search($uid, $a_cache_index)) !== FALSE) + $start_index = min($index, $start_index); } // clear cache from the lowest index on @@ -1097,7 +1528,12 @@ } - // clear all messages in a specific mailbox + /** + * Clear all messages in a specific mailbox + * + * @param string Mailbox name + * @return int Above 0 on success + */ function clear_mailbox($mbox_name=NULL) { $mbox_name = stripslashes($mbox_name); @@ -1124,7 +1560,13 @@ } - // send IMAP expunge command and clear cache + /** + * Send IMAP expunge command and clear cache + * + * @param string Mailbox name + * @param boolean False if cache should not be cleared + * @return boolean True on success + */ function expunge($mbox_name='', $clear_cache=TRUE) { $mbox_name = stripslashes($mbox_name); @@ -1133,14 +1575,19 @@ } - // send IMAP expunge command and clear cache + /** + * Send IMAP expunge command and clear cache + * + * @see rcube_imap::expunge() + * @access private + */ function _expunge($mailbox, $clear_cache=TRUE) { $result = iil_C_Expunge($this->conn, $mailbox); if ($result>=0 && $clear_cache) { - //$this->clear_message_cache($mailbox.'.msg'); + $this->clear_message_cache($mailbox.'.msg'); $this->_clear_messagecount($mailbox); } @@ -1157,7 +1604,7 @@ * Get a list of all folders available on the IMAP server * * @param string IMAP root dir - * @return array Inbdexed array with folder names + * @return array Indexed array with folder names */ function list_unsubscribed($root='') { @@ -1184,46 +1631,46 @@ /** - * Get quota + * Get mailbox quota information * added by Nuny + * + * @return mixed Quota info or False if not supported */ function get_quota() { if ($this->get_capability('QUOTA')) - { - $result = iil_C_GetQuota($this->conn); - if ($result["total"]) - return sprintf("%.2fMB / %.2fMB (%.0f%%)", $result["used"] / 1000.0, $result["total"] / 1000.0, $result["percent"]); - } - + return iil_C_GetQuota($this->conn); + return FALSE; } /** - * subscribe to a specific mailbox(es) + * Subscribe to a specific mailbox(es) + * + * @param array Mailbox name(s) + * @return boolean True on success */ - function subscribe($mbox_name, $mode='subscribe') + function subscribe($a_mboxes) { - if (is_array($mbox_name)) - $a_mboxes = $mbox_name; - else if (is_string($mbox_name) && strlen($mbox_name)) - $a_mboxes = explode(',', $mbox_name); - + if (!is_array($a_mboxes)) + $a_mboxes = array($a_mboxes); + // let this common function do the main work return $this->_change_subscription($a_mboxes, 'subscribe'); } /** - * unsubscribe mailboxes + * Unsubscribe mailboxes + * + * @param array Mailbox name(s) + * @return boolean True on success */ - function unsubscribe($mbox_name) + function unsubscribe($a_mboxes) { - if (is_array($mbox_name)) - $a_mboxes = $mbox_name; - else if (is_string($mbox_name) && strlen($mbox_name)) - $a_mboxes = explode(',', $mbox_name); + if (!is_array($a_mboxes)) + $a_mboxes = array($a_mboxes); // let this common function do the main work return $this->_change_subscription($a_mboxes, 'unsubscribe'); @@ -1231,7 +1678,11 @@ /** - * create a new mailbox on the server and register it in local cache + * Create a new mailbox on the server and register it in local cache + * + * @param string New mailbox name (as utf-7 string) + * @param boolean True if the new mailbox should be subscribed + * @param string Name of the created mailbox, false on error */ function create_mailbox($name, $subscribe=FALSE) { @@ -1240,27 +1691,29 @@ // replace backslashes $name = preg_replace('/[\\\]+/', '-', $name); - $name_enc = UTF7EncodeString($name); - // reduce mailbox name to 100 chars - $name_enc = substr($name_enc, 0, 100); + $name = substr($name, 0, 100); - $abs_name = $this->_mod_mailbox($name_enc); + $abs_name = $this->_mod_mailbox($name); $a_mailbox_cache = $this->get_cache('mailboxes'); - if (strlen($abs_name) && (!is_array($a_mailbox_cache) || !in_array_nocase($abs_name, $a_mailbox_cache))) + if (strlen($abs_name) && (!is_array($a_mailbox_cache) || !in_array($abs_name, $a_mailbox_cache))) $result = iil_C_CreateFolder($this->conn, $abs_name); // try to subscribe it - if ($subscribe) - $this->subscribe($name_enc); + if ($result && $subscribe) + $this->subscribe($name); return $result ? $name : FALSE; } /** - * set a new name to an existing mailbox + * Set a new name to an existing mailbox + * + * @param string Mailbox to rename (as utf-7 string) + * @param string New mailbox name (as utf-7 string) + * @return string Name of the renames mailbox, False on error */ function rename_mailbox($mbox_name, $new_name) { @@ -1270,28 +1723,53 @@ $name = preg_replace('/[\\\]+/', '-', $new_name); // encode mailbox name and reduce it to 100 chars - $name_enc = substr(UTF7EncodeString($new_name), 0, 100); + $name = substr($new_name, 0, 100); // make absolute path $mailbox = $this->_mod_mailbox($mbox_name); - $abs_name = $this->_mod_mailbox($name_enc); + $abs_name = $this->_mod_mailbox($name); + // check if mailbox is subscribed + $a_subscribed = $this->_list_mailboxes(); + $subscribed = in_array($mailbox, $a_subscribed); + + // unsubscribe folder + if ($subscribed) + iil_C_UnSubscribe($this->conn, $mailbox); + if (strlen($abs_name)) $result = iil_C_RenameFolder($this->conn, $mailbox, $abs_name); - - // clear cache + if ($result) { + $delm = $this->get_hierarchy_delimiter(); + + // check if mailbox children are subscribed + foreach ($a_subscribed as $c_subscribed) + if (preg_match('/^'.preg_quote($mailbox.$delm, '/').'/', $c_subscribed)) + { + iil_C_UnSubscribe($this->conn, $c_subscribed); + iil_C_Subscribe($this->conn, preg_replace('/^'.preg_quote($mailbox, '/').'/', $abs_name, $c_subscribed)); + } + + // clear cache $this->clear_message_cache($mailbox.'.msg'); - $this->clear_cache('mailboxes'); + $this->clear_cache('mailboxes'); } + + // try to subscribe it + if ($result && $subscribed) + iil_C_Subscribe($this->conn, $abs_name); return $result ? $name : FALSE; } /** - * remove mailboxes from server + * Remove mailboxes from server + * + * @param string Mailbox name + * @return boolean True on success */ function delete_mailbox($mbox_name) { @@ -1301,6 +1779,8 @@ $a_mboxes = $mbox_name; else if (is_string($mbox_name) && strlen($mbox_name)) $a_mboxes = explode(',', $mbox_name); + + $all_mboxes = iil_C_ListMailboxes($this->conn, $this->_mod_mailbox($root), '*'); if (is_array($a_mboxes)) foreach ($a_mboxes as $mbox_name) @@ -1314,6 +1794,19 @@ $result = iil_C_DeleteFolder($this->conn, $mailbox); if ($result>=0) $deleted = TRUE; + + foreach ($all_mboxes as $c_mbox) + { + $regex = preg_quote($mailbox . $this->delimiter, '/'); + $regex = '/^' . $regex . '/'; + if (preg_match($regex, $c_mbox)) + { + iil_C_UnSubscribe($this->conn, $c_mbox); + $result = iil_C_DeleteFolder($this->conn, $c_mbox); + if ($result>=0) + $deleted = TRUE; + } + } } // clear mailboxlist cache @@ -1339,13 +1832,10 @@ foreach ($this->default_folders as $folder) { $abs_name = $this->_mod_mailbox($folder); - if (!in_array_nocase($abs_name, $a_subscribed)) - { - if (!in_array_nocase($abs_name, $a_folders)) - $this->create_mailbox($folder, TRUE); - else - $this->subscribe($folder); - } + if (!in_array_nocase($abs_name, $a_folders)) + $this->create_mailbox($folder, TRUE); + else if (!in_array_nocase($abs_name, $a_subscribed)) + $this->subscribe($folder); } } @@ -1355,7 +1845,9 @@ * internal caching methods * --------------------------------*/ - + /** + * @access private + */ function set_caching($set) { if ($set && is_object($this->db)) @@ -1364,7 +1856,9 @@ $this->caching_enabled = FALSE; } - + /** + * @access private + */ function get_cache($key) { // read cache @@ -1377,7 +1871,9 @@ return $this->cache[$key]; } - + /** + * @access private + */ function update_cache($key, $data) { $this->cache[$key] = $data; @@ -1385,7 +1881,9 @@ $this->cache_changes[$key] = TRUE; } - + /** + * @access private + */ function write_cache() { if ($this->caching_enabled && $this->cache_changed) @@ -1398,7 +1896,9 @@ } } - + /** + * @access private + */ function clear_cache($key=NULL) { if ($key===NULL) @@ -1418,8 +1918,9 @@ } } - - + /** + * @access private + */ function _read_cache_record($key) { $cache_data = FALSE; @@ -1442,10 +1943,12 @@ } } - return $cache_data; + return $cache_data; } - + /** + * @access private + */ function _write_cache_record($key, $data) { if (!$this->db) @@ -1473,7 +1976,7 @@ { $this->db->query( "UPDATE ".get_table_name('cache')." - SET created=now(), + SET created=".$this->db->now().", data=? WHERE user_id=? AND cache_key=?", @@ -1487,14 +1990,16 @@ $this->db->query( "INSERT INTO ".get_table_name('cache')." (created, user_id, cache_key, data) - VALUES (now(), ?, ?, ?)", + VALUES (".$this->db->now().", ?, ?, ?)", $_SESSION['user_id'], $key, $data); } } - + /** + * @access private + */ function _clear_cache_record($key) { $this->db->query( @@ -1512,8 +2017,13 @@ * --------------------------------*/ - // checks if the cache is up-to-date - // return: -3 = off, -2 = incomplete, -1 = dirty + /** + * Checks if the cache is up-to-date + * + * @param string Mailbox name + * @param string Internal cache key + * @return int -3 = off, -2 = incomplete, -1 = dirty + */ function check_cache_status($mailbox, $cache_key) { if (!$this->caching_enabled) @@ -1545,8 +2055,9 @@ return -2; } - - + /** + * @access private + */ function get_message_cache($key, $from, $to, $sort_field, $sort_order) { $cache_key = "$key:$from:$to:$sort_field:$sort_order"; @@ -1574,25 +2085,27 @@ { $uid = $sql_arr['uid']; $this->cache[$cache_key][$uid] = unserialize($sql_arr['headers']); + + // featch headers if unserialize failed + if (empty($this->cache[$cache_key][$uid])) + $this->cache[$cache_key][$uid] = iil_C_FetchHeader($this->conn, preg_replace('/.msg$/', '', $key), $uid, true); } } return $this->cache[$cache_key]; } - - function get_cached_message($key, $uid, $body=FALSE) + /** + * @access private + */ + function &get_cached_message($key, $uid, $struct=false) { - if (!$this->caching_enabled) - return FALSE; - $internal_key = '__single_msg'; - if ($this->caching_enabled && (!isset($this->cache[$internal_key][$uid]) || $body)) + + if ($this->caching_enabled && (!isset($this->cache[$internal_key][$uid]) || + ($struct && empty($this->cache[$internal_key][$uid]->structure)))) { - $sql_select = "idx, uid, headers"; - if ($body) - $sql_select .= ", body"; - + $sql_select = "idx, uid, headers" . ($struct ? ", structure" : ''); $sql_result = $this->db->query( "SELECT $sql_select FROM ".get_table_name('messages')." @@ -1602,27 +2115,27 @@ $_SESSION['user_id'], $key, $uid); - + if ($sql_arr = $this->db->fetch_assoc($sql_result)) { - $headers = unserialize($sql_arr['headers']); - if (is_object($headers) && !empty($sql_arr['body'])) - $headers->body = $sql_arr['body']; - - $this->cache[$internal_key][$uid] = $headers; + $this->cache[$internal_key][$uid] = unserialize($sql_arr['headers']); + if (is_object($this->cache[$internal_key][$uid]) && !empty($sql_arr['structure'])) + $this->cache[$internal_key][$uid]->structure = unserialize($sql_arr['structure']); } } return $this->cache[$internal_key][$uid]; } - + /** + * @access private + */ function get_message_cache_index($key, $force=FALSE, $sort_col='idx', $sort_order='ASC') { static $sa_message_index = array(); // empty key -> empty array - if (empty($key)) + if (!$this->caching_enabled || empty($key)) return array(); if (!empty($sa_message_index[$key]) && !$force) @@ -1644,31 +2157,76 @@ return $sa_message_index[$key]; } - - function add_message_cache($key, $index, $headers) + /** + * @access private + */ + function add_message_cache($key, $index, $headers, $struct=null) { - if (!$key || !is_object($headers) || empty($headers->uid)) + if (empty($key) || !is_object($headers) || empty($headers->uid)) + return; + + // add to internal (fast) cache + $this->cache['__single_msg'][$headers->uid] = $headers; + $this->cache['__single_msg'][$headers->uid]->structure = $struct; + + // no further caching + if (!$this->caching_enabled) return; + + // check for an existing record (probly headers are cached but structure not) + $sql_result = $this->db->query( + "SELECT message_id + FROM ".get_table_name('messages')." + WHERE user_id=? + AND cache_key=? + AND uid=? + AND del<>1", + $_SESSION['user_id'], + $key, + $headers->uid); - $this->db->query( - "INSERT INTO ".get_table_name('messages')." - (user_id, del, cache_key, created, idx, uid, subject, ".$this->db->quoteIdentifier('from').", ".$this->db->quoteIdentifier('to').", cc, date, size, headers) - VALUES (?, 0, ?, now(), ?, ?, ?, ?, ?, ?, ".$this->db->fromunixtime($headers->timestamp).", ?, ?)", - $_SESSION['user_id'], - $key, - $index, - $headers->uid, - (string)substr($this->decode_header($headers->subject, TRUE), 0, 128), - (string)substr($this->decode_header($headers->from, TRUE), 0, 128), - (string)substr($this->decode_header($headers->to, TRUE), 0, 128), - (string)substr($this->decode_header($headers->cc, TRUE), 0, 128), - (int)$headers->size, - serialize($headers)); + // update cache record + if ($sql_arr = $this->db->fetch_assoc($sql_result)) + { + $this->db->query( + "UPDATE ".get_table_name('messages')." + SET idx=?, headers=?, structure=? + WHERE message_id=?", + $index, + serialize($headers), + is_object($struct) ? serialize($struct) : NULL, + $sql_arr['message_id'] + ); + } + else // insert new record + { + $this->db->query( + "INSERT INTO ".get_table_name('messages')." + (user_id, del, cache_key, created, idx, uid, subject, ".$this->db->quoteIdentifier('from').", ".$this->db->quoteIdentifier('to').", cc, date, size, headers, structure) + VALUES (?, 0, ?, ".$this->db->now().", ?, ?, ?, ?, ?, ?, ".$this->db->fromunixtime($headers->timestamp).", ?, ?, ?)", + $_SESSION['user_id'], + $key, + $index, + $headers->uid, + (string)substr($this->decode_header($headers->subject, TRUE), 0, 128), + (string)substr($this->decode_header($headers->from, TRUE), 0, 128), + (string)substr($this->decode_header($headers->to, TRUE), 0, 128), + (string)substr($this->decode_header($headers->cc, TRUE), 0, 128), + (int)$headers->size, + serialize($headers), + is_object($struct) ? serialize($struct) : NULL + ); + } } - + /** + * @access private + */ function remove_message_cache($key, $index) { + if (!$this->caching_enabled) + return; + $this->db->query( "DELETE FROM ".get_table_name('messages')." WHERE user_id=? @@ -1679,9 +2237,14 @@ $index); } - + /** + * @access private + */ function clear_message_cache($key, $start_index=1) { + if (!$this->caching_enabled) + return; + $this->db->query( "DELETE FROM ".get_table_name('messages')." WHERE user_id=? @@ -1699,11 +2262,20 @@ * encoding/decoding methods * --------------------------------*/ - - function decode_address_list($input, $max=NULL) + /** + * Split an address list into a structured array list + * + * @param string Input string + * @param int List only this number of addresses + * @param boolean Decode address strings + * @return array Indexed list of addresses + */ + function decode_address_list($input, $max=null, $decode=true) { - $a = $this->_parse_address_list($input); + $a = $this->_parse_address_list($input, $decode); $out = array(); + // Special chars as defined by RFC 822 need to in quoted string (or escaped). + $special_chars = '[\(\)\<\>\\\.\[\]@,;:"]'; if (!is_array($a)) return $out; @@ -1716,7 +2288,12 @@ $j++; $address = $val['address']; $name = preg_replace(array('/^[\'"]/', '/[\'"]$/'), '', trim($val['name'])); - $string = $name!==$address ? sprintf('%s <%s>', strpos($name, ',')!==FALSE ? '"'.$name.'"' : $name, $address) : $address; + if ($name && $address && $name != $address) + $string = sprintf('%s <%s>', preg_match("/$special_chars/", $name) ? '"'.addcslashes($name, '"').'"' : $name, $address); + else if ($address) + $string = $address; + else if ($name) + $string = $name; $out[$j] = array('name' => $name, 'mailto' => $address, @@ -1730,13 +2307,18 @@ } + /** + * Decode a message header value + * + * @param string Header value + * @param boolean Remove quotes if necessary + * @return string Decoded string + */ function decode_header($input, $remove_quotes=FALSE) { - $str = $this->decode_mime_string((string)$input); + $str = rcube_imap::decode_mime_string((string)$input, $this->default_charset); if ($str{0}=='"' && $remove_quotes) - { $str = str_replace('"', '', $str); - } return $str; } @@ -1745,15 +2327,22 @@ /** * Decode a mime-encoded string to internal charset * - * @access static + * @param string Header value + * @param string Fallback charset if none specified + * @return string Decoded string + * @static */ - function decode_mime_string($input, $recursive=false) + function decode_mime_string($input, $fallback=null) { $out = ''; $pos = strpos($input, '=?'); if ($pos !== false) { + // rfc: all line breaks or other characters not found in the Base64 Alphabet must be ignored by decoding software + // delete all blanks between MIME-lines, differently we can receive unnecessary blanks and broken utf-8 symbols + $input = preg_replace("/\?=\s+=\?/", '?==?', $input); + $out = substr($input, 0, $pos); $end_cs_pos = strpos($input, "?", $pos+2); @@ -1764,20 +2353,20 @@ $rest = substr($input, $end_pos+2); $out .= rcube_imap::_decode_mime_string_part($encstr); - $out .= rcube_imap::decode_mime_string($rest); + $out .= rcube_imap::decode_mime_string($rest, $fallback); return $out; } - // no encoding information, defaults to what is specified in the class header - return rcube_charset_convert($input, 'ISO-8859-1'); + // no encoding information, use fallback + return rcube_charset_convert($input, !empty($fallback) ? $fallback : 'ISO-8859-1'); } /** * Decode a part of a mime-encoded string * - * @access static + * @access private */ function _decode_mime_string_part($str) { @@ -1805,6 +2394,14 @@ } + /** + * Decode a mime part + * + * @param string Input string + * @param string Part encoding + * @return string Decoded string + * @access private + */ function mime_decode($input, $encoding='7bit') { switch (strtolower($encoding)) @@ -1827,34 +2424,49 @@ } - function mime_encode($input, $encoding='7bit') - { - switch ($encoding) - { - case 'quoted-printable': - return quoted_printable_encode($input); - break; - - case 'base64': - return base64_encode($input); - break; - - default: - return $input; - } - } - - - // convert body chars according to the ctype_parameters + /** + * Convert body charset to UTF-8 according to the ctype_parameters + * + * @param string Part body to decode + * @param string Charset to convert from + * @return string Content converted to internal charset + */ function charset_decode($body, $ctype_param) { if (is_array($ctype_param) && !empty($ctype_param['charset'])) return rcube_charset_convert($body, $ctype_param['charset']); // defaults to what is specified in the class header - return rcube_charset_convert($body, 'ISO-8859-1'); + return rcube_charset_convert($body, $this->default_charset); } + + /** + * Translate UID to message ID + * + * @param int Message UID + * @param string Mailbox name + * @return int Message ID + */ + function get_id($uid, $mbox_name=NULL) + { + $mailbox = $mbox_name ? $this->_mod_mailbox($mbox_name) : $this->mailbox; + return $this->_uid2id($uid, $mailbox); + } + + + /** + * Translate message number to UID + * + * @param int Message ID + * @param string Mailbox name + * @return int Message UID + */ + function get_uid($id,$mbox_name=NULL) + { + $mailbox = $mbox_name ? $this->_mod_mailbox($mbox_name) : $this->mailbox; + return $this->_id2uid($id, $mailbox); + } @@ -1863,6 +2475,9 @@ * --------------------------------*/ + /** + * @access private + */ function _mod_mailbox($mbox_name, $mode='in') { if ((!empty($this->root_ns) && $this->root_ns == $mbox_name) || $mbox_name == 'INBOX') @@ -1876,8 +2491,22 @@ return $mbox_name; } + /** + * Validate the given input and save to local properties + * @access private + */ + function _set_sort_order($sort_field, $sort_order) + { + if ($sort_field != null) + $this->sort_field = asciiwords($sort_field); + if ($sort_order != null) + $this->sort_order = strtoupper($sort_order) == 'DESC' ? 'DESC' : 'ASC'; + } - // sort mailboxes first by default folders and then in alphabethical order + /** + * Sort mailboxes first by default folders and then in alphabethical order + * @access private + */ function _sort_mailbox_list($a_folders) { $a_out = $a_defaults = array(); @@ -1886,30 +2515,23 @@ foreach($a_folders as $i => $folder) { if ($folder{0}=='.') - continue; + continue; - if (($p = array_search(strtolower($folder), $this->default_folders_lc))!==FALSE) - $a_defaults[$p] = $folder; + if (($p = array_search(strtolower($folder), $this->default_folders_lc)) !== false && !$a_defaults[$p]) + $a_defaults[$p] = $folder; else $a_out[] = $folder; } - sort($a_out); + natcasesort($a_out); ksort($a_defaults); return array_merge($a_defaults, $a_out); } - function get_id($uid, $mbox_name=NULL) - { - return $this->_uid2id($uid, $mbox_name); - } - - function get_uid($id,$mbox_name=NULL) - { - return $this->_id2uid($id, $mbox_name); - } - + /** + * @access private + */ function _uid2id($uid, $mbox_name=NULL) { if (!$mbox_name) @@ -1921,16 +2543,31 @@ return $this->uid_id_map[$mbox_name][$uid]; } + /** + * @access private + */ function _id2uid($id, $mbox_name=NULL) { if (!$mbox_name) $mbox_name = $this->mailbox; - return iil_C_ID2UID($this->conn, $mbox_name, $id); + $index = array_flip((array)$this->uid_id_map[$mbox_name]); + if (isset($index[$id])) + $uid = $index[$id]; + else + { + $uid = iil_C_ID2UID($this->conn, $mbox_name, $id); + $this->uid_id_map[$mbox_name][$uid] = $id; + } + + return $uid; } - // parse string or array of server capabilities and put them in internal array + /** + * Parse string or array of server capabilities and put them in internal array + * @access private + */ function _parse_capability($caps) { if (!is_array($caps)) @@ -1957,7 +2594,10 @@ } - // subscribe/unsubscribe a list of mailboxes and update local cache + /** + * Subscribe/unsubscribe a list of mailboxes and update local cache + * @access private + */ function _change_subscription($a_mboxes, $mode) { $updated = FALSE; @@ -1998,7 +2638,10 @@ } - // increde/decrese messagecount for a specific mailbox + /** + * Increde/decrese messagecount for a specific mailbox + * @access private + */ function _set_messagecount($mbox_name, $mode, $increment) { $a_mailbox_cache = FALSE; @@ -2024,7 +2667,10 @@ } - // remove messagecount of a specific mailbox from cache + /** + * Remove messagecount of a specific mailbox from cache + * @access private + */ function _clear_messagecount($mbox_name='') { $a_mailbox_cache = FALSE; @@ -2040,20 +2686,48 @@ } - function _parse_address_list($str) + /** + * Split RFC822 header string into an associative array + * @access private + */ + function _parse_headers($headers) { - $a = $this->_explode_quoted_string(',', $str); + $a_headers = array(); + $lines = explode("\n", $headers); + $c = count($lines); + for ($i=0; $i<$c; $i++) + { + if ($p = strpos($lines[$i], ': ')) + { + $field = strtolower(substr($lines[$i], 0, $p)); + $value = trim(substr($lines[$i], $p+1)); + if (!empty($value)) + $a_headers[$field] = $value; + } + } + + return $a_headers; + } + + + /** + * @access private + */ + function _parse_address_list($str, $decode=true) + { + // remove any newlines and carriage returns before + $a = $this->_explode_quoted_string('[,;]', preg_replace( "/[\r\n]/", " ", $str)); $result = array(); foreach ($a as $key => $val) { - $val = str_replace("\"<", "\" <", $val); - $sub_a = $this->_explode_quoted_string(' ', $this->decode_header($val)); + $val = preg_replace("/([\"\w])</", "$1 <", $val); + $sub_a = $this->_explode_quoted_string(' ', $decode ? $this->decode_header($val) : $val); $result[$key]['name'] = ''; foreach ($sub_a as $k => $v) { - if ((strpos($v, '@') > 0) && (strpos($v, '.') > 0)) + if (strpos($v, '@') > 0) $result[$key]['address'] = str_replace('<', '', str_replace('>', '', $v)); else $result[$key]['name'] .= (empty($result[$key]['name'])?'':' ').str_replace("\"",'',stripslashes($v)); @@ -2067,30 +2741,58 @@ } + /** + * @access private + */ function _explode_quoted_string($delimiter, $string) { - $quotes = explode("\"", $string); - foreach ($quotes as $key => $val) - if (($key % 2) == 1) - $quotes[$key] = str_replace($delimiter, "_!@!_", $quotes[$key]); - - $string = implode("\"", $quotes); - - $result = explode($delimiter, $string); - foreach ($result as $key => $val) - $result[$key] = str_replace("_!@!_", $delimiter, $result[$key]); + $result = array(); + $strlen = strlen($string); + for ($q=$p=$i=0; $i < $strlen; $i++) + { + if ($string{$i} == "\"" && $string{$i-1} != "\\") + $q = $q ? false : true; + else if (!$q && preg_match("/$delimiter/", $string{$i})) + { + $result[] = substr($string, $p, $i - $p); + $p = $i + 1; + } + } + $result[] = substr($string, $p); return $result; } - } +} // end class rcube_imap /** - * rcube_header_sorter - * + * Class representing a message part + * + * @package Mail + */ +class rcube_message_part +{ + var $mime_id = ''; + var $ctype_primary = 'text'; + var $ctype_secondary = 'plain'; + var $mimetype = 'text/plain'; + var $disposition = ''; + var $filename = ''; + var $encoding = '8bit'; + var $charset = ''; + var $size = 0; + var $headers = array(); + var $d_parameters = array(); + var $ctype_parameters = array(); + +} + + +/** * Class for sorting an array of iilBasicHeader objects in a predetermined order. * + * @package Mail * @author Eric Stadtherr */ class rcube_header_sorter @@ -2098,9 +2800,9 @@ var $sequence_numbers = array(); /** - * set the predetermined sort order. + * Set the predetermined sort order. * - * @param array $seqnums numerically indexed array of IMAP message sequence numbers + * @param array Numerically indexed array of IMAP message sequence numbers */ function set_sequence_numbers($seqnums) { @@ -2108,9 +2810,9 @@ } /** - * sort the array of header objects + * Sort the array of header objects * - * @param array $headers array of iilBasicHeader objects indexed by UID + * @param array Array of iilBasicHeader objects indexed by UID */ function sort_headers(&$headers) { @@ -2125,9 +2827,10 @@ } /** - * get the position of a message sequence number in my sequence_numbers array + * Get the position of a message sequence number in my sequence_numbers array * - * @param integer $seqnum message sequence number contained in sequence_numbers + * @param int Message sequence number contained in sequence_numbers + * @return int Position, -1 if not found */ function position_of($seqnum) { @@ -2163,10 +2866,10 @@ /** * Add quoted-printable encoding to a given string * - * @param string $input string to encode - * @param int $line_max add new line after this number of characters - * @param boolena $space_conf true if spaces should be converted into =20 - * @return encoded string + * @param string String to encode + * @param int Add new line after this number of characters + * @param boolean True if spaces should be converted into =20 + * @return string Encoded string */ function quoted_printable_encode($input, $line_max=76, $space_conv=false) { @@ -2225,4 +2928,5 @@ return trim($output); } + ?> -- Gitblit v1.9.1