alecpl
2008-10-29 8498dce502f9265278f7eb2b01ae4e65187a1a84
program/include/rcube_imap.php
@@ -59,7 +59,6 @@
  var $cache_changes = array();
  var $uid_id_map = array();
  var $msg_headers = array();
  var $capabilities = array();
  var $skip_deleted = FALSE;
  var $search_set = NULL;
  var $search_subject = '';
@@ -81,17 +80,6 @@
  /**
   * PHP 4 object constructor
   *
   * @see  rcube_imap::__construct
   */
  function rcube_imap($db_conn)
    {
    $this->__construct($db_conn);
    }
  /**
   * Connect to an IMAP server
   *
   * @param  string   Host to connect
@@ -102,7 +90,7 @@
   * @return boolean  TRUE on success, FALSE on failure
   * @access public
   */
  function connect($host, $user, $pass, $port=143, $use_ssl=null)
  function connect($host, $user, $pass, $port=143, $use_ssl=null, $auth_type=null)
    {
    global $ICL_SSL, $ICL_PORT, $IMAP_USE_INTERNAL_DATE;
    
@@ -119,9 +107,7 @@
    $ICL_PORT = $port;
    $IMAP_USE_INTERNAL_DATE = false;
    $auth_type = rcmail::get_instance()->config->get('imap_auth_type', 'check');
    $this->conn = iil_Connect($host, $user, $pass, array('imap' => $auth_type));
    $this->conn = iil_Connect($host, $user, $pass, array('imap' => $auth_type ? $auth_type : 'check'));
    $this->host = $host;
    $this->user = $user;
    $this->pass = $pass;
@@ -144,8 +130,6 @@
    // get server properties
    if ($this->conn)
      {
      $this->_parse_capability($this->conn->capability);
      if (!empty($this->conn->delimiter))
        $this->delimiter = $this->conn->delimiter;
      if (!empty($this->conn->rootdir))
@@ -182,6 +166,10 @@
    {
    $this->close();
    $this->connect($this->host, $this->user, $this->pass, $this->port, $this->ssl);
    // issue SELECT command to restore connection status
    if ($this->mailbox)
      iil_C_Select($this->conn, $this->mailbox);
    }
@@ -342,8 +330,22 @@
   */
  function get_capability($cap)
    {
    $cap = strtoupper($cap);
    return $this->capabilities[$cap];
    return iil_C_GetCapability($this->conn, strtoupper($cap));
    }
  /**
   * Checks the PERMANENTFLAGS capability of the current mailbox
   * and returns true if the given flag is supported by the IMAP server
   *
   * @param   string  Permanentflag name
   * @return  mixed   True if this flag is supported
   * @access  public
   */
  function check_permflag($flag)
    {
    $flagsmap = $GLOBALS['IMAP_FLAGS'];
    return (($imap_flag = $flagsmap[strtoupper($flag)]) && in_array_nocase($imap_flag, $this->conn->permanentflags));
    }
@@ -1015,7 +1017,7 @@
   * an object structure similar to the one generated by PEAR::Mail_mimeDecode
   *
   * @param int Message UID to fetch
   * @return object stdClass Message part tree or False on failure
   * @return object rcube_message_part Message part tree or False on failure
   */
  function &get_structure($uid)
    {
@@ -1023,14 +1025,16 @@
    $headers = &$this->get_cached_message($cache_key, $uid, true);
    // return cached message structure
    if (is_object($headers) && is_object($headers->structure))
    if (is_object($headers) && is_object($headers->structure)) {
      return $headers->structure;
    // resolve message sequence number
    if (!($msg_id = $this->_uid2id($uid)))
      return FALSE;
    }
    $structure_str = iil_C_FetchStructureString($this->conn, $this->mailbox, $msg_id);
    // resolve message sequence number
    if (!($msg_id = $this->_uid2id($uid))) {
      return FALSE;
    }
    $structure_str = iil_C_FetchStructureString($this->conn, $this->mailbox, $msg_id);
    $structure = iml_GetRawStructureArray($structure_str);
    $struct = false;
@@ -1055,7 +1059,7 @@
      if ($this->caching_enabled)
        $this->add_message_cache($cache_key, $msg_id, $headers, $struct);
      }
    return $struct;
    }
@@ -1076,7 +1080,7 @@
      $struct->ctype_primary = 'multipart';
      
      // find first non-array entry
      for ($i=1; count($part); $i++)
      for ($i=1; $i<count($part); $i++)
        if (!is_array($part[$i]))
          {
          $struct->ctype_secondary = strtolower($part[$i]);
@@ -1087,7 +1091,7 @@
      $struct->parts = array();
      for ($i=0, $count=0; $i<count($part); $i++)
        if (is_array($part[$i]) && count($part[$i]) > 5)
        if (is_array($part[$i]) && count($part[$i]) > 3)
          $struct->parts[] = $this->_structure_part($part[$i], ++$count, $struct->mime_id);
          
      return $struct;
@@ -1151,32 +1155,133 @@
      if (empty($struct->disposition))
        $struct->disposition = 'inline';
      }
    // fetch message headers if message/rfc822 or named part (could contain Content-Location header)
    if ($struct->ctype_primary == 'message' || ($struct->ctype_parameters['name'] && !$struct->content_id)) {
      $part_headers = iil_C_FetchPartHeader($this->conn, $this->mailbox, $this->_msg_id, $struct->mime_id);
      $struct->headers = $this->_parse_headers($part_headers) + $struct->headers;
    }
    // fetch message headers if message/rfc822
    if ($struct->ctype_primary=='message')
      {
      $headers = iil_C_FetchPartBody($this->conn, $this->mailbox, $this->_msg_id, $struct->mime_id.'.HEADER');
      $struct->headers = $this->_parse_headers($headers);
    if ($struct->ctype_primary=='message') {
      if (is_array($part[8]) && empty($struct->parts))
        $struct->parts[] = $this->_structure_part($part[8], ++$count, $struct->mime_id);
      }
    // normalize filename property
    if ($filename_mime = $struct->d_parameters['filename'] ? $struct->d_parameters['filename'] : $struct->ctype_parameters['name'])
      $struct->filename = rcube_imap::decode_mime_string($filename_mime, $this->default_charset);
    else if ($filename_encoded = $struct->d_parameters['filename*'] ? $struct->d_parameters['filename*'] : $struct->ctype_parameters['name*'])
    {
      // decode filename according to RFC 2231, Section 4
      list($filename_charset,, $filename_urlencoded) = split('\'', $filename_encoded);
      $struct->filename = rcube_charset_convert(urldecode($filename_urlencoded), $filename_charset);
    }
    else if (!empty($struct->headers['content-description']))
      $struct->filename = rcube_imap::decode_mime_string($struct->headers['content-description'], $this->default_charset);
    // normalize filename property
    $this->_set_part_filename($struct);
    return $struct;
    }
    
  /**
   * Set attachment filename from message part structure
   *
   * @access private
   * @param  object rcube_message_part Part object
   */
  function _set_part_filename(&$part)
    {
    if (!empty($part->d_parameters['filename']))
      $filename_mime = $part->d_parameters['filename'];
    else if (!empty($part->d_parameters['filename*']))
      $filename_encoded = $part->d_parameters['filename*'];
    else if (!empty($part->ctype_parameters['name*']))
      $filename_encoded = $part->ctype_parameters['name*'];
    // RFC2231 value continuations
    // TODO: this should be rewrited to support RFC2231 4.1 combinations
    else if (!empty($part->d_parameters['filename*0'])) {
      $i = 0;
      while (isset($part->d_parameters['filename*'.$i])) {
        $filename_mime .= $part->d_parameters['filename*'.$i];
        $i++;
      }
      // some servers (eg. dovecot-1.x) have no support for parameter value continuations
      // we must fetch and parse headers "manually"
      //TODO: fetching headers for a second time is not effecient, this code should be moved somewhere earlier --tensor
      if ($i<2) {
        // TODO: fetch only Content-Type/Content-Disposition header
        $headers = iil_C_FetchPartHeader($this->conn, $this->mailbox, $this->_msg_id, $part->mime_id);
        $filename_mime = '';
        $i = 0;
        while (preg_match('/filename\*'.$i.'\s*=\s*"*([^"\n;]+)[";]*/', $headers, $matches)) {
          $filename_mime .= $matches[1];
          $i++;
        }
      }
    }
    else if (!empty($part->d_parameters['filename*0*'])) {
      $i = 0;
      while (isset($part->d_parameters['filename*'.$i.'*'])) {
        $filename_encoded .= $part->d_parameters['filename*'.$i.'*'];
        $i++;
      }
      if ($i<2) {
        $headers = iil_C_FetchPartHeader($this->conn, $this->mailbox, $this->_msg_id, $part->mime_id);
        $filename_encoded = '';
        $i = 0; $matches = array();
        while (preg_match('/filename\*'.$i.'\*\s*=\s*"*([^"\n;]+)[";]*/', $headers, $matches)) {
          $filename_encoded .= $matches[1];
          $i++;
        }
      }
    }
    else if (!empty($part->ctype_parameters['name*0'])) {
      $i = 0;
      while (isset($part->ctype_parameters['name*'.$i])) {
        $filename_mime .= $part->ctype_parameters['name*'.$i];
        $i++;
      }
      if ($i<2) {
        $headers = iil_C_FetchPartHeader($this->conn, $this->mailbox, $this->_msg_id, $part->mime_id);
        $filename_mime = '';
        $i = 0; $matches = array();
        while (preg_match('/\s+name\*'.$i.'\s*=\s*"*([^"\n;]+)[";]*/', $headers, $matches)) {
          $filename_mime .= $matches[1];
          $i++;
        }
      }
    }
    else if (!empty($part->ctype_parameters['name*0*'])) {
      $i = 0;
      while (isset($part->ctype_parameters['name*'.$i.'*'])) {
        $filename_encoded .= $part->ctype_parameters['name*'.$i.'*'];
        $i++;
      }
      if ($i<2) {
        $headers = iil_C_FetchPartHeader($this->conn, $this->mailbox, $this->_msg_id, $part->mime_id);
        $filename_encoded = '';
        $i = 0; $matches = array();
        while (preg_match('/\s+name\*'.$i.'\*\s*=\s*"*([^"\n;]+)[";]*/', $headers, $matches)) {
          $filename_encoded .= $matches[1];
          $i++;
        }
      }
    }
    // read 'name' after rfc2231 parameters as it may contains truncated filename (from Thunderbird)
    else if (!empty($part->ctype_parameters['name']))
      $filename_mime = $part->ctype_parameters['name'];
    // Content-Disposition
    else if (!empty($part->headers['content-description']))
      $filename_mime = $part->headers['content-description'];
    else
      return;
    // decode filename
    if (!empty($filename_mime)) {
      $part->filename = rcube_imap::decode_mime_string($filename_mime,
        $part->charset ? $part->charset : rc_detect_encoding($filename_mime, $this->default_charset));
      }
    else if (!empty($filename_encoded)) {
      // decode filename according to RFC 2231, Section 4
      if (preg_match("/^([^']*)'[^']*'(.*)$/", $filename_encoded, $fmatches)) {
        $filename_charset = $fmatches[1];
        $filename_encoded = $fmatches[2];
        }
      $part->filename = rcube_charset_convert(urldecode($filename_encoded), $filename_charset);
      }
    }
  
  /**
   * Fetch message body of a specific message from the server
@@ -1185,9 +1290,10 @@
   * @param  string Part number
   * @param  object rcube_message_part Part object created by get_structure()
   * @param  mixed  True to print part, ressource to write part contents in
   * @param  resource File pointer to save the message part
   * @return string Message/part body if not printed
   */
  function &get_message_part($uid, $part=1, $o_part=NULL, $print=NULL)
  function &get_message_part($uid, $part=1, $o_part=NULL, $print=NULL, $fp=NULL)
    {
    if (!($msg_id = $this->_uid2id($uid)))
      return FALSE;
@@ -1220,7 +1326,10 @@
      }
    else
      {
      $body = iil_C_HandlePartBody($this->conn, $this->mailbox, $msg_id, $part, 1);
      if ($fp && $o_part->encoding == 'base64')
        return iil_C_HandlePartBody($this->conn, $this->mailbox, $msg_id, $part, 3, $fp);
      else
        $body = iil_C_HandlePartBody($this->conn, $this->mailbox, $msg_id, $part, 1);
      // decode part body
      if ($o_part->encoding)
@@ -1235,8 +1344,14 @@
        $body = rcube_charset_convert($body, $o_part->charset);
        }
      if ($fp)
        {
        fwrite($fp, $body);
        return true;
        }
      }
    return $body;
    }
