source: subversion/trunk/roundcubemail/program/include/rcube_imap.php @ 1380

Last change on this file since 1380 was 1380, checked in by alec, 5 years ago

-added check for caching_enabled (#1485051)

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