PageRenderTime 703ms CodeModel.GetById 81ms app.highlight 465ms RepoModel.GetById 80ms app.codeStats 1ms

/htdocs/includes/nusoap/lib/Mail/mimeDecode.php

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