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