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

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

Remove newlines from mail headers (#1484031)

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