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