3 * The Mail_mimeDecode class is used to decode mail/mime messages
5 * This class will parse a raw mime email and return
6 * the structure. Returned structure is similar to
7 * that returned by imap_fetchstructure().
9 * +----------------------------- IMPORTANT ------------------------------+
10 * | Usage of this class compared to native php extensions such as |
11 * | mailparse or imap, is slow and may be feature deficient. If available|
12 * | you are STRONGLY recommended to use the php extensions. |
13 * +----------------------------------------------------------------------+
15 * Compatible with PHP versions 4 and 5
17 * LICENSE: This LICENSE is in the BSD license style.
18 * Copyright (c) 2002-2003, Richard Heyes <richard@phpguru.org>
19 * Copyright (c) 2003-2006, PEAR <pear-group@php.net>
20 * All rights reserved.
22 * Redistribution and use in source and binary forms, with or
23 * without modification, are permitted provided that the following
26 * - Redistributions of source code must retain the above copyright
27 * notice, this list of conditions and the following disclaimer.
28 * - Redistributions in binary form must reproduce the above copyright
29 * notice, this list of conditions and the following disclaimer in the
30 * documentation and/or other materials provided with the distribution.
31 * - Neither the name of the authors, nor the names of its contributors
32 * may be used to endorse or promote products derived from this
33 * software without specific prior written permission.
35 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
36 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
37 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
38 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
39 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
40 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
41 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
42 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
43 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
44 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
45 * THE POSSIBILITY OF SUCH DAMAGE.
49 * @author Richard Heyes <richard@phpguru.org>
50 * @author George Schlossnagle <george@omniti.com>
51 * @author Cipriano Groenendal <cipri@php.net>
52 * @author Sean Coates <sean@php.net>
53 * @copyright 2003-2006 PEAR <pear-group@php.net>
54 * @license http://www.opensource.org/licenses/bsd-license.php BSD License
55 * @version CVS: $Id: mimeDecode.php 305875 2010-12-01 07:17:10Z alan_k $
56 * @link http://pear.php.net/package/Mail_mime
63 * This package depends on PEAR to raise errors.
65 require_once 'PEAR.php';
69 * The Mail_mimeDecode class is used to decode mail/mime messages
71 * This class will parse a raw mime email and return the structure.
72 * Returned structure is similar to that returned by imap_fetchstructure().
74 * +----------------------------- IMPORTANT ------------------------------+
75 * | Usage of this class compared to native php extensions such as |
76 * | mailparse or imap, is slow and may be feature deficient. If available|
77 * | you are STRONGLY recommended to use the php extensions. |
78 * +----------------------------------------------------------------------+
82 * @author Richard Heyes <richard@phpguru.org>
83 * @author George Schlossnagle <george@omniti.com>
84 * @author Cipriano Groenendal <cipri@php.net>
85 * @author Sean Coates <sean@php.net>
86 * @copyright 2003-2006 PEAR <pear-group@php.net>
87 * @license http://www.opensource.org/licenses/bsd-license.php BSD License
88 * @version Release: @package_version@
89 * @link http://pear.php.net/package/Mail_mime
91 class Mail_mimeDecode extends PEAR
94 * The raw email to decode
102 * The header part of the input
110 * The body part of the input
118 * If an error occurs, this is used to store the message
126 * Flag to determine whether to include bodies in the
132 var $_include_bodies;
135 * Flag to determine whether to decode bodies
143 * Flag to determine whether to decode headers
148 var $_decode_headers;
151 * Flag to determine whether to include attached messages
152 * as body in the returned object. Depends on $_include_bodies
162 * Sets up the object, initialise the variables, and splits and
163 * stores the header and body of the input.
165 * @param string The input to decode
168 function Mail_mimeDecode($input)
170 list($header, $body) = $this->_splitBodyHeader($input);
172 $this->_input = $input;
173 $this->_header = $header;
174 $this->_body = $body;
175 $this->_decode_bodies = false;
176 $this->_include_bodies = true;
177 $this->_rfc822_bodies = false;
181 * Begins the decoding process. If called statically
182 * it will create an object and call the decode() method
185 * @param array An array of various parameters that determine
187 * include_bodies - Whether to include the body in the returned
189 * decode_bodies - Whether to decode the bodies
190 * of the parts. (Transfer encoding)
191 * decode_headers - Whether to decode headers
192 * input - If called statically, this will be treated
194 * @return object Decoded results
197 function decode($params = null)
199 // determine if this method has been called statically
200 $isStatic = empty($this) || !is_a($this, __CLASS__);
202 // Have we been called statically?
203 // If so, create an object and pass details to that.
204 if ($isStatic AND isset($params['input'])) {
206 $obj = new Mail_mimeDecode($params['input']);
207 $structure = $obj->decode($params);
209 // Called statically but no input
210 } elseif ($isStatic) {
211 return PEAR::raiseError('Called statically and no input given');
213 // Called via an object
215 $this->_include_bodies = isset($params['include_bodies']) ?
216 $params['include_bodies'] : false;
217 $this->_decode_bodies = isset($params['decode_bodies']) ?
218 $params['decode_bodies'] : false;
219 $this->_decode_headers = isset($params['decode_headers']) ?
220 $params['decode_headers'] : false;
221 $this->_rfc822_bodies = isset($params['rfc_822bodies']) ?
222 $params['rfc_822bodies'] : false;
224 $structure = $this->_decode($this->_header, $this->_body);
225 if ($structure === false) {
226 $structure = $this->raiseError($this->_error);
234 * Performs the decoding. Decodes the body string passed to it
235 * If it finds certain content-types it will call itself in a
238 * @param string Header section
239 * @param string Body section
240 * @return object Results of decoding process
243 function _decode($headers, $body, $default_ctype = 'text/plain')
245 $return = new stdClass;
246 $return->headers = array();
247 $headers = $this->_parseHeaders($headers);
249 foreach ($headers as $value) {
250 $value['value'] = $this->_decode_headers ? $this->_decodeHeader($value['value']) : $value['value'];
251 if (isset($return->headers[strtolower($value['name'])]) AND !is_array($return->headers[strtolower($value['name'])])) {
252 $return->headers[strtolower($value['name'])] = array($return->headers[strtolower($value['name'])]);
253 $return->headers[strtolower($value['name'])][] = $value['value'];
255 } elseif (isset($return->headers[strtolower($value['name'])])) {
256 $return->headers[strtolower($value['name'])][] = $value['value'];
259 $return->headers[strtolower($value['name'])] = $value['value'];
264 foreach ($headers as $key => $value) {
265 $headers[$key]['name'] = strtolower($headers[$key]['name']);
266 switch ($headers[$key]['name']) {
269 $content_type = $this->_parseHeaderValue($headers[$key]['value']);
271 if (preg_match('/([0-9a-z+.-]+)\/([0-9a-z+.-]+)/i', $content_type['value'], $regs)) {
272 $return->ctype_primary = $regs[1];
273 $return->ctype_secondary = $regs[2];
276 if (isset($content_type['other'])) {
277 foreach($content_type['other'] as $p_name => $p_value) {
278 $return->ctype_parameters[$p_name] = $p_value;
283 case 'content-disposition':
284 $content_disposition = $this->_parseHeaderValue($headers[$key]['value']);
285 $return->disposition = $content_disposition['value'];
286 if (isset($content_disposition['other'])) {
287 foreach($content_disposition['other'] as $p_name => $p_value) {
288 $return->d_parameters[$p_name] = $p_value;
293 case 'content-transfer-encoding':
294 $content_transfer_encoding = $this->_parseHeaderValue($headers[$key]['value']);
299 if (isset($content_type)) {
300 switch (strtolower($content_type['value'])) {
302 $encoding = isset($content_transfer_encoding) ? $content_transfer_encoding['value'] : '7bit';
303 $this->_include_bodies ? $return->body = ($this->_decode_bodies ? $this->_decodeBody($body, $encoding) : $body) : null;
307 $encoding = isset($content_transfer_encoding) ? $content_transfer_encoding['value'] : '7bit';
308 $this->_include_bodies ? $return->body = ($this->_decode_bodies ? $this->_decodeBody($body, $encoding) : $body) : null;
311 case 'multipart/parallel':
312 case 'multipart/appledouble': // Appledouble mail
313 case 'multipart/report': // RFC1892
314 case 'multipart/signed': // PGP
315 case 'multipart/digest':
316 case 'multipart/alternative':
317 case 'multipart/related':
318 case 'multipart/mixed':
319 case 'application/vnd.wap.multipart.related':
320 if(!isset($content_type['other']['boundary'])){
321 $this->_error = 'No boundary found for ' . $content_type['value'] . ' part';
325 $default_ctype = (strtolower($content_type['value']) === 'multipart/digest') ? 'message/rfc822' : 'text/plain';
327 $parts = $this->_boundarySplit($body, $content_type['other']['boundary']);
328 for ($i = 0; $i < count($parts); $i++) {
329 list($part_header, $part_body) = $this->_splitBodyHeader($parts[$i]);
330 $part = $this->_decode($part_header, $part_body, $default_ctype);
332 $part = $this->raiseError($this->_error);
333 $return->parts[] = $part;
337 case 'message/rfc822':
338 if ($this->_rfc822_bodies) {
339 $encoding = isset($content_transfer_encoding) ? $content_transfer_encoding['value'] : '7bit';
340 $return->body = ($this->_decode_bodies ? $this->_decodeBody($body, $encoding) : $body);
342 $obj = new Mail_mimeDecode($body);
343 $return->parts[] = $obj->decode(array('include_bodies' => $this->_include_bodies,
344 'decode_bodies' => $this->_decode_bodies,
345 'decode_headers' => $this->_decode_headers));
350 if(!isset($content_transfer_encoding['value']))
351 $content_transfer_encoding['value'] = '7bit';
352 $this->_include_bodies ? $return->body = ($this->_decode_bodies ? $this->_decodeBody($body, $content_transfer_encoding['value']) : $body) : null;
357 $ctype = explode('/', $default_ctype);
358 $return->ctype_primary = $ctype[0];
359 $return->ctype_secondary = $ctype[1];
360 $this->_include_bodies ? $return->body = ($this->_decode_bodies ? $this->_decodeBody($body) : $body) : null;
367 * Given the output of the above function, this will return an
368 * array of references to the parts, indexed by mime number.
370 * @param object $structure The structure to go through
371 * @param string $mime_number Internal use only.
372 * @return array Mime numbers
374 function &getMimeNumbers(&$structure, $no_refs = false, $mime_number = '', $prepend = '')
377 if (!empty($structure->parts)) {
378 if ($mime_number != '') {
379 $structure->mime_id = $prepend . $mime_number;
380 $return[$prepend . $mime_number] = &$structure;
382 for ($i = 0; $i < count($structure->parts); $i++) {
385 if (!empty($structure->headers['content-type']) AND substr(strtolower($structure->headers['content-type']), 0, 8) == 'message/') {
386 $prepend = $prepend . $mime_number . '.';
389 $_mime_number = ($mime_number == '' ? $i + 1 : sprintf('%s.%s', $mime_number, $i + 1));
392 $arr = &Mail_mimeDecode::getMimeNumbers($structure->parts[$i], $no_refs, $_mime_number, $prepend);
393 foreach ($arr as $key => $val) {
394 $no_refs ? $return[$key] = '' : $return[$key] = &$arr[$key];
398 if ($mime_number == '') {
401 $structure->mime_id = $prepend . $mime_number;
402 $no_refs ? $return[$prepend . $mime_number] = '' : $return[$prepend . $mime_number] = &$structure;
409 * Given a string containing a header and body
410 * section, this function will split them (at the first
411 * blank line) and return them.
413 * @param string Input to split apart
414 * @return array Contains header and body section
417 function _splitBodyHeader($input)
419 if (preg_match("/^(.*?)\r?\n\r?\n(.*)/s", $input, $match)) {
420 return array($match[1], $match[2]);
422 // bug #17325 - empty bodies are allowed. - we just check that at least one line
423 // of headers exist..
424 if (count(explode("\n",$input))) {
425 return array($input, '');
427 $this->_error = 'Could not split header and body';
432 * Parse headers given in $input and return
435 * @param string Headers to parse
436 * @return array Contains parsed headers
439 function _parseHeaders($input)
444 $input = preg_replace("/\r?\n/", "\r\n", $input);
445 //#7065 - wrapping.. with encoded stuff.. - probably not needed,
446 // wrapping space should only get removed if the trailing item on previous line is a
448 $input = preg_replace("/=\r\n(\t| )+/", '=', $input);
449 $input = preg_replace("/\r\n(\t| )+/", ' ', $input);
451 $headers = explode("\r\n", trim($input));
453 foreach ($headers as $value) {
454 $hdr_name = substr($value, 0, $pos = strpos($value, ':'));
455 $hdr_value = substr($value, $pos+1);
456 if($hdr_value[0] == ' ')
457 $hdr_value = substr($hdr_value, 1);
461 'value' => $hdr_value
472 * Function to parse a header value,
473 * extract first part, and any secondary
474 * parts (after ;) This function is not as
475 * robust as it could be. Eg. header comments
476 * in the wrong place will probably break it.
478 * @param string Header value to parse
479 * @return array Contains parsed result
482 function _parseHeaderValue($input)
485 if (($pos = strpos($input, ';')) === false) {
486 $input = $this->_decode_headers ? $this->_decodeHeader($input) : $input;
487 $return['value'] = trim($input);
493 $value = substr($input, 0, $pos);
494 $value = $this->_decode_headers ? $this->_decodeHeader($value) : $value;
495 $return['value'] = trim($value);
496 $input = trim(substr($input, $pos+1));
498 if (!strlen($input) > 0) {
501 // at this point input contains xxxx=".....";zzzz="...."
502 // since we are dealing with quoted strings, we need to handle this properly..
506 $val = false; // our string - including quotes..
507 $q = false; // in quote..
508 $lq = ''; // last quote..
513 //var_dump(array('i'=>$i,'c'=>$c,'q'=>$q, 'lq'=>$lq, 'key'=>$key, 'val' =>$val));
518 if ($i == $l-1) { // end of string.
527 if ($val === false) {
528 if (!$escaped && $c == '=') {
534 if (!$escaped && $c == ';') {
535 if ($key) { // a key without a value..
537 $return['other'][$key] = '';
538 $return['other'][strtolower($key)] = '';
547 // state - in value.. (as $val is set..)
551 if ((!strlen($val) || $lq !== false) && $c == ' ' || $c == "\t") {
553 continue; // skip leading spaces after '=' or after '"'
555 if (!$escaped && ($c == '"' || $c == "'")) {
556 // start quoted area..
558 // in theory should not happen raw text in value part..
559 // but we will handle it as a merged part of the string..
560 $val = !strlen(trim($val)) ? '' : trim($val);
565 if (!$escaped && $c == ';') {
569 if (preg_match('/\*[0-9]+$/', $key)) {
570 // this is the extended aaa*0=...;aaa*1=.... code
571 // it assumes the pieces arrive in order, and are valid...
572 $key = preg_replace('/\*[0-9]+$/', '', $key);
573 if (isset($return['other'][$key])) {
574 $return['other'][$key] .= $val;
575 if (strtolower($key) != $key) {
576 $return['other'][strtolower($key)] .= $val;
580 // continue and use standard setters..
583 $return['other'][$key] = $val;
584 $return['other'][strtolower($key)] = $val;
598 // state - in quote..
599 if (!$escaped && $c == $q) { // potential exit state..
601 // end of quoted string..
608 // normal char inside of quoted string..
613 // do we have anything left..
614 if (strlen(trim($key)) || $val !== false) {
618 if ($val !== false && preg_match('/\*[0-9]+$/', $key)) {
619 // no dupes due to our crazy regexp.
620 $key = preg_replace('/\*[0-9]+$/', '', $key);
621 if (isset($return['other'][$key])) {
622 $return['other'][$key] .= $val;
623 if (strtolower($key) != $key) {
624 $return['other'][strtolower($key)] .= $val;
628 // continue and use standard setters..
631 $return['other'][$key] = $val;
632 $return['other'][strtolower($key)] = $val;
636 foreach($return['other'] as $key =>$val) {
637 $return['other'][$key] = $this->_decode_headers ? $this->_decodeHeader($val) : $val;
644 * This function splits the input based
645 * on the given boundary
647 * @param string Input to parse
648 * @return array Contains array of resulting mime parts
651 function _boundarySplit($input, $boundary)
655 $bs_possible = substr($boundary, 2, -2);
656 $bs_check = '\"' . $bs_possible . '\"';
658 if ($boundary == $bs_check) {
659 $boundary = $bs_possible;
661 $tmp = preg_split("/--".preg_quote($boundary, '/')."((?=\s)|--)/", $input);
663 $len = count($tmp) -1;
664 for ($i = 1; $i < $len; $i++) {
665 if (strlen(trim($tmp[$i]))) {
670 // add the last part on if it does not end with the 'closing indicator'
671 if (!empty($tmp[$len]) && strlen(trim($tmp[$len])) && $tmp[$len][0] != '-') {
672 $parts[] = $tmp[$len];
678 * Given a header, this function will decode it
679 * according to RFC2047. Probably not *exactly*
680 * conformant, but it does pass all the given
681 * examples (in RFC2047).
683 * @param string Input header value to decode
684 * @return string Decoded header value
687 function _decodeHeader($input)
689 // Remove white space between encoded-words
690 $input = preg_replace('/(=\?[^?]+\?(q|b)\?[^?]*\?=)(\s)+=\?/i', '\1=?', $input);
692 // For each encoded-word...
693 while (preg_match('/(=\?([^?]+)\?(q|b)\?([^?]*)\?=)/i', $input, $matches)) {
695 $encoded = $matches[1];
696 $charset = $matches[2];
697 $encoding = $matches[3];
700 switch (strtolower($encoding)) {
702 $text = base64_decode($text);
706 $text = str_replace('_', ' ', $text);
707 preg_match_all('/=([a-f0-9]{2})/i', $text, $matches);
708 foreach($matches[1] as $value)
709 $text = str_replace('='.$value, chr(hexdec($value)), $text);
713 $input = str_replace($encoded, $text, $input);
720 * Given a body string and an encoding type,
721 * this function will decode and return it.
723 * @param string Input body to decode
724 * @param string Encoding type to use.
725 * @return string Decoded body
728 function _decodeBody($input, $encoding = '7bit')
730 switch (strtolower($encoding)) {
735 case 'quoted-printable':
736 return $this->_quotedPrintableDecode($input);
740 return base64_decode($input);
749 * Given a quoted-printable string, this
750 * function will decode and return it.
752 * @param string Input body to decode
753 * @return string Decoded body
756 function _quotedPrintableDecode($input)
758 // Remove soft line breaks
759 $input = preg_replace("/=\r?\n/", '', $input);
761 // Replace encoded characters
762 $input = preg_replace('/=([a-f0-9]{2})/ie', "chr(hexdec('\\1'))", $input);
768 * Checks the input for uuencoded files and returns
769 * an array of them. Can be called statically, eg:
771 * $files =& Mail_mimeDecode::uudecode($some_text);
773 * It will check for the begin 666 ... end syntax
774 * however and won't just blindly decode whatever you
777 * @param string Input body to look for attahcments in
778 * @return array Decoded bodies, filenames and permissions
782 function &uudecode($input)
784 // Find all uuencoded sections
785 preg_match_all("/begin ([0-7]{3}) (.+)\r?\n(.+)\r?\nend/Us", $input, $matches);
787 for ($j = 0; $j < count($matches[3]); $j++) {
789 $str = $matches[3][$j];
790 $filename = $matches[2][$j];
791 $fileperm = $matches[1][$j];
794 $str = preg_split("/\r?\n/", trim($str));
795 $strlen = count($str);
797 for ($i = 0; $i < $strlen; $i++) {
800 $len=(int)(((ord(substr($str[$i],0,1)) -32) - ' ') & 077);
802 while (($d + 3 <= $len) AND ($pos + 4 <= strlen($str[$i]))) {
803 $c0 = (ord(substr($str[$i],$pos,1)) ^ 0x20);
804 $c1 = (ord(substr($str[$i],$pos+1,1)) ^ 0x20);
805 $c2 = (ord(substr($str[$i],$pos+2,1)) ^ 0x20);
806 $c3 = (ord(substr($str[$i],$pos+3,1)) ^ 0x20);
807 $file .= chr(((($c0 - ' ') & 077) << 2) | ((($c1 - ' ') & 077) >> 4));
809 $file .= chr(((($c1 - ' ') & 077) << 4) | ((($c2 - ' ') & 077) >> 2));
811 $file .= chr(((($c2 - ' ') & 077) << 6) | (($c3 - ' ') & 077));
817 if (($d + 2 <= $len) && ($pos + 3 <= strlen($str[$i]))) {
818 $c0 = (ord(substr($str[$i],$pos,1)) ^ 0x20);
819 $c1 = (ord(substr($str[$i],$pos+1,1)) ^ 0x20);
820 $c2 = (ord(substr($str[$i],$pos+2,1)) ^ 0x20);
821 $file .= chr(((($c0 - ' ') & 077) << 2) | ((($c1 - ' ') & 077) >> 4));
823 $file .= chr(((($c1 - ' ') & 077) << 4) | ((($c2 - ' ') & 077) >> 2));
829 if (($d + 1 <= $len) && ($pos + 2 <= strlen($str[$i]))) {
830 $c0 = (ord(substr($str[$i],$pos,1)) ^ 0x20);
831 $c1 = (ord(substr($str[$i],$pos+1,1)) ^ 0x20);
832 $file .= chr(((($c0 - ' ') & 077) << 2) | ((($c1 - ' ') & 077) >> 4));
836 $files[] = array('filename' => $filename, 'fileperm' => $fileperm, 'filedata' => $file);
843 * getSendArray() returns the arguments required for Mail::send()
844 * used to build the arguments for a mail::send() call
847 * $mailtext = Full email (for example generated by a template)
848 * $decoder = new Mail_mimeDecode($mailtext);
849 * $parts = $decoder->getSendArray();
850 * if (!PEAR::isError($parts) {
851 * list($recipents,$headers,$body) = $parts;
852 * $mail = Mail::factory('smtp');
853 * $mail->send($recipents,$headers,$body);
855 * echo $parts->message;
857 * @return mixed array of recipeint, headers,body or Pear_Error
859 * @author Alan Knowles <alan@akbkhome.com>
861 function getSendArray()
863 // prevent warning if this is not set
864 $this->_decode_headers = FALSE;
865 $headerlist =$this->_parseHeaders($this->_header);
868 return $this->raiseError("Message did not contain headers");
870 foreach($headerlist as $item) {
871 $header[$item['name']] = $item['value'];
872 switch (strtolower($item['name'])) {
876 $to .= ",".$item['value'];
882 return $this->raiseError("Message did not contain any recipents");
885 return array($to,$header,$this->_body);
889 * Returns a xml copy of the output of
890 * Mail_mimeDecode::decode. Pass the output in as the
891 * argument. This function can be called statically. Eg:
893 * $output = $obj->decode();
894 * $xml = Mail_mimeDecode::getXML($output);
896 * The DTD used for this should have been in the package. Or
897 * alternatively you can get it from cvs, or here:
898 * http://www.phpguru.org/xmail/xmail.dtd.
900 * @param object Input to convert to xml. This should be the
901 * output of the Mail_mimeDecode::decode function
902 * @return string XML version of input
905 function getXML($input)
908 $output = '<?xml version=\'1.0\'?>' . $crlf .
909 '<!DOCTYPE email SYSTEM "http://www.phpguru.org/xmail/xmail.dtd">' . $crlf .
911 Mail_mimeDecode::_getXML($input) .
918 * Function that does the actual conversion to xml. Does a single
919 * mimepart at a time.
921 * @param object Input to convert to xml. This is a mimepart object.
922 * It may or may not contain subparts.
923 * @param integer Number of tabs to indent
924 * @return string XML version of input
927 function _getXML($input, $indent = 1)
932 $headers = @(array)$input->headers;
934 foreach ($headers as $hdr_name => $hdr_value) {
936 // Multiple headers with this name
937 if (is_array($headers[$hdr_name])) {
938 for ($i = 0; $i < count($hdr_value); $i++) {
939 $output .= Mail_mimeDecode::_getXML_helper($hdr_name, $hdr_value[$i], $indent);
942 // Only one header of this sort
944 $output .= Mail_mimeDecode::_getXML_helper($hdr_name, $hdr_value, $indent);
948 if (!empty($input->parts)) {
949 for ($i = 0; $i < count($input->parts); $i++) {
950 $output .= $crlf . str_repeat($htab, $indent) . '<mimepart>' . $crlf .
951 Mail_mimeDecode::_getXML($input->parts[$i], $indent+1) .
952 str_repeat($htab, $indent) . '</mimepart>' . $crlf;
954 } elseif (isset($input->body)) {
955 $output .= $crlf . str_repeat($htab, $indent) . '<body><![CDATA[' .
956 $input->body . ']]></body>' . $crlf;
963 * Helper function to _getXML(). Returns xml of a header.
965 * @param string Name of header
966 * @param string Value of header
967 * @param integer Number of tabs to indent
968 * @return string XML version of input
971 function _getXML_helper($hdr_name, $hdr_value, $indent)
977 $new_hdr_value = ($hdr_name != 'received') ? Mail_mimeDecode::_parseHeaderValue($hdr_value) : array('value' => $hdr_value);
978 $new_hdr_name = str_replace(' ', '-', ucwords(str_replace('-', ' ', $hdr_name)));
980 // Sort out any parameters
981 if (!empty($new_hdr_value['other'])) {
982 foreach ($new_hdr_value['other'] as $paramname => $paramvalue) {
983 $params[] = str_repeat($htab, $indent) . $htab . '<parameter>' . $crlf .
984 str_repeat($htab, $indent) . $htab . $htab . '<paramname>' . htmlspecialchars($paramname) . '</paramname>' . $crlf .
985 str_repeat($htab, $indent) . $htab . $htab . '<paramvalue>' . htmlspecialchars($paramvalue) . '</paramvalue>' . $crlf .
986 str_repeat($htab, $indent) . $htab . '</parameter>' . $crlf;
989 $params = implode('', $params);
994 $return = str_repeat($htab, $indent) . '<header>' . $crlf .
995 str_repeat($htab, $indent) . $htab . '<headername>' . htmlspecialchars($new_hdr_name) . '</headername>' . $crlf .
996 str_repeat($htab, $indent) . $htab . '<headervalue>' . htmlspecialchars($new_hdr_value['value']) . '</headervalue>' . $crlf .
998 str_repeat($htab, $indent) . '</header>' . $crlf;