PageRenderTime 56ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/zpush/include/mimeDecode.php

https://github.com/muchael/expressolivre
PHP | 1060 lines | 554 code | 123 blank | 383 comment | 100 complexity | 77d88fcf06e0b7be396b8d41aa0e7f30 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1, BSD-2-Clause, BSD-3-Clause, AGPL-3.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 305875 2010-12-01 07:17:10Z alan_k $
  56. * @link http://pear.php.net/package/Mail_mime
  57. */
  58. /**
  59. * Z-Push changes
  60. *
  61. * removed PEAR dependency by implementing own raiseError()
  62. * implemented automated decoding of strings from mail charset
  63. *
  64. * Reference implementation used:
  65. * http://download.pear.php.net/package/Mail_mimeDecode-1.5.5.tgz
  66. *
  67. * used "old" method of checking if called statically, as this is deprecated between php 5.0.0 and 5.3.0
  68. * (isStatic of decode() around line 215)
  69. *
  70. */
  71. /**
  72. * require PEAR
  73. *
  74. * This package depends on PEAR to raise errors.
  75. */
  76. //require_once 'PEAR.php';
  77. /**
  78. * The Mail_mimeDecode class is used to decode mail/mime messages
  79. *
  80. * This class will parse a raw mime email and return the structure.
  81. * Returned structure is similar to that returned by imap_fetchstructure().
  82. *
  83. * +----------------------------- IMPORTANT ------------------------------+
  84. * | Usage of this class compared to native php extensions such as |
  85. * | mailparse or imap, is slow and may be feature deficient. If available|
  86. * | you are STRONGLY recommended to use the php extensions. |
  87. * +----------------------------------------------------------------------+
  88. *
  89. * @category Mail
  90. * @package Mail_Mime
  91. * @author Richard Heyes <richard@phpguru.org>
  92. * @author George Schlossnagle <george@omniti.com>
  93. * @author Cipriano Groenendal <cipri@php.net>
  94. * @author Sean Coates <sean@php.net>
  95. * @copyright 2003-2006 PEAR <pear-group@php.net>
  96. * @license http://www.opensource.org/licenses/bsd-license.php BSD License
  97. * @version Release: @package_version@
  98. * @link http://pear.php.net/package/Mail_mime
  99. */
  100. class Mail_mimeDecode
  101. {
  102. /**
  103. * The raw email to decode
  104. *
  105. * @var string
  106. * @access private
  107. */
  108. var $_input;
  109. /**
  110. * The header part of the input
  111. *
  112. * @var string
  113. * @access private
  114. */
  115. var $_header;
  116. /**
  117. * The body part of the input
  118. *
  119. * @var string
  120. * @access private
  121. */
  122. var $_body;
  123. /**
  124. * If an error occurs, this is used to store the message
  125. *
  126. * @var string
  127. * @access private
  128. */
  129. var $_error;
  130. /**
  131. * Flag to determine whether to include bodies in the
  132. * returned object.
  133. *
  134. * @var boolean
  135. * @access private
  136. */
  137. var $_include_bodies;
  138. /**
  139. * Flag to determine whether to decode bodies
  140. *
  141. * @var boolean
  142. * @access private
  143. */
  144. var $_decode_bodies;
  145. /**
  146. * Flag to determine whether to decode headers
  147. *
  148. * @var boolean
  149. * @access private
  150. */
  151. var $_decode_headers;
  152. /**
  153. * Flag to determine whether to include attached messages
  154. * as body in the returned object. Depends on $_include_bodies
  155. *
  156. * @var boolean
  157. * @access private
  158. */
  159. var $_rfc822_bodies;
  160. /**
  161. * Constructor.
  162. *
  163. * Sets up the object, initialise the variables, and splits and
  164. * stores the header and body of the input.
  165. *
  166. * @param string The input to decode
  167. * @access public
  168. */
  169. function Mail_mimeDecode($input, $deprecated_linefeed = '')
  170. {
  171. list($header, $body) = $this->_splitBodyHeader($input);
  172. $this->_input = $input;
  173. $this->_header = $header;
  174. $this->_body = $body;
  175. $this->_decode_bodies = false;
  176. $this->_include_bodies = true;
  177. $this->_rfc822_bodies = false;
  178. }
  179. /**
  180. * Begins the decoding process. If called statically
  181. * it will create an object and call the decode() method
  182. * of it.
  183. *
  184. * @param array An array of various parameters that determine
  185. * various things:
  186. * include_bodies - Whether to include the body in the returned
  187. * object.
  188. * decode_bodies - Whether to decode the bodies
  189. * of the parts. (Transfer encoding)
  190. * decode_headers - Whether to decode headers
  191. * input - If called statically, this will be treated
  192. * as the input
  193. * charset - convert all data to this charset
  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. // Have we been called statically?
  202. // If so, create an object and pass details to that.
  203. if ($isStatic AND isset($params['input'])) {
  204. $obj = new Mail_mimeDecode($params['input']);
  205. $structure = $obj->decode($params);
  206. // Called statically but no input
  207. } elseif ($isStatic) {
  208. return $this->raiseError('Called statically and no input given');
  209. // Called via an object
  210. } else {
  211. $this->_include_bodies = isset($params['include_bodies']) ?
  212. $params['include_bodies'] : false;
  213. $this->_decode_bodies = isset($params['decode_bodies']) ?
  214. $params['decode_bodies'] : false;
  215. $this->_decode_headers = isset($params['decode_headers']) ?
  216. $params['decode_headers'] : false;
  217. $this->_rfc822_bodies = isset($params['rfc_822bodies']) ?
  218. $params['rfc_822bodies'] : false;
  219. $this->_charset = isset($params['charset']) ?
  220. strtolower($params['charset']) : 'utf-8';
  221. $structure = $this->_decode($this->_header, $this->_body);
  222. if ($structure === false) {
  223. $structure = $this->raiseError($this->_error);
  224. }
  225. }
  226. return $structure;
  227. }
  228. /**
  229. * Performs the decoding. Decodes the body string passed to it
  230. * If it finds certain content-types it will call itself in a
  231. * recursive fashion
  232. *
  233. * @param string Header section
  234. * @param string Body section
  235. * @return object Results of decoding process
  236. * @access private
  237. */
  238. function _decode($headers, $body, $default_ctype = 'text/plain')
  239. {
  240. $return = new stdClass;
  241. $return->headers = array();
  242. $headers = $this->_parseHeaders($headers);
  243. foreach ($headers as $value) {
  244. $value['value'] = $this->_decode_headers ? $this->_decodeHeader($value['value']) : $value['value'];
  245. if (isset($return->headers[strtolower($value['name'])]) AND !is_array($return->headers[strtolower($value['name'])])) {
  246. $return->headers[strtolower($value['name'])] = array($return->headers[strtolower($value['name'])]);
  247. $return->headers[strtolower($value['name'])][] = $value['value'];
  248. } elseif (isset($return->headers[strtolower($value['name'])])) {
  249. $return->headers[strtolower($value['name'])][] = $value['value'];
  250. } else {
  251. $return->headers[strtolower($value['name'])] = $value['value'];
  252. }
  253. }
  254. foreach ($headers as $key => $value) {
  255. $headers[$key]['name'] = strtolower($headers[$key]['name']);
  256. switch ($headers[$key]['name']) {
  257. case 'content-type':
  258. $content_type = $this->_parseHeaderValue($headers[$key]['value']);
  259. if (preg_match('/([0-9a-z+.-]+)\/([0-9a-z+.-]+)/i', $content_type['value'], $regs)) {
  260. $return->ctype_primary = $regs[1];
  261. $return->ctype_secondary = $regs[2];
  262. }
  263. if (isset($content_type['other'])) {
  264. foreach($content_type['other'] as $p_name => $p_value) {
  265. $return->ctype_parameters[$p_name] = $p_value;
  266. }
  267. }
  268. break;
  269. case 'content-disposition':
  270. $content_disposition = $this->_parseHeaderValue($headers[$key]['value']);
  271. $return->disposition = $content_disposition['value'];
  272. if (isset($content_disposition['other'])) {
  273. foreach($content_disposition['other'] as $p_name => $p_value) {
  274. $return->d_parameters[$p_name] = $p_value;
  275. }
  276. }
  277. break;
  278. case 'content-transfer-encoding':
  279. $content_transfer_encoding = $this->_parseHeaderValue($headers[$key]['value']);
  280. break;
  281. }
  282. }
  283. if (isset($content_type)) {
  284. switch (strtolower($content_type['value'])) {
  285. case 'text/plain':
  286. $encoding = isset($content_transfer_encoding) ? $content_transfer_encoding['value'] : '7bit';
  287. $charset = isset($return->ctype_parameters['charset']) ? $return->ctype_parameters['charset'] : $this->_charset;
  288. $this->_include_bodies ? $return->body = ($this->_decode_bodies ? $this->_decodeBody($body, $encoding, $charset) : $body) : null;
  289. break;
  290. case 'text/html':
  291. $encoding = isset($content_transfer_encoding) ? $content_transfer_encoding['value'] : '7bit';
  292. $charset = isset($return->ctype_parameters['charset']) ? $return->ctype_parameters['charset'] : $this->_charset;
  293. $this->_include_bodies ? $return->body = ($this->_decode_bodies ? $this->_decodeBody($body, $encoding, $charset) : $body) : null;
  294. break;
  295. case 'multipart/parallel':
  296. case 'multipart/appledouble': // Appledouble mail
  297. case 'multipart/report': // RFC1892
  298. case 'multipart/signed': // PGP
  299. case 'multipart/digest':
  300. case 'multipart/alternative':
  301. case 'multipart/related':
  302. case 'multipart/mixed':
  303. case 'application/vnd.wap.multipart.related':
  304. if(!isset($content_type['other']['boundary'])){
  305. $this->_error = 'No boundary found for ' . $content_type['value'] . ' part';
  306. return false;
  307. }
  308. $default_ctype = (strtolower($content_type['value']) === 'multipart/digest') ? 'message/rfc822' : 'text/plain';
  309. $parts = $this->_boundarySplit($body, $content_type['other']['boundary']);
  310. for ($i = 0; $i < count($parts); $i++) {
  311. list($part_header, $part_body) = $this->_splitBodyHeader($parts[$i]);
  312. $part = $this->_decode($part_header, $part_body, $default_ctype);
  313. if($part === false)
  314. $part = $this->raiseError($this->_error);
  315. $return->parts[] = $part;
  316. }
  317. break;
  318. case 'message/rfc822':
  319. if ($this->_rfc822_bodies) {
  320. $encoding = isset($content_transfer_encoding) ? $content_transfer_encoding['value'] : '7bit';
  321. $charset = isset($return->ctype_parameters['charset']) ? $return->ctype_parameters['charset'] : $this->_charset;
  322. $return->body = ($this->_decode_bodies ? $this->_decodeBody($body, $encoding, $charset) : $body);
  323. }
  324. $obj = new Mail_mimeDecode($body);
  325. $return->parts[] = $obj->decode(array('include_bodies' => $this->_include_bodies,
  326. 'decode_bodies' => $this->_decode_bodies,
  327. 'decode_headers' => $this->_decode_headers));
  328. unset($obj);
  329. break;
  330. default:
  331. if(!isset($content_transfer_encoding['value']))
  332. $content_transfer_encoding['value'] = '7bit';
  333. // if there is no explicit charset, then don't try to convert to default charset, and make sure that only text mimetypes are converted
  334. $charset = (isset($return->ctype_parameters['charset']) && ((isset($return->ctype_primary) && $return->ctype_primary == 'text') || !isset($return->ctype_primary)) )? $return->ctype_parameters['charset']: '';
  335. $this->_include_bodies ? $return->body = ($this->_decode_bodies ? $this->_decodeBody($body, $content_transfer_encoding['value'], $charset) : $body) : null;
  336. break;
  337. }
  338. } else {
  339. $ctype = explode('/', $default_ctype);
  340. $return->ctype_primary = $ctype[0];
  341. $return->ctype_secondary = $ctype[1];
  342. $this->_include_bodies ? $return->body = ($this->_decode_bodies ? $this->_decodeBody($body) : $body) : null;
  343. }
  344. return $return;
  345. }
  346. /**
  347. * Given the output of the above function, this will return an
  348. * array of references to the parts, indexed by mime number.
  349. *
  350. * @param object $structure The structure to go through
  351. * @param string $mime_number Internal use only.
  352. * @return array Mime numbers
  353. */
  354. function &getMimeNumbers(&$structure, $no_refs = false, $mime_number = '', $prepend = '')
  355. {
  356. $return = array();
  357. if (!empty($structure->parts)) {
  358. if ($mime_number != '') {
  359. $structure->mime_id = $prepend . $mime_number;
  360. $return[$prepend . $mime_number] = &$structure;
  361. }
  362. for ($i = 0; $i < count($structure->parts); $i++) {
  363. if (!empty($structure->headers['content-type']) AND substr(strtolower($structure->headers['content-type']), 0, 8) == 'message/') {
  364. $prepend = $prepend . $mime_number . '.';
  365. $_mime_number = '';
  366. } else {
  367. $_mime_number = ($mime_number == '' ? $i + 1 : sprintf('%s.%s', $mime_number, $i + 1));
  368. }
  369. $arr = &Mail_mimeDecode::getMimeNumbers($structure->parts[$i], $no_refs, $_mime_number, $prepend);
  370. foreach ($arr as $key => $val) {
  371. $no_refs ? $return[$key] = '' : $return[$key] = &$arr[$key];
  372. }
  373. }
  374. } else {
  375. if ($mime_number == '') {
  376. $mime_number = '1';
  377. }
  378. $structure->mime_id = $prepend . $mime_number;
  379. $no_refs ? $return[$prepend . $mime_number] = '' : $return[$prepend . $mime_number] = &$structure;
  380. }
  381. return $return;
  382. }
  383. /**
  384. * Given a string containing a header and body
  385. * section, this function will split them (at the first
  386. * blank line) and return them.
  387. *
  388. * @param string Input to split apart
  389. * @return array Contains header and body section
  390. * @access private
  391. */
  392. function _splitBodyHeader($input)
  393. {
  394. if (preg_match("/^(.*?)\r?\n\r?\n(.*)/s", $input, $match)) {
  395. return array($match[1], $match[2]);
  396. }
  397. // bug #17325 - empty bodies are allowed. - we just check that at least one line
  398. // of headers exist..
  399. if (count(explode("\n",$input))) {
  400. return array($input, '');
  401. }
  402. $this->_error = 'Could not split header and body';
  403. return false;
  404. }
  405. /**
  406. * Parse headers given in $input and return
  407. * as assoc array.
  408. *
  409. * @param string Headers to parse
  410. * @return array Contains parsed headers
  411. * @access private
  412. */
  413. function _parseHeaders($input)
  414. {
  415. if ($input !== '') {
  416. // Unfold the input
  417. $input = preg_replace("/\r?\n/", "\r\n", $input);
  418. //#7065 - wrapping.. with encoded stuff.. - probably not needed,
  419. // wrapping space should only get removed if the trailing item on previous line is a
  420. // encoded character
  421. $input = preg_replace("/=\r\n(\t| )+/", '=', $input);
  422. $input = preg_replace("/\r\n(\t| )+/", ' ', $input);
  423. $headers = explode("\r\n", trim($input));
  424. foreach ($headers as $value) {
  425. $hdr_name = substr($value, 0, $pos = strpos($value, ':'));
  426. $hdr_value = substr($value, $pos+1);
  427. if($hdr_value[0] == ' ')
  428. $hdr_value = substr($hdr_value, 1);
  429. $return[] = array(
  430. 'name' => $hdr_name,
  431. 'value' => $hdr_value
  432. );
  433. }
  434. } else {
  435. $return = array();
  436. }
  437. return $return;
  438. }
  439. /**
  440. * Function to parse a header value,
  441. * extract first part, and any secondary
  442. * parts (after ;) This function is not as
  443. * robust as it could be. Eg. header comments
  444. * in the wrong place will probably break it.
  445. *
  446. * @param string Header value to parse
  447. * @return array Contains parsed result
  448. * @access private
  449. */
  450. function _parseHeaderValue($input)
  451. {
  452. if (($pos = strpos($input, ';')) === false) {
  453. $input = $this->_decode_headers ? $this->_decodeHeader($input) : $input;
  454. $return['value'] = trim($input);
  455. return $return;
  456. }
  457. $value = substr($input, 0, $pos);
  458. $value = $this->_decode_headers ? $this->_decodeHeader($value) : $value;
  459. $return['value'] = trim($value);
  460. $input = trim(substr($input, $pos+1));
  461. if (!strlen($input) > 0) {
  462. return $return;
  463. }
  464. // at this point input contains xxxx=".....";zzzz="...."
  465. // since we are dealing with quoted strings, we need to handle this properly..
  466. $i = 0;
  467. $l = strlen($input);
  468. $key = '';
  469. $val = false; // our string - including quotes..
  470. $q = false; // in quote..
  471. $lq = ''; // last quote..
  472. while ($i < $l) {
  473. $c = $input[$i];
  474. //var_dump(array('i'=>$i,'c'=>$c,'q'=>$q, 'lq'=>$lq, 'key'=>$key, 'val' =>$val));
  475. $escaped = false;
  476. if ($c == '\\') {
  477. $i++;
  478. if ($i == $l-1) { // end of string.
  479. break;
  480. }
  481. $escaped = true;
  482. $c = $input[$i];
  483. }
  484. // state - in key..
  485. if ($val === false) {
  486. if (!$escaped && $c == '=') {
  487. $val = '';
  488. $key = trim($key);
  489. $i++;
  490. continue;
  491. }
  492. if (!$escaped && $c == ';') {
  493. if ($key) { // a key without a value..
  494. $key= trim($key);
  495. $return['other'][$key] = '';
  496. $return['other'][strtolower($key)] = '';
  497. }
  498. $key = '';
  499. }
  500. $key .= $c;
  501. $i++;
  502. continue;
  503. }
  504. // state - in value.. (as $val is set..)
  505. if ($q === false) {
  506. // not in quote yet.
  507. if ((!strlen($val) || $lq !== false) && $c == ' ' || $c == "\t") {
  508. $i++;
  509. continue; // skip leading spaces after '=' or after '"'
  510. }
  511. if (!$escaped && ($c == '"' || $c == "'")) {
  512. // start quoted area..
  513. $q = $c;
  514. // in theory should not happen raw text in value part..
  515. // but we will handle it as a merged part of the string..
  516. $val = !strlen(trim($val)) ? '' : trim($val);
  517. $i++;
  518. continue;
  519. }
  520. // got end....
  521. if (!$escaped && $c == ';') {
  522. $val = trim($val);
  523. $added = false;
  524. if (preg_match('/\*[0-9]+$/', $key)) {
  525. // this is the extended aaa*0=...;aaa*1=.... code
  526. // it assumes the pieces arrive in order, and are valid...
  527. $key = preg_replace('/\*[0-9]+$/', '', $key);
  528. if (isset($return['other'][$key])) {
  529. $return['other'][$key] .= $val;
  530. if (strtolower($key) != $key) {
  531. $return['other'][strtolower($key)] .= $val;
  532. }
  533. $added = true;
  534. }
  535. // continue and use standard setters..
  536. }
  537. if (!$added) {
  538. $return['other'][$key] = $val;
  539. $return['other'][strtolower($key)] = $val;
  540. }
  541. $val = false;
  542. $key = '';
  543. $lq = false;
  544. $i++;
  545. continue;
  546. }
  547. $val .= $c;
  548. $i++;
  549. continue;
  550. }
  551. // state - in quote..
  552. if (!$escaped && $c == $q) { // potential exit state..
  553. // end of quoted string..
  554. $lq = $q;
  555. $q = false;
  556. $i++;
  557. continue;
  558. }
  559. // normal char inside of quoted string..
  560. $val.= $c;
  561. $i++;
  562. }
  563. // do we have anything left..
  564. if (strlen(trim($key)) || $val !== false) {
  565. $val = trim($val);
  566. $added = false;
  567. if ($val !== false && preg_match('/\*[0-9]+$/', $key)) {
  568. // no dupes due to our crazy regexp.
  569. $key = preg_replace('/\*[0-9]+$/', '', $key);
  570. if (isset($return['other'][$key])) {
  571. $return['other'][$key] .= $val;
  572. if (strtolower($key) != $key) {
  573. $return['other'][strtolower($key)] .= $val;
  574. }
  575. $added = true;
  576. }
  577. // continue and use standard setters..
  578. }
  579. if (!$added) {
  580. $return['other'][$key] = $val;
  581. $return['other'][strtolower($key)] = $val;
  582. }
  583. }
  584. // decode values.
  585. foreach($return['other'] as $key =>$val) {
  586. $return['other'][$key] = $this->_decode_headers ? $this->_decodeHeader($val) : $val;
  587. }
  588. //print_r($return);
  589. return $return;
  590. }
  591. /**
  592. * This function splits the input based
  593. * on the given boundary
  594. *
  595. * @param string Input to parse
  596. * @return array Contains array of resulting mime parts
  597. * @access private
  598. */
  599. function _boundarySplit($input, $boundary)
  600. {
  601. $parts = array();
  602. $bs_possible = substr($boundary, 2, -2);
  603. $bs_check = '\"' . $bs_possible . '\"';
  604. if ($boundary == $bs_check) {
  605. $boundary = $bs_possible;
  606. }
  607. $tmp = preg_split("/--".preg_quote($boundary, '/')."((?=\s)|--)/", $input);
  608. $len = count($tmp) -1;
  609. for ($i = 1; $i < $len; $i++) {
  610. if (strlen(trim($tmp[$i]))) {
  611. $parts[] = $tmp[$i];
  612. }
  613. }
  614. // add the last part on if it does not end with the 'closing indicator'
  615. if (!empty($tmp[$len]) && strlen(trim($tmp[$len])) && $tmp[$len][0] != '-') {
  616. $parts[] = $tmp[$len];
  617. }
  618. return $parts;
  619. }
  620. /**
  621. * Given a header, this function will decode it
  622. * according to RFC2047. Probably not *exactly*
  623. * conformant, but it does pass all the given
  624. * examples (in RFC2047).
  625. *
  626. * @param string Input header value to decode
  627. * @return string Decoded header value
  628. * @access private
  629. */
  630. function _decodeHeader($input)
  631. {
  632. // Remove white space between encoded-words
  633. $input = preg_replace('/(=\?[^?]+\?(q|b)\?[^?]*\?=)(\s)+=\?/i', '\1=?', $input);
  634. // For each encoded-word...
  635. while (preg_match('/(=\?([^?]+)\?(q|b)\?([^?]*)\?=)/i', $input, $matches)) {
  636. $encoded = $matches[1];
  637. $charset = $matches[2];
  638. $encoding = $matches[3];
  639. $text = $matches[4];
  640. switch (strtolower($encoding)) {
  641. case 'b':
  642. $text = base64_decode($text);
  643. break;
  644. case 'q':
  645. $text = str_replace('_', ' ', $text);
  646. preg_match_all('/=([a-f0-9]{2})/i', $text, $matches);
  647. foreach($matches[1] as $value)
  648. $text = str_replace('='.$value, chr(hexdec($value)), $text);
  649. break;
  650. }
  651. $input = str_replace($encoded, $this->_fromCharset($charset, $text), $input);
  652. }
  653. return $input;
  654. }
  655. /**
  656. * Given a body string and an encoding type,
  657. * this function will decode and return it.
  658. *
  659. * @param string Input body to decode
  660. * @param string Encoding type to use.
  661. * @return string Decoded body
  662. * @access private
  663. */
  664. function _decodeBody($input, $encoding = '7bit', $charset = '')
  665. {
  666. switch (strtolower($encoding)) {
  667. case '7bit':
  668. return $this->_fromCharset($charset, $input);;
  669. break;
  670. case '8bit':
  671. return $this->_fromCharset($charset, $input);
  672. break;
  673. case 'quoted-printable':
  674. return $this->_fromCharset($charset, $this->_quotedPrintableDecode($input));
  675. break;
  676. case 'base64':
  677. return $this->_fromCharset($charset, base64_decode($input));
  678. break;
  679. default:
  680. return $input;
  681. }
  682. }
  683. /**
  684. * Given a quoted-printable string, this
  685. * function will decode and return it.
  686. *
  687. * @param string Input body to decode
  688. * @return string Decoded body
  689. * @access private
  690. */
  691. function _quotedPrintableDecode($input)
  692. {
  693. // Remove soft line breaks
  694. $input = preg_replace("/=\r?\n/", '', $input);
  695. // Replace encoded characters
  696. $input = preg_replace('/=([a-f0-9]{2})/ie', "chr(hexdec('\\1'))", $input);
  697. return $input;
  698. }
  699. /**
  700. * Checks the input for uuencoded files and returns
  701. * an array of them. Can be called statically, eg:
  702. *
  703. * $files =& Mail_mimeDecode::uudecode($some_text);
  704. *
  705. * It will check for the begin 666 ... end syntax
  706. * however and won't just blindly decode whatever you
  707. * pass it.
  708. *
  709. * @param string Input body to look for attahcments in
  710. * @return array Decoded bodies, filenames and permissions
  711. * @access public
  712. * @author Unknown
  713. */
  714. function &uudecode($input)
  715. {
  716. // Find all uuencoded sections
  717. preg_match_all("/begin ([0-7]{3}) (.+)\r?\n(.+)\r?\nend/Us", $input, $matches);
  718. for ($j = 0; $j < count($matches[3]); $j++) {
  719. $str = $matches[3][$j];
  720. $filename = $matches[2][$j];
  721. $fileperm = $matches[1][$j];
  722. $file = '';
  723. $str = preg_split("/\r?\n/", trim($str));
  724. $strlen = count($str);
  725. for ($i = 0; $i < $strlen; $i++) {
  726. $pos = 1;
  727. $d = 0;
  728. $len=(int)(((ord(substr($str[$i],0,1)) -32) - ' ') & 077);
  729. while (($d + 3 <= $len) AND ($pos + 4 <= strlen($str[$i]))) {
  730. $c0 = (ord(substr($str[$i],$pos,1)) ^ 0x20);
  731. $c1 = (ord(substr($str[$i],$pos+1,1)) ^ 0x20);
  732. $c2 = (ord(substr($str[$i],$pos+2,1)) ^ 0x20);
  733. $c3 = (ord(substr($str[$i],$pos+3,1)) ^ 0x20);
  734. $file .= chr(((($c0 - ' ') & 077) << 2) | ((($c1 - ' ') & 077) >> 4));
  735. $file .= chr(((($c1 - ' ') & 077) << 4) | ((($c2 - ' ') & 077) >> 2));
  736. $file .= chr(((($c2 - ' ') & 077) << 6) | (($c3 - ' ') & 077));
  737. $pos += 4;
  738. $d += 3;
  739. }
  740. if (($d + 2 <= $len) && ($pos + 3 <= strlen($str[$i]))) {
  741. $c0 = (ord(substr($str[$i],$pos,1)) ^ 0x20);
  742. $c1 = (ord(substr($str[$i],$pos+1,1)) ^ 0x20);
  743. $c2 = (ord(substr($str[$i],$pos+2,1)) ^ 0x20);
  744. $file .= chr(((($c0 - ' ') & 077) << 2) | ((($c1 - ' ') & 077) >> 4));
  745. $file .= chr(((($c1 - ' ') & 077) << 4) | ((($c2 - ' ') & 077) >> 2));
  746. $pos += 3;
  747. $d += 2;
  748. }
  749. if (($d + 1 <= $len) && ($pos + 2 <= strlen($str[$i]))) {
  750. $c0 = (ord(substr($str[$i],$pos,1)) ^ 0x20);
  751. $c1 = (ord(substr($str[$i],$pos+1,1)) ^ 0x20);
  752. $file .= chr(((($c0 - ' ') & 077) << 2) | ((($c1 - ' ') & 077) >> 4));
  753. }
  754. }
  755. $files[] = array('filename' => $filename, 'fileperm' => $fileperm, 'filedata' => $file);
  756. }
  757. return $files;
  758. }
  759. /**
  760. * getSendArray() returns the arguments required for Mail::send()
  761. * used to build the arguments for a mail::send() call
  762. *
  763. * Usage:
  764. * $mailtext = Full email (for example generated by a template)
  765. * $decoder = new Mail_mimeDecode($mailtext);
  766. * $parts = $decoder->getSendArray();
  767. * if (!PEAR::isError($parts) {
  768. * list($recipents,$headers,$body) = $parts;
  769. * $mail = Mail::factory('smtp');
  770. * $mail->send($recipents,$headers,$body);
  771. * } else {
  772. * echo $parts->message;
  773. * }
  774. * @return mixed array of recipeint, headers,body or Pear_Error
  775. * @access public
  776. * @author Alan Knowles <alan@akbkhome.com>
  777. */
  778. function getSendArray()
  779. {
  780. // prevent warning if this is not set
  781. $this->_decode_headers = FALSE;
  782. $headerlist =$this->_parseHeaders($this->_header);
  783. $to = "";
  784. if (!$headerlist) {
  785. return $this->raiseError("Message did not contain headers");
  786. }
  787. foreach($headerlist as $item) {
  788. $header[$item['name']] = $item['value'];
  789. switch (strtolower($item['name'])) {
  790. case "to":
  791. case "cc":
  792. case "bcc":
  793. $to .= ",".$item['value'];
  794. default:
  795. break;
  796. }
  797. }
  798. if ($to == "") {
  799. return $this->raiseError("Message did not contain any recipents");
  800. }
  801. $to = substr($to,1);
  802. return array($to,$header,$this->_body);
  803. }
  804. /**
  805. * Returns a xml copy of the output of
  806. * Mail_mimeDecode::decode. Pass the output in as the
  807. * argument. This function can be called statically. Eg:
  808. *
  809. * $output = $obj->decode();
  810. * $xml = Mail_mimeDecode::getXML($output);
  811. *
  812. * The DTD used for this should have been in the package. Or
  813. * alternatively you can get it from cvs, or here:
  814. * http://www.phpguru.org/xmail/xmail.dtd.
  815. *
  816. * @param object Input to convert to xml. This should be the
  817. * output of the Mail_mimeDecode::decode function
  818. * @return string XML version of input
  819. * @access public
  820. */
  821. function getXML($input)
  822. {
  823. $crlf = "\r\n";
  824. $output = '<?xml version=\'1.0\'?>' . $crlf .
  825. '<!DOCTYPE email SYSTEM "http://www.phpguru.org/xmail/xmail.dtd">' . $crlf .
  826. '<email>' . $crlf .
  827. Mail_mimeDecode::_getXML($input) .
  828. '</email>';
  829. return $output;
  830. }
  831. /**
  832. * Function that does the actual conversion to xml. Does a single
  833. * mimepart at a time.
  834. *
  835. * @param object Input to convert to xml. This is a mimepart object.
  836. * It may or may not contain subparts.
  837. * @param integer Number of tabs to indent
  838. * @return string XML version of input
  839. * @access private
  840. */
  841. function _getXML($input, $indent = 1)
  842. {
  843. $htab = "\t";
  844. $crlf = "\r\n";
  845. $output = '';
  846. $headers = @(array)$input->headers;
  847. foreach ($headers as $hdr_name => $hdr_value) {
  848. // Multiple headers with this name
  849. if (is_array($headers[$hdr_name])) {
  850. for ($i = 0; $i < count($hdr_value); $i++) {
  851. $output .= Mail_mimeDecode::_getXML_helper($hdr_name, $hdr_value[$i], $indent);
  852. }
  853. // Only one header of this sort
  854. } else {
  855. $output .= Mail_mimeDecode::_getXML_helper($hdr_name, $hdr_value, $indent);
  856. }
  857. }
  858. if (!empty($input->parts)) {
  859. for ($i = 0; $i < count($input->parts); $i++) {
  860. $output .= $crlf . str_repeat($htab, $indent) . '<mimepart>' . $crlf .
  861. Mail_mimeDecode::_getXML($input->parts[$i], $indent+1) .
  862. str_repeat($htab, $indent) . '</mimepart>' . $crlf;
  863. }
  864. } elseif (isset($input->body)) {
  865. $output .= $crlf . str_repeat($htab, $indent) . '<body><![CDATA[' .
  866. $input->body . ']]></body>' . $crlf;
  867. }
  868. return $output;
  869. }
  870. /**
  871. * Helper function to _getXML(). Returns xml of a header.
  872. *
  873. * @param string Name of header
  874. * @param string Value of header
  875. * @param integer Number of tabs to indent
  876. * @return string XML version of input
  877. * @access private
  878. */
  879. function _getXML_helper($hdr_name, $hdr_value, $indent)
  880. {
  881. $htab = "\t";
  882. $crlf = "\r\n";
  883. $return = '';
  884. $new_hdr_value = ($hdr_name != 'received') ? Mail_mimeDecode::_parseHeaderValue($hdr_value) : array('value' => $hdr_value);
  885. $new_hdr_name = str_replace(' ', '-', ucwords(str_replace('-', ' ', $hdr_name)));
  886. // Sort out any parameters
  887. if (!empty($new_hdr_value['other'])) {
  888. foreach ($new_hdr_value['other'] as $paramname => $paramvalue) {
  889. $params[] = str_repeat($htab, $indent) . $htab . '<parameter>' . $crlf .
  890. str_repeat($htab, $indent) . $htab . $htab . '<paramname>' . htmlspecialchars($paramname) . '</paramname>' . $crlf .
  891. str_repeat($htab, $indent) . $htab . $htab . '<paramvalue>' . htmlspecialchars($paramvalue) . '</paramvalue>' . $crlf .
  892. str_repeat($htab, $indent) . $htab . '</parameter>' . $crlf;
  893. }
  894. $params = implode('', $params);
  895. } else {
  896. $params = '';
  897. }
  898. $return = str_repeat($htab, $indent) . '<header>' . $crlf .
  899. str_repeat($htab, $indent) . $htab . '<headername>' . htmlspecialchars($new_hdr_name) . '</headername>' . $crlf .
  900. str_repeat($htab, $indent) . $htab . '<headervalue>' . htmlspecialchars($new_hdr_value['value']) . '</headervalue>' . $crlf .
  901. $params .
  902. str_repeat($htab, $indent) . '</header>' . $crlf;
  903. return $return;
  904. }
  905. /**
  906. * Z-Push helper to decode text
  907. *
  908. * @param string current charset of input
  909. * @param string input
  910. * @return string XML version of input
  911. * @access private
  912. */
  913. function _fromCharset($charset, $input) {
  914. if($charset == '' || (strtolower($charset) == $this->_charset))
  915. return $input;
  916. // all ISO-8859-1 are converted as if they were Windows-1252 - see Mantis #456
  917. if (strtolower($charset) == 'iso-8859-1')
  918. $charset = 'Windows-1252';
  919. return @iconv($charset, $this->_charset. "//TRANSLIT", $input);
  920. }
  921. /**
  922. * Z-Push helper for error logging
  923. * removing PEAR dependency
  924. *
  925. * @param string debug message
  926. * @return boolean always false as there was an error
  927. * @access private
  928. */
  929. function raiseError($message) {
  930. ZLog::Write(LOGLEVEL_ERROR, "mimeDecode error: ". $message);
  931. return false;
  932. }
  933. } // End of class