source: github/program/include/rcube_imap.inc @ 107bde9

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

Added MSSQL support

  • 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) - 3;
1016    if (is_array($part[$di]))
1017      {
1018      $struct->disposition = strtolower($part[$di][0]);
1019
1020      if (is_array($part[$di][1]))
1021        for ($n=0; $n<count($part[$di][1]); $n+=2)
1022          $struct->d_parameters[strtolower($part[$di][1][$n])] = $part[$di][1][$n+1];
1023      }
1024     
1025    // get child parts
1026    if (is_array($part[8]) && $di != 8)
1027      {
1028      $struct->parts = array();
1029      for ($i=0, $count=0; $i<count($part[8]); $i++)
1030        if (is_array($part[8][$i]) && count($part[8][$i]) > 5)
1031          $struct->parts[] = $this->_structure_part($part[8][$i], ++$count, $struct->mime_id);
1032      }
1033     
1034        // get part ID
1035        if (!empty($part[3]) && $part[3]!='NIL')
1036          {
1037          $struct->content_id = $part[3];
1038          $struct->headers['content-id'] = $part[3];
1039         
1040          if (empty($struct->disposition))
1041            $struct->disposition = 'inline';
1042          }
1043
1044    // fetch message headers if message/rfc822
1045    if ($struct->ctype_primary=='message')
1046      {
1047      $headers = iil_C_FetchPartBody($this->conn, $this->mailbox, $this->_msg_id, $struct->mime_id.'.HEADER');
1048      $struct->headers = $this->_parse_headers($headers);
1049      }
1050 
1051        return $struct;
1052    }
1053   
1054 
1055  /**
1056   * Return a flat array with references to all parts, indexed by part numbmers
1057   *
1058   * @param object Message body structure
1059   * @return Array with part number -> object pairs
1060   */
1061  function get_mime_numbers(&$structure)
1062    {
1063    $a_parts = array();
1064    $this->_get_part_numbers($structure, $a_parts);
1065    return $a_parts;
1066    }
1067 
1068 
1069  /**
1070   * Helper method for recursive calls
1071   *
1072   * @access
1073   */
1074  function _get_part_numbers(&$part, &$a_parts)
1075    {
1076    if ($part->mime_id)
1077      $a_parts[$part->mime_id] = &$part;
1078     
1079    if (is_array($part->parts))
1080      for ($i=0; $i<count($part->parts); $i++)
1081        $this->_get_part_numbers($part->parts[$i], $a_parts);
1082    }
1083 
1084
1085  /**
1086   * Fetch message body of a specific message from the server
1087   *
1088   * @param  int    Message UID
1089   * @param  string Part number
1090   * @param  object Part object created by get_structure()
1091   * @param  mixed  True to print part, ressource to write part contents in
1092   * @return Message/part body if not printed
1093   */
1094  function &get_message_part($uid, $part=1, $o_part=NULL, $print=NULL)
1095    {
1096    if (!($msg_id = $this->_uid2id($uid)))
1097      return FALSE;
1098   
1099    // get part encoding if not provided
1100    if (!is_object($o_part))
1101      {
1102      $structure_str = iil_C_FetchStructureString($this->conn, $this->mailbox, $msg_id);
1103      $structure = iml_GetRawStructureArray($structure_str);
1104      $part_type = iml_GetPartTypeCode($structure, $part);
1105      $o_part = new rcube_message_part;
1106      $o_part->ctype_primary = $part_type==0 ? 'text' : ($part_type==2 ? 'message' : 'other');
1107      $o_part->encoding = strtolower(iml_GetPartEncodingString($structure, $part));
1108      $o_part->charset = iml_GetPartCharset($structure, $part);
1109      }
1110     
1111    // TODO: Add caching for message parts
1112
1113    if ($print)
1114      {
1115      iil_C_HandlePartBody($this->conn, $this->mailbox, $msg_id, $part, ($o_part->encoding=='base64'?3:2));
1116      $body = TRUE;
1117      }
1118    else
1119      {
1120      $body = iil_C_HandlePartBody($this->conn, $this->mailbox, $msg_id, $part, 1);
1121
1122      // decode part body
1123      if ($o_part->encoding=='base64' || $o_part->encoding=='quoted-printable')
1124        $body = $this->mime_decode($body, $o_part->encoding);
1125
1126      // convert charset (if text or message part)
1127      if ($o_part->ctype_primary=='text' || $o_part->ctype_primary=='message')
1128        {
1129        // assume ISO-8859-1 if no charset specified
1130        if (empty($o_part->charset))
1131          $o_part->charset = 'ISO-8859-1';
1132
1133        $body = rcube_charset_convert($body, $o_part->charset);
1134        }
1135      }
1136
1137    return $body;
1138    }
1139
1140
1141  /**
1142   * Fetch message body of a specific message from the server
1143   *
1144   * @param  int    Message UID
1145   * @return Message/part body
1146   * @see    ::get_message_part()
1147   */
1148  function &get_body($uid, $part=1)
1149    {
1150    return $this->get_message_part($uid, $part);
1151    }
1152
1153
1154  /**
1155   * Returns the whole message source as string
1156   *
1157   * @param int  Message UID
1158   * @return Message source string
1159   */
1160  function &get_raw_body($uid)
1161    {
1162    if (!($msg_id = $this->_uid2id($uid)))
1163      return FALSE;
1164
1165        $body = iil_C_FetchPartHeader($this->conn, $this->mailbox, $msg_id, NULL);
1166        $body .= iil_C_HandlePartBody($this->conn, $this->mailbox, $msg_id, NULL, 1);
1167
1168    return $body;   
1169    }
1170   
1171
1172  /**
1173   * Sends the whole message source to stdout
1174   *
1175   * @param int  Message UID
1176   */
1177  function print_raw_body($uid)
1178    {
1179    if (!($msg_id = $this->_uid2id($uid)))
1180      return FALSE;
1181
1182        print iil_C_FetchPartHeader($this->conn, $this->mailbox, $msg_id, NULL);
1183        flush();
1184        iil_C_HandlePartBody($this->conn, $this->mailbox, $msg_id, NULL, 2);
1185    }
1186
1187
1188  /**
1189   * Set message flag to one or several messages
1190   *
1191   * @param mixed  Message UIDs as array or as comma-separated string
1192   * @param string Flag to set: SEEN, UNDELETED, DELETED, RECENT, ANSWERED, DRAFT
1193   * @return True on success, False on failure
1194   */
1195  function set_flag($uids, $flag)
1196    {
1197    $flag = strtoupper($flag);
1198    $msg_ids = array();
1199    if (!is_array($uids))
1200      $uids = explode(',',$uids);
1201     
1202    foreach ($uids as $uid) {
1203      $msg_ids[$uid] = $this->_uid2id($uid);
1204    }
1205     
1206    if ($flag=='UNDELETED')
1207      $result = iil_C_Undelete($this->conn, $this->mailbox, join(',', array_values($msg_ids)));
1208    else if ($flag=='UNSEEN')
1209      $result = iil_C_Unseen($this->conn, $this->mailbox, join(',', array_values($msg_ids)));
1210    else
1211      $result = iil_C_Flag($this->conn, $this->mailbox, join(',', array_values($msg_ids)), $flag);
1212
1213    // reload message headers if cached
1214    $cache_key = $this->mailbox.'.msg';
1215    if ($this->caching_enabled)
1216      {
1217      foreach ($msg_ids as $uid => $id)
1218        {
1219        if ($cached_headers = $this->get_cached_message($cache_key, $uid))
1220          {
1221          $this->remove_message_cache($cache_key, $id);
1222          //$this->get_headers($uid);
1223          }
1224        }
1225
1226      // close and re-open connection
1227      // this prevents connection problems with Courier
1228      $this->reconnect();
1229      }
1230
1231    // set nr of messages that were flaged
1232    $count = count($msg_ids);
1233
1234    // clear message count cache
1235    if ($result && $flag=='SEEN')
1236      $this->_set_messagecount($this->mailbox, 'UNSEEN', $count*(-1));
1237    else if ($result && $flag=='UNSEEN')
1238      $this->_set_messagecount($this->mailbox, 'UNSEEN', $count);
1239    else if ($result && $flag=='DELETED')
1240      $this->_set_messagecount($this->mailbox, 'ALL', $count*(-1));
1241
1242    return $result;
1243    }
1244
1245
1246  // append a mail message (source) to a specific mailbox
1247  function save_message($mbox_name, &$message)
1248    {
1249    $mbox_name = stripslashes($mbox_name);
1250    $mailbox = $this->_mod_mailbox($mbox_name);
1251
1252    // make sure mailbox exists
1253    if (in_array($mailbox, $this->_list_mailboxes()))
1254      $saved = iil_C_Append($this->conn, $mailbox, $message);
1255
1256    if ($saved)
1257      {
1258      // increase messagecount of the target mailbox
1259      $this->_set_messagecount($mailbox, 'ALL', 1);
1260      }
1261         
1262    return $saved;
1263    }
1264
1265
1266  // move a message from one mailbox to another
1267  function move_message($uids, $to_mbox, $from_mbox='')
1268    {
1269    $to_mbox = stripslashes($to_mbox);
1270    $from_mbox = stripslashes($from_mbox);
1271    $to_mbox = $this->_mod_mailbox($to_mbox);
1272    $from_mbox = $from_mbox ? $this->_mod_mailbox($from_mbox) : $this->mailbox;
1273
1274    // make sure mailbox exists
1275    if (!in_array($to_mbox, $this->_list_mailboxes()))
1276      {
1277      if (in_array(strtolower($to_mbox), $this->default_folders))
1278        $this->create_mailbox($to_mbox, TRUE);
1279      else
1280        return FALSE;
1281      }
1282
1283    // convert the list of uids to array
1284    $a_uids = is_string($uids) ? explode(',', $uids) : (is_array($uids) ? $uids : NULL);
1285   
1286    // exit if no message uids are specified
1287    if (!is_array($a_uids))
1288      return false;
1289
1290    // convert uids to message ids
1291    $a_mids = array();
1292    foreach ($a_uids as $uid)
1293      $a_mids[] = $this->_uid2id($uid, $from_mbox);
1294
1295    $moved = iil_C_Move($this->conn, join(',', $a_mids), $from_mbox, $to_mbox);
1296   
1297    // send expunge command in order to have the moved message
1298    // really deleted from the source mailbox
1299    if ($moved)
1300      {
1301      $this->_expunge($from_mbox, FALSE);
1302      $this->_clear_messagecount($from_mbox);
1303      $this->_clear_messagecount($to_mbox);
1304      }
1305
1306    // update cached message headers
1307    $cache_key = $from_mbox.'.msg';
1308    if ($moved && ($a_cache_index = $this->get_message_cache_index($cache_key)))
1309      {
1310      $start_index = 100000;
1311      foreach ($a_uids as $uid)
1312        {
1313        if(($index = array_search($uid, $a_cache_index)) !== FALSE)
1314          $start_index = min($index, $start_index);
1315        }
1316
1317      // clear cache from the lowest index on
1318      $this->clear_message_cache($cache_key, $start_index);
1319      }
1320
1321    return $moved;
1322    }
1323
1324
1325  // mark messages as deleted and expunge mailbox
1326  function delete_message($uids, $mbox_name='')
1327    {
1328    $mbox_name = stripslashes($mbox_name);
1329    $mailbox = $mbox_name ? $this->_mod_mailbox($mbox_name) : $this->mailbox;
1330
1331    // convert the list of uids to array
1332    $a_uids = is_string($uids) ? explode(',', $uids) : (is_array($uids) ? $uids : NULL);
1333   
1334    // exit if no message uids are specified
1335    if (!is_array($a_uids))
1336      return false;
1337
1338
1339    // convert uids to message ids
1340    $a_mids = array();
1341    foreach ($a_uids as $uid)
1342      $a_mids[] = $this->_uid2id($uid, $mailbox);
1343       
1344    $deleted = iil_C_Delete($this->conn, $mailbox, join(',', $a_mids));
1345   
1346    // send expunge command in order to have the deleted message
1347    // really deleted from the mailbox
1348    if ($deleted)
1349      {
1350      $this->_expunge($mailbox, FALSE);
1351      $this->_clear_messagecount($mailbox);
1352      }
1353
1354    // remove deleted messages from cache
1355    $cache_key = $mailbox.'.msg';
1356    if ($deleted && ($a_cache_index = $this->get_message_cache_index($cache_key)))
1357      {
1358      $start_index = 100000;
1359      foreach ($a_uids as $uid)
1360        {
1361        $index = array_search($uid, $a_cache_index);
1362        $start_index = min($index, $start_index);
1363        }
1364
1365      // clear cache from the lowest index on
1366      $this->clear_message_cache($cache_key, $start_index);
1367      }
1368
1369    return $deleted;
1370    }
1371
1372
1373  // clear all messages in a specific mailbox
1374  function clear_mailbox($mbox_name=NULL)
1375    {
1376    $mbox_name = stripslashes($mbox_name);
1377    $mailbox = !empty($mbox_name) ? $this->_mod_mailbox($mbox_name) : $this->mailbox;
1378    $msg_count = $this->_messagecount($mailbox, 'ALL');
1379   
1380    if ($msg_count>0)
1381      {
1382      $cleared = iil_C_ClearFolder($this->conn, $mailbox);
1383     
1384      // make sure the message count cache is cleared as well
1385      if ($cleared)
1386        {
1387        $this->clear_message_cache($mailbox.'.msg');     
1388        $a_mailbox_cache = $this->get_cache('messagecount');
1389        unset($a_mailbox_cache[$mailbox]);
1390        $this->update_cache('messagecount', $a_mailbox_cache);
1391        }
1392       
1393      return $cleared;
1394      }
1395    else
1396      return 0;
1397    }
1398
1399
1400  // send IMAP expunge command and clear cache
1401  function expunge($mbox_name='', $clear_cache=TRUE)
1402    {
1403    $mbox_name = stripslashes($mbox_name);
1404    $mailbox = $mbox_name ? $this->_mod_mailbox($mbox_name) : $this->mailbox;
1405    return $this->_expunge($mailbox, $clear_cache);
1406    }
1407
1408
1409  // send IMAP expunge command and clear cache
1410  function _expunge($mailbox, $clear_cache=TRUE)
1411    {
1412    $result = iil_C_Expunge($this->conn, $mailbox);
1413
1414    if ($result>=0 && $clear_cache)
1415      {
1416      //$this->clear_message_cache($mailbox.'.msg');
1417      $this->_clear_messagecount($mailbox);
1418      }
1419     
1420    return $result;
1421    }
1422
1423
1424  /* --------------------------------
1425   *        folder managment
1426   * --------------------------------*/
1427
1428
1429  /**
1430   * Get a list of all folders available on the IMAP server
1431   *
1432   * @param string IMAP root dir
1433   * @return array Inbdexed array with folder names
1434   */
1435  function list_unsubscribed($root='')
1436    {
1437    static $sa_unsubscribed;
1438   
1439    if (is_array($sa_unsubscribed))
1440      return $sa_unsubscribed;
1441     
1442    // retrieve list of folders from IMAP server
1443    $a_mboxes = iil_C_ListMailboxes($this->conn, $this->_mod_mailbox($root), '*');
1444
1445    // modify names with root dir
1446    foreach ($a_mboxes as $mbox_name)
1447      {
1448      $name = $this->_mod_mailbox($mbox_name, 'out');
1449      if (strlen($name))
1450        $a_folders[] = $name;
1451      }
1452
1453    // filter folders and sort them
1454    $sa_unsubscribed = $this->_sort_mailbox_list($a_folders);
1455    return $sa_unsubscribed;
1456    }
1457
1458
1459  /**
1460   * Get quota
1461   * added by Nuny
1462   */
1463  function get_quota()
1464    {
1465    if ($this->get_capability('QUOTA'))
1466      {
1467      $result = iil_C_GetQuota($this->conn);
1468      if ($result["total"])
1469        return sprintf("%.2fMB / %.2fMB (%.0f%%)", $result["used"] / 1000.0, $result["total"] / 1000.0, $result["percent"]);       
1470      }
1471
1472    return FALSE;
1473    }
1474
1475
1476  /**
1477   * subscribe to a specific mailbox(es)
1478   */
1479  function subscribe($mbox_name, $mode='subscribe')
1480    {
1481    if (is_array($mbox_name))
1482      $a_mboxes = $mbox_name;
1483    else if (is_string($mbox_name) && strlen($mbox_name))
1484      $a_mboxes = explode(',', $mbox_name);
1485   
1486    // let this common function do the main work
1487    return $this->_change_subscription($a_mboxes, 'subscribe');
1488    }
1489
1490
1491  /**
1492   * unsubscribe mailboxes
1493   */
1494  function unsubscribe($mbox_name)
1495    {
1496    if (is_array($mbox_name))
1497      $a_mboxes = $mbox_name;
1498    else if (is_string($mbox_name) && strlen($mbox_name))
1499      $a_mboxes = explode(',', $mbox_name);
1500
1501    // let this common function do the main work
1502    return $this->_change_subscription($a_mboxes, 'unsubscribe');
1503    }
1504
1505
1506  /**
1507   * Create a new mailbox on the server and register it in local cache
1508   *
1509   * @param string  New mailbox name (as utf-7 string)
1510   * @param boolean True if the new mailbox should be subscribed
1511   * @param string  Name of the created mailbox, false on error
1512   */
1513  function create_mailbox($name, $subscribe=FALSE)
1514    {
1515    $result = FALSE;
1516   
1517    // replace backslashes
1518    $name = preg_replace('/[\\\]+/', '-', $name);
1519
1520    // reduce mailbox name to 100 chars
1521    $name = substr($name, 0, 100);
1522
1523    $abs_name = $this->_mod_mailbox($name);
1524    $a_mailbox_cache = $this->get_cache('mailboxes');
1525
1526    if (strlen($abs_name) && (!is_array($a_mailbox_cache) || !in_array_nocase($abs_name, $a_mailbox_cache)))
1527      $result = iil_C_CreateFolder($this->conn, $abs_name);
1528
1529    // try to subscribe it
1530    if ($subscribe)
1531      $this->subscribe($name);
1532
1533    return $result ? $name : FALSE;
1534    }
1535
1536
1537  /**
1538   * Set a new name to an existing mailbox
1539   *
1540   * @param string Mailbox to rename (as utf-7 string)
1541   * @param string New mailbox name (as utf-7 string)
1542   * @param string Name of the renames mailbox, false on error
1543   */
1544  function rename_mailbox($mbox_name, $new_name)
1545    {
1546    $result = FALSE;
1547
1548    // replace backslashes
1549    $name = preg_replace('/[\\\]+/', '-', $new_name);
1550       
1551    // encode mailbox name and reduce it to 100 chars
1552    $name = substr($new_name, 0, 100);
1553
1554    // make absolute path
1555    $mailbox = $this->_mod_mailbox($mbox_name);
1556    $abs_name = $this->_mod_mailbox($name);
1557   
1558    // check if mailbox is subscribed
1559    $a_subscribed = $this->_list_mailboxes();
1560    $subscribed = in_array($mailbox, $a_subscribed);
1561   
1562    // unsubscribe folder
1563    if ($subscribed)
1564      iil_C_UnSubscribe($this->conn, $mailbox);
1565
1566    if (strlen($abs_name))
1567      $result = iil_C_RenameFolder($this->conn, $mailbox, $abs_name);
1568
1569    // clear cache
1570    if ($result)
1571      {
1572      $this->clear_message_cache($mailbox.'.msg');
1573      $this->clear_cache('mailboxes');     
1574      }
1575
1576    // try to subscribe it
1577    if ($result && $subscribed)
1578      iil_C_Subscribe($this->conn, $abs_name);
1579
1580    return $result ? $name : FALSE;
1581    }
1582
1583
1584  /**
1585   * remove mailboxes from server
1586   */
1587  function delete_mailbox($mbox_name)
1588    {
1589    $deleted = FALSE;
1590
1591    if (is_array($mbox_name))
1592      $a_mboxes = $mbox_name;
1593    else if (is_string($mbox_name) && strlen($mbox_name))
1594      $a_mboxes = explode(',', $mbox_name);
1595
1596    if (is_array($a_mboxes))
1597      foreach ($a_mboxes as $mbox_name)
1598        {
1599        $mailbox = $this->_mod_mailbox($mbox_name);
1600
1601        // unsubscribe mailbox before deleting
1602        iil_C_UnSubscribe($this->conn, $mailbox);
1603
1604        // send delete command to server
1605        $result = iil_C_DeleteFolder($this->conn, $mailbox);
1606        if ($result>=0)
1607          $deleted = TRUE;
1608        }
1609
1610    // clear mailboxlist cache
1611    if ($deleted)
1612      {
1613      $this->clear_message_cache($mailbox.'.msg');
1614      $this->clear_cache('mailboxes');
1615      }
1616
1617    return $deleted;
1618    }
1619
1620
1621  /**
1622   * Create all folders specified as default
1623   */
1624  function create_default_folders()
1625    {
1626    $a_folders = iil_C_ListMailboxes($this->conn, $this->_mod_mailbox(''), '*');
1627    $a_subscribed = iil_C_ListSubscribed($this->conn, $this->_mod_mailbox(''), '*');
1628   
1629    // create default folders if they do not exist
1630    foreach ($this->default_folders as $folder)
1631      {
1632      $abs_name = $this->_mod_mailbox($folder);
1633      if (!in_array_nocase($abs_name, $a_subscribed))
1634        {
1635        if (!in_array_nocase($abs_name, $a_folders))
1636          $this->create_mailbox($folder, TRUE);
1637        else
1638          $this->subscribe($folder);
1639        }
1640      }
1641    }
1642
1643
1644
1645  /* --------------------------------
1646   *   internal caching methods
1647   * --------------------------------*/
1648
1649
1650  function set_caching($set)
1651    {
1652    if ($set && is_object($this->db))
1653      $this->caching_enabled = TRUE;
1654    else
1655      $this->caching_enabled = FALSE;
1656    }
1657
1658
1659  function get_cache($key)
1660    {
1661    // read cache
1662    if (!isset($this->cache[$key]) && $this->caching_enabled)
1663      {
1664      $cache_data = $this->_read_cache_record('IMAP.'.$key);
1665      $this->cache[$key] = strlen($cache_data) ? unserialize($cache_data) : FALSE;
1666      }
1667   
1668    return $this->cache[$key];
1669    }
1670
1671
1672  function update_cache($key, $data)
1673    {
1674    $this->cache[$key] = $data;
1675    $this->cache_changed = TRUE;
1676    $this->cache_changes[$key] = TRUE;
1677    }
1678
1679
1680  function write_cache()
1681    {
1682    if ($this->caching_enabled && $this->cache_changed)
1683      {
1684      foreach ($this->cache as $key => $data)
1685        {
1686        if ($this->cache_changes[$key])
1687          $this->_write_cache_record('IMAP.'.$key, serialize($data));
1688        }
1689      }   
1690    }
1691
1692
1693  function clear_cache($key=NULL)
1694    {
1695    if ($key===NULL)
1696      {
1697      foreach ($this->cache as $key => $data)
1698        $this->_clear_cache_record('IMAP.'.$key);
1699
1700      $this->cache = array();
1701      $this->cache_changed = FALSE;
1702      $this->cache_changes = array();
1703      }
1704    else
1705      {
1706      $this->_clear_cache_record('IMAP.'.$key);
1707      $this->cache_changes[$key] = FALSE;
1708      unset($this->cache[$key]);
1709      }
1710    }
1711
1712
1713
1714  function _read_cache_record($key)
1715    {
1716    $cache_data = FALSE;
1717   
1718    if ($this->db)
1719      {
1720      // get cached data from DB
1721      $sql_result = $this->db->query(
1722        "SELECT cache_id, data
1723         FROM ".get_table_name('cache')."
1724         WHERE  user_id=?
1725         AND    cache_key=?",
1726        $_SESSION['user_id'],
1727        $key);
1728
1729      if ($sql_arr = $this->db->fetch_assoc($sql_result))
1730        {
1731        $cache_data = $sql_arr['data'];
1732        $this->cache_keys[$key] = $sql_arr['cache_id'];
1733        }
1734      }
1735
1736    return $cache_data;   
1737    }
1738   
1739
1740  function _write_cache_record($key, $data)
1741    {
1742    if (!$this->db)
1743      return FALSE;
1744
1745    // check if we already have a cache entry for this key
1746    if (!isset($this->cache_keys[$key]))
1747      {
1748      $sql_result = $this->db->query(
1749        "SELECT cache_id
1750         FROM ".get_table_name('cache')."
1751         WHERE  user_id=?
1752         AND    cache_key=?",
1753        $_SESSION['user_id'],
1754        $key);
1755                                     
1756      if ($sql_arr = $this->db->fetch_assoc($sql_result))
1757        $this->cache_keys[$key] = $sql_arr['cache_id'];
1758      else
1759        $this->cache_keys[$key] = FALSE;
1760      }
1761
1762    // update existing cache record
1763    if ($this->cache_keys[$key])
1764      {
1765      $this->db->query(
1766        "UPDATE ".get_table_name('cache')."
1767         SET    created=".$this->db->now().",
1768                data=?
1769         WHERE  user_id=?
1770         AND    cache_key=?",
1771        $data,
1772        $_SESSION['user_id'],
1773        $key);
1774      }
1775    // add new cache record
1776    else
1777      {
1778      $this->db->query(
1779        "INSERT INTO ".get_table_name('cache')."
1780         (created, user_id, cache_key, data)
1781         VALUES (".$this->db->now().", ?, ?, ?)",
1782        $_SESSION['user_id'],
1783        $key,
1784        $data);
1785      }
1786    }
1787
1788
1789  function _clear_cache_record($key)
1790    {
1791    $this->db->query(
1792      "DELETE FROM ".get_table_name('cache')."
1793       WHERE  user_id=?
1794       AND    cache_key=?",
1795      $_SESSION['user_id'],
1796      $key);
1797    }
1798
1799
1800
1801  /* --------------------------------
1802   *   message caching methods
1803   * --------------------------------*/
1804   
1805
1806  // checks if the cache is up-to-date
1807  // return: -3 = off, -2 = incomplete, -1 = dirty
1808  function check_cache_status($mailbox, $cache_key)
1809    {
1810    if (!$this->caching_enabled)
1811      return -3;
1812
1813    $cache_index = $this->get_message_cache_index($cache_key, TRUE);
1814    $msg_count = $this->_messagecount($mailbox);
1815    $cache_count = count($cache_index);
1816
1817    // console("Cache check: $msg_count !== ".count($cache_index));
1818
1819    if ($cache_count==$msg_count)
1820      {
1821      // get highest index
1822      $header = iil_C_FetchHeader($this->conn, $mailbox, "$msg_count");
1823      $cache_uid = array_pop($cache_index);
1824     
1825      // uids of highest message matches -> cache seems OK
1826      if ($cache_uid == $header->uid)
1827        return 1;
1828
1829      // cache is dirty
1830      return -1;
1831      }
1832    // if cache count differs less than 10% report as dirty
1833    else if (abs($msg_count - $cache_count) < $msg_count/10)
1834      return -1;
1835    else
1836      return -2;
1837    }
1838
1839
1840
1841  function get_message_cache($key, $from, $to, $sort_field, $sort_order)
1842    {
1843    $cache_key = "$key:$from:$to:$sort_field:$sort_order";
1844    $db_header_fields = array('idx', 'uid', 'subject', 'from', 'to', 'cc', 'date', 'size');
1845   
1846    if (!in_array($sort_field, $db_header_fields))
1847      $sort_field = 'idx';
1848   
1849    if ($this->caching_enabled && !isset($this->cache[$cache_key]))
1850      {
1851      $this->cache[$cache_key] = array();
1852      $sql_result = $this->db->limitquery(
1853        "SELECT idx, uid, headers
1854         FROM ".get_table_name('messages')."
1855         WHERE  user_id=?
1856         AND    cache_key=?
1857         ORDER BY ".$this->db->quoteIdentifier($sort_field)." ".
1858         strtoupper($sort_order),
1859        $from,
1860        $to-$from,
1861        $_SESSION['user_id'],
1862        $key);
1863
1864      while ($sql_arr = $this->db->fetch_assoc($sql_result))
1865        {
1866        $uid = $sql_arr['uid'];
1867        $this->cache[$cache_key][$uid] = unserialize($sql_arr['headers']);
1868        }
1869      }
1870     
1871    return $this->cache[$cache_key];
1872    }
1873
1874
1875  function &get_cached_message($key, $uid, $struct=false)
1876    {
1877    if (!$this->caching_enabled)
1878      return FALSE;
1879
1880    $internal_key = '__single_msg';
1881    if ($this->caching_enabled && (!isset($this->cache[$internal_key][$uid]) ||
1882        ($struct && empty($this->cache[$internal_key][$uid]->structure))))
1883      {
1884      $sql_select = "idx, uid, headers" . ($struct ? ", structure" : '');
1885      $sql_result = $this->db->query(
1886        "SELECT $sql_select
1887         FROM ".get_table_name('messages')."
1888         WHERE  user_id=?
1889         AND    cache_key=?
1890         AND    uid=?",
1891        $_SESSION['user_id'],
1892        $key,
1893        $uid);
1894
1895      if ($sql_arr = $this->db->fetch_assoc($sql_result))
1896        {
1897        $this->cache[$internal_key][$uid] = unserialize($sql_arr['headers']);
1898        if (is_object($this->cache[$internal_key][$uid]) && !empty($sql_arr['structure']))
1899          $this->cache[$internal_key][$uid]->structure = unserialize($sql_arr['structure']);
1900        }
1901      }
1902
1903    return $this->cache[$internal_key][$uid];
1904    }
1905
1906   
1907  function get_message_cache_index($key, $force=FALSE, $sort_col='idx', $sort_order='ASC')
1908    {
1909    static $sa_message_index = array();
1910   
1911    // empty key -> empty array
1912    if (empty($key))
1913      return array();
1914   
1915    if (!empty($sa_message_index[$key]) && !$force)
1916      return $sa_message_index[$key];
1917   
1918    $sa_message_index[$key] = array();
1919    $sql_result = $this->db->query(
1920      "SELECT idx, uid
1921       FROM ".get_table_name('messages')."
1922       WHERE  user_id=?
1923       AND    cache_key=?
1924       ORDER BY ".$this->db->quote_identifier($sort_col)." ".$sort_order,
1925      $_SESSION['user_id'],
1926      $key);
1927
1928    while ($sql_arr = $this->db->fetch_assoc($sql_result))
1929      $sa_message_index[$key][$sql_arr['idx']] = $sql_arr['uid'];
1930     
1931    return $sa_message_index[$key];
1932    }
1933
1934
1935  function add_message_cache($key, $index, $headers, $struct=null)
1936    {
1937    if (empty($key) || !is_object($headers) || empty($headers->uid))
1938      return;
1939     
1940    // check for an existing record (probly headers are cached but structure not)
1941    $sql_result = $this->db->query(
1942        "SELECT message_id
1943         FROM ".get_table_name('messages')."
1944         WHERE  user_id=?
1945         AND    cache_key=?
1946         AND    uid=?
1947         AND    del<>1",
1948        $_SESSION['user_id'],
1949        $key,
1950        $headers->uid);
1951
1952    // update cache record
1953    if ($sql_arr = $this->db->fetch_assoc($sql_result))
1954      {
1955      $this->db->query(
1956        "UPDATE ".get_table_name('messages')."
1957         SET   idx=?, headers=?, structure=?
1958         WHERE message_id=?",
1959        $index,
1960        serialize($headers),
1961        is_object($struct) ? serialize($struct) : NULL,
1962        $sql_arr['message_id']
1963        );
1964      }
1965    else  // insert new record
1966      {
1967      $this->db->query(
1968        "INSERT INTO ".get_table_name('messages')."
1969         (user_id, del, cache_key, created, idx, uid, subject, ".$this->db->quoteIdentifier('from').", ".$this->db->quoteIdentifier('to').", cc, date, size, headers, structure)
1970         VALUES (?, 0, ?, ".$this->db->now().", ?, ?, ?, ?, ?, ?, ".$this->db->fromunixtime($headers->timestamp).", ?, ?, ?)",
1971        $_SESSION['user_id'],
1972        $key,
1973        $index,
1974        $headers->uid,
1975        (string)substr($this->decode_header($headers->subject, TRUE), 0, 128),
1976        (string)substr($this->decode_header($headers->from, TRUE), 0, 128),
1977        (string)substr($this->decode_header($headers->to, TRUE), 0, 128),
1978        (string)substr($this->decode_header($headers->cc, TRUE), 0, 128),
1979        (int)$headers->size,
1980        serialize($headers),
1981        is_object($struct) ? serialize($struct) : NULL
1982        );
1983      }
1984    }
1985   
1986   
1987  function remove_message_cache($key, $index)
1988    {
1989    $this->db->query(
1990      "DELETE FROM ".get_table_name('messages')."
1991       WHERE  user_id=?
1992       AND    cache_key=?
1993       AND    idx=?",
1994      $_SESSION['user_id'],
1995      $key,
1996      $index);
1997    }
1998
1999
2000  function clear_message_cache($key, $start_index=1)
2001    {
2002    $this->db->query(
2003      "DELETE FROM ".get_table_name('messages')."
2004       WHERE  user_id=?
2005       AND    cache_key=?
2006       AND    idx>=?",
2007      $_SESSION['user_id'],
2008      $key,
2009      $start_index);
2010    }
2011
2012
2013
2014
2015  /* --------------------------------
2016   *   encoding/decoding methods
2017   * --------------------------------*/
2018
2019 
2020  function decode_address_list($input, $max=NULL)
2021    {
2022    $a = $this->_parse_address_list($input);
2023    $out = array();
2024   
2025    if (!is_array($a))
2026      return $out;
2027
2028    $c = count($a);
2029    $j = 0;
2030
2031    foreach ($a as $val)
2032      {
2033      $j++;
2034      $address = $val['address'];
2035      $name = preg_replace(array('/^[\'"]/', '/[\'"]$/'), '', trim($val['name']));
2036      $string = $name!==$address ? sprintf('%s <%s>', strpos($name, ',')!==FALSE ? '"'.$name.'"' : $name, $address) : $address;
2037     
2038      $out[$j] = array('name' => $name,
2039                       'mailto' => $address,
2040                       'string' => $string);
2041             
2042      if ($max && $j==$max)
2043        break;
2044      }
2045   
2046    return $out;
2047    }
2048
2049
2050  function decode_header($input, $remove_quotes=FALSE)
2051    {
2052    $str = $this->decode_mime_string((string)$input);
2053    if ($str{0}=='"' && $remove_quotes)
2054      {
2055      $str = str_replace('"', '', $str);
2056      }
2057   
2058    return $str;
2059    }
2060
2061
2062  /**
2063   * Decode a mime-encoded string to internal charset
2064   *
2065   * @access static
2066   */
2067  function decode_mime_string($input, $recursive=false)
2068    {
2069    $out = '';
2070
2071    $pos = strpos($input, '=?');
2072    if ($pos !== false)
2073      {
2074      $out = substr($input, 0, $pos);
2075 
2076      $end_cs_pos = strpos($input, "?", $pos+2);
2077      $end_en_pos = strpos($input, "?", $end_cs_pos+1);
2078      $end_pos = strpos($input, "?=", $end_en_pos+1);
2079 
2080      $encstr = substr($input, $pos+2, ($end_pos-$pos-2));
2081      $rest = substr($input, $end_pos+2);
2082
2083      $out .= rcube_imap::_decode_mime_string_part($encstr);
2084      $out .= rcube_imap::decode_mime_string($rest);
2085
2086      return $out;
2087      }
2088     
2089    // no encoding information, defaults to what is specified in the class header
2090    return rcube_charset_convert($input, 'ISO-8859-1');
2091    }
2092
2093
2094  /**
2095   * Decode a part of a mime-encoded string
2096   *
2097   * @access static
2098   */
2099  function _decode_mime_string_part($str)
2100    {
2101    $a = explode('?', $str);
2102    $count = count($a);
2103
2104    // should be in format "charset?encoding?base64_string"
2105    if ($count >= 3)
2106      {
2107      for ($i=2; $i<$count; $i++)
2108        $rest.=$a[$i];
2109
2110      if (($a[1]=="B")||($a[1]=="b"))
2111        $rest = base64_decode($rest);
2112      else if (($a[1]=="Q")||($a[1]=="q"))
2113        {
2114        $rest = str_replace("_", " ", $rest);
2115        $rest = quoted_printable_decode($rest);
2116        }
2117
2118      return rcube_charset_convert($rest, $a[0]);
2119      }
2120    else
2121      return $str;    // we dont' know what to do with this 
2122    }
2123
2124
2125  function mime_decode($input, $encoding='7bit')
2126    {
2127    switch (strtolower($encoding))
2128      {
2129      case '7bit':
2130        return $input;
2131        break;
2132     
2133      case 'quoted-printable':
2134        return quoted_printable_decode($input);
2135        break;
2136     
2137      case 'base64':
2138        return base64_decode($input);
2139        break;
2140     
2141      default:
2142        return $input;
2143      }
2144    }
2145
2146
2147  function mime_encode($input, $encoding='7bit')
2148    {
2149    switch ($encoding)
2150      {
2151      case 'quoted-printable':
2152        return quoted_printable_encode($input);
2153        break;
2154
2155      case 'base64':
2156        return base64_encode($input);
2157        break;
2158
2159      default:
2160        return $input;
2161      }
2162    }
2163
2164
2165  // convert body chars according to the ctype_parameters
2166  function charset_decode($body, $ctype_param)
2167    {
2168    if (is_array($ctype_param) && !empty($ctype_param['charset']))
2169      return rcube_charset_convert($body, $ctype_param['charset']);
2170
2171    // defaults to what is specified in the class header
2172    return rcube_charset_convert($body,  'ISO-8859-1');
2173    }
2174
2175
2176
2177
2178  /* --------------------------------
2179   *         private methods
2180   * --------------------------------*/
2181
2182
2183  function _mod_mailbox($mbox_name, $mode='in')
2184    {
2185    if ((!empty($this->root_ns) && $this->root_ns == $mbox_name) || $mbox_name == 'INBOX')
2186      return $mbox_name;
2187
2188    if (!empty($this->root_dir) && $mode=='in')
2189      $mbox_name = $this->root_dir.$this->delimiter.$mbox_name;
2190    else if (strlen($this->root_dir) && $mode=='out')
2191      $mbox_name = substr($mbox_name, strlen($this->root_dir)+1);
2192
2193    return $mbox_name;
2194    }
2195
2196
2197  // sort mailboxes first by default folders and then in alphabethical order
2198  function _sort_mailbox_list($a_folders)
2199    {
2200    $a_out = $a_defaults = array();
2201
2202    // find default folders and skip folders starting with '.'
2203    foreach($a_folders as $i => $folder)
2204      {
2205      if ($folder{0}=='.')
2206        continue;
2207
2208      if (($p = array_search(strtolower($folder), $this->default_folders_lc))!==FALSE)
2209        $a_defaults[$p] = $folder;
2210      else
2211        $a_out[] = $folder;
2212      }
2213
2214    sort($a_out);
2215    ksort($a_defaults);
2216   
2217    return array_merge($a_defaults, $a_out);
2218    }
2219
2220  function get_id($uid, $mbox_name=NULL)
2221    {
2222      return $this->_uid2id($uid, $mbox_name);
2223    }
2224 
2225  function get_uid($id,$mbox_name=NULL)
2226    {
2227      return $this->_id2uid($id, $mbox_name);
2228    }
2229
2230  function _uid2id($uid, $mbox_name=NULL)
2231    {
2232    if (!$mbox_name)
2233      $mbox_name = $this->mailbox;
2234     
2235    if (!isset($this->uid_id_map[$mbox_name][$uid]))
2236      $this->uid_id_map[$mbox_name][$uid] = iil_C_UID2ID($this->conn, $mbox_name, $uid);
2237
2238    return $this->uid_id_map[$mbox_name][$uid];
2239    }
2240
2241  function _id2uid($id, $mbox_name=NULL)
2242    {
2243    if (!$mbox_name)
2244      $mbox_name = $this->mailbox;
2245     
2246    return iil_C_ID2UID($this->conn, $mbox_name, $id);
2247    }
2248
2249
2250  // parse string or array of server capabilities and put them in internal array
2251  function _parse_capability($caps)
2252    {
2253    if (!is_array($caps))
2254      $cap_arr = explode(' ', $caps);
2255    else
2256      $cap_arr = $caps;
2257   
2258    foreach ($cap_arr as $cap)
2259      {
2260      if ($cap=='CAPABILITY')
2261        continue;
2262
2263      if (strpos($cap, '=')>0)
2264        {
2265        list($key, $value) = explode('=', $cap);
2266        if (!is_array($this->capabilities[$key]))
2267          $this->capabilities[$key] = array();
2268         
2269        $this->capabilities[$key][] = $value;
2270        }
2271      else
2272        $this->capabilities[$cap] = TRUE;
2273      }
2274    }
2275
2276
2277  // subscribe/unsubscribe a list of mailboxes and update local cache
2278  function _change_subscription($a_mboxes, $mode)
2279    {
2280    $updated = FALSE;
2281   
2282    if (is_array($a_mboxes))
2283      foreach ($a_mboxes as $i => $mbox_name)
2284        {
2285        $mailbox = $this->_mod_mailbox($mbox_name);
2286        $a_mboxes[$i] = $mailbox;
2287
2288        if ($mode=='subscribe')
2289          $result = iil_C_Subscribe($this->conn, $mailbox);
2290        else if ($mode=='unsubscribe')
2291          $result = iil_C_UnSubscribe($this->conn, $mailbox);
2292
2293        if ($result>=0)
2294          $updated = TRUE;
2295        }
2296       
2297    // get cached mailbox list   
2298    if ($updated)
2299      {
2300      $a_mailbox_cache = $this->get_cache('mailboxes');
2301      if (!is_array($a_mailbox_cache))
2302        return $updated;
2303
2304      // modify cached list
2305      if ($mode=='subscribe')
2306        $a_mailbox_cache = array_merge($a_mailbox_cache, $a_mboxes);
2307      else if ($mode=='unsubscribe')
2308        $a_mailbox_cache = array_diff($a_mailbox_cache, $a_mboxes);
2309       
2310      // write mailboxlist to cache
2311      $this->update_cache('mailboxes', $this->_sort_mailbox_list($a_mailbox_cache));
2312      }
2313
2314    return $updated;
2315    }
2316
2317
2318  // increde/decrese messagecount for a specific mailbox
2319  function _set_messagecount($mbox_name, $mode, $increment)
2320    {
2321    $a_mailbox_cache = FALSE;
2322    $mailbox = $mbox_name ? $mbox_name : $this->mailbox;
2323    $mode = strtoupper($mode);
2324
2325    $a_mailbox_cache = $this->get_cache('messagecount');
2326   
2327    if (!is_array($a_mailbox_cache[$mailbox]) || !isset($a_mailbox_cache[$mailbox][$mode]) || !is_numeric($increment))
2328      return FALSE;
2329   
2330    // add incremental value to messagecount
2331    $a_mailbox_cache[$mailbox][$mode] += $increment;
2332   
2333    // there's something wrong, delete from cache
2334    if ($a_mailbox_cache[$mailbox][$mode] < 0)
2335      unset($a_mailbox_cache[$mailbox][$mode]);
2336
2337    // write back to cache
2338    $this->update_cache('messagecount', $a_mailbox_cache);
2339   
2340    return TRUE;
2341    }
2342
2343
2344  // remove messagecount of a specific mailbox from cache
2345  function _clear_messagecount($mbox_name='')
2346    {
2347    $a_mailbox_cache = FALSE;
2348    $mailbox = $mbox_name ? $mbox_name : $this->mailbox;
2349
2350    $a_mailbox_cache = $this->get_cache('messagecount');
2351
2352    if (is_array($a_mailbox_cache[$mailbox]))
2353      {
2354      unset($a_mailbox_cache[$mailbox]);
2355      $this->update_cache('messagecount', $a_mailbox_cache);
2356      }
2357    }
2358
2359
2360  // split RFC822 header string into an associative array
2361  function _parse_headers($headers)
2362    {
2363    $a_headers = array();
2364    $lines = explode("\n", $headers);
2365    $c = count($lines);
2366    for ($i=0; $i<$c; $i++)
2367      {
2368      if ($p = strpos($lines[$i], ': '))
2369        {
2370        $field = strtolower(substr($lines[$i], 0, $p));
2371        $value = trim(substr($lines[$i], $p+1));
2372        if (!empty($value))
2373          $a_headers[$field] = $value;
2374        }
2375      }
2376   
2377    return $a_headers;
2378    }
2379
2380
2381  function _parse_address_list($str)
2382    {
2383    $a = $this->_explode_quoted_string(',', $str);
2384    $result = array();
2385   
2386    foreach ($a as $key => $val)
2387      {
2388      $val = str_replace("\"<", "\" <", $val);
2389      $sub_a = $this->_explode_quoted_string(' ', $this->decode_header($val));
2390      $result[$key]['name'] = '';
2391
2392      foreach ($sub_a as $k => $v)
2393        {
2394        if ((strpos($v, '@') > 0) && (strpos($v, '.') > 0))
2395          $result[$key]['address'] = str_replace('<', '', str_replace('>', '', $v));
2396        else
2397          $result[$key]['name'] .= (empty($result[$key]['name'])?'':' ').str_replace("\"",'',stripslashes($v));
2398        }
2399       
2400      if (empty($result[$key]['name']))
2401        $result[$key]['name'] = $result[$key]['address'];       
2402      }
2403   
2404    return $result;
2405    }
2406
2407
2408  function _explode_quoted_string($delimiter, $string)
2409    {
2410    $quotes = explode("\"", $string);
2411    foreach ($quotes as $key => $val)
2412      if (($key % 2) == 1)
2413        $quotes[$key] = str_replace($delimiter, "_!@!_", $quotes[$key]);
2414       
2415    $string = implode("\"", $quotes);
2416
2417    $result = explode($delimiter, $string);
2418    foreach ($result as $key => $val)
2419      $result[$key] = str_replace("_!@!_", $delimiter, $result[$key]);
2420   
2421    return $result;
2422    }
2423  }
2424
2425
2426/**
2427 * Class representing a message part
2428 */
2429class rcube_message_part
2430{
2431  var $mime_id = '';
2432  var $ctype_primary = 'text';
2433  var $ctype_secondary = 'plain';
2434  var $mimetype = 'text/plain';
2435  var $disposition = '';
2436  var $encoding = '8bit';
2437  var $charset = '';
2438  var $size = 0;
2439  var $headers = array();
2440  var $d_parameters = array();
2441  var $ctype_parameters = array();
2442
2443}
2444
2445
2446/**
2447 * rcube_header_sorter
2448 *
2449 * Class for sorting an array of iilBasicHeader objects in a predetermined order.
2450 *
2451 * @author Eric Stadtherr
2452 */
2453class rcube_header_sorter
2454{
2455   var $sequence_numbers = array();
2456   
2457   /**
2458    * set the predetermined sort order.
2459    *
2460    * @param array $seqnums numerically indexed array of IMAP message sequence numbers
2461    */
2462   function set_sequence_numbers($seqnums)
2463   {
2464      $this->sequence_numbers = $seqnums;
2465   }
2466 
2467   /**
2468    * sort the array of header objects
2469    *
2470    * @param array $headers array of iilBasicHeader objects indexed by UID
2471    */
2472   function sort_headers(&$headers)
2473   {
2474      /*
2475       * uksort would work if the keys were the sequence number, but unfortunately
2476       * the keys are the UIDs.  We'll use uasort instead and dereference the value
2477       * to get the sequence number (in the "id" field).
2478       *
2479       * uksort($headers, array($this, "compare_seqnums"));
2480       */
2481       uasort($headers, array($this, "compare_seqnums"));
2482   }
2483 
2484   /**
2485    * get the position of a message sequence number in my sequence_numbers array
2486    *
2487    * @param integer $seqnum message sequence number contained in sequence_numbers 
2488    */
2489   function position_of($seqnum)
2490   {
2491      $c = count($this->sequence_numbers);
2492      for ($pos = 0; $pos <= $c; $pos++)
2493      {
2494         if ($this->sequence_numbers[$pos] == $seqnum)
2495            return $pos;
2496      }
2497      return -1;
2498   }
2499 
2500   /**
2501    * Sort method called by uasort()
2502    */
2503   function compare_seqnums($a, $b)
2504   {
2505      // First get the sequence number from the header object (the 'id' field).
2506      $seqa = $a->id;
2507      $seqb = $b->id;
2508     
2509      // then find each sequence number in my ordered list
2510      $posa = $this->position_of($seqa);
2511      $posb = $this->position_of($seqb);
2512     
2513      // return the relative position as the comparison value
2514      $ret = $posa - $posb;
2515      return $ret;
2516   }
2517}
2518
2519
2520/**
2521 * Add quoted-printable encoding to a given string
2522 *
2523 * @param string  $input      string to encode
2524 * @param int     $line_max   add new line after this number of characters
2525 * @param boolena $space_conf true if spaces should be converted into =20
2526 * @return encoded string
2527 */
2528function quoted_printable_encode($input, $line_max=76, $space_conv=false)
2529  {
2530  $hex = array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');
2531  $lines = preg_split("/(?:\r\n|\r|\n)/", $input);
2532  $eol = "\r\n";
2533  $escape = "=";
2534  $output = "";
2535
2536  while( list(, $line) = each($lines))
2537    {
2538    //$line = rtrim($line); // remove trailing white space -> no =20\r\n necessary
2539    $linlen = strlen($line);
2540    $newline = "";
2541    for($i = 0; $i < $linlen; $i++)
2542      {
2543      $c = substr( $line, $i, 1 );
2544      $dec = ord( $c );
2545      if ( ( $i == 0 ) && ( $dec == 46 ) ) // convert first point in the line into =2E
2546        {
2547        $c = "=2E";
2548        }
2549      if ( $dec == 32 )
2550        {
2551        if ( $i == ( $linlen - 1 ) ) // convert space at eol only
2552          {
2553          $c = "=20";
2554          }
2555        else if ( $space_conv )
2556          {
2557          $c = "=20";
2558          }
2559        }
2560      else if ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) )  // always encode "\t", which is *not* required
2561        {
2562        $h2 = floor($dec/16);
2563        $h1 = floor($dec%16);
2564        $c = $escape.$hex["$h2"].$hex["$h1"];
2565        }
2566         
2567      if ( (strlen($newline) + strlen($c)) >= $line_max )  // CRLF is not counted
2568        {
2569        $output .= $newline.$escape.$eol; // soft line break; " =\r\n" is okay
2570        $newline = "";
2571        // check if newline first character will be point or not
2572        if ( $dec == 46 )
2573          {
2574          $c = "=2E";
2575          }
2576        }
2577      $newline .= $c;
2578      } // end of for
2579    $output .= $newline.$eol;
2580    } // end of while
2581
2582  return trim($output);
2583  }
2584
2585
2586?>
Note: See TracBrowser for help on using the repository browser.