mimeDecode.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807
  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. require_once 'PEAR.php';
  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.34 $
  66. * @package Mail
  67. */
  68. class Mail_mimeDecode extends PEAR
  69. {
  70. /**
  71. * The raw email to decode
  72. * @var string
  73. */
  74. var $_input;
  75. /**
  76. * The header part of the input
  77. * @var string
  78. */
  79. var $_header;
  80. /**
  81. * The body part of the input
  82. * @var string
  83. */
  84. var $_body;
  85. /**
  86. * If an error occurs, this is used to store the message
  87. * @var string
  88. */
  89. var $_error;
  90. /**
  91. * Flag to determine whether to include bodies in the
  92. * returned object.
  93. * @var boolean
  94. */
  95. var $_include_bodies;
  96. /**
  97. * Flag to determine whether to decode bodies
  98. * @var boolean
  99. */
  100. var $_decode_bodies;
  101. /**
  102. * Flag to determine whether to decode headers
  103. * @var boolean
  104. */
  105. var $_decode_headers;
  106. /**
  107. * If invoked from a class, $this will be set. This has problematic
  108. * connotations for calling decode() statically. Hence this variable
  109. * is used to determine if we are indeed being called statically or
  110. * via an object.
  111. */
  112. var $mailMimeDecode;
  113. /**
  114. * Constructor.
  115. *
  116. * Sets up the object, initialise the variables, and splits and
  117. * stores the header and body of the input.
  118. *
  119. * @param string The input to decode
  120. * @access public
  121. */
  122. function Mail_mimeDecode($input)
  123. {
  124. list($header, $body) = $this->_splitBodyHeader($input);
  125. $this->_input = $input;
  126. $this->_header = $header;
  127. $this->_body = $body;
  128. $this->_decode_bodies = false;
  129. $this->_include_bodies = true;
  130. $this->mailMimeDecode = true;
  131. }
  132. /**
  133. * Begins the decoding process. If called statically
  134. * it will create an object and call the decode() method
  135. * of it.
  136. *
  137. * @param array An array of various parameters that determine
  138. * various things:
  139. * include_bodies - Whether to include the body in the returned
  140. * object.
  141. * decode_bodies - Whether to decode the bodies
  142. * of the parts. (Transfer encoding)
  143. * decode_headers - Whether to decode headers
  144. * input - If called statically, this will be treated
  145. * as the input
  146. * @return object Decoded results
  147. * @access public
  148. */
  149. function decode($params = null)
  150. {
  151. // Have we been called statically? If so, create an object and pass details to that.
  152. if (!isset($this->mailMimeDecode) AND isset($params['input'])) {
  153. $obj = new Mail_mimeDecode($params['input']);
  154. $structure = $obj->decode($params);
  155. // Called statically but no input
  156. } elseif (!isset($this->mailMimeDecode)) {
  157. return PEAR::raiseError('Called statically and no input given');
  158. // Called via an object
  159. } else {
  160. $this->_include_bodies = isset($params['include_bodies']) ? $params['include_bodies'] : false;
  161. $this->_decode_bodies = isset($params['decode_bodies']) ? $params['decode_bodies'] : false;
  162. $this->_decode_headers = isset($params['decode_headers']) ? $params['decode_headers'] : false;
  163. $structure = $this->_decode($this->_header, $this->_body);
  164. if ($structure === false) {
  165. $structure = $this->raiseError($this->_error);
  166. }
  167. }
  168. return $structure;
  169. }
  170. /**
  171. * Performs the decoding. Decodes the body string passed to it
  172. * If it finds certain content-types it will call itself in a
  173. * recursive fashion
  174. *
  175. * @param string Header section
  176. * @param string Body section
  177. * @return object Results of decoding process
  178. * @access private
  179. */
  180. function _decode($headers, $body, $default_ctype = 'text/plain')
  181. {
  182. $return = new stdClass;
  183. $headers = $this->_parseHeaders($headers);
  184. foreach ($headers as $value) {
  185. if (isset($return->headers[strtolower($value['name'])]) AND !is_array($return->headers[strtolower($value['name'])])) {
  186. $return->headers[strtolower($value['name'])] = array($return->headers[strtolower($value['name'])]);
  187. $return->headers[strtolower($value['name'])][] = $value['value'];
  188. } elseif (isset($return->headers[strtolower($value['name'])])) {
  189. $return->headers[strtolower($value['name'])][] = $value['value'];
  190. } else {
  191. $return->headers[strtolower($value['name'])] = $value['value'];
  192. }
  193. }
  194. reset($headers);
  195. while (list($key, $value) = each($headers)) {
  196. $headers[$key]['name'] = strtolower($headers[$key]['name']);
  197. switch ($headers[$key]['name']) {
  198. case 'content-type':
  199. $content_type = $this->_parseHeaderValue($headers[$key]['value']);
  200. if (preg_match('/([0-9a-z+.-]+)\/([0-9a-z+.-]+)/i', $content_type['value'], $regs)) {
  201. $return->ctype_primary = $regs[1];
  202. $return->ctype_secondary = $regs[2];
  203. }
  204. if (isset($content_type['other'])) {
  205. while (list($p_name, $p_value) = each($content_type['other'])) {
  206. $return->ctype_parameters[$p_name] = $p_value;
  207. }
  208. }
  209. break;
  210. case 'content-disposition';
  211. $content_disposition = $this->_parseHeaderValue($headers[$key]['value']);
  212. $return->disposition = $content_disposition['value'];
  213. if (isset($content_disposition['other'])) {
  214. while (list($p_name, $p_value) = each($content_disposition['other'])) {
  215. $return->d_parameters[$p_name] = $p_value;
  216. }
  217. }
  218. break;
  219. case 'content-transfer-encoding':
  220. $content_transfer_encoding = $this->_parseHeaderValue($headers[$key]['value']);
  221. break;
  222. }
  223. }
  224. if (isset($content_type)) {
  225. switch (strtolower($content_type['value'])) {
  226. case 'text/plain':
  227. $encoding = isset($content_transfer_encoding) ? $content_transfer_encoding['value'] : '7bit';
  228. $this->_include_bodies ? $return->body = ($this->_decode_bodies ? $this->_decodeBody($body, $encoding) : $body) : null;
  229. break;
  230. case 'text/html':
  231. $encoding = isset($content_transfer_encoding) ? $content_transfer_encoding['value'] : '7bit';
  232. $this->_include_bodies ? $return->body = ($this->_decode_bodies ? $this->_decodeBody($body, $encoding) : $body) : null;
  233. break;
  234. case 'multipart/parallel':
  235. case 'multipart/report': // RFC1892
  236. case 'multipart/signed': // PGP
  237. case 'multipart/digest':
  238. case 'multipart/alternative':
  239. case 'multipart/related':
  240. case 'multipart/mixed':
  241. if(!isset($content_type['other']['boundary'])){
  242. $this->_error = 'No boundary found for ' . $content_type['value'] . ' part';
  243. return false;
  244. }
  245. $default_ctype = (strtolower($content_type['value']) === 'multipart/digest') ? 'message/rfc822' : 'text/plain';
  246. $parts = $this->_boundarySplit($body, $content_type['other']['boundary']);
  247. for ($i = 0; $i < count($parts); $i++) {
  248. list($part_header, $part_body) = $this->_splitBodyHeader($parts[$i]);
  249. $part = $this->_decode($part_header, $part_body, $default_ctype);
  250. if($part === false)
  251. $part = $this->raiseError($this->_error);
  252. $return->parts[] = $part;
  253. }
  254. break;
  255. case 'message/rfc822':
  256. $obj = &new Mail_mimeDecode($body);
  257. $return->parts[] = $obj->decode(array('include_bodies' => $this->_include_bodies));
  258. unset($obj);
  259. break;
  260. default:
  261. if(!isset($content_transfer_encoding['value']))
  262. $content_transfer_encoding['value'] = '7bit';
  263. $this->_include_bodies ? $return->body = ($this->_decode_bodies ? $this->_decodeBody($body, $content_transfer_encoding['value']) : $body) : null;
  264. break;
  265. }
  266. } else {
  267. $ctype = explode('/', $default_ctype);
  268. $return->ctype_primary = $ctype[0];
  269. $return->ctype_secondary = $ctype[1];
  270. $this->_include_bodies ? $return->body = ($this->_decode_bodies ? $this->_decodeBody($body) : $body) : null;
  271. }
  272. return $return;
  273. }
  274. /**
  275. * Given the output of the above function, this will return an
  276. * array of references to the parts, indexed by mime number.
  277. *
  278. * @param object $structure The structure to go through
  279. * @param string $mime_number Internal use only.
  280. * @return array Mime numbers
  281. */
  282. function &getMimeNumbers(&$structure, $no_refs = false, $mime_number = '', $prepend = '')
  283. {
  284. $return = array();
  285. if (!empty($structure->parts)) {
  286. if ($mime_number != '') {
  287. $structure->mime_id = $prepend . $mime_number;
  288. $return[$prepend . $mime_number] = &$structure;
  289. }
  290. for ($i = 0; $i < count($structure->parts); $i++) {
  291. if (!empty($structure->headers['content-type']) AND substr(strtolower($structure->headers['content-type']), 0, 8) == 'message/') {
  292. $prepend = $prepend . $mime_number . '.';
  293. $_mime_number = '';
  294. } else {
  295. $_mime_number = ($mime_number == '' ? $i + 1 : sprintf('%s.%s', $mime_number, $i + 1));
  296. }
  297. $arr = &Mail_mimeDecode::getMimeNumbers($structure->parts[$i], $no_refs, $_mime_number, $prepend);
  298. foreach ($arr as $key => $val) {
  299. $no_refs ? $return[$key] = '' : $return[$key] = &$arr[$key];
  300. }
  301. }
  302. } else {
  303. if ($mime_number == '') {
  304. $mime_number = '1';
  305. }
  306. $structure->mime_id = $prepend . $mime_number;
  307. $no_refs ? $return[$prepend . $mime_number] = '' : $return[$prepend . $mime_number] = &$structure;
  308. }
  309. return $return;
  310. }
  311. /**
  312. * Given a string containing a header and body
  313. * section, this function will split them (at the first
  314. * blank line) and return them.
  315. *
  316. * @param string Input to split apart
  317. * @return array Contains header and body section
  318. * @access private
  319. */
  320. function _splitBodyHeader($input)
  321. {
  322. if (preg_match("/^(.*?)\r?\n\r?\n(.*)/s", $input, $match)) {
  323. return array($match[1], $match[2]);
  324. }
  325. $this->_error = 'Could not split header and body';
  326. return false;
  327. }
  328. /**
  329. * Parse headers given in $input and return
  330. * as assoc array.
  331. *
  332. * @param string Headers to parse
  333. * @return array Contains parsed headers
  334. * @access private
  335. */
  336. function _parseHeaders($input)
  337. {
  338. if ($input !== '') {
  339. // Unfold the input
  340. $input = preg_replace("/\r?\n/", "\r\n", $input);
  341. $input = preg_replace("/\r\n(\t| )+/", ' ', $input);
  342. $headers = explode("\r\n", trim($input));
  343. foreach ($headers as $value) {
  344. $hdr_name = substr($value, 0, $pos = strpos($value, ':'));
  345. $hdr_value = substr($value, $pos+1);
  346. if($hdr_value[0] == ' ')
  347. $hdr_value = substr($hdr_value, 1);
  348. $return[] = array(
  349. 'name' => $hdr_name,
  350. 'value' => $this->_decode_headers ? $this->_decodeHeader($hdr_value) : $hdr_value
  351. );
  352. }
  353. } else {
  354. $return = array();
  355. }
  356. return $return;
  357. }
  358. /**
  359. * Function to parse a header value,
  360. * extract first part, and any secondary
  361. * parts (after ;) This function is not as
  362. * robust as it could be. Eg. header comments
  363. * in the wrong place will probably break it.
  364. *
  365. * @param string Header value to parse
  366. * @return array Contains parsed result
  367. * @access private
  368. */
  369. function _parseHeaderValue($input)
  370. {
  371. if (($pos = strpos($input, ';')) !== false) {
  372. $return['value'] = trim(substr($input, 0, $pos));
  373. $input = trim(substr($input, $pos+1));
  374. if (strlen($input) > 0) {
  375. // This splits on a semi-colon, if there's no preceeding backslash
  376. // Can't handle if it's in double quotes however. (Of course anyone
  377. // sending that needs a good slap).
  378. $parameters = preg_split('/\s*(?<!\\\\);\s*/i', $input);
  379. for ($i = 0; $i < count($parameters); $i++) {
  380. $param_name = substr($parameters[$i], 0, $pos = strpos($parameters[$i], '='));
  381. $param_value = substr($parameters[$i], $pos + 1);
  382. if ($param_value[0] == '"') {
  383. $param_value = substr($param_value, 1, -1);
  384. }
  385. $return['other'][$param_name] = $param_value;
  386. $return['other'][strtolower($param_name)] = $param_value;
  387. }
  388. }
  389. } else {
  390. $return['value'] = trim($input);
  391. }
  392. return $return;
  393. }
  394. /**
  395. * This function splits the input based
  396. * on the given boundary
  397. *
  398. * @param string Input to parse
  399. * @return array Contains array of resulting mime parts
  400. * @access private
  401. */
  402. function _boundarySplit($input, $boundary)
  403. {
  404. $tmp = explode('--'.$boundary, $input);
  405. for ($i=1; $i<count($tmp)-1; $i++) {
  406. $parts[] = $tmp[$i];
  407. }
  408. return $parts;
  409. }
  410. /**
  411. * Given a header, this function will decode it
  412. * according to RFC2047. Probably not *exactly*
  413. * conformant, but it does pass all the given
  414. * examples (in RFC2047).
  415. *
  416. * @param string Input header value to decode
  417. * @return string Decoded header value
  418. * @access private
  419. */
  420. function _decodeHeader($input)
  421. {
  422. // Remove white space between encoded-words
  423. $input = preg_replace('/(=\?[^?]+\?(q|b)\?[^?]*\?=)(\s)+=\?/i', '\1=?', $input);
  424. // For each encoded-word...
  425. while (preg_match('/(=\?([^?]+)\?(q|b)\?([^?]*)\?=)/i', $input, $matches)) {
  426. $encoded = $matches[1];
  427. $charset = $matches[2];
  428. $encoding = $matches[3];
  429. $text = $matches[4];
  430. switch (strtolower($encoding)) {
  431. case 'b':
  432. $text = base64_decode($text);
  433. break;
  434. case 'q':
  435. $text = str_replace('_', ' ', $text);
  436. preg_match_all('/=([a-f0-9]{2})/i', $text, $matches);
  437. foreach($matches[1] as $value)
  438. $text = str_replace('='.$value, chr(hexdec($value)), $text);
  439. break;
  440. }
  441. $input = str_replace($encoded, $text, $input);
  442. }
  443. return $input;
  444. }
  445. /**
  446. * Given a body string and an encoding type,
  447. * this function will decode and return it.
  448. *
  449. * @param string Input body to decode
  450. * @param string Encoding type to use.
  451. * @return string Decoded body
  452. * @access private
  453. */
  454. function _decodeBody($input, $encoding = '7bit')
  455. {
  456. switch ($encoding) {
  457. case '7bit':
  458. return $input;
  459. break;
  460. case 'quoted-printable':
  461. return $this->_quotedPrintableDecode($input);
  462. break;
  463. case 'base64':
  464. return base64_decode($input);
  465. break;
  466. default:
  467. return $input;
  468. }
  469. }
  470. /**
  471. * Given a quoted-printable string, this
  472. * function will decode and return it.
  473. *
  474. * @param string Input body to decode
  475. * @return string Decoded body
  476. * @access private
  477. */
  478. function _quotedPrintableDecode($input)
  479. {
  480. // Remove soft line breaks
  481. $input = preg_replace("/=\r?\n/", '', $input);
  482. // Replace encoded characters
  483. $input = preg_replace('/=([a-f0-9]{2})/ie', "chr(hexdec('\\1'))", $input);
  484. return $input;
  485. }
  486. /**
  487. * Checks the input for uuencoded files and returns
  488. * an array of them. Can be called statically, eg:
  489. *
  490. * $files =& Mail_mimeDecode::uudecode($some_text);
  491. *
  492. * It will check for the begin 666 ... end syntax
  493. * however and won't just blindly decode whatever you
  494. * pass it.
  495. *
  496. * @param string Input body to look for attahcments in
  497. * @return array Decoded bodies, filenames and permissions
  498. * @access public
  499. * @author Unknown
  500. */
  501. function &uudecode($input)
  502. {
  503. // Find all uuencoded sections
  504. preg_match_all("/begin ([0-7]{3}) (.+)\r?\n(.+)\r?\nend/Us", $input, $matches);
  505. for ($j = 0; $j < count($matches[3]); $j++) {
  506. $str = $matches[3][$j];
  507. $filename = $matches[2][$j];
  508. $fileperm = $matches[1][$j];
  509. $file = '';
  510. $str = preg_split("/\r?\n/", trim($str));
  511. $strlen = count($str);
  512. for ($i = 0; $i < $strlen; $i++) {
  513. $pos = 1;
  514. $d = 0;
  515. $len=(int)(((ord(substr($str[$i],0,1)) -32) - ' ') & 077);
  516. while (($d + 3 <= $len) AND ($pos + 4 <= strlen($str[$i]))) {
  517. $c0 = (ord(substr($str[$i],$pos,1)) ^ 0x20);
  518. $c1 = (ord(substr($str[$i],$pos+1,1)) ^ 0x20);
  519. $c2 = (ord(substr($str[$i],$pos+2,1)) ^ 0x20);
  520. $c3 = (ord(substr($str[$i],$pos+3,1)) ^ 0x20);
  521. $file .= chr(((($c0 - ' ') & 077) << 2) | ((($c1 - ' ') & 077) >> 4));
  522. $file .= chr(((($c1 - ' ') & 077) << 4) | ((($c2 - ' ') & 077) >> 2));
  523. $file .= chr(((($c2 - ' ') & 077) << 6) | (($c3 - ' ') & 077));
  524. $pos += 4;
  525. $d += 3;
  526. }
  527. if (($d + 2 <= $len) && ($pos + 3 <= strlen($str[$i]))) {
  528. $c0 = (ord(substr($str[$i],$pos,1)) ^ 0x20);
  529. $c1 = (ord(substr($str[$i],$pos+1,1)) ^ 0x20);
  530. $c2 = (ord(substr($str[$i],$pos+2,1)) ^ 0x20);
  531. $file .= chr(((($c0 - ' ') & 077) << 2) | ((($c1 - ' ') & 077) >> 4));
  532. $file .= chr(((($c1 - ' ') & 077) << 4) | ((($c2 - ' ') & 077) >> 2));
  533. $pos += 3;
  534. $d += 2;
  535. }
  536. if (($d + 1 <= $len) && ($pos + 2 <= strlen($str[$i]))) {
  537. $c0 = (ord(substr($str[$i],$pos,1)) ^ 0x20);
  538. $c1 = (ord(substr($str[$i],$pos+1,1)) ^ 0x20);
  539. $file .= chr(((($c0 - ' ') & 077) << 2) | ((($c1 - ' ') & 077) >> 4));
  540. }
  541. }
  542. $files[] = array('filename' => $filename, 'fileperm' => $fileperm, 'filedata' => $file);
  543. }
  544. return $files;
  545. }
  546. /**
  547. * getSendArray() returns the arguments required for Mail::send()
  548. * used to build the arguments for a mail::send() call
  549. *
  550. * Usage:
  551. * $mailtext = Full email (for example generated by a template)
  552. * $decoder = new Mail_mimeDecode($mailtext);
  553. * $parts = $decoder->getSendArray();
  554. * if (!PEAR::isError($parts) {
  555. * list($recipents,$headers,$body) = $parts;
  556. * $mail = Mail::factory('smtp');
  557. * $mail->send($recipents,$headers,$body);
  558. * } else {
  559. * echo $parts->message;
  560. * }
  561. * @return mixed array of recipeint, headers,body or Pear_Error
  562. * @access public
  563. * @author Alan Knowles <alan@akbkhome.com>
  564. */
  565. function getSendArray()
  566. {
  567. // prevent warning if this is not set
  568. $this->_decode_headers = FALSE;
  569. $headerlist =$this->_parseHeaders($this->_header);
  570. $to = "";
  571. if (!$headerlist) {
  572. return $this->raiseError("Message did not contain headers");
  573. }
  574. foreach($headerlist as $item) {
  575. $header[$item['name']] = $item['value'];
  576. switch (strtolower($item['name'])) {
  577. case "to":
  578. case "cc":
  579. case "bcc":
  580. $to = ",".$item['value'];
  581. default:
  582. break;
  583. }
  584. }
  585. if ($to == "") {
  586. return $this->raiseError("Message did not contain any recipents");
  587. }
  588. $to = substr($to,1);
  589. return array($to,$header,$this->_body);
  590. }
  591. /**
  592. * Returns a xml copy of the output of
  593. * Mail_mimeDecode::decode. Pass the output in as the
  594. * argument. This function can be called statically. Eg:
  595. *
  596. * $output = $obj->decode();
  597. * $xml = Mail_mimeDecode::getXML($output);
  598. *
  599. * The DTD used for this should have been in the package. Or
  600. * alternatively you can get it from cvs, or here:
  601. * http://www.phpguru.org/xmail/xmail.dtd.
  602. *
  603. * @param object Input to convert to xml. This should be the
  604. * output of the Mail_mimeDecode::decode function
  605. * @return string XML version of input
  606. * @access public
  607. */
  608. function getXML($input)
  609. {
  610. $crlf = "\r\n";
  611. $output = '<?xml version=\'1.0\'?>' . $crlf .
  612. '<!DOCTYPE email SYSTEM "http://www.phpguru.org/xmail/xmail.dtd">' . $crlf .
  613. '<email>' . $crlf .
  614. Mail_mimeDecode::_getXML($input) .
  615. '</email>';
  616. return $output;
  617. }
  618. /**
  619. * Function that does the actual conversion to xml. Does a single
  620. * mimepart at a time.
  621. *
  622. * @param object Input to convert to xml. This is a mimepart object.
  623. * It may or may not contain subparts.
  624. * @param integer Number of tabs to indent
  625. * @return string XML version of input
  626. * @access private
  627. */
  628. function _getXML($input, $indent = 1)
  629. {
  630. $htab = "\t";
  631. $crlf = "\r\n";
  632. $output = '';
  633. $headers = @(array)$input->headers;
  634. foreach ($headers as $hdr_name => $hdr_value) {
  635. // Multiple headers with this name
  636. if (is_array($headers[$hdr_name])) {
  637. for ($i = 0; $i < count($hdr_value); $i++) {
  638. $output .= Mail_mimeDecode::_getXML_helper($hdr_name, $hdr_value[$i], $indent);
  639. }
  640. // Only one header of this sort
  641. } else {
  642. $output .= Mail_mimeDecode::_getXML_helper($hdr_name, $hdr_value, $indent);
  643. }
  644. }
  645. if (!empty($input->parts)) {
  646. for ($i = 0; $i < count($input->parts); $i++) {
  647. $output .= $crlf . str_repeat($htab, $indent) . '<mimepart>' . $crlf .
  648. Mail_mimeDecode::_getXML($input->parts[$i], $indent+1) .
  649. str_repeat($htab, $indent) . '</mimepart>' . $crlf;
  650. }
  651. } elseif (isset($input->body)) {
  652. $output .= $crlf . str_repeat($htab, $indent) . '<body><![CDATA[' .
  653. $input->body . ']]></body>' . $crlf;
  654. }
  655. return $output;
  656. }
  657. /**
  658. * Helper function to _getXML(). Returns xml of a header.
  659. *
  660. * @param string Name of header
  661. * @param string Value of header
  662. * @param integer Number of tabs to indent
  663. * @return string XML version of input
  664. * @access private
  665. */
  666. function _getXML_helper($hdr_name, $hdr_value, $indent)
  667. {
  668. $htab = "\t";
  669. $crlf = "\r\n";
  670. $return = '';
  671. $new_hdr_value = ($hdr_name != 'received') ? Mail_mimeDecode::_parseHeaderValue($hdr_value) : array('value' => $hdr_value);
  672. $new_hdr_name = str_replace(' ', '-', ucwords(str_replace('-', ' ', $hdr_name)));
  673. // Sort out any parameters
  674. if (!empty($new_hdr_value['other'])) {
  675. foreach ($new_hdr_value['other'] as $paramname => $paramvalue) {
  676. $params[] = str_repeat($htab, $indent) . $htab . '<parameter>' . $crlf .
  677. str_repeat($htab, $indent) . $htab . $htab . '<paramname>' . htmlspecialchars($paramname) . '</paramname>' . $crlf .
  678. str_repeat($htab, $indent) . $htab . $htab . '<paramvalue>' . htmlspecialchars($paramvalue) . '</paramvalue>' . $crlf .
  679. str_repeat($htab, $indent) . $htab . '</parameter>' . $crlf;
  680. }
  681. $params = implode('', $params);
  682. } else {
  683. $params = '';
  684. }
  685. $return = str_repeat($htab, $indent) . '<header>' . $crlf .
  686. str_repeat($htab, $indent) . $htab . '<headername>' . htmlspecialchars($new_hdr_name) . '</headername>' . $crlf .
  687. str_repeat($htab, $indent) . $htab . '<headervalue>' . htmlspecialchars($new_hdr_value['value']) . '</headervalue>' . $crlf .
  688. $params .
  689. str_repeat($htab, $indent) . '</header>' . $crlf;
  690. return $return;
  691. }
  692. } // End of class
  693. ?>