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