You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

rcube_mime_decode.php 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. <?php
  2. /**
  3. +-----------------------------------------------------------------------+
  4. | This file is part of the Roundcube Webmail client |
  5. | Copyright (C) 2005-2015, The Roundcube Dev Team |
  6. | Copyright (C) 2011-2015, Kolab Systems AG |
  7. | |
  8. | Licensed under the GNU General Public License version 3 or |
  9. | any later version with exceptions for skins & plugins. |
  10. | See the README file for a full license statement. |
  11. | |
  12. | PURPOSE: |
  13. | MIME message parsing utilities derived from Mail_mimeDecode |
  14. +-----------------------------------------------------------------------+
  15. | Author: Thomas Bruederli <roundcube@gmail.com> |
  16. | Author: Aleksander Machniak <alec@alec.pl> |
  17. | Author: Richard Heyes <richard@phpguru.org> |
  18. +-----------------------------------------------------------------------+
  19. */
  20. /**
  21. * Class for parsing MIME messages
  22. *
  23. * @package Framework
  24. * @subpackage Storage
  25. * @author Aleksander Machniak <alec@alec.pl>
  26. */
  27. class rcube_mime_decode
  28. {
  29. /**
  30. * Class configuration parameters.
  31. *
  32. * @var array
  33. */
  34. protected $params = array(
  35. 'include_bodies' => true,
  36. 'decode_bodies' => true,
  37. 'decode_headers' => true,
  38. 'crlf' => "\r\n",
  39. 'default_charset' => RCUBE_CHARSET,
  40. );
  41. /**
  42. * Constructor.
  43. *
  44. * Sets up the object, initialise the variables, and splits and
  45. * stores the header and body of the input.
  46. *
  47. * @param array $params An array of various parameters that determine
  48. * various things:
  49. * include_bodies - Whether to include the body in the returned
  50. * object.
  51. * decode_bodies - Whether to decode the bodies
  52. * of the parts. (Transfer encoding)
  53. * decode_headers - Whether to decode headers
  54. * crlf - CRLF type to use (CRLF/LF/CR)
  55. */
  56. public function __construct($params = array())
  57. {
  58. if (!empty($params)) {
  59. $this->params = array_merge($this->params, (array) $params);
  60. }
  61. }
  62. /**
  63. * Performs the decoding process.
  64. *
  65. * @param string $input The input to decode
  66. * @param bool $convert Convert result to rcube_message_part structure
  67. *
  68. * @return object|bool Decoded results or False on failure
  69. */
  70. public function decode($input, $convert = true)
  71. {
  72. list($header, $body) = $this->splitBodyHeader($input);
  73. $struct = $this->do_decode($header, $body);
  74. if ($struct && $convert) {
  75. $struct = $this->structure_part($struct);
  76. }
  77. return $struct;
  78. }
  79. /**
  80. * Performs the decoding. Decodes the body string passed to it
  81. * If it finds certain content-types it will call itself in a
  82. * recursive fashion
  83. *
  84. * @param string $headers Header section
  85. * @param string $body Body section
  86. * @param string $default_ctype Default content type
  87. *
  88. * @return object|bool Decoded results or False on error
  89. */
  90. protected function do_decode($headers, $body, $default_ctype = 'text/plain')
  91. {
  92. $return = new stdClass;
  93. $headers = $this->parseHeaders($headers);
  94. foreach ($headers as $value) {
  95. $header_name = strtolower($value['name']);
  96. if (isset($return->headers[$header_name]) && !is_array($return->headers[$header_name])) {
  97. $return->headers[$header_name] = array($return->headers[$header_name]);
  98. $return->headers[$header_name][] = $value['value'];
  99. }
  100. else if (isset($return->headers[$header_name])) {
  101. $return->headers[$header_name][] = $value['value'];
  102. }
  103. else {
  104. $return->headers[$header_name] = $value['value'];
  105. }
  106. switch ($header_name) {
  107. case 'content-type':
  108. $content_type = $this->parseHeaderValue($value['value']);
  109. if (preg_match('/([0-9a-z+.-]+)\/([0-9a-z+.-]+)/i', $content_type['value'], $regs)) {
  110. $return->ctype_primary = $regs[1];
  111. $return->ctype_secondary = $regs[2];
  112. }
  113. if (!empty($content_type['other'])) {
  114. $return->ctype_parameters = array_merge((array) $return->ctype_parameters, (array) $content_type['other']);
  115. }
  116. break;
  117. case 'content-disposition';
  118. $content_disposition = $this->parseHeaderValue($value['value']);
  119. $return->disposition = $content_disposition['value'];
  120. if (!empty($content_disposition['other'])) {
  121. $return->d_parameters = array_merge((array) $return->d_parameters, (array) $content_disposition['other']);
  122. }
  123. break;
  124. case 'content-transfer-encoding':
  125. $content_transfer_encoding = $this->parseHeaderValue($value['value']);
  126. break;
  127. }
  128. }
  129. if (isset($content_type)) {
  130. $ctype = strtolower($content_type['value']);
  131. switch ($ctype) {
  132. case 'text/plain':
  133. $encoding = isset($content_transfer_encoding) ? $content_transfer_encoding['value'] : '7bit';
  134. if ($this->params['include_bodies']) {
  135. $return->body = $this->params['decode_bodies'] ? rcube_mime::decode($body, $encoding) : $body;
  136. }
  137. break;
  138. case 'text/html':
  139. $encoding = isset($content_transfer_encoding) ? $content_transfer_encoding['value'] : '7bit';
  140. if ($this->params['include_bodies']) {
  141. $return->body = $this->params['decode_bodies'] ? rcube_mime::decode($body, $encoding) : $body;
  142. }
  143. break;
  144. case 'multipart/digest':
  145. case 'multipart/alternative':
  146. case 'multipart/related':
  147. case 'multipart/mixed':
  148. case 'multipart/signed':
  149. case 'multipart/encrypted':
  150. if (!isset($content_type['other']['boundary'])) {
  151. return false;
  152. }
  153. $default_ctype = $ctype === 'multipart/digest' ? 'message/rfc822' : 'text/plain';
  154. $parts = $this->boundarySplit($body, $content_type['other']['boundary']);
  155. for ($i = 0; $i < count($parts); $i++) {
  156. list($part_header, $part_body) = $this->splitBodyHeader($parts[$i]);
  157. $return->parts[] = $this->do_decode($part_header, $part_body, $default_ctype);
  158. }
  159. break;
  160. case 'message/rfc822':
  161. $obj = new rcube_mime_decode($this->params);
  162. $return->parts[] = $obj->decode($body, false);
  163. unset($obj);
  164. break;
  165. default:
  166. if ($this->params['include_bodies']) {
  167. $return->body = $this->params['decode_bodies'] ? rcube_mime::decode($body, $content_transfer_encoding['value']) : $body;
  168. }
  169. break;
  170. }
  171. }
  172. else {
  173. $ctype = explode('/', $default_ctype);
  174. $return->ctype_primary = $ctype[0];
  175. $return->ctype_secondary = $ctype[1];
  176. if ($this->params['include_bodies']) {
  177. $return->body = $this->params['decode_bodies'] ? rcube_mime::decode($body) : $body;
  178. }
  179. }
  180. return $return;
  181. }
  182. /**
  183. * Given a string containing a header and body
  184. * section, this function will split them (at the first
  185. * blank line) and return them.
  186. *
  187. * @param string $input Input to split apart
  188. *
  189. * @return array Contains header and body section
  190. */
  191. protected function splitBodyHeader($input)
  192. {
  193. $pos = strpos($input, $this->params['crlf'] . $this->params['crlf']);
  194. if ($pos === false) {
  195. return false;
  196. }
  197. $crlf_len = strlen($this->params['crlf']);
  198. $header = substr($input, 0, $pos);
  199. $body = substr($input, $pos + 2 * $crlf_len);
  200. if (substr_compare($body, $this->params['crlf'], -$crlf_len) === 0) {
  201. $body = substr($body, 0, -$crlf_len);
  202. }
  203. return array($header, $body);
  204. }
  205. /**
  206. * Parse headers given in $input and return as assoc array.
  207. *
  208. * @param string $input Headers to parse
  209. *
  210. * @return array Contains parsed headers
  211. */
  212. protected function parseHeaders($input)
  213. {
  214. if ($input !== '') {
  215. // Unfold the input
  216. $input = preg_replace('/' . $this->params['crlf'] . "(\t| )/", ' ', $input);
  217. $headers = explode($this->params['crlf'], trim($input));
  218. foreach ($headers as $value) {
  219. $hdr_name = substr($value, 0, $pos = strpos($value, ':'));
  220. $hdr_value = substr($value, $pos+1);
  221. if ($hdr_value[0] == ' ') {
  222. $hdr_value = substr($hdr_value, 1);
  223. }
  224. $return[] = array(
  225. 'name' => $hdr_name,
  226. 'value' => $this->params['decode_headers'] ? $this->decodeHeader($hdr_value) : $hdr_value,
  227. );
  228. }
  229. }
  230. else {
  231. $return = array();
  232. }
  233. return $return;
  234. }
  235. /**
  236. * Function to parse a header value, extract first part, and any secondary
  237. * parts (after ;) This function is not as robust as it could be.
  238. * Eg. header comments in the wrong place will probably break it.
  239. *
  240. * @param string $input Header value to parse
  241. *
  242. * @return array Contains parsed result
  243. */
  244. protected function parseHeaderValue($input)
  245. {
  246. $parts = preg_split('/;\s*/', $input);
  247. if (!empty($parts)) {
  248. $return['value'] = trim($parts[0]);
  249. for ($n = 1; $n < count($parts); $n++) {
  250. if (preg_match_all('/(([[:alnum:]]+)="?([^"]*)"?\s?;?)+/i', $parts[$n], $matches)) {
  251. for ($i = 0; $i < count($matches[2]); $i++) {
  252. $return['other'][strtolower($matches[2][$i])] = $matches[3][$i];
  253. }
  254. }
  255. }
  256. }
  257. else {
  258. $return['value'] = trim($input);
  259. }
  260. return $return;
  261. }
  262. /**
  263. * This function splits the input based on the given boundary
  264. *
  265. * @param string $input Input to parse
  266. * @param string $boundary Boundary
  267. *
  268. * @return array Contains array of resulting mime parts
  269. */
  270. protected function boundarySplit($input, $boundary)
  271. {
  272. $tmp = explode('--' . $boundary, $input);
  273. for ($i = 1; $i < count($tmp)-1; $i++) {
  274. $parts[] = $tmp[$i];
  275. }
  276. return $parts;
  277. }
  278. /**
  279. * Given a header, this function will decode it according to RFC2047.
  280. * Probably not *exactly* conformant, but it does pass all the given
  281. * examples (in RFC2047).
  282. *
  283. * @param string $input Input header value to decode
  284. *
  285. * @return string Decoded header value
  286. */
  287. protected function decodeHeader($input)
  288. {
  289. return rcube_mime::decode_mime_string($input, $this->params['default_charset']);
  290. }
  291. /**
  292. * Recursive method to convert a rcube_mime_decode structure
  293. * into a rcube_message_part object.
  294. *
  295. * @param object $part A message part struct
  296. * @param int $count Part count
  297. * @param string $parent Parent MIME ID
  298. *
  299. * @return object rcube_message_part
  300. * @see self::decode()
  301. */
  302. protected function structure_part($part, $count = 0, $parent = '')
  303. {
  304. $struct = new rcube_message_part;
  305. $struct->mime_id = $part->mime_id ?: (empty($parent) ? (string)$count : "$parent.$count");
  306. $struct->headers = $part->headers;
  307. $struct->mimetype = $part->ctype_primary . '/' . $part->ctype_secondary;
  308. $struct->ctype_primary = $part->ctype_primary;
  309. $struct->ctype_secondary = $part->ctype_secondary;
  310. $struct->ctype_parameters = $part->ctype_parameters;
  311. if ($part->headers['content-transfer-encoding']) {
  312. $struct->encoding = $part->headers['content-transfer-encoding'];
  313. }
  314. if ($part->ctype_parameters['charset']) {
  315. $struct->charset = $part->ctype_parameters['charset'];
  316. }
  317. $part_charset = $struct->charset ?: $this->params['default_charset'];
  318. // determine filename
  319. if (($filename = $part->d_parameters['filename']) || ($filename = $part->ctype_parameters['name'])) {
  320. if (!$this->params['decode_headers']) {
  321. $filename = $this->decodeHeader($filename);
  322. }
  323. $struct->filename = $filename;
  324. }
  325. $struct->body = $part->body;
  326. $struct->size = strlen($part->body);
  327. $struct->disposition = $part->disposition;
  328. $count = 0;
  329. foreach ((array)$part->parts as $child_part) {
  330. $struct->parts[] = $this->structure_part($child_part, ++$count, $struct->mime_id);
  331. }
  332. return $struct;
  333. }
  334. }