-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-// +-----------------------------------------------------------------------+
-// | Copyright (c) 2002-2003 Richard Heyes |
-// | Copyright (c) 2003-2005 The PHP Group |
-// | All rights reserved. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | o Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | o Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution.|
-// | o The names of the authors may not be used to endorse or promote |
-// | products derived from this software without specific prior written |
-// | permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
-// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
-// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
-// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
-// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
-// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
-// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
-// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
-// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
-// | |
-// +-----------------------------------------------------------------------+
-// | Author: Richard Heyes <richard@phpguru.org> |
-// +-----------------------------------------------------------------------+
-
-require_once 'PEAR.php';
-
-/**
-* +----------------------------- IMPORTANT ------------------------------+
-* | Usage of this class compared to native php extensions such as |
-* | mailparse or imap, is slow and may be feature deficient. If available|
-* | you are STRONGLY recommended to use the php extensions. |
-* +----------------------------------------------------------------------+
-*
-* Mime Decoding class
-*
-* This class will parse a raw mime email and return
-* the structure. Returned structure is similar to
-* that returned by imap_fetchstructure().
-*
-* USAGE: (assume $input is your raw email)
-*
-* $decode = new Mail_mimeDecode($input, "\r\n");
-* $structure = $decode->decode();
-* print_r($structure);
-*
-* Or statically:
-*
-* $params['input'] = $input;
-* $structure = Mail_mimeDecode::decode($params);
-* print_r($structure);
-*
-* TODO:
-* o Implement multipart/appledouble
-* o UTF8: ???
-
- > 4. We have also found a solution for decoding the UTF-8
- > headers. Therefore I made the following function:
- >
- > function decode_utf8($txt) {
- > $trans=array("Å‘"=>"õ","ű"=>"û","Å\90"=>"Õ","Å°"
- =>"Û");
- > $txt=strtr($txt,$trans);
- > return(utf8_decode($txt));
- > }
- >
- > And I have inserted the following line to the class:
- >
- > if (strtolower($charset)=="utf-8") $text=decode_utf8($text);
- >
- > ... before the following one in the "_decodeHeader" function:
- >
- > $input = str_replace($encoded, $text, $input);
- >
- > This way from now on it can easily decode the UTF-8 headers too.
-
-*
-* @author Richard Heyes <richard@phpguru.org>
-* @version $Revision: 1.1 $
-* @package Mail
-*/
-class Mail_mimeDecode extends PEAR
-{
- /**
- * The raw email to decode
- * @var string
- */
- var $_input;
-
- /**
- * The header part of the input
- * @var string
- */
- var $_header;
-
- /**
- * The body part of the input
- * @var string
- */
- var $_body;
-
- /**
- * If an error occurs, this is used to store the message
- * @var string
- */
- var $_error;
-
- /**
- * Flag to determine whether to include bodies in the
- * returned object.
- * @var boolean
- */
- var $_include_bodies;
-
- /**
- * Flag to determine whether to decode bodies
- * @var boolean
- */
- var $_decode_bodies;
-
- /**
- * Flag to determine whether to decode headers
- * @var boolean
- */
- var $_decode_headers;
-
- /**
- * 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)
- {
- list($header, $body) = $this->_splitBodyHeader($input);
-
- $this->_input = $input;
- $this->_header = $header;
- $this->_body = $body;
- $this->_decode_bodies = false;
- $this->_include_bodies = true;
- }
-
- /**
- * 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
- * @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 PEAR::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;
-
- $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';
- $this->_include_bodies ? $return->body = ($this->_decode_bodies ? $this->_decodeBody($body, $encoding) : $body) : null;
- break;
-
- case 'text/html':
- $encoding = isset($content_transfer_encoding) ? $content_transfer_encoding['value'] : '7bit';
- $this->_include_bodies ? $return->body = ($this->_decode_bodies ? $this->_decodeBody($body, $encoding) : $body) : null;
- break;
-
- case 'multipart/parallel':
- 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':
- $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';
- $this->_include_bodies ? $return->body = ($this->_decode_bodies ? $this->_decodeBody($body, $content_transfer_encoding['value']) : $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 = '/([^;\'"]*[\'"]([^\'"]*([^\'"]*)*)[\'"][^;\'"]*|([^;]+))(;|$)/';
- 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 ($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, $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')
- {
- switch (strtolower($encoding)) {
- case '7bit':
- return $input;
- break;
-
- case 'quoted-printable':
- return $this->_quotedPrintableDecode($input);
- break;
-
- case 'base64':
- return 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) .
- '</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;
- }
-
-} // End of class
-?>
+<?php\r
+/**\r
+ * The Mail_mimeDecode class is used to decode mail/mime messages\r
+ *\r
+ * This class will parse a raw mime email and return\r
+ * the structure. Returned structure is similar to\r
+ * that returned by imap_fetchstructure().\r
+ *\r
+ * +----------------------------- IMPORTANT ------------------------------+\r
+ * | Usage of this class compared to native php extensions such as |\r
+ * | mailparse or imap, is slow and may be feature deficient. If available|\r
+ * | you are STRONGLY recommended to use the php extensions. |\r
+ * +----------------------------------------------------------------------+\r
+ *\r
+ * Compatible with PHP versions 4 and 5\r
+ *\r
+ * LICENSE: This LICENSE is in the BSD license style.\r
+ * Copyright (c) 2002-2003, Richard Heyes <richard@phpguru.org>\r
+ * Copyright (c) 2003-2006, PEAR <pear-group@php.net>\r
+ * All rights reserved.\r
+ *\r
+ * Redistribution and use in source and binary forms, with or\r
+ * without modification, are permitted provided that the following\r
+ * conditions are met:\r
+ *\r
+ * - Redistributions of source code must retain the above copyright\r
+ * notice, this list of conditions and the following disclaimer.\r
+ * - Redistributions in binary form must reproduce the above copyright\r
+ * notice, this list of conditions and the following disclaimer in the\r
+ * documentation and/or other materials provided with the distribution.\r
+ * - Neither the name of the authors, nor the names of its contributors \r
+ * may be used to endorse or promote products derived from this \r
+ * software without specific prior written permission.\r
+ *\r
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"\r
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\r
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\r
+ * THE POSSIBILITY OF SUCH DAMAGE.\r
+ *\r
+ * @category Mail\r
+ * @package Mail_Mime\r
+ * @author Richard Heyes <richard@phpguru.org>\r
+ * @author George Schlossnagle <george@omniti.com>\r
+ * @author Cipriano Groenendal <cipri@php.net>\r
+ * @author Sean Coates <sean@php.net>\r
+ * @copyright 2003-2006 PEAR <pear-group@php.net>\r
+ * @license http://www.opensource.org/licenses/bsd-license.php BSD License\r
+ * @version CVS: $Id: mimeDecode.php,v 1.8 2008/07/19 17:46:36 hsur Exp $\r
+ * @link http://pear.php.net/package/Mail_mime\r
+ */\r
+\r
+\r
+/**\r
+ * require PEAR\r
+ *\r
+ * This package depends on PEAR to raise errors.\r
+ */\r
+require_once 'PEAR.php';\r
+\r
+\r
+/**\r
+ * The Mail_mimeDecode class is used to decode mail/mime messages\r
+ *\r
+ * This class will parse a raw mime email and return the structure.\r
+ * Returned structure is similar to that returned by imap_fetchstructure().\r
+ *\r
+ * +----------------------------- IMPORTANT ------------------------------+\r
+ * | Usage of this class compared to native php extensions such as |\r
+ * | mailparse or imap, is slow and may be feature deficient. If available|\r
+ * | you are STRONGLY recommended to use the php extensions. |\r
+ * +----------------------------------------------------------------------+\r
+ *\r
+ * @category Mail\r
+ * @package Mail_Mime\r
+ * @author Richard Heyes <richard@phpguru.org>\r
+ * @author George Schlossnagle <george@omniti.com>\r
+ * @author Cipriano Groenendal <cipri@php.net>\r
+ * @author Sean Coates <sean@php.net>\r
+ * @copyright 2003-2006 PEAR <pear-group@php.net>\r
+ * @license http://www.opensource.org/licenses/bsd-license.php BSD License\r
+ * @version Release: @package_version@\r
+ * @link http://pear.php.net/package/Mail_mime\r
+ */\r
+class Mail_mimeDecode extends PEAR\r
+{\r
+ /**\r
+ * The raw email to decode\r
+ *\r
+ * @var string\r
+ * @access private\r
+ */\r
+ var $_input;\r
+\r
+ /**\r
+ * The header part of the input\r
+ *\r
+ * @var string\r
+ * @access private\r
+ */\r
+ var $_header;\r
+\r
+ /**\r
+ * The body part of the input\r
+ *\r
+ * @var string\r
+ * @access private\r
+ */\r
+ var $_body;\r
+\r
+ /**\r
+ * If an error occurs, this is used to store the message\r
+ *\r
+ * @var string\r
+ * @access private\r
+ */\r
+ var $_error;\r
+\r
+ /**\r
+ * Flag to determine whether to include bodies in the\r
+ * returned object.\r
+ *\r
+ * @var boolean\r
+ * @access private\r
+ */\r
+ var $_include_bodies;\r
+\r
+ /**\r
+ * Flag to determine whether to decode bodies\r
+ *\r
+ * @var boolean\r
+ * @access private\r
+ */\r
+ var $_decode_bodies;\r
+\r
+ /**\r
+ * Flag to determine whether to decode headers\r
+ *\r
+ * @var boolean\r
+ * @access private\r
+ */\r
+ var $_decode_headers;\r
+\r
+ /**\r
+ * Constructor.\r
+ *\r
+ * Sets up the object, initialise the variables, and splits and\r
+ * stores the header and body of the input.\r
+ *\r
+ * @param string The input to decode\r
+ * @access public\r
+ */\r
+ function Mail_mimeDecode($input)\r
+ {\r
+ list($header, $body) = $this->_splitBodyHeader($input);\r
+\r
+ $this->_input = $input;\r
+ $this->_header = $header;\r
+ $this->_body = $body;\r
+ $this->_decode_bodies = false;\r
+ $this->_include_bodies = true;\r
+ }\r
+\r
+ /**\r
+ * Begins the decoding process. If called statically\r
+ * it will create an object and call the decode() method\r
+ * of it.\r
+ *\r
+ * @param array An array of various parameters that determine\r
+ * various things:\r
+ * include_bodies - Whether to include the body in the returned\r
+ * object.\r
+ * decode_bodies - Whether to decode the bodies\r
+ * of the parts. (Transfer encoding)\r
+ * decode_headers - Whether to decode headers\r
+ * input - If called statically, this will be treated\r
+ * as the input\r
+ * @return object Decoded results\r
+ * @access public\r
+ */\r
+ function decode($params = null)\r
+ {\r
+ // determine if this method has been called statically\r
+ $isStatic = !(isset($this) && get_class($this) == __CLASS__);\r
+\r
+ // Have we been called statically?\r
+ // If so, create an object and pass details to that.\r
+ if ($isStatic AND isset($params['input'])) {\r
+\r
+ $obj = new Mail_mimeDecode($params['input']);\r
+ $structure = $obj->decode($params);\r
+\r
+ // Called statically but no input\r
+ } elseif ($isStatic) {\r
+ return PEAR::raiseError('Called statically and no input given');\r
+\r
+ // Called via an object\r
+ } else {\r
+ $this->_include_bodies = isset($params['include_bodies']) ?\r
+ $params['include_bodies'] : false;\r
+ $this->_decode_bodies = isset($params['decode_bodies']) ?\r
+ $params['decode_bodies'] : false;\r
+ $this->_decode_headers = isset($params['decode_headers']) ?\r
+ $params['decode_headers'] : false;\r
+\r
+ $structure = $this->_decode($this->_header, $this->_body);\r
+ if ($structure === false) {\r
+ $structure = $this->raiseError($this->_error);\r
+ }\r
+ }\r
+\r
+ return $structure;\r
+ }\r
+\r
+ /**\r
+ * Performs the decoding. Decodes the body string passed to it\r
+ * If it finds certain content-types it will call itself in a\r
+ * recursive fashion\r
+ *\r
+ * @param string Header section\r
+ * @param string Body section\r
+ * @return object Results of decoding process\r
+ * @access private\r
+ */\r
+ function _decode($headers, $body, $default_ctype = 'text/plain')\r
+ {\r
+ $return = new stdClass;\r
+ $return->headers = array();\r
+ $headers = $this->_parseHeaders($headers);\r
+\r
+ foreach ($headers as $value) {\r
+ if (isset($return->headers[strtolower($value['name'])]) AND !is_array($return->headers[strtolower($value['name'])])) {\r
+ $return->headers[strtolower($value['name'])] = array($return->headers[strtolower($value['name'])]);\r
+ $return->headers[strtolower($value['name'])][] = $value['value'];\r
+\r
+ } elseif (isset($return->headers[strtolower($value['name'])])) {\r
+ $return->headers[strtolower($value['name'])][] = $value['value'];\r
+\r
+ } else {\r
+ $return->headers[strtolower($value['name'])] = $value['value'];\r
+ }\r
+ }\r
+\r
+ reset($headers);\r
+ while (list($key, $value) = each($headers)) {\r
+ $headers[$key]['name'] = strtolower($headers[$key]['name']);\r
+ switch ($headers[$key]['name']) {\r
+\r
+ case 'content-type':\r
+ $content_type = $this->_parseHeaderValue($headers[$key]['value']);\r
+\r
+ if (preg_match('/([0-9a-z+.-]+)\/([0-9a-z+.-]+)/i', $content_type['value'], $regs)) {\r
+ $return->ctype_primary = $regs[1];\r
+ $return->ctype_secondary = $regs[2];\r
+ }\r
+\r
+ if (isset($content_type['other'])) {\r
+ while (list($p_name, $p_value) = each($content_type['other'])) {\r
+ $return->ctype_parameters[$p_name] = $p_value;\r
+ }\r
+ }\r
+ break;\r
+\r
+ case 'content-disposition':\r
+ $content_disposition = $this->_parseHeaderValue($headers[$key]['value']);\r
+ $return->disposition = $content_disposition['value'];\r
+ if (isset($content_disposition['other'])) {\r
+ while (list($p_name, $p_value) = each($content_disposition['other'])) {\r
+ $return->d_parameters[$p_name] = $p_value;\r
+ }\r
+ }\r
+ break;\r
+\r
+ case 'content-transfer-encoding':\r
+ $content_transfer_encoding = $this->_parseHeaderValue($headers[$key]['value']);\r
+ break;\r
+ }\r
+ }\r
+\r
+ if (isset($content_type)) {\r
+ switch (strtolower($content_type['value'])) {\r
+ case 'text/plain':\r
+ $encoding = isset($content_transfer_encoding) ? $content_transfer_encoding['value'] : '7bit';\r
+ $this->_include_bodies ? $return->body = ($this->_decode_bodies ? $this->_decodeBody($body, $encoding) : $body) : null;\r
+ break;\r
+\r
+ case 'text/html':\r
+ $encoding = isset($content_transfer_encoding) ? $content_transfer_encoding['value'] : '7bit';\r
+ $this->_include_bodies ? $return->body = ($this->_decode_bodies ? $this->_decodeBody($body, $encoding) : $body) : null;\r
+ break;\r
+\r
+ case 'multipart/parallel':\r
+ case 'multipart/appledouble': // Appledouble mail\r
+ case 'multipart/report': // RFC1892\r
+ case 'multipart/signed': // PGP\r
+ case 'multipart/digest':\r
+ case 'multipart/alternative':\r
+ case 'multipart/related':\r
+ case 'multipart/mixed':\r
+ if(!isset($content_type['other']['boundary'])){\r
+ $this->_error = 'No boundary found for ' . $content_type['value'] . ' part';\r
+ return false;\r
+ }\r
+\r
+ $default_ctype = (strtolower($content_type['value']) === 'multipart/digest') ? 'message/rfc822' : 'text/plain';\r
+\r
+ $parts = $this->_boundarySplit($body, $content_type['other']['boundary']);\r
+ for ($i = 0; $i < count($parts); $i++) {\r
+ list($part_header, $part_body) = $this->_splitBodyHeader($parts[$i]);\r
+ $part = $this->_decode($part_header, $part_body, $default_ctype);\r
+ if($part === false)\r
+ $part = $this->raiseError($this->_error);\r
+ $return->parts[] = $part;\r
+ }\r
+ break;\r
+\r
+ case 'message/rfc822':\r
+ $obj = &new Mail_mimeDecode($body);\r
+ $return->parts[] = $obj->decode(array('include_bodies' => $this->_include_bodies,\r
+ 'decode_bodies' => $this->_decode_bodies,\r
+ 'decode_headers' => $this->_decode_headers));\r
+ unset($obj);\r
+ break;\r
+\r
+ default:\r
+ if(!isset($content_transfer_encoding['value']))\r
+ $content_transfer_encoding['value'] = '7bit';\r
+ $this->_include_bodies ? $return->body = ($this->_decode_bodies ? $this->_decodeBody($body, $content_transfer_encoding['value']) : $body) : null;\r
+ break;\r
+ }\r
+\r
+ } else {\r
+ $ctype = explode('/', $default_ctype);\r
+ $return->ctype_primary = $ctype[0];\r
+ $return->ctype_secondary = $ctype[1];\r
+ $this->_include_bodies ? $return->body = ($this->_decode_bodies ? $this->_decodeBody($body) : $body) : null;\r
+ }\r
+\r
+ return $return;\r
+ }\r
+\r
+ /**\r
+ * Given the output of the above function, this will return an\r
+ * array of references to the parts, indexed by mime number.\r
+ *\r
+ * @param object $structure The structure to go through\r
+ * @param string $mime_number Internal use only.\r
+ * @return array Mime numbers\r
+ */\r
+ function &getMimeNumbers(&$structure, $no_refs = false, $mime_number = '', $prepend = '')\r
+ {\r
+ $return = array();\r
+ if (!empty($structure->parts)) {\r
+ if ($mime_number != '') {\r
+ $structure->mime_id = $prepend . $mime_number;\r
+ $return[$prepend . $mime_number] = &$structure;\r
+ }\r
+ for ($i = 0; $i < count($structure->parts); $i++) {\r
+\r
+ \r
+ if (!empty($structure->headers['content-type']) AND substr(strtolower($structure->headers['content-type']), 0, 8) == 'message/') {\r
+ $prepend = $prepend . $mime_number . '.';\r
+ $_mime_number = '';\r
+ } else {\r
+ $_mime_number = ($mime_number == '' ? $i + 1 : sprintf('%s.%s', $mime_number, $i + 1));\r
+ }\r
+\r
+ $arr = &Mail_mimeDecode::getMimeNumbers($structure->parts[$i], $no_refs, $_mime_number, $prepend);\r
+ foreach ($arr as $key => $val) {\r
+ $no_refs ? $return[$key] = '' : $return[$key] = &$arr[$key];\r
+ }\r
+ }\r
+ } else {\r
+ if ($mime_number == '') {\r
+ $mime_number = '1';\r
+ }\r
+ $structure->mime_id = $prepend . $mime_number;\r
+ $no_refs ? $return[$prepend . $mime_number] = '' : $return[$prepend . $mime_number] = &$structure;\r
+ }\r
+ \r
+ return $return;\r
+ }\r
+\r
+ /**\r
+ * Given a string containing a header and body\r
+ * section, this function will split them (at the first\r
+ * blank line) and return them.\r
+ *\r
+ * @param string Input to split apart\r
+ * @return array Contains header and body section\r
+ * @access private\r
+ */\r
+ function _splitBodyHeader($input)\r
+ {\r
+ if (preg_match("/^(.*?)\r?\n\r?\n(.*)/s", $input, $match)) {\r
+ return array($match[1], $match[2]);\r
+ }\r
+ $this->_error = 'Could not split header and body';\r
+ return false;\r
+ }\r
+\r
+ /**\r
+ * Parse headers given in $input and return\r
+ * as assoc array.\r
+ *\r
+ * @param string Headers to parse\r
+ * @return array Contains parsed headers\r
+ * @access private\r
+ */\r
+ function _parseHeaders($input)\r
+ {\r
+\r
+ if ($input !== '') {\r
+ // Unfold the input\r
+ $input = preg_replace("/\r?\n/", "\r\n", $input);\r
+ $input = preg_replace("/\r\n(\t| )+/", ' ', $input);\r
+ $headers = explode("\r\n", trim($input));\r
+\r
+ foreach ($headers as $value) {\r
+ $hdr_name = substr($value, 0, $pos = strpos($value, ':'));\r
+ $hdr_value = substr($value, $pos+1);\r
+ if($hdr_value[0] == ' ')\r
+ $hdr_value = substr($hdr_value, 1);\r
+\r
+ $return[] = array(\r
+ 'name' => $hdr_name,\r
+ 'value' => $this->_decode_headers ? $this->_decodeHeader($hdr_value) : $hdr_value\r
+ );\r
+ }\r
+ } else {\r
+ $return = array();\r
+ }\r
+\r
+ return $return;\r
+ }\r
+\r
+ /**\r
+ * Function to parse a header value,\r
+ * extract first part, and any secondary\r
+ * parts (after ;) This function is not as\r
+ * robust as it could be. Eg. header comments\r
+ * in the wrong place will probably break it.\r
+ *\r
+ * @param string Header value to parse\r
+ * @return array Contains parsed result\r
+ * @access private\r
+ */\r
+ function _parseHeaderValue($input)\r
+ {\r
+\r
+ if (($pos = strpos($input, ';')) !== false) {\r
+\r
+ $return['value'] = trim(substr($input, 0, $pos));\r
+ $input = trim(substr($input, $pos+1));\r
+\r
+ if (strlen($input) > 0) {\r
+\r
+ // This splits on a semi-colon, if there's no preceeding backslash\r
+ // Now works with quoted values; had to glue the \; breaks in PHP\r
+ // the regex is already bordering on incomprehensible\r
+ $splitRegex = '/([^;\'"]*[\'"]([^\'"]*([^\'"]*)*)[\'"][^;\'"]*|([^;]+))(;|$)/';\r
+ preg_match_all($splitRegex, $input, $matches);\r
+ $parameters = array();\r
+ for ($i=0; $i<count($matches[0]); $i++) {\r
+ $param = $matches[0][$i];\r
+ while (substr($param, -2) == '\;') {\r
+ $param .= $matches[0][++$i];\r
+ }\r
+ $parameters[] = $param;\r
+ }\r
+\r
+ for ($i = 0; $i < count($parameters); $i++) {\r
+ $param_name = trim(substr($parameters[$i], 0, $pos = strpos($parameters[$i], '=')), "'\";\t\\ ");\r
+ $param_value = trim(str_replace('\;', ';', substr($parameters[$i], $pos + 1)), "'\";\t\\ ");\r
+ if ($param_value[0] == '"') {\r
+ $param_value = substr($param_value, 1, -1);\r
+ }\r
+ $return['other'][$param_name] = $param_value;\r
+ $return['other'][strtolower($param_name)] = $param_value;\r
+ }\r
+ }\r
+ } else {\r
+ $return['value'] = trim($input);\r
+ }\r
+\r
+ return $return;\r
+ }\r
+\r
+ /**\r
+ * This function splits the input based\r
+ * on the given boundary\r
+ *\r
+ * @param string Input to parse\r
+ * @return array Contains array of resulting mime parts\r
+ * @access private\r
+ */\r
+ function _boundarySplit($input, $boundary)\r
+ {\r
+ $parts = array();\r
+\r
+ $bs_possible = substr($boundary, 2, -2);\r
+ $bs_check = '\"' . $bs_possible . '\"';\r
+\r
+ if ($boundary == $bs_check) {\r
+ $boundary = $bs_possible;\r
+ }\r
+\r
+ $tmp = explode('--' . $boundary, $input);\r
+\r
+ for ($i = 1; $i < count($tmp) - 1; $i++) {\r
+ $parts[] = $tmp[$i];\r
+ }\r
+\r
+ return $parts;\r
+ }\r
+\r
+ /**\r
+ * Given a header, this function will decode it\r
+ * according to RFC2047. Probably not *exactly*\r
+ * conformant, but it does pass all the given\r
+ * examples (in RFC2047).\r
+ *\r
+ * @param string Input header value to decode\r
+ * @return string Decoded header value\r
+ * @access private\r
+ */\r
+ function _decodeHeader($input)\r
+ {\r
+ // Remove white space between encoded-words\r
+ $input = preg_replace('/(=\?[^?]+\?(q|b)\?[^?]*\?=)(\s)+=\?/i', '\1=?', $input);\r
+\r
+ // For each encoded-word...\r
+ while (preg_match('/(=\?([^?]+)\?(q|b)\?([^?]*)\?=)/i', $input, $matches)) {\r
+\r
+ $encoded = $matches[1];\r
+ $charset = $matches[2];\r
+ $encoding = $matches[3];\r
+ $text = $matches[4];\r
+\r
+ switch (strtolower($encoding)) {\r
+ case 'b':\r
+ $text = base64_decode($text);\r
+ break;\r
+\r
+ case 'q':\r
+ $text = str_replace('_', ' ', $text);\r
+ preg_match_all('/=([a-f0-9]{2})/i', $text, $matches);\r
+ foreach($matches[1] as $value)\r
+ $text = str_replace('='.$value, chr(hexdec($value)), $text);\r
+ break;\r
+ }\r
+\r
+ $input = str_replace($encoded, $text, $input);\r
+ }\r
+\r
+ return $input;\r
+ }\r
+\r
+ /**\r
+ * Given a body string and an encoding type,\r
+ * this function will decode and return it.\r
+ *\r
+ * @param string Input body to decode\r
+ * @param string Encoding type to use.\r
+ * @return string Decoded body\r
+ * @access private\r
+ */\r
+ function _decodeBody($input, $encoding = '7bit')\r
+ {\r
+ switch (strtolower($encoding)) {\r
+ case '7bit':\r
+ return $input;\r
+ break;\r
+\r
+ case 'quoted-printable':\r
+ return $this->_quotedPrintableDecode($input);\r
+ break;\r
+\r
+ case 'base64':\r
+ return base64_decode($input);\r
+ break;\r
+\r
+ default:\r
+ return $input;\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Given a quoted-printable string, this\r
+ * function will decode and return it.\r
+ *\r
+ * @param string Input body to decode\r
+ * @return string Decoded body\r
+ * @access private\r
+ */\r
+ function _quotedPrintableDecode($input)\r
+ {\r
+ // Remove soft line breaks\r
+ $input = preg_replace("/=\r?\n/", '', $input);\r
+\r
+ // Replace encoded characters\r
+ $input = preg_replace('/=([a-f0-9]{2})/ie', "chr(hexdec('\\1'))", $input);\r
+\r
+ return $input;\r
+ }\r
+\r
+ /**\r
+ * Checks the input for uuencoded files and returns\r
+ * an array of them. Can be called statically, eg:\r
+ *\r
+ * $files =& Mail_mimeDecode::uudecode($some_text);\r
+ *\r
+ * It will check for the begin 666 ... end syntax\r
+ * however and won't just blindly decode whatever you\r
+ * pass it.\r
+ *\r
+ * @param string Input body to look for attahcments in\r
+ * @return array Decoded bodies, filenames and permissions\r
+ * @access public\r
+ * @author Unknown\r
+ */\r
+ function &uudecode($input)\r
+ {\r
+ // Find all uuencoded sections\r
+ preg_match_all("/begin ([0-7]{3}) (.+)\r?\n(.+)\r?\nend/Us", $input, $matches);\r
+\r
+ for ($j = 0; $j < count($matches[3]); $j++) {\r
+\r
+ $str = $matches[3][$j];\r
+ $filename = $matches[2][$j];\r
+ $fileperm = $matches[1][$j];\r
+\r
+ $file = '';\r
+ $str = preg_split("/\r?\n/", trim($str));\r
+ $strlen = count($str);\r
+\r
+ for ($i = 0; $i < $strlen; $i++) {\r
+ $pos = 1;\r
+ $d = 0;\r
+ $len=(int)(((ord(substr($str[$i],0,1)) -32) - ' ') & 077);\r
+\r
+ while (($d + 3 <= $len) AND ($pos + 4 <= strlen($str[$i]))) {\r
+ $c0 = (ord(substr($str[$i],$pos,1)) ^ 0x20);\r
+ $c1 = (ord(substr($str[$i],$pos+1,1)) ^ 0x20);\r
+ $c2 = (ord(substr($str[$i],$pos+2,1)) ^ 0x20);\r
+ $c3 = (ord(substr($str[$i],$pos+3,1)) ^ 0x20);\r
+ $file .= chr(((($c0 - ' ') & 077) << 2) | ((($c1 - ' ') & 077) >> 4));\r
+\r
+ $file .= chr(((($c1 - ' ') & 077) << 4) | ((($c2 - ' ') & 077) >> 2));\r
+\r
+ $file .= chr(((($c2 - ' ') & 077) << 6) | (($c3 - ' ') & 077));\r
+\r
+ $pos += 4;\r
+ $d += 3;\r
+ }\r
+\r
+ if (($d + 2 <= $len) && ($pos + 3 <= strlen($str[$i]))) {\r
+ $c0 = (ord(substr($str[$i],$pos,1)) ^ 0x20);\r
+ $c1 = (ord(substr($str[$i],$pos+1,1)) ^ 0x20);\r
+ $c2 = (ord(substr($str[$i],$pos+2,1)) ^ 0x20);\r
+ $file .= chr(((($c0 - ' ') & 077) << 2) | ((($c1 - ' ') & 077) >> 4));\r
+\r
+ $file .= chr(((($c1 - ' ') & 077) << 4) | ((($c2 - ' ') & 077) >> 2));\r
+\r
+ $pos += 3;\r
+ $d += 2;\r
+ }\r
+\r
+ if (($d + 1 <= $len) && ($pos + 2 <= strlen($str[$i]))) {\r
+ $c0 = (ord(substr($str[$i],$pos,1)) ^ 0x20);\r
+ $c1 = (ord(substr($str[$i],$pos+1,1)) ^ 0x20);\r
+ $file .= chr(((($c0 - ' ') & 077) << 2) | ((($c1 - ' ') & 077) >> 4));\r
+\r
+ }\r
+ }\r
+ $files[] = array('filename' => $filename, 'fileperm' => $fileperm, 'filedata' => $file);\r
+ }\r
+\r
+ return $files;\r
+ }\r
+\r
+ /**\r
+ * getSendArray() returns the arguments required for Mail::send()\r
+ * used to build the arguments for a mail::send() call \r
+ *\r
+ * Usage:\r
+ * $mailtext = Full email (for example generated by a template)\r
+ * $decoder = new Mail_mimeDecode($mailtext);\r
+ * $parts = $decoder->getSendArray();\r
+ * if (!PEAR::isError($parts) {\r
+ * list($recipents,$headers,$body) = $parts;\r
+ * $mail = Mail::factory('smtp');\r
+ * $mail->send($recipents,$headers,$body);\r
+ * } else {\r
+ * echo $parts->message;\r
+ * }\r
+ * @return mixed array of recipeint, headers,body or Pear_Error\r
+ * @access public\r
+ * @author Alan Knowles <alan@akbkhome.com>\r
+ */\r
+ function getSendArray()\r
+ {\r
+ // prevent warning if this is not set\r
+ $this->_decode_headers = FALSE;\r
+ $headerlist =$this->_parseHeaders($this->_header);\r
+ $to = "";\r
+ if (!$headerlist) {\r
+ return $this->raiseError("Message did not contain headers");\r
+ }\r
+ foreach($headerlist as $item) {\r
+ $header[$item['name']] = $item['value'];\r
+ switch (strtolower($item['name'])) {\r
+ case "to":\r
+ case "cc":\r
+ case "bcc":\r
+ $to = ",".$item['value'];\r
+ default:\r
+ break;\r
+ }\r
+ }\r
+ if ($to == "") {\r
+ return $this->raiseError("Message did not contain any recipents");\r
+ }\r
+ $to = substr($to,1);\r
+ return array($to,$header,$this->_body);\r
+ } \r
+\r
+ /**\r
+ * Returns a xml copy of the output of\r
+ * Mail_mimeDecode::decode. Pass the output in as the\r
+ * argument. This function can be called statically. Eg:\r
+ *\r
+ * $output = $obj->decode();\r
+ * $xml = Mail_mimeDecode::getXML($output);\r
+ *\r
+ * The DTD used for this should have been in the package. Or\r
+ * alternatively you can get it from cvs, or here:\r
+ * http://www.phpguru.org/xmail/xmail.dtd.\r
+ *\r
+ * @param object Input to convert to xml. This should be the\r
+ * output of the Mail_mimeDecode::decode function\r
+ * @return string XML version of input\r
+ * @access public\r
+ */\r
+ function getXML($input)\r
+ {\r
+ $crlf = "\r\n";\r
+ $output = '<?xml version=\'1.0\'?>' . $crlf .\r
+ '<!DOCTYPE email SYSTEM "http://www.phpguru.org/xmail/xmail.dtd">' . $crlf .\r
+ '<email>' . $crlf .\r
+ Mail_mimeDecode::_getXML($input) .\r
+ '</email>';\r
+\r
+ return $output;\r
+ }\r
+\r
+ /**\r
+ * Function that does the actual conversion to xml. Does a single\r
+ * mimepart at a time.\r
+ *\r
+ * @param object Input to convert to xml. This is a mimepart object.\r
+ * It may or may not contain subparts.\r
+ * @param integer Number of tabs to indent\r
+ * @return string XML version of input\r
+ * @access private\r
+ */\r
+ function _getXML($input, $indent = 1)\r
+ {\r
+ $htab = "\t";\r
+ $crlf = "\r\n";\r
+ $output = '';\r
+ $headers = @(array)$input->headers;\r
+\r
+ foreach ($headers as $hdr_name => $hdr_value) {\r
+\r
+ // Multiple headers with this name\r
+ if (is_array($headers[$hdr_name])) {\r
+ for ($i = 0; $i < count($hdr_value); $i++) {\r
+ $output .= Mail_mimeDecode::_getXML_helper($hdr_name, $hdr_value[$i], $indent);\r
+ }\r
+\r
+ // Only one header of this sort\r
+ } else {\r
+ $output .= Mail_mimeDecode::_getXML_helper($hdr_name, $hdr_value, $indent);\r
+ }\r
+ }\r
+\r
+ if (!empty($input->parts)) {\r
+ for ($i = 0; $i < count($input->parts); $i++) {\r
+ $output .= $crlf . str_repeat($htab, $indent) . '<mimepart>' . $crlf .\r
+ Mail_mimeDecode::_getXML($input->parts[$i], $indent+1) .\r
+ str_repeat($htab, $indent) . '</mimepart>' . $crlf;\r
+ }\r
+ } elseif (isset($input->body)) {\r
+ $output .= $crlf . str_repeat($htab, $indent) . '<body><![CDATA[' .\r
+ $input->body . ']]></body>' . $crlf;\r
+ }\r
+\r
+ return $output;\r
+ }\r
+\r
+ /**\r
+ * Helper function to _getXML(). Returns xml of a header.\r
+ *\r
+ * @param string Name of header\r
+ * @param string Value of header\r
+ * @param integer Number of tabs to indent\r
+ * @return string XML version of input\r
+ * @access private\r
+ */\r
+ function _getXML_helper($hdr_name, $hdr_value, $indent)\r
+ {\r
+ $htab = "\t";\r
+ $crlf = "\r\n";\r
+ $return = '';\r
+\r
+ $new_hdr_value = ($hdr_name != 'received') ? Mail_mimeDecode::_parseHeaderValue($hdr_value) : array('value' => $hdr_value);\r
+ $new_hdr_name = str_replace(' ', '-', ucwords(str_replace('-', ' ', $hdr_name)));\r
+\r
+ // Sort out any parameters\r
+ if (!empty($new_hdr_value['other'])) {\r
+ foreach ($new_hdr_value['other'] as $paramname => $paramvalue) {\r
+ $params[] = str_repeat($htab, $indent) . $htab . '<parameter>' . $crlf .\r
+ str_repeat($htab, $indent) . $htab . $htab . '<paramname>' . htmlspecialchars($paramname) . '</paramname>' . $crlf .\r
+ str_repeat($htab, $indent) . $htab . $htab . '<paramvalue>' . htmlspecialchars($paramvalue) . '</paramvalue>' . $crlf .\r
+ str_repeat($htab, $indent) . $htab . '</parameter>' . $crlf;\r
+ }\r
+\r
+ $params = implode('', $params);\r
+ } else {\r
+ $params = '';\r
+ }\r
+\r
+ $return = str_repeat($htab, $indent) . '<header>' . $crlf .\r
+ str_repeat($htab, $indent) . $htab . '<headername>' . htmlspecialchars($new_hdr_name) . '</headername>' . $crlf .\r
+ str_repeat($htab, $indent) . $htab . '<headervalue>' . htmlspecialchars($new_hdr_value['value']) . '</headervalue>' . $crlf .\r
+ $params .\r
+ str_repeat($htab, $indent) . '</header>' . $crlf;\r
+\r
+ return $return;\r
+ }\r
+\r
+} // End of class\r