source: subversion/trunk/roundcubemail/program/include/rcube_imap.inc @ 692

Last change on this file since 692 was 692, checked in by thomasb, 6 years ago

Clear cache when compacting a folder (reported by Joan)

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