thomascube
2008-09-25 cefd1d8c913aa81ddce83e9de7f5bfb22aa4b2d9
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->ctype_parameters['name']))
1186       $filename_mime = $part->ctype_parameters['name'];
1187     else if (!empty($part->d_parameters['filename*']))
1188       $filename_encoded = $part->d_parameters['filename*'];
1189     else if (!empty($part->ctype_parameters['name*']))
1190       $filename_encoded = $part->ctype_parameters['name*'];
1191     // RFC2231 value continuations
1192     // TODO: this should be rewrited to support RFC2231 4.1 combinations
1193     else if (!empty($part->d_parameters['filename*0'])) {
1194       $i = 0;
1195       while (isset($part->d_parameters['filename*'.$i])) {
1196         $i++;
1197         $filename_mime .= $part->d_parameters['filename*'.$i];
1198     }
1199       // some servers (eg. dovecot-1.x) have no support for parameter value continuations
1200       // we must fetch and parse headers "manually"
20a251 1201       //TODO: fetching headers for a second time is not effecient, this code should be moved somewhere earlier --tensor
5df0ad 1202       if ($i<2) {
A 1203         // TODO: fetch only Content-Type/Content-Disposition header
20a251 1204         $headers = iil_C_FetchPartHeader($this->conn, $this->mailbox, $this->_msg_id, $part->mime_id);
42e328 1205         $filename_mime = '';
T 1206         $i = 0;
1207         while (preg_match('/filename\*'.$i.'\s*=\s*"*([^"\n;]+)[";]*/', $headers, $matches)) {
1208           $filename_mime .= $matches[1];
1209           $i++;
1210         }
5df0ad 1211       }
42e328 1212     }
5df0ad 1213     else if (!empty($part->d_parameters['filename*0*'])) {
A 1214       $i = 0;
1215       while (isset($part->d_parameters['filename*'.$i.'*'])) {
1216         $i++;
42e328 1217         $filename_encoded .= $part->d_parameters['filename*'.$i.'*'];
T 1218       }
5df0ad 1219       if ($i<2) {
20a251 1220         $headers = iil_C_FetchPartHeader($this->conn, $this->mailbox, $this->_msg_id, $part->mime_id);
42e328 1221         $filename_encoded = '';
T 1222         $i = 0; $matches = array();
1223         while (preg_match('/filename\*'.$i.'\*\s*=\s*"*([^"\n;]+)[";]*/', $headers, $matches)) {
1224           $filename_encoded .= $matches[1];
1225           $i++;
1226         }
5df0ad 1227       }
42e328 1228     }
5df0ad 1229     else if (!empty($part->ctype_parameters['name*0'])) {
A 1230       $i = 0;
1231       while (isset($part->ctype_parameters['name*'.$i])) {
1232         $i++;
1233         $filename_mime .= $part->ctype_parameters['name*'.$i];
42e328 1234       }
5df0ad 1235       if ($i<2) {
20a251 1236         $headers = iil_C_FetchPartHeader($this->conn, $this->mailbox, $this->_msg_id, $part->mime_id);
42e328 1237         $filename_mime = '';
T 1238         $i = 0; $matches = array();
1239         while (preg_match('/\s+name\*'.$i.'\s*=\s*"*([^"\n;]+)[";]*/', $headers, $matches)) {
1240           $filename_mime .= $matches[1];
1241           $i++;
1242         }
5df0ad 1243       }
42e328 1244     }
5df0ad 1245     else if (!empty($part->ctype_parameters['name*0*'])) {
A 1246       $i = 0;
1247       while (isset($part->ctype_parameters['name*'.$i.'*'])) {
1248         $i++;
1249         $filename_encoded .= $part->ctype_parameters['name*'.$i.'*'];
42e328 1250       }
5df0ad 1251       if ($i<2) {
20a251 1252         $headers = iil_C_FetchPartHeader($this->conn, $this->mailbox, $this->_msg_id, $part->mime_id);
42e328 1253         $filename_encoded = '';
T 1254         $i = 0; $matches = array();
1255         while (preg_match('/\s+name\*'.$i.'\*\s*=\s*"*([^"\n;]+)[";]*/', $headers, $matches)) {
1256           $filename_encoded .= $matches[1];
1257           $i++;
1258         }
5df0ad 1259       }
42e328 1260     }
5df0ad 1261     // Content-Disposition
A 1262     else if (!empty($part->headers['content-description']))
1263       $filename_mime = $part->headers['content-description'];
1264     else
1265       return;
1266
1267     // decode filename
1268     if (!empty($filename_mime)) {
1269       $part->filename = rcube_imap::decode_mime_string($filename_mime, 
42e328 1270         $part->charset ? $part->charset : rc_detect_encoding($filename_mime, $this->default_charset));
5df0ad 1271       } 
A 1272     else if (!empty($filename_encoded)) {
1273       // decode filename according to RFC 2231, Section 4
94a99c 1274       if (preg_match("/^([^']*)'[^']*'(.*)$/", $filename_encoded, $fmatches)) {
A 1275         $filename_charset = $fmatches[1];
1276         $filename_encoded = $fmatches[2];
1277         }
1278       $part->filename = rcube_charset_convert(urldecode($filename_encoded), $filename_charset);
5df0ad 1279       }
A 1280     }
1281      
8d4bcd 1282   
T 1283   /**
1284    * Fetch message body of a specific message from the server
1285    *
1286    * @param  int    Message UID
1287    * @param  string Part number
6d969b 1288    * @param  object rcube_message_part Part object created by get_structure()
8d4bcd 1289    * @param  mixed  True to print part, ressource to write part contents in
81b573 1290    * @param  resource File pointer to save the message part
6d969b 1291    * @return string Message/part body if not printed
8d4bcd 1292    */
81b573 1293   function &get_message_part($uid, $part=1, $o_part=NULL, $print=NULL, $fp=NULL)
8d4bcd 1294     {
T 1295     if (!($msg_id = $this->_uid2id($uid)))
1296       return FALSE;
1297     
1298     // get part encoding if not provided
1299     if (!is_object($o_part))
1300       {
1301       $structure_str = iil_C_FetchStructureString($this->conn, $this->mailbox, $msg_id); 
1302       $structure = iml_GetRawStructureArray($structure_str);
1303       $part_type = iml_GetPartTypeCode($structure, $part);
1304       $o_part = new rcube_message_part;
1305       $o_part->ctype_primary = $part_type==0 ? 'text' : ($part_type==2 ? 'message' : 'other');
1306       $o_part->encoding = strtolower(iml_GetPartEncodingString($structure, $part));
1307       $o_part->charset = iml_GetPartCharset($structure, $part);
1308       }
1309       
1310     // TODO: Add caching for message parts
1311
1312     if ($print)
1313       {
a9cc52 1314       $mode = $o_part->encoding == 'base64' ? 3 : ($o_part->encoding == 'quoted-printable' ? 1 : 2);
T 1315       $body = iil_C_HandlePartBody($this->conn, $this->mailbox, $msg_id, $part, $mode);
1316       
1317       // we have to decode the part manually before printing
1318       if ($mode == 1)
1319         {
1320         echo $this->mime_decode($body, $o_part->encoding);
1321         $body = true;
1322         }
8d4bcd 1323       }
T 1324     else
1325       {
81b573 1326       if ($fp && $o_part->encoding == 'base64')
A 1327         return iil_C_HandlePartBody($this->conn, $this->mailbox, $msg_id, $part, 3, $fp);
1328       else
1329         $body = iil_C_HandlePartBody($this->conn, $this->mailbox, $msg_id, $part, 1);
8d4bcd 1330
T 1331       // decode part body
a9cc52 1332       if ($o_part->encoding)
8d4bcd 1333         $body = $this->mime_decode($body, $o_part->encoding);
T 1334
1335       // convert charset (if text or message part)
f7bfec 1336       if ($o_part->ctype_primary=='text' || $o_part->ctype_primary=='message')
T 1337         {
17b5fb 1338         // assume default if no charset specified
f7bfec 1339         if (empty($o_part->charset))
17b5fb 1340           $o_part->charset = $this->default_charset;
f7bfec 1341
8d4bcd 1342         $body = rcube_charset_convert($body, $o_part->charset);
f7bfec 1343         }
81b573 1344       
A 1345       if ($fp)
1346         {
1347         fwrite($fp, $body);
42e328 1348         return true;
81b573 1349         }
8d4bcd 1350       }
81b573 1351     
4e17e6 1352     return $body;
T 1353     }
1354
1355
8d4bcd 1356   /**
T 1357    * Fetch message body of a specific message from the server
1358    *
1359    * @param  int    Message UID
6d969b 1360    * @return string Message/part body
T 1361    * @see    rcube_imap::get_message_part()
8d4bcd 1362    */
T 1363   function &get_body($uid, $part=1)
1364     {
0a9989 1365     $headers = $this->get_headers($uid);
T 1366     return rcube_charset_convert(
1367       $this->mime_decode($this->get_message_part($uid, $part), 'quoted-printable'),
1368       $headers->charset ? $headers->charset : $this->default_charset);
8d4bcd 1369     }
T 1370
1371
1372   /**
1373    * Returns the whole message source as string
1374    *
1375    * @param int  Message UID
6d969b 1376    * @return string Message source string
8d4bcd 1377    */
T 1378   function &get_raw_body($uid)
4e17e6 1379     {
T 1380     if (!($msg_id = $this->_uid2id($uid)))
1381       return FALSE;
1382
6d969b 1383     $body = iil_C_FetchPartHeader($this->conn, $this->mailbox, $msg_id, NULL);
T 1384     $body .= iil_C_HandlePartBody($this->conn, $this->mailbox, $msg_id, NULL, 1);
4e17e6 1385
T 1386     return $body;    
1387     }
e5686f 1388
A 1389
1390   /**
1391    * Returns the message headers as string
1392    *
1393    * @param int  Message UID
1394    * @return string Message headers string
1395    */
1396   function &get_raw_headers($uid)
1397     {
1398     if (!($msg_id = $this->_uid2id($uid)))
1399       return FALSE;
1400
1401     $headers = iil_C_FetchPartHeader($this->conn, $this->mailbox, $msg_id, NULL);
1402
1403     return $headers;    
1404     }
8d4bcd 1405     
T 1406
1407   /**
1408    * Sends the whole message source to stdout
1409    *
1410    * @param int  Message UID
1411    */ 
1412   function print_raw_body($uid)
1413     {
1414     if (!($msg_id = $this->_uid2id($uid)))
1415       return FALSE;
1416
6d969b 1417     print iil_C_FetchPartHeader($this->conn, $this->mailbox, $msg_id, NULL);
T 1418     flush();
1419     iil_C_HandlePartBody($this->conn, $this->mailbox, $msg_id, NULL, 2);
8d4bcd 1420     }
4e17e6 1421
T 1422
8d4bcd 1423   /**
T 1424    * Set message flag to one or several messages
1425    *
1426    * @param mixed  Message UIDs as array or as comma-separated string
ed5407 1427    * @param string Flag to set: SEEN, UNDELETED, DELETED, RECENT, ANSWERED, DRAFT, MDNSENT
6d969b 1428    * @return boolean True on success, False on failure
8d4bcd 1429    */
4e17e6 1430   function set_flag($uids, $flag)
T 1431     {
1432     $flag = strtoupper($flag);
1433     $msg_ids = array();
1434     if (!is_array($uids))
8fae1e 1435       $uids = explode(',',$uids);
4e17e6 1436       
8fae1e 1437     foreach ($uids as $uid) {
31b2ce 1438       $msg_ids[$uid] = $this->_uid2id($uid);
8fae1e 1439     }
4e17e6 1440       
8fae1e 1441     if ($flag=='UNDELETED')
S 1442       $result = iil_C_Undelete($this->conn, $this->mailbox, join(',', array_values($msg_ids)));
1443     else if ($flag=='UNSEEN')
31b2ce 1444       $result = iil_C_Unseen($this->conn, $this->mailbox, join(',', array_values($msg_ids)));
e189a6 1445     else if ($flag=='UNFLAGGED')
A 1446       $result = iil_C_UnFlag($this->conn, $this->mailbox, join(',', array_values($msg_ids)), 'FLAGGED');
4e17e6 1447     else
31b2ce 1448       $result = iil_C_Flag($this->conn, $this->mailbox, join(',', array_values($msg_ids)), $flag);
4e17e6 1449
T 1450     // reload message headers if cached
1451     $cache_key = $this->mailbox.'.msg';
1cded8 1452     if ($this->caching_enabled)
4e17e6 1453       {
31b2ce 1454       foreach ($msg_ids as $uid => $id)
4e17e6 1455         {
31b2ce 1456         if ($cached_headers = $this->get_cached_message($cache_key, $uid))
4e17e6 1457           {
1cded8 1458           $this->remove_message_cache($cache_key, $id);
T 1459           //$this->get_headers($uid);
4e17e6 1460           }
T 1461         }
1cded8 1462
T 1463       // close and re-open connection
1464       // this prevents connection problems with Courier 
1465       $this->reconnect();
4e17e6 1466       }
T 1467
1468     // set nr of messages that were flaged
31b2ce 1469     $count = count($msg_ids);
4e17e6 1470
T 1471     // clear message count cache
1472     if ($result && $flag=='SEEN')
1473       $this->_set_messagecount($this->mailbox, 'UNSEEN', $count*(-1));
1474     else if ($result && $flag=='UNSEEN')
1475       $this->_set_messagecount($this->mailbox, 'UNSEEN', $count);
1476     else if ($result && $flag=='DELETED')
1477       $this->_set_messagecount($this->mailbox, 'ALL', $count*(-1));
1478
1479     return $result;
1480     }
1481
1482
6d969b 1483   /**
T 1484    * Append a mail message (source) to a specific mailbox
1485    *
1486    * @param string Target mailbox
1487    * @param string Message source
1488    * @return boolean True on success, False on error
1489    */
b068a0 1490   function save_message($mbox_name, &$message)
4e17e6 1491     {
a894ba 1492     $mbox_name = stripslashes($mbox_name);
aadfa1 1493     $mailbox = $this->_mod_mailbox($mbox_name);
4e17e6 1494
f88d41 1495     // make sure mailbox exists
4e17e6 1496     if (in_array($mailbox, $this->_list_mailboxes()))
T 1497       $saved = iil_C_Append($this->conn, $mailbox, $message);
1cded8 1498
4e17e6 1499     if ($saved)
T 1500       {
1501       // increase messagecount of the target mailbox
1502       $this->_set_messagecount($mailbox, 'ALL', 1);
1503       }
1504           
1505     return $saved;
1506     }
1507
1508
6d969b 1509   /**
T 1510    * Move a message from one mailbox to another
1511    *
1512    * @param string List of UIDs to move, separated by comma
1513    * @param string Target mailbox
1514    * @param string Source mailbox
1515    * @return boolean True on success, False on error
1516    */
4e17e6 1517   function move_message($uids, $to_mbox, $from_mbox='')
T 1518     {
a05793 1519     $to_mbox_in = stripslashes($to_mbox);
a894ba 1520     $from_mbox = stripslashes($from_mbox);
a05793 1521     $to_mbox = $this->_mod_mailbox($to_mbox_in);
4e17e6 1522     $from_mbox = $from_mbox ? $this->_mod_mailbox($from_mbox) : $this->mailbox;
T 1523
f88d41 1524     // make sure mailbox exists
4e17e6 1525     if (!in_array($to_mbox, $this->_list_mailboxes()))
f88d41 1526       {
a05793 1527       if (in_array($to_mbox_in, $this->default_folders))
T 1528         $this->create_mailbox($to_mbox_in, TRUE);
f88d41 1529       else
T 1530         return FALSE;
1531       }
1532
4e17e6 1533     // convert the list of uids to array
T 1534     $a_uids = is_string($uids) ? explode(',', $uids) : (is_array($uids) ? $uids : NULL);
1535     
1536     // exit if no message uids are specified
1537     if (!is_array($a_uids))
1538       return false;
520c36 1539
4e17e6 1540     // convert uids to message ids
T 1541     $a_mids = array();
1542     foreach ($a_uids as $uid)
1543       $a_mids[] = $this->_uid2id($uid, $from_mbox);
520c36 1544
4379bb 1545     $iil_move = iil_C_Move($this->conn, join(',', $a_mids), $from_mbox, $to_mbox);
T 1546     $moved = !($iil_move === false || $iil_move < 0);
4e17e6 1547     
T 1548     // send expunge command in order to have the moved message
1549     // really deleted from the source mailbox
bf0cb9 1550     if ($moved) {
d87fc2 1551       // but only when flag_for_deletion is set to false
A 1552       if (!rcmail::get_instance()->config->get('flag_for_deletion', false))
1553         {
1554         $this->_expunge($from_mbox, FALSE);
1555         $this->_clear_messagecount($from_mbox);
1556         $this->_clear_messagecount($to_mbox);
1557         }
bf0cb9 1558     }
T 1559     // moving failed
1560     else if (rcmail::get_instance()->config->get('delete_always', false)) {
1561       return iil_C_Delete($this->conn, $from_mbox, join(',', $a_mids));
1562     }
04c618 1563       
T 1564     // remove message ids from search set
1565     if ($moved && $this->search_set && $from_mbox == $this->mailbox)
1566       $this->search_set = array_diff($this->search_set, $a_mids);
4e17e6 1567
T 1568     // update cached message headers
1569     $cache_key = $from_mbox.'.msg';
1cded8 1570     if ($moved && ($a_cache_index = $this->get_message_cache_index($cache_key)))
4e17e6 1571       {
1cded8 1572       $start_index = 100000;
4e17e6 1573       foreach ($a_uids as $uid)
1cded8 1574         {
04c618 1575         if (($index = array_search($uid, $a_cache_index)) !== FALSE)
T 1576           $start_index = min($index, $start_index);
1cded8 1577         }
4e17e6 1578
1cded8 1579       // clear cache from the lowest index on
T 1580       $this->clear_message_cache($cache_key, $start_index);
4e17e6 1581       }
T 1582
1583     return $moved;
1584     }
1585
1586
6d969b 1587   /**
T 1588    * Mark messages as deleted and expunge mailbox
1589    *
1590    * @param string List of UIDs to move, separated by comma
1591    * @param string Source mailbox
1592    * @return boolean True on success, False on error
1593    */
aadfa1 1594   function delete_message($uids, $mbox_name='')
4e17e6 1595     {
a894ba 1596     $mbox_name = stripslashes($mbox_name);
aadfa1 1597     $mailbox = $mbox_name ? $this->_mod_mailbox($mbox_name) : $this->mailbox;
4e17e6 1598
T 1599     // convert the list of uids to array
1600     $a_uids = is_string($uids) ? explode(',', $uids) : (is_array($uids) ? $uids : NULL);
1601     
1602     // exit if no message uids are specified
1603     if (!is_array($a_uids))
1604       return false;
1605
1606     // convert uids to message ids
1607     $a_mids = array();
1608     foreach ($a_uids as $uid)
1609       $a_mids[] = $this->_uid2id($uid, $mailbox);
1610         
1611     $deleted = iil_C_Delete($this->conn, $mailbox, join(',', $a_mids));
1612     
1613     // send expunge command in order to have the deleted message
1614     // really deleted from the mailbox
1615     if ($deleted)
1616       {
1cded8 1617       $this->_expunge($mailbox, FALSE);
4e17e6 1618       $this->_clear_messagecount($mailbox);
c719f3 1619       unset($this->uid_id_map[$mailbox]);
4e17e6 1620       }
T 1621
04c618 1622     // remove message ids from search set
077070 1623     if ($deleted && $this->search_set && $mailbox == $this->mailbox)
04c618 1624       $this->search_set = array_diff($this->search_set, $a_mids);
T 1625
4e17e6 1626     // remove deleted messages from cache
1cded8 1627     $cache_key = $mailbox.'.msg';
T 1628     if ($deleted && ($a_cache_index = $this->get_message_cache_index($cache_key)))
4e17e6 1629       {
1cded8 1630       $start_index = 100000;
4e17e6 1631       foreach ($a_uids as $uid)
1cded8 1632         {
6ce04b 1633         if (($index = array_search($uid, $a_cache_index)) !== FALSE)
S 1634           $start_index = min($index, $start_index);
1cded8 1635         }
4e17e6 1636
1cded8 1637       // clear cache from the lowest index on
T 1638       $this->clear_message_cache($cache_key, $start_index);
4e17e6 1639       }
T 1640
1641     return $deleted;
1642     }
1643
1644
6d969b 1645   /**
T 1646    * Clear all messages in a specific mailbox
1647    *
1648    * @param string Mailbox name
1649    * @return int Above 0 on success
1650    */
aadfa1 1651   function clear_mailbox($mbox_name=NULL)
a95e0e 1652     {
a894ba 1653     $mbox_name = stripslashes($mbox_name);
aadfa1 1654     $mailbox = !empty($mbox_name) ? $this->_mod_mailbox($mbox_name) : $this->mailbox;
a95e0e 1655     $msg_count = $this->_messagecount($mailbox, 'ALL');
T 1656     
1657     if ($msg_count>0)
1cded8 1658       {
5e3512 1659       $cleared = iil_C_ClearFolder($this->conn, $mailbox);
T 1660       
1661       // make sure the message count cache is cleared as well
1662       if ($cleared)
1663         {
1664         $this->clear_message_cache($mailbox.'.msg');      
1665         $a_mailbox_cache = $this->get_cache('messagecount');
1666         unset($a_mailbox_cache[$mailbox]);
1667         $this->update_cache('messagecount', $a_mailbox_cache);
1668         }
1669         
1670       return $cleared;
1cded8 1671       }
a95e0e 1672     else
T 1673       return 0;
1674     }
1675
1676
6d969b 1677   /**
T 1678    * Send IMAP expunge command and clear cache
1679    *
1680    * @param string Mailbox name
1681    * @param boolean False if cache should not be cleared
1682    * @return boolean True on success
1683    */
aadfa1 1684   function expunge($mbox_name='', $clear_cache=TRUE)
4e17e6 1685     {
a894ba 1686     $mbox_name = stripslashes($mbox_name);
aadfa1 1687     $mailbox = $mbox_name ? $this->_mod_mailbox($mbox_name) : $this->mailbox;
1cded8 1688     return $this->_expunge($mailbox, $clear_cache);
T 1689     }
1690
1691
6d969b 1692   /**
T 1693    * Send IMAP expunge command and clear cache
1694    *
1695    * @see rcube_imap::expunge()
1696    * @access private
1697    */
1cded8 1698   function _expunge($mailbox, $clear_cache=TRUE)
T 1699     {
4e17e6 1700     $result = iil_C_Expunge($this->conn, $mailbox);
T 1701
1702     if ($result>=0 && $clear_cache)
1703       {
5c69aa 1704       $this->clear_message_cache($mailbox.'.msg');
4e17e6 1705       $this->_clear_messagecount($mailbox);
T 1706       }
1707       
1708     return $result;
1709     }
1710
1711
1712   /* --------------------------------
1713    *        folder managment
1714    * --------------------------------*/
1715
1716
fa4cd2 1717   /**
T 1718    * Get a list of all folders available on the IMAP server
1719    * 
1720    * @param string IMAP root dir
6d969b 1721    * @return array Indexed array with folder names
fa4cd2 1722    */
4e17e6 1723   function list_unsubscribed($root='')
T 1724     {
1725     static $sa_unsubscribed;
1726     
1727     if (is_array($sa_unsubscribed))
1728       return $sa_unsubscribed;
1729       
1730     // retrieve list of folders from IMAP server
1731     $a_mboxes = iil_C_ListMailboxes($this->conn, $this->_mod_mailbox($root), '*');
1732
1733     // modify names with root dir
aadfa1 1734     foreach ($a_mboxes as $mbox_name)
4e17e6 1735       {
aadfa1 1736       $name = $this->_mod_mailbox($mbox_name, 'out');
4e17e6 1737       if (strlen($name))
T 1738         $a_folders[] = $name;
1739       }
1740
1741     // filter folders and sort them
1742     $sa_unsubscribed = $this->_sort_mailbox_list($a_folders);
1743     return $sa_unsubscribed;
1744     }
1745
1746
58e360 1747   /**
6d969b 1748    * Get mailbox quota information
58e360 1749    * added by Nuny
6d969b 1750    * 
T 1751    * @return mixed Quota info or False if not supported
58e360 1752    */
T 1753   function get_quota()
1754     {
1755     if ($this->get_capability('QUOTA'))
fda695 1756       return iil_C_GetQuota($this->conn);
3ea0e3 1757     
4647e1 1758     return FALSE;
58e360 1759     }
T 1760
1761
fa4cd2 1762   /**
6d969b 1763    * Subscribe to a specific mailbox(es)
T 1764    *
c5097c 1765    * @param array Mailbox name(s)
6d969b 1766    * @return boolean True on success
fa4cd2 1767    */ 
c5097c 1768   function subscribe($a_mboxes)
4e17e6 1769     {
c5097c 1770     if (!is_array($a_mboxes))
A 1771       $a_mboxes = array($a_mboxes);
1772
4e17e6 1773     // let this common function do the main work
T 1774     return $this->_change_subscription($a_mboxes, 'subscribe');
1775     }
1776
1777
fa4cd2 1778   /**
6d969b 1779    * Unsubscribe mailboxes
T 1780    *
c5097c 1781    * @param array Mailbox name(s)
6d969b 1782    * @return boolean True on success
fa4cd2 1783    */
c5097c 1784   function unsubscribe($a_mboxes)
4e17e6 1785     {
c5097c 1786     if (!is_array($a_mboxes))
A 1787       $a_mboxes = array($a_mboxes);
4e17e6 1788
T 1789     // let this common function do the main work
1790     return $this->_change_subscription($a_mboxes, 'unsubscribe');
1791     }
1792
1793
fa4cd2 1794   /**
4d4264 1795    * Create a new mailbox on the server and register it in local cache
T 1796    *
1797    * @param string  New mailbox name (as utf-7 string)
1798    * @param boolean True if the new mailbox should be subscribed
1799    * @param string  Name of the created mailbox, false on error
fa4cd2 1800    */
4e17e6 1801   function create_mailbox($name, $subscribe=FALSE)
T 1802     {
1803     $result = FALSE;
1cded8 1804     
T 1805     // replace backslashes
1806     $name = preg_replace('/[\\\]+/', '-', $name);
1807
1808     // reduce mailbox name to 100 chars
4d4264 1809     $name = substr($name, 0, 100);
1cded8 1810
4d4264 1811     $abs_name = $this->_mod_mailbox($name);
4e17e6 1812     $a_mailbox_cache = $this->get_cache('mailboxes');
fa4cd2 1813
719a25 1814     if (strlen($abs_name) && (!is_array($a_mailbox_cache) || !in_array($abs_name, $a_mailbox_cache)))
a95e0e 1815       $result = iil_C_CreateFolder($this->conn, $abs_name);
4e17e6 1816
fa4cd2 1817     // try to subscribe it
719a25 1818     if ($result && $subscribe)
4d4264 1819       $this->subscribe($name);
4e17e6 1820
7902df 1821     return $result ? $name : FALSE;
4e17e6 1822     }
T 1823
1824
fa4cd2 1825   /**
4d4264 1826    * Set a new name to an existing mailbox
T 1827    *
1828    * @param string Mailbox to rename (as utf-7 string)
1829    * @param string New mailbox name (as utf-7 string)
6d969b 1830    * @return string Name of the renames mailbox, False on error
fa4cd2 1831    */
f9c107 1832   function rename_mailbox($mbox_name, $new_name)
4e17e6 1833     {
c8c1e0 1834     $result = FALSE;
S 1835
1836     // replace backslashes
1837     $name = preg_replace('/[\\\]+/', '-', $new_name);
f9c107 1838         
T 1839     // encode mailbox name and reduce it to 100 chars
4d4264 1840     $name = substr($new_name, 0, 100);
c8c1e0 1841
f9c107 1842     // make absolute path
T 1843     $mailbox = $this->_mod_mailbox($mbox_name);
4d4264 1844     $abs_name = $this->_mod_mailbox($name);
f7bfec 1845     
T 1846     // check if mailbox is subscribed
1847     $a_subscribed = $this->_list_mailboxes();
1848     $subscribed = in_array($mailbox, $a_subscribed);
1849     
1850     // unsubscribe folder
1851     if ($subscribed)
1852       iil_C_UnSubscribe($this->conn, $mailbox);
4d4264 1853
f9c107 1854     if (strlen($abs_name))
T 1855       $result = iil_C_RenameFolder($this->conn, $mailbox, $abs_name);
4d4264 1856
f9c107 1857     if ($result)
T 1858       {
574564 1859       $delm = $this->get_hierarchy_delimiter();
T 1860       
1861       // check if mailbox children are subscribed
1862       foreach ($a_subscribed as $c_subscribed)
1863         if (preg_match('/^'.preg_quote($mailbox.$delm, '/').'/', $c_subscribed))
1864           {
1865           iil_C_UnSubscribe($this->conn, $c_subscribed);
1866           iil_C_Subscribe($this->conn, preg_replace('/^'.preg_quote($mailbox, '/').'/', $abs_name, $c_subscribed));
1867           }
1868
1869       // clear cache
f9c107 1870       $this->clear_message_cache($mailbox.'.msg');
f7bfec 1871       $this->clear_cache('mailboxes');      
f9c107 1872       }
f7bfec 1873
4d4264 1874     // try to subscribe it
f7bfec 1875     if ($result && $subscribed)
T 1876       iil_C_Subscribe($this->conn, $abs_name);
c8c1e0 1877
S 1878     return $result ? $name : FALSE;
4e17e6 1879     }
T 1880
1881
fa4cd2 1882   /**
6d969b 1883    * Remove mailboxes from server
T 1884    *
1885    * @param string Mailbox name
1886    * @return boolean True on success
fa4cd2 1887    */
aadfa1 1888   function delete_mailbox($mbox_name)
4e17e6 1889     {
T 1890     $deleted = FALSE;
1891
aadfa1 1892     if (is_array($mbox_name))
S 1893       $a_mboxes = $mbox_name;
1894     else if (is_string($mbox_name) && strlen($mbox_name))
1895       $a_mboxes = explode(',', $mbox_name);
4e17e6 1896
97a656 1897     $all_mboxes = iil_C_ListMailboxes($this->conn, $this->_mod_mailbox($root), '*');
S 1898
4e17e6 1899     if (is_array($a_mboxes))
aadfa1 1900       foreach ($a_mboxes as $mbox_name)
4e17e6 1901         {
aadfa1 1902         $mailbox = $this->_mod_mailbox($mbox_name);
4e17e6 1903
T 1904         // unsubscribe mailbox before deleting
1905         iil_C_UnSubscribe($this->conn, $mailbox);
fa4cd2 1906
4e17e6 1907         // send delete command to server
T 1908         $result = iil_C_DeleteFolder($this->conn, $mailbox);
1909         if ($result>=0)
1910           $deleted = TRUE;
97a656 1911
S 1912         foreach ($all_mboxes as $c_mbox)
fa0152 1913           {
T 1914           $regex = preg_quote($mailbox . $this->delimiter, '/');
1915           $regex = '/^' . $regex . '/';
1916           if (preg_match($regex, $c_mbox))
97a656 1917             {
S 1918             iil_C_UnSubscribe($this->conn, $c_mbox);
1919             $result = iil_C_DeleteFolder($this->conn, $c_mbox);
1920             if ($result>=0)
1921               $deleted = TRUE;
1922             }
fa0152 1923           }
4e17e6 1924         }
T 1925
1926     // clear mailboxlist cache
1927     if ($deleted)
1cded8 1928       {
T 1929       $this->clear_message_cache($mailbox.'.msg');
4e17e6 1930       $this->clear_cache('mailboxes');
1cded8 1931       }
4e17e6 1932
1cded8 1933     return $deleted;
4e17e6 1934     }
T 1935
fa4cd2 1936
T 1937   /**
1938    * Create all folders specified as default
1939    */
1940   function create_default_folders()
1941     {
1942     $a_folders = iil_C_ListMailboxes($this->conn, $this->_mod_mailbox(''), '*');
1943     $a_subscribed = iil_C_ListSubscribed($this->conn, $this->_mod_mailbox(''), '*');
1944     
1945     // create default folders if they do not exist
1946     foreach ($this->default_folders as $folder)
1947       {
1948       $abs_name = $this->_mod_mailbox($folder);
719a25 1949       if (!in_array_nocase($abs_name, $a_folders))
T 1950         $this->create_mailbox($folder, TRUE);
1951       else if (!in_array_nocase($abs_name, $a_subscribed))
1952         $this->subscribe($folder);
fa4cd2 1953       }
T 1954     }
4e17e6 1955
T 1956
1957
1958   /* --------------------------------
1cded8 1959    *   internal caching methods
4e17e6 1960    * --------------------------------*/
6dc026 1961
6d969b 1962   /**
T 1963    * @access private
1964    */
6dc026 1965   function set_caching($set)
T 1966     {
1cded8 1967     if ($set && is_object($this->db))
6dc026 1968       $this->caching_enabled = TRUE;
T 1969     else
1970       $this->caching_enabled = FALSE;
1971     }
1cded8 1972
6d969b 1973   /**
T 1974    * @access private
1975    */
4e17e6 1976   function get_cache($key)
T 1977     {
1978     // read cache
6dc026 1979     if (!isset($this->cache[$key]) && $this->caching_enabled)
4e17e6 1980       {
1cded8 1981       $cache_data = $this->_read_cache_record('IMAP.'.$key);
4e17e6 1982       $this->cache[$key] = strlen($cache_data) ? unserialize($cache_data) : FALSE;
T 1983       }
1984     
1cded8 1985     return $this->cache[$key];
4e17e6 1986     }
T 1987
6d969b 1988   /**
T 1989    * @access private
1990    */
4e17e6 1991   function update_cache($key, $data)
T 1992     {
1993     $this->cache[$key] = $data;
1994     $this->cache_changed = TRUE;
1995     $this->cache_changes[$key] = TRUE;
1996     }
1997
6d969b 1998   /**
T 1999    * @access private
2000    */
4e17e6 2001   function write_cache()
T 2002     {
6dc026 2003     if ($this->caching_enabled && $this->cache_changed)
4e17e6 2004       {
T 2005       foreach ($this->cache as $key => $data)
2006         {
2007         if ($this->cache_changes[$key])
1cded8 2008           $this->_write_cache_record('IMAP.'.$key, serialize($data));
4e17e6 2009         }
T 2010       }    
2011     }
2012
6d969b 2013   /**
T 2014    * @access private
2015    */
4e17e6 2016   function clear_cache($key=NULL)
T 2017     {
fc2312 2018     if (!$this->caching_enabled)
A 2019       return;
2020     
4e17e6 2021     if ($key===NULL)
T 2022       {
2023       foreach ($this->cache as $key => $data)
1cded8 2024         $this->_clear_cache_record('IMAP.'.$key);
4e17e6 2025
T 2026       $this->cache = array();
2027       $this->cache_changed = FALSE;
2028       $this->cache_changes = array();
2029       }
2030     else
2031       {
1cded8 2032       $this->_clear_cache_record('IMAP.'.$key);
4e17e6 2033       $this->cache_changes[$key] = FALSE;
T 2034       unset($this->cache[$key]);
2035       }
2036     }
2037
6d969b 2038   /**
T 2039    * @access private
2040    */
1cded8 2041   function _read_cache_record($key)
T 2042     {
2043     $cache_data = FALSE;
2044     
2045     if ($this->db)
2046       {
2047       // get cached data from DB
2048       $sql_result = $this->db->query(
2049         "SELECT cache_id, data
2050          FROM ".get_table_name('cache')."
2051          WHERE  user_id=?
2052          AND    cache_key=?",
2053         $_SESSION['user_id'],
2054         $key);
2055
2056       if ($sql_arr = $this->db->fetch_assoc($sql_result))
2057         {
2058         $cache_data = $sql_arr['data'];
2059         $this->cache_keys[$key] = $sql_arr['cache_id'];
2060         }
2061       }
2062
6d969b 2063     return $cache_data;
1cded8 2064     }
T 2065
6d969b 2066   /**
T 2067    * @access private
2068    */
1cded8 2069   function _write_cache_record($key, $data)
T 2070     {
2071     if (!$this->db)
2072       return FALSE;
2073
2074     // check if we already have a cache entry for this key
2075     if (!isset($this->cache_keys[$key]))
2076       {
2077       $sql_result = $this->db->query(
2078         "SELECT cache_id
2079          FROM ".get_table_name('cache')."
2080          WHERE  user_id=?
2081          AND    cache_key=?",
2082         $_SESSION['user_id'],
2083         $key);
2084                                      
2085       if ($sql_arr = $this->db->fetch_assoc($sql_result))
2086         $this->cache_keys[$key] = $sql_arr['cache_id'];
2087       else
2088         $this->cache_keys[$key] = FALSE;
2089       }
2090
2091     // update existing cache record
2092     if ($this->cache_keys[$key])
2093       {
2094       $this->db->query(
2095         "UPDATE ".get_table_name('cache')."
107bde 2096          SET    created=".$this->db->now().",
1cded8 2097                 data=?
T 2098          WHERE  user_id=?
2099          AND    cache_key=?",
2100         $data,
2101         $_SESSION['user_id'],
2102         $key);
2103       }
2104     // add new cache record
2105     else
2106       {
2107       $this->db->query(
2108         "INSERT INTO ".get_table_name('cache')."
2109          (created, user_id, cache_key, data)
107bde 2110          VALUES (".$this->db->now().", ?, ?, ?)",
1cded8 2111         $_SESSION['user_id'],
T 2112         $key,
2113         $data);
2114       }
2115     }
2116
6d969b 2117   /**
T 2118    * @access private
2119    */
1cded8 2120   function _clear_cache_record($key)
T 2121     {
2122     $this->db->query(
2123       "DELETE FROM ".get_table_name('cache')."
2124        WHERE  user_id=?
2125        AND    cache_key=?",
2126       $_SESSION['user_id'],
2127       $key);
2128     }
2129
2130
2131
4e17e6 2132   /* --------------------------------
1cded8 2133    *   message caching methods
T 2134    * --------------------------------*/
2135    
2136
6d969b 2137   /**
T 2138    * Checks if the cache is up-to-date
2139    *
2140    * @param string Mailbox name
2141    * @param string Internal cache key
2142    * @return int -3 = off, -2 = incomplete, -1 = dirty
2143    */
1cded8 2144   function check_cache_status($mailbox, $cache_key)
T 2145     {
2146     if (!$this->caching_enabled)
2147       return -3;
2148
2149     $cache_index = $this->get_message_cache_index($cache_key, TRUE);
2150     $msg_count = $this->_messagecount($mailbox);
2151     $cache_count = count($cache_index);
2152
2153     // console("Cache check: $msg_count !== ".count($cache_index));
2154
2155     if ($cache_count==$msg_count)
2156       {
2157       // get highest index
2158       $header = iil_C_FetchHeader($this->conn, $mailbox, "$msg_count");
2159       $cache_uid = array_pop($cache_index);
2160       
e6f360 2161       // uids of highest message matches -> cache seems OK
1cded8 2162       if ($cache_uid == $header->uid)
T 2163         return 1;
2164
2165       // cache is dirty
2166       return -1;
2167       }
e6f360 2168     // if cache count differs less than 10% report as dirty
1cded8 2169     else if (abs($msg_count - $cache_count) < $msg_count/10)
T 2170       return -1;
2171     else
2172       return -2;
2173     }
2174
6d969b 2175   /**
T 2176    * @access private
2177    */
1cded8 2178   function get_message_cache($key, $from, $to, $sort_field, $sort_order)
T 2179     {
2180     $cache_key = "$key:$from:$to:$sort_field:$sort_order";
2181     $db_header_fields = array('idx', 'uid', 'subject', 'from', 'to', 'cc', 'date', 'size');
2182     
2183     if (!in_array($sort_field, $db_header_fields))
2184       $sort_field = 'idx';
2185     
2186     if ($this->caching_enabled && !isset($this->cache[$cache_key]))
2187       {
2188       $this->cache[$cache_key] = array();
2189       $sql_result = $this->db->limitquery(
2190         "SELECT idx, uid, headers
2191          FROM ".get_table_name('messages')."
2192          WHERE  user_id=?
2193          AND    cache_key=?
2194          ORDER BY ".$this->db->quoteIdentifier($sort_field)." ".
2195          strtoupper($sort_order),
2196         $from,
2197         $to-$from,
2198         $_SESSION['user_id'],
2199         $key);
2200
2201       while ($sql_arr = $this->db->fetch_assoc($sql_result))
2202         {
2203         $uid = $sql_arr['uid'];
2204         $this->cache[$cache_key][$uid] = unserialize($sql_arr['headers']);
ecd2e7 2205         
T 2206         // featch headers if unserialize failed
2207         if (empty($this->cache[$cache_key][$uid]))
2208           $this->cache[$cache_key][$uid] = iil_C_FetchHeader($this->conn, preg_replace('/.msg$/', '', $key), $uid, true);
1cded8 2209         }
T 2210       }
2211       
2212     return $this->cache[$cache_key];
2213     }
2214
6d969b 2215   /**
T 2216    * @access private
2217    */
f7bfec 2218   function &get_cached_message($key, $uid, $struct=false)
1cded8 2219     {
T 2220     $internal_key = '__single_msg';
017def 2221     
f7bfec 2222     if ($this->caching_enabled && (!isset($this->cache[$internal_key][$uid]) ||
T 2223         ($struct && empty($this->cache[$internal_key][$uid]->structure))))
1cded8 2224       {
f7bfec 2225       $sql_select = "idx, uid, headers" . ($struct ? ", structure" : '');
1cded8 2226       $sql_result = $this->db->query(
T 2227         "SELECT $sql_select
2228          FROM ".get_table_name('messages')."
2229          WHERE  user_id=?
2230          AND    cache_key=?
2231          AND    uid=?",
2232         $_SESSION['user_id'],
2233         $key,
2234         $uid);
f7bfec 2235
1cded8 2236       if ($sql_arr = $this->db->fetch_assoc($sql_result))
T 2237         {
f7bfec 2238         $this->cache[$internal_key][$uid] = unserialize($sql_arr['headers']);
T 2239         if (is_object($this->cache[$internal_key][$uid]) && !empty($sql_arr['structure']))
2240           $this->cache[$internal_key][$uid]->structure = unserialize($sql_arr['structure']);
1cded8 2241         }
T 2242       }
2243
2244     return $this->cache[$internal_key][$uid];
2245     }
2246
6d969b 2247   /**
T 2248    * @access private
2249    */  
0677ca 2250   function get_message_cache_index($key, $force=FALSE, $sort_col='idx', $sort_order='ASC')
1cded8 2251     {
T 2252     static $sa_message_index = array();
2253     
4647e1 2254     // empty key -> empty array
ffb0b0 2255     if (!$this->caching_enabled || empty($key))
4647e1 2256       return array();
T 2257     
1cded8 2258     if (!empty($sa_message_index[$key]) && !$force)
T 2259       return $sa_message_index[$key];
2260     
2261     $sa_message_index[$key] = array();
2262     $sql_result = $this->db->query(
2263       "SELECT idx, uid
2264        FROM ".get_table_name('messages')."
2265        WHERE  user_id=?
2266        AND    cache_key=?
0677ca 2267        ORDER BY ".$this->db->quote_identifier($sort_col)." ".$sort_order,
1cded8 2268       $_SESSION['user_id'],
T 2269       $key);
2270
2271     while ($sql_arr = $this->db->fetch_assoc($sql_result))
2272       $sa_message_index[$key][$sql_arr['idx']] = $sql_arr['uid'];
2273       
2274     return $sa_message_index[$key];
2275     }
2276
6d969b 2277   /**
T 2278    * @access private
2279    */
f7bfec 2280   function add_message_cache($key, $index, $headers, $struct=null)
1cded8 2281     {
017def 2282     if (empty($key) || !is_object($headers) || empty($headers->uid))
T 2283         return;
2284     
2285     // add to internal (fast) cache
2286     $this->cache['__single_msg'][$headers->uid] = $headers;
2287     $this->cache['__single_msg'][$headers->uid]->structure = $struct;
2288     
2289     // no further caching
2290     if (!$this->caching_enabled)
31b2ce 2291       return;
017def 2292     
f7bfec 2293     // check for an existing record (probly headers are cached but structure not)
T 2294     $sql_result = $this->db->query(
2295         "SELECT message_id
2296          FROM ".get_table_name('messages')."
2297          WHERE  user_id=?
2298          AND    cache_key=?
2299          AND    uid=?
2300          AND    del<>1",
2301         $_SESSION['user_id'],
2302         $key,
2303         $headers->uid);
31b2ce 2304
f7bfec 2305     // update cache record
T 2306     if ($sql_arr = $this->db->fetch_assoc($sql_result))
2307       {
2308       $this->db->query(
2309         "UPDATE ".get_table_name('messages')."
2310          SET   idx=?, headers=?, structure=?
2311          WHERE message_id=?",
2312         $index,
2313         serialize($headers),
2314         is_object($struct) ? serialize($struct) : NULL,
2315         $sql_arr['message_id']
2316         );
2317       }
2318     else  // insert new record
2319       {
2320       $this->db->query(
2321         "INSERT INTO ".get_table_name('messages')."
2322          (user_id, del, cache_key, created, idx, uid, subject, ".$this->db->quoteIdentifier('from').", ".$this->db->quoteIdentifier('to').", cc, date, size, headers, structure)
107bde 2323          VALUES (?, 0, ?, ".$this->db->now().", ?, ?, ?, ?, ?, ?, ".$this->db->fromunixtime($headers->timestamp).", ?, ?, ?)",
f7bfec 2324         $_SESSION['user_id'],
T 2325         $key,
2326         $index,
2327         $headers->uid,
2328         (string)substr($this->decode_header($headers->subject, TRUE), 0, 128),
2329         (string)substr($this->decode_header($headers->from, TRUE), 0, 128),
2330         (string)substr($this->decode_header($headers->to, TRUE), 0, 128),
2331         (string)substr($this->decode_header($headers->cc, TRUE), 0, 128),
2332         (int)$headers->size,
2333         serialize($headers),
2334         is_object($struct) ? serialize($struct) : NULL
2335         );
2336       }
1cded8 2337     }
T 2338     
6d969b 2339   /**
T 2340    * @access private
2341    */
1cded8 2342   function remove_message_cache($key, $index)
T 2343     {
780527 2344     if (!$this->caching_enabled)
T 2345       return;
2346     
1cded8 2347     $this->db->query(
T 2348       "DELETE FROM ".get_table_name('messages')."
2349        WHERE  user_id=?
2350        AND    cache_key=?
2351        AND    idx=?",
2352       $_SESSION['user_id'],
2353       $key,
2354       $index);
2355     }
2356
6d969b 2357   /**
T 2358    * @access private
2359    */
1cded8 2360   function clear_message_cache($key, $start_index=1)
T 2361     {
780527 2362     if (!$this->caching_enabled)
T 2363       return;
2364     
1cded8 2365     $this->db->query(
T 2366       "DELETE FROM ".get_table_name('messages')."
2367        WHERE  user_id=?
2368        AND    cache_key=?
2369        AND    idx>=?",
2370       $_SESSION['user_id'],
2371       $key,
2372       $start_index);
2373     }
2374
2375
2376
2377
2378   /* --------------------------------
2379    *   encoding/decoding methods
4e17e6 2380    * --------------------------------*/
T 2381
6d969b 2382   /**
T 2383    * Split an address list into a structured array list
2384    *
2385    * @param string  Input string
2386    * @param int     List only this number of addresses
2387    * @param boolean Decode address strings
2388    * @return array  Indexed list of addresses
2389    */
f11541 2390   function decode_address_list($input, $max=null, $decode=true)
4e17e6 2391     {
f11541 2392     $a = $this->_parse_address_list($input, $decode);
4e17e6 2393     $out = array();
0c6f4b 2394     // Special chars as defined by RFC 822 need to in quoted string (or escaped).
T 2395     $special_chars = '[\(\)\<\>\\\.\[\]@,;:"]';
41fa0b 2396     
4e17e6 2397     if (!is_array($a))
T 2398       return $out;
2399
2400     $c = count($a);
2401     $j = 0;
2402
2403     foreach ($a as $val)
2404       {
2405       $j++;
2406       $address = $val['address'];
2407       $name = preg_replace(array('/^[\'"]/', '/[\'"]$/'), '', trim($val['name']));
3cf664 2408       if ($name && $address && $name != $address)
0c6f4b 2409         $string = sprintf('%s <%s>', preg_match("/$special_chars/", $name) ? '"'.addcslashes($name, '"').'"' : $name, $address);
3cf664 2410       else if ($address)
T 2411         $string = $address;
2412       else if ($name)
2413         $string = $name;
4e17e6 2414       
T 2415       $out[$j] = array('name' => $name,
2416                        'mailto' => $address,
2417                        'string' => $string);
2418               
2419       if ($max && $j==$max)
2420         break;
2421       }
2422     
2423     return $out;
2424     }
2425
2426
6d969b 2427   /**
T 2428    * Decode a message header value
2429    *
2430    * @param string  Header value
2431    * @param boolean Remove quotes if necessary
2432    * @return string Decoded string
2433    */
1cded8 2434   function decode_header($input, $remove_quotes=FALSE)
4e17e6 2435     {
17b5fb 2436     $str = rcube_imap::decode_mime_string((string)$input, $this->default_charset);
1cded8 2437     if ($str{0}=='"' && $remove_quotes)
T 2438       $str = str_replace('"', '', $str);
2439     
2440     return $str;
4b0f65 2441     }
ba8f44 2442
T 2443
2444   /**
2445    * Decode a mime-encoded string to internal charset
2446    *
6d969b 2447    * @param string  Header value
T 2448    * @param string  Fallback charset if none specified
2449    * @return string Decoded string
2450    * @static
ba8f44 2451    */
f11541 2452   function decode_mime_string($input, $fallback=null)
4b0f65 2453     {
2e6825 2454     // Initialize variable
4e17e6 2455     $out = '';
T 2456
2e6825 2457     // Iterate instead of recursing, this way if there are too many values we don't have stack overflows
T 2458     // rfc: all line breaks or other characters not found 
2459     // in the Base64 Alphabet must be ignored by decoding software
2460     // delete all blanks between MIME-lines, differently we can 
2461     // receive unnecessary blanks and broken utf-8 symbols
2462     $input = preg_replace("/\?=\s+=\?/", '?==?', $input);
9e60d4 2463
2e6825 2464     // Check if there is stuff to decode
T 2465     if (strpos($input, '=?') !== false) {
2466       // Loop through the string to decode all occurences of =? ?= into the variable $out 
2467       while(($pos = strpos($input, '=?')) !== false) {
2468         // Append everything that is before the text to be decoded
2469         $out .= substr($input, 0, $pos);
4e17e6 2470
2e6825 2471         // Get the location of the text to decode
T 2472         $end_cs_pos = strpos($input, "?", $pos+2);
2473         $end_en_pos = strpos($input, "?", $end_cs_pos+1);
2474         $end_pos = strpos($input, "?=", $end_en_pos+1);
4e17e6 2475
2e6825 2476         // Extract the encoded string
T 2477         $encstr = substr($input, $pos+2, ($end_pos-$pos-2));
2478         // Extract the remaining string
2479         $input = substr($input, $end_pos+2);
2480
2481         // Decode the string fragement
2482         $out .= rcube_imap::_decode_mime_string_part($encstr);
4e17e6 2483       }
399835 2484
2e6825 2485       // Deocde the rest (if any)
T 2486       if (strlen($input) != 0)
2487          $out .= rcube_imap::decode_mime_string($input, $fallback);
2488
2489        // return the results
2490       return $out;
2491     }
2492
f11541 2493     // no encoding information, use fallback
399835 2494     return rcube_charset_convert($input, 
b026c3 2495       !empty($fallback) ? $fallback : rcmail::get_instance()->config->get('default_charset', 'ISO-8859-1'));
4e17e6 2496     }
T 2497
2498
ba8f44 2499   /**
T 2500    * Decode a part of a mime-encoded string
2501    *
6d969b 2502    * @access private
ba8f44 2503    */
4b0f65 2504   function _decode_mime_string_part($str)
4e17e6 2505     {
T 2506     $a = explode('?', $str);
2507     $count = count($a);
2508
2509     // should be in format "charset?encoding?base64_string"
2510     if ($count >= 3)
2511       {
2512       for ($i=2; $i<$count; $i++)
2513         $rest.=$a[$i];
2514
2515       if (($a[1]=="B")||($a[1]=="b"))
2516         $rest = base64_decode($rest);
2517       else if (($a[1]=="Q")||($a[1]=="q"))
2518         {
2519         $rest = str_replace("_", " ", $rest);
2520         $rest = quoted_printable_decode($rest);
2521         }
2522
3f9edb 2523       return rcube_charset_convert($rest, $a[0]);
4e17e6 2524       }
T 2525     else
3f9edb 2526       return $str;    // we dont' know what to do with this  
4e17e6 2527     }
T 2528
2529
6d969b 2530   /**
T 2531    * Decode a mime part
2532    *
2533    * @param string Input string
2534    * @param string Part encoding
2535    * @return string Decoded string
2536    * @access private
2537    */
4e17e6 2538   function mime_decode($input, $encoding='7bit')
T 2539     {
2540     switch (strtolower($encoding))
2541       {
2542       case '7bit':
2543         return $input;
2544         break;
2545       
2546       case 'quoted-printable':
2547         return quoted_printable_decode($input);
2548         break;
2549       
2550       case 'base64':
2551         return base64_decode($input);
2552         break;
2553       
2554       default:
2555         return $input;
2556       }
2557     }
2558
2559
6d969b 2560   /**
T 2561    * Convert body charset to UTF-8 according to the ctype_parameters
2562    *
2563    * @param string Part body to decode
2564    * @param string Charset to convert from
2565    * @return string Content converted to internal charset
2566    */
4e17e6 2567   function charset_decode($body, $ctype_param)
T 2568     {
a95e0e 2569     if (is_array($ctype_param) && !empty($ctype_param['charset']))
3f9edb 2570       return rcube_charset_convert($body, $ctype_param['charset']);
4e17e6 2571
fb5f4f 2572     // defaults to what is specified in the class header
17b5fb 2573     return rcube_charset_convert($body,  $this->default_charset);
4e17e6 2574     }
T 2575
2576
6d969b 2577   /**
T 2578    * Translate UID to message ID
2579    *
2580    * @param int    Message UID
2581    * @param string Mailbox name
2582    * @return int   Message ID
2583    */
2584   function get_id($uid, $mbox_name=NULL) 
2585     {
2586       $mailbox = $mbox_name ? $this->_mod_mailbox($mbox_name) : $this->mailbox;
2587       return $this->_uid2id($uid, $mailbox);
2588     }
2589
2590
2591   /**
2592    * Translate message number to UID
2593    *
2594    * @param int    Message ID
2595    * @param string Mailbox name
2596    * @return int   Message UID
2597    */
2598   function get_uid($id,$mbox_name=NULL)
2599     {
2600       $mailbox = $mbox_name ? $this->_mod_mailbox($mbox_name) : $this->mailbox;
2601       return $this->_id2uid($id, $mailbox);
2602     }
2603
1cded8 2604
ba8f44 2605
4e17e6 2606   /* --------------------------------
T 2607    *         private methods
2608    * --------------------------------*/
2609
2610
6d969b 2611   /**
T 2612    * @access private
2613    */
aadfa1 2614   function _mod_mailbox($mbox_name, $mode='in')
4e17e6 2615     {
ae4d74 2616     if ((!empty($this->root_ns) && $this->root_ns == $mbox_name) || $mbox_name == 'INBOX')
aadfa1 2617       return $mbox_name;
7902df 2618
f619de 2619     if (!empty($this->root_dir) && $mode=='in') 
aadfa1 2620       $mbox_name = $this->root_dir.$this->delimiter.$mbox_name;
7902df 2621     else if (strlen($this->root_dir) && $mode=='out') 
aadfa1 2622       $mbox_name = substr($mbox_name, strlen($this->root_dir)+1);
4e17e6 2623
aadfa1 2624     return $mbox_name;
4e17e6 2625     }
T 2626
d5342a 2627   /**
T 2628    * Validate the given input and save to local properties
2629    * @access private
2630    */
2631   function _set_sort_order($sort_field, $sort_order)
2632   {
2633     if ($sort_field != null)
2634       $this->sort_field = asciiwords($sort_field);
2635     if ($sort_order != null)
2636       $this->sort_order = strtoupper($sort_order) == 'DESC' ? 'DESC' : 'ASC';
2637   }
4e17e6 2638
6d969b 2639   /**
T 2640    * Sort mailboxes first by default folders and then in alphabethical order
2641    * @access private
2642    */
4e17e6 2643   function _sort_mailbox_list($a_folders)
T 2644     {
ea400e 2645     $a_out = $a_defaults = $folders = array();
681a59 2646
A 2647     $delimiter = $this->get_hierarchy_delimiter();
4e17e6 2648
T 2649     // find default folders and skip folders starting with '.'
681a59 2650     foreach ($a_folders as $i => $folder)
4e17e6 2651       {
T 2652       if ($folder{0}=='.')
6d969b 2653         continue;
fa4cd2 2654
c007e6 2655       if (($p = array_search(strtolower($folder), $this->default_folders_lc)) !== false && !$a_defaults[$p])
6d969b 2656         $a_defaults[$p] = $folder;
4e17e6 2657       else
70aa90 2658         $folders[$folder] = rc_strtolower(rcube_charset_convert($folder, 'UTF-7'));
681a59 2659       }
A 2660
2661     asort($folders, SORT_LOCALE_STRING);
2662     ksort($a_defaults);
2663
2664     $folders = array_merge($a_defaults, array_keys($folders));
2665
2666     // finally we must rebuild the list to move 
f219a2 2667     // subfolders of default folders to their place...
A 2668     // ...also do this for the rest of folders because
2669     // asort() is not properly sorting case sensitive names    
681a59 2670     while (list($key, $folder) = each($folders)) {
A 2671       $a_out[] = $folder;
2672       unset($folders[$key]);
f219a2 2673       foreach ($folders as $idx => $f) {
A 2674     if (strpos($f, $folder.$delimiter) === 0) {
2675           $a_out[] = $f;
2676       unset($folders[$idx]);
681a59 2677       }
f219a2 2678         }
A 2679       reset($folders);  
4e17e6 2680       }
T 2681
681a59 2682     return $a_out;
4e17e6 2683     }
T 2684
6d969b 2685   /**
T 2686    * @access private
2687    */
aadfa1 2688   function _uid2id($uid, $mbox_name=NULL)
4e17e6 2689     {
aadfa1 2690     if (!$mbox_name)
S 2691       $mbox_name = $this->mailbox;
4e17e6 2692       
aadfa1 2693     if (!isset($this->uid_id_map[$mbox_name][$uid]))
S 2694       $this->uid_id_map[$mbox_name][$uid] = iil_C_UID2ID($this->conn, $mbox_name, $uid);
4e17e6 2695
aadfa1 2696     return $this->uid_id_map[$mbox_name][$uid];
4e17e6 2697     }
T 2698
6d969b 2699   /**
T 2700    * @access private
2701    */
aadfa1 2702   function _id2uid($id, $mbox_name=NULL)
e6f360 2703     {
aadfa1 2704     if (!$mbox_name)
S 2705       $mbox_name = $this->mailbox;
e6f360 2706       
1fb2c8 2707     $index = array_flip((array)$this->uid_id_map[$mbox_name]);
017def 2708     if (isset($index[$id]))
T 2709       $uid = $index[$id];
2710     else
2711       {
2712       $uid = iil_C_ID2UID($this->conn, $mbox_name, $id);
2713       $this->uid_id_map[$mbox_name][$uid] = $id;
2714       }
2715     
2716     return $uid;
1cded8 2717     }
T 2718
2719
6d969b 2720   /**
T 2721    * Subscribe/unsubscribe a list of mailboxes and update local cache
2722    * @access private
2723    */
4e17e6 2724   function _change_subscription($a_mboxes, $mode)
T 2725     {
2726     $updated = FALSE;
2727     
2728     if (is_array($a_mboxes))
aadfa1 2729       foreach ($a_mboxes as $i => $mbox_name)
4e17e6 2730         {
aadfa1 2731         $mailbox = $this->_mod_mailbox($mbox_name);
4e17e6 2732         $a_mboxes[$i] = $mailbox;
T 2733
2734         if ($mode=='subscribe')
2735           $result = iil_C_Subscribe($this->conn, $mailbox);
2736         else if ($mode=='unsubscribe')
2737           $result = iil_C_UnSubscribe($this->conn, $mailbox);
2738
2739         if ($result>=0)
2740           $updated = TRUE;
2741         }
2742         
2743     // get cached mailbox list    
2744     if ($updated)
2745       {
2746       $a_mailbox_cache = $this->get_cache('mailboxes');
2747       if (!is_array($a_mailbox_cache))
2748         return $updated;
2749
2750       // modify cached list
2751       if ($mode=='subscribe')
2752         $a_mailbox_cache = array_merge($a_mailbox_cache, $a_mboxes);
2753       else if ($mode=='unsubscribe')
2754         $a_mailbox_cache = array_diff($a_mailbox_cache, $a_mboxes);
2755         
2756       // write mailboxlist to cache
2757       $this->update_cache('mailboxes', $this->_sort_mailbox_list($a_mailbox_cache));
2758       }
2759
2760     return $updated;
2761     }
2762
2763
6d969b 2764   /**
T 2765    * Increde/decrese messagecount for a specific mailbox
2766    * @access private
2767    */
aadfa1 2768   function _set_messagecount($mbox_name, $mode, $increment)
4e17e6 2769     {
T 2770     $a_mailbox_cache = FALSE;
aadfa1 2771     $mailbox = $mbox_name ? $mbox_name : $this->mailbox;
4e17e6 2772     $mode = strtoupper($mode);
T 2773
2774     $a_mailbox_cache = $this->get_cache('messagecount');
2775     
2776     if (!is_array($a_mailbox_cache[$mailbox]) || !isset($a_mailbox_cache[$mailbox][$mode]) || !is_numeric($increment))
2777       return FALSE;
2778     
2779     // add incremental value to messagecount
2780     $a_mailbox_cache[$mailbox][$mode] += $increment;
31b2ce 2781     
T 2782     // there's something wrong, delete from cache
2783     if ($a_mailbox_cache[$mailbox][$mode] < 0)
2784       unset($a_mailbox_cache[$mailbox][$mode]);
4e17e6 2785
T 2786     // write back to cache
2787     $this->update_cache('messagecount', $a_mailbox_cache);
2788     
2789     return TRUE;
2790     }
2791
2792
6d969b 2793   /**
T 2794    * Remove messagecount of a specific mailbox from cache
2795    * @access private
2796    */
aadfa1 2797   function _clear_messagecount($mbox_name='')
4e17e6 2798     {
T 2799     $a_mailbox_cache = FALSE;
aadfa1 2800     $mailbox = $mbox_name ? $mbox_name : $this->mailbox;
4e17e6 2801
T 2802     $a_mailbox_cache = $this->get_cache('messagecount');
2803
2804     if (is_array($a_mailbox_cache[$mailbox]))
2805       {
2806       unset($a_mailbox_cache[$mailbox]);
2807       $this->update_cache('messagecount', $a_mailbox_cache);
2808       }
2809     }
2810
2811
6d969b 2812   /**
T 2813    * Split RFC822 header string into an associative array
2814    * @access private
2815    */
8d4bcd 2816   function _parse_headers($headers)
T 2817     {
2818     $a_headers = array();
2819     $lines = explode("\n", $headers);
2820     $c = count($lines);
2821     for ($i=0; $i<$c; $i++)
2822       {
2823       if ($p = strpos($lines[$i], ': '))
2824         {
2825         $field = strtolower(substr($lines[$i], 0, $p));
2826         $value = trim(substr($lines[$i], $p+1));
2827         if (!empty($value))
2828           $a_headers[$field] = $value;
2829         }
2830       }
2831     
2832     return $a_headers;
2833     }
2834
2835
6d969b 2836   /**
T 2837    * @access private
2838    */
f11541 2839   function _parse_address_list($str, $decode=true)
4e17e6 2840     {
d04d20 2841     // remove any newlines and carriage returns before
5a6ad2 2842     $a = $this->_explode_quoted_string('[,;]', preg_replace( "/[\r\n]/", " ", $str));
4e17e6 2843     $result = array();
41fa0b 2844     
4e17e6 2845     foreach ($a as $key => $val)
T 2846       {
568ba3 2847       $val = preg_replace("/([\"\w])</", "$1 <", $val);
f11541 2848       $sub_a = $this->_explode_quoted_string(' ', $decode ? $this->decode_header($val) : $val);
41fa0b 2849       $result[$key]['name'] = '';
T 2850
4e17e6 2851       foreach ($sub_a as $k => $v)
T 2852         {
3cf664 2853         if (strpos($v, '@') > 0)
4e17e6 2854           $result[$key]['address'] = str_replace('<', '', str_replace('>', '', $v));
T 2855         else
2856           $result[$key]['name'] .= (empty($result[$key]['name'])?'':' ').str_replace("\"",'',stripslashes($v));
2857         }
2858         
2859       if (empty($result[$key]['name']))
41fa0b 2860         $result[$key]['name'] = $result[$key]['address'];        
4e17e6 2861       }
T 2862     
2863     return $result;
2864     }
2865
2866
6d969b 2867   /**
T 2868    * @access private
2869    */
4e17e6 2870   function _explode_quoted_string($delimiter, $string)
T 2871     {
5a6ad2 2872     $result = array();
T 2873     $strlen = strlen($string);
2874     for ($q=$p=$i=0; $i < $strlen; $i++)
2875     {
2876       if ($string{$i} == "\"" && $string{$i-1} != "\\")
2877         $q = $q ? false : true;
2878       else if (!$q && preg_match("/$delimiter/", $string{$i}))
2879       {
2880         $result[] = substr($string, $p, $i - $p);
2881         $p = $i + 1;
2882       }
2883     }
4e17e6 2884     
5a6ad2 2885     $result[] = substr($string, $p);
4e17e6 2886     return $result;
T 2887     }
6d969b 2888
T 2889 }  // end class rcube_imap
4e17e6 2890
8d4bcd 2891
T 2892 /**
2893  * Class representing a message part
6d969b 2894  *
T 2895  * @package Mail
8d4bcd 2896  */
T 2897 class rcube_message_part
2898 {
2899   var $mime_id = '';
2900   var $ctype_primary = 'text';
2901   var $ctype_secondary = 'plain';
2902   var $mimetype = 'text/plain';
2903   var $disposition = '';
5cc4b1 2904   var $filename = '';
8d4bcd 2905   var $encoding = '8bit';
T 2906   var $charset = '';
2907   var $size = 0;
2908   var $headers = array();
2909   var $d_parameters = array();
2910   var $ctype_parameters = array();
2911
2912 }
4e17e6 2913
T 2914
7e93ff 2915 /**
T 2916  * Class for sorting an array of iilBasicHeader objects in a predetermined order.
2917  *
6d969b 2918  * @package Mail
7e93ff 2919  * @author Eric Stadtherr
T 2920  */
2921 class rcube_header_sorter
2922 {
2923    var $sequence_numbers = array();
2924    
2925    /**
6d969b 2926     * Set the predetermined sort order.
7e93ff 2927     *
6d969b 2928     * @param array Numerically indexed array of IMAP message sequence numbers
7e93ff 2929     */
T 2930    function set_sequence_numbers($seqnums)
2931    {
05d180 2932       $this->sequence_numbers = array_flip($seqnums);
7e93ff 2933    }
T 2934  
2935    /**
6d969b 2936     * Sort the array of header objects
7e93ff 2937     *
6d969b 2938     * @param array Array of iilBasicHeader objects indexed by UID
7e93ff 2939     */
T 2940    function sort_headers(&$headers)
2941    {
2942       /*
2943        * uksort would work if the keys were the sequence number, but unfortunately
2944        * the keys are the UIDs.  We'll use uasort instead and dereference the value
2945        * to get the sequence number (in the "id" field).
2946        * 
2947        * uksort($headers, array($this, "compare_seqnums")); 
2948        */
2949        uasort($headers, array($this, "compare_seqnums"));
2950    }
2951  
2952    /**
2953     * Sort method called by uasort()
2954     */
2955    function compare_seqnums($a, $b)
2956    {
2957       // First get the sequence number from the header object (the 'id' field).
2958       $seqa = $a->id;
2959       $seqb = $b->id;
2960       
2961       // then find each sequence number in my ordered list
05d180 2962       $posa = isset($this->sequence_numbers[$seqa]) ? intval($this->sequence_numbers[$seqa]) : -1;
T 2963       $posb = isset($this->sequence_numbers[$seqb]) ? intval($this->sequence_numbers[$seqb]) : -1;
7e93ff 2964       
T 2965       // return the relative position as the comparison value
05d180 2966       return $posa - $posb;
7e93ff 2967    }
T 2968 }
4e17e6 2969
T 2970
7e93ff 2971 /**
T 2972  * Add quoted-printable encoding to a given string
2973  * 
6d969b 2974  * @param string   String to encode
T 2975  * @param int      Add new line after this number of characters
2976  * @param boolean  True if spaces should be converted into =20
2977  * @return string Encoded string
7e93ff 2978  */
T 2979 function quoted_printable_encode($input, $line_max=76, $space_conv=false)
4e17e6 2980   {
T 2981   $hex = array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');
2982   $lines = preg_split("/(?:\r\n|\r|\n)/", $input);
2983   $eol = "\r\n";
2984   $escape = "=";
2985   $output = "";
2986
2987   while( list(, $line) = each($lines))
2988     {
2989     //$line = rtrim($line); // remove trailing white space -> no =20\r\n necessary
2990     $linlen = strlen($line);
2991     $newline = "";
2992     for($i = 0; $i < $linlen; $i++)
2993       {
2994       $c = substr( $line, $i, 1 );
2995       $dec = ord( $c );
2996       if ( ( $i == 0 ) && ( $dec == 46 ) ) // convert first point in the line into =2E
2997         {
2998         $c = "=2E";
2999         }
3000       if ( $dec == 32 )
3001         {
3002         if ( $i == ( $linlen - 1 ) ) // convert space at eol only
3003           {
3004           $c = "=20";
3005           }
3006         else if ( $space_conv )
3007           {
3008           $c = "=20";
3009           }
3010         }
3011       else if ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) )  // always encode "\t", which is *not* required
3012         {
3013         $h2 = floor($dec/16);
3014         $h1 = floor($dec%16);
3015         $c = $escape.$hex["$h2"].$hex["$h1"];
3016         }
3017          
3018       if ( (strlen($newline) + strlen($c)) >= $line_max )  // CRLF is not counted
3019         {
3020         $output .= $newline.$escape.$eol; // soft line break; " =\r\n" is okay
3021         $newline = "";
3022         // check if newline first character will be point or not
3023         if ( $dec == 46 )
3024           {
3025           $c = "=2E";
3026           }
3027         }
3028       $newline .= $c;
3029       } // end of for
3030     $output .= $newline.$eol;
3031     } // end of while
3032
3033   return trim($output);
3034   }
3035
8d4bcd 3036