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