source: github/program/include/rcube_imap.inc @ 04c6180

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

Fixed wrong message listing when showing search results

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