@@ -1250,7 +1365,10 @@
   */
  function &get_body($uid, $part=1)
    {
    return $this->get_message_part($uid, $part);
    $headers = $this->get_headers($uid);
    return rcube_charset_convert(
      $this->mime_decode($this->get_message_part($uid, $part), 'quoted-printable'),
      $headers->charset ? $headers->charset : $this->default_charset);
    }
@@ -1269,6 +1387,23 @@
    $body .= iil_C_HandlePartBody($this->conn, $this->mailbox, $msg_id, NULL, 1);
    return $body;    
    }
  /**
   * Returns the message headers as string
   *
   * @param int  Message UID
   * @return string Message headers string
   */
  function &get_raw_headers($uid)
    {
    if (!($msg_id = $this->_uid2id($uid)))
      return FALSE;
    $headers = iil_C_FetchPartHeader($this->conn, $this->mailbox, $msg_id, NULL);
    return $headers;
    }
    
@@ -1310,6 +1445,8 @@
      $result = iil_C_Undelete($this->conn, $this->mailbox, join(',', array_values($msg_ids)));
    else if ($flag=='UNSEEN')
      $result = iil_C_Unseen($this->conn, $this->mailbox, join(',', array_values($msg_ids)));
    else if ($flag=='UNFLAGGED')
      $result = iil_C_UnFlag($this->conn, $this->mailbox, join(',', array_values($msg_ids)), 'FLAGGED');
    else
      $result = iil_C_Flag($this->conn, $this->mailbox, join(',', array_values($msg_ids)), $flag);
