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