svncommit
2006-09-23 6649b1f0a5db6160d197a13ca79cfd67fbb02d77
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]);
2f2f15 1013
8d4bcd 1014     // read part disposition
ea206d 1015     $di = count($part) - 2;
2f2f15 1016     if ((is_array($part[$di]) && count($part[$di]) == 2 && is_array($part[$di][1])) ||
T 1017         (is_array($part[--$di]) && count($part[$di]) == 2))
8d4bcd 1018       {
T 1019       $struct->disposition = strtolower($part[$di][0]);
1020
1021       if (is_array($part[$di][1]))
1022         for ($n=0; $n<count($part[$di][1]); $n+=2)
1023           $struct->d_parameters[strtolower($part[$di][1][$n])] = $part[$di][1][$n+1];
1024       }
1025       
1026     // get child parts
1027     if (is_array($part[8]) && $di != 8)
1028       {
1029       $struct->parts = array();
1030       for ($i=0, $count=0; $i<count($part[8]); $i++)
1031         if (is_array($part[8][$i]) && count($part[8][$i]) > 5)
1032           $struct->parts[] = $this->_structure_part($part[8][$i], ++$count, $struct->mime_id);
1033       }
1034       
1035     // get part ID
1036     if (!empty($part[3]) && $part[3]!='NIL')
1037       {
1038       $struct->content_id = $part[3];
1039       $struct->headers['content-id'] = $part[3];
1040       
1041       if (empty($struct->disposition))
1042         $struct->disposition = 'inline';
1043       }
1044
1045     // fetch message headers if message/rfc822
1046     if ($struct->ctype_primary=='message')
1047       {
1048       $headers = iil_C_FetchPartBody($this->conn, $this->mailbox, $this->_msg_id, $struct->mime_id.'.HEADER');
1049       $struct->headers = $this->_parse_headers($headers);
1050       }
1051   
1052       return $struct;
1053     }
1054     
1055   
1056   /**
1057    * Return a flat array with references to all parts, indexed by part numbmers
1058    *
1059    * @param object Message body structure
1060    * @return Array with part number -> object pairs
1061    */
1062   function get_mime_numbers(&$structure)
1063     {
1064     $a_parts = array();
1065     $this->_get_part_numbers($structure, $a_parts);
1066     return $a_parts;
1067     }
1068   
1069   
1070   /**
1071    * Helper method for recursive calls
1072    *
1073    * @access 
1074    */
1075   function _get_part_numbers(&$part, &$a_parts)
1076     {
1077     if ($part->mime_id)
1078       $a_parts[$part->mime_id] = &$part;
1079       
1080     if (is_array($part->parts))
1081       for ($i=0; $i<count($part->parts); $i++)
996066 1082         $this->_get_part_numbers($part->parts[$i], $a_parts);
8d4bcd 1083     }
T 1084   
1085
1086   /**
1087    * Fetch message body of a specific message from the server
1088    *
1089    * @param  int    Message UID
1090    * @param  string Part number
1091    * @param  object Part object created by get_structure()
1092    * @param  mixed  True to print part, ressource to write part contents in
1093    * @return Message/part body if not printed
1094    */
1095   function &get_message_part($uid, $part=1, $o_part=NULL, $print=NULL)
1096     {
1097     if (!($msg_id = $this->_uid2id($uid)))
1098       return FALSE;
1099     
1100     // get part encoding if not provided
1101     if (!is_object($o_part))
1102       {
1103       $structure_str = iil_C_FetchStructureString($this->conn, $this->mailbox, $msg_id); 
1104       $structure = iml_GetRawStructureArray($structure_str);
1105       $part_type = iml_GetPartTypeCode($structure, $part);
1106       $o_part = new rcube_message_part;
1107       $o_part->ctype_primary = $part_type==0 ? 'text' : ($part_type==2 ? 'message' : 'other');
1108       $o_part->encoding = strtolower(iml_GetPartEncodingString($structure, $part));
1109       $o_part->charset = iml_GetPartCharset($structure, $part);
1110       }
1111       
1112     // TODO: Add caching for message parts
1113
1114     if ($print)
1115       {
1116       iil_C_HandlePartBody($this->conn, $this->mailbox, $msg_id, $part, ($o_part->encoding=='base64'?3:2));
1117       $body = TRUE;
1118       }
1119     else
1120       {
1121       $body = iil_C_HandlePartBody($this->conn, $this->mailbox, $msg_id, $part, 1);
1122
1123       // decode part body
1124       if ($o_part->encoding=='base64' || $o_part->encoding=='quoted-printable')
1125         $body = $this->mime_decode($body, $o_part->encoding);
1126
1127       // convert charset (if text or message part)
f7bfec 1128       if ($o_part->ctype_primary=='text' || $o_part->ctype_primary=='message')
T 1129         {
1130         // assume ISO-8859-1 if no charset specified
1131         if (empty($o_part->charset))
1132           $o_part->charset = 'ISO-8859-1';
1133
8d4bcd 1134         $body = rcube_charset_convert($body, $o_part->charset);
f7bfec 1135         }
8d4bcd 1136       }
4e17e6 1137
T 1138     return $body;
1139     }
1140
1141
8d4bcd 1142   /**
T 1143    * Fetch message body of a specific message from the server
1144    *
1145    * @param  int    Message UID
1146    * @return Message/part body
1147    * @see    ::get_message_part()
1148    */
1149   function &get_body($uid, $part=1)
1150     {
1151     return $this->get_message_part($uid, $part);
1152     }
1153
1154
1155   /**
1156    * Returns the whole message source as string
1157    *
1158    * @param int  Message UID
1159    * @return Message source string
1160    */
1161   function &get_raw_body($uid)
4e17e6 1162     {
T 1163     if (!($msg_id = $this->_uid2id($uid)))
1164       return FALSE;
1165
1166     $body = iil_C_FetchPartHeader($this->conn, $this->mailbox, $msg_id, NULL);
1167     $body .= iil_C_HandlePartBody($this->conn, $this->mailbox, $msg_id, NULL, 1);
1168
1169     return $body;    
1170     }
8d4bcd 1171     
T 1172
1173   /**
1174    * Sends the whole message source to stdout
1175    *
1176    * @param int  Message UID
1177    */ 
1178   function print_raw_body($uid)
1179     {
1180     if (!($msg_id = $this->_uid2id($uid)))
1181       return FALSE;
1182
1183     print iil_C_FetchPartHeader($this->conn, $this->mailbox, $msg_id, NULL);
1184     flush();
1185     iil_C_HandlePartBody($this->conn, $this->mailbox, $msg_id, NULL, 2);
1186     }
4e17e6 1187
T 1188
8d4bcd 1189   /**
T 1190    * Set message flag to one or several messages
1191    *
1192    * @param mixed  Message UIDs as array or as comma-separated string
1193    * @param string Flag to set: SEEN, UNDELETED, DELETED, RECENT, ANSWERED, DRAFT
1194    * @return True on success, False on failure
1195    */
4e17e6 1196   function set_flag($uids, $flag)
T 1197     {
1198     $flag = strtoupper($flag);
1199     $msg_ids = array();
1200     if (!is_array($uids))
8fae1e 1201       $uids = explode(',',$uids);
4e17e6 1202       
8fae1e 1203     foreach ($uids as $uid) {
31b2ce 1204       $msg_ids[$uid] = $this->_uid2id($uid);
8fae1e 1205     }
4e17e6 1206       
8fae1e 1207     if ($flag=='UNDELETED')
S 1208       $result = iil_C_Undelete($this->conn, $this->mailbox, join(',', array_values($msg_ids)));
1209     else if ($flag=='UNSEEN')
31b2ce 1210       $result = iil_C_Unseen($this->conn, $this->mailbox, join(',', array_values($msg_ids)));
4e17e6 1211     else
31b2ce 1212       $result = iil_C_Flag($this->conn, $this->mailbox, join(',', array_values($msg_ids)), $flag);
4e17e6 1213
T 1214     // reload message headers if cached
1215     $cache_key = $this->mailbox.'.msg';
1cded8 1216     if ($this->caching_enabled)
4e17e6 1217       {
31b2ce 1218       foreach ($msg_ids as $uid => $id)
4e17e6 1219         {
31b2ce 1220         if ($cached_headers = $this->get_cached_message($cache_key, $uid))
4e17e6 1221           {
1cded8 1222           $this->remove_message_cache($cache_key, $id);
T 1223           //$this->get_headers($uid);
4e17e6 1224           }
T 1225         }
1cded8 1226
T 1227       // close and re-open connection
1228       // this prevents connection problems with Courier 
1229       $this->reconnect();
4e17e6 1230       }
T 1231
1232     // set nr of messages that were flaged
31b2ce 1233     $count = count($msg_ids);
4e17e6 1234
T 1235     // clear message count cache
1236     if ($result && $flag=='SEEN')
1237       $this->_set_messagecount($this->mailbox, 'UNSEEN', $count*(-1));
1238     else if ($result && $flag=='UNSEEN')
1239       $this->_set_messagecount($this->mailbox, 'UNSEEN', $count);
1240     else if ($result && $flag=='DELETED')
1241       $this->_set_messagecount($this->mailbox, 'ALL', $count*(-1));
1242
1243     return $result;
1244     }
1245
1246
1247   // append a mail message (source) to a specific mailbox
b068a0 1248   function save_message($mbox_name, &$message)
4e17e6 1249     {
a894ba 1250     $mbox_name = stripslashes($mbox_name);
aadfa1 1251     $mailbox = $this->_mod_mailbox($mbox_name);
4e17e6 1252
f88d41 1253     // make sure mailbox exists
4e17e6 1254     if (in_array($mailbox, $this->_list_mailboxes()))
T 1255       $saved = iil_C_Append($this->conn, $mailbox, $message);
1cded8 1256
4e17e6 1257     if ($saved)
T 1258       {
1259       // increase messagecount of the target mailbox
1260       $this->_set_messagecount($mailbox, 'ALL', 1);
1261       }
1262           
1263     return $saved;
1264     }
1265
1266
1267   // move a message from one mailbox to another
1268   function move_message($uids, $to_mbox, $from_mbox='')
1269     {
a894ba 1270     $to_mbox = stripslashes($to_mbox);
S 1271     $from_mbox = stripslashes($from_mbox);
4e17e6 1272     $to_mbox = $this->_mod_mailbox($to_mbox);
T 1273     $from_mbox = $from_mbox ? $this->_mod_mailbox($from_mbox) : $this->mailbox;
1274
f88d41 1275     // make sure mailbox exists
4e17e6 1276     if (!in_array($to_mbox, $this->_list_mailboxes()))
f88d41 1277       {
T 1278       if (in_array(strtolower($to_mbox), $this->default_folders))
1279         $this->create_mailbox($to_mbox, TRUE);
1280       else
1281         return FALSE;
1282       }
1283
4e17e6 1284     // convert the list of uids to array
T 1285     $a_uids = is_string($uids) ? explode(',', $uids) : (is_array($uids) ? $uids : NULL);
1286     
1287     // exit if no message uids are specified
1288     if (!is_array($a_uids))
1289       return false;
520c36 1290
4e17e6 1291     // convert uids to message ids
T 1292     $a_mids = array();
1293     foreach ($a_uids as $uid)
1294       $a_mids[] = $this->_uid2id($uid, $from_mbox);
520c36 1295
4e17e6 1296     $moved = iil_C_Move($this->conn, join(',', $a_mids), $from_mbox, $to_mbox);
T 1297     
1298     // send expunge command in order to have the moved message
1299     // really deleted from the source mailbox
1300     if ($moved)
1301       {
1cded8 1302       $this->_expunge($from_mbox, FALSE);
4e17e6 1303       $this->_clear_messagecount($from_mbox);
T 1304       $this->_clear_messagecount($to_mbox);
1305       }
1306
1307     // update cached message headers
1308     $cache_key = $from_mbox.'.msg';
1cded8 1309     if ($moved && ($a_cache_index = $this->get_message_cache_index($cache_key)))
4e17e6 1310       {
1cded8 1311       $start_index = 100000;
4e17e6 1312       foreach ($a_uids as $uid)
1cded8 1313         {
25d8ba 1314         if(($index = array_search($uid, $a_cache_index)) !== FALSE)
S 1315       $start_index = min($index, $start_index);
1cded8 1316         }
4e17e6 1317
1cded8 1318       // clear cache from the lowest index on
T 1319       $this->clear_message_cache($cache_key, $start_index);
4e17e6 1320       }
T 1321
1322     return $moved;
1323     }
1324
1325
1326   // mark messages as deleted and expunge mailbox
aadfa1 1327   function delete_message($uids, $mbox_name='')
4e17e6 1328     {
a894ba 1329     $mbox_name = stripslashes($mbox_name);
aadfa1 1330     $mailbox = $mbox_name ? $this->_mod_mailbox($mbox_name) : $this->mailbox;
4e17e6 1331
T 1332     // convert the list of uids to array
1333     $a_uids = is_string($uids) ? explode(',', $uids) : (is_array($uids) ? $uids : NULL);
1334     
1335     // exit if no message uids are specified
1336     if (!is_array($a_uids))
1337       return false;
1338
1339
1340     // convert uids to message ids
1341     $a_mids = array();
1342     foreach ($a_uids as $uid)
1343       $a_mids[] = $this->_uid2id($uid, $mailbox);
1344         
1345     $deleted = iil_C_Delete($this->conn, $mailbox, join(',', $a_mids));
1346     
1347     // send expunge command in order to have the deleted message
1348     // really deleted from the mailbox
1349     if ($deleted)
1350       {
1cded8 1351       $this->_expunge($mailbox, FALSE);
4e17e6 1352       $this->_clear_messagecount($mailbox);
T 1353       }
1354
1355     // remove deleted messages from cache
1cded8 1356     $cache_key = $mailbox.'.msg';
T 1357     if ($deleted && ($a_cache_index = $this->get_message_cache_index($cache_key)))
4e17e6 1358       {
1cded8 1359       $start_index = 100000;
4e17e6 1360       foreach ($a_uids as $uid)
1cded8 1361         {
T 1362         $index = array_search($uid, $a_cache_index);
1363         $start_index = min($index, $start_index);
1364         }
4e17e6 1365
1cded8 1366       // clear cache from the lowest index on
T 1367       $this->clear_message_cache($cache_key, $start_index);
4e17e6 1368       }
T 1369
1370     return $deleted;
1371     }
1372
1373
a95e0e 1374   // clear all messages in a specific mailbox
aadfa1 1375   function clear_mailbox($mbox_name=NULL)
a95e0e 1376     {
a894ba 1377     $mbox_name = stripslashes($mbox_name);
aadfa1 1378     $mailbox = !empty($mbox_name) ? $this->_mod_mailbox($mbox_name) : $this->mailbox;
a95e0e 1379     $msg_count = $this->_messagecount($mailbox, 'ALL');
T 1380     
1381     if ($msg_count>0)
1cded8 1382       {
5e3512 1383       $cleared = iil_C_ClearFolder($this->conn, $mailbox);
T 1384       
1385       // make sure the message count cache is cleared as well
1386       if ($cleared)
1387         {
1388         $this->clear_message_cache($mailbox.'.msg');      
1389         $a_mailbox_cache = $this->get_cache('messagecount');
1390         unset($a_mailbox_cache[$mailbox]);
1391         $this->update_cache('messagecount', $a_mailbox_cache);
1392         }
1393         
1394       return $cleared;
1cded8 1395       }
a95e0e 1396     else
T 1397       return 0;
1398     }
1399
1400
4e17e6 1401   // send IMAP expunge command and clear cache
aadfa1 1402   function expunge($mbox_name='', $clear_cache=TRUE)
4e17e6 1403     {
a894ba 1404     $mbox_name = stripslashes($mbox_name);
aadfa1 1405     $mailbox = $mbox_name ? $this->_mod_mailbox($mbox_name) : $this->mailbox;
1cded8 1406     return $this->_expunge($mailbox, $clear_cache);
T 1407     }
1408
1409
1410   // send IMAP expunge command and clear cache
1411   function _expunge($mailbox, $clear_cache=TRUE)
1412     {
4e17e6 1413     $result = iil_C_Expunge($this->conn, $mailbox);
T 1414
1415     if ($result>=0 && $clear_cache)
1416       {
1cded8 1417       //$this->clear_message_cache($mailbox.'.msg');
4e17e6 1418       $this->_clear_messagecount($mailbox);
T 1419       }
1420       
1421     return $result;
1422     }
1423
1424
1425   /* --------------------------------
1426    *        folder managment
1427    * --------------------------------*/
1428
1429
fa4cd2 1430   /**
T 1431    * Get a list of all folders available on the IMAP server
1432    * 
1433    * @param string IMAP root dir
1434    * @return array Inbdexed array with folder names 
1435    */
4e17e6 1436   function list_unsubscribed($root='')
T 1437     {
1438     static $sa_unsubscribed;
1439     
1440     if (is_array($sa_unsubscribed))
1441       return $sa_unsubscribed;
1442       
1443     // retrieve list of folders from IMAP server
1444     $a_mboxes = iil_C_ListMailboxes($this->conn, $this->_mod_mailbox($root), '*');
1445
1446     // modify names with root dir
aadfa1 1447     foreach ($a_mboxes as $mbox_name)
4e17e6 1448       {
aadfa1 1449       $name = $this->_mod_mailbox($mbox_name, 'out');
4e17e6 1450       if (strlen($name))
T 1451         $a_folders[] = $name;
1452       }
1453
1454     // filter folders and sort them
1455     $sa_unsubscribed = $this->_sort_mailbox_list($a_folders);
1456     return $sa_unsubscribed;
1457     }
1458
1459
58e360 1460   /**
T 1461    * Get quota
1462    * added by Nuny
1463    */
1464   function get_quota()
1465     {
1466     if ($this->get_capability('QUOTA'))
fda695 1467       return iil_C_GetQuota($this->conn);
3ea0e3 1468     
4647e1 1469     return FALSE;
58e360 1470     }
T 1471
1472
fa4cd2 1473   /**
T 1474    * subscribe to a specific mailbox(es)
1475    */ 
aadfa1 1476   function subscribe($mbox_name, $mode='subscribe')
4e17e6 1477     {
aadfa1 1478     if (is_array($mbox_name))
S 1479       $a_mboxes = $mbox_name;
1480     else if (is_string($mbox_name) && strlen($mbox_name))
1481       $a_mboxes = explode(',', $mbox_name);
4e17e6 1482     
T 1483     // let this common function do the main work
1484     return $this->_change_subscription($a_mboxes, 'subscribe');
1485     }
1486
1487
fa4cd2 1488   /**
T 1489    * unsubscribe mailboxes
1490    */
aadfa1 1491   function unsubscribe($mbox_name)
4e17e6 1492     {
aadfa1 1493     if (is_array($mbox_name))
S 1494       $a_mboxes = $mbox_name;
1495     else if (is_string($mbox_name) && strlen($mbox_name))
1496       $a_mboxes = explode(',', $mbox_name);
4e17e6 1497
T 1498     // let this common function do the main work
1499     return $this->_change_subscription($a_mboxes, 'unsubscribe');
1500     }
1501
1502
fa4cd2 1503   /**
4d4264 1504    * Create a new mailbox on the server and register it in local cache
T 1505    *
1506    * @param string  New mailbox name (as utf-7 string)
1507    * @param boolean True if the new mailbox should be subscribed
1508    * @param string  Name of the created mailbox, false on error
fa4cd2 1509    */
4e17e6 1510   function create_mailbox($name, $subscribe=FALSE)
T 1511     {
1512     $result = FALSE;
1cded8 1513     
T 1514     // replace backslashes
1515     $name = preg_replace('/[\\\]+/', '-', $name);
1516
1517     // reduce mailbox name to 100 chars
4d4264 1518     $name = substr($name, 0, 100);
1cded8 1519
4d4264 1520     $abs_name = $this->_mod_mailbox($name);
4e17e6 1521     $a_mailbox_cache = $this->get_cache('mailboxes');
fa4cd2 1522
T 1523     if (strlen($abs_name) && (!is_array($a_mailbox_cache) || !in_array_nocase($abs_name, $a_mailbox_cache)))
a95e0e 1524       $result = iil_C_CreateFolder($this->conn, $abs_name);
4e17e6 1525
fa4cd2 1526     // try to subscribe it
T 1527     if ($subscribe)
4d4264 1528       $this->subscribe($name);
4e17e6 1529
7902df 1530     return $result ? $name : FALSE;
4e17e6 1531     }
T 1532
1533
fa4cd2 1534   /**
4d4264 1535    * Set a new name to an existing mailbox
T 1536    *
1537    * @param string Mailbox to rename (as utf-7 string)
1538    * @param string New mailbox name (as utf-7 string)
1539    * @param string Name of the renames mailbox, false on error
fa4cd2 1540    */
f9c107 1541   function rename_mailbox($mbox_name, $new_name)
4e17e6 1542     {
c8c1e0 1543     $result = FALSE;
S 1544
1545     // replace backslashes
1546     $name = preg_replace('/[\\\]+/', '-', $new_name);
f9c107 1547         
T 1548     // encode mailbox name and reduce it to 100 chars
4d4264 1549     $name = substr($new_name, 0, 100);
c8c1e0 1550
f9c107 1551     // make absolute path
T 1552     $mailbox = $this->_mod_mailbox($mbox_name);
4d4264 1553     $abs_name = $this->_mod_mailbox($name);
f7bfec 1554     
T 1555     // check if mailbox is subscribed
1556     $a_subscribed = $this->_list_mailboxes();
1557     $subscribed = in_array($mailbox, $a_subscribed);
1558     
1559     // unsubscribe folder
1560     if ($subscribed)
1561       iil_C_UnSubscribe($this->conn, $mailbox);
4d4264 1562
f9c107 1563     if (strlen($abs_name))
T 1564       $result = iil_C_RenameFolder($this->conn, $mailbox, $abs_name);
4d4264 1565
f9c107 1566     // clear cache
T 1567     if ($result)
1568       {
1569       $this->clear_message_cache($mailbox.'.msg');
f7bfec 1570       $this->clear_cache('mailboxes');      
f9c107 1571       }
f7bfec 1572
4d4264 1573     // try to subscribe it
f7bfec 1574     if ($result && $subscribed)
T 1575       iil_C_Subscribe($this->conn, $abs_name);
c8c1e0 1576
S 1577     return $result ? $name : FALSE;
4e17e6 1578     }
T 1579
1580
fa4cd2 1581   /**
T 1582    * remove mailboxes from server
1583    */
aadfa1 1584   function delete_mailbox($mbox_name)
4e17e6 1585     {
T 1586     $deleted = FALSE;
1587
aadfa1 1588     if (is_array($mbox_name))
S 1589       $a_mboxes = $mbox_name;
1590     else if (is_string($mbox_name) && strlen($mbox_name))
1591       $a_mboxes = explode(',', $mbox_name);
4e17e6 1592
T 1593     if (is_array($a_mboxes))
aadfa1 1594       foreach ($a_mboxes as $mbox_name)
4e17e6 1595         {
aadfa1 1596         $mailbox = $this->_mod_mailbox($mbox_name);
4e17e6 1597
T 1598         // unsubscribe mailbox before deleting
1599         iil_C_UnSubscribe($this->conn, $mailbox);
fa4cd2 1600
4e17e6 1601         // send delete command to server
T 1602         $result = iil_C_DeleteFolder($this->conn, $mailbox);
1603         if ($result>=0)
1604           $deleted = TRUE;
1605         }
1606
1607     // clear mailboxlist cache
1608     if ($deleted)
1cded8 1609       {
T 1610       $this->clear_message_cache($mailbox.'.msg');
4e17e6 1611       $this->clear_cache('mailboxes');
1cded8 1612       }
4e17e6 1613
1cded8 1614     return $deleted;
4e17e6 1615     }
T 1616
fa4cd2 1617
T 1618   /**
1619    * Create all folders specified as default
1620    */
1621   function create_default_folders()
1622     {
1623     $a_folders = iil_C_ListMailboxes($this->conn, $this->_mod_mailbox(''), '*');
1624     $a_subscribed = iil_C_ListSubscribed($this->conn, $this->_mod_mailbox(''), '*');
1625     
1626     // create default folders if they do not exist
1627     foreach ($this->default_folders as $folder)
1628       {
1629       $abs_name = $this->_mod_mailbox($folder);
1630       if (!in_array_nocase($abs_name, $a_subscribed))
1631         {
1632         if (!in_array_nocase($abs_name, $a_folders))
1633           $this->create_mailbox($folder, TRUE);
1634         else
1635           $this->subscribe($folder);
1636         }
1637       }
1638     }
4e17e6 1639
T 1640
1641
1642   /* --------------------------------
1cded8 1643    *   internal caching methods
4e17e6 1644    * --------------------------------*/
6dc026 1645
T 1646
1647   function set_caching($set)
1648     {
1cded8 1649     if ($set && is_object($this->db))
6dc026 1650       $this->caching_enabled = TRUE;
T 1651     else
1652       $this->caching_enabled = FALSE;
1653     }
1cded8 1654
4e17e6 1655
T 1656   function get_cache($key)
1657     {
1658     // read cache
6dc026 1659     if (!isset($this->cache[$key]) && $this->caching_enabled)
4e17e6 1660       {
1cded8 1661       $cache_data = $this->_read_cache_record('IMAP.'.$key);
4e17e6 1662       $this->cache[$key] = strlen($cache_data) ? unserialize($cache_data) : FALSE;
T 1663       }
1664     
1cded8 1665     return $this->cache[$key];
4e17e6 1666     }
T 1667
1668
1669   function update_cache($key, $data)
1670     {
1671     $this->cache[$key] = $data;
1672     $this->cache_changed = TRUE;
1673     $this->cache_changes[$key] = TRUE;
1674     }
1675
1676
1677   function write_cache()
1678     {
6dc026 1679     if ($this->caching_enabled && $this->cache_changed)
4e17e6 1680       {
T 1681       foreach ($this->cache as $key => $data)
1682         {
1683         if ($this->cache_changes[$key])
1cded8 1684           $this->_write_cache_record('IMAP.'.$key, serialize($data));
4e17e6 1685         }
T 1686       }    
1687     }
1688
1689
1690   function clear_cache($key=NULL)
1691     {
1692     if ($key===NULL)
1693       {
1694       foreach ($this->cache as $key => $data)
1cded8 1695         $this->_clear_cache_record('IMAP.'.$key);
4e17e6 1696
T 1697       $this->cache = array();
1698       $this->cache_changed = FALSE;
1699       $this->cache_changes = array();
1700       }
1701     else
1702       {
1cded8 1703       $this->_clear_cache_record('IMAP.'.$key);
4e17e6 1704       $this->cache_changes[$key] = FALSE;
T 1705       unset($this->cache[$key]);
1706       }
1707     }
1708
1709
1710
1cded8 1711   function _read_cache_record($key)
T 1712     {
1713     $cache_data = FALSE;
1714     
1715     if ($this->db)
1716       {
1717       // get cached data from DB
1718       $sql_result = $this->db->query(
1719         "SELECT cache_id, data
1720          FROM ".get_table_name('cache')."
1721          WHERE  user_id=?
1722          AND    cache_key=?",
1723         $_SESSION['user_id'],
1724         $key);
1725
1726       if ($sql_arr = $this->db->fetch_assoc($sql_result))
1727         {
1728         $cache_data = $sql_arr['data'];
1729         $this->cache_keys[$key] = $sql_arr['cache_id'];
1730         }
1731       }
1732
1733     return $cache_data;    
1734     }
1735     
1736
1737   function _write_cache_record($key, $data)
1738     {
1739     if (!$this->db)
1740       return FALSE;
1741
1742     // check if we already have a cache entry for this key
1743     if (!isset($this->cache_keys[$key]))
1744       {
1745       $sql_result = $this->db->query(
1746         "SELECT cache_id
1747          FROM ".get_table_name('cache')."
1748          WHERE  user_id=?
1749          AND    cache_key=?",
1750         $_SESSION['user_id'],
1751         $key);
1752                                      
1753       if ($sql_arr = $this->db->fetch_assoc($sql_result))
1754         $this->cache_keys[$key] = $sql_arr['cache_id'];
1755       else
1756         $this->cache_keys[$key] = FALSE;
1757       }
1758
1759     // update existing cache record
1760     if ($this->cache_keys[$key])
1761       {
1762       $this->db->query(
1763         "UPDATE ".get_table_name('cache')."
107bde 1764          SET    created=".$this->db->now().",
1cded8 1765                 data=?
T 1766          WHERE  user_id=?
1767          AND    cache_key=?",
1768         $data,
1769         $_SESSION['user_id'],
1770         $key);
1771       }
1772     // add new cache record
1773     else
1774       {
1775       $this->db->query(
1776         "INSERT INTO ".get_table_name('cache')."
1777          (created, user_id, cache_key, data)
107bde 1778          VALUES (".$this->db->now().", ?, ?, ?)",
1cded8 1779         $_SESSION['user_id'],
T 1780         $key,
1781         $data);
1782       }
1783     }
1784
1785
1786   function _clear_cache_record($key)
1787     {
1788     $this->db->query(
1789       "DELETE FROM ".get_table_name('cache')."
1790        WHERE  user_id=?
1791        AND    cache_key=?",
1792       $_SESSION['user_id'],
1793       $key);
1794     }
1795
1796
1797
4e17e6 1798   /* --------------------------------
1cded8 1799    *   message caching methods
T 1800    * --------------------------------*/
1801    
1802
1803   // checks if the cache is up-to-date
1804   // return: -3 = off, -2 = incomplete, -1 = dirty
1805   function check_cache_status($mailbox, $cache_key)
1806     {
1807     if (!$this->caching_enabled)
1808       return -3;
1809
1810     $cache_index = $this->get_message_cache_index($cache_key, TRUE);
1811     $msg_count = $this->_messagecount($mailbox);
1812     $cache_count = count($cache_index);
1813
1814     // console("Cache check: $msg_count !== ".count($cache_index));
1815
1816     if ($cache_count==$msg_count)
1817       {
1818       // get highest index
1819       $header = iil_C_FetchHeader($this->conn, $mailbox, "$msg_count");
1820       $cache_uid = array_pop($cache_index);
1821       
e6f360 1822       // uids of highest message matches -> cache seems OK
1cded8 1823       if ($cache_uid == $header->uid)
T 1824         return 1;
1825
1826       // cache is dirty
1827       return -1;
1828       }
e6f360 1829     // if cache count differs less than 10% report as dirty
1cded8 1830     else if (abs($msg_count - $cache_count) < $msg_count/10)
T 1831       return -1;
1832     else
1833       return -2;
1834     }
1835
1836
1837
1838   function get_message_cache($key, $from, $to, $sort_field, $sort_order)
1839     {
1840     $cache_key = "$key:$from:$to:$sort_field:$sort_order";
1841     $db_header_fields = array('idx', 'uid', 'subject', 'from', 'to', 'cc', 'date', 'size');
1842     
1843     if (!in_array($sort_field, $db_header_fields))
1844       $sort_field = 'idx';
1845     
1846     if ($this->caching_enabled && !isset($this->cache[$cache_key]))
1847       {
1848       $this->cache[$cache_key] = array();
1849       $sql_result = $this->db->limitquery(
1850         "SELECT idx, uid, headers
1851          FROM ".get_table_name('messages')."
1852          WHERE  user_id=?
1853          AND    cache_key=?
1854          ORDER BY ".$this->db->quoteIdentifier($sort_field)." ".
1855          strtoupper($sort_order),
1856         $from,
1857         $to-$from,
1858         $_SESSION['user_id'],
1859         $key);
1860
1861       while ($sql_arr = $this->db->fetch_assoc($sql_result))
1862         {
1863         $uid = $sql_arr['uid'];
1864         $this->cache[$cache_key][$uid] = unserialize($sql_arr['headers']);
1865         }
1866       }
1867       
1868     return $this->cache[$cache_key];
1869     }
1870
1871
f7bfec 1872   function &get_cached_message($key, $uid, $struct=false)
1cded8 1873     {
T 1874     if (!$this->caching_enabled)
1875       return FALSE;
1876
1877     $internal_key = '__single_msg';
f7bfec 1878     if ($this->caching_enabled && (!isset($this->cache[$internal_key][$uid]) ||
T 1879         ($struct && empty($this->cache[$internal_key][$uid]->structure))))
1cded8 1880       {
f7bfec 1881       $sql_select = "idx, uid, headers" . ($struct ? ", structure" : '');
1cded8 1882       $sql_result = $this->db->query(
T 1883         "SELECT $sql_select
1884          FROM ".get_table_name('messages')."
1885          WHERE  user_id=?
1886          AND    cache_key=?
1887          AND    uid=?",
1888         $_SESSION['user_id'],
1889         $key,
1890         $uid);
f7bfec 1891
1cded8 1892       if ($sql_arr = $this->db->fetch_assoc($sql_result))
T 1893         {
f7bfec 1894         $this->cache[$internal_key][$uid] = unserialize($sql_arr['headers']);
T 1895         if (is_object($this->cache[$internal_key][$uid]) && !empty($sql_arr['structure']))
1896           $this->cache[$internal_key][$uid]->structure = unserialize($sql_arr['structure']);
1cded8 1897         }
T 1898       }
1899
1900     return $this->cache[$internal_key][$uid];
1901     }
1902
1903    
0677ca 1904   function get_message_cache_index($key, $force=FALSE, $sort_col='idx', $sort_order='ASC')
1cded8 1905     {
T 1906     static $sa_message_index = array();
1907     
4647e1 1908     // empty key -> empty array
T 1909     if (empty($key))
1910       return array();
1911     
1cded8 1912     if (!empty($sa_message_index[$key]) && !$force)
T 1913       return $sa_message_index[$key];
1914     
1915     $sa_message_index[$key] = array();
1916     $sql_result = $this->db->query(
1917       "SELECT idx, uid
1918        FROM ".get_table_name('messages')."
1919        WHERE  user_id=?
1920        AND    cache_key=?
0677ca 1921        ORDER BY ".$this->db->quote_identifier($sort_col)." ".$sort_order,
1cded8 1922       $_SESSION['user_id'],
T 1923       $key);
1924
1925     while ($sql_arr = $this->db->fetch_assoc($sql_result))
1926       $sa_message_index[$key][$sql_arr['idx']] = $sql_arr['uid'];
1927       
1928     return $sa_message_index[$key];
1929     }
1930
1931
f7bfec 1932   function add_message_cache($key, $index, $headers, $struct=null)
1cded8 1933     {
f7bfec 1934     if (empty($key) || !is_object($headers) || empty($headers->uid))
31b2ce 1935       return;
f7bfec 1936       
T 1937     // check for an existing record (probly headers are cached but structure not)
1938     $sql_result = $this->db->query(
1939         "SELECT message_id
1940          FROM ".get_table_name('messages')."
1941          WHERE  user_id=?
1942          AND    cache_key=?
1943          AND    uid=?
1944          AND    del<>1",
1945         $_SESSION['user_id'],
1946         $key,
1947         $headers->uid);
31b2ce 1948
f7bfec 1949     // update cache record
T 1950     if ($sql_arr = $this->db->fetch_assoc($sql_result))
1951       {
1952       $this->db->query(
1953         "UPDATE ".get_table_name('messages')."
1954          SET   idx=?, headers=?, structure=?
1955          WHERE message_id=?",
1956         $index,
1957         serialize($headers),
1958         is_object($struct) ? serialize($struct) : NULL,
1959         $sql_arr['message_id']
1960         );
1961       }
1962     else  // insert new record
1963       {
1964       $this->db->query(
1965         "INSERT INTO ".get_table_name('messages')."
1966          (user_id, del, cache_key, created, idx, uid, subject, ".$this->db->quoteIdentifier('from').", ".$this->db->quoteIdentifier('to').", cc, date, size, headers, structure)
107bde 1967          VALUES (?, 0, ?, ".$this->db->now().", ?, ?, ?, ?, ?, ?, ".$this->db->fromunixtime($headers->timestamp).", ?, ?, ?)",
f7bfec 1968         $_SESSION['user_id'],
T 1969         $key,
1970         $index,
1971         $headers->uid,
1972         (string)substr($this->decode_header($headers->subject, TRUE), 0, 128),
1973         (string)substr($this->decode_header($headers->from, TRUE), 0, 128),
1974         (string)substr($this->decode_header($headers->to, TRUE), 0, 128),
1975         (string)substr($this->decode_header($headers->cc, TRUE), 0, 128),
1976         (int)$headers->size,
1977         serialize($headers),
1978         is_object($struct) ? serialize($struct) : NULL
1979         );
1980       }
1cded8 1981     }
T 1982     
1983     
1984   function remove_message_cache($key, $index)
1985     {
1986     $this->db->query(
1987       "DELETE FROM ".get_table_name('messages')."
1988        WHERE  user_id=?
1989        AND    cache_key=?
1990        AND    idx=?",
1991       $_SESSION['user_id'],
1992       $key,
1993       $index);
1994     }
1995
1996
1997   function clear_message_cache($key, $start_index=1)
1998     {
1999     $this->db->query(
2000       "DELETE FROM ".get_table_name('messages')."
2001        WHERE  user_id=?
2002        AND    cache_key=?
2003        AND    idx>=?",
2004       $_SESSION['user_id'],
2005       $key,
2006       $start_index);
2007     }
2008
2009
2010
2011
2012   /* --------------------------------
2013    *   encoding/decoding methods
4e17e6 2014    * --------------------------------*/
T 2015
2016   
2017   function decode_address_list($input, $max=NULL)
2018     {
2019     $a = $this->_parse_address_list($input);
2020     $out = array();
41fa0b 2021     
4e17e6 2022     if (!is_array($a))
T 2023       return $out;
2024
2025     $c = count($a);
2026     $j = 0;
2027
2028     foreach ($a as $val)
2029       {
2030       $j++;
2031       $address = $val['address'];
2032       $name = preg_replace(array('/^[\'"]/', '/[\'"]$/'), '', trim($val['name']));
2033       $string = $name!==$address ? sprintf('%s <%s>', strpos($name, ',')!==FALSE ? '"'.$name.'"' : $name, $address) : $address;
2034       
2035       $out[$j] = array('name' => $name,
2036                        'mailto' => $address,
2037                        'string' => $string);
2038               
2039       if ($max && $j==$max)
2040         break;
2041       }
2042     
2043     return $out;
2044     }
2045
2046
1cded8 2047   function decode_header($input, $remove_quotes=FALSE)
4e17e6 2048     {
31b2ce 2049     $str = $this->decode_mime_string((string)$input);
1cded8 2050     if ($str{0}=='"' && $remove_quotes)
T 2051       {
2052       $str = str_replace('"', '', $str);
2053       }
2054     
2055     return $str;
4b0f65 2056     }
ba8f44 2057
T 2058
2059   /**
2060    * Decode a mime-encoded string to internal charset
2061    *
2062    * @access static
2063    */
bac7d1 2064   function decode_mime_string($input, $recursive=false)
4b0f65 2065     {
4e17e6 2066     $out = '';
T 2067
2068     $pos = strpos($input, '=?');
2069     if ($pos !== false)
2070       {
2071       $out = substr($input, 0, $pos);
2072   
2073       $end_cs_pos = strpos($input, "?", $pos+2);
2074       $end_en_pos = strpos($input, "?", $end_cs_pos+1);
2075       $end_pos = strpos($input, "?=", $end_en_pos+1);
2076   
2077       $encstr = substr($input, $pos+2, ($end_pos-$pos-2));
2078       $rest = substr($input, $end_pos+2);
2079
4b0f65 2080       $out .= rcube_imap::_decode_mime_string_part($encstr);
T 2081       $out .= rcube_imap::decode_mime_string($rest);
4e17e6 2082
T 2083       return $out;
2084       }
bac7d1 2085       
fb5f4f 2086     // no encoding information, defaults to what is specified in the class header
ba8f44 2087     return rcube_charset_convert($input, 'ISO-8859-1');
4e17e6 2088     }
T 2089
2090
ba8f44 2091   /**
T 2092    * Decode a part of a mime-encoded string
2093    *
2094    * @access static
2095    */
4b0f65 2096   function _decode_mime_string_part($str)
4e17e6 2097     {
T 2098     $a = explode('?', $str);
2099     $count = count($a);
2100
2101     // should be in format "charset?encoding?base64_string"
2102     if ($count >= 3)
2103       {
2104       for ($i=2; $i<$count; $i++)
2105         $rest.=$a[$i];
2106
2107       if (($a[1]=="B")||($a[1]=="b"))
2108         $rest = base64_decode($rest);
2109       else if (($a[1]=="Q")||($a[1]=="q"))
2110         {
2111         $rest = str_replace("_", " ", $rest);
2112         $rest = quoted_printable_decode($rest);
2113         }
2114
3f9edb 2115       return rcube_charset_convert($rest, $a[0]);
4e17e6 2116       }
T 2117     else
3f9edb 2118       return $str;    // we dont' know what to do with this  
4e17e6 2119     }
T 2120
2121
2122   function mime_decode($input, $encoding='7bit')
2123     {
2124     switch (strtolower($encoding))
2125       {
2126       case '7bit':
2127         return $input;
2128         break;
2129       
2130       case 'quoted-printable':
2131         return quoted_printable_decode($input);
2132         break;
2133       
2134       case 'base64':
2135         return base64_decode($input);
2136         break;
2137       
2138       default:
2139         return $input;
2140       }
2141     }
2142
2143
2144   function mime_encode($input, $encoding='7bit')
2145     {
2146     switch ($encoding)
2147       {
2148       case 'quoted-printable':
2149         return quoted_printable_encode($input);
2150         break;
2151
2152       case 'base64':
2153         return base64_encode($input);
2154         break;
2155
2156       default:
2157         return $input;
2158       }
2159     }
2160
2161
2162   // convert body chars according to the ctype_parameters
2163   function charset_decode($body, $ctype_param)
2164     {
a95e0e 2165     if (is_array($ctype_param) && !empty($ctype_param['charset']))
3f9edb 2166       return rcube_charset_convert($body, $ctype_param['charset']);
4e17e6 2167
fb5f4f 2168     // defaults to what is specified in the class header
ba8f44 2169     return rcube_charset_convert($body,  'ISO-8859-1');
4e17e6 2170     }
T 2171
2172
1cded8 2173
ba8f44 2174
4e17e6 2175   /* --------------------------------
T 2176    *         private methods
2177    * --------------------------------*/
2178
2179
aadfa1 2180   function _mod_mailbox($mbox_name, $mode='in')
4e17e6 2181     {
fa4cd2 2182     if ((!empty($this->root_ns) && $this->root_ns == $mbox_name) || $mbox_name == 'INBOX')
aadfa1 2183       return $mbox_name;
7902df 2184
f619de 2185     if (!empty($this->root_dir) && $mode=='in') 
aadfa1 2186       $mbox_name = $this->root_dir.$this->delimiter.$mbox_name;
7902df 2187     else if (strlen($this->root_dir) && $mode=='out') 
aadfa1 2188       $mbox_name = substr($mbox_name, strlen($this->root_dir)+1);
4e17e6 2189
aadfa1 2190     return $mbox_name;
4e17e6 2191     }
T 2192
2193
2194   // sort mailboxes first by default folders and then in alphabethical order
2195   function _sort_mailbox_list($a_folders)
2196     {
2197     $a_out = $a_defaults = array();
2198
2199     // find default folders and skip folders starting with '.'
2200     foreach($a_folders as $i => $folder)
2201       {
2202       if ($folder{0}=='.')
2203           continue;
fa4cd2 2204
T 2205       if (($p = array_search(strtolower($folder), $this->default_folders_lc))!==FALSE)
4e17e6 2206           $a_defaults[$p] = $folder;
T 2207       else
2208         $a_out[] = $folder;
2209       }
2210
2211     sort($a_out);
2212     ksort($a_defaults);
2213     
2214     return array_merge($a_defaults, $a_out);
2215     }
2216
1966c5 2217   function get_id($uid, $mbox_name=NULL) 
e6f360 2218     {
1966c5 2219       return $this->_uid2id($uid, $mbox_name);
e6f360 2220     }
T 2221   
1966c5 2222   function get_uid($id,$mbox_name=NULL)
e6f360 2223     {
1966c5 2224       return $this->_id2uid($id, $mbox_name);
e6f360 2225     }
4e17e6 2226
aadfa1 2227   function _uid2id($uid, $mbox_name=NULL)
4e17e6 2228     {
aadfa1 2229     if (!$mbox_name)
S 2230       $mbox_name = $this->mailbox;
4e17e6 2231       
aadfa1 2232     if (!isset($this->uid_id_map[$mbox_name][$uid]))
S 2233       $this->uid_id_map[$mbox_name][$uid] = iil_C_UID2ID($this->conn, $mbox_name, $uid);
4e17e6 2234
aadfa1 2235     return $this->uid_id_map[$mbox_name][$uid];
4e17e6 2236     }
T 2237
aadfa1 2238   function _id2uid($id, $mbox_name=NULL)
e6f360 2239     {
aadfa1 2240     if (!$mbox_name)
S 2241       $mbox_name = $this->mailbox;
e6f360 2242       
aadfa1 2243     return iil_C_ID2UID($this->conn, $mbox_name, $id);
e6f360 2244     }
T 2245
4e17e6 2246
1cded8 2247   // parse string or array of server capabilities and put them in internal array
T 2248   function _parse_capability($caps)
2249     {
2250     if (!is_array($caps))
2251       $cap_arr = explode(' ', $caps);
2252     else
2253       $cap_arr = $caps;
2254     
2255     foreach ($cap_arr as $cap)
2256       {
2257       if ($cap=='CAPABILITY')
2258         continue;
2259
2260       if (strpos($cap, '=')>0)
2261         {
2262         list($key, $value) = explode('=', $cap);
2263         if (!is_array($this->capabilities[$key]))
2264           $this->capabilities[$key] = array();
2265           
2266         $this->capabilities[$key][] = $value;
2267         }
2268       else
2269         $this->capabilities[$cap] = TRUE;
2270       }
2271     }
2272
2273
4e17e6 2274   // subscribe/unsubscribe a list of mailboxes and update local cache
T 2275   function _change_subscription($a_mboxes, $mode)
2276     {
2277     $updated = FALSE;
2278     
2279     if (is_array($a_mboxes))
aadfa1 2280       foreach ($a_mboxes as $i => $mbox_name)
4e17e6 2281         {
aadfa1 2282         $mailbox = $this->_mod_mailbox($mbox_name);
4e17e6 2283         $a_mboxes[$i] = $mailbox;
T 2284
2285         if ($mode=='subscribe')
2286           $result = iil_C_Subscribe($this->conn, $mailbox);
2287         else if ($mode=='unsubscribe')
2288           $result = iil_C_UnSubscribe($this->conn, $mailbox);
2289
2290         if ($result>=0)
2291           $updated = TRUE;
2292         }
2293         
2294     // get cached mailbox list    
2295     if ($updated)
2296       {
2297       $a_mailbox_cache = $this->get_cache('mailboxes');
2298       if (!is_array($a_mailbox_cache))
2299         return $updated;
2300
2301       // modify cached list
2302       if ($mode=='subscribe')
2303         $a_mailbox_cache = array_merge($a_mailbox_cache, $a_mboxes);
2304       else if ($mode=='unsubscribe')
2305         $a_mailbox_cache = array_diff($a_mailbox_cache, $a_mboxes);
2306         
2307       // write mailboxlist to cache
2308       $this->update_cache('mailboxes', $this->_sort_mailbox_list($a_mailbox_cache));
2309       }
2310
2311     return $updated;
2312     }
2313
2314
2315   // increde/decrese messagecount for a specific mailbox
aadfa1 2316   function _set_messagecount($mbox_name, $mode, $increment)
4e17e6 2317     {
T 2318     $a_mailbox_cache = FALSE;
aadfa1 2319     $mailbox = $mbox_name ? $mbox_name : $this->mailbox;
4e17e6 2320     $mode = strtoupper($mode);
T 2321
2322     $a_mailbox_cache = $this->get_cache('messagecount');
2323     
2324     if (!is_array($a_mailbox_cache[$mailbox]) || !isset($a_mailbox_cache[$mailbox][$mode]) || !is_numeric($increment))
2325       return FALSE;
2326     
2327     // add incremental value to messagecount
2328     $a_mailbox_cache[$mailbox][$mode] += $increment;
31b2ce 2329     
T 2330     // there's something wrong, delete from cache
2331     if ($a_mailbox_cache[$mailbox][$mode] < 0)
2332       unset($a_mailbox_cache[$mailbox][$mode]);
4e17e6 2333
T 2334     // write back to cache
2335     $this->update_cache('messagecount', $a_mailbox_cache);
2336     
2337     return TRUE;
2338     }
2339
2340
2341   // remove messagecount of a specific mailbox from cache
aadfa1 2342   function _clear_messagecount($mbox_name='')
4e17e6 2343     {
T 2344     $a_mailbox_cache = FALSE;
aadfa1 2345     $mailbox = $mbox_name ? $mbox_name : $this->mailbox;
4e17e6 2346
T 2347     $a_mailbox_cache = $this->get_cache('messagecount');
2348
2349     if (is_array($a_mailbox_cache[$mailbox]))
2350       {
2351       unset($a_mailbox_cache[$mailbox]);
2352       $this->update_cache('messagecount', $a_mailbox_cache);
2353       }
2354     }
2355
2356
8d4bcd 2357   // split RFC822 header string into an associative array
T 2358   function _parse_headers($headers)
2359     {
2360     $a_headers = array();
2361     $lines = explode("\n", $headers);
2362     $c = count($lines);
2363     for ($i=0; $i<$c; $i++)
2364       {
2365       if ($p = strpos($lines[$i], ': '))
2366         {
2367         $field = strtolower(substr($lines[$i], 0, $p));
2368         $value = trim(substr($lines[$i], $p+1));
2369         if (!empty($value))
2370           $a_headers[$field] = $value;
2371         }
2372       }
2373     
2374     return $a_headers;
2375     }
2376
2377
4e17e6 2378   function _parse_address_list($str)
T 2379     {
2380     $a = $this->_explode_quoted_string(',', $str);
2381     $result = array();
41fa0b 2382     
4e17e6 2383     foreach ($a as $key => $val)
T 2384       {
2385       $val = str_replace("\"<", "\" <", $val);
41fa0b 2386       $sub_a = $this->_explode_quoted_string(' ', $this->decode_header($val));
T 2387       $result[$key]['name'] = '';
2388
4e17e6 2389       foreach ($sub_a as $k => $v)
T 2390         {
2391         if ((strpos($v, '@') > 0) && (strpos($v, '.') > 0)) 
2392           $result[$key]['address'] = str_replace('<', '', str_replace('>', '', $v));
2393         else
2394           $result[$key]['name'] .= (empty($result[$key]['name'])?'':' ').str_replace("\"",'',stripslashes($v));
2395         }
2396         
2397       if (empty($result[$key]['name']))
41fa0b 2398         $result[$key]['name'] = $result[$key]['address'];        
4e17e6 2399       }
T 2400     
2401     return $result;
2402     }
2403
2404
2405   function _explode_quoted_string($delimiter, $string)
2406     {
2407     $quotes = explode("\"", $string);
2408     foreach ($quotes as $key => $val)
2409       if (($key % 2) == 1)
2410         $quotes[$key] = str_replace($delimiter, "_!@!_", $quotes[$key]);
2411         
2412     $string = implode("\"", $quotes);
2413
2414     $result = explode($delimiter, $string);
2415     foreach ($result as $key => $val) 
2416       $result[$key] = str_replace("_!@!_", $delimiter, $result[$key]);
2417     
2418     return $result;
2419     }
2420   }
2421
8d4bcd 2422
T 2423 /**
2424  * Class representing a message part
2425  */
2426 class rcube_message_part
2427 {
2428   var $mime_id = '';
2429   var $ctype_primary = 'text';
2430   var $ctype_secondary = 'plain';
2431   var $mimetype = 'text/plain';
2432   var $disposition = '';
2433   var $encoding = '8bit';
2434   var $charset = '';
2435   var $size = 0;
2436   var $headers = array();
2437   var $d_parameters = array();
2438   var $ctype_parameters = array();
2439
2440 }
4e17e6 2441
T 2442
7e93ff 2443 /**
T 2444  * rcube_header_sorter
2445  * 
2446  * Class for sorting an array of iilBasicHeader objects in a predetermined order.
2447  *
2448  * @author Eric Stadtherr
2449  */
2450 class rcube_header_sorter
2451 {
2452    var $sequence_numbers = array();
2453    
2454    /**
2455     * set the predetermined sort order.
2456     *
2457     * @param array $seqnums numerically indexed array of IMAP message sequence numbers
2458     */
2459    function set_sequence_numbers($seqnums)
2460    {
2461       $this->sequence_numbers = $seqnums;
2462    }
2463  
2464    /**
2465     * sort the array of header objects
2466     *
2467     * @param array $headers array of iilBasicHeader objects indexed by UID
2468     */
2469    function sort_headers(&$headers)
2470    {
2471       /*
2472        * uksort would work if the keys were the sequence number, but unfortunately
2473        * the keys are the UIDs.  We'll use uasort instead and dereference the value
2474        * to get the sequence number (in the "id" field).
2475        * 
2476        * uksort($headers, array($this, "compare_seqnums")); 
2477        */
2478        uasort($headers, array($this, "compare_seqnums"));
2479    }
2480  
2481    /**
2482     * get the position of a message sequence number in my sequence_numbers array
2483     *
2484     * @param integer $seqnum message sequence number contained in sequence_numbers  
2485     */
2486    function position_of($seqnum)
2487    {
2488       $c = count($this->sequence_numbers);
2489       for ($pos = 0; $pos <= $c; $pos++)
2490       {
2491          if ($this->sequence_numbers[$pos] == $seqnum)
2492             return $pos;
2493       }
2494       return -1;
2495    }
2496  
2497    /**
2498     * Sort method called by uasort()
2499     */
2500    function compare_seqnums($a, $b)
2501    {
2502       // First get the sequence number from the header object (the 'id' field).
2503       $seqa = $a->id;
2504       $seqb = $b->id;
2505       
2506       // then find each sequence number in my ordered list
2507       $posa = $this->position_of($seqa);
2508       $posb = $this->position_of($seqb);
2509       
2510       // return the relative position as the comparison value
2511       $ret = $posa - $posb;
2512       return $ret;
2513    }
2514 }
4e17e6 2515
T 2516
7e93ff 2517 /**
T 2518  * Add quoted-printable encoding to a given string
2519  * 
2520  * @param string  $input      string to encode
2521  * @param int     $line_max   add new line after this number of characters
2522  * @param boolena $space_conf true if spaces should be converted into =20
2523  * @return encoded string
2524  */
2525 function quoted_printable_encode($input, $line_max=76, $space_conv=false)
4e17e6 2526   {
T 2527   $hex = array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');
2528   $lines = preg_split("/(?:\r\n|\r|\n)/", $input);
2529   $eol = "\r\n";
2530   $escape = "=";
2531   $output = "";
2532
2533   while( list(, $line) = each($lines))
2534     {
2535     //$line = rtrim($line); // remove trailing white space -> no =20\r\n necessary
2536     $linlen = strlen($line);
2537     $newline = "";
2538     for($i = 0; $i < $linlen; $i++)
2539       {
2540       $c = substr( $line, $i, 1 );
2541       $dec = ord( $c );
2542       if ( ( $i == 0 ) && ( $dec == 46 ) ) // convert first point in the line into =2E
2543         {
2544         $c = "=2E";
2545         }
2546       if ( $dec == 32 )
2547         {
2548         if ( $i == ( $linlen - 1 ) ) // convert space at eol only
2549           {
2550           $c = "=20";
2551           }
2552         else if ( $space_conv )
2553           {
2554           $c = "=20";
2555           }
2556         }
2557       else if ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) )  // always encode "\t", which is *not* required
2558         {
2559         $h2 = floor($dec/16);
2560         $h1 = floor($dec%16);
2561         $c = $escape.$hex["$h2"].$hex["$h1"];
2562         }
2563          
2564       if ( (strlen($newline) + strlen($c)) >= $line_max )  // CRLF is not counted
2565         {
2566         $output .= $newline.$escape.$eol; // soft line break; " =\r\n" is okay
2567         $newline = "";
2568         // check if newline first character will be point or not
2569         if ( $dec == 46 )
2570           {
2571           $c = "=2E";
2572           }
2573         }
2574       $newline .= $c;
2575       } // end of for
2576     $output .= $newline.$eol;
2577     } // end of while
2578
2579   return trim($output);
2580   }
2581
8d4bcd 2582
1966c5 2583 ?>