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