home *** CD-ROM | disk | FTP | other *** search
/ Chip 2004 April / CMCD0404.ISO / Software / Freeware / Programare / groupoffice-com-2.01 / classes / mimeDecode.class.inc < prev    next >
Text File  |  2004-03-08  |  30KB  |  795 lines

  1. <?Php
  2. // +-----------------------------------------------------------------------+
  3. // | Copyright (c) 2002  Richard Heyes                                     |
  4. // | All rights reserved.                                                  |
  5. // |                                                                       |
  6. // | Redistribution and use in source and binary forms, with or without    |
  7. // | modification, are permitted provided that the following conditions    |
  8. // | are met:                                                              |
  9. // |                                                                       |
  10. // | o Redistributions of source code must retain the above copyright      |
  11. // |   notice, this list of conditions and the following disclaimer.       |
  12. // | o Redistributions in binary form must reproduce the above copyright   |
  13. // |   notice, this list of conditions and the following disclaimer in the |
  14. // |   documentation and/or other materials provided with the distribution.|
  15. // | o The names of the authors may not be used to endorse or promote      |
  16. // |   products derived from this software without specific prior written  |
  17. // |   permission.                                                         |
  18. // |                                                                       |
  19. // | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS   |
  20. // | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT     |
  21. // | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
  22. // | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT  |
  23. // | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
  24. // | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT      |
  25. // | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
  26. // | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
  27. // | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT   |
  28. // | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
  29. // | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.  |
  30. // |                                                                       |
  31. // +-----------------------------------------------------------------------+
  32. // | Author: Richard Heyes <richard@phpguru.org>                           |
  33. // +-----------------------------------------------------------------------+
  34.  
  35. /**
  36. *  +----------------------------- IMPORTANT ------------------------------+
  37. *  | Usage of this class compared to native php extensions such as        |
  38. *  | mailparse or imap, is slow and may be feature deficient. If available|
  39. *  | you are STRONGLY recommended to use the php extensions.              |
  40. *  +----------------------------------------------------------------------+
  41. *
  42. * Mime Decoding class
  43. *
  44. * This class will parse a raw mime email and return
  45. * the structure. Returned structure is similar to
  46. * that returned by imap_fetchstructure().
  47. *
  48. * USAGE: (assume $input is your raw email)
  49. *
  50. * $decode = new Mail_mimeDecode($input, "\r\n");
  51. * $structure = $decode->decode();
  52. * print_r($structure);
  53. *
  54. * Or statically:
  55. *
  56. * $params['input'] = $input;
  57. * $structure = Mail_mimeDecode::decode($params);
  58. * print_r($structure);
  59. *
  60. * TODO:
  61. *  - Implement further content types, eg. multipart/parallel,
  62. *    perhaps even message/partial.
  63. *
  64. * @author  Richard Heyes <richard@phpguru.org>
  65. * @version $Revision: 1.1 $
  66. * @package Mail
  67. */
  68.  
  69. class Mail_mimeDecode
  70. {
  71.  
  72.     /**
  73.      * The raw email to decode
  74.      * @var    string
  75.      */
  76.     var $_input;
  77.  
  78.     /**
  79.      * The header part of the input
  80.      * @var    string
  81.      */
  82.     var $_header;
  83.  
  84.     /**
  85.      * The body part of the input
  86.      * @var    string
  87.      */
  88.     var $_body;
  89.  
  90.     /**
  91.      * If an error occurs, this is used to store the message
  92.      * @var    string
  93.      */
  94.     var $_error;
  95.  
  96.     /**
  97.      * Flag to determine whether to include bodies in the
  98.      * returned object.
  99.      * @var    boolean
  100.      */
  101.     var $_include_bodies;
  102.  
  103.     /**
  104.      * Flag to determine whether to decode bodies
  105.      * @var    boolean
  106.      */
  107.     var $_decode_bodies;
  108.  
  109.     /**
  110.      * Flag to determine whether to decode headers
  111.      * @var    boolean
  112.      */
  113.     var $_decode_headers;
  114.  
  115.     /**
  116.     * If invoked from a class, $this will be set. This has problematic
  117.     * connotations for calling decode() statically. Hence this variable
  118.     * is used to determine if we are indeed being called statically or
  119.     * via an object.
  120.     */
  121.     var $mailMimeDecode;
  122.  
  123.     /**
  124.      * Constructor.
  125.      *
  126.      * Sets up the object, initialise the variables, and splits and
  127.      * stores the header and body of the input.
  128.      *
  129.      * @param string The input to decode
  130.      * @access public
  131.      */
  132.     function Mail_mimeDecode($input)
  133.     {
  134.         list($header, $body)   = $this->_splitBodyHeader($input);
  135.  
  136.         $this->_input          = $input;
  137.         $this->_header         = $header;
  138.         $this->_body           = $body;
  139.         $this->_decode_bodies  = false;
  140.         $this->_include_bodies = true;
  141.         
  142.         $this->mailMimeDecode  = true;
  143.     }
  144.  
  145.     /**
  146.      * Begins the decoding process. If called statically
  147.      * it will create an object and call the decode() method
  148.      * of it.
  149.      *
  150.      * @param array An array of various parameters that determine
  151.      *              various things:
  152.      *              include_bodies - Whether to include the body in the returned
  153.      *                               object.
  154.      *              decode_bodies  - Whether to decode the bodies
  155.      *                               of the parts. (Transfer encoding)
  156.      *              decode_headers - Whether to decode headers
  157.      *              input          - If called statically, this will be treated
  158.      *                               as the input
  159.      * @return object Decoded results
  160.      * @access public
  161.      */
  162.     function decode($params = null)
  163.     {
  164.  
  165.         // Have we been called statically? If so, create an object and pass details to that.
  166.         if (!isset($this->mailMimeDecode) AND isset($params['input'])) {
  167.  
  168.             $obj = new Mail_mimeDecode($params['input']);
  169.             $structure = $obj->decode($params);
  170.  
  171.         // Called statically but no input
  172.         } elseif (!isset($this->mailMimeDecode)) {
  173.             return false;
  174.  
  175.         // Called via an object
  176.         } else {
  177.             $this->_include_bodies = isset($params['include_bodies'])  ? $params['include_bodies']  : false;
  178.             $this->_decode_bodies  = isset($params['decode_bodies'])   ? $params['decode_bodies']   : false;
  179.             $this->_decode_headers = isset($params['decode_headers'])  ? $params['decode_headers']  : false;
  180.  
  181.             $structure = $this->_decode($this->_header, $this->_body);
  182.         }
  183.  
  184.         return $structure;
  185.     }
  186.  
  187.     /**
  188.      * Performs the decoding. Decodes the body string passed to it
  189.      * If it finds certain content-types it will call itself in a
  190.      * recursive fashion
  191.      *
  192.      * @param string Header section
  193.      * @param string Body section
  194.      * @return object Results of decoding process
  195.      * @access private
  196.      */
  197.     function _decode($headers, $body, $default_ctype = 'text/plain')
  198.     {
  199.         $return = new stdClass;
  200.         $headers = $this->_parseHeaders($headers);
  201.  
  202.         foreach ($headers as $value) {
  203.             if (isset($return->headers[strtolower($value['name'])]) AND !is_array($return->headers[strtolower($value['name'])])) {
  204.                 $return->headers[strtolower($value['name'])]   = array($return->headers[strtolower($value['name'])]);
  205.                 $return->headers[strtolower($value['name'])][] = $value['value'];
  206.  
  207.             } elseif (isset($return->headers[strtolower($value['name'])])) {
  208.                 $return->headers[strtolower($value['name'])][] = $value['value'];
  209.  
  210.             } else {
  211.                 $return->headers[strtolower($value['name'])] = $value['value'];
  212.             }
  213.         }
  214.  
  215.         reset($headers);
  216.         while (list($key, $value) = each($headers)) {
  217.             $headers[$key]['name'] = strtolower($headers[$key]['name']);
  218.             switch ($headers[$key]['name']) {
  219.  
  220.                 case 'content-type':
  221.                     $content_type = $this->_parseHeaderValue($headers[$key]['value']);
  222.  
  223.                     if (preg_match('/([0-9a-z+.-]+)\/([0-9a-z+.-]+)/i', $content_type['value'], $regs)) {
  224.                         $return->ctype_primary   = $regs[1];
  225.                         $return->ctype_secondary = $regs[2];
  226.                     }
  227.  
  228.                     if (isset($content_type['other'])) {
  229.                         while (list($p_name, $p_value) = each($content_type['other'])) {
  230.                             $return->ctype_parameters[$p_name] = $p_value;
  231.                         }
  232.                     }
  233.                     break;
  234.  
  235.                 case 'content-disposition';
  236.                     $content_disposition = $this->_parseHeaderValue($headers[$key]['value']);
  237.                     $return->disposition   = $content_disposition['value'];
  238.                     if (isset($content_disposition['other'])) {
  239.                         while (list($p_name, $p_value) = each($content_disposition['other'])) {
  240.                             $return->d_parameters[$p_name] = $p_value;
  241.                         }
  242.                     }
  243.                     break;
  244.  
  245.                 case 'content-transfer-encoding':
  246.                     $content_transfer_encoding = $this->_parseHeaderValue($headers[$key]['value']);
  247.                     break;
  248.             }
  249.         }
  250.  
  251.         if (isset($content_type)) {
  252.             switch (strtolower($content_type['value'])) {
  253.                 case 'text/plain':
  254.                     $encoding = isset($content_transfer_encoding) ? $content_transfer_encoding['value'] : '7bit';
  255.                     $this->_include_bodies ? $return->body = ($this->_decode_bodies ? $this->_decodeBody($body, $encoding) : $body) : null;
  256.                     break;
  257.  
  258.                 case 'text/html':
  259.                     $encoding = isset($content_transfer_encoding) ? $content_transfer_encoding['value'] : '7bit';
  260.                     $this->_include_bodies ? $return->body = ($this->_decode_bodies ? $this->_decodeBody($body, $encoding) : $body) : null;
  261.                     break;
  262.  
  263.                 case 'multipart/parallel':
  264.                 case 'multipart/report': // RFC1892
  265.                 case 'multipart/signed': // PGP
  266.                 case 'multipart/digest':
  267.                 case 'multipart/alternative':
  268.                 case 'multipart/related':
  269.                 case 'multipart/mixed':
  270.                     if(!isset($content_type['other']['boundary'])){
  271.                         $this->_error = 'No boundary found for ' . $content_type['value'] . ' part';
  272.                         return false;
  273.                     }
  274.  
  275.                     $default_ctype = (strtolower($content_type['value']) === 'multipart/digest') ? 'message/rfc822' : 'text/plain';
  276.  
  277.                     $parts = $this->_boundarySplit($body, $content_type['other']['boundary']);
  278.                     for ($i = 0; $i < count($parts); $i++) {
  279.                         list($part_header, $part_body) = $this->_splitBodyHeader($parts[$i]);
  280.                         $part = $this->_decode($part_header, $part_body, $default_ctype);
  281.                         if($part === false)
  282.                             return false;
  283.                         $return->parts[] = $part;
  284.                     }
  285.                     break;
  286.  
  287.                 case 'message/rfc822':
  288.                     $obj = &new Mail_mimeDecode($body);
  289.                     $return->parts[] = $obj->decode(array('include_bodies' => $this->_include_bodies));
  290.                     unset($obj);
  291.                     break;
  292.  
  293.                 default:
  294.                     if(!isset($content_transfer_encoding['value']))
  295.                         $content_transfer_encoding['value'] = '7bit';
  296.                     $this->_include_bodies ? $return->body = ($this->_decode_bodies ? $this->_decodeBody($body, $content_transfer_encoding['value']) : $body) : null;
  297.                     break;
  298.             }
  299.  
  300.         } else {
  301.             $ctype = explode('/', $default_ctype);
  302.             $return->ctype_primary   = $ctype[0];
  303.             $return->ctype_secondary = $ctype[1];
  304.             $this->_include_bodies ? $return->body = ($this->_decode_bodies ? $this->_decodeBody($body) : $body) : null;
  305.         }
  306.  
  307.         return $return;
  308.     }
  309.  
  310.     /**
  311.      * Given the output of the above function, this will return an
  312.      * array of references to the parts, indexed by mime number.
  313.      *
  314.      * @param  object $structure   The structure to go through
  315.      * @param  string $mime_number Internal use only.
  316.      * @return array               Mime numbers
  317.      */
  318.     function &getMimeNumbers(&$structure, $no_refs = false, $mime_number = '', $prepend = '')
  319.     {
  320.         $return = array();
  321.         if (!empty($structure->parts)) {
  322.             if ($mime_number != '') {
  323.                 $structure->mime_id = $prepend . $mime_number;
  324.                 $return[$prepend . $mime_number] = &$structure;
  325.             }
  326.             for ($i = 0; $i < count($structure->parts); $i++) {
  327.  
  328.             
  329.                 if (!empty($structure->headers['content-type']) AND substr(strtolower($structure->headers['content-type']), 0, 8) == 'message/') {
  330.                     $prepend      = $prepend . $mime_number . '.';
  331.                     $_mime_number = '';
  332.                 } else {
  333.                     $_mime_number = ($mime_number == '' ? $i + 1 : sprintf('%s.%s', $mime_number, $i + 1));
  334.                 }
  335.  
  336.                 $arr = &Mail_mimeDecode::getMimeNumbers($structure->parts[$i], $no_refs, $_mime_number, $prepend);
  337.                 foreach ($arr as $key => $val) {
  338.                     $no_refs ? $return[$key] = '' : $return[$key] = &$arr[$key];
  339.                 }
  340.             }
  341.         } else {
  342.             if ($mime_number == '') {
  343.                 $mime_number = '1';
  344.             }
  345.             $structure->mime_id = $prepend . $mime_number;
  346.             $no_refs ? $return[$prepend . $mime_number] = '' : $return[$prepend . $mime_number] = &$structure;
  347.         }
  348.         
  349.         return $return;
  350.     }
  351.  
  352.     /**
  353.      * Given a string containing a header and body
  354.      * section, this function will split them (at the first
  355.      * blank line) and return them.
  356.      *
  357.      * @param string Input to split apart
  358.      * @return array Contains header and body section
  359.      * @access private
  360.      */
  361.     function _splitBodyHeader($input)
  362.     {
  363.         if (preg_match("/^(.*?)\r?\n\r?\n(.*)/s", $input, $match)) {
  364.             return array($match[1], $match[2]);
  365.         }
  366.         $this->_error = 'Could not split header and body';
  367.         return false;
  368.     }
  369.  
  370.     /**
  371.      * Parse headers given in $input and return
  372.      * as assoc array.
  373.      *
  374.      * @param string Headers to parse
  375.      * @return array Contains parsed headers
  376.      * @access private
  377.      */
  378.     function _parseHeaders($input)
  379.     {
  380.  
  381.         if ($input !== '') {
  382.             // Unfold the input
  383.             $input   = preg_replace("/\r?\n/", "\r\n", $input);
  384.             $input   = preg_replace("/\r\n(\t| )+/", ' ', $input);
  385.             $headers = explode("\r\n", trim($input));
  386.  
  387.             foreach ($headers as $value) {
  388.                 $hdr_name = substr($value, 0, $pos = strpos($value, ':'));
  389.                 $hdr_value = substr($value, $pos+1);
  390.                 if($hdr_value[0] == ' ')
  391.                     $hdr_value = substr($hdr_value, 1);
  392.  
  393.                 $return[] = array(
  394.                                   'name'  => $hdr_name,
  395.                                   'value' => $this->_decode_headers ? $this->_decodeHeader($hdr_value) : $hdr_value
  396.                                  );
  397.             }
  398.         } else {
  399.             $return = array();
  400.         }
  401.  
  402.         return $return;
  403.     }
  404.  
  405.     /**
  406.      * Function to parse a header value,
  407.      * extract first part, and any secondary
  408.      * parts (after ;) This function is not as
  409.      * robust as it could be. Eg. header comments
  410.      * in the wrong place will probably break it.
  411.      *
  412.      * @param string Header value to parse
  413.      * @return array Contains parsed result
  414.      * @access private
  415.      */
  416.     function _parseHeaderValue($input)
  417.     {
  418.  
  419.         if (($pos = strpos($input, ';')) !== false) {
  420.  
  421.             $return['value'] = trim(substr($input, 0, $pos));
  422.             $input = trim(substr($input, $pos+1));
  423.  
  424.             if (strlen($input) > 0) {
  425.  
  426.                 // This splits on a semi-colon, if there's no preceeding backslash
  427.                 // Can't handle if it's in double quotes however. (Of course anyone
  428.                 // sending that needs a good slap).
  429.                 $parameters = preg_split('/\s*(?<!\\\\);\s*/i', $input);
  430.  
  431.                 for ($i = 0; $i < count($parameters); $i++) {
  432.                     $param_name  = substr($parameters[$i], 0, $pos = strpos($parameters[$i], '='));
  433.                     $param_value = substr($parameters[$i], $pos + 1);
  434.                     if ($param_value[0] == '"') {
  435.                         $param_value = substr($param_value, 1, -1);
  436.                     }
  437.                     $return['other'][$param_name] = $param_value;
  438.                     $return['other'][strtolower($param_name)] = $param_value;
  439.                 }
  440.             }
  441.         } else {
  442.             $return['value'] = trim($input);
  443.         }
  444.  
  445.         return $return;
  446.     }
  447.  
  448.     /**
  449.      * This function splits the input based
  450.      * on the given boundary
  451.      *
  452.      * @param string Input to parse
  453.      * @return array Contains array of resulting mime parts
  454.      * @access private
  455.      */
  456.     function _boundarySplit($input, $boundary)
  457.     {
  458.         $tmp = explode('--'.$boundary, $input);
  459.  
  460.         for ($i=1; $i<count($tmp)-1; $i++) {
  461.             $parts[] = $tmp[$i];
  462.         }
  463.  
  464.         return $parts;
  465.     }
  466.  
  467.     /**
  468.      * Given a header, this function will decode it
  469.      * according to RFC2047. Probably not *exactly*
  470.      * conformant, but it does pass all the given
  471.      * examples (in RFC2047).
  472.      *
  473.      * @param string Input header value to decode
  474.      * @return string Decoded header value
  475.      * @access private
  476.      */
  477.     function _decodeHeader($input)
  478.     {
  479.         // Remove white space between encoded-words
  480.         $input = preg_replace('/(=\?[^?]+\?(q|b)\?[^?]*\?=)(\s)+=\?/i', '\1=?', $input);
  481.  
  482.         // For each encoded-word...
  483.         while (preg_match('/(=\?([^?]+)\?(q|b)\?([^?]*)\?=)/i', $input, $matches)) {
  484.  
  485.             $encoded  = $matches[1];
  486.             $charset  = $matches[2];
  487.             $encoding = $matches[3];
  488.             $text     = $matches[4];
  489.  
  490.             switch (strtolower($encoding)) {
  491.                 case 'b':
  492.                     $text = base64_decode($text);
  493.                     break;
  494.  
  495.                 case 'q':
  496.                     $text = str_replace('_', ' ', $text);
  497.                     preg_match_all('/=([a-f0-9]{2})/i', $text, $matches);
  498.                     foreach($matches[1] as $value)
  499.                         $text = str_replace('='.$value, chr(hexdec($value)), $text);
  500.                     break;
  501.             }
  502.  
  503.             $input = str_replace($encoded, $text, $input);
  504.         }
  505.  
  506.         return $input;
  507.     }
  508.  
  509.     /**
  510.      * Given a body string and an encoding type,
  511.      * this function will decode and return it.
  512.      *
  513.      * @param  string Input body to decode
  514.      * @param  string Encoding type to use.
  515.      * @return string Decoded body
  516.      * @access private
  517.      */
  518.     function _decodeBody($input, $encoding = '7bit')
  519.     {
  520.         switch ($encoding) {
  521.             case '7bit':
  522.                 return $input;
  523.                 break;
  524.  
  525.             case 'quoted-printable':
  526.                 return $this->_quotedPrintableDecode($input);
  527.                 break;
  528.  
  529.             case 'base64':
  530.                 return base64_decode($input);
  531.                 break;
  532.  
  533.             default:
  534.                 return $input;
  535.         }
  536.     }
  537.  
  538.     /**
  539.      * Given a quoted-printable string, this
  540.      * function will decode and return it.
  541.      *
  542.      * @param  string Input body to decode
  543.      * @return string Decoded body
  544.      * @access private
  545.      */
  546.     function _quotedPrintableDecode($input)
  547.     {
  548.         // Remove soft line breaks
  549.         $input = preg_replace("/=\r?\n/", '', $input);
  550.  
  551.         // Replace encoded characters
  552.         $input = preg_replace('/=([a-f0-9]{2})/ie', "chr(hexdec('\\1'))", $input);
  553.  
  554.         return $input;
  555.     }
  556.  
  557.     /**
  558.      * Checks the input for uuencoded files and returns
  559.      * an array of them. Can be called statically, eg:
  560.      *
  561.      * $files =& Mail_mimeDecode::uudecode($some_text);
  562.      *
  563.      * It will check for the begin 666 ... end syntax
  564.      * however and won't just blindly decode whatever you
  565.      * pass it.
  566.      *
  567.      * @param  string Input body to look for attahcments in
  568.      * @return array  Decoded bodies, filenames and permissions
  569.      * @access public
  570.      * @author Unknown
  571.      */
  572.     function &uudecode($input)
  573.     {
  574.         // Find all uuencoded sections
  575.         preg_match_all("/begin ([0-7]{3}) (.+)\r?\n(.+)\r?\nend/Us", $input, $matches);
  576.  
  577.         for ($j = 0; $j < count($matches[3]); $j++) {
  578.  
  579.             $str      = $matches[3][$j];
  580.             $filename = $matches[2][$j];
  581.             $fileperm = $matches[1][$j];
  582.  
  583.             $file = '';
  584.             $str = preg_split("/\r?\n/", trim($str));
  585.             $strlen = count($str);
  586.  
  587.             for ($i = 0; $i < $strlen; $i++) {
  588.                 $pos = 1;
  589.                 $d = 0;
  590.                 $len=(int)(((ord(substr($str[$i],0,1)) -32) - ' ') & 077);
  591.  
  592.                 while (($d + 3 <= $len) AND ($pos + 4 <= strlen($str[$i]))) {
  593.                     $c0 = (ord(substr($str[$i],$pos,1)) ^ 0x20);
  594.                     $c1 = (ord(substr($str[$i],$pos+1,1)) ^ 0x20);
  595.                     $c2 = (ord(substr($str[$i],$pos+2,1)) ^ 0x20);
  596.                     $c3 = (ord(substr($str[$i],$pos+3,1)) ^ 0x20);
  597.                     $file .= chr(((($c0 - ' ') & 077) << 2) | ((($c1 - ' ') & 077) >> 4));
  598.  
  599.                     $file .= chr(((($c1 - ' ') & 077) << 4) | ((($c2 - ' ') & 077) >> 2));
  600.  
  601.                     $file .= chr(((($c2 - ' ') & 077) << 6) |  (($c3 - ' ') & 077));
  602.  
  603.                     $pos += 4;
  604.                     $d += 3;
  605.                 }
  606.  
  607.                 if (($d + 2 <= $len) && ($pos + 3 <= strlen($str[$i]))) {
  608.                     $c0 = (ord(substr($str[$i],$pos,1)) ^ 0x20);
  609.                     $c1 = (ord(substr($str[$i],$pos+1,1)) ^ 0x20);
  610.                     $c2 = (ord(substr($str[$i],$pos+2,1)) ^ 0x20);
  611.                     $file .= chr(((($c0 - ' ') & 077) << 2) | ((($c1 - ' ') & 077) >> 4));
  612.  
  613.                     $file .= chr(((($c1 - ' ') & 077) << 4) | ((($c2 - ' ') & 077) >> 2));
  614.  
  615.                     $pos += 3;
  616.                     $d += 2;
  617.                 }
  618.  
  619.                 if (($d + 1 <= $len) && ($pos + 2 <= strlen($str[$i]))) {
  620.                     $c0 = (ord(substr($str[$i],$pos,1)) ^ 0x20);
  621.                     $c1 = (ord(substr($str[$i],$pos+1,1)) ^ 0x20);
  622.                     $file .= chr(((($c0 - ' ') & 077) << 2) | ((($c1 - ' ') & 077) >> 4));
  623.  
  624.                 }
  625.             }
  626.             $files[] = array('filename' => $filename, 'fileperm' => $fileperm, 'filedata' => $file);
  627.         }
  628.  
  629.         return $files;
  630.     }
  631.  
  632.     /**
  633.      * getSendArray() returns the arguments required for Mail::send()
  634.      * used to build the arguments for a mail::send() call 
  635.      *
  636.      * Usage:
  637.      * $mailtext = Full email (for example generated by a template)
  638.      * $decoder = new Mail_mimeDecode($mailtext);
  639.      * $parts =  $decoder->getSendArray();
  640.      * if (!PEAR::isError($parts) {
  641.      *     list($recipents,$headers,$body) = $parts;
  642.      *     $mail = Mail::factory('smtp');
  643.      *     $mail->send($recipents,$headers,$body);
  644.      * } else {
  645.      *     echo $parts->message;
  646.      * }
  647.      * @return mixed   array of recipeint, headers,body or Pear_Error
  648.      * @access public
  649.      * @author Alan Knowles <alan@akbkhome.com>
  650.      */
  651.     function getSendArray()
  652.     {
  653.         // prevent warning if this is not set
  654.         $this->_decode_headers = FALSE;
  655.         $headerlist =$this->_parseHeaders($this->_header);
  656.         $to = "";
  657.         if (!$headerlist) {
  658.             return false;
  659.         }
  660.         foreach($headerlist as $item) {
  661.             $header[$item['name']] = $item['value'];
  662.             switch (strtolower($item['name'])) {
  663.                 case "to":
  664.                 case "cc":
  665.                 case "bcc":
  666.                     $to = ",".$item['value'];
  667.                 default:
  668.                    break;
  669.             }
  670.         }
  671.         if ($to == "") {
  672.             return false;
  673.         }
  674.         $to = substr($to,1);
  675.         return array($to,$header,$this->_body);
  676.     } 
  677.  
  678.     /**
  679.      * Returns a xml copy of the output of
  680.      * Mail_mimeDecode::decode. Pass the output in as the
  681.      * argument. This function can be called statically. Eg:
  682.      *
  683.      * $output = $obj->decode();
  684.      * $xml    = Mail_mimeDecode::getXML($output);
  685.      *
  686.      * The DTD used for this should have been in the package. Or
  687.      * alternatively you can get it from cvs, or here:
  688.      * http://www.phpguru.org/xmail/xmail.dtd.
  689.      *
  690.      * @param  object Input to convert to xml. This should be the
  691.      *                output of the Mail_mimeDecode::decode function
  692.      * @return string XML version of input
  693.      * @access public
  694.      */
  695.     function getXML($input)
  696.     {
  697.         $crlf    =  "\r\n";
  698.         $output  = '<?xml version=\'1.0\'?>' . $crlf .
  699.                    '<!DOCTYPE email SYSTEM "http://www.phpguru.org/xmail/xmail.dtd">' . $crlf .
  700.                    '<email>' . $crlf .
  701.                    Mail_mimeDecode::_getXML($input) .
  702.                    '</email>';
  703.  
  704.         return $output;
  705.     }
  706.  
  707.     /**
  708.      * Function that does the actual conversion to xml. Does a single
  709.      * mimepart at a time.
  710.      *
  711.      * @param  object  Input to convert to xml. This is a mimepart object.
  712.      *                 It may or may not contain subparts.
  713.      * @param  integer Number of tabs to indent
  714.      * @return string  XML version of input
  715.      * @access private
  716.      */
  717.     function _getXML($input, $indent = 1)
  718.     {
  719.         $htab    =  "\t";
  720.         $crlf    =  "\r\n";
  721.         $output  =  '';
  722.         $headers = @(array)$input->headers;
  723.  
  724.         foreach ($headers as $hdr_name => $hdr_value) {
  725.  
  726.             // Multiple headers with this name
  727.             if (is_array($headers[$hdr_name])) {
  728.                 for ($i = 0; $i < count($hdr_value); $i++) {
  729.                     $output .= Mail_mimeDecode::_getXML_helper($hdr_name, $hdr_value[$i], $indent);
  730.                 }
  731.  
  732.             // Only one header of this sort
  733.             } else {
  734.                 $output .= Mail_mimeDecode::_getXML_helper($hdr_name, $hdr_value, $indent);
  735.             }
  736.         }
  737.  
  738.         if (!empty($input->parts)) {
  739.             for ($i = 0; $i < count($input->parts); $i++) {
  740.                 $output .= $crlf . str_repeat($htab, $indent) . '<mimepart>' . $crlf .
  741.                            Mail_mimeDecode::_getXML($input->parts[$i], $indent+1) .
  742.                            str_repeat($htab, $indent) . '</mimepart>' . $crlf;
  743.             }
  744.         } elseif (isset($input->body)) {
  745.             $output .= $crlf . str_repeat($htab, $indent) . '<body><![CDATA[' .
  746.                        $input->body . ']]></body>' . $crlf;
  747.         }
  748.  
  749.         return $output;
  750.     }
  751.  
  752.     /**
  753.      * Helper function to _getXML(). Returns xml of a header.
  754.      *
  755.      * @param  string  Name of header
  756.      * @param  string  Value of header
  757.      * @param  integer Number of tabs to indent
  758.      * @return string  XML version of input
  759.      * @access private
  760.      */
  761.     function _getXML_helper($hdr_name, $hdr_value, $indent)
  762.     {
  763.         $htab   = "\t";
  764.         $crlf   = "\r\n";
  765.         $return = '';
  766.  
  767.         $new_hdr_value = ($hdr_name != 'received') ? Mail_mimeDecode::_parseHeaderValue($hdr_value) : array('value' => $hdr_value);
  768.         $new_hdr_name  = str_replace(' ', '-', ucwords(str_replace('-', ' ', $hdr_name)));
  769.  
  770.         // Sort out any parameters
  771.         if (!empty($new_hdr_value['other'])) {
  772.             foreach ($new_hdr_value['other'] as $paramname => $paramvalue) {
  773.                 $params[] = str_repeat($htab, $indent) . $htab . '<parameter>' . $crlf .
  774.                             str_repeat($htab, $indent) . $htab . $htab . '<paramname>' . htmlspecialchars($paramname) . '</paramname>' . $crlf .
  775.                             str_repeat($htab, $indent) . $htab . $htab . '<paramvalue>' . htmlspecialchars($paramvalue) . '</paramvalue>' . $crlf .
  776.                             str_repeat($htab, $indent) . $htab . '</parameter>' . $crlf;
  777.             }
  778.  
  779.             $params = implode('', $params);
  780.         } else {
  781.             $params = '';
  782.         }
  783.  
  784.         $return = str_repeat($htab, $indent) . '<header>' . $crlf .
  785.                   str_repeat($htab, $indent) . $htab . '<headername>' . htmlspecialchars($new_hdr_name) . '</headername>' . $crlf .
  786.                   str_repeat($htab, $indent) . $htab . '<headervalue>' . htmlspecialchars($new_hdr_value['value']) . '</headervalue>' . $crlf .
  787.                   $params .
  788.                   str_repeat($htab, $indent) . '</header>' . $crlf;
  789.  
  790.         return $return;
  791.     }
  792.  
  793. } // End of class
  794. ?>
  795.