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

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

applied tensor's patch: incorrect handling of filename of second and subsequent long non-ASCII attachments

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