@@ -1359,7 +1496,7 @@
    $mailbox = $this->_mod_mailbox($mbox_name);
    // make sure mailbox exists
    if (in_array($mailbox, $this->_list_mailboxes()))
    if (($mailbox == 'INBOX') || in_array($mailbox, $this->_list_mailboxes()))
      $saved = iil_C_Append($this->conn, $mailbox, $message);
    if ($saved)
@@ -1414,9 +1551,13 @@
    // send expunge command in order to have the moved message
    // really deleted from the source mailbox
    if ($moved) {
      $this->_expunge($from_mbox, FALSE);
      $this->_clear_messagecount($from_mbox);
      $this->_clear_messagecount($to_mbox);
      // but only when flag_for_deletion is set to false
      if (!rcmail::get_instance()->config->get('flag_for_deletion', false))
        {
        $this->_expunge($from_mbox, FALSE);
        $this->_clear_messagecount($from_mbox);
        $this->_clear_messagecount($to_mbox);
        }
    }
    // moving failed
    else if (rcmail::get_instance()->config->get('delete_always', false)) {
@@ -1465,7 +1606,6 @@
    if (!is_array($a_uids))
      return false;
    // convert uids to message ids
    $a_mids = array();
    foreach ($a_uids as $uid)
@@ -1479,10 +1619,11 @@
      {
      $this->_expunge($mailbox, FALSE);
      $this->_clear_messagecount($mailbox);
      unset($this->uid_id_map[$mailbox]);
      }
    // remove message ids from search set
    if ($moved && $this->search_set && $mailbox == $this->mailbox)
    if ($deleted && $this->search_set && $mailbox == $this->mailbox)
      $this->search_set = array_diff($this->search_set, $a_mids);
    // remove deleted messages from cache
@@ -2313,31 +2454,44 @@
   */
  function decode_mime_string($input, $fallback=null)
    {
    // Initialize variable
    $out = '';
    $pos = strpos($input, '=?');
    if ($pos !== false)
      {
      // rfc: all line breaks or other characters not found
      // in the Base64 Alphabet must be ignored by decoding software
      // delete all blanks between MIME-lines, differently we can
      // receive unnecessary blanks and broken utf-8 symbols
      $input = preg_replace("/\?=\s+=\?/", '?==?', $input);
    // Iterate instead of recursing, this way if there are too many values we don't have stack overflows
    // rfc: all line breaks or other characters not found
    // in the Base64 Alphabet must be ignored by decoding software
    // delete all blanks between MIME-lines, differently we can
    // receive unnecessary blanks and broken utf-8 symbols
    $input = preg_replace("/\?=\s+=\?/", '?==?', $input);
      $out = substr($input, 0, $pos);
      $end_cs_pos = strpos($input, "?", $pos+2);
      $end_en_pos = strpos($input, "?", $end_cs_pos+1);
      $end_pos = strpos($input, "?=", $end_en_pos+1);
      $encstr = substr($input, $pos+2, ($end_pos-$pos-2));
      $rest = substr($input, $end_pos+2);
    // Check if there is stuff to decode
    if (strpos($input, '=?') !== false) {
      // Loop through the string to decode all occurences of =? ?= into the variable $out
      while(($pos = strpos($input, '=?')) !== false) {
        // Append everything that is before the text to be decoded
        $out .= substr($input, 0, $pos);
      $out .= rcube_imap::_decode_mime_string_part($encstr);
      $out .= rcube_imap::decode_mime_string($rest, $fallback);
        // Get the location of the text to decode
        $end_cs_pos = strpos($input, "?", $pos+2);
        $end_en_pos = strpos($input, "?", $end_cs_pos+1);
        $end_pos = strpos($input, "?=", $end_en_pos+1);
      return $out;
        // Extract the encoded string
        $encstr = substr($input, $pos+2, ($end_pos-$pos-2));
        // Extract the remaining string
        $input = substr($input, $end_pos+2);
        // Decode the string fragement
        $out .= rcube_imap::_decode_mime_string_part($encstr);
      }
      // Deocde the rest (if any)
      if (strlen($input) != 0)
         $out .= rcube_imap::decode_mime_string($input, $fallback);
       // return the results
      return $out;
    }
    // no encoding information, use fallback
    return rcube_charset_convert($input, 
@@ -2491,10 +2645,12 @@
   */
  function _sort_mailbox_list($a_folders)
    {
    $a_out = $a_defaults = array();
    $a_out = $a_defaults = $folders = array();
    $delimiter = $this->get_hierarchy_delimiter();
    // find default folders and skip folders starting with '.'
    foreach($a_folders as $i => $folder)
    foreach ($a_folders as $i => $folder)
      {
      if ($folder{0}=='.')
        continue;
@@ -2502,15 +2658,33 @@
      if (($p = array_search(strtolower($folder), $this->default_folders_lc)) !== false && !$a_defaults[$p])
        $a_defaults[$p] = $folder;
      else
   {
   $l_folders[$folder] = mb_strtolower(rcube_charset_convert($folder, 'UTF-7'));
   }
        $folders[$folder] = rc_strtolower(rcube_charset_convert($folder, 'UTF-7'));
      }
    asort($l_folders, SORT_LOCALE_STRING);
    asort($folders, SORT_LOCALE_STRING);
    ksort($a_defaults);
    return array_merge($a_defaults, array_keys($l_folders));
    $folders = array_merge($a_defaults, array_keys($folders));
    // finally we must rebuild the list to move
    // subfolders of default folders to their place...
    // ...also do this for the rest of folders because
    // asort() is not properly sorting case sensitive names
    // set the type of folder name variable (#1485527)
    while (list($key, $folder) = each($folders)) {
      $a_out[] = (string) $folder;
      unset($folders[$key]);
      foreach ($folders as $idx => $f) {
   if (strpos($f, $folder.$delimiter) === 0) {
         $a_out[] = (string) $f;
     unset($folders[$idx]);
     }
        }
      reset($folders);
      }
    return $a_out;
    }
  /**
@@ -2545,36 +2719,6 @@
      }
    
    return $uid;
    }
  /**
   * Parse string or array of server capabilities and put them in internal array
   * @access private
   */
  function _parse_capability($caps)
    {
    if (!is_array($caps))
      $cap_arr = explode(' ', $caps);
    else
      $cap_arr = $caps;
    foreach ($cap_arr as $cap)
      {
      if ($cap=='CAPABILITY')
        continue;
      if (strpos($cap, '=')>0)
        {
        list($key, $value) = explode('=', $cap);
        if (!is_array($this->capabilities[$key]))
          $this->capabilities[$key] = array();
        $this->capabilities[$key][] = $value;
        }
      else
        $this->capabilities[$cap] = TRUE;
      }
    }