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