Index: /contrib/z-push/include/mimeDecode.php
===================================================================
--- /contrib/z-push/include/mimeDecode.php	(revision 3637)
+++ /contrib/z-push/include/mimeDecode.php	(revision 3754)
@@ -29,6 +29,6 @@
  *   notice, this list of conditions and the following disclaimer in the
  *   documentation and/or other materials provided with the distribution.
- * - Neither the name of the authors, nor the names of its contributors 
- *   may be used to endorse or promote products derived from this 
+ * - Neither the name of the authors, nor the names of its contributors
+ *   may be used to endorse or promote products derived from this
  *   software without specific prior written permission.
  *
@@ -64,8 +64,8 @@
  * removed deprecated referencing: $obj = &new Mail_mimeDecode($body); in _decode()
  * implemented automated decoding of strings from mail charset
- * 
- * Reference implementation used: 
+ *
+ * Reference implementation used:
  * http://download.pear.php.net/package/Mail_mimeDecode-1.5.1.tgz
- * 
+ *
  */
 
@@ -102,818 +102,818 @@
 class Mail_mimeDecode
 {
-    /**
-     * The raw email to decode
-     *
-     * @var    string
-     * @access private
-     */
-    var $_input;
-
-    /**
-     * The header part of the input
-     *
-     * @var    string
-     * @access private
-     */
-    var $_header;
-
-    /**
-     * The body part of the input
-     *
-     * @var    string
-     * @access private
-     */
-    var $_body;
-
-    /**
-     * If an error occurs, this is used to store the message
-     *
-     * @var    string
-     * @access private
-     */
-    var $_error;
-
-    /**
-     * Flag to determine whether to include bodies in the
-     * returned object.
-     *
-     * @var    boolean
-     * @access private
-     */
-    var $_include_bodies;
-
-    /**
-     * Flag to determine whether to decode bodies
-     *
-     * @var    boolean
-     * @access private
-     */
-    var $_decode_bodies;
-
-    /**
-     * Flag to determine whether to decode headers
-     *
-     * @var    boolean
-     * @access private
-     */
-    var $_decode_headers;
-
-    /**
-     * Flag to determine whether to include attached messages
-     * as body in the returned object. Depends on $_include_bodies
-     *
-     * @var    boolean
-     * @access private
-     */
-    var $_rfc822_bodies;
-
-    /**
-     * Constructor.
-     *
-     * Sets up the object, initialise the variables, and splits and
-     * stores the header and body of the input.
-     *
-     * @param string The input to decode
-     * @access public
-     */
-    function Mail_mimeDecode($input, $deprecated_linefeed = '')
-    {
-        list($header, $body)   = $this->_splitBodyHeader($input);
-
-        $this->_input          = $input;
-        $this->_header         = $header;
-        $this->_body           = $body;
-        $this->_decode_bodies  = false;
-        $this->_include_bodies = true;
-        $this->_rfc822_bodies  = false;
-    }
-
-    /**
-     * Begins the decoding process. If called statically
-     * it will create an object and call the decode() method
-     * of it.
-     *
-     * @param array An array of various parameters that determine
-     *              various things:
-     *              include_bodies - Whether to include the body in the returned
-     *                               object.
-     *              decode_bodies  - Whether to decode the bodies
-     *                               of the parts. (Transfer encoding)
-     *              decode_headers - Whether to decode headers
-     *              input          - If called statically, this will be treated
-     *                               as the input
-     *              charset        - convert all data to this charset
-     * @return object Decoded results
-     * @access public
-     */
-    function decode($params = null)
-    {
-        // determine if this method has been called statically
-        $isStatic = !(isset($this) && get_class($this) == __CLASS__);
-
-        // Have we been called statically?
-        // If so, create an object and pass details to that.
-        if ($isStatic AND isset($params['input'])) {
-
-            $obj = new Mail_mimeDecode($params['input']);
-            $structure = $obj->decode($params);
-
-        // Called statically but no input
-        } elseif ($isStatic) {
-            return $this->raiseError('Called statically and no input given');
-
-        // Called via an object
-        } else {
-            $this->_include_bodies = isset($params['include_bodies']) ?
-                                 $params['include_bodies'] : false;
-            $this->_decode_bodies  = isset($params['decode_bodies']) ?
-                                 $params['decode_bodies']  : false;
-            $this->_decode_headers = isset($params['decode_headers']) ?
-                                 $params['decode_headers'] : false;
-            $this->_rfc822_bodies  = isset($params['rfc_822bodies']) ?
-                                 $params['rfc_822bodies']  : false;
-            $this->_charset = isset($params['charset']) ?
-                                 $params['charset'] : 'utf-8';
-                                 
-            $structure = $this->_decode($this->_header, $this->_body);
-            if ($structure === false) {
-                $structure = $this->raiseError($this->_error);
-            }
-        }
-
-        return $structure;
-    }
-
-    /**
-     * Performs the decoding. Decodes the body string passed to it
-     * If it finds certain content-types it will call itself in a
-     * recursive fashion
-     *
-     * @param string Header section
-     * @param string Body section
-     * @return object Results of decoding process
-     * @access private
-     */
-    function _decode($headers, $body, $default_ctype = 'text/plain')
-    {
-        $return = new stdClass;
-        $return->headers = array();
-        $headers = $this->_parseHeaders($headers);
-
-        foreach ($headers as $value) {
-            if (isset($return->headers[strtolower($value['name'])]) AND !is_array($return->headers[strtolower($value['name'])])) {
-                $return->headers[strtolower($value['name'])]   = array($return->headers[strtolower($value['name'])]);
-                $return->headers[strtolower($value['name'])][] = $value['value'];
-
-            } elseif (isset($return->headers[strtolower($value['name'])])) {
-                $return->headers[strtolower($value['name'])][] = $value['value'];
-
-            } else {
-                $return->headers[strtolower($value['name'])] = $value['value'];
-            }
-        }
-
-        reset($headers);
-        while (list($key, $value) = each($headers)) {
-            $headers[$key]['name'] = strtolower($headers[$key]['name']);
-            switch ($headers[$key]['name']) {
-
-                case 'content-type':
-                    $content_type = $this->_parseHeaderValue($headers[$key]['value']);
-
-                    if (preg_match('/([0-9a-z+.-]+)\/([0-9a-z+.-]+)/i', $content_type['value'], $regs)) {
-                        $return->ctype_primary   = $regs[1];
-                        $return->ctype_secondary = $regs[2];
-                    }
-
-                    if (isset($content_type['other'])) {
-                        while (list($p_name, $p_value) = each($content_type['other'])) {
-                            $return->ctype_parameters[$p_name] = $p_value;
-                        }
-                    }
-                    break;
-
-                case 'content-disposition':
-                    $content_disposition = $this->_parseHeaderValue($headers[$key]['value']);
-                    $return->disposition   = $content_disposition['value'];
-                    if (isset($content_disposition['other'])) {
-                        while (list($p_name, $p_value) = each($content_disposition['other'])) {
-                            $return->d_parameters[$p_name] = $p_value;
-                        }
-                    }
-                    break;
-
-                case 'content-transfer-encoding':
-                    $content_transfer_encoding = $this->_parseHeaderValue($headers[$key]['value']);
-                    break;
-            }
-        }
-
-        if (isset($content_type)) {
-            switch (strtolower($content_type['value'])) {
-                case 'text/plain':
-                    $encoding = isset($content_transfer_encoding) ? $content_transfer_encoding['value'] : '7bit';
-                    $charset = isset($return->ctype_parameters['charset']) ? $return->ctype_parameters['charset'] : $this->_charset;
-                    $this->_include_bodies ? $return->body = ($this->_decode_bodies ? $this->_decodeBody($body, $encoding, $charset) : $body) : null;
-                    break;
-
-                case 'text/html':
-                    $encoding = isset($content_transfer_encoding) ? $content_transfer_encoding['value'] : '7bit';
-                    $charset = isset($return->ctype_parameters['charset']) ? $return->ctype_parameters['charset'] : $this->_charset;
-                    $this->_include_bodies ? $return->body = ($this->_decode_bodies ? $this->_decodeBody($body, $encoding, $charset) : $body) : null;
-                    break;
-
-                case 'multipart/parallel':
-                case 'multipart/appledouble': // Appledouble mail
-                case 'multipart/report': // RFC1892
-                case 'multipart/signed': // PGP
-                case 'multipart/digest':
-                case 'multipart/alternative':
-                case 'multipart/related':
-                case 'multipart/mixed':
-                    if(!isset($content_type['other']['boundary'])){
-                        $this->_error = 'No boundary found for ' . $content_type['value'] . ' part';
-                        return false;
-                    }
-
-                    $default_ctype = (strtolower($content_type['value']) === 'multipart/digest') ? 'message/rfc822' : 'text/plain';
-
-                    $parts = $this->_boundarySplit($body, $content_type['other']['boundary']);
-                    for ($i = 0; $i < count($parts); $i++) {
-                        list($part_header, $part_body) = $this->_splitBodyHeader($parts[$i]);
-                        $part = $this->_decode($part_header, $part_body, $default_ctype);
-                        if($part === false)
-                            $part = $this->raiseError($this->_error);
-                        $return->parts[] = $part;
-                    }
-                    break;
-
-                case 'message/rfc822':
-                    if ($this->_rfc822_bodies) {
-                        $encoding = isset($content_transfer_encoding) ? $content_transfer_encoding['value'] : '7bit';
-                        $charset = isset($return->ctype_parameters['charset']) ? $return->ctype_parameters['charset'] : $this->_charset;
-                        $return->body = ($this->_decode_bodies ? $this->_decodeBody($body, $encoding, $charset) : $body);
-                    }
-
-                    $obj = new Mail_mimeDecode($body);
-                    $return->parts[] = $obj->decode(array('include_bodies' => $this->_include_bodies,
+	/**
+	 * The raw email to decode
+	 *
+	 * @var    string
+	 * @access private
+	 */
+	var $_input;
+
+	/**
+	 * The header part of the input
+	 *
+	 * @var    string
+	 * @access private
+	 */
+	var $_header;
+
+	/**
+	 * The body part of the input
+	 *
+	 * @var    string
+	 * @access private
+	 */
+	var $_body;
+
+	/**
+	 * If an error occurs, this is used to store the message
+	 *
+	 * @var    string
+	 * @access private
+	 */
+	var $_error;
+
+	/**
+	 * Flag to determine whether to include bodies in the
+	 * returned object.
+	 *
+	 * @var    boolean
+	 * @access private
+	 */
+	var $_include_bodies;
+
+	/**
+	 * Flag to determine whether to decode bodies
+	 *
+	 * @var    boolean
+	 * @access private
+	 */
+	var $_decode_bodies;
+
+	/**
+	 * Flag to determine whether to decode headers
+	 *
+	 * @var    boolean
+	 * @access private
+	 */
+	var $_decode_headers;
+
+	/**
+	 * Flag to determine whether to include attached messages
+	 * as body in the returned object. Depends on $_include_bodies
+	 *
+	 * @var    boolean
+	 * @access private
+	 */
+	var $_rfc822_bodies;
+
+	/**
+	 * Constructor.
+	 *
+	 * Sets up the object, initialise the variables, and splits and
+	 * stores the header and body of the input.
+	 *
+	 * @param string The input to decode
+	 * @access public
+	 */
+	function Mail_mimeDecode($input, $deprecated_linefeed = '')
+	{
+		list($header, $body)   = $this->_splitBodyHeader($input);
+
+		$this->_input          = $input;
+		$this->_header         = $header;
+		$this->_body           = $body;
+		$this->_decode_bodies  = false;
+		$this->_include_bodies = true;
+		$this->_rfc822_bodies  = false;
+	}
+
+	/**
+	 * Begins the decoding process. If called statically
+	 * it will create an object and call the decode() method
+	 * of it.
+	 *
+	 * @param array An array of various parameters that determine
+	 *              various things:
+	 *              include_bodies - Whether to include the body in the returned
+	 *                               object.
+	 *              decode_bodies  - Whether to decode the bodies
+	 *                               of the parts. (Transfer encoding)
+	 *              decode_headers - Whether to decode headers
+	 *              input          - If called statically, this will be treated
+	 *                               as the input
+	 *              charset        - convert all data to this charset
+	 * @return object Decoded results
+	 * @access public
+	 */
+	function decode($params = null)
+	{
+		// determine if this method has been called statically
+		$isStatic = !(isset($this) && get_class($this) == __CLASS__);
+
+		// Have we been called statically?
+		// If so, create an object and pass details to that.
+		if ($isStatic AND isset($params['input'])) {
+
+			$obj = new Mail_mimeDecode($params['input']);
+			$structure = $obj->decode($params);
+
+			// Called statically but no input
+		} elseif ($isStatic) {
+			return $this->raiseError('Called statically and no input given');
+
+			// Called via an object
+		} else {
+			$this->_include_bodies = isset($params['include_bodies']) ?
+			$params['include_bodies'] : false;
+			$this->_decode_bodies  = isset($params['decode_bodies']) ?
+			$params['decode_bodies']  : false;
+			$this->_decode_headers = isset($params['decode_headers']) ?
+			$params['decode_headers'] : false;
+			$this->_rfc822_bodies  = isset($params['rfc_822bodies']) ?
+			$params['rfc_822bodies']  : false;
+			$this->_charset = isset($params['charset']) ?
+			$params['charset'] : 'utf-8';
+			 
+			$structure = $this->_decode($this->_header, $this->_body);
+			if ($structure === false) {
+				$structure = $this->raiseError($this->_error);
+			}
+		}
+
+		return $structure;
+	}
+
+	/**
+	 * Performs the decoding. Decodes the body string passed to it
+	 * If it finds certain content-types it will call itself in a
+	 * recursive fashion
+	 *
+	 * @param string Header section
+	 * @param string Body section
+	 * @return object Results of decoding process
+	 * @access private
+	 */
+	function _decode($headers, $body, $default_ctype = 'text/plain')
+	{
+		$return = new stdClass;
+		$return->headers = array();
+		$headers = $this->_parseHeaders($headers);
+
+		foreach ($headers as $value) {
+			if (isset($return->headers[strtolower($value['name'])]) AND !is_array($return->headers[strtolower($value['name'])])) {
+				$return->headers[strtolower($value['name'])]   = array($return->headers[strtolower($value['name'])]);
+				$return->headers[strtolower($value['name'])][] = $value['value'];
+
+			} elseif (isset($return->headers[strtolower($value['name'])])) {
+				$return->headers[strtolower($value['name'])][] = $value['value'];
+
+			} else {
+				$return->headers[strtolower($value['name'])] = $value['value'];
+			}
+		}
+
+		reset($headers);
+		while (list($key, $value) = each($headers)) {
+			$headers[$key]['name'] = strtolower($headers[$key]['name']);
+			switch ($headers[$key]['name']) {
+
+				case 'content-type':
+					$content_type = $this->_parseHeaderValue($headers[$key]['value']);
+
+					if (preg_match('/([0-9a-z+.-]+)\/([0-9a-z+.-]+)/i', $content_type['value'], $regs)) {
+						$return->ctype_primary   = $regs[1];
+						$return->ctype_secondary = $regs[2];
+					}
+
+					if (isset($content_type['other'])) {
+						while (list($p_name, $p_value) = each($content_type['other'])) {
+							$return->ctype_parameters[$p_name] = $p_value;
+						}
+					}
+					break;
+
+				case 'content-disposition':
+					$content_disposition = $this->_parseHeaderValue($headers[$key]['value']);
+					$return->disposition   = $content_disposition['value'];
+					if (isset($content_disposition['other'])) {
+						while (list($p_name, $p_value) = each($content_disposition['other'])) {
+							$return->d_parameters[$p_name] = $p_value;
+						}
+					}
+					break;
+
+				case 'content-transfer-encoding':
+					$content_transfer_encoding = $this->_parseHeaderValue($headers[$key]['value']);
+					break;
+			}
+		}
+
+		if (isset($content_type)) {
+			switch (strtolower($content_type['value'])) {
+				case 'text/plain':
+					$encoding = isset($content_transfer_encoding) ? $content_transfer_encoding['value'] : '7bit';
+					$charset = isset($return->ctype_parameters['charset']) ? $return->ctype_parameters['charset'] : $this->_charset;
+					$this->_include_bodies ? $return->body = ($this->_decode_bodies ? $this->_decodeBody($body, $encoding, $charset) : $body) : null;
+					break;
+
+				case 'text/html':
+					$encoding = isset($content_transfer_encoding) ? $content_transfer_encoding['value'] : '7bit';
+					$charset = isset($return->ctype_parameters['charset']) ? $return->ctype_parameters['charset'] : $this->_charset;
+					$this->_include_bodies ? $return->body = ($this->_decode_bodies ? $this->_decodeBody($body, $encoding, $charset) : $body) : null;
+					break;
+
+				case 'multipart/parallel':
+				case 'multipart/appledouble': // Appledouble mail
+				case 'multipart/report': // RFC1892
+				case 'multipart/signed': // PGP
+				case 'multipart/digest':
+				case 'multipart/alternative':
+				case 'multipart/related':
+				case 'multipart/mixed':
+					if(!isset($content_type['other']['boundary'])){
+						$this->_error = 'No boundary found for ' . $content_type['value'] . ' part';
+						return false;
+					}
+
+					$default_ctype = (strtolower($content_type['value']) === 'multipart/digest') ? 'message/rfc822' : 'text/plain';
+
+					$parts = $this->_boundarySplit($body, $content_type['other']['boundary']);
+					for ($i = 0; $i < count($parts); $i++) {
+						list($part_header, $part_body) = $this->_splitBodyHeader($parts[$i]);
+						$part = $this->_decode($part_header, $part_body, $default_ctype);
+						if($part === false)
+						$part = $this->raiseError($this->_error);
+						$return->parts[] = $part;
+					}
+					break;
+
+				case 'message/rfc822':
+					if ($this->_rfc822_bodies) {
+						$encoding = isset($content_transfer_encoding) ? $content_transfer_encoding['value'] : '7bit';
+						$charset = isset($return->ctype_parameters['charset']) ? $return->ctype_parameters['charset'] : $this->_charset;
+						$return->body = ($this->_decode_bodies ? $this->_decodeBody($body, $encoding, $charset) : $body);
+					}
+
+					$obj = new Mail_mimeDecode($body);
+					$return->parts[] = $obj->decode(array('include_bodies' => $this->_include_bodies,
                                                           'decode_bodies'  => $this->_decode_bodies,
                                                           'decode_headers' => $this->_decode_headers));
-                    unset($obj);
-                    break;
-
-                default:
-                    if(!isset($content_transfer_encoding['value']))
-                        $content_transfer_encoding['value'] = '7bit';
-                        // if there is no explicit charset, then don't try to convert to default charset
-                        $charset = isset($return->ctype_parameters['charset']) ? $return->ctype_parameters['charset'] : '';
-                        $this->_include_bodies ? $return->body = ($this->_decode_bodies ? $this->_decodeBody($body, $content_transfer_encoding['value'], $charset) : $body) : null;
-                    break;
-            }
-
-        } else {
-            $ctype = explode('/', $default_ctype);
-            $return->ctype_primary   = $ctype[0];
-            $return->ctype_secondary = $ctype[1];
-            $this->_include_bodies ? $return->body = ($this->_decode_bodies ? $this->_decodeBody($body) : $body) : null;
-        }
-
-        return $return;
-    }
-
-    /**
-     * Given the output of the above function, this will return an
-     * array of references to the parts, indexed by mime number.
-     *
-     * @param  object $structure   The structure to go through
-     * @param  string $mime_number Internal use only.
-     * @return array               Mime numbers
-     */
-    function &getMimeNumbers(&$structure, $no_refs = false, $mime_number = '', $prepend = '')
-    {
-        $return = array();
-        if (!empty($structure->parts)) {
-            if ($mime_number != '') {
-                $structure->mime_id = $prepend . $mime_number;
-                $return[$prepend . $mime_number] = &$structure;
-            }
-            for ($i = 0; $i < count($structure->parts); $i++) {
-
-            
-                if (!empty($structure->headers['content-type']) AND substr(strtolower($structure->headers['content-type']), 0, 8) == 'message/') {
-                    $prepend      = $prepend . $mime_number . '.';
-                    $_mime_number = '';
-                } else {
-                    $_mime_number = ($mime_number == '' ? $i + 1 : sprintf('%s.%s', $mime_number, $i + 1));
-                }
-
-                $arr = &Mail_mimeDecode::getMimeNumbers($structure->parts[$i], $no_refs, $_mime_number, $prepend);
-                foreach ($arr as $key => $val) {
-                    $no_refs ? $return[$key] = '' : $return[$key] = &$arr[$key];
-                }
-            }
-        } else {
-            if ($mime_number == '') {
-                $mime_number = '1';
-            }
-            $structure->mime_id = $prepend . $mime_number;
-            $no_refs ? $return[$prepend . $mime_number] = '' : $return[$prepend . $mime_number] = &$structure;
-        }
-        
-        return $return;
-    }
-
-    /**
-     * Given a string containing a header and body
-     * section, this function will split them (at the first
-     * blank line) and return them.
-     *
-     * @param string Input to split apart
-     * @return array Contains header and body section
-     * @access private
-     */
-    function _splitBodyHeader($input)
-    {
-        if (preg_match("/^(.*?)\r?\n\r?\n(.*)/s", $input, $match)) {
-            return array($match[1], $match[2]);
-        }
-        $this->_error = 'Could not split header and body';
-        return false;
-    }
-
-    /**
-     * Parse headers given in $input and return
-     * as assoc array.
-     *
-     * @param string Headers to parse
-     * @return array Contains parsed headers
-     * @access private
-     */
-    function _parseHeaders($input)
-    {
-
-        if ($input !== '') {
-            // Unfold the input
-            $input   = preg_replace("/\r?\n/", "\r\n", $input);
-            $input   = preg_replace("/\r\n(\t| )+/", ' ', $input);
-            $headers = explode("\r\n", trim($input));
-
-            foreach ($headers as $value) {
-                $hdr_name = substr($value, 0, $pos = strpos($value, ':'));
-                $hdr_value = substr($value, $pos+1);
-                if($hdr_value[0] == ' ')
-                    $hdr_value = substr($hdr_value, 1);
-
-                $return[] = array(
+					unset($obj);
+					break;
+
+				default:
+					if(!isset($content_transfer_encoding['value']))
+					$content_transfer_encoding['value'] = '7bit';
+					// if there is no explicit charset, then don't try to convert to default charset
+					$charset = isset($return->ctype_parameters['charset']) ? $return->ctype_parameters['charset'] : '';
+					$this->_include_bodies ? $return->body = ($this->_decode_bodies ? $this->_decodeBody($body, $content_transfer_encoding['value'], $charset) : $body) : null;
+					break;
+			}
+
+		} else {
+			$ctype = explode('/', $default_ctype);
+			$return->ctype_primary   = $ctype[0];
+			$return->ctype_secondary = $ctype[1];
+			$this->_include_bodies ? $return->body = ($this->_decode_bodies ? $this->_decodeBody($body) : $body) : null;
+		}
+
+		return $return;
+	}
+
+	/**
+	 * Given the output of the above function, this will return an
+	 * array of references to the parts, indexed by mime number.
+	 *
+	 * @param  object $structure   The structure to go through
+	 * @param  string $mime_number Internal use only.
+	 * @return array               Mime numbers
+	 */
+	function &getMimeNumbers(&$structure, $no_refs = false, $mime_number = '', $prepend = '')
+	{
+		$return = array();
+		if (!empty($structure->parts)) {
+			if ($mime_number != '') {
+				$structure->mime_id = $prepend . $mime_number;
+				$return[$prepend . $mime_number] = &$structure;
+			}
+			for ($i = 0; $i < count($structure->parts); $i++) {
+
+
+				if (!empty($structure->headers['content-type']) AND substr(strtolower($structure->headers['content-type']), 0, 8) == 'message/') {
+					$prepend      = $prepend . $mime_number . '.';
+					$_mime_number = '';
+				} else {
+					$_mime_number = ($mime_number == '' ? $i + 1 : sprintf('%s.%s', $mime_number, $i + 1));
+				}
+
+				$arr = &Mail_mimeDecode::getMimeNumbers($structure->parts[$i], $no_refs, $_mime_number, $prepend);
+				foreach ($arr as $key => $val) {
+					$no_refs ? $return[$key] = '' : $return[$key] = &$arr[$key];
+				}
+			}
+		} else {
+			if ($mime_number == '') {
+				$mime_number = '1';
+			}
+			$structure->mime_id = $prepend . $mime_number;
+			$no_refs ? $return[$prepend . $mime_number] = '' : $return[$prepend . $mime_number] = &$structure;
+		}
+
+		return $return;
+	}
+
+	/**
+	 * Given a string containing a header and body
+	 * section, this function will split them (at the first
+	 * blank line) and return them.
+	 *
+	 * @param string Input to split apart
+	 * @return array Contains header and body section
+	 * @access private
+	 */
+	function _splitBodyHeader($input)
+	{
+		if (preg_match("/^(.*?)\r?\n\r?\n(.*)/s", $input, $match)) {
+			return array($match[1], $match[2]);
+		}
+		$this->_error = 'Could not split header and body';
+		return false;
+	}
+
+	/**
+	 * Parse headers given in $input and return
+	 * as assoc array.
+	 *
+	 * @param string Headers to parse
+	 * @return array Contains parsed headers
+	 * @access private
+	 */
+	function _parseHeaders($input)
+	{
+
+		if ($input !== '') {
+			// Unfold the input
+			$input   = preg_replace("/\r?\n/", "\r\n", $input);
+			$input   = preg_replace("/\r\n(\t| )+/", ' ', $input);
+			$headers = explode("\r\n", trim($input));
+
+			foreach ($headers as $value) {
+				$hdr_name = substr($value, 0, $pos = strpos($value, ':'));
+				$hdr_value = substr($value, $pos+1);
+				if($hdr_value[0] == ' ')
+				$hdr_value = substr($hdr_value, 1);
+
+				$return[] = array(
                                   'name'  => $hdr_name,
                                   'value' => $this->_decode_headers ? $this->_decodeHeader($hdr_value) : $hdr_value
-                                 );
-            }
-        } else {
-            $return = array();
-        }
-
-        return $return;
-    }
-
-    /**
-     * Function to parse a header value,
-     * extract first part, and any secondary
-     * parts (after ;) This function is not as
-     * robust as it could be. Eg. header comments
-     * in the wrong place will probably break it.
-     *
-     * @param string Header value to parse
-     * @return array Contains parsed result
-     * @access private
-     */
-    function _parseHeaderValue($input)
-    {
-
-        if (($pos = strpos($input, ';')) !== false) {
-
-            $return['value'] = trim(substr($input, 0, $pos));
-            $input = trim(substr($input, $pos+1));
-
-            if (strlen($input) > 0) {
-
-                // This splits on a semi-colon, if there's no preceeding backslash
-                // Now works with quoted values; had to glue the \; breaks in PHP
-                // the regex is already bordering on incomprehensible
-                //$splitRegex = '/([^;\'"]*[\'"]([^\'"]*([^\'"]*)*)[\'"][^;\'"]*|([^;]+))(;|$)/';
-                // simplyfied RegEx - Nokia Mail2 sends boundaries containing ' which break the above regex
-                $splitRegex = '/([^;\'"]*[\'"]([^\'"]*)[\'"][^;\'"]*|([^;]+))(;|$)/';
-                preg_match_all($splitRegex, $input, $matches);
-
-                $parameters = array();
-                for ($i=0; $i<count($matches[0]); $i++) {
-                    $param = $matches[0][$i];
-                    while (substr($param, -2) == '\;') {
-                        $param .= $matches[0][++$i];
-                    }
-                    $parameters[] = $param;
-                }
-
-                for ($i = 0; $i < count($parameters); $i++) {
-                    $param_name  = trim(substr($parameters[$i], 0, $pos = strpos($parameters[$i], '=')), "'\";\t\\ ");
-                    $param_value = trim(str_replace('\;', ';', substr($parameters[$i], $pos + 1)), "'\";\t\\ ");
-                    if (!empty($param_value[0]) && $param_value[0] == '"') {
-                        $param_value = substr($param_value, 1, -1);
-                    }
-                    $return['other'][$param_name] = $param_value;
-                    $return['other'][strtolower($param_name)] = $param_value;
-                }
-            }
-        } else {
-            $return['value'] = trim($input);
-        }
-
-        return $return;
-    }
-
-    /**
-     * This function splits the input based
-     * on the given boundary
-     *
-     * @param string Input to parse
-     * @return array Contains array of resulting mime parts
-     * @access private
-     */
-    function _boundarySplit($input, $boundary)
-    {
-        $parts = array();
-
-        $bs_possible = substr($boundary, 2, -2);
-        $bs_check = '\"' . $bs_possible . '\"';
-
-        if ($boundary == $bs_check) {
-            $boundary = $bs_possible;
-        }
-
-        $tmp = explode('--' . $boundary, $input);
-
-        for ($i = 1; $i < count($tmp) - 1; $i++) {
-            $parts[] = $tmp[$i];
-        }
-
-        return $parts;
-    }
-
-    /**
-     * Given a header, this function will decode it
-     * according to RFC2047. Probably not *exactly*
-     * conformant, but it does pass all the given
-     * examples (in RFC2047).
-     *
-     * @param string Input header value to decode
-     * @return string Decoded header value
-     * @access private
-     */
-    function _decodeHeader($input)
-    {
-        // Remove white space between encoded-words
-        $input = preg_replace('/(=\?[^?]+\?(q|b)\?[^?]*\?=)(\s)+=\?/i', '\1=?', $input);
-
-        // For each encoded-word...
-        while (preg_match('/(=\?([^?]+)\?(q|b)\?([^?]*)\?=)/i', $input, $matches)) {
-
-            $encoded  = $matches[1];
-            $charset  = $matches[2];
-            $encoding = $matches[3];
-            $text     = $matches[4];
-
-            switch (strtolower($encoding)) {
-                case 'b':
-                    $text = base64_decode($text);
-                    break;
-
-                case 'q':
-                    $text = str_replace('_', ' ', $text);
-                    preg_match_all('/=([a-f0-9]{2})/i', $text, $matches);
-                    foreach($matches[1] as $value)
-                        $text = str_replace('='.$value, chr(hexdec($value)), $text);
-                    break;
-            }
-
-            $input = str_replace($encoded, $this->_fromCharset($charset, $text), $input);
-        }
-
-        return $input;
-    }
-
-    /**
-     * Given a body string and an encoding type,
-     * this function will decode and return it.
-     *
-     * @param  string Input body to decode
-     * @param  string Encoding type to use.
-     * @return string Decoded body
-     * @access private
-     */
-    function _decodeBody($input, $encoding = '7bit', $charset = '')
-    {
-        switch (strtolower($encoding)) {
-            case '7bit':
-                return $this->_fromCharset($charset, $input);;
-                break;
-
-            case '8bit':
-                return $this->_fromCharset($charset, $input);
-                break;
-                                
-            case 'quoted-printable':
-                return $this->_fromCharset($charset, $this->_quotedPrintableDecode($input));
-                break;
-
-            case 'base64':
-                return $this->_fromCharset($charset, base64_decode($input));
-                break;
-
-            default:
-                return $input;
-        }
-    }
-
-    /**
-     * Given a quoted-printable string, this
-     * function will decode and return it.
-     *
-     * @param  string Input body to decode
-     * @return string Decoded body
-     * @access private
-     */
-    function _quotedPrintableDecode($input)
-    {
-        // Remove soft line breaks
-        $input = preg_replace("/=\r?\n/", '', $input);
-
-        // Replace encoded characters
-        $input = preg_replace('/=([a-f0-9]{2})/ie', "chr(hexdec('\\1'))", $input);
-
-        return $input;
-    }
-
-    /**
-     * Checks the input for uuencoded files and returns
-     * an array of them. Can be called statically, eg:
-     *
-     * $files =& Mail_mimeDecode::uudecode($some_text);
-     *
-     * It will check for the begin 666 ... end syntax
-     * however and won't just blindly decode whatever you
-     * pass it.
-     *
-     * @param  string Input body to look for attahcments in
-     * @return array  Decoded bodies, filenames and permissions
-     * @access public
-     * @author Unknown
-     */
-    function &uudecode($input)
-    {
-        // Find all uuencoded sections
-        preg_match_all("/begin ([0-7]{3}) (.+)\r?\n(.+)\r?\nend/Us", $input, $matches);
-
-        for ($j = 0; $j < count($matches[3]); $j++) {
-
-            $str      = $matches[3][$j];
-            $filename = $matches[2][$j];
-            $fileperm = $matches[1][$j];
-
-            $file = '';
-            $str = preg_split("/\r?\n/", trim($str));
-            $strlen = count($str);
-
-            for ($i = 0; $i < $strlen; $i++) {
-                $pos = 1;
-                $d = 0;
-                $len=(int)(((ord(substr($str[$i],0,1)) -32) - ' ') & 077);
-
-                while (($d + 3 <= $len) AND ($pos + 4 <= strlen($str[$i]))) {
-                    $c0 = (ord(substr($str[$i],$pos,1)) ^ 0x20);
-                    $c1 = (ord(substr($str[$i],$pos+1,1)) ^ 0x20);
-                    $c2 = (ord(substr($str[$i],$pos+2,1)) ^ 0x20);
-                    $c3 = (ord(substr($str[$i],$pos+3,1)) ^ 0x20);
-                    $file .= chr(((($c0 - ' ') & 077) << 2) | ((($c1 - ' ') & 077) >> 4));
-
-                    $file .= chr(((($c1 - ' ') & 077) << 4) | ((($c2 - ' ') & 077) >> 2));
-
-                    $file .= chr(((($c2 - ' ') & 077) << 6) |  (($c3 - ' ') & 077));
-
-                    $pos += 4;
-                    $d += 3;
-                }
-
-                if (($d + 2 <= $len) && ($pos + 3 <= strlen($str[$i]))) {
-                    $c0 = (ord(substr($str[$i],$pos,1)) ^ 0x20);
-                    $c1 = (ord(substr($str[$i],$pos+1,1)) ^ 0x20);
-                    $c2 = (ord(substr($str[$i],$pos+2,1)) ^ 0x20);
-                    $file .= chr(((($c0 - ' ') & 077) << 2) | ((($c1 - ' ') & 077) >> 4));
-
-                    $file .= chr(((($c1 - ' ') & 077) << 4) | ((($c2 - ' ') & 077) >> 2));
-
-                    $pos += 3;
-                    $d += 2;
-                }
-
-                if (($d + 1 <= $len) && ($pos + 2 <= strlen($str[$i]))) {
-                    $c0 = (ord(substr($str[$i],$pos,1)) ^ 0x20);
-                    $c1 = (ord(substr($str[$i],$pos+1,1)) ^ 0x20);
-                    $file .= chr(((($c0 - ' ') & 077) << 2) | ((($c1 - ' ') & 077) >> 4));
-
-                }
-            }
-            $files[] = array('filename' => $filename, 'fileperm' => $fileperm, 'filedata' => $file);
-        }
-
-        return $files;
-    }
-
-    /**
-     * getSendArray() returns the arguments required for Mail::send()
-     * used to build the arguments for a mail::send() call 
-     *
-     * Usage:
-     * $mailtext = Full email (for example generated by a template)
-     * $decoder = new Mail_mimeDecode($mailtext);
-     * $parts =  $decoder->getSendArray();
-     * if (!PEAR::isError($parts) {
-     *     list($recipents,$headers,$body) = $parts;
-     *     $mail = Mail::factory('smtp');
-     *     $mail->send($recipents,$headers,$body);
-     * } else {
-     *     echo $parts->message;
-     * }
-     * @return mixed   array of recipeint, headers,body or Pear_Error
-     * @access public
-     * @author Alan Knowles <alan@akbkhome.com>
-     */
-    function getSendArray()
-    {
-        // prevent warning if this is not set
-        $this->_decode_headers = FALSE;
-        $headerlist =$this->_parseHeaders($this->_header);
-        $to = "";
-        if (!$headerlist) {
-            return $this->raiseError("Message did not contain headers");
-        }
-        foreach($headerlist as $item) {
-            $header[$item['name']] = $item['value'];
-            switch (strtolower($item['name'])) {
-                case "to":
-                case "cc":
-                case "bcc":
-                    $to .= ",".$item['value'];
-                default:
-                   break;
-            }
-        }
-        if ($to == "") {
-            return $this->raiseError("Message did not contain any recipents");
-        }
-        $to = substr($to,1);
-        return array($to,$header,$this->_body);
-    } 
-
-    /**
-     * Returns a xml copy of the output of
-     * Mail_mimeDecode::decode. Pass the output in as the
-     * argument. This function can be called statically. Eg:
-     *
-     * $output = $obj->decode();
-     * $xml    = Mail_mimeDecode::getXML($output);
-     *
-     * The DTD used for this should have been in the package. Or
-     * alternatively you can get it from cvs, or here:
-     * http://www.phpguru.org/xmail/xmail.dtd.
-     *
-     * @param  object Input to convert to xml. This should be the
-     *                output of the Mail_mimeDecode::decode function
-     * @return string XML version of input
-     * @access public
-     */
-    function getXML($input)
-    {
-        $crlf    =  "\r\n";
-        $output  = '<?xml version=\'1.0\'?>' . $crlf .
+				);
+			}
+		} else {
+			$return = array();
+		}
+
+		return $return;
+	}
+
+	/**
+	 * Function to parse a header value,
+	 * extract first part, and any secondary
+	 * parts (after ;) This function is not as
+	 * robust as it could be. Eg. header comments
+	 * in the wrong place will probably break it.
+	 *
+	 * @param string Header value to parse
+	 * @return array Contains parsed result
+	 * @access private
+	 */
+	function _parseHeaderValue($input)
+	{
+
+		if (($pos = strpos($input, ';')) !== false) {
+
+			$return['value'] = trim(substr($input, 0, $pos));
+			$input = trim(substr($input, $pos+1));
+
+			if (strlen($input) > 0) {
+
+				// This splits on a semi-colon, if there's no preceeding backslash
+				// Now works with quoted values; had to glue the \; breaks in PHP
+				// the regex is already bordering on incomprehensible
+				//$splitRegex = '/([^;\'"]*[\'"]([^\'"]*([^\'"]*)*)[\'"][^;\'"]*|([^;]+))(;|$)/';
+				// simplyfied RegEx - Nokia Mail2 sends boundaries containing ' which break the above regex
+				$splitRegex = '/([^;\'"]*[\'"]([^\'"]*)[\'"][^;\'"]*|([^;]+))(;|$)/';
+				preg_match_all($splitRegex, $input, $matches);
+
+				$parameters = array();
+				for ($i=0; $i<count($matches[0]); $i++) {
+					$param = $matches[0][$i];
+					while (substr($param, -2) == '\;') {
+						$param .= $matches[0][++$i];
+					}
+					$parameters[] = $param;
+				}
+
+				for ($i = 0; $i < count($parameters); $i++) {
+					$param_name  = trim(substr($parameters[$i], 0, $pos = strpos($parameters[$i], '=')), "'\";\t\\ ");
+					$param_value = trim(str_replace('\;', ';', substr($parameters[$i], $pos + 1)), "'\";\t\\ ");
+					if (!empty($param_value[0]) && $param_value[0] == '"') {
+						$param_value = substr($param_value, 1, -1);
+					}
+					$return['other'][$param_name] = $param_value;
+					$return['other'][strtolower($param_name)] = $param_value;
+				}
+			}
+		} else {
+			$return['value'] = trim($input);
+		}
+
+		return $return;
+	}
+
+	/**
+	 * This function splits the input based
+	 * on the given boundary
+	 *
+	 * @param string Input to parse
+	 * @return array Contains array of resulting mime parts
+	 * @access private
+	 */
+	function _boundarySplit($input, $boundary)
+	{
+		$parts = array();
+
+		$bs_possible = substr($boundary, 2, -2);
+		$bs_check = '\"' . $bs_possible . '\"';
+
+		if ($boundary == $bs_check) {
+			$boundary = $bs_possible;
+		}
+
+		$tmp = explode('--' . $boundary, $input);
+
+		for ($i = 1; $i < count($tmp) - 1; $i++) {
+			$parts[] = $tmp[$i];
+		}
+
+		return $parts;
+	}
+
+	/**
+	 * Given a header, this function will decode it
+	 * according to RFC2047. Probably not *exactly*
+	 * conformant, but it does pass all the given
+	 * examples (in RFC2047).
+	 *
+	 * @param string Input header value to decode
+	 * @return string Decoded header value
+	 * @access private
+	 */
+	function _decodeHeader($input)
+	{
+		// Remove white space between encoded-words
+		$input = preg_replace('/(=\?[^?]+\?(q|b)\?[^?]*\?=)(\s)+=\?/i', '\1=?', $input);
+
+		// For each encoded-word...
+		while (preg_match('/(=\?([^?]+)\?(q|b)\?([^?]*)\?=)/i', $input, $matches)) {
+
+			$encoded  = $matches[1];
+			$charset  = $matches[2];
+			$encoding = $matches[3];
+			$text     = $matches[4];
+
+			switch (strtolower($encoding)) {
+				case 'b':
+					$text = base64_decode($text);
+					break;
+
+				case 'q':
+					$text = str_replace('_', ' ', $text);
+					preg_match_all('/=([a-f0-9]{2})/i', $text, $matches);
+					foreach($matches[1] as $value)
+					$text = str_replace('='.$value, chr(hexdec($value)), $text);
+					break;
+			}
+
+			$input = str_replace($encoded, $this->_fromCharset($charset, $text), $input);
+		}
+
+		return $input;
+	}
+
+	/**
+	 * Given a body string and an encoding type,
+	 * this function will decode and return it.
+	 *
+	 * @param  string Input body to decode
+	 * @param  string Encoding type to use.
+	 * @return string Decoded body
+	 * @access private
+	 */
+	function _decodeBody($input, $encoding = '7bit', $charset = '')
+	{
+		switch (strtolower($encoding)) {
+			case '7bit':
+				return $this->_fromCharset($charset, $input);;
+				break;
+
+			case '8bit':
+				return $this->_fromCharset($charset, $input);
+				break;
+
+			case 'quoted-printable':
+				return $this->_fromCharset($charset, $this->_quotedPrintableDecode($input));
+				break;
+
+			case 'base64':
+				return $this->_fromCharset($charset, base64_decode($input));
+				break;
+
+			default:
+				return $input;
+		}
+	}
+
+	/**
+	 * Given a quoted-printable string, this
+	 * function will decode and return it.
+	 *
+	 * @param  string Input body to decode
+	 * @return string Decoded body
+	 * @access private
+	 */
+	function _quotedPrintableDecode($input)
+	{
+		// Remove soft line breaks
+		$input = preg_replace("/=\r?\n/", '', $input);
+
+		// Replace encoded characters
+		$input = preg_replace('/=([a-f0-9]{2})/ie', "chr(hexdec('\\1'))", $input);
+
+		return $input;
+	}
+
+	/**
+	 * Checks the input for uuencoded files and returns
+	 * an array of them. Can be called statically, eg:
+	 *
+	 * $files =& Mail_mimeDecode::uudecode($some_text);
+	 *
+	 * It will check for the begin 666 ... end syntax
+	 * however and won't just blindly decode whatever you
+	 * pass it.
+	 *
+	 * @param  string Input body to look for attahcments in
+	 * @return array  Decoded bodies, filenames and permissions
+	 * @access public
+	 * @author Unknown
+	 */
+	function &uudecode($input)
+	{
+		// Find all uuencoded sections
+		preg_match_all("/begin ([0-7]{3}) (.+)\r?\n(.+)\r?\nend/Us", $input, $matches);
+
+		for ($j = 0; $j < count($matches[3]); $j++) {
+
+			$str      = $matches[3][$j];
+			$filename = $matches[2][$j];
+			$fileperm = $matches[1][$j];
+
+			$file = '';
+			$str = preg_split("/\r?\n/", trim($str));
+			$strlen = count($str);
+
+			for ($i = 0; $i < $strlen; $i++) {
+				$pos = 1;
+				$d = 0;
+				$len=(int)(((ord(substr($str[$i],0,1)) -32) - ' ') & 077);
+
+				while (($d + 3 <= $len) AND ($pos + 4 <= strlen($str[$i]))) {
+					$c0 = (ord(substr($str[$i],$pos,1)) ^ 0x20);
+					$c1 = (ord(substr($str[$i],$pos+1,1)) ^ 0x20);
+					$c2 = (ord(substr($str[$i],$pos+2,1)) ^ 0x20);
+					$c3 = (ord(substr($str[$i],$pos+3,1)) ^ 0x20);
+					$file .= chr(((($c0 - ' ') & 077) << 2) | ((($c1 - ' ') & 077) >> 4));
+
+					$file .= chr(((($c1 - ' ') & 077) << 4) | ((($c2 - ' ') & 077) >> 2));
+
+					$file .= chr(((($c2 - ' ') & 077) << 6) |  (($c3 - ' ') & 077));
+
+					$pos += 4;
+					$d += 3;
+				}
+
+				if (($d + 2 <= $len) && ($pos + 3 <= strlen($str[$i]))) {
+					$c0 = (ord(substr($str[$i],$pos,1)) ^ 0x20);
+					$c1 = (ord(substr($str[$i],$pos+1,1)) ^ 0x20);
+					$c2 = (ord(substr($str[$i],$pos+2,1)) ^ 0x20);
+					$file .= chr(((($c0 - ' ') & 077) << 2) | ((($c1 - ' ') & 077) >> 4));
+
+					$file .= chr(((($c1 - ' ') & 077) << 4) | ((($c2 - ' ') & 077) >> 2));
+
+					$pos += 3;
+					$d += 2;
+				}
+
+				if (($d + 1 <= $len) && ($pos + 2 <= strlen($str[$i]))) {
+					$c0 = (ord(substr($str[$i],$pos,1)) ^ 0x20);
+					$c1 = (ord(substr($str[$i],$pos+1,1)) ^ 0x20);
+					$file .= chr(((($c0 - ' ') & 077) << 2) | ((($c1 - ' ') & 077) >> 4));
+
+				}
+			}
+			$files[] = array('filename' => $filename, 'fileperm' => $fileperm, 'filedata' => $file);
+		}
+
+		return $files;
+	}
+
+	/**
+	 * getSendArray() returns the arguments required for Mail::send()
+	 * used to build the arguments for a mail::send() call
+	 *
+	 * Usage:
+	 * $mailtext = Full email (for example generated by a template)
+	 * $decoder = new Mail_mimeDecode($mailtext);
+	 * $parts =  $decoder->getSendArray();
+	 * if (!PEAR::isError($parts) {
+	 *     list($recipents,$headers,$body) = $parts;
+	 *     $mail = Mail::factory('smtp');
+	 *     $mail->send($recipents,$headers,$body);
+	 * } else {
+	 *     echo $parts->message;
+	 * }
+	 * @return mixed   array of recipeint, headers,body or Pear_Error
+	 * @access public
+	 * @author Alan Knowles <alan@akbkhome.com>
+	 */
+	function getSendArray()
+	{
+		// prevent warning if this is not set
+		$this->_decode_headers = FALSE;
+		$headerlist =$this->_parseHeaders($this->_header);
+		$to = "";
+		if (!$headerlist) {
+			return $this->raiseError("Message did not contain headers");
+		}
+		foreach($headerlist as $item) {
+			$header[$item['name']] = $item['value'];
+			switch (strtolower($item['name'])) {
+				case "to":
+				case "cc":
+				case "bcc":
+					$to .= ",".$item['value'];
+				default:
+					break;
+			}
+		}
+		if ($to == "") {
+			return $this->raiseError("Message did not contain any recipents");
+		}
+		$to = substr($to,1);
+		return array($to,$header,$this->_body);
+	}
+
+	/**
+	 * Returns a xml copy of the output of
+	 * Mail_mimeDecode::decode. Pass the output in as the
+	 * argument. This function can be called statically. Eg:
+	 *
+	 * $output = $obj->decode();
+	 * $xml    = Mail_mimeDecode::getXML($output);
+	 *
+	 * The DTD used for this should have been in the package. Or
+	 * alternatively you can get it from cvs, or here:
+	 * http://www.phpguru.org/xmail/xmail.dtd.
+	 *
+	 * @param  object Input to convert to xml. This should be the
+	 *                output of the Mail_mimeDecode::decode function
+	 * @return string XML version of input
+	 * @access public
+	 */
+	function getXML($input)
+	{
+		$crlf    =  "\r\n";
+		$output  = '<?xml version=\'1.0\'?>' . $crlf .
                    '<!DOCTYPE email SYSTEM "http://www.phpguru.org/xmail/xmail.dtd">' . $crlf .
                    '<email>' . $crlf .
-                   Mail_mimeDecode::_getXML($input) .
+		Mail_mimeDecode::_getXML($input) .
                    '</email>';
 
-        return $output;
-    }
-
-    /**
-     * Function that does the actual conversion to xml. Does a single
-     * mimepart at a time.
-     *
-     * @param  object  Input to convert to xml. This is a mimepart object.
-     *                 It may or may not contain subparts.
-     * @param  integer Number of tabs to indent
-     * @return string  XML version of input
-     * @access private
-     */
-    function _getXML($input, $indent = 1)
-    {
-        $htab    =  "\t";
-        $crlf    =  "\r\n";
-        $output  =  '';
-        $headers = @(array)$input->headers;
-
-        foreach ($headers as $hdr_name => $hdr_value) {
-
-            // Multiple headers with this name
-            if (is_array($headers[$hdr_name])) {
-                for ($i = 0; $i < count($hdr_value); $i++) {
-                    $output .= Mail_mimeDecode::_getXML_helper($hdr_name, $hdr_value[$i], $indent);
-                }
-
-            // Only one header of this sort
-            } else {
-                $output .= Mail_mimeDecode::_getXML_helper($hdr_name, $hdr_value, $indent);
-            }
-        }
-
-        if (!empty($input->parts)) {
-            for ($i = 0; $i < count($input->parts); $i++) {
-                $output .= $crlf . str_repeat($htab, $indent) . '<mimepart>' . $crlf .
-                           Mail_mimeDecode::_getXML($input->parts[$i], $indent+1) .
-                           str_repeat($htab, $indent) . '</mimepart>' . $crlf;
-            }
-        } elseif (isset($input->body)) {
-            $output .= $crlf . str_repeat($htab, $indent) . '<body><![CDATA[' .
-                       $input->body . ']]></body>' . $crlf;
-        }
-
-        return $output;
-    }
-
-    /**
-     * Helper function to _getXML(). Returns xml of a header.
-     *
-     * @param  string  Name of header
-     * @param  string  Value of header
-     * @param  integer Number of tabs to indent
-     * @return string  XML version of input
-     * @access private
-     */
-    function _getXML_helper($hdr_name, $hdr_value, $indent)
-    {
-        $htab   = "\t";
-        $crlf   = "\r\n";
-        $return = '';
-
-        $new_hdr_value = ($hdr_name != 'received') ? Mail_mimeDecode::_parseHeaderValue($hdr_value) : array('value' => $hdr_value);
-        $new_hdr_name  = str_replace(' ', '-', ucwords(str_replace('-', ' ', $hdr_name)));
-
-        // Sort out any parameters
-        if (!empty($new_hdr_value['other'])) {
-            foreach ($new_hdr_value['other'] as $paramname => $paramvalue) {
-                $params[] = str_repeat($htab, $indent) . $htab . '<parameter>' . $crlf .
-                            str_repeat($htab, $indent) . $htab . $htab . '<paramname>' . htmlspecialchars($paramname) . '</paramname>' . $crlf .
-                            str_repeat($htab, $indent) . $htab . $htab . '<paramvalue>' . htmlspecialchars($paramvalue) . '</paramvalue>' . $crlf .
-                            str_repeat($htab, $indent) . $htab . '</parameter>' . $crlf;
-            }
-
-            $params = implode('', $params);
-        } else {
-            $params = '';
-        }
-
-        $return = str_repeat($htab, $indent) . '<header>' . $crlf .
-                  str_repeat($htab, $indent) . $htab . '<headername>' . htmlspecialchars($new_hdr_name) . '</headername>' . $crlf .
-                  str_repeat($htab, $indent) . $htab . '<headervalue>' . htmlspecialchars($new_hdr_value['value']) . '</headervalue>' . $crlf .
-                  $params .
-                  str_repeat($htab, $indent) . '</header>' . $crlf;
-
-        return $return;
-    }
-
-    /**
-     * Z-Push helper to decode text
-     *
-     * @param  string  current charset of input
-     * @param  string  input
-     * @return string  XML version of input
-     * @access private
-     */
-    function _fromCharset($charset, $input) {
-        if($charset == '')
+		return $output;
+	}
+
+	/**
+	 * Function that does the actual conversion to xml. Does a single
+	 * mimepart at a time.
+	 *
+	 * @param  object  Input to convert to xml. This is a mimepart object.
+	 *                 It may or may not contain subparts.
+	 * @param  integer Number of tabs to indent
+	 * @return string  XML version of input
+	 * @access private
+	 */
+	function _getXML($input, $indent = 1)
+	{
+		$htab    =  "\t";
+		$crlf    =  "\r\n";
+		$output  =  '';
+		$headers = @(array)$input->headers;
+
+		foreach ($headers as $hdr_name => $hdr_value) {
+
+			// Multiple headers with this name
+			if (is_array($headers[$hdr_name])) {
+				for ($i = 0; $i < count($hdr_value); $i++) {
+					$output .= Mail_mimeDecode::_getXML_helper($hdr_name, $hdr_value[$i], $indent);
+				}
+
+				// Only one header of this sort
+			} else {
+				$output .= Mail_mimeDecode::_getXML_helper($hdr_name, $hdr_value, $indent);
+			}
+		}
+
+		if (!empty($input->parts)) {
+			for ($i = 0; $i < count($input->parts); $i++) {
+				$output .= $crlf . str_repeat($htab, $indent) . '<mimepart>' . $crlf .
+				Mail_mimeDecode::_getXML($input->parts[$i], $indent+1) .
+				str_repeat($htab, $indent) . '</mimepart>' . $crlf;
+			}
+		} elseif (isset($input->body)) {
+			$output .= $crlf . str_repeat($htab, $indent) . '<body><![CDATA[' .
+			$input->body . ']]></body>' . $crlf;
+		}
+
+		return $output;
+	}
+
+	/**
+	 * Helper function to _getXML(). Returns xml of a header.
+	 *
+	 * @param  string  Name of header
+	 * @param  string  Value of header
+	 * @param  integer Number of tabs to indent
+	 * @return string  XML version of input
+	 * @access private
+	 */
+	function _getXML_helper($hdr_name, $hdr_value, $indent)
+	{
+		$htab   = "\t";
+		$crlf   = "\r\n";
+		$return = '';
+
+		$new_hdr_value = ($hdr_name != 'received') ? Mail_mimeDecode::_parseHeaderValue($hdr_value) : array('value' => $hdr_value);
+		$new_hdr_name  = str_replace(' ', '-', ucwords(str_replace('-', ' ', $hdr_name)));
+
+		// Sort out any parameters
+		if (!empty($new_hdr_value['other'])) {
+			foreach ($new_hdr_value['other'] as $paramname => $paramvalue) {
+				$params[] = str_repeat($htab, $indent) . $htab . '<parameter>' . $crlf .
+				str_repeat($htab, $indent) . $htab . $htab . '<paramname>' . htmlspecialchars($paramname) . '</paramname>' . $crlf .
+				str_repeat($htab, $indent) . $htab . $htab . '<paramvalue>' . htmlspecialchars($paramvalue) . '</paramvalue>' . $crlf .
+				str_repeat($htab, $indent) . $htab . '</parameter>' . $crlf;
+			}
+
+			$params = implode('', $params);
+		} else {
+			$params = '';
+		}
+
+		$return = str_repeat($htab, $indent) . '<header>' . $crlf .
+		str_repeat($htab, $indent) . $htab . '<headername>' . htmlspecialchars($new_hdr_name) . '</headername>' . $crlf .
+		str_repeat($htab, $indent) . $htab . '<headervalue>' . htmlspecialchars($new_hdr_value['value']) . '</headervalue>' . $crlf .
+		$params .
+		str_repeat($htab, $indent) . '</header>' . $crlf;
+
+		return $return;
+	}
+
+	/**
+	 * Z-Push helper to decode text
+	 *
+	 * @param  string  current charset of input
+	 * @param  string  input
+	 * @return string  XML version of input
+	 * @access private
+	 */
+	function _fromCharset($charset, $input) {
+		if($charset == '' || ($charset == $this->_charset))
             return $input;
 
         return @iconv($charset, $this->_charset. "//TRANSLIT", $input);
-    }
-    
-    /**
-     * Z-Push helper for error logging
-     * removing PEAR dependency
-     *
-     * @param  string  debug message
-     * @return boolean always false as there was an error
-     * @access private
-     */   
-    function raiseError($message) {
-        debugLog("mimeDecode error: ". $message);
-        return false;
-    }    
+	}
+
+	/**
+	 * Z-Push helper for error logging
+	 * removing PEAR dependency
+	 *
+	 * @param  string  debug message
+	 * @return boolean always false as there was an error
+	 * @access private
+	 */
+	function raiseError($message) {
+		debugLog("mimeDecode error: ". $message);
+		return false;
+	}
 } // End of class
Index: /contrib/z-push/include/dbconnect.php
===================================================================
--- /contrib/z-push/include/dbconnect.php	(revision 3637)
+++ /contrib/z-push/include/dbconnect.php	(revision 3754)
@@ -5,6 +5,6 @@
         // set up database connection details
         $dbhost = "10.200.112.132"; // replace with your database hostname or ip
-        $dbuser = "postgres"; // replace with your database username
-        $dbpass = "senha123"; // replace with your database password
+        $dbuser = "zpush"; // replace with your database username
+        $dbpass = "zpush"; // replace with your database password
         $dbname = "expresso"; // replace with your database name
 
Index: /contrib/z-push/backend/BackendProxy.php
===================================================================
--- /contrib/z-push/backend/BackendProxy.php	(revision 3637)
+++ /contrib/z-push/backend/BackendProxy.php	(revision 3754)
@@ -17,4 +17,5 @@
 	var $BackendContacts;
 	var $BackendCalendar;
+	var $folderid;
 
 	function __construct()
@@ -41,8 +42,16 @@
 		debugLog('BackendProxy::Setup('.$user.','.$devid.','.$protocolversion.')');
 		global $BACKEND_EMAIL, $BACKEND_CONTACTS, $BACKEND_CALENDAR;
+		$this->_user = $user;
+		$this->_devid = $devid;
+		$this->_protocolversion = $protocolversion;
 		if (isset($BACKEND_EMAIL)) $this->BackendEmail->Setup($user, $devid, $protocolversion);
 		if (isset($BACKEND_CONTACTS)) $this->BackendContacts->Setup($user, $devid, $protocolversion);
 		if (isset($BACKEND_CALENDAR)) $this->BackendCalendar->Setup($user, $devid, $protocolversion);
 		return true;
+	}
+
+	function GetExporter($folderid = false) {
+		$this->folderid = $folderid;
+		return parent::GetExporter($folderid);
 	}
 
@@ -147,9 +156,13 @@
 		} else return $this->BackendEmail->MoveMessage($folderid, $id, $newfolderid);
 	}
+
 	function AlterPing() {
-		//TODO:  Verificar como deve ser tratado esse método
-		//if (isset($BACKEND_EMAIL)) return true;
-		return true;
+		if ($this->folderid == 'root') {
+			return false;
+		} else if ($this->folderid == 'calendar') {
+			return false;
+		} else return true;
 	}
+
 	function AlterPingChanges($folderid, &$syncstate) {
 		if ($folderid == 'root') {
Index: /contrib/z-push/backend/imap.php
===================================================================
--- /contrib/z-push/backend/imap.php	(revision 3754)
+++ /contrib/z-push/backend/imap.php	(revision 3754)
@@ -0,0 +1,952 @@
+<?php
+/***********************************************
+ * File      :   imap.php
+ * Project   :   Z-Push
+ * Descr     :   This backend is based on
+ *               'BackendDiff' and implements an
+ *               IMAP interface
+ *
+ * Created   :   10.10.2007
+ *
+ * ï¿œ Zarafa Deutschland GmbH, www.zarafaserver.de
+ * This file is distributed under GPL v2.
+ * Consult LICENSE file for details
+ ************************************************/
+
+include_once('diffbackend.php');
+
+// The is an improved version of mimeDecode from PEAR that correctly
+// handles charsets and charset conversion
+include_once('mimeDecode.php');
+require_once('z_RFC822.php');
+
+class BackendIMAP extends BackendDiff {
+	/* Called to logon a user. These are the three authentication strings that you must
+	 * specify in ActiveSync on the PDA. Normally you would do some kind of password
+	 * check here. Alternatively, you could ignore the password here and have Apache
+	 * do authentication via mod_auth_*
+	 */
+	function Logon($username, $domain, $password) {
+		$this->_wasteID = false;
+		$this->_sentID = false;
+		$this->_server = "{" . IMAP_SERVER . ":" . IMAP_PORT . "/imap" . IMAP_OPTIONS . "}";
+
+		if (!function_exists("imap_open"))
+		debugLog("ERROR BackendIMAP : PHP-IMAP module not installed!!!!!");
+
+		// open the IMAP-mailbox
+		$this->_mbox = @imap_open($this->_server , $username, $password, OP_HALFOPEN);
+		$this->_mboxFolder = "";
+
+		if ($this->_mbox) {
+			debugLog("IMAP connection opened sucessfully ");
+			$this->_username = $username;
+			$this->_domain = $domain;
+			// set serverdelimiter
+			$this->_serverdelimiter = $this->getServerDelimiter();
+			return true;
+		}
+		else {
+			debugLog("IMAP can't connect: " . imap_last_error());
+			return false;
+		}
+	}
+
+	/* Called before shutting down the request to close the IMAP connection
+	 */
+	function Logoff() {
+		if ($this->_mbox) {
+			// list all errors
+			$errors = imap_errors();
+			if (is_array($errors)) {
+				foreach ($errors as $e)    debugLog("IMAP-errors: $e");
+			}
+			@imap_close($this->_mbox);
+			debugLog("IMAP connection closed");
+		}
+	}
+
+	/* Called directly after the logon. This specifies the client's protocol version
+	 * and device id. The device ID can be used for various things, including saving
+	 * per-device state information.
+	 * The $user parameter here is normally equal to the $username parameter from the
+	 * Logon() call. In theory though, you could log on a 'foo', and then sync the emails
+	 * of user 'bar'. The $user here is the username specified in the request URL, while the
+	 * $username in the Logon() call is the username which was sent as a part of the HTTP
+	 * authentication.
+	 */
+	function Setup($user, $devid, $protocolversion) {
+		$this->_user = $user;
+		$this->_devid = $devid;
+		$this->_protocolversion = $protocolversion;
+
+		return true;
+	}
+
+	/* Sends a message which is passed as rfc822. You basically can do two things
+	 * 1) Send the message to an SMTP server as-is
+	 * 2) Parse the message yourself, and send it some other way
+	 * It is up to you whether you want to put the message in the sent items folder. If you
+	 * want it in 'sent items', then the next sync on the 'sent items' folder should return
+	 * the new message as any other new message in a folder.
+	 */
+	function SendMail($rfc822, $forward = false, $reply = false, $parent = false) {
+		debugLog("IMAP-SendMail: " . $rfc822 . "for: $forward   reply: $reply   parent: $parent" );
+
+		$mobj = new Mail_mimeDecode($rfc822);
+		$message = $mobj->decode(array('decode_headers' => false, 'decode_bodies' => true, 'include_bodies' => true, 'input' => $rfc822, 'crlf' => "\n", 'charset' => 'utf-8'));
+
+		$toaddr = $ccaddr = $bccaddr = "";
+		if(isset($message->headers["to"]))
+		$toaddr = $this->parseAddr(Mail_RFC822::parseAddressList($message->headers["to"]));
+		if(isset($message->headers["cc"]))
+		$ccaddr = $this->parseAddr(Mail_RFC822::parseAddressList($message->headers["cc"]));
+		if(isset($message->headers["bcc"]))
+		$bccaddr = $this->parseAddr(Mail_RFC822::parseAddressList($message->headers["bcc"]));
+
+		// save some headers when forwarding mails (content type & transfer-encoding)
+		$headers = "";
+		$forward_h_ct = "";
+		$forward_h_cte = "";
+
+		$use_orgbody = false;
+
+		// clean up the transmitted headers
+		// remove default headers because we are using imap_mail
+		$changedfrom = false;
+		$returnPathSet = false;
+		$body_base64 = false;
+		$org_charset = "";
+		foreach($message->headers as $k => $v) {
+			if ($k == "subject" || $k == "to" || $k == "cc" || $k == "bcc")
+			continue;
+
+			if ($k == "content-type") {
+				// save the original content-type header for the body part when forwarding
+				if ($forward) {
+					$forward_h_ct = $v;
+					continue;
+				}
+
+				// set charset always to utf-8
+				$org_charset = $v;
+				$v = preg_replace("/charset=([A-Za-z0-9-\"']+)/", "charset=\"utf-8\"", $v);
+			}
+
+			if ($k == "content-transfer-encoding") {
+				// if the content was base64 encoded, encode the body again when sending
+				if (trim($v) == "base64") $body_base64 = true;
+
+				// save the original encoding header for the body part when forwarding
+				if ($forward) {
+					$forward_h_cte = $v;
+					continue;
+				}
+			}
+
+			// if the message is a multipart message, then we should use the sent body
+			if (!$forward && $k == "content-type" && preg_match("/multipart/i", $v)) {
+				$use_orgbody = true;
+			}
+
+			// check if "from"-header is set
+			if ($k == "from" && ! trim($v) && IMAP_DEFAULTFROM) {
+				$changedfrom = true;
+				if      (IMAP_DEFAULTFROM == 'username') $v = $this->_username;
+				else if (IMAP_DEFAULTFROM == 'domain')   $v = $this->_domain;
+				else $v = $this->_username . IMAP_DEFAULTFROM;
+			}
+
+			// check if "Return-Path"-header is set
+			if ($k == "return-path") {
+				$returnPathSet = true;
+				if (! trim($v) && IMAP_DEFAULTFROM) {
+					if      (IMAP_DEFAULTFROM == 'username') $v = $this->_username;
+					else if (IMAP_DEFAULTFROM == 'domain')   $v = $this->_domain;
+					else $v = $this->_username . IMAP_DEFAULTFROM;
+				}
+			}
+
+			// all other headers stay
+			if ($headers) $headers .= "\n";
+			$headers .= ucfirst($k) . ": ". $v;
+		}
+
+		// set "From" header if not set on the device
+		if(IMAP_DEFAULTFROM && !$changedfrom){
+			if      (IMAP_DEFAULTFROM == 'username') $v = $this->_username;
+			else if (IMAP_DEFAULTFROM == 'domain')   $v = $this->_domain;
+			else $v = $this->_username . IMAP_DEFAULTFROM;
+			if ($headers) $headers .= "\n";
+			$headers .= 'From: '.$v;
+		}
+
+		// set "Return-Path" header if not set on the device
+		if(IMAP_DEFAULTFROM && !$returnPathSet){
+			if      (IMAP_DEFAULTFROM == 'username') $v = $this->_username;
+			else if (IMAP_DEFAULTFROM == 'domain')   $v = $this->_domain;
+			else $v = $this->_username . IMAP_DEFAULTFROM;
+			if ($headers) $headers .= "\n";
+			$headers .= 'Return-Path: '.$v;
+		}
+
+		// if this is a multipart message with a boundary, we must use the original body
+		if ($use_orgbody) {
+			list(,$body) = $mobj->_splitBodyHeader($rfc822);
+		}
+		else
+		$body = $this->getBody($message);
+
+		// reply
+		if (isset($reply) && isset($parent) &&  $reply && $parent) {
+			$this->imap_reopenFolder($parent);
+			// receive entire mail (header + body) to decode body correctly
+			$origmail = @imap_fetchheader($this->_mbox, $reply, FT_PREFETCHTEXT | FT_UID) . @imap_body($this->_mbox, $reply, FT_PEEK | FT_UID);
+			$mobj2 = new Mail_mimeDecode($origmail);
+			// receive only body
+			$body .= $this->getBody($mobj2->decode(array('decode_headers' => false, 'decode_bodies' => true, 'include_bodies' => true, 'input' => $origmail, 'crlf' => "\n", 'charset' => 'utf-8')));
+			// unset mimedecoder & origmail - free memory
+			unset($mobj2);
+			unset($origmail);
+		}
+
+		// encode the body to base64 if it was sent originally in base64 by the pda
+		// the encoded body is included in the forward
+		if ($body_base64) $body = base64_encode($body);
+
+
+		// forward
+		if (isset($forward) && isset($parent) && $forward && $parent) {
+			$this->imap_reopenFolder($parent);
+			// receive entire mail (header + body)
+			$origmail = @imap_fetchheader($this->_mbox, $forward, FT_PREFETCHTEXT | FT_UID) . @imap_body($this->_mbox, $forward, FT_PEEK | FT_UID);
+
+			// build a new mime message, forward entire old mail as file
+			list($aheader, $body) = $this->mail_attach("forwarded_message.eml",strlen($origmail),$origmail, $body, $forward_h_ct, $forward_h_cte);
+
+			// unset origmail - free memory
+			unset($origmail);
+
+			// add boundary headers
+			$headers .= "\n" . $aheader;
+		}
+
+		//advanced debugging
+		//debugLog("IMAP-SendMail: parsed message: ". print_r($message,1));
+		//debugLog("IMAP-SendMail: headers: $headers");
+		//debugLog("IMAP-SendMail: subject: {$message->headers["subject"]}");
+		//debugLog("IMAP-SendMail: body: $body");
+
+		$send =  @imap_mail ( $toaddr, $message->headers["subject"], $body, $headers, $ccaddr, $bccaddr);
+
+		// email sent?
+		if (!$send) {
+			debugLog("The email could not be sent. Last-IMAP-error: ". imap_last_error());
+		}
+
+		// add message to the sent folder
+		// build complete headers
+		$cheaders  = "To: " . $toaddr. "\n";
+		$cheaders .= "Subject: " . $message->headers["subject"] . "\n";
+		$cheaders .= "Cc: " . $ccaddr . "\n";
+		$cheaders .= $headers;
+
+		$asf = false;
+		if ($this->_sentID) {
+			$asf = $this->addSentMessage($this->_sentID, $cheaders, $body);
+		}
+		else if (IMAP_SENTFOLDER) {
+			$asf = $this->addSentMessage(IMAP_SENTFOLDER, $cheaders, $body);
+			debugLog("IMAP-SendMail: Outgoing mail saved in configured 'Sent' folder '".IMAP_SENTFOLDER."': ". (($asf)?"success":"failed"));
+		}
+		// No Sent folder set, try defaults
+		else {
+			debugLog("IMAP-SendMail: No Sent mailbox set");
+			if($this->addSentMessage("INBOX.Sent", $cheaders, $body)) {
+				debugLog("IMAP-SendMail: Outgoing mail saved in 'INBOX.Sent'");
+				$asf = true;
+			}
+			else if ($this->addSentMessage("Sent", $cheaders, $body)) {
+				debugLog("IMAP-SendMail: Outgoing mail saved in 'Sent'");
+				$asf = true;
+			}
+			else if ($this->addSentMessage("Sent Items", $cheaders, $body)) {
+				debugLog("IMAP-SendMail: Outgoing mail saved in 'Sent Items'");
+				$asf = true;
+			}
+		}
+
+		// unset mimedecoder - free memory
+		unset($mobj);
+		return ($send && $asf);
+	}
+
+	/* Should return a wastebasket folder if there is one. This is used when deleting
+	 * items; if this function returns a valid folder ID, then all deletes are handled
+	 * as moves and are sent to your backend as a move. If it returns FALSE, then deletes
+	 * are always handled as real deletes and will be sent to your importer as a DELETE
+	 */
+	function GetWasteBasket() {
+		return $this->_wasteID;
+	}
+
+	/* Should return a list (array) of messages, each entry being an associative array
+	 * with the same entries as StatMessage(). This function should return stable information; ie
+	 * if nothing has changed, the items in the array must be exactly the same. The order of
+	 * the items within the array is not important though.
+	 *
+	 * The cutoffdate is a date in the past, representing the date since which items should be shown.
+	 * This cutoffdate is determined by the user's setting of getting 'Last 3 days' of e-mail, etc. If
+	 * you ignore the cutoffdate, the user will not be able to select their own cutoffdate, but all
+	 * will work OK apart from that.
+	 */
+
+	function GetMessageList($folderid, $cutoffdate) {
+		debugLog("IMAP-GetMessageList: (fid: '$folderid'  cutdate: '$cutoffdate' )");
+
+		$messages = array();
+		$this->imap_reopenFolder($folderid, true);
+
+		$sequence = "1:*";
+		if ($cutoffdate > 0) {
+			$search = @imap_search($this->_mbox, "SINCE ". date("d-M-Y", $cutoffdate));
+			if ($search !== false)
+			$sequence = implode(",", $search);
+		}
+		$overviews = @imap_fetch_overview($this->_mbox, $sequence);
+
+		if (!$overviews) {
+			debugLog("IMAP-GetMessageList: Failed to retrieve overview");
+		} else {
+			foreach($overviews as $overview) {
+				$date = "";
+				$vars = get_object_vars($overview);
+				if (array_key_exists( "date", $vars)) {
+					// message is out of range for cutoffdate, ignore it
+					if(strtotime(preg_replace("/\(.*\)/", "", $overview->date)) < $cutoffdate) continue; // emerson-faria.nobre@serpro.gov.br - 07/feb/2011
+					//if(strtotime($overview->date) < $cutoffdate) continue;
+					$date = $overview->date;
+				}
+
+				// cut of deleted messages
+				if (array_key_exists( "deleted", $vars) && $overview->deleted)
+				continue;
+
+				if (array_key_exists( "uid", $vars)) {
+					$message = array();
+					$message["mod"] = $date;
+					$message["id"] = $overview->uid;
+					// 'seen' aka 'read' is the only flag we want to know about
+					$message["flags"] = 0;
+
+					if(array_key_exists( "seen", $vars) && $overview->seen)
+					$message["flags"] = 1;
+
+					array_push($messages, $message);
+				}
+			}
+		}
+		return $messages;
+	}
+
+	/* This function is analogous to GetMessageList.
+	 *
+	 */
+	function GetFolderList() {
+		$folders = array();
+
+		$list = @imap_getmailboxes($this->_mbox, $this->_server, "*");
+		if (is_array($list)) {
+			// reverse list to obtain folders in right order
+			$list = array_reverse($list);
+			foreach ($list as $val) {
+				$box = array();
+
+				// cut off serverstring
+				$box["id"] = imap_utf7_decode(substr($val->name, strlen($this->_server)));
+
+				// always use "." as folder delimiter
+				$box["id"] = imap_utf7_encode(str_replace($val->delimiter, ".", $box["id"]));
+
+				// explode hierarchies
+				$fhir = explode(".", $box["id"]);
+				if (count($fhir) > 1) {
+					$box["mod"] = imap_utf7_encode(array_pop($fhir)); // mod is last part of path
+					$box["parent"] = imap_utf7_encode(implode(".", $fhir)); // parent is all previous parts of path
+				}
+				else {
+					$box["mod"] = imap_utf7_encode($box["id"]);
+					$box["parent"] = "0";
+				}
+
+				$folders[]=$box;
+			}
+		}
+		else {
+			debugLog("GetFolderList: imap_list failed: " . imap_last_error());
+		}
+
+		return $folders;
+	}
+
+	/* GetFolder should return an actual SyncFolder object with all the properties set. Folders
+	 * are pretty simple really, having only a type, a name, a parent and a server ID.
+	 */
+
+	function GetFolder($id) {
+		$folder = new SyncFolder();
+		$folder->serverid = $id;
+
+		// explode hierarchy
+		$fhir = explode(".", $id);
+
+		// compare on lowercase strings
+		$lid = strtolower($id);
+
+		if($lid == "inbox") {
+			$folder->parentid = "0"; // Root
+			$folder->displayname = "Inbox";
+			$folder->type = SYNC_FOLDER_TYPE_INBOX;
+		}
+		// Zarafa IMAP-Gateway outputs
+		else if($lid == "drafts") {
+			$folder->parentid = "0";
+			$folder->displayname = "Drafts";
+			$folder->type = SYNC_FOLDER_TYPE_DRAFTS;
+		}
+		else if($lid == "trash") {
+			$folder->parentid = "0";
+			$folder->displayname = "Trash";
+			$folder->type = SYNC_FOLDER_TYPE_WASTEBASKET;
+			$this->_wasteID = $id;
+		}
+		else if($lid == "sent" || $lid == "sent items" || $lid == IMAP_SENTFOLDER) {
+			$folder->parentid = "0";
+			$folder->displayname = "Sent";
+			$folder->type = SYNC_FOLDER_TYPE_SENTMAIL;
+			$this->_sentID = $id;
+		}
+		// courier-imap outputs
+		else if($lid == "inbox.drafts") {
+			$folder->parentid = $fhir[0];
+			$folder->displayname = "Drafts";
+			$folder->type = SYNC_FOLDER_TYPE_DRAFTS;
+		}
+		else if($lid == "inbox.trash") {
+			$folder->parentid = $fhir[0];
+			$folder->displayname = "Trash";
+			$folder->type = SYNC_FOLDER_TYPE_WASTEBASKET;
+			$this->_wasteID = $id;
+		}
+		else if($lid == "inbox.sent") {
+			$folder->parentid = $fhir[0];
+			$folder->displayname = "Sent";
+			$folder->type = SYNC_FOLDER_TYPE_SENTMAIL;
+			$this->_sentID = $id;
+		}
+
+		// define the rest as other-folders
+		else {
+			if (count($fhir) > 1) {
+				$folder->displayname = windows1252_to_utf8(imap_utf7_decode(array_pop($fhir)));
+				$folder->parentid = implode(".", $fhir);
+			}
+			else {
+				$folder->displayname = windows1252_to_utf8(imap_utf7_decode($id));
+				$folder->parentid = "0";
+			}
+			$folder->type = SYNC_FOLDER_TYPE_OTHER;
+		}
+
+		//advanced debugging
+		//debugLog("IMAP-GetFolder(id: '$id') -> " . print_r($folder, 1));
+
+		return $folder;
+	}
+
+	/* Return folder stats. This means you must return an associative array with the
+	 * following properties:
+	 * "id" => The server ID that will be used to identify the folder. It must be unique, and not too long
+	 *         How long exactly is not known, but try keeping it under 20 chars or so. It must be a string.
+	 * "parent" => The server ID of the parent of the folder. Same restrictions as 'id' apply.
+	 * "mod" => This is the modification signature. It is any arbitrary string which is constant as long as
+	 *          the folder has not changed. In practice this means that 'mod' can be equal to the folder name
+	 *          as this is the only thing that ever changes in folders. (the type is normally constant)
+	 */
+	function StatFolder($id) {
+		$folder = $this->GetFolder($id);
+
+		$stat = array();
+		$stat["id"] = $id;
+		$stat["parent"] = $folder->parentid;
+		$stat["mod"] = $folder->displayname;
+
+		return $stat;
+	}
+
+	/* Creates or modifies a folder
+	 * "folderid" => id of the parent folder
+	 * "oldid" => if empty -> new folder created, else folder is to be renamed
+	 * "displayname" => new folder name (to be created, or to be renamed to)
+	 * "type" => folder type, ignored in IMAP
+	 *
+	 */
+	function ChangeFolder($folderid, $oldid, $displayname, $type){
+		debugLog("ChangeFolder: (parent: '$folderid'  oldid: '$oldid'  displayname: '$displayname'  type: '$type')");
+
+		// go to parent mailbox
+		$this->imap_reopenFolder($folderid);
+
+		// build name for new mailbox
+		$newname = $this->_server . str_replace(".", $this->_serverdelimiter, $folderid) . $this->_serverdelimiter . $displayname;
+
+		$csts = false;
+		// if $id is set => rename mailbox, otherwise create
+		if ($oldid) {
+			// rename doesn't work properly with IMAP
+			// the activesync client doesn't support a 'changing ID'
+			//$csts = imap_renamemailbox($this->_mbox, $this->_server . imap_utf7_encode(str_replace(".", $this->_serverdelimiter, $oldid)), $newname);
+		}
+		else {
+			$csts = @imap_createmailbox($this->_mbox, $newname);
+		}
+		if ($csts) {
+			return $this->StatFolder($folderid . "." . $displayname);
+		}
+		else
+		return false;
+	}
+
+	/* Should return attachment data for the specified attachment. The passed attachment identifier is
+	 * the exact string that is returned in the 'AttName' property of an SyncAttachment. So, you should
+	 * encode any information you need to find the attachment in that 'attname' property.
+	 */
+	function GetAttachmentData($attname) {
+		debugLog("getAttachmentDate: (attname: '$attname')");
+
+		list($folderid, $id, $part) = explode(":", $attname);
+
+		$this->imap_reopenFolder($folderid);
+		$mail = @imap_fetchheader($this->_mbox, $id, FT_PREFETCHTEXT | FT_UID) . @imap_body($this->_mbox, $id, FT_PEEK | FT_UID);
+
+		$mobj = new Mail_mimeDecode($mail);
+		$message = $mobj->decode(array('decode_headers' => true, 'decode_bodies' => true, 'include_bodies' => true, 'input' => $mail, 'crlf' => "\n", 'charset' => 'utf-8'));
+
+		if (isset($message->parts[$part]->body))
+		print $message->parts[$part]->body;
+
+		// unset mimedecoder & mail
+		unset($mobj);
+		unset($mail);
+		return true;
+	}
+
+	/* StatMessage should return message stats, analogous to the folder stats (StatFolder). Entries are:
+	 * 'id'     => Server unique identifier for the message. Again, try to keep this short (under 20 chars)
+	 * 'flags'     => simply '0' for unread, '1' for read
+	 * 'mod'    => modification signature. As soon as this signature changes, the item is assumed to be completely
+	 *             changed, and will be sent to the PDA as a whole. Normally you can use something like the modification
+	 *             time for this field, which will change as soon as the contents have changed.
+	 */
+
+	function StatMessage($folderid, $id) {
+		debugLog("IMAP-StatMessage: (fid: '$folderid'  id: '$id' )");
+
+		$this->imap_reopenFolder($folderid);
+		$overview = @imap_fetch_overview( $this->_mbox , $id , FT_UID);
+
+		if (!$overview) {
+			debugLog("IMAP-StatMessage: Failed to retrieve overview: ". imap_last_error());
+			return false;
+		}
+
+		else {
+			// check if variables for this overview object are available
+			$vars = get_object_vars($overview[0]);
+
+			// without uid it's not a valid message
+			if (! array_key_exists( "uid", $vars)) return false;
+
+
+			$entry = array();
+			$entry["mod"] = (array_key_exists( "date", $vars)) ? $overview[0]->date : "";
+			$entry["id"] = $overview[0]->uid;
+			// 'seen' aka 'read' is the only flag we want to know about
+			$entry["flags"] = 0;
+
+			if(array_key_exists( "seen", $vars) && $overview[0]->seen)
+			$entry["flags"] = 1;
+
+			//advanced debugging
+			//debugLog("IMAP-StatMessage-parsed: ". print_r($entry,1));
+
+			return $entry;
+		}
+	}
+
+	/* GetMessage should return the actual SyncXXX object type. You may or may not use the '$folderid' parent folder
+	 * identifier here.
+	 * Note that mixing item types is illegal and will be blocked by the engine; ie returning an Email object in a
+	 * Tasks folder will not do anything. The SyncXXX objects should be filled with as much information as possible,
+	 * but at least the subject, body, to, from, etc.
+	 */
+	function GetMessage($folderid, $id, $truncsize, $mimesupport = 0) {
+		debugLog("IMAP-GetMessage: (fid: '$folderid'  id: '$id'  truncsize: $truncsize)");
+
+		// Get flags, etc
+		$stat = $this->StatMessage($folderid, $id);
+
+		if ($stat) {
+			$this->imap_reopenFolder($folderid);
+			$mail = @imap_fetchheader($this->_mbox, $id, FT_PREFETCHTEXT | FT_UID) . @imap_body($this->_mbox, $id, FT_PEEK | FT_UID);
+
+			$mobj = new Mail_mimeDecode($mail);
+			$message = $mobj->decode(array('decode_headers' => true, 'decode_bodies' => true, 'include_bodies' => true, 'input' => $mail, 'crlf' => "\n", 'charset' => 'utf-8'));
+
+			$output = new SyncMail();
+
+			$body = $this->getBody($message);
+			// truncate body, if requested
+			if(strlen($body) > $truncsize) {
+				$body = utf8_truncate($body, $truncsize);
+				$output->bodytruncated = 1;
+			} else {
+				$body = $body;
+				$output->bodytruncated = 0;
+			}
+			$body = str_replace("\n","\r\n", str_replace("\r","",$body));
+
+			$output->bodysize = strlen($body);
+			$output->body = $body;
+			//$output->datereceived = isset($message->headers["date"]) ? strtotime($message->headers["date"]) : null;
+			$output->datereceived = isset($message->headers["date"]) ? strtotime(preg_replace("/\(.*\)/", "", $message->headers["date"])) : null; // emerson-faria.nobre@serpro.gov.br
+			$output->displayto = isset($message->headers["to"]) ? $message->headers["to"] : null;
+			$output->importance = isset($message->headers["x-priority"]) ? preg_replace("/\D+/", "", $message->headers["x-priority"]) : null;
+			$output->messageclass = "IPM.Note";
+			$output->subject = isset($message->headers["subject"]) ? $message->headers["subject"] : "";
+			$output->read = $stat["flags"];
+			$output->to = isset($message->headers["to"]) ? $message->headers["to"] : null;
+			$output->cc = isset($message->headers["cc"]) ? $message->headers["cc"] : null;
+			$output->from = isset($message->headers["from"]) ? $message->headers["from"] : null;
+			$output->reply_to = isset($message->headers["reply-to"]) ? $message->headers["reply-to"] : null;
+
+			// Attachments are only searched in the top-level part
+			$n = 0;
+			if(isset($message->parts)) {
+				foreach($message->parts as $part) {
+					if(isset($part->disposition) && ($part->disposition == "attachment" || $part->disposition == "inline")) {
+						$attachment = new SyncAttachment();
+
+						if (isset($part->body))
+						$attachment->attsize = strlen($part->body);
+
+						if(isset($part->d_parameters['filename']))
+						$attname = $part->d_parameters['filename'];
+						else if(isset($part->ctype_parameters['name']))
+						$attname = $part->ctype_parameters['name'];
+						else if(isset($part->headers['content-description']))
+						$attname = $part->headers['content-description'];
+						else $attname = "unknown attachment";
+
+						$attachment->displayname = $attname;
+						$attachment->attname = $folderid . ":" . $id . ":" . $n;
+						$attachment->attmethod = 1;
+						$attachment->attoid = isset($part->headers['content-id']) ? $part->headers['content-id'] : "";
+						array_push($output->attachments, $attachment);
+					}
+					$n++;
+				}
+			}
+			// unset mimedecoder & mail
+			unset($mobj);
+			unset($mail);
+			return $output;
+		}
+		return false;
+	}
+
+	/* This function is called when the user has requested to delete (really delete) a message. Usually
+	 * this means just unlinking the file its in or somesuch. After this call has succeeded, a call to
+	 * GetMessageList() should no longer list the message. If it does, the message will be re-sent to the PDA
+	 * as it will be seen as a 'new' item. This means that if you don't implement this function, you will
+	 * be able to delete messages on the PDA, but as soon as you sync, you'll get the item back
+	 */
+	function DeleteMessage($folderid, $id) {
+		debugLog("IMAP-DeleteMessage: (fid: '$folderid'  id: '$id' )");
+
+		$this->imap_reopenFolder($folderid);
+		$s1 = @imap_delete ($this->_mbox, $id, FT_UID);
+		$s11 = @imap_setflag_full($this->_mbox, $id, "\\Deleted", FT_UID);
+		$s2 = @imap_expunge($this->_mbox);
+
+		debugLog("IMAP-DeleteMessage: s-delete: $s1   s-expunge: $s2    setflag: $s11");
+
+		return ($s1 && $s2 && $s11);
+	}
+
+	/* This should change the 'read' flag of a message on disk. The $flags
+	 * parameter can only be '1' (read) or '0' (unread). After a call to
+	 * SetReadFlag(), GetMessageList() should return the message with the
+	 * new 'flags' but should not modify the 'mod' parameter. If you do
+	 * change 'mod', simply setting the message to 'read' on the PDA will trigger
+	 * a full resync of the item from the server
+	 */
+	function SetReadFlag($folderid, $id, $flags) {
+		debugLog("IMAP-SetReadFlag: (fid: '$folderid'  id: '$id'  flags: '$flags' )");
+
+		$this->imap_reopenFolder($folderid);
+
+		if ($flags == 0) {
+			// set as "Unseen" (unread)
+			$status = @imap_clearflag_full ( $this->_mbox, $id, "\\Seen", ST_UID);
+		} else {
+			// set as "Seen" (read)
+			$status = @imap_setflag_full($this->_mbox, $id, "\\Seen",ST_UID);
+		}
+
+		debugLog("IMAP-SetReadFlag -> set as " . (($flags) ? "read" : "unread") . "-->". $status);
+
+		return $status;
+	}
+
+	/* This function is called when a message has been changed on the PDA. You should parse the new
+	 * message here and save the changes to disk. The return value must be whatever would be returned
+	 * from StatMessage() after the message has been saved. This means that both the 'flags' and the 'mod'
+	 * properties of the StatMessage() item may change via ChangeMessage().
+	 * Note that this function will never be called on E-mail items as you can't change e-mail items, you
+	 * can only set them as 'read'.
+	 */
+	function ChangeMessage($folderid, $id, $message) {
+		return false;
+	}
+
+	/* This function is called when the user moves an item on the PDA. You should do whatever is needed
+	 * to move the message on disk. After this call, StatMessage() and GetMessageList() should show the items
+	 * to have a new parent. This means that it will disappear from GetMessageList() will not return the item
+	 * at all on the source folder, and the destination folder will show the new message
+	 *
+	 */
+	function MoveMessage($folderid, $id, $newfolderid) {
+		debugLog("IMAP-MoveMessage: (sfid: '$folderid'  id: '$id'  dfid: '$newfolderid' )");
+
+		$this->imap_reopenFolder($folderid);
+
+		// read message flags
+		$overview = @imap_fetch_overview ( $this->_mbox , $id, FT_UID);
+
+		if (!$overview) {
+			debugLog("IMAP-MoveMessage: Failed to retrieve overview");
+			return false;
+		}
+		else {
+			// move message
+			$s1 = imap_mail_move($this->_mbox, $id, str_replace(".", $this->_serverdelimiter, $newfolderid), FT_UID);
+
+			// delete message in from-folder
+			$s2 = imap_expunge($this->_mbox);
+
+			// open new folder
+			$this->imap_reopenFolder($newfolderid);
+
+			// remove all flags
+			$s3 = @imap_clearflag_full ($this->_mbox, $id, "\\Seen \\Answered \\Flagged \\Deleted \\Draft", FT_UID);
+			$newflags = "";
+			if ($overview[0]->seen) $newflags .= "\\Seen";
+			if ($overview[0]->flagged) $newflags .= " \\Flagged";
+			if ($overview[0]->answered) $newflags .= " \\Answered";
+			$s4 = @imap_setflag_full ($this->_mbox, $id, $newflags, FT_UID);
+
+			debugLog("MoveMessage: (" . $folderid . "->" . $newfolderid . ") s-move: $s1   s-expunge: $s2    unset-Flags: $s3    set-Flags: $s4");
+
+			return ($s1 && $s2 && $s3 && $s4);
+		}
+	}
+
+	// new ping mechanism for the IMAP-Backend
+	function AlterPing() {
+		return true;
+	}
+
+	// returns a changes array using imap_status
+	// if changes occurr default diff engine computes the actual changes
+	function AlterPingChanges($folderid, &$syncstate) {
+		debugLog("AlterPingChanges on $folderid stat: ". $syncstate);
+		$this->imap_reopenFolder($folderid);
+
+		// courier-imap only cleares the status cache after checking
+		@imap_check($this->_mbox);
+
+		$status = imap_status($this->_mbox, $this->_server . str_replace(".", $this->_serverdelimiter, $folderid), SA_ALL);
+		if (!$status) {
+			debugLog("AlterPingChanges: could not stat folder $folderid : ". imap_last_error());
+			return false;
+		}
+		else {
+			$newstate = "M:". $status->messages ."-R:". $status->recent ."-U:". $status->unseen;
+
+			// message number is different - change occured
+			if ($syncstate != $newstate) {
+				$syncstate = $newstate;
+				debugLog("AlterPingChanges: Change FOUND!");
+				// build a dummy change
+				return array(array("type" => "fakeChange"));
+			}
+		}
+
+		return array();
+	}
+
+	// ----------------------------------------
+	// imap-specific internals
+
+	/* Parse the message and return only the plaintext body
+	 */
+	function getBody($message) {
+		$body = "";
+		$htmlbody = "";
+
+		$this->getBodyRecursive($message, "plain", $body);
+
+		if(!isset($body) || $body === "") {
+			$this->getBodyRecursive($message, "html", $body);
+			// remove css-style tags
+			$body = preg_replace("/<style.*?<\/style>/is", "a", $body);
+			// remove all other html
+			//$body = strip_tags($body);
+
+			// Remove the HTML tags using the 'html2text' - emerson-faria.nobre@serpro.gov.br
+			// The 'html2text' (http://www.mbayer.de/html2text) must be installed in Z-Push server.
+				
+			// Advanced debug
+			// debugLog("IMAP-getBody: subject: " . $message->headers["subject"]);
+			$body = utf8_encode($body);	
+			libxml_use_internal_errors(true);
+			try {
+				$doc = new DOMDocument('1.0', 'UTF-8');
+				@$doc->loadHTML($body);
+				$tables = $doc->getElementsByTagName('table');
+				foreach ($tables as $table)
+				{
+					$tds = $table->getElementsByTagName('td');
+					foreach ($tds as $td)
+					{
+						foreach ($td->childNodes as $td_child) {
+							if ($td_child->nodeName == 'br') $td->removeChild($td_child);
+						}
+					}
+				}
+				$links = $doc->getElementsByTagName('a');
+				foreach ($links as $link)
+				{
+					if ($link->hasAttributes()){
+						$novoNo = $doc->createTextNode(' (' . $link->getAttribute('href') . ')');
+						$link->parentNode->insertBefore($novoNo, $link->nextSibling);
+					}
+				}
+				$body =  $doc->saveHTML();
+			} catch (Exception $e) {
+				debugLog("IMAP-getBody: Alert - DOMDocument cannot parse HTML.");
+			}
+			$filename = "./state/" . $this->_user . "-" . $this->_devid . ".html";
+			$fp = fopen($filename, 'w') or die("can't open file");
+			fwrite($fp, $body);
+			$body_aux = shell_exec('html2text -nobs -style compact "' . $filename . '"');
+			if (trim($body_aux) != '') $body = $body_aux;
+			unset($body_aux);
+			fclose($fp);
+			unlink($filename);
+			$body = utf8_decode($body);
+			$body = str_replace('_','',$body);
+			// End change block - Remove the HTML tags using the 'html2text' Linux application
+		}
+		return $body;
+	}
+
+	// Get all parts in the message with specified type and concatenate them together, unless the
+	// Content-Disposition is 'attachment', in which case the text is apparently an attachment
+	function getBodyRecursive($message, $subtype, &$body) {
+		if(!isset($message->ctype_primary)) return;
+		if(strcasecmp($message->ctype_primary,"text")==0 && strcasecmp($message->ctype_secondary,$subtype)==0 && isset($message->body))
+		$body .= $message->body;
+
+		if(strcasecmp($message->ctype_primary,"multipart")==0 && isset($message->parts) && is_array($message->parts)) {
+			foreach($message->parts as $part) {
+				if(!isset($part->disposition) || strcasecmp($part->disposition,"attachment"))  {
+					$this->getBodyRecursive($part, $subtype, $body);
+				}
+			}
+		}
+	}
+
+	// save the serverdelimiter for later folder (un)parsing
+	function getServerDelimiter() {
+		$list = @imap_getmailboxes($this->_mbox, $this->_server, "*");
+		if (is_array($list)) {
+			$val = $list[0];
+
+			return $val->delimiter;
+		}
+		return "."; // default "."
+	}
+
+	// speed things up
+	// remember what folder is currently open and only change if necessary
+	function imap_reopenFolder($folderid, $force = false) {
+		// to see changes, the folder has to be reopened!
+		if ($this->_mboxFolder != $folderid || $force) {
+			$s = @imap_reopen($this->_mbox, $this->_server . str_replace(".", $this->_serverdelimiter, $folderid));
+			if (!$s) debugLog("failed to change folder: ". implode(", ", imap_errors()));
+			$this->_mboxFolder = $folderid;
+		}
+	}
+
+
+	// build a multipart email, embedding body and one file (for attachments)
+	function mail_attach($filenm,$filesize,$file_cont,$body, $body_ct, $body_cte) {
+
+		$boundary = strtoupper(md5(uniqid(time())));
+
+		$mail_header = "Content-Type: multipart/mixed; boundary=$boundary\n";
+
+		// build main body with the sumitted type & encoding from the pda
+		$mail_body  = "This is a multi-part message in MIME format\n\n";
+		$mail_body .= "--$boundary\n";
+		$mail_body .= "Content-Type:$body_ct\n";
+		$mail_body .= "Content-Transfer-Encoding:$body_cte\n\n";
+		$mail_body .= "$body\n\n";
+
+		$mail_body .= "--$boundary\n";
+		$mail_body .= "Content-Type: text/plain; name=\"$filenm\"\n";
+		$mail_body .= "Content-Transfer-Encoding: base64\n";
+		$mail_body .= "Content-Disposition: attachment; filename=\"$filenm\"\n";
+		$mail_body .= "Content-Description: $filenm\n\n";
+		$mail_body .= base64_encode($file_cont) . "\n\n";
+
+		$mail_body .= "--$boundary--\n\n";
+
+		return array($mail_header, $mail_body);
+	}
+
+	// adds a message as seen to a specified folder (used for saving sent mails)
+	function addSentMessage($folderid, $header, $body) {
+		$header_body = str_replace("\n", "\r\n", str_replace("\r", "", $header . "\n\n" . $body));
+
+		return @imap_append($this->_mbox, $this->_server . $folderid, $header_body, "\\Seen");
+	}
+
+
+	// parses address objects back to a simple "," separated string
+	function parseAddr($ad) {
+		$addr_string = "";
+		if (isset($ad) && is_array($ad)) {
+			foreach($ad as $addr) {
+				if ($addr_string) $addr_string .= ",";
+				$addr_string .= $addr->mailbox . "@" . $addr->host;
+			}
+		}
+		return $addr_string;
+	}
+
+};
+
+?>
