alecpl
2008-10-03 f613a1e4e004dd03d7de80ea5a45bee71d3a3454
commit | author | age
4e17e6 1 <?php
T 2
3 /*
4  +-----------------------------------------------------------------------+
47124c 5  | program/include/rcube_imap.php                                        |
4e17e6 6  |                                                                       |
T 7  | This file is part of the RoundCube Webmail client                     |
47124c 8  | Copyright (C) 2005-2008, RoundCube Dev. - Switzerland                 |
30233b 9  | Licensed under the GNU GPL                                            |
4e17e6 10  |                                                                       |
T 11  | PURPOSE:                                                              |
12  |   IMAP wrapper that implements the Iloha IMAP Library (IIL)           |
13  |   See http://ilohamail.org/ for details                               |
14  |                                                                       |
15  +-----------------------------------------------------------------------+
16  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
17  +-----------------------------------------------------------------------+
18
19  $Id$
20
21 */
22
23
6d969b 24 /*
15a9d1 25  * Obtain classes from the Iloha IMAP library
T 26  */
4e17e6 27 require_once('lib/imap.inc');
T 28 require_once('lib/mime.inc');
29
30
15a9d1 31 /**
T 32  * Interface class for accessing an IMAP server
33  *
34  * This is a wrapper that implements the Iloha IMAP Library (IIL)
35  *
6d969b 36  * @package    Mail
15a9d1 37  * @author     Thomas Bruederli <roundcube@gmail.com>
d5342a 38  * @version    1.40
15a9d1 39  * @link       http://ilohamail.org
T 40  */
4e17e6 41 class rcube_imap
6d969b 42 {
1cded8 43   var $db;
4e17e6 44   var $conn;
520c36 45   var $root_ns = '';
4e17e6 46   var $root_dir = '';
T 47   var $mailbox = 'INBOX';
48   var $list_page = 1;
49   var $page_size = 10;
31b2ce 50   var $sort_field = 'date';
T 51   var $sort_order = 'DESC';
9490b7 52   var $delimiter = NULL;
6dc026 53   var $caching_enabled = FALSE;
17b5fb 54   var $default_charset = 'ISO-8859-1';
fa4cd2 55   var $default_folders = array('INBOX');
T 56   var $default_folders_lc = array('inbox');
4e17e6 57   var $cache = array();
1cded8 58   var $cache_keys = array();  
326e87 59   var $cache_changes = array();
4e17e6 60   var $uid_id_map = array();
T 61   var $msg_headers = array();
15a9d1 62   var $skip_deleted = FALSE;
04c618 63   var $search_set = NULL;
T 64   var $search_subject = '';
65   var $search_string = '';
66   var $search_charset = '';
15a9d1 67   var $debug_level = 1;
fc6725 68   var $error_code = 0;
4e17e6 69
T 70
15a9d1 71   /**
T 72    * Object constructor
73    *
6d969b 74    * @param object DB Database connection
15a9d1 75    */
1cded8 76   function __construct($db_conn)
4e17e6 77     {
3f9edb 78     $this->db = $db_conn;
4e17e6 79     }
T 80
15a9d1 81
T 82   /**
83    * Connect to an IMAP server
84    *
85    * @param  string   Host to connect
86    * @param  string   Username for IMAP account
87    * @param  string   Password for IMAP account
88    * @param  number   Port to connect to
5bc0ab 89    * @param  string   SSL schema (either ssl or tls) or null if plain connection
15a9d1 90    * @return boolean  TRUE on success, FALSE on failure
T 91    * @access public
92    */
1fb78c 93   function connect($host, $user, $pass, $port=143, $use_ssl=null, $auth_type=null)
4e17e6 94     {
4647e1 95     global $ICL_SSL, $ICL_PORT, $IMAP_USE_INTERNAL_DATE;
42b113 96     
T 97     // check for Open-SSL support in PHP build
98     if ($use_ssl && in_array('openssl', get_loaded_extensions()))
5bc0ab 99       $ICL_SSL = $use_ssl == 'imaps' ? 'ssl' : $use_ssl;
520c36 100     else if ($use_ssl)
T 101       {
15a9d1 102       raise_error(array('code' => 403, 'type' => 'imap', 'file' => __FILE__,
520c36 103                         'message' => 'Open SSL not available;'), TRUE, FALSE);
T 104       $port = 143;
105       }
4e17e6 106
T 107     $ICL_PORT = $port;
4647e1 108     $IMAP_USE_INTERNAL_DATE = false;
b026c3 109
1fb78c 110     $this->conn = iil_Connect($host, $user, $pass, array('imap' => $auth_type ? $auth_type : 'check'));
4e17e6 111     $this->host = $host;
T 112     $this->user = $user;
113     $this->pass = $pass;
520c36 114     $this->port = $port;
T 115     $this->ssl = $use_ssl;
42b113 116     
520c36 117     // print trace mesages
15a9d1 118     if ($this->conn && ($this->debug_level & 8))
520c36 119       console($this->conn->message);
T 120     
121     // write error log
42b113 122     else if (!$this->conn && $GLOBALS['iil_error'])
T 123       {
fc6725 124       $this->error_code = $GLOBALS['iil_errornum'];
42b113 125       raise_error(array('code' => 403,
T 126                        'type' => 'imap',
127                        'message' => $GLOBALS['iil_error']), TRUE, FALSE);
520c36 128       }
T 129
f7bfec 130     // get server properties
520c36 131     if ($this->conn)
T 132       {
133       if (!empty($this->conn->delimiter))
134         $this->delimiter = $this->conn->delimiter;
135       if (!empty($this->conn->rootdir))
7902df 136         {
T 137         $this->set_rootdir($this->conn->rootdir);
138         $this->root_ns = ereg_replace('[\.\/]$', '', $this->conn->rootdir);
139         }
42b113 140       }
4e17e6 141
T 142     return $this->conn ? TRUE : FALSE;
143     }
144
145
15a9d1 146   /**
T 147    * Close IMAP connection
148    * Usually done on script shutdown
149    *
150    * @access public
151    */
4e17e6 152   function close()
T 153     {    
154     if ($this->conn)
155       iil_Close($this->conn);
156     }
157
158
15a9d1 159   /**
T 160    * Close IMAP connection and re-connect
161    * This is used to avoid some strange socket errors when talking to Courier IMAP
162    *
163    * @access public
164    */
520c36 165   function reconnect()
T 166     {
167     $this->close();
168     $this->connect($this->host, $this->user, $this->pass, $this->port, $this->ssl);
32efb0 169     
T 170     // issue SELECT command to restore connection status
171     if ($this->mailbox)
172       iil_C_Select($this->conn, $this->mailbox);
520c36 173     }
T 174
175
15a9d1 176   /**
T 177    * Set a root folder for the IMAP connection.
178    *
179    * Only folders within this root folder will be displayed
180    * and all folder paths will be translated using this folder name
181    *
182    * @param  string   Root folder
183    * @access public
184    */
4e17e6 185   function set_rootdir($root)
T 186     {
520c36 187     if (ereg('[\.\/]$', $root)) //(substr($root, -1, 1)==='/')
4e17e6 188       $root = substr($root, 0, -1);
T 189
190     $this->root_dir = $root;
520c36 191     
T 192     if (empty($this->delimiter))
193       $this->get_hierarchy_delimiter();
17b5fb 194     }
T 195
196
197   /**
198    * Set default message charset
199    *
200    * This will be used for message decoding if a charset specification is not available
201    *
202    * @param  string   Charset string
203    * @access public
204    */
205   function set_charset($cs)
206     {
f94a80 207     $this->default_charset = $cs;
4e17e6 208     }
T 209
210
15a9d1 211   /**
T 212    * This list of folders will be listed above all other folders
213    *
214    * @param  array  Indexed list of folder names
215    * @access public
216    */
4e17e6 217   function set_default_mailboxes($arr)
T 218     {
219     if (is_array($arr))
220       {
fa4cd2 221       $this->default_folders = $arr;
T 222       $this->default_folders_lc = array();
223
4e17e6 224       // add inbox if not included
fa4cd2 225       if (!in_array_nocase('INBOX', $this->default_folders))
T 226         array_unshift($this->default_folders, 'INBOX');
227
228       // create a second list with lower cased names
229       foreach ($this->default_folders as $mbox)
230         $this->default_folders_lc[] = strtolower($mbox);
4e17e6 231       }
T 232     }
233
234
15a9d1 235   /**
T 236    * Set internal mailbox reference.
237    *
238    * All operations will be perfomed on this mailbox/folder
239    *
240    * @param  string  Mailbox/Folder name
241    * @access public
242    */
aadfa1 243   function set_mailbox($new_mbox)
4e17e6 244     {
aadfa1 245     $mailbox = $this->_mod_mailbox($new_mbox);
4e17e6 246
T 247     if ($this->mailbox == $mailbox)
248       return;
249
250     $this->mailbox = $mailbox;
251
252     // clear messagecount cache for this mailbox
253     $this->_clear_messagecount($mailbox);
254     }
255
256
15a9d1 257   /**
T 258    * Set internal list page
259    *
260    * @param  number  Page number to list
261    * @access public
262    */
4e17e6 263   function set_page($page)
T 264     {
265     $this->list_page = (int)$page;
266     }
267
268
15a9d1 269   /**
T 270    * Set internal page size
271    *
272    * @param  number  Number of messages to display on one page
273    * @access public
274    */
4e17e6 275   function set_pagesize($size)
T 276     {
277     $this->page_size = (int)$size;
278     }
04c618 279     
T 280
281   /**
282    * Save a set of message ids for future message listing methods
283    *
284    * @param  array  List of IMAP fields to search in
285    * @param  string Search string
286    * @param  array  List of message ids or NULL if empty
287    */
288   function set_search_set($subject, $str=null, $msgs=null, $charset=null)
289     {
290     if (is_array($subject) && $str == null && $msgs == null)
291       list($subject, $str, $msgs, $charset) = $subject;
292     if ($msgs != null && !is_array($msgs))
293       $msgs = split(',', $msgs);
294       
295     $this->search_subject = $subject;
296     $this->search_string = $str;
4845a1 297     $this->search_set = (array)$msgs;
04c618 298     $this->search_charset = $charset;
T 299     }
300
301
302   /**
303    * Return the saved search set as hash array
6d969b 304    * @return array Search set
04c618 305    */
T 306   function get_search_set()
307     {
308     return array($this->search_subject, $this->search_string, $this->search_set, $this->search_charset);
309     }
4e17e6 310
T 311
15a9d1 312   /**
T 313    * Returns the currently used mailbox name
314    *
315    * @return  string Name of the mailbox/folder
316    * @access  public
317    */
4e17e6 318   function get_mailbox_name()
T 319     {
320     return $this->conn ? $this->_mod_mailbox($this->mailbox, 'out') : '';
1cded8 321     }
T 322
323
15a9d1 324   /**
T 325    * Returns the IMAP server's capability
326    *
327    * @param   string  Capability name
328    * @return  mixed   Capability value or TRUE if supported, FALSE if not
329    * @access  public
330    */
1cded8 331   function get_capability($cap)
T 332     {
11ef97 333     return iil_C_GetCapability($this->conn, strtoupper($cap));
4e17e6 334     }
T 335
336
15a9d1 337   /**
5b3dd4 338    * Checks the PERMANENTFLAGS capability of the current mailbox
T 339    * and returns true if the given flag is supported by the IMAP server
340    *
341    * @param   string  Permanentflag name
342    * @return  mixed   True if this flag is supported
343    * @access  public
344    */
345   function check_permflag($flag)
346     {
347     $flagsmap = $GLOBALS['IMAP_FLAGS'];
348     return (($imap_flag = $flagsmap[strtoupper($flag)]) && in_array_nocase($imap_flag, $this->conn->permanentflags));
349     }
350
351
352   /**
15a9d1 353    * Returns the delimiter that is used by the IMAP server for folder separation
T 354    *
355    * @return  string  Delimiter string
356    * @access  public
357    */
597170 358   function get_hierarchy_delimiter()
T 359     {
360     if ($this->conn && empty($this->delimiter))
361       $this->delimiter = iil_C_GetHierarchyDelimiter($this->conn);
362
7902df 363     if (empty($this->delimiter))
T 364       $this->delimiter = '/';
365
597170 366     return $this->delimiter;
T 367     }
368
15a9d1 369
T 370   /**
371    * Public method for mailbox listing.
372    *
373    * Converts mailbox name with root dir first
374    *
375    * @param   string  Optional root folder
376    * @param   string  Optional filter for mailbox listing
377    * @return  array   List of mailboxes/folders
378    * @access  public
379    */
4e17e6 380   function list_mailboxes($root='', $filter='*')
T 381     {
382     $a_out = array();
383     $a_mboxes = $this->_list_mailboxes($root, $filter);
384
aadfa1 385     foreach ($a_mboxes as $mbox_row)
4e17e6 386       {
aadfa1 387       $name = $this->_mod_mailbox($mbox_row, 'out');
4e17e6 388       if (strlen($name))
T 389         $a_out[] = $name;
390       }
391
fa4cd2 392     // INBOX should always be available
T 393     if (!in_array_nocase('INBOX', $a_out))
394       array_unshift($a_out, 'INBOX');
395
4e17e6 396     // sort mailboxes
T 397     $a_out = $this->_sort_mailbox_list($a_out);
398
399     return $a_out;
400     }
401
15a9d1 402
T 403   /**
404    * Private method for mailbox listing
405    *
406    * @return  array   List of mailboxes/folders
6d969b 407    * @see     rcube_imap::list_mailboxes()
15a9d1 408    * @access  private
T 409    */
4e17e6 410   function _list_mailboxes($root='', $filter='*')
T 411     {
412     $a_defaults = $a_out = array();
413     
414     // get cached folder list    
415     $a_mboxes = $this->get_cache('mailboxes');
416     if (is_array($a_mboxes))
417       return $a_mboxes;
418
419     // retrieve list of folders from IMAP server
420     $a_folders = iil_C_ListSubscribed($this->conn, $this->_mod_mailbox($root), $filter);
421     
422     if (!is_array($a_folders) || !sizeof($a_folders))
423       $a_folders = array();
424
425     // write mailboxlist to cache
426     $this->update_cache('mailboxes', $a_folders);
427     
428     return $a_folders;
429     }
430
431
3f9edb 432   /**
T 433    * Get message count for a specific mailbox
434    *
435    * @param   string   Mailbox/folder name
436    * @param   string   Mode for count [ALL|UNSEEN|RECENT]
437    * @param   boolean  Force reading from server and update cache
6d969b 438    * @return  int      Number of messages
T 439    * @access  public
3f9edb 440    */
aadfa1 441   function messagecount($mbox_name='', $mode='ALL', $force=FALSE)
4e17e6 442     {
aadfa1 443     $mailbox = $mbox_name ? $this->_mod_mailbox($mbox_name) : $this->mailbox;
4e17e6 444     return $this->_messagecount($mailbox, $mode, $force);
T 445     }
446
3f9edb 447
T 448   /**
449    * Private method for getting nr of messages
450    *
451    * @access  private
6d969b 452    * @see     rcube_imap::messagecount()
3f9edb 453    */
4e17e6 454   function _messagecount($mailbox='', $mode='ALL', $force=FALSE)
T 455     {
456     $a_mailbox_cache = FALSE;
457     $mode = strtoupper($mode);
458
15a9d1 459     if (empty($mailbox))
4e17e6 460       $mailbox = $this->mailbox;
04c618 461       
T 462     // count search set
110748 463     if ($this->search_string && $mailbox == $this->mailbox && $mode == 'ALL' && !$force)
4845a1 464       return count((array)$this->search_set);
4e17e6 465
T 466     $a_mailbox_cache = $this->get_cache('messagecount');
467     
468     // return cached value
469     if (!$force && is_array($a_mailbox_cache[$mailbox]) && isset($a_mailbox_cache[$mailbox][$mode]))
31b2ce 470       return $a_mailbox_cache[$mailbox][$mode];
4e17e6 471
197601 472     // RECENT count is fetched a bit different
15a9d1 473     if ($mode == 'RECENT')
T 474        $count = iil_C_CheckForRecent($this->conn, $mailbox);
31b2ce 475
15a9d1 476     // use SEARCH for message counting
T 477     else if ($this->skip_deleted)
31b2ce 478       {
15a9d1 479       $search_str = "ALL UNDELETED";
T 480
481       // get message count and store in cache
482       if ($mode == 'UNSEEN')
483         $search_str .= " UNSEEN";
484
485       // get message count using SEARCH
486       // not very performant but more precise (using UNDELETED)
487       $count = 0;
488       $index = $this->_search_index($mailbox, $search_str);
489       if (is_array($index))
490         {
491         $str = implode(",", $index);
492         if (!empty($str))
493           $count = count($index);
494         }
495       }
496     else
497       {
498       if ($mode == 'UNSEEN')
499         $count = iil_C_CountUnseen($this->conn, $mailbox);
500       else
501         $count = iil_C_CountMessages($this->conn, $mailbox);
31b2ce 502       }
4e17e6 503
13c1af 504     if (!is_array($a_mailbox_cache[$mailbox]))
4e17e6 505       $a_mailbox_cache[$mailbox] = array();
T 506       
507     $a_mailbox_cache[$mailbox][$mode] = (int)$count;
31b2ce 508
4e17e6 509     // write back to cache
T 510     $this->update_cache('messagecount', $a_mailbox_cache);
511
512     return (int)$count;
513     }
514
515
3f9edb 516   /**
T 517    * Public method for listing headers
518    * convert mailbox name with root dir first
519    *
520    * @param   string   Mailbox/folder name
6d969b 521    * @param   int      Current page to list
3f9edb 522    * @param   string   Header field to sort by
T 523    * @param   string   Sort order [ASC|DESC]
524    * @return  array    Indexed array with message header objects
525    * @access  public   
526    */
aadfa1 527   function list_headers($mbox_name='', $page=NULL, $sort_field=NULL, $sort_order=NULL)
4e17e6 528     {
aadfa1 529     $mailbox = $mbox_name ? $this->_mod_mailbox($mbox_name) : $this->mailbox;
4e17e6 530     return $this->_list_headers($mailbox, $page, $sort_field, $sort_order);
T 531     }
532
533
3f9edb 534   /**
4647e1 535    * Private method for listing message headers
3f9edb 536    *
T 537    * @access  private
538    * @see     rcube_imap::list_headers
539    */
31b2ce 540   function _list_headers($mailbox='', $page=NULL, $sort_field=NULL, $sort_order=NULL, $recursive=FALSE)
4e17e6 541     {
T 542     if (!strlen($mailbox))
17fc71 543       return array();
04c618 544
T 545     // use saved message set
4845a1 546     if ($this->search_string && $mailbox == $this->mailbox)
04c618 547       return $this->_list_header_set($mailbox, $this->search_set, $page, $sort_field, $sort_order);
T 548
d5342a 549     $this->_set_sort_order($sort_field, $sort_order);
4e17e6 550
1cded8 551     $max = $this->_messagecount($mailbox);
T 552     $start_msg = ($this->list_page-1) * $this->page_size;
06ec1f 553
4647e1 554     list($begin, $end) = $this->_get_message_range($max, $page);
06ec1f 555
04c618 556     // mailbox is empty
078adf 557     if ($begin >= $end)
T 558       return array();
04c618 559       
1cded8 560     $headers_sorted = FALSE;
T 561     $cache_key = $mailbox.'.msg';
562     $cache_status = $this->check_cache_status($mailbox, $cache_key);
563
564     // cache is OK, we can get all messages from local cache
565     if ($cache_status>0)
566       {
31b2ce 567       $a_msg_headers = $this->get_message_cache($cache_key, $start_msg, $start_msg+$this->page_size, $this->sort_field, $this->sort_order);
1cded8 568       $headers_sorted = TRUE;
T 569       }
c4e7e4 570     // cache is dirty, sync it
T 571     else if ($this->caching_enabled && $cache_status==-1 && !$recursive)
572       {
573       $this->sync_header_index($mailbox);
574       return $this->_list_headers($mailbox, $page, $this->sort_field, $this->sort_order, TRUE);
575       }
1cded8 576     else
T 577       {
578       // retrieve headers from IMAP
15a9d1 579       if ($this->get_capability('sort') && ($msg_index = iil_C_Sort($this->conn, $mailbox, $this->sort_field, $this->skip_deleted ? 'UNDELETED' : '')))
05d180 580         {
T 581         $mymsgidx = array_slice ($msg_index, $begin, $end-$begin);
257782 582         $msgs = join(",", $mymsgidx);
1cded8 583         }
T 584       else
585         {
c4e7e4 586         $msgs = sprintf("%d:%d", $begin+1, $end);
257782 587         $msg_index = range($begin, $end);
1cded8 588         }
T 589
06ec1f 590
1cded8 591       // fetch reuested headers from server
T 592       $a_msg_headers = array();
15a9d1 593       $deleted_count = $this->_fetch_headers($mailbox, $msgs, $a_msg_headers, $cache_key);
257782 594       if ($this->sort_order == 'DESC' && $headers_sorted) {  
A 595         //since the sort order is not used in the iil_c_sort function we have to do it here
596         $a_msg_headers = array_reverse($a_msg_headers);
597       }
f388a8 598       // delete cached messages with a higher index than $max+1
S 599       // Changed $max to $max+1 to fix this bug : #1484295
600       $this->clear_message_cache($cache_key, $max + 1);
1cded8 601
06ec1f 602
1cded8 603       // kick child process to sync cache
31b2ce 604       // ...
06ec1f 605
1cded8 606       }
T 607
608     // return empty array if no messages found
257782 609     if (!is_array($a_msg_headers) || empty($a_msg_headers)) {
A 610       return array();
611     }
1cded8 612
T 613     // if not already sorted
06ec1f 614     if (!$headers_sorted)
7e93ff 615       {
257782 616       // use this class for message sorting
A 617       $sorter = new rcube_header_sorter();
618       $sorter->set_sequence_numbers($msg_index);
7e93ff 619       $sorter->sort_headers($a_msg_headers);
e6f360 620
7e93ff 621       if ($this->sort_order == 'DESC')
T 622         $a_msg_headers = array_reverse($a_msg_headers);
623       }
1cded8 624
T 625     return array_values($a_msg_headers);
4e17e6 626     }
7e93ff 627
T 628
15a9d1 629
4647e1 630   /**
T 631    * Public method for listing a specific set of headers
632    * convert mailbox name with root dir first
633    *
634    * @param   string   Mailbox/folder name
635    * @param   array    List of message ids to list
6d969b 636    * @param   int      Current page to list
4647e1 637    * @param   string   Header field to sort by
T 638    * @param   string   Sort order [ASC|DESC]
639    * @return  array    Indexed array with message header objects
640    * @access  public   
641    */
aadfa1 642   function list_header_set($mbox_name='', $msgs, $page=NULL, $sort_field=NULL, $sort_order=NULL)
4647e1 643     {
aadfa1 644     $mailbox = $mbox_name ? $this->_mod_mailbox($mbox_name) : $this->mailbox;
4647e1 645     return $this->_list_header_set($mailbox, $msgs, $page, $sort_field, $sort_order);    
T 646     }
647     
648
649   /**
650    * Private method for listing a set of message headers
651    *
652    * @access  private
6d969b 653    * @see     rcube_imap::list_header_set()
4647e1 654    */
T 655   function _list_header_set($mailbox, $msgs, $page=NULL, $sort_field=NULL, $sort_order=NULL)
656     {
657     if (!strlen($mailbox) || empty($msgs))
658       return array();
659
257782 660     // also accept a comma-separated list of message ids
A 661     if (is_array ($msgs)) {
662       $max = count ($msgs);
663       $msgs = join (',', $msgs);
664     } else {
665       $max = count(split(',', $msgs));
666     } 
667
d5342a 668     $this->_set_sort_order($sort_field, $sort_order);
4647e1 669
T 670     $start_msg = ($this->list_page-1) * $this->page_size;
671
672     // fetch reuested headers from server
673     $a_msg_headers = array();
c5cc38 674     $this->_fetch_headers($mailbox, $msgs, $a_msg_headers, NULL);
4647e1 675
T 676     // return empty array if no messages found
04c618 677     if (!is_array($a_msg_headers) || empty($a_msg_headers))
T 678       return array();
4647e1 679
T 680     // if not already sorted
681     $a_msg_headers = iil_SortHeaders($a_msg_headers, $this->sort_field, $this->sort_order);
682
04c618 683     // only return the requested part of the set
T 684     return array_slice(array_values($a_msg_headers), $start_msg, min($max-$start_msg, $this->page_size));
4647e1 685     }
T 686
687
688   /**
689    * Helper function to get first and last index of the requested set
690    *
6d969b 691    * @param  int     message count
4647e1 692    * @param  mixed   page number to show, or string 'all'
T 693    * @return array   array with two values: first index, last index
694    * @access private
695    */
696   function _get_message_range($max, $page)
697     {
698     $start_msg = ($this->list_page-1) * $this->page_size;
699     
700     if ($page=='all')
701       {
702       $begin = 0;
703       $end = $max;
704       }
705     else if ($this->sort_order=='DESC')
706       {
707       $begin = $max - $this->page_size - $start_msg;
708       $end =   $max - $start_msg;
709       }
710     else
711       {
712       $begin = $start_msg;
713       $end   = $start_msg + $this->page_size;
714       }
715
716     if ($begin < 0) $begin = 0;
717     if ($end < 0) $end = $max;
718     if ($end > $max) $end = $max;
719     
720     return array($begin, $end);
721     }
722     
723     
15a9d1 724
T 725   /**
726    * Fetches message headers
727    * Used for loop
728    *
729    * @param  string  Mailbox name
4647e1 730    * @param  string  Message index to fetch
15a9d1 731    * @param  array   Reference to message headers array
T 732    * @param  array   Array with cache index
6d969b 733    * @return int     Number of deleted messages
15a9d1 734    * @access private
T 735    */
736   function _fetch_headers($mailbox, $msgs, &$a_msg_headers, $cache_key)
737     {
738     // cache is incomplete
739     $cache_index = $this->get_message_cache_index($cache_key);
4647e1 740     
15a9d1 741     // fetch reuested headers from server
T 742     $a_header_index = iil_C_FetchHeaders($this->conn, $mailbox, $msgs);
743     $deleted_count = 0;
744     
745     if (!empty($a_header_index))
746       {
747       foreach ($a_header_index as $i => $headers)
748         {
749         if ($headers->deleted && $this->skip_deleted)
750           {
751           // delete from cache
752           if ($cache_index[$headers->id] && $cache_index[$headers->id] == $headers->uid)
753             $this->remove_message_cache($cache_key, $headers->id);
754
755           $deleted_count++;
756           continue;
757           }
758
759         // add message to cache
760         if ($this->caching_enabled && $cache_index[$headers->id] != $headers->uid)
761           $this->add_message_cache($cache_key, $headers->id, $headers);
762
763         $a_msg_headers[$headers->uid] = $headers;
764         }
765       }
766         
767     return $deleted_count;
768     }
769     
e6f360 770   
8d4bcd 771   /**
T 772    * Return sorted array of message UIDs
773    *
774    * @param string Mailbox to get index from
775    * @param string Sort column
776    * @param string Sort order [ASC, DESC]
777    * @return array Indexed array with message ids
778    */
aadfa1 779   function message_index($mbox_name='', $sort_field=NULL, $sort_order=NULL)
4e17e6 780     {
d5342a 781     $this->_set_sort_order($sort_field, $sort_order);
31b2ce 782
aadfa1 783     $mailbox = $mbox_name ? $this->_mod_mailbox($mbox_name) : $this->mailbox;
df0da2 784     $key = "{$mailbox}:{$this->sort_field}:{$this->sort_order}:{$this->search_string}.msgi";
T 785
786     // we have a saved search result. get index from there
787     if (!isset($this->cache[$key]) && $this->search_string && $mailbox == $this->mailbox)
788     {
789       $this->cache[$key] = $a_msg_headers = array();
790       $this->_fetch_headers($mailbox, join(',', $this->search_set), $a_msg_headers, NULL);
791
792       foreach (iil_SortHeaders($a_msg_headers, $this->sort_field, $this->sort_order) as $i => $msg)
793         $this->cache[$key][] = $msg->uid;
794     }
4e17e6 795
31b2ce 796     // have stored it in RAM
T 797     if (isset($this->cache[$key]))
798       return $this->cache[$key];
4e17e6 799
31b2ce 800     // check local cache
T 801     $cache_key = $mailbox.'.msg';
802     $cache_status = $this->check_cache_status($mailbox, $cache_key);
4e17e6 803
31b2ce 804     // cache is OK
T 805     if ($cache_status>0)
806       {
0677ca 807       $a_index = $this->get_message_cache_index($cache_key, TRUE, $this->sort_field, $this->sort_order);
31b2ce 808       return array_values($a_index);
T 809       }
810
811
812     // fetch complete message index
813     $msg_count = $this->_messagecount($mailbox);
e6f360 814     if ($this->get_capability('sort') && ($a_index = iil_C_Sort($this->conn, $mailbox, $this->sort_field, '', TRUE)))
31b2ce 815       {
T 816       if ($this->sort_order == 'DESC')
817         $a_index = array_reverse($a_index);
818
e6f360 819       $this->cache[$key] = $a_index;
T 820
31b2ce 821       }
T 822     else
823       {
824       $a_index = iil_C_FetchHeaderIndex($this->conn, $mailbox, "1:$msg_count", $this->sort_field);
825       $a_uids = iil_C_FetchUIDs($this->conn, $mailbox);
826     
827       if ($this->sort_order=="ASC")
828         asort($a_index);
829       else if ($this->sort_order=="DESC")
830         arsort($a_index);
831         
832       $i = 0;
833       $this->cache[$key] = array();
834       foreach ($a_index as $index => $value)
835         $this->cache[$key][$i++] = $a_uids[$index];
836       }
837
838     return $this->cache[$key];
4e17e6 839     }
T 840
841
6d969b 842   /**
T 843    * @access private
844    */
1cded8 845   function sync_header_index($mailbox)
4e17e6 846     {
1cded8 847     $cache_key = $mailbox.'.msg';
T 848     $cache_index = $this->get_message_cache_index($cache_key);
849     $msg_count = $this->_messagecount($mailbox);
850
851     // fetch complete message index
852     $a_message_index = iil_C_FetchHeaderIndex($this->conn, $mailbox, "1:$msg_count", 'UID');
853         
854     foreach ($a_message_index as $id => $uid)
855       {
856       // message in cache at correct position
857       if ($cache_index[$id] == $uid)
858         {
859         unset($cache_index[$id]);
860         continue;
861         }
862         
863       // message in cache but in wrong position
864       if (in_array((string)$uid, $cache_index, TRUE))
865         {
866         unset($cache_index[$id]);        
867         }
868       
869       // other message at this position
870       if (isset($cache_index[$id]))
871         {
872         $this->remove_message_cache($cache_key, $id);
873         unset($cache_index[$id]);
874         }
875         
876
877       // fetch complete headers and add to cache
878       $headers = iil_C_FetchHeader($this->conn, $mailbox, $id);
879       $this->add_message_cache($cache_key, $headers->id, $headers);
880       }
881
882     // those ids that are still in cache_index have been deleted      
883     if (!empty($cache_index))
884       {
885       foreach ($cache_index as $id => $uid)
886         $this->remove_message_cache($cache_key, $id);
887       }
4e17e6 888     }
T 889
890
4647e1 891   /**
T 892    * Invoke search request to IMAP server
893    *
894    * @param  string  mailbox name to search in
895    * @param  string  search criteria (ALL, TO, FROM, SUBJECT, etc)
896    * @param  string  search string
897    * @return array   search results as list of message ids
898    * @access public
899    */
42000a 900   function search($mbox_name='', $criteria='ALL', $str=NULL, $charset=NULL)
4e17e6 901     {
aadfa1 902     $mailbox = $mbox_name ? $this->_mod_mailbox($mbox_name) : $this->mailbox;
04c618 903
T 904     // have an array of criterias => execute multiple searches
905     if (is_array($criteria) && $str)
906       {
907       $results = array();
908       foreach ($criteria as $crit)
e6c7c3 909         if ($search_result = $this->search($mbox_name, $crit, $str, $charset))
T 910           $results = array_merge($results, $search_result);
04c618 911       
T 912       $results = array_unique($results);
913       $this->set_search_set($criteria, $str, $results, $charset);
914       return $results;
915       }
916     else if ($str && $criteria)
4647e1 917       {
42000a 918       $search = (!empty($charset) ? "CHARSET $charset " : '') . sprintf("%s {%d}\r\n%s", $criteria, strlen($str), $str);
T 919       $results = $this->_search_index($mailbox, $search);
920
4d4264 921       // try search with ISO charset (should be supported by server)
T 922       if (empty($results) && !empty($charset) && $charset!='ISO-8859-1')
923         $results = $this->search($mbox_name, $criteria, rcube_charset_convert($str, $charset, 'ISO-8859-1'), 'ISO-8859-1');
42000a 924       
04c618 925       $this->set_search_set($criteria, $str, $results, $charset);
42000a 926       return $results;
4647e1 927       }
T 928     else
929       return $this->_search_index($mailbox, $criteria);
930     }    
931
932
933   /**
934    * Private search method
935    *
936    * @return array   search results as list of message ids
937    * @access private
938    * @see rcube_imap::search()
939    */
31b2ce 940   function _search_index($mailbox, $criteria='ALL')
T 941     {
4e17e6 942     $a_messages = iil_C_Search($this->conn, $mailbox, $criteria);
4647e1 943     // clean message list (there might be some empty entries)
4f2d81 944     if (is_array($a_messages))
T 945       {
946       foreach ($a_messages as $i => $val)
947         if (empty($val))
948           unset($a_messages[$i]);
949       }
4647e1 950         
4e17e6 951     return $a_messages;
04c618 952     }
T 953     
954   
955   /**
956    * Refresh saved search set
6d969b 957    *
T 958    * @return array Current search set
04c618 959    */
T 960   function refresh_search()
961     {
962     if (!empty($this->search_subject) && !empty($this->search_string))
963       $this->search_set = $this->search('', $this->search_subject, $this->search_string, $this->search_charset);
964       
965     return $this->get_search_set();
4e17e6 966     }
110748 967   
T 968   
969   /**
970    * Check if the given message ID is part of the current search set
971    *
ed5407 972    * @return boolean True on match or if no search request is stored
110748 973    */
T 974   function in_searchset($msgid)
975   {
976     if (!empty($this->search_string))
977       return in_array("$msgid", (array)$this->search_set, true);
978     else
979       return true;
980   }
4e17e6 981
T 982
8d4bcd 983   /**
T 984    * Return message headers object of a specific message
985    *
986    * @param int     Message ID
987    * @param string  Mailbox to read from 
988    * @param boolean True if $id is the message UID
989    * @return object Message headers representation
990    */
aadfa1 991   function get_headers($id, $mbox_name=NULL, $is_uid=TRUE)
4e17e6 992     {
aadfa1 993     $mailbox = $mbox_name ? $this->_mod_mailbox($mbox_name) : $this->mailbox;
8d4bcd 994     $uid = $is_uid ? $id : $this->_id2uid($id);
1cded8 995
4e17e6 996     // get cached headers
f7bfec 997     if ($uid && ($headers = &$this->get_cached_message($mailbox.'.msg', $uid)))
1cded8 998       return $headers;
520c36 999
f7bfec 1000     $headers = iil_C_FetchHeader($this->conn, $mailbox, $id, $is_uid);
520c36 1001
4e17e6 1002     // write headers cache
1cded8 1003     if ($headers)
f7bfec 1004       {
017def 1005       if ($headers->uid && $headers->id)
T 1006         $this->uid_id_map[$mailbox][$headers->uid] = $headers->id;
f7bfec 1007
T 1008       $this->add_message_cache($mailbox.'.msg', $headers->id, $headers);
1009       }
4e17e6 1010
1cded8 1011     return $headers;
4e17e6 1012     }
T 1013
1014
8d4bcd 1015   /**
T 1016    * Fetch body structure from the IMAP server and build
1017    * an object structure similar to the one generated by PEAR::Mail_mimeDecode
1018    *
6d969b 1019    * @param int Message UID to fetch
e93e54 1020    * @return object rcube_message_part Message part tree or False on failure
8d4bcd 1021    */
T 1022   function &get_structure($uid)
4e17e6 1023     {
f7bfec 1024     $cache_key = $this->mailbox.'.msg';
T 1025     $headers = &$this->get_cached_message($cache_key, $uid, true);
1026
1027     // return cached message structure
1028     if (is_object($headers) && is_object($headers->structure))
1029       return $headers->structure;
1030     
1031     // resolve message sequence number
4e17e6 1032     if (!($msg_id = $this->_uid2id($uid)))
T 1033       return FALSE;
1034
5cc4b1 1035     $structure_str = iil_C_FetchStructureString($this->conn, $this->mailbox, $msg_id); 
T 1036     $structure = iml_GetRawStructureArray($structure_str);
1037     $struct = false;
1038
8d4bcd 1039     // parse structure and add headers
T 1040     if (!empty($structure))
1041       {
1042       $this->_msg_id = $msg_id;
017def 1043       $headers = $this->get_headers($uid);
8d4bcd 1044       
T 1045       $struct = &$this->_structure_part($structure);
1046       $struct->headers = get_object_vars($headers);
58afbe 1047
8d4bcd 1048       // don't trust given content-type
58afbe 1049       if (empty($struct->parts) && !empty($struct->headers['ctype']))
8d4bcd 1050         {
T 1051         $struct->mime_id = '1';
1052         $struct->mimetype = strtolower($struct->headers['ctype']);
1053         list($struct->ctype_primary, $struct->ctype_secondary) = explode('/', $struct->mimetype);
1054         }
f7bfec 1055
T 1056       // write structure to cache
1057       if ($this->caching_enabled)
1058         $this->add_message_cache($cache_key, $msg_id, $headers, $struct);
8d4bcd 1059       }
94a99c 1060
5cc4b1 1061     return $struct;
T 1062     }
4e17e6 1063
8d4bcd 1064   
T 1065   /**
1066    * Build message part object
1067    *
1068    * @access private
1069    */
1070   function &_structure_part($part, $count=0, $parent='')
1071     {
1072     $struct = new rcube_message_part;
1073     $struct->mime_id = empty($parent) ? (string)$count : "$parent.$count";
4e17e6 1074     
8d4bcd 1075     // multipart
T 1076     if (is_array($part[0]))
1077       {
1078       $struct->ctype_primary = 'multipart';
1079       
1080       // find first non-array entry
cfe4a6 1081       for ($i=1; $i<count($part); $i++)
8d4bcd 1082         if (!is_array($part[$i]))
T 1083           {
1084           $struct->ctype_secondary = strtolower($part[$i]);
1085           break;
1086           }
1087           
1088       $struct->mimetype = 'multipart/'.$struct->ctype_secondary;
1089
1090       $struct->parts = array();
1091       for ($i=0, $count=0; $i<count($part); $i++)
cfe4a6 1092         if (is_array($part[$i]) && count($part[$i]) > 3)
8d4bcd 1093           $struct->parts[] = $this->_structure_part($part[$i], ++$count, $struct->mime_id);
5cc4b1 1094           
T 1095       return $struct;
8d4bcd 1096       }
T 1097     
1098     
1099     // regular part
1100     $struct->ctype_primary = strtolower($part[0]);
1101     $struct->ctype_secondary = strtolower($part[1]);
1102     $struct->mimetype = $struct->ctype_primary.'/'.$struct->ctype_secondary;
5cc4b1 1103
8d4bcd 1104     // read content type parameters
5cc4b1 1105     if (is_array($part[2]))
T 1106       {
1107       $struct->ctype_parameters = array();
8d4bcd 1108       for ($i=0; $i<count($part[2]); $i+=2)
T 1109         $struct->ctype_parameters[strtolower($part[2][$i])] = $part[2][$i+1];
1110         
1111       if (isset($struct->ctype_parameters['charset']))
1112         $struct->charset = $struct->ctype_parameters['charset'];
5cc4b1 1113       }
T 1114     
1115     // read content encoding
1116     if (!empty($part[5]) && $part[5]!='NIL')
1117       {
1118       $struct->encoding = strtolower($part[5]);
1119       $struct->headers['content-transfer-encoding'] = $struct->encoding;
1120       }
1121     
1122     // get part size
1123     if (!empty($part[6]) && $part[6]!='NIL')
1124       $struct->size = intval($part[6]);
2f2f15 1125
5cc4b1 1126     // read part disposition
ea206d 1127     $di = count($part) - 2;
2f2f15 1128     if ((is_array($part[$di]) && count($part[$di]) == 2 && is_array($part[$di][1])) ||
T 1129         (is_array($part[--$di]) && count($part[$di]) == 2))
8d4bcd 1130       {
T 1131       $struct->disposition = strtolower($part[$di][0]);
1132
1133       if (is_array($part[$di][1]))
1134         for ($n=0; $n<count($part[$di][1]); $n+=2)
1135           $struct->d_parameters[strtolower($part[$di][1][$n])] = $part[$di][1][$n+1];
1136       }
1137       
1138     // get child parts
1139     if (is_array($part[8]) && $di != 8)
1140       {
1141       $struct->parts = array();
1142       for ($i=0, $count=0; $i<count($part[8]); $i++)
1143         if (is_array($part[8][$i]) && count($part[8][$i]) > 5)
1144           $struct->parts[] = $this->_structure_part($part[8][$i], ++$count, $struct->mime_id);
1145       }
5cc4b1 1146
T 1147     // get part ID
1148     if (!empty($part[3]) && $part[3]!='NIL')
1149       {
1150       $struct->content_id = $part[3];
1151       $struct->headers['content-id'] = $part[3];
1152     
1153       if (empty($struct->disposition))
1154         $struct->disposition = 'inline';
1155       }
c505e5 1156     
T 1157     // fetch message headers if message/rfc822 or named part (could contain Content-Location header)
1158     if ($struct->ctype_primary == 'message' || ($struct->ctype_parameters['name'] && !$struct->content_id)) {
1159       $part_headers = iil_C_FetchPartHeader($this->conn, $this->mailbox, $this->_msg_id, $struct->mime_id);
1160       $struct->headers = $this->_parse_headers($part_headers) + $struct->headers;
1161     }
8d4bcd 1162
c505e5 1163     if ($struct->ctype_primary=='message') {
5cc4b1 1164       if (is_array($part[8]) && empty($struct->parts))
T 1165         $struct->parts[] = $this->_structure_part($part[8], ++$count, $struct->mime_id);
c505e5 1166     }
b54121 1167
5cc4b1 1168     // normalize filename property
5df0ad 1169     $this->_set_part_filename($struct);
A 1170
5cc4b1 1171     return $struct;
8d4bcd 1172     }
T 1173     
5df0ad 1174
A 1175   /**
97e9d1 1176    * Set attachment filename from message part structure 
5df0ad 1177    *
A 1178    * @access private
1179    * @param  object rcube_message_part Part object
1180    */
1181   function _set_part_filename(&$part)
1182     {
1183     if (!empty($part->d_parameters['filename']))
1184       $filename_mime = $part->d_parameters['filename'];
1185     else if (!empty($part->d_parameters['filename*']))
1186       $filename_encoded = $part->d_parameters['filename*'];
1187     else if (!empty($part->ctype_parameters['name*']))
1188       $filename_encoded = $part->ctype_parameters['name*'];
1189     // RFC2231 value continuations
1190     // TODO: this should be rewrited to support RFC2231 4.1 combinations
1191     else if (!empty($part->d_parameters['filename*0'])) {
1192       $i = 0;
1193       while (isset($part->d_parameters['filename*'.$i])) {
1194         $i++;
1195         $filename_mime .= $part->d_parameters['filename*'.$i];
1196     }
1197       // some servers (eg. dovecot-1.x) have no support for parameter value continuations
1198       // we must fetch and parse headers "manually"
20a251 1199       //TODO: fetching headers for a second time is not effecient, this code should be moved somewhere earlier --tensor
5df0ad 1200       if ($i<2) {
A 1201         // TODO: fetch only Content-Type/Content-Disposition header
20a251 1202         $headers = iil_C_FetchPartHeader($this->conn, $this->mailbox, $this->_msg_id, $part->mime_id);
42e328 1203         $filename_mime = '';
T 1204         $i = 0;
1205         while (preg_match('/filename\*'.$i.'\s*=\s*"*([^"\n;]+)[";]*/', $headers, $matches)) {
1206           $filename_mime .= $matches[1];
1207           $i++;
1208         }
5df0ad 1209       }
42e328 1210     }
5df0ad 1211     else if (!empty($part->d_parameters['filename*0*'])) {
A 1212       $i = 0;
1213       while (isset($part->d_parameters['filename*'.$i.'*'])) {
1214         $i++;
42e328 1215         $filename_encoded .= $part->d_parameters['filename*'.$i.'*'];
T 1216       }
5df0ad 1217       if ($i<2) {
20a251 1218         $headers = iil_C_FetchPartHeader($this->conn, $this->mailbox, $this->_msg_id, $part->mime_id);
42e328 1219         $filename_encoded = '';
T 1220         $i = 0; $matches = array();
1221         while (preg_match('/filename\*'.$i.'\*\s*=\s*"*([^"\n;]+)[";]*/', $headers, $matches)) {
1222           $filename_encoded .= $matches[1];
1223           $i++;
1224         }
5df0ad 1225       }
42e328 1226     }
5df0ad 1227     else if (!empty($part->ctype_parameters['name*0'])) {
A 1228       $i = 0;
1229       while (isset($part->ctype_parameters['name*'.$i])) {
1230         $i++;
1231         $filename_mime .= $part->ctype_parameters['name*'.$i];
42e328 1232       }
5df0ad 1233       if ($i<2) {
20a251 1234         $headers = iil_C_FetchPartHeader($this->conn, $this->mailbox, $this->_msg_id, $part->mime_id);
42e328 1235         $filename_mime = '';
T 1236         $i = 0; $matches = array();
1237         while (preg_match('/\s+name\*'.$i.'\s*=\s*"*([^"\n;]+)[";]*/', $headers, $matches)) {
1238           $filename_mime .= $matches[1];
1239           $i++;
1240         }
5df0ad 1241       }
42e328 1242     }
5df0ad 1243     else if (!empty($part->ctype_parameters['name*0*'])) {
A 1244       $i = 0;
1245       while (isset($part->ctype_parameters['name*'.$i.'*'])) {
1246         $i++;
1247         $filename_encoded .= $part->ctype_parameters['name*'.$i.'*'];
42e328 1248       }
5df0ad 1249       if ($i<2) {
20a251 1250         $headers = iil_C_FetchPartHeader($this->conn, $this->mailbox, $this->_msg_id, $part->mime_id);
42e328 1251         $filename_encoded = '';
T 1252         $i = 0; $matches = array();
1253         while (preg_match('/\s+name\*'.$i.'\*\s*=\s*"*([^"\n;]+)[";]*/', $headers, $matches)) {
1254           $filename_encoded .= $matches[1];
1255           $i++;
1256         }
5df0ad 1257       }
42e328 1258     }
5b4562 1259     // read 'name' after rfc2231 parameters as it may contains truncated filename (from Thunderbird)
A 1260     else if (!empty($part->ctype_parameters['name']))
1261       $filename_mime = $part->ctype_parameters['name'];
5df0ad 1262     // Content-Disposition
A 1263     else if (!empty($part->headers['content-description']))
1264       $filename_mime = $part->headers['content-description'];
1265     else
1266       return;
1267
1268     // decode filename
1269     if (!empty($filename_mime)) {
1270       $part->filename = rcube_imap::decode_mime_string($filename_mime, 
42e328 1271         $part->charset ? $part->charset : rc_detect_encoding($filename_mime, $this->default_charset));
5df0ad 1272       } 
A 1273     else if (!empty($filename_encoded)) {
1274       // decode filename according to RFC 2231, Section 4
94a99c 1275       if (preg_match("/^([^']*)'[^']*'(.*)$/", $filename_encoded, $fmatches)) {
A 1276         $filename_charset = $fmatches[1];
1277         $filename_encoded = $fmatches[2];
1278         }
1279       $part->filename = rcube_charset_convert(urldecode($filename_encoded), $filename_charset);
5df0ad 1280       }
A 1281     }
1282      
8d4bcd 1283   
T 1284   /**
1285    * Fetch message body of a specific message from the server
1286    *
1287    * @param  int    Message UID
1288    * @param  string Part number
6d969b 1289    * @param  object rcube_message_part Part object created by get_structure()
8d4bcd 1290    * @param  mixed  True to print part, ressource to write part contents in
81b573 1291    * @param  resource File pointer to save the message part
6d969b 1292    * @return string Message/part body if not printed
8d4bcd 1293    */
81b573 1294   function &get_message_part($uid, $part=1, $o_part=NULL, $print=NULL, $fp=NULL)
8d4bcd 1295     {
T 1296     if (!($msg_id = $this->_uid2id($uid)))
1297       return FALSE;
1298     
1299     // get part encoding if not provided
1300     if (!is_object($o_part))
1301       {
1302       $structure_str = iil_C_FetchStructureString($this->conn, $this->mailbox, $msg_id); 
1303       $structure = iml_GetRawStructureArray($structure_str);
1304       $part_type = iml_GetPartTypeCode($structure, $part);
1305       $o_part = new rcube_message_part;
1306       $o_part->ctype_primary = $part_type==0 ? 'text' : ($part_type==2 ? 'message' : 'other');
1307       $o_part->encoding = strtolower(iml_GetPartEncodingString($structure, $part));
1308       $o_part->charset = iml_GetPartCharset($structure, $part);
1309       }
1310       
1311     // TODO: Add caching for message parts
1312
1313     if ($print)
1314       {
a9cc52 1315       $mode = $o_part->encoding == 'base64' ? 3 : ($o_part->encoding == 'quoted-printable' ? 1 : 2);
T 1316       $body = iil_C_HandlePartBody($this->conn, $this->mailbox, $msg_id, $part, $mode);
1317       
1318       // we have to decode the part manually before printing
1319       if ($mode == 1)
1320         {
1321         echo $this->mime_decode($body, $o_part->encoding);
1322         $body = true;
1323         }
8d4bcd 1324       }
T 1325     else
1326       {
81b573 1327       if ($fp && $o_part->encoding == 'base64')
A 1328         return iil_C_HandlePartBody($this->conn, $this->mailbox, $msg_id, $part, 3, $fp);
1329       else
1330         $body = iil_C_HandlePartBody($this->conn, $this->mailbox, $msg_id, $part, 1);
8d4bcd 1331
T 1332       // decode part body
a9cc52 1333       if ($o_part->encoding)
8d4bcd 1334         $body = $this->mime_decode($body, $o_part->encoding);
T 1335
1336       // convert charset (if text or message part)
f7bfec 1337       if ($o_part->ctype_primary=='text' || $o_part->ctype_primary=='message')
T 1338         {
17b5fb 1339         // assume default if no charset specified
f7bfec 1340         if (empty($o_part->charset))
17b5fb 1341           $o_part->charset = $this->default_charset;
f7bfec 1342
8d4bcd 1343         $body = rcube_charset_convert($body, $o_part->charset);
f7bfec 1344         }
81b573 1345       
A 1346       if ($fp)
1347         {
1348         fwrite($fp, $body);
42e328 1349         return true;
81b573 1350         }
8d4bcd 1351       }
81b573 1352     
4e17e6 1353     return $body;
T 1354     }
1355
1356
8d4bcd 1357   /**
T 1358    * Fetch message body of a specific message from the server
1359    *
1360    * @param  int    Message UID
6d969b 1361    * @return string Message/part body
T 1362    * @see    rcube_imap::get_message_part()
8d4bcd 1363    */
T 1364   function &get_body($uid, $part=1)
1365     {
0a9989 1366     $headers = $this->get_headers($uid);
T 1367     return rcube_charset_convert(
1368       $this->mime_decode($this->get_message_part($uid, $part), 'quoted-printable'),
1369       $headers->charset ? $headers->charset : $this->default_charset);
8d4bcd 1370     }
T 1371
1372
1373   /**
1374    * Returns the whole message source as string
1375    *
1376    * @param int  Message UID
6d969b 1377    * @return string Message source string
8d4bcd 1378    */
T 1379   function &get_raw_body($uid)
4e17e6 1380     {
T 1381     if (!($msg_id = $this->_uid2id($uid)))
1382       return FALSE;
1383
6d969b 1384     $body = iil_C_FetchPartHeader($this->conn, $this->mailbox, $msg_id, NULL);
T 1385     $body .= iil_C_HandlePartBody($this->conn, $this->mailbox, $msg_id, NULL, 1);
4e17e6 1386
T 1387     return $body;    
1388     }
e5686f 1389
A 1390
1391   /**
1392    * Returns the message headers as string
1393    *
1394    * @param int  Message UID
1395    * @return string Message headers string
1396    */
1397   function &get_raw_headers($uid)
1398     {
1399     if (!($msg_id = $this->_uid2id($uid)))
1400       return FALSE;
1401
1402     $headers = iil_C_FetchPartHeader($this->conn, $this->mailbox, $msg_id, NULL);
1403
1404     return $headers;    
1405     }
8d4bcd 1406     
T 1407
1408   /**
1409    * Sends the whole message source to stdout
1410    *
1411    * @param int  Message UID
1412    */ 
1413   function print_raw_body($uid)
1414     {
1415     if (!($msg_id = $this->_uid2id($uid)))
1416       return FALSE;
1417
6d969b 1418     print iil_C_FetchPartHeader($this->conn, $this->mailbox, $msg_id, NULL);
T 1419     flush();
1420     iil_C_HandlePartBody($this->conn, $this->mailbox, $msg_id, NULL, 2);
8d4bcd 1421     }
4e17e6 1422
T 1423
8d4bcd 1424   /**
T 1425    * Set message flag to one or several messages
1426    *
1427    * @param mixed  Message UIDs as array or as comma-separated string
ed5407 1428    * @param string Flag to set: SEEN, UNDELETED, DELETED, RECENT, ANSWERED, DRAFT, MDNSENT
6d969b 1429    * @return boolean True on success, False on failure
8d4bcd 1430    */
4e17e6 1431   function set_flag($uids, $flag)
T 1432     {
1433     $flag = strtoupper($flag);
1434     $msg_ids = array();
1435     if (!is_array($uids))
8fae1e 1436       $uids = explode(',',$uids);
4e17e6 1437       
8fae1e 1438     foreach ($uids as $uid) {
31b2ce 1439       $msg_ids[$uid] = $this->_uid2id($uid);
8fae1e 1440     }
4e17e6 1441       
8fae1e 1442     if ($flag=='UNDELETED')
S 1443       $result = iil_C_Undelete($this->conn, $this->mailbox, join(',', array_values($msg_ids)));
1444     else if ($flag=='UNSEEN')
31b2ce 1445       $result = iil_C_Unseen($this->conn, $this->mailbox, join(',', array_values($msg_ids)));
e189a6 1446     else if ($flag=='UNFLAGGED')
A 1447       $result = iil_C_UnFlag($this->conn, $this->mailbox, join(',', array_values($msg_ids)), 'FLAGGED');
4e17e6 1448     else
31b2ce 1449       $result = iil_C_Flag($this->conn, $this->mailbox, join(',', array_values($msg_ids)), $flag);
4e17e6 1450
T 1451     // reload message headers if cached
1452     $cache_key = $this->mailbox.'.msg';
1cded8 1453     if ($this->caching_enabled)
4e17e6 1454       {
31b2ce 1455       foreach ($msg_ids as $uid => $id)
4e17e6 1456         {
31b2ce 1457         if ($cached_headers = $this->get_cached_message($cache_key, $uid))
4e17e6 1458           {
1cded8 1459           $this->remove_message_cache($cache_key, $id);
T 1460           //$this->get_headers($uid);
4e17e6 1461           }
T 1462         }
1cded8 1463
T 1464       // close and re-open connection
1465       // this prevents connection problems with Courier 
1466       $this->reconnect();
4e17e6 1467       }
T 1468
1469     // set nr of messages that were flaged
31b2ce 1470     $count = count($msg_ids);
4e17e6 1471
T 1472     // clear message count cache
1473     if ($result && $flag=='SEEN')
1474       $this->_set_messagecount($this->mailbox, 'UNSEEN', $count*(-1));
1475     else if ($result && $flag=='UNSEEN')
1476       $this->_set_messagecount($this->mailbox, 'UNSEEN', $count);
1477     else if ($result && $flag=='DELETED')
1478       $this->_set_messagecount($this->mailbox, 'ALL', $count*(-1));
1479
1480     return $result;
1481     }
1482
1483
6d969b 1484   /**
T 1485    * Append a mail message (source) to a specific mailbox
1486    *
1487    * @param string Target mailbox
1488    * @param string Message source
1489    * @return boolean True on success, False on error
1490    */
b068a0 1491   function save_message($mbox_name, &$message)
4e17e6 1492     {
a894ba 1493     $mbox_name = stripslashes($mbox_name);
aadfa1 1494     $mailbox = $this->_mod_mailbox($mbox_name);
4e17e6 1495
f88d41 1496     // make sure mailbox exists
47c9cc 1497     if (($mailbox == 'INBOX') || in_array($mailbox, $this->_list_mailboxes()))
4e17e6 1498       $saved = iil_C_Append($this->conn, $mailbox, $message);
1cded8 1499
4e17e6 1500     if ($saved)
T 1501       {
1502       // increase messagecount of the target mailbox
1503       $this->_set_messagecount($mailbox, 'ALL', 1);
1504       }
1505           
1506     return $saved;
1507     }
1508
1509
6d969b 1510   /**
T 1511    * Move a message from one mailbox to another
1512    *
1513    * @param string List of UIDs to move, separated by comma
1514    * @param string Target mailbox
1515    * @param string Source mailbox
1516    * @return boolean True on success, False on error
1517    */
4e17e6 1518   function move_message($uids, $to_mbox, $from_mbox='')
T 1519     {
a05793 1520     $to_mbox_in = stripslashes($to_mbox);
a894ba 1521     $from_mbox = stripslashes($from_mbox);
a05793 1522     $to_mbox = $this->_mod_mailbox($to_mbox_in);
4e17e6 1523     $from_mbox = $from_mbox ? $this->_mod_mailbox($from_mbox) : $this->mailbox;
T 1524
f88d41 1525     // make sure mailbox exists
4e17e6 1526     if (!in_array($to_mbox, $this->_list_mailboxes()))
f88d41 1527       {
a05793 1528       if (in_array($to_mbox_in, $this->default_folders))
T 1529         $this->create_mailbox($to_mbox_in, TRUE);
f88d41 1530       else
T 1531         return FALSE;
1532       }
1533
4e17e6 1534     // convert the list of uids to array
T 1535     $a_uids = is_string($uids) ? explode(',', $uids) : (is_array($uids) ? $uids : NULL);
1536     
1537     // exit if no message uids are specified
1538     if (!is_array($a_uids))
1539       return false;
520c36 1540
4e17e6 1541     // convert uids to message ids
T 1542     $a_mids = array();
1543     foreach ($a_uids as $uid)
1544       $a_mids[] = $this->_uid2id($uid, $from_mbox);
520c36 1545
4379bb 1546     $iil_move = iil_C_Move($this->conn, join(',', $a_mids), $from_mbox, $to_mbox);
T 1547     $moved = !($iil_move === false || $iil_move < 0);
4e17e6 1548     
T 1549     // send expunge command in order to have the moved message
1550     // really deleted from the source mailbox
bf0cb9 1551     if ($moved) {
d87fc2 1552       // but only when flag_for_deletion is set to false
A 1553       if (!rcmail::get_instance()->config->get('flag_for_deletion', false))
1554         {
1555         $this->_expunge($from_mbox, FALSE);
1556         $this->_clear_messagecount($from_mbox);
1557         $this->_clear_messagecount($to_mbox);
1558         }
bf0cb9 1559     }
T 1560     // moving failed
1561     else if (rcmail::get_instance()->config->get('delete_always', false)) {
1562       return iil_C_Delete($this->conn, $from_mbox, join(',', $a_mids));
1563     }
04c618 1564       
T 1565     // remove message ids from search set
1566     if ($moved && $this->search_set && $from_mbox == $this->mailbox)
1567       $this->search_set = array_diff($this->search_set, $a_mids);
4e17e6 1568
T 1569     // update cached message headers
1570     $cache_key = $from_mbox.'.msg';
1cded8 1571     if ($moved && ($a_cache_index = $this->get_message_cache_index($cache_key)))
4e17e6 1572       {
1cded8 1573       $start_index = 100000;
4e17e6 1574       foreach ($a_uids as $uid)
1cded8 1575         {
04c618 1576         if (($index = array_search($uid, $a_cache_index)) !== FALSE)
T 1577           $start_index = min($index, $start_index);
1cded8 1578         }
4e17e6 1579
1cded8 1580       // clear cache from the lowest index on
T 1581       $this->clear_message_cache($cache_key, $start_index);
4e17e6 1582       }
T 1583
1584     return $moved;
1585     }
1586
1587
6d969b 1588   /**
T 1589    * Mark messages as deleted and expunge mailbox
1590    *
1591    * @param string List of UIDs to move, separated by comma
1592    * @param string Source mailbox
1593    * @return boolean True on success, False on error
1594    */
aadfa1 1595   function delete_message($uids, $mbox_name='')
4e17e6 1596     {
a894ba 1597     $mbox_name = stripslashes($mbox_name);
aadfa1 1598     $mailbox = $mbox_name ? $this->_mod_mailbox($mbox_name) : $this->mailbox;
4e17e6 1599
T 1600     // convert the list of uids to array
1601     $a_uids = is_string($uids) ? explode(',', $uids) : (is_array($uids) ? $uids : NULL);
1602     
1603     // exit if no message uids are specified
1604     if (!is_array($a_uids))
1605       return false;
1606
1607     // convert uids to message ids
1608     $a_mids = array();
1609     foreach ($a_uids as $uid)
1610       $a_mids[] = $this->_uid2id($uid, $mailbox);
1611         
1612     $deleted = iil_C_Delete($this->conn, $mailbox, join(',', $a_mids));
1613     
1614     // send expunge command in order to have the deleted message
1615     // really deleted from the mailbox
1616     if ($deleted)
1617       {
1cded8 1618       $this->_expunge($mailbox, FALSE);
4e17e6 1619       $this->_clear_messagecount($mailbox);
c719f3 1620       unset($this->uid_id_map[$mailbox]);
4e17e6 1621       }
T 1622
04c618 1623     // remove message ids from search set
077070 1624     if ($deleted && $this->search_set && $mailbox == $this->mailbox)
04c618 1625       $this->search_set = array_diff($this->search_set, $a_mids);
T 1626
4e17e6 1627     // remove deleted messages from cache
1cded8 1628     $cache_key = $mailbox.'.msg';
T 1629     if ($deleted && ($a_cache_index = $this->get_message_cache_index($cache_key)))
4e17e6 1630       {
1cded8 1631       $start_index = 100000;
4e17e6 1632       foreach ($a_uids as $uid)
1cded8 1633         {
6ce04b 1634         if (($index = array_search($uid, $a_cache_index)) !== FALSE)
S 1635           $start_index = min($index, $start_index);
1cded8 1636         }
4e17e6 1637
1cded8 1638       // clear cache from the lowest index on
T 1639       $this->clear_message_cache($cache_key, $start_index);
4e17e6 1640       }
T 1641
1642     return $deleted;
1643     }
1644
1645
6d969b 1646   /**
T 1647    * Clear all messages in a specific mailbox
1648    *
1649    * @param string Mailbox name
1650    * @return int Above 0 on success
1651    */
aadfa1 1652   function clear_mailbox($mbox_name=NULL)
a95e0e 1653     {
a894ba 1654     $mbox_name = stripslashes($mbox_name);
aadfa1 1655     $mailbox = !empty($mbox_name) ? $this->_mod_mailbox($mbox_name) : $this->mailbox;
a95e0e 1656     $msg_count = $this->_messagecount($mailbox, 'ALL');
T 1657     
1658     if ($msg_count>0)
1cded8 1659       {
5e3512 1660       $cleared = iil_C_ClearFolder($this->conn, $mailbox);
T 1661       
1662       // make sure the message count cache is cleared as well
1663       if ($cleared)
1664         {
1665         $this->clear_message_cache($mailbox.'.msg');      
1666         $a_mailbox_cache = $this->get_cache('messagecount');
1667         unset($a_mailbox_cache[$mailbox]);
1668         $this->update_cache('messagecount', $a_mailbox_cache);
1669         }
1670         
1671       return $cleared;
1cded8 1672       }
a95e0e 1673     else
T 1674       return 0;
1675     }
1676
1677
6d969b 1678   /**
T 1679    * Send IMAP expunge command and clear cache
1680    *
1681    * @param string Mailbox name
1682    * @param boolean False if cache should not be cleared
1683    * @return boolean True on success
1684    */
aadfa1 1685   function expunge($mbox_name='', $clear_cache=TRUE)
4e17e6 1686     {
a894ba 1687     $mbox_name = stripslashes($mbox_name);
aadfa1 1688     $mailbox = $mbox_name ? $this->_mod_mailbox($mbox_name) : $this->mailbox;
1cded8 1689     return $this->_expunge($mailbox, $clear_cache);
T 1690     }
1691
1692
6d969b 1693   /**
T 1694    * Send IMAP expunge command and clear cache
1695    *
1696    * @see rcube_imap::expunge()
1697    * @access private
1698    */
1cded8 1699   function _expunge($mailbox, $clear_cache=TRUE)
T 1700     {
4e17e6 1701     $result = iil_C_Expunge($this->conn, $mailbox);
T 1702
1703     if ($result>=0 && $clear_cache)
1704       {
5c69aa 1705       $this->clear_message_cache($mailbox.'.msg');
4e17e6 1706       $this->_clear_messagecount($mailbox);
T 1707       }
1708       
1709     return $result;
1710     }
1711
1712
1713   /* --------------------------------
1714    *        folder managment
1715    * --------------------------------*/
1716
1717
fa4cd2 1718   /**
T 1719    * Get a list of all folders available on the IMAP server
1720    * 
1721    * @param string IMAP root dir
6d969b 1722    * @return array Indexed array with folder names
fa4cd2 1723    */
4e17e6 1724   function list_unsubscribed($root='')
T 1725     {
1726     static $sa_unsubscribed;
1727     
1728     if (is_array($sa_unsubscribed))
1729       return $sa_unsubscribed;
1730       
1731     // retrieve list of folders from IMAP server
1732     $a_mboxes = iil_C_ListMailboxes($this->conn, $this->_mod_mailbox($root), '*');
1733
1734     // modify names with root dir
aadfa1 1735     foreach ($a_mboxes as $mbox_name)
4e17e6 1736       {
aadfa1 1737       $name = $this->_mod_mailbox($mbox_name, 'out');
4e17e6 1738       if (strlen($name))
T 1739         $a_folders[] = $name;
1740       }
1741
1742     // filter folders and sort them
1743     $sa_unsubscribed = $this->_sort_mailbox_list($a_folders);
1744     return $sa_unsubscribed;
1745     }
1746
1747
58e360 1748   /**
6d969b 1749    * Get mailbox quota information
58e360 1750    * added by Nuny
6d969b 1751    * 
T 1752    * @return mixed Quota info or False if not supported
58e360 1753    */
T 1754   function get_quota()
1755     {
1756     if ($this->get_capability('QUOTA'))
fda695 1757       return iil_C_GetQuota($this->conn);
3ea0e3 1758     
4647e1 1759     return FALSE;
58e360 1760     }
T 1761
1762
fa4cd2 1763   /**
6d969b 1764    * Subscribe to a specific mailbox(es)
T 1765    *
c5097c 1766    * @param array Mailbox name(s)
6d969b 1767    * @return boolean True on success
fa4cd2 1768    */ 
c5097c 1769   function subscribe($a_mboxes)
4e17e6 1770     {
c5097c 1771     if (!is_array($a_mboxes))
A 1772       $a_mboxes = array($a_mboxes);
1773
4e17e6 1774     // let this common function do the main work
T 1775     return $this->_change_subscription($a_mboxes, 'subscribe');
1776     }
1777
1778
fa4cd2 1779   /**
6d969b 1780    * Unsubscribe mailboxes
T 1781    *
c5097c 1782    * @param array Mailbox name(s)
6d969b 1783    * @return boolean True on success
fa4cd2 1784    */
c5097c 1785   function unsubscribe($a_mboxes)
4e17e6 1786     {
c5097c 1787     if (!is_array($a_mboxes))
A 1788       $a_mboxes = array($a_mboxes);
4e17e6 1789
T 1790     // let this common function do the main work
1791     return $this->_change_subscription($a_mboxes, 'unsubscribe');
1792     }
1793
1794
fa4cd2 1795   /**
4d4264 1796    * Create a new mailbox on the server and register it in local cache
T 1797    *
1798    * @param string  New mailbox name (as utf-7 string)
1799    * @param boolean True if the new mailbox should be subscribed
1800    * @param string  Name of the created mailbox, false on error
fa4cd2 1801    */
4e17e6 1802   function create_mailbox($name, $subscribe=FALSE)
T 1803     {
1804     $result = FALSE;
1cded8 1805     
T 1806     // replace backslashes
1807     $name = preg_replace('/[\\\]+/', '-', $name);
1808
1809     // reduce mailbox name to 100 chars
4d4264 1810     $name = substr($name, 0, 100);
1cded8 1811
4d4264 1812     $abs_name = $this->_mod_mailbox($name);
4e17e6 1813     $a_mailbox_cache = $this->get_cache('mailboxes');
fa4cd2 1814
719a25 1815     if (strlen($abs_name) && (!is_array($a_mailbox_cache) || !in_array($abs_name, $a_mailbox_cache)))
a95e0e 1816       $result = iil_C_CreateFolder($this->conn, $abs_name);
4e17e6 1817
fa4cd2 1818     // try to subscribe it
719a25 1819     if ($result && $subscribe)
4d4264 1820       $this->subscribe($name);
4e17e6 1821
7902df 1822     return $result ? $name : FALSE;
4e17e6 1823     }
T 1824
1825
fa4cd2 1826   /**
4d4264 1827    * Set a new name to an existing mailbox
T 1828    *
1829    * @param string Mailbox to rename (as utf-7 string)
1830    * @param string New mailbox name (as utf-7 string)
6d969b 1831    * @return string Name of the renames mailbox, False on error
fa4cd2 1832    */
f9c107 1833   function rename_mailbox($mbox_name, $new_name)
4e17e6 1834     {
c8c1e0 1835     $result = FALSE;
S 1836
1837     // replace backslashes
1838     $name = preg_replace('/[\\\]+/', '-', $new_name);
f9c107 1839         
T 1840     // encode mailbox name and reduce it to 100 chars
4d4264 1841     $name = substr($new_name, 0, 100);
c8c1e0 1842
f9c107 1843     // make absolute path
T 1844     $mailbox = $this->_mod_mailbox($mbox_name);
4d4264 1845     $abs_name = $this->_mod_mailbox($name);
f7bfec 1846     
T 1847     // check if mailbox is subscribed
1848     $a_subscribed = $this->_list_mailboxes();
1849     $subscribed = in_array($mailbox, $a_subscribed);
1850     
1851     // unsubscribe folder
1852     if ($subscribed)
1853       iil_C_UnSubscribe($this->conn, $mailbox);
4d4264 1854
f9c107 1855     if (strlen($abs_name))
T 1856       $result = iil_C_RenameFolder($this->conn, $mailbox, $abs_name);
4d4264 1857
f9c107 1858     if ($result)
T 1859       {
574564 1860       $delm = $this->get_hierarchy_delimiter();
T 1861       
1862       // check if mailbox children are subscribed
1863       foreach ($a_subscribed as $c_subscribed)
1864         if (preg_match('/^'.preg_quote($mailbox.$delm, '/').'/', $c_subscribed))
1865           {
1866           iil_C_UnSubscribe($this->conn, $c_subscribed);
1867           iil_C_Subscribe($this->conn, preg_replace('/^'.preg_quote($mailbox, '/').'/', $abs_name, $c_subscribed));
1868           }
1869
1870       // clear cache
f9c107 1871       $this->clear_message_cache($mailbox.'.msg');
f7bfec 1872       $this->clear_cache('mailboxes');      
f9c107 1873       }
f7bfec 1874
4d4264 1875     // try to subscribe it
f7bfec 1876     if ($result && $subscribed)
T 1877       iil_C_Subscribe($this->conn, $abs_name);
c8c1e0 1878
S 1879     return $result ? $name : FALSE;
4e17e6 1880     }
T 1881
1882
fa4cd2 1883   /**
6d969b 1884    * Remove mailboxes from server
T 1885    *
1886    * @param string Mailbox name
1887    * @return boolean True on success
fa4cd2 1888    */
aadfa1 1889   function delete_mailbox($mbox_name)
4e17e6 1890     {
T 1891     $deleted = FALSE;
1892
aadfa1 1893     if (is_array($mbox_name))
S 1894       $a_mboxes = $mbox_name;
1895     else if (is_string($mbox_name) && strlen($mbox_name))
1896       $a_mboxes = explode(',', $mbox_name);
4e17e6 1897
97a656 1898     $all_mboxes = iil_C_ListMailboxes($this->conn, $this->_mod_mailbox($root), '*');
S 1899
4e17e6 1900     if (is_array($a_mboxes))
aadfa1 1901       foreach ($a_mboxes as $mbox_name)
4e17e6 1902         {
aadfa1 1903         $mailbox = $this->_mod_mailbox($mbox_name);
4e17e6 1904
T 1905         // unsubscribe mailbox before deleting
1906         iil_C_UnSubscribe($this->conn, $mailbox);
fa4cd2 1907
4e17e6 1908         // send delete command to server
T 1909         $result = iil_C_DeleteFolder($this->conn, $mailbox);
1910         if ($result>=0)
1911           $deleted = TRUE;
97a656 1912
S 1913         foreach ($all_mboxes as $c_mbox)
fa0152 1914           {
T 1915           $regex = preg_quote($mailbox . $this->delimiter, '/');
1916           $regex = '/^' . $regex . '/';
1917           if (preg_match($regex, $c_mbox))
97a656 1918             {
S 1919             iil_C_UnSubscribe($this->conn, $c_mbox);
1920             $result = iil_C_DeleteFolder($this->conn, $c_mbox);
1921             if ($result>=0)
1922               $deleted = TRUE;
1923             }
fa0152 1924           }
4e17e6 1925         }
T 1926
1927     // clear mailboxlist cache
1928     if ($deleted)
1cded8 1929       {
T 1930       $this->clear_message_cache($mailbox.'.msg');
4e17e6 1931       $this->clear_cache('mailboxes');
1cded8 1932       }
4e17e6 1933
1cded8 1934     return $deleted;
4e17e6 1935     }
T 1936
fa4cd2 1937
T 1938   /**
1939    * Create all folders specified as default
1940    */
1941   function create_default_folders()
1942     {
1943     $a_folders = iil_C_ListMailboxes($this->conn, $this->_mod_mailbox(''), '*');
1944     $a_subscribed = iil_C_ListSubscribed($this->conn, $this->_mod_mailbox(''), '*');
1945     
1946     // create default folders if they do not exist
1947     foreach ($this->default_folders as $folder)
1948       {
1949       $abs_name = $this->_mod_mailbox($folder);
719a25 1950       if (!in_array_nocase($abs_name, $a_folders))
T 1951         $this->create_mailbox($folder, TRUE);
1952       else if (!in_array_nocase($abs_name, $a_subscribed))
1953         $this->subscribe($folder);
fa4cd2 1954       }
T 1955     }
4e17e6 1956
T 1957
1958
1959   /* --------------------------------
1cded8 1960    *   internal caching methods
4e17e6 1961    * --------------------------------*/
6dc026 1962
6d969b 1963   /**
T 1964    * @access private
1965    */
6dc026 1966   function set_caching($set)
T 1967     {
1cded8 1968     if ($set && is_object($this->db))
6dc026 1969       $this->caching_enabled = TRUE;
T 1970     else
1971       $this->caching_enabled = FALSE;
1972     }
1cded8 1973
6d969b 1974   /**
T 1975    * @access private
1976    */
4e17e6 1977   function get_cache($key)
T 1978     {
1979     // read cache
6dc026 1980     if (!isset($this->cache[$key]) && $this->caching_enabled)
4e17e6 1981       {
1cded8 1982       $cache_data = $this->_read_cache_record('IMAP.'.$key);
4e17e6 1983       $this->cache[$key] = strlen($cache_data) ? unserialize($cache_data) : FALSE;
T 1984       }
1985     
1cded8 1986     return $this->cache[$key];
4e17e6 1987     }
T 1988
6d969b 1989   /**
T 1990    * @access private
1991    */
4e17e6 1992   function update_cache($key, $data)
T 1993     {
1994     $this->cache[$key] = $data;
1995     $this->cache_changed = TRUE;
1996     $this->cache_changes[$key] = TRUE;
1997     }
1998
6d969b 1999   /**
T 2000    * @access private
2001    */
4e17e6 2002   function write_cache()
T 2003     {
6dc026 2004     if ($this->caching_enabled && $this->cache_changed)
4e17e6 2005       {
T 2006       foreach ($this->cache as $key => $data)
2007         {
2008         if ($this->cache_changes[$key])
1cded8 2009           $this->_write_cache_record('IMAP.'.$key, serialize($data));
4e17e6 2010         }
T 2011       }    
2012     }
2013
6d969b 2014   /**
T 2015    * @access private
2016    */
4e17e6 2017   function clear_cache($key=NULL)
T 2018     {
fc2312 2019     if (!$this->caching_enabled)
A 2020       return;
2021     
4e17e6 2022     if ($key===NULL)
T 2023       {
2024       foreach ($this->cache as $key => $data)
1cded8 2025         $this->_clear_cache_record('IMAP.'.$key);
4e17e6 2026
T 2027       $this->cache = array();
2028       $this->cache_changed = FALSE;
2029       $this->cache_changes = array();
2030       }
2031     else
2032       {
1cded8 2033       $this->_clear_cache_record('IMAP.'.$key);
4e17e6 2034       $this->cache_changes[$key] = FALSE;
T 2035       unset($this->cache[$key]);
2036       }
2037     }
2038
6d969b 2039   /**
T 2040    * @access private
2041    */
1cded8 2042   function _read_cache_record($key)
T 2043     {
2044     $cache_data = FALSE;
2045     
2046     if ($this->db)
2047       {
2048       // get cached data from DB
2049       $sql_result = $this->db->query(
2050         "SELECT cache_id, data
2051          FROM ".get_table_name('cache')."
2052          WHERE  user_id=?
2053          AND    cache_key=?",
2054         $_SESSION['user_id'],
2055         $key);
2056
2057       if ($sql_arr = $this->db->fetch_assoc($sql_result))
2058         {
2059         $cache_data = $sql_arr['data'];
2060         $this->cache_keys[$key] = $sql_arr['cache_id'];
2061         }
2062       }
2063
6d969b 2064     return $cache_data;
1cded8 2065     }
T 2066
6d969b 2067   /**
T 2068    * @access private
2069    */
1cded8 2070   function _write_cache_record($key, $data)
T 2071     {
2072     if (!$this->db)
2073       return FALSE;
2074
2075     // check if we already have a cache entry for this key
2076     if (!isset($this->cache_keys[$key]))
2077       {
2078       $sql_result = $this->db->query(
2079         "SELECT cache_id
2080          FROM ".get_table_name('cache')."
2081          WHERE  user_id=?
2082          AND    cache_key=?",
2083         $_SESSION['user_id'],
2084         $key);
2085                                      
2086       if ($sql_arr = $this->db->fetch_assoc($sql_result))
2087         $this->cache_keys[$key] = $sql_arr['cache_id'];
2088       else
2089         $this->cache_keys[$key] = FALSE;
2090       }
2091
2092     // update existing cache record
2093     if ($this->cache_keys[$key])
2094       {
2095       $this->db->query(
2096         "UPDATE ".get_table_name('cache')."
107bde 2097          SET    created=".$this->db->now().",
1cded8 2098                 data=?
T 2099          WHERE  user_id=?
2100          AND    cache_key=?",
2101         $data,
2102         $_SESSION['user_id'],
2103         $key);
2104       }
2105     // add new cache record
2106     else
2107       {
2108       $this->db->query(
2109         "INSERT INTO ".get_table_name('cache')."
2110          (created, user_id, cache_key, data)
107bde 2111          VALUES (".$this->db->now().", ?, ?, ?)",
1cded8 2112         $_SESSION['user_id'],
T 2113         $key,
2114         $data);
2115       }
2116     }
2117
6d969b 2118   /**
T 2119    * @access private
2120    */
1cded8 2121   function _clear_cache_record($key)
T 2122     {
2123     $this->db->query(
2124       "DELETE FROM ".get_table_name('cache')."
2125        WHERE  user_id=?
2126        AND    cache_key=?",
2127       $_SESSION['user_id'],
2128       $key);
2129     }
2130
2131
2132
4e17e6 2133   /* --------------------------------
1cded8 2134    *   message caching methods
T 2135    * --------------------------------*/
2136    
2137
6d969b 2138   /**
T 2139    * Checks if the cache is up-to-date
2140    *
2141    * @param string Mailbox name
2142    * @param string Internal cache key
2143    * @return int -3 = off, -2 = incomplete, -1 = dirty
2144    */
1cded8 2145   function check_cache_status($mailbox, $cache_key)
T 2146     {
2147     if (!$this->caching_enabled)
2148       return -3;
2149
2150     $cache_index = $this->get_message_cache_index($cache_key, TRUE);
2151     $msg_count = $this->_messagecount($mailbox);
2152     $cache_count = count($cache_index);
2153
2154     // console("Cache check: $msg_count !== ".count($cache_index));
2155
2156     if ($cache_count==$msg_count)
2157       {
2158       // get highest index
2159       $header = iil_C_FetchHeader($this->conn, $mailbox, "$msg_count");
2160       $cache_uid = array_pop($cache_index);
2161       
e6f360 2162       // uids of highest message matches -> cache seems OK
1cded8 2163       if ($cache_uid == $header->uid)
T 2164         return 1;
2165
2166       // cache is dirty
2167       return -1;
2168       }
e6f360 2169     // if cache count differs less than 10% report as dirty
1cded8 2170     else if (abs($msg_count - $cache_count) < $msg_count/10)
T 2171       return -1;
2172     else
2173       return -2;
2174     }
2175
6d969b 2176   /**
T 2177    * @access private
2178    */
1cded8 2179   function get_message_cache($key, $from, $to, $sort_field, $sort_order)
T 2180     {
2181     $cache_key = "$key:$from:$to:$sort_field:$sort_order";
2182     $db_header_fields = array('idx', 'uid', 'subject', 'from', 'to', 'cc', 'date', 'size');
2183     
2184     if (!in_array($sort_field, $db_header_fields))
2185       $sort_field = 'idx';
2186     
2187     if ($this->caching_enabled && !isset($this->cache[$cache_key]))
2188       {
2189       $this->cache[$cache_key] = array();
2190       $sql_result = $this->db->limitquery(
2191         "SELECT idx, uid, headers
2192          FROM ".get_table_name('messages')."
2193          WHERE  user_id=?
2194          AND    cache_key=?
2195          ORDER BY ".$this->db->quoteIdentifier($sort_field)." ".
2196          strtoupper($sort_order),
2197         $from,
2198         $to-$from,
2199         $_SESSION['user_id'],
2200         $key);
2201
2202       while ($sql_arr = $this->db->fetch_assoc($sql_result))
2203         {
2204         $uid = $sql_arr['uid'];
2205         $this->cache[$cache_key][$uid] = unserialize($sql_arr['headers']);
ecd2e7 2206         
T 2207         // featch headers if unserialize failed
2208         if (empty($this->cache[$cache_key][$uid]))
2209           $this->cache[$cache_key][$uid] = iil_C_FetchHeader($this->conn, preg_replace('/.msg$/', '', $key), $uid, true);
1cded8 2210         }
T 2211       }
2212       
2213     return $this->cache[$cache_key];
2214     }
2215
6d969b 2216   /**
T 2217    * @access private
2218    */
f7bfec 2219   function &get_cached_message($key, $uid, $struct=false)
1cded8 2220     {
T 2221     $internal_key = '__single_msg';
017def 2222     
f7bfec 2223     if ($this->caching_enabled && (!isset($this->cache[$internal_key][$uid]) ||
T 2224         ($struct && empty($this->cache[$internal_key][$uid]->structure))))
1cded8 2225       {
f7bfec 2226       $sql_select = "idx, uid, headers" . ($struct ? ", structure" : '');
1cded8 2227       $sql_result = $this->db->query(
T 2228         "SELECT $sql_select
2229          FROM ".get_table_name('messages')."
2230          WHERE  user_id=?
2231          AND    cache_key=?
2232          AND    uid=?",
2233         $_SESSION['user_id'],
2234         $key,
2235         $uid);
f7bfec 2236
1cded8 2237       if ($sql_arr = $this->db->fetch_assoc($sql_result))
T 2238         {
f7bfec 2239         $this->cache[$internal_key][$uid] = unserialize($sql_arr['headers']);
T 2240         if (is_object($this->cache[$internal_key][$uid]) && !empty($sql_arr['structure']))
2241           $this->cache[$internal_key][$uid]->structure = unserialize($sql_arr['structure']);
1cded8 2242         }
T 2243       }
2244
2245     return $this->cache[$internal_key][$uid];
2246     }
2247
6d969b 2248   /**
T 2249    * @access private
2250    */  
0677ca 2251   function get_message_cache_index($key, $force=FALSE, $sort_col='idx', $sort_order='ASC')
1cded8 2252     {
T 2253     static $sa_message_index = array();
2254     
4647e1 2255     // empty key -> empty array
ffb0b0 2256     if (!$this->caching_enabled || empty($key))
4647e1 2257       return array();
T 2258     
1cded8 2259     if (!empty($sa_message_index[$key]) && !$force)
T 2260       return $sa_message_index[$key];
2261     
2262     $sa_message_index[$key] = array();
2263     $sql_result = $this->db->query(
2264       "SELECT idx, uid
2265        FROM ".get_table_name('messages')."
2266        WHERE  user_id=?
2267        AND    cache_key=?
0677ca 2268        ORDER BY ".$this->db->quote_identifier($sort_col)." ".$sort_order,
1cded8 2269       $_SESSION['user_id'],
T 2270       $key);
2271
2272     while ($sql_arr = $this->db->fetch_assoc($sql_result))
2273       $sa_message_index[$key][$sql_arr['idx']] = $sql_arr['uid'];
2274       
2275     return $sa_message_index[$key];
2276     }
2277
6d969b 2278   /**
T 2279    * @access private
2280    */
f7bfec 2281   function add_message_cache($key, $index, $headers, $struct=null)
1cded8 2282     {
017def 2283     if (empty($key) || !is_object($headers) || empty($headers->uid))
T 2284         return;
2285     
2286     // add to internal (fast) cache
2287     $this->cache['__single_msg'][$headers->uid] = $headers;
2288     $this->cache['__single_msg'][$headers->uid]->structure = $struct;
2289     
2290     // no further caching
2291     if (!$this->caching_enabled)
31b2ce 2292       return;
017def 2293     
f7bfec 2294     // check for an existing record (probly headers are cached but structure not)
T 2295     $sql_result = $this->db->query(
2296         "SELECT message_id
2297          FROM ".get_table_name('messages')."
2298          WHERE  user_id=?
2299          AND    cache_key=?
2300          AND    uid=?
2301          AND    del<>1",
2302         $_SESSION['user_id'],
2303         $key,
2304         $headers->uid);
31b2ce 2305
f7bfec 2306     // update cache record
T 2307     if ($sql_arr = $this->db->fetch_assoc($sql_result))
2308       {
2309       $this->db->query(
2310         "UPDATE ".get_table_name('messages')."
2311          SET   idx=?, headers=?, structure=?
2312          WHERE message_id=?",
2313         $index,
2314         serialize($headers),
2315         is_object($struct) ? serialize($struct) : NULL,
2316         $sql_arr['message_id']
2317         );
2318       }
2319     else  // insert new record
2320       {
2321       $this->db->query(
2322         "INSERT INTO ".get_table_name('messages')."
2323          (user_id, del, cache_key, created, idx, uid, subject, ".$this->db->quoteIdentifier('from').", ".$this->db->quoteIdentifier('to').", cc, date, size, headers, structure)
107bde 2324          VALUES (?, 0, ?, ".$this->db->now().", ?, ?, ?, ?, ?, ?, ".$this->db->fromunixtime($headers->timestamp).", ?, ?, ?)",
f7bfec 2325         $_SESSION['user_id'],
T 2326         $key,
2327         $index,
2328         $headers->uid,
2329         (string)substr($this->decode_header($headers->subject, TRUE), 0, 128),
2330         (string)substr($this->decode_header($headers->from, TRUE), 0, 128),
2331         (string)substr($this->decode_header($headers->to, TRUE), 0, 128),
2332         (string)substr($this->decode_header($headers->cc, TRUE), 0, 128),
2333         (int)$headers->size,
2334         serialize($headers),
2335         is_object($struct) ? serialize($struct) : NULL
2336         );
2337       }
1cded8 2338     }
T 2339     
6d969b 2340   /**
T 2341    * @access private
2342    */
1cded8 2343   function remove_message_cache($key, $index)
T 2344     {
780527 2345     if (!$this->caching_enabled)
T 2346       return;
2347     
1cded8 2348     $this->db->query(
T 2349       "DELETE FROM ".get_table_name('messages')."
2350        WHERE  user_id=?
2351        AND    cache_key=?
2352        AND    idx=?",
2353       $_SESSION['user_id'],
2354       $key,
2355       $index);
2356     }
2357
6d969b 2358   /**
T 2359    * @access private
2360    */
1cded8 2361   function clear_message_cache($key, $start_index=1)
T 2362     {
780527 2363     if (!$this->caching_enabled)
T 2364       return;
2365     
1cded8 2366     $this->db->query(
T 2367       "DELETE FROM ".get_table_name('messages')."
2368        WHERE  user_id=?
2369        AND    cache_key=?
2370        AND    idx>=?",
2371       $_SESSION['user_id'],
2372       $key,
2373       $start_index);
2374     }
2375
2376
2377
2378
2379   /* --------------------------------
2380    *   encoding/decoding methods
4e17e6 2381    * --------------------------------*/
T 2382
6d969b 2383   /**
T 2384    * Split an address list into a structured array list
2385    *
2386    * @param string  Input string
2387    * @param int     List only this number of addresses
2388    * @param boolean Decode address strings
2389    * @return array  Indexed list of addresses
2390    */
f11541 2391   function decode_address_list($input, $max=null, $decode=true)
4e17e6 2392     {
f11541 2393     $a = $this->_parse_address_list($input, $decode);
4e17e6 2394     $out = array();
0c6f4b 2395     // Special chars as defined by RFC 822 need to in quoted string (or escaped).
T 2396     $special_chars = '[\(\)\<\>\\\.\[\]@,;:"]';
41fa0b 2397     
4e17e6 2398     if (!is_array($a))
T 2399       return $out;
2400
2401     $c = count($a);
2402     $j = 0;
2403
2404     foreach ($a as $val)
2405       {
2406       $j++;
2407       $address = $val['address'];
2408       $name = preg_replace(array('/^[\'"]/', '/[\'"]$/'), '', trim($val['name']));
3cf664 2409       if ($name && $address && $name != $address)
0c6f4b 2410         $string = sprintf('%s <%s>', preg_match("/$special_chars/", $name) ? '"'.addcslashes($name, '"').'"' : $name, $address);
3cf664 2411       else if ($address)
T 2412         $string = $address;
2413       else if ($name)
2414         $string = $name;
4e17e6 2415       
T 2416       $out[$j] = array('name' => $name,
2417                        'mailto' => $address,
2418                        'string' => $string);
2419               
2420       if ($max && $j==$max)
2421         break;
2422       }
2423     
2424     return $out;
2425     }
2426
2427
6d969b 2428   /**
T 2429    * Decode a message header value
2430    *
2431    * @param string  Header value
2432    * @param boolean Remove quotes if necessary
2433    * @return string Decoded string
2434    */
1cded8 2435   function decode_header($input, $remove_quotes=FALSE)
4e17e6 2436     {
17b5fb 2437     $str = rcube_imap::decode_mime_string((string)$input, $this->default_charset);
1cded8 2438     if ($str{0}=='"' && $remove_quotes)
T 2439       $str = str_replace('"', '', $str);
2440     
2441     return $str;
4b0f65 2442     }
ba8f44 2443
T 2444
2445   /**
2446    * Decode a mime-encoded string to internal charset
2447    *
6d969b 2448    * @param string  Header value
T 2449    * @param string  Fallback charset if none specified
2450    * @return string Decoded string
2451    * @static
ba8f44 2452    */
f11541 2453   function decode_mime_string($input, $fallback=null)
4b0f65 2454     {
2e6825 2455     // Initialize variable
4e17e6 2456     $out = '';
T 2457
2e6825 2458     // Iterate instead of recursing, this way if there are too many values we don't have stack overflows
T 2459     // rfc: all line breaks or other characters not found 
2460     // in the Base64 Alphabet must be ignored by decoding software
2461     // delete all blanks between MIME-lines, differently we can 
2462     // receive unnecessary blanks and broken utf-8 symbols
2463     $input = preg_replace("/\?=\s+=\?/", '?==?', $input);
9e60d4 2464
2e6825 2465     // Check if there is stuff to decode
T 2466     if (strpos($input, '=?') !== false) {
2467       // Loop through the string to decode all occurences of =? ?= into the variable $out 
2468       while(($pos = strpos($input, '=?')) !== false) {
2469         // Append everything that is before the text to be decoded
2470         $out .= substr($input, 0, $pos);
4e17e6 2471
2e6825 2472         // Get the location of the text to decode
T 2473         $end_cs_pos = strpos($input, "?", $pos+2);
2474         $end_en_pos = strpos($input, "?", $end_cs_pos+1);
2475         $end_pos = strpos($input, "?=", $end_en_pos+1);
4e17e6 2476
2e6825 2477         // Extract the encoded string
T 2478         $encstr = substr($input, $pos+2, ($end_pos-$pos-2));
2479         // Extract the remaining string
2480         $input = substr($input, $end_pos+2);
2481
2482         // Decode the string fragement
2483         $out .= rcube_imap::_decode_mime_string_part($encstr);
4e17e6 2484       }
399835 2485
2e6825 2486       // Deocde the rest (if any)
T 2487       if (strlen($input) != 0)
2488          $out .= rcube_imap::decode_mime_string($input, $fallback);
2489
2490        // return the results
2491       return $out;
2492     }
2493
f11541 2494     // no encoding information, use fallback
399835 2495     return rcube_charset_convert($input, 
b026c3 2496       !empty($fallback) ? $fallback : rcmail::get_instance()->config->get('default_charset', 'ISO-8859-1'));
4e17e6 2497     }
T 2498
2499
ba8f44 2500   /**
T 2501    * Decode a part of a mime-encoded string
2502    *
6d969b 2503    * @access private
ba8f44 2504    */
4b0f65 2505   function _decode_mime_string_part($str)
4e17e6 2506     {
T 2507     $a = explode('?', $str);
2508     $count = count($a);
2509
2510     // should be in format "charset?encoding?base64_string"
2511     if ($count >= 3)
2512       {
2513       for ($i=2; $i<$count; $i++)
2514         $rest.=$a[$i];
2515
2516       if (($a[1]=="B")||($a[1]=="b"))
2517         $rest = base64_decode($rest);
2518       else if (($a[1]=="Q")||($a[1]=="q"))
2519         {
2520         $rest = str_replace("_", " ", $rest);
2521         $rest = quoted_printable_decode($rest);
2522         }
2523
3f9edb 2524       return rcube_charset_convert($rest, $a[0]);
4e17e6 2525       }
T 2526     else
3f9edb 2527       return $str;    // we dont' know what to do with this  
4e17e6 2528     }
T 2529
2530
6d969b 2531   /**
T 2532    * Decode a mime part
2533    *
2534    * @param string Input string
2535    * @param string Part encoding
2536    * @return string Decoded string
2537    * @access private
2538    */
4e17e6 2539   function mime_decode($input, $encoding='7bit')
T 2540     {
2541     switch (strtolower($encoding))
2542       {
2543       case '7bit':
2544         return $input;
2545         break;
2546       
2547       case 'quoted-printable':
2548         return quoted_printable_decode($input);
2549         break;
2550       
2551       case 'base64':
2552         return base64_decode($input);
2553         break;
2554       
2555       default:
2556         return $input;
2557       }
2558     }
2559
2560
6d969b 2561   /**
T 2562    * Convert body charset to UTF-8 according to the ctype_parameters
2563    *
2564    * @param string Part body to decode
2565    * @param string Charset to convert from
2566    * @return string Content converted to internal charset
2567    */
4e17e6 2568   function charset_decode($body, $ctype_param)
T 2569     {
a95e0e 2570     if (is_array($ctype_param) && !empty($ctype_param['charset']))
3f9edb 2571       return rcube_charset_convert($body, $ctype_param['charset']);
4e17e6 2572
fb5f4f 2573     // defaults to what is specified in the class header
17b5fb 2574     return rcube_charset_convert($body,  $this->default_charset);
4e17e6 2575     }
T 2576
2577
6d969b 2578   /**
T 2579    * Translate UID to message ID
2580    *
2581    * @param int    Message UID
2582    * @param string Mailbox name
2583    * @return int   Message ID
2584    */
2585   function get_id($uid, $mbox_name=NULL) 
2586     {
2587       $mailbox = $mbox_name ? $this->_mod_mailbox($mbox_name) : $this->mailbox;
2588       return $this->_uid2id($uid, $mailbox);
2589     }
2590
2591
2592   /**
2593    * Translate message number to UID
2594    *
2595    * @param int    Message ID
2596    * @param string Mailbox name
2597    * @return int   Message UID
2598    */
2599   function get_uid($id,$mbox_name=NULL)
2600     {
2601       $mailbox = $mbox_name ? $this->_mod_mailbox($mbox_name) : $this->mailbox;
2602       return $this->_id2uid($id, $mailbox);
2603     }
2604
1cded8 2605
ba8f44 2606
4e17e6 2607   /* --------------------------------
T 2608    *         private methods
2609    * --------------------------------*/
2610
2611
6d969b 2612   /**
T 2613    * @access private
2614    */
aadfa1 2615   function _mod_mailbox($mbox_name, $mode='in')
4e17e6 2616     {
ae4d74 2617     if ((!empty($this->root_ns) && $this->root_ns == $mbox_name) || $mbox_name == 'INBOX')
aadfa1 2618       return $mbox_name;
7902df 2619
f619de 2620     if (!empty($this->root_dir) && $mode=='in') 
aadfa1 2621       $mbox_name = $this->root_dir.$this->delimiter.$mbox_name;
7902df 2622     else if (strlen($this->root_dir) && $mode=='out') 
aadfa1 2623       $mbox_name = substr($mbox_name, strlen($this->root_dir)+1);
4e17e6 2624
aadfa1 2625     return $mbox_name;
4e17e6 2626     }
T 2627
d5342a 2628   /**
T 2629    * Validate the given input and save to local properties
2630    * @access private
2631    */
2632   function _set_sort_order($sort_field, $sort_order)
2633   {
2634     if ($sort_field != null)
2635       $this->sort_field = asciiwords($sort_field);
2636     if ($sort_order != null)
2637       $this->sort_order = strtoupper($sort_order) == 'DESC' ? 'DESC' : 'ASC';
2638   }
4e17e6 2639
6d969b 2640   /**
T 2641    * Sort mailboxes first by default folders and then in alphabethical order
2642    * @access private
2643    */
4e17e6 2644   function _sort_mailbox_list($a_folders)
T 2645     {
ea400e 2646     $a_out = $a_defaults = $folders = array();
681a59 2647
A 2648     $delimiter = $this->get_hierarchy_delimiter();
4e17e6 2649
T 2650     // find default folders and skip folders starting with '.'
681a59 2651     foreach ($a_folders as $i => $folder)
4e17e6 2652       {
T 2653       if ($folder{0}=='.')
6d969b 2654         continue;
fa4cd2 2655
c007e6 2656       if (($p = array_search(strtolower($folder), $this->default_folders_lc)) !== false && !$a_defaults[$p])
6d969b 2657         $a_defaults[$p] = $folder;
4e17e6 2658       else
70aa90 2659         $folders[$folder] = rc_strtolower(rcube_charset_convert($folder, 'UTF-7'));
681a59 2660       }
A 2661
2662     asort($folders, SORT_LOCALE_STRING);
2663     ksort($a_defaults);
2664
2665     $folders = array_merge($a_defaults, array_keys($folders));
2666
2667     // finally we must rebuild the list to move 
f219a2 2668     // subfolders of default folders to their place...
A 2669     // ...also do this for the rest of folders because
2670     // asort() is not properly sorting case sensitive names    
681a59 2671     while (list($key, $folder) = each($folders)) {
A 2672       $a_out[] = $folder;
2673       unset($folders[$key]);
f219a2 2674       foreach ($folders as $idx => $f) {
A 2675     if (strpos($f, $folder.$delimiter) === 0) {
2676           $a_out[] = $f;
2677       unset($folders[$idx]);
681a59 2678       }
f219a2 2679         }
A 2680       reset($folders);  
4e17e6 2681       }
T 2682
681a59 2683     return $a_out;
4e17e6 2684     }
T 2685
6d969b 2686   /**
T 2687    * @access private
2688    */
aadfa1 2689   function _uid2id($uid, $mbox_name=NULL)
4e17e6 2690     {
aadfa1 2691     if (!$mbox_name)
S 2692       $mbox_name = $this->mailbox;
4e17e6 2693       
aadfa1 2694     if (!isset($this->uid_id_map[$mbox_name][$uid]))
S 2695       $this->uid_id_map[$mbox_name][$uid] = iil_C_UID2ID($this->conn, $mbox_name, $uid);
4e17e6 2696
aadfa1 2697     return $this->uid_id_map[$mbox_name][$uid];
4e17e6 2698     }
T 2699
6d969b 2700   /**
T 2701    * @access private
2702    */
aadfa1 2703   function _id2uid($id, $mbox_name=NULL)
e6f360 2704     {
aadfa1 2705     if (!$mbox_name)
S 2706       $mbox_name = $this->mailbox;
e6f360 2707       
1fb2c8 2708     $index = array_flip((array)$this->uid_id_map[$mbox_name]);
017def 2709     if (isset($index[$id]))
T 2710       $uid = $index[$id];
2711     else
2712       {
2713       $uid = iil_C_ID2UID($this->conn, $mbox_name, $id);
2714       $this->uid_id_map[$mbox_name][$uid] = $id;
2715       }
2716     
2717     return $uid;
1cded8 2718     }
T 2719
2720
6d969b 2721   /**
T 2722    * Subscribe/unsubscribe a list of mailboxes and update local cache
2723    * @access private
2724    */
4e17e6 2725   function _change_subscription($a_mboxes, $mode)
T 2726     {
2727     $updated = FALSE;
2728     
2729     if (is_array($a_mboxes))
aadfa1 2730       foreach ($a_mboxes as $i => $mbox_name)
4e17e6 2731         {
aadfa1 2732         $mailbox = $this->_mod_mailbox($mbox_name);
4e17e6 2733         $a_mboxes[$i] = $mailbox;
T 2734
2735         if ($mode=='subscribe')
2736           $result = iil_C_Subscribe($this->conn, $mailbox);
2737         else if ($mode=='unsubscribe')
2738           $result = iil_C_UnSubscribe($this->conn, $mailbox);
2739
2740         if ($result>=0)
2741           $updated = TRUE;
2742         }
2743         
2744     // get cached mailbox list    
2745     if ($updated)
2746       {
2747       $a_mailbox_cache = $this->get_cache('mailboxes');
2748       if (!is_array($a_mailbox_cache))
2749         return $updated;
2750
2751       // modify cached list
2752       if ($mode=='subscribe')
2753         $a_mailbox_cache = array_merge($a_mailbox_cache, $a_mboxes);
2754       else if ($mode=='unsubscribe')
2755         $a_mailbox_cache = array_diff($a_mailbox_cache, $a_mboxes);
2756         
2757       // write mailboxlist to cache
2758       $this->update_cache('mailboxes', $this->_sort_mailbox_list($a_mailbox_cache));
2759       }
2760
2761     return $updated;
2762     }
2763
2764
6d969b 2765   /**
T 2766    * Increde/decrese messagecount for a specific mailbox
2767    * @access private
2768    */
aadfa1 2769   function _set_messagecount($mbox_name, $mode, $increment)
4e17e6 2770     {
T 2771     $a_mailbox_cache = FALSE;
aadfa1 2772     $mailbox = $mbox_name ? $mbox_name : $this->mailbox;
4e17e6 2773     $mode = strtoupper($mode);
T 2774
2775     $a_mailbox_cache = $this->get_cache('messagecount');
2776     
2777     if (!is_array($a_mailbox_cache[$mailbox]) || !isset($a_mailbox_cache[$mailbox][$mode]) || !is_numeric($increment))
2778       return FALSE;
2779     
2780     // add incremental value to messagecount
2781     $a_mailbox_cache[$mailbox][$mode] += $increment;
31b2ce 2782     
T 2783     // there's something wrong, delete from cache
2784     if ($a_mailbox_cache[$mailbox][$mode] < 0)
2785       unset($a_mailbox_cache[$mailbox][$mode]);
4e17e6 2786
T 2787     // write back to cache
2788     $this->update_cache('messagecount', $a_mailbox_cache);
2789     
2790     return TRUE;
2791     }
2792
2793
6d969b 2794   /**
T 2795    * Remove messagecount of a specific mailbox from cache
2796    * @access private
2797    */
aadfa1 2798   function _clear_messagecount($mbox_name='')
4e17e6 2799     {
T 2800     $a_mailbox_cache = FALSE;
aadfa1 2801     $mailbox = $mbox_name ? $mbox_name : $this->mailbox;
4e17e6 2802
T 2803     $a_mailbox_cache = $this->get_cache('messagecount');
2804
2805     if (is_array($a_mailbox_cache[$mailbox]))
2806       {
2807       unset($a_mailbox_cache[$mailbox]);
2808       $this->update_cache('messagecount', $a_mailbox_cache);
2809       }
2810     }
2811
2812
6d969b 2813   /**
T 2814    * Split RFC822 header string into an associative array
2815    * @access private
2816    */
8d4bcd 2817   function _parse_headers($headers)
T 2818     {
2819     $a_headers = array();
2820     $lines = explode("\n", $headers);
2821     $c = count($lines);
2822     for ($i=0; $i<$c; $i++)
2823       {
2824       if ($p = strpos($lines[$i], ': '))
2825         {
2826         $field = strtolower(substr($lines[$i], 0, $p));
2827         $value = trim(substr($lines[$i], $p+1));
2828         if (!empty($value))
2829           $a_headers[$field] = $value;
2830         }
2831       }
2832     
2833     return $a_headers;
2834     }
2835
2836
6d969b 2837   /**
T 2838    * @access private
2839    */
f11541 2840   function _parse_address_list($str, $decode=true)
4e17e6 2841     {
d04d20 2842     // remove any newlines and carriage returns before
5a6ad2 2843     $a = $this->_explode_quoted_string('[,;]', preg_replace( "/[\r\n]/", " ", $str));
4e17e6 2844     $result = array();
41fa0b 2845     
4e17e6 2846     foreach ($a as $key => $val)
T 2847       {
568ba3 2848       $val = preg_replace("/([\"\w])</", "$1 <", $val);
f11541 2849       $sub_a = $this->_explode_quoted_string(' ', $decode ? $this->decode_header($val) : $val);
41fa0b 2850       $result[$key]['name'] = '';
T 2851
4e17e6 2852       foreach ($sub_a as $k => $v)
T 2853         {
3cf664 2854         if (strpos($v, '@') > 0)
4e17e6 2855           $result[$key]['address'] = str_replace('<', '', str_replace('>', '', $v));
T 2856         else
2857           $result[$key]['name'] .= (empty($result[$key]['name'])?'':' ').str_replace("\"",'',stripslashes($v));
2858         }
2859         
2860       if (empty($result[$key]['name']))
41fa0b 2861         $result[$key]['name'] = $result[$key]['address'];        
4e17e6 2862       }
T 2863     
2864     return $result;
2865     }
2866
2867
6d969b 2868   /**
T 2869    * @access private
2870    */
4e17e6 2871   function _explode_quoted_string($delimiter, $string)
T 2872     {
5a6ad2 2873     $result = array();
T 2874     $strlen = strlen($string);
2875     for ($q=$p=$i=0; $i < $strlen; $i++)
2876     {
2877       if ($string{$i} == "\"" && $string{$i-1} != "\\")
2878         $q = $q ? false : true;
2879       else if (!$q && preg_match("/$delimiter/", $string{$i}))
2880       {
2881         $result[] = substr($string, $p, $i - $p);
2882         $p = $i + 1;
2883       }
2884     }
4e17e6 2885     
5a6ad2 2886     $result[] = substr($string, $p);
4e17e6 2887     return $result;
T 2888     }
6d969b 2889
T 2890 }  // end class rcube_imap
4e17e6 2891
8d4bcd 2892
T 2893 /**
2894  * Class representing a message part
6d969b 2895  *
T 2896  * @package Mail
8d4bcd 2897  */
T 2898 class rcube_message_part
2899 {
2900   var $mime_id = '';
2901   var $ctype_primary = 'text';
2902   var $ctype_secondary = 'plain';
2903   var $mimetype = 'text/plain';
2904   var $disposition = '';
5cc4b1 2905   var $filename = '';
8d4bcd 2906   var $encoding = '8bit';
T 2907   var $charset = '';
2908   var $size = 0;
2909   var $headers = array();
2910   var $d_parameters = array();
2911   var $ctype_parameters = array();
2912
2913 }
4e17e6 2914
T 2915
7e93ff 2916 /**
T 2917  * Class for sorting an array of iilBasicHeader objects in a predetermined order.
2918  *
6d969b 2919  * @package Mail
7e93ff 2920  * @author Eric Stadtherr
T 2921  */
2922 class rcube_header_sorter
2923 {
2924    var $sequence_numbers = array();
2925    
2926    /**
6d969b 2927     * Set the predetermined sort order.
7e93ff 2928     *
6d969b 2929     * @param array Numerically indexed array of IMAP message sequence numbers
7e93ff 2930     */
T 2931    function set_sequence_numbers($seqnums)
2932    {
05d180 2933       $this->sequence_numbers = array_flip($seqnums);
7e93ff 2934    }
T 2935  
2936    /**
6d969b 2937     * Sort the array of header objects
7e93ff 2938     *
6d969b 2939     * @param array Array of iilBasicHeader objects indexed by UID
7e93ff 2940     */
T 2941    function sort_headers(&$headers)
2942    {
2943       /*
2944        * uksort would work if the keys were the sequence number, but unfortunately
2945        * the keys are the UIDs.  We'll use uasort instead and dereference the value
2946        * to get the sequence number (in the "id" field).
2947        * 
2948        * uksort($headers, array($this, "compare_seqnums")); 
2949        */
2950        uasort($headers, array($this, "compare_seqnums"));
2951    }
2952  
2953    /**
2954     * Sort method called by uasort()
2955     */
2956    function compare_seqnums($a, $b)
2957    {
2958       // First get the sequence number from the header object (the 'id' field).
2959       $seqa = $a->id;
2960       $seqb = $b->id;
2961       
2962       // then find each sequence number in my ordered list
05d180 2963       $posa = isset($this->sequence_numbers[$seqa]) ? intval($this->sequence_numbers[$seqa]) : -1;
T 2964       $posb = isset($this->sequence_numbers[$seqb]) ? intval($this->sequence_numbers[$seqb]) : -1;
7e93ff 2965       
T 2966       // return the relative position as the comparison value
05d180 2967       return $posa - $posb;
7e93ff 2968    }
T 2969 }
4e17e6 2970
T 2971
7e93ff 2972 /**
T 2973  * Add quoted-printable encoding to a given string
2974  * 
6d969b 2975  * @param string   String to encode
T 2976  * @param int      Add new line after this number of characters
2977  * @param boolean  True if spaces should be converted into =20
2978  * @return string Encoded string
7e93ff 2979  */
T 2980 function quoted_printable_encode($input, $line_max=76, $space_conv=false)
4e17e6 2981   {
T 2982   $hex = array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');
2983   $lines = preg_split("/(?:\r\n|\r|\n)/", $input);
2984   $eol = "\r\n";
2985   $escape = "=";
2986   $output = "";
2987
2988   while( list(, $line) = each($lines))
2989     {
2990     //$line = rtrim($line); // remove trailing white space -> no =20\r\n necessary
2991     $linlen = strlen($line);
2992     $newline = "";
2993     for($i = 0; $i < $linlen; $i++)
2994       {
2995       $c = substr( $line, $i, 1 );
2996       $dec = ord( $c );
2997       if ( ( $i == 0 ) && ( $dec == 46 ) ) // convert first point in the line into =2E
2998         {
2999         $c = "=2E";
3000         }
3001       if ( $dec == 32 )
3002         {
3003         if ( $i == ( $linlen - 1 ) ) // convert space at eol only
3004           {
3005           $c = "=20";
3006           }
3007         else if ( $space_conv )
3008           {
3009           $c = "=20";
3010           }
3011         }
3012       else if ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) )  // always encode "\t", which is *not* required
3013         {
3014         $h2 = floor($dec/16);
3015         $h1 = floor($dec%16);
3016         $c = $escape.$hex["$h2"].$hex["$h1"];
3017         }
3018          
3019       if ( (strlen($newline) + strlen($c)) >= $line_max )  // CRLF is not counted
3020         {
3021         $output .= $newline.$escape.$eol; // soft line break; " =\r\n" is okay
3022         $newline = "";
3023         // check if newline first character will be point or not
3024         if ( $dec == 46 )
3025           {
3026           $c = "=2E";
3027           }
3028         }
3029       $newline .= $c;
3030       } // end of for
3031     $output .= $newline.$eol;
3032     } // end of while
3033
3034   return trim($output);
3035   }
3036
8d4bcd 3037