PageRenderTime 63ms CodeModel.GetById 30ms RepoModel.GetById 0ms app.codeStats 0ms

/include/pear/Mail/mimeDecode.php

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