source: github/program/include/rcube_imap.inc @ d5342aa

HEADcourier-fixdev-browser-capabilitiespdorelease-0.6release-0.7release-0.8
Last change on this file since d5342aa was d5342aa, checked in by thomascube <thomas@…>, 5 years ago

More input sanitizing

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