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