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