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_message.php 39KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038
  1. <?php
  2. /**
  3. +-----------------------------------------------------------------------+
  4. | This file is part of the Roundcube Webmail client |
  5. | Copyright (C) 2008-2014, The Roundcube Dev Team |
  6. | |
  7. | Licensed under the GNU General Public License version 3 or |
  8. | any later version with exceptions for skins & plugins. |
  9. | See the README file for a full license statement. |
  10. | |
  11. | PURPOSE: |
  12. | Logical representation of a mail message with all its data |
  13. | and related functions |
  14. +-----------------------------------------------------------------------+
  15. | Author: Thomas Bruederli <roundcube@gmail.com> |
  16. +-----------------------------------------------------------------------+
  17. */
  18. /**
  19. * Logical representation of a mail message with all its data
  20. * and related functions
  21. *
  22. * @package Framework
  23. * @subpackage Storage
  24. * @author Thomas Bruederli <roundcube@gmail.com>
  25. */
  26. class rcube_message
  27. {
  28. /**
  29. * Instace of framework class.
  30. *
  31. * @var rcube
  32. */
  33. private $app;
  34. /**
  35. * Instance of storage class
  36. *
  37. * @var rcube_storage
  38. */
  39. private $storage;
  40. /**
  41. * Instance of mime class
  42. *
  43. * @var rcube_mime
  44. */
  45. private $mime;
  46. private $opt = array();
  47. private $parse_alternative = false;
  48. public $uid;
  49. public $folder;
  50. public $headers;
  51. public $sender;
  52. public $parts = array();
  53. public $mime_parts = array();
  54. public $inline_parts = array();
  55. public $attachments = array();
  56. public $subject = '';
  57. public $is_safe = false;
  58. const BODY_MAX_SIZE = 1048576; // 1MB
  59. /**
  60. * __construct
  61. *
  62. * Provide a uid, and parse message structure.
  63. *
  64. * @param string $uid The message UID.
  65. * @param string $folder Folder name
  66. * @param bool $is_safe Security flag
  67. *
  68. * @see self::$app, self::$storage, self::$opt, self::$parts
  69. */
  70. function __construct($uid, $folder = null, $is_safe = false)
  71. {
  72. // decode combined UID-folder identifier
  73. if (preg_match('/^\d+-.+/', $uid)) {
  74. list($uid, $folder) = explode('-', $uid, 2);
  75. }
  76. $this->uid = $uid;
  77. $this->app = rcube::get_instance();
  78. $this->storage = $this->app->get_storage();
  79. $this->folder = strlen($folder) ? $folder : $this->storage->get_folder();
  80. // Set current folder
  81. $this->storage->set_folder($this->folder);
  82. $this->storage->set_options(array('all_headers' => true));
  83. $this->headers = $this->storage->get_message($uid);
  84. if (!$this->headers) {
  85. return;
  86. }
  87. $this->mime = new rcube_mime($this->headers->charset);
  88. $this->subject = $this->headers->get('subject');
  89. list(, $this->sender) = each($this->mime->decode_address_list($this->headers->from, 1));
  90. $this->set_safe($is_safe || $_SESSION['safe_messages'][$this->folder.':'.$uid]);
  91. $this->opt = array(
  92. 'safe' => $this->is_safe,
  93. 'prefer_html' => $this->app->config->get('prefer_html'),
  94. 'get_url' => $this->app->url(array(
  95. 'action' => 'get',
  96. 'mbox' => $this->folder,
  97. 'uid' => $uid),
  98. false, false, true)
  99. );
  100. if (!empty($this->headers->structure)) {
  101. $this->get_mime_numbers($this->headers->structure);
  102. $this->parse_structure($this->headers->structure);
  103. }
  104. else {
  105. $this->body = $this->storage->get_body($uid);
  106. }
  107. // notify plugins and let them analyze this structured message object
  108. $this->app->plugins->exec_hook('message_load', array('object' => $this));
  109. }
  110. /**
  111. * Return a (decoded) message header
  112. *
  113. * @param string $name Header name
  114. * @param bool $row Don't mime-decode the value
  115. * @return string Header value
  116. */
  117. public function get_header($name, $raw = false)
  118. {
  119. if (empty($this->headers)) {
  120. return null;
  121. }
  122. return $this->headers->get($name, !$raw);
  123. }
  124. /**
  125. * Set is_safe var and session data
  126. *
  127. * @param bool $safe enable/disable
  128. */
  129. public function set_safe($safe = true)
  130. {
  131. $_SESSION['safe_messages'][$this->folder.':'.$this->uid] = $this->is_safe = $safe;
  132. }
  133. /**
  134. * Compose a valid URL for getting a message part
  135. *
  136. * @param string $mime_id Part MIME-ID
  137. * @param mixed $embed Mimetype class for parts to be embedded
  138. * @return string URL or false if part does not exist
  139. */
  140. public function get_part_url($mime_id, $embed = false)
  141. {
  142. if ($this->mime_parts[$mime_id])
  143. return $this->opt['get_url'] . '&_part=' . $mime_id . ($embed ? '&_embed=1&_mimeclass=' . $embed : '');
  144. else
  145. return false;
  146. }
  147. /**
  148. * Get content of a specific part of this message
  149. *
  150. * @param string $mime_id Part MIME-ID
  151. * @param resource $fp File pointer to save the message part
  152. * @param boolean $skip_charset_conv Disables charset conversion
  153. * @param int $max_bytes Only read this number of bytes
  154. * @param boolean $formatted Enables formatting of text/* parts bodies
  155. *
  156. * @return string Part content
  157. * @deprecated
  158. */
  159. public function get_part_content($mime_id, $fp = null, $skip_charset_conv = false, $max_bytes = 0, $formatted = true)
  160. {
  161. if ($part = $this->mime_parts[$mime_id]) {
  162. // stored in message structure (winmail/inline-uuencode)
  163. if (!empty($part->body) || $part->encoding == 'stream') {
  164. if ($fp) {
  165. fwrite($fp, $part->body);
  166. }
  167. return $fp ? true : $part->body;
  168. }
  169. // get from IMAP
  170. $this->storage->set_folder($this->folder);
  171. return $this->storage->get_message_part($this->uid, $mime_id, $part,
  172. NULL, $fp, $skip_charset_conv, $max_bytes, $formatted);
  173. }
  174. }
  175. /**
  176. * Get content of a specific part of this message
  177. *
  178. * @param string $mime_id Part ID
  179. * @param boolean $formatted Enables formatting of text/* parts bodies
  180. * @param int $max_bytes Only return/read this number of bytes
  181. * @param mixed $mode NULL to return a string, -1 to print body
  182. * or file pointer to save the body into
  183. *
  184. * @return string|bool Part content or operation status
  185. */
  186. public function get_part_body($mime_id, $formatted = false, $max_bytes = 0, $mode = null)
  187. {
  188. if (!($part = $this->mime_parts[$mime_id])) {
  189. return;
  190. }
  191. // allow plugins to modify part body
  192. $plugin = $this->app->plugins->exec_hook('message_part_body',
  193. array('object' => $this, 'part' => $part));
  194. // only text parts can be formatted
  195. $formatted = $formatted && $part->ctype_primary == 'text';
  196. // part body not fetched yet... save in memory if it's small enough
  197. if ($part->body === null && is_numeric($mime_id) && $part->size < self::BODY_MAX_SIZE) {
  198. $this->storage->set_folder($this->folder);
  199. // Warning: body here should be always unformatted
  200. $part->body = $this->storage->get_message_part($this->uid, $mime_id, $part,
  201. null, null, true, 0, false);
  202. }
  203. // body stored in message structure (winmail/inline-uuencode)
  204. if ($part->body !== null || $part->encoding == 'stream') {
  205. $body = $part->body;
  206. if ($formatted && $body) {
  207. $body = self::format_part_body($body, $part, $this->headers->charset);
  208. }
  209. if ($max_bytes && strlen($body) > $max_bytes) {
  210. $body = substr($body, 0, $max_bytes);
  211. }
  212. if (is_resource($mode)) {
  213. if ($body !== false) {
  214. fwrite($mode, $body);
  215. rewind($mode);
  216. }
  217. return $body !== false;
  218. }
  219. if ($mode === -1) {
  220. if ($body !== false) {
  221. print($body);
  222. }
  223. return $body !== false;
  224. }
  225. return $body;
  226. }
  227. // get the body from IMAP
  228. $this->storage->set_folder($this->folder);
  229. $body = $this->storage->get_message_part($this->uid, $mime_id, $part,
  230. $mode === -1, is_resource($mode) ? $mode : null,
  231. !($mode && $formatted), $max_bytes, $mode && $formatted);
  232. if (is_resource($mode)) {
  233. rewind($mode);
  234. return $body !== false;
  235. }
  236. if (!$mode && $body && $formatted) {
  237. $body = self::format_part_body($body, $part, $this->headers->charset);
  238. }
  239. return $body;
  240. }
  241. /**
  242. * Format text message part for display
  243. *
  244. * @param string $body Part body
  245. * @param rcube_message_part $part Part object
  246. * @param string $default_charset Fallback charset if part charset is not specified
  247. *
  248. * @return string Formatted body
  249. */
  250. public static function format_part_body($body, $part, $default_charset = null)
  251. {
  252. // remove useless characters
  253. $body = preg_replace('/[\t\r\0\x0B]+\n/', "\n", $body);
  254. // remove NULL characters if any (#1486189)
  255. if (strpos($body, "\x00") !== false) {
  256. $body = str_replace("\x00", '', $body);
  257. }
  258. // detect charset...
  259. if (!$part->charset || strtoupper($part->charset) == 'US-ASCII') {
  260. // try to extract charset information from HTML meta tag (#1488125)
  261. if ($part->ctype_secondary == 'html' && preg_match('/<meta[^>]+charset=([a-z0-9-_]+)/i', $body, $m)) {
  262. $part->charset = strtoupper($m[1]);
  263. }
  264. else if ($default_charset) {
  265. $part->charset = $default_charset;
  266. }
  267. else {
  268. $rcube = rcube::get_instance();
  269. $part->charset = $rcube->config->get('default_charset', RCUBE_CHARSET);
  270. }
  271. }
  272. // ..convert charset encoding
  273. $body = rcube_charset::convert($body, $part->charset);
  274. return $body;
  275. }
  276. /**
  277. * Determine if the message contains a HTML part. This must to be
  278. * a real part not an attachment (or its part)
  279. *
  280. * @param bool $enriched Enables checking for text/enriched parts too
  281. * @param rcube_message_part &$part Reference to the part if found
  282. *
  283. * @return bool True if a HTML is available, False if not
  284. */
  285. public function has_html_part($enriched = false, &$part = null)
  286. {
  287. // check all message parts
  288. foreach ($this->mime_parts as $part) {
  289. if ($part->mimetype == 'text/html' || ($enriched && $part->mimetype == 'text/enriched')) {
  290. // Skip if part is an attachment, don't use is_attachment() here
  291. if ($part->filename) {
  292. continue;
  293. }
  294. $level = explode('.', $part->mime_id);
  295. $depth = count($level);
  296. $last = '';
  297. // Check if the part belongs to higher-level's multipart part
  298. // this can be alternative/related/signed/encrypted or mixed
  299. while (array_pop($level) !== null) {
  300. $parent_depth = count($level);
  301. if (!$parent_depth) {
  302. return true;
  303. }
  304. $parent = $this->mime_parts[join('.', $level)];
  305. $max_delta = $depth - (1 + ($last == 'multipart/alternative' ? 1 : 0));
  306. $last = $parent->mimetype;
  307. if (!preg_match('/^multipart\/(alternative|related|signed|encrypted|mixed)$/', $parent->mimetype)
  308. || ($parent->mimetype == 'multipart/mixed' && $parent_depth < $max_delta)) {
  309. continue 2;
  310. }
  311. }
  312. if ($part->size) {
  313. return true;
  314. }
  315. }
  316. }
  317. $part = null;
  318. return false;
  319. }
  320. /**
  321. * Determine if the message contains a text/plain part. This must to be
  322. * a real part not an attachment (or its part)
  323. *
  324. * @param rcube_message_part &$part Reference to the part if found
  325. *
  326. * @return bool True if a plain text part is available, False if not
  327. */
  328. public function has_text_part(&$part = null)
  329. {
  330. // check all message parts
  331. foreach ($this->mime_parts as $part) {
  332. if ($part->mimetype == 'text/plain') {
  333. // Skip if part is an attachment, don't use is_attachment() here
  334. if ($part->filename) {
  335. continue;
  336. }
  337. $level = explode('.', $part->mime_id);
  338. // Check if the part belongs to higher-level's alternative/related
  339. while (array_pop($level) !== null) {
  340. if (!count($level)) {
  341. return true;
  342. }
  343. $parent = $this->mime_parts[join('.', $level)];
  344. if ($parent->mimetype != 'multipart/alternative' && $parent->mimetype != 'multipart/related') {
  345. continue 2;
  346. }
  347. }
  348. if ($part->size) {
  349. return true;
  350. }
  351. }
  352. }
  353. $part = null;
  354. return false;
  355. }
  356. /**
  357. * Return the first HTML part of this message
  358. *
  359. * @param rcube_message_part &$part Reference to the part if found
  360. * @param bool $enriched Enables checking for text/enriched parts too
  361. *
  362. * @return string HTML message part content
  363. */
  364. public function first_html_part(&$part = null, $enriched = false)
  365. {
  366. if ($this->has_html_part($enriched, $part)) {
  367. $body = $this->get_part_body($part->mime_id, true);
  368. if ($part->mimetype == 'text/enriched') {
  369. $body = rcube_enriched::to_html($body);
  370. }
  371. return $body;
  372. }
  373. }
  374. /**
  375. * Return the first text part of this message.
  376. * If there's no text/plain part but $strict=true and text/html part
  377. * exists, it will be returned in text/plain format.
  378. *
  379. * @param rcube_message_part &$part Reference to the part if found
  380. * @param bool $strict Check only text/plain parts
  381. *
  382. * @return string Plain text message/part content
  383. */
  384. public function first_text_part(&$part = null, $strict = false)
  385. {
  386. // no message structure, return complete body
  387. if (empty($this->parts)) {
  388. return $this->body;
  389. }
  390. if ($this->has_text_part($part)) {
  391. return $this->get_part_body($part->mime_id, true);
  392. }
  393. if (!$strict && ($body = $this->first_html_part($part, true))) {
  394. // create instance of html2text class
  395. $h2t = new rcube_html2text($body);
  396. return $h2t->get_text();
  397. }
  398. }
  399. /**
  400. * Checks if part of the message is an attachment (or part of it)
  401. *
  402. * @param rcube_message_part $part Message part
  403. *
  404. * @return bool True if the part is an attachment part
  405. */
  406. public function is_attachment($part)
  407. {
  408. foreach ($this->attachments as $att_part) {
  409. if ($att_part->mime_id == $part->mime_id) {
  410. return true;
  411. }
  412. // check if the part is a subpart of another attachment part (message/rfc822)
  413. if ($att_part->mimetype == 'message/rfc822') {
  414. if (in_array($part, (array)$att_part->parts)) {
  415. return true;
  416. }
  417. }
  418. }
  419. return false;
  420. }
  421. /**
  422. * In a multipart/encrypted encrypted message,
  423. * find the encrypted message payload part.
  424. *
  425. * @return rcube_message_part
  426. */
  427. public function get_multipart_encrypted_part()
  428. {
  429. foreach ($this->mime_parts as $mime_id => $mpart) {
  430. if ($mpart->mimetype == 'multipart/encrypted') {
  431. $this->pgp_mime = true;
  432. }
  433. if ($this->pgp_mime && ($mpart->mimetype == 'application/octet-stream' ||
  434. (!empty($mpart->filename) && $mpart->filename != 'version.txt'))) {
  435. $this->encrypted_part = $mime_id;
  436. return $mpart;
  437. }
  438. }
  439. return false;
  440. }
  441. /**
  442. * Read the message structure returend by the IMAP server
  443. * and build flat lists of content parts and attachments
  444. *
  445. * @param rcube_message_part $structure Message structure node
  446. * @param bool $recursive True when called recursively
  447. */
  448. private function parse_structure($structure, $recursive = false)
  449. {
  450. // real content-type of message/rfc822 part
  451. if ($structure->mimetype == 'message/rfc822' && $structure->real_mimetype) {
  452. $mimetype = $structure->real_mimetype;
  453. // parse headers from message/rfc822 part
  454. if (!isset($structure->headers['subject']) && !isset($structure->headers['from'])) {
  455. list($headers, ) = explode("\r\n\r\n", $this->get_part_body($structure->mime_id, false, 32768));
  456. $structure->headers = rcube_mime::parse_headers($headers);
  457. }
  458. }
  459. else {
  460. $mimetype = $structure->mimetype;
  461. }
  462. // show message headers
  463. if ($recursive && is_array($structure->headers) &&
  464. (isset($structure->headers['subject']) || $structure->headers['from'] || $structure->headers['to'])) {
  465. $c = new stdClass;
  466. $c->type = 'headers';
  467. $c->headers = $structure->headers;
  468. $this->parts[] = $c;
  469. }
  470. // Allow plugins to handle message parts
  471. $plugin = $this->app->plugins->exec_hook('message_part_structure',
  472. array('object' => $this, 'structure' => $structure,
  473. 'mimetype' => $mimetype, 'recursive' => $recursive));
  474. if ($plugin['abort']) {
  475. return;
  476. }
  477. $structure = $plugin['structure'];
  478. $mimetype = $plugin['mimetype'];
  479. $recursive = $plugin['recursive'];
  480. list($message_ctype_primary, $message_ctype_secondary) = explode('/', $mimetype);
  481. // print body if message doesn't have multiple parts
  482. if ($message_ctype_primary == 'text' && !$recursive) {
  483. // parts with unsupported type add to attachments list
  484. if (!in_array($message_ctype_secondary, array('plain', 'html', 'enriched'))) {
  485. $this->attachments[] = $structure;
  486. return;
  487. }
  488. $structure->type = 'content';
  489. $this->parts[] = $structure;
  490. // Parse simple (plain text) message body
  491. if ($message_ctype_secondary == 'plain') {
  492. foreach ((array)$this->uu_decode($structure) as $uupart) {
  493. $this->mime_parts[$uupart->mime_id] = $uupart;
  494. $this->attachments[] = $uupart;
  495. }
  496. }
  497. }
  498. // the same for pgp signed messages
  499. else if ($mimetype == 'application/pgp' && !$recursive) {
  500. $structure->type = 'content';
  501. $this->parts[] = $structure;
  502. }
  503. // message contains (more than one!) alternative parts
  504. else if ($mimetype == 'multipart/alternative'
  505. && is_array($structure->parts) && count($structure->parts) > 1
  506. ) {
  507. // get html/plaintext parts, other add to attachments list
  508. foreach ($structure->parts as $p => $sub_part) {
  509. $sub_mimetype = $sub_part->mimetype;
  510. $is_multipart = preg_match('/^multipart\/(related|relative|mixed|alternative)/', $sub_mimetype);
  511. // skip empty text parts
  512. if (!$sub_part->size && !$is_multipart) {
  513. continue;
  514. }
  515. // We've encountered (malformed) messages with more than
  516. // one text/plain or text/html part here. There's no way to choose
  517. // which one is better, so we'll display first of them and add
  518. // others as attachments (#1489358)
  519. // check if sub part is
  520. if ($is_multipart)
  521. $related_part = $p;
  522. else if ($sub_mimetype == 'text/plain' && !$plain_part)
  523. $plain_part = $p;
  524. else if ($sub_mimetype == 'text/html' && !$html_part) {
  525. $html_part = $p;
  526. $this->got_html_part = true;
  527. }
  528. else if ($sub_mimetype == 'text/enriched' && !$enriched_part)
  529. $enriched_part = $p;
  530. else {
  531. // add unsupported/unrecognized parts to attachments list
  532. $this->attachments[] = $sub_part;
  533. }
  534. }
  535. // parse related part (alternative part could be in here)
  536. if ($related_part !== null && !$this->parse_alternative) {
  537. $this->parse_alternative = true;
  538. $this->parse_structure($structure->parts[$related_part], true);
  539. $this->parse_alternative = false;
  540. // if plain part was found, we should unset it if html is preferred
  541. if ($this->opt['prefer_html'] && count($this->parts))
  542. $plain_part = null;
  543. }
  544. // choose html/plain part to print
  545. if ($html_part !== null && $this->opt['prefer_html']) {
  546. $print_part = $structure->parts[$html_part];
  547. }
  548. else if ($enriched_part !== null) {
  549. $print_part = $structure->parts[$enriched_part];
  550. }
  551. else if ($plain_part !== null) {
  552. $print_part = $structure->parts[$plain_part];
  553. }
  554. // add the right message body
  555. if (is_object($print_part)) {
  556. $print_part->type = 'content';
  557. $this->parts[] = $print_part;
  558. }
  559. // show plaintext warning
  560. else if ($html_part !== null && empty($this->parts)) {
  561. $c = new stdClass;
  562. $c->type = 'content';
  563. $c->ctype_primary = 'text';
  564. $c->ctype_secondary = 'plain';
  565. $c->mimetype = 'text/plain';
  566. $c->realtype = 'text/html';
  567. $this->parts[] = $c;
  568. }
  569. }
  570. // this is an ecrypted message -> create a plaintext body with the according message
  571. else if ($mimetype == 'multipart/encrypted') {
  572. $p = new stdClass;
  573. $p->type = 'content';
  574. $p->ctype_primary = 'text';
  575. $p->ctype_secondary = 'plain';
  576. $p->mimetype = 'text/plain';
  577. $p->realtype = 'multipart/encrypted';
  578. $p->mime_id = $structure->mime_id;
  579. $this->parts[] = $p;
  580. // add encrypted payload part as attachment
  581. if (is_array($structure->parts)) {
  582. for ($i=0; $i < count($structure->parts); $i++) {
  583. $subpart = $structure->parts[$i];
  584. if ($subpart->mimetype == 'application/octet-stream' || !empty($subpart->filename)) {
  585. $this->attachments[] = $subpart;
  586. }
  587. }
  588. }
  589. }
  590. // this is an S/MIME ecrypted message -> create a plaintext body with the according message
  591. else if ($mimetype == 'application/pkcs7-mime') {
  592. $p = new stdClass;
  593. $p->type = 'content';
  594. $p->ctype_primary = 'text';
  595. $p->ctype_secondary = 'plain';
  596. $p->mimetype = 'text/plain';
  597. $p->realtype = 'application/pkcs7-mime';
  598. $p->mime_id = $structure->mime_id;
  599. $this->parts[] = $p;
  600. if (!empty($structure->filename)) {
  601. $this->attachments[] = $structure;
  602. }
  603. }
  604. // message contains multiple parts
  605. else if (is_array($structure->parts) && !empty($structure->parts)) {
  606. // iterate over parts
  607. for ($i=0; $i < count($structure->parts); $i++) {
  608. $mail_part = &$structure->parts[$i];
  609. $primary_type = $mail_part->ctype_primary;
  610. $secondary_type = $mail_part->ctype_secondary;
  611. $part_mimetype = $mail_part->mimetype;
  612. // multipart/alternative or message/rfc822
  613. if ($primary_type == 'multipart' || $part_mimetype == 'message/rfc822') {
  614. $this->parse_structure($mail_part, true);
  615. // list message/rfc822 as attachment as well (mostly .eml)
  616. if ($primary_type == 'message' && !empty($mail_part->filename)) {
  617. $this->attachments[] = $mail_part;
  618. }
  619. }
  620. // part text/[plain|html] or delivery status
  621. else if ((($part_mimetype == 'text/plain' || $part_mimetype == 'text/html') && $mail_part->disposition != 'attachment') ||
  622. in_array($part_mimetype, array('message/delivery-status', 'text/rfc822-headers', 'message/disposition-notification'))
  623. ) {
  624. // Allow plugins to handle also this part
  625. $plugin = $this->app->plugins->exec_hook('message_part_structure',
  626. array('object' => $this, 'structure' => $mail_part,
  627. 'mimetype' => $part_mimetype, 'recursive' => true));
  628. if ($plugin['abort']) {
  629. continue;
  630. }
  631. if ($part_mimetype == 'text/html' && $mail_part->size) {
  632. $this->got_html_part = true;
  633. }
  634. $mail_part = $plugin['structure'];
  635. list($primary_type, $secondary_type) = explode('/', $plugin['mimetype']);
  636. // add text part if it matches the prefs
  637. if (!$this->parse_alternative ||
  638. ($secondary_type == 'html' && $this->opt['prefer_html']) ||
  639. ($secondary_type == 'plain' && !$this->opt['prefer_html'])
  640. ) {
  641. $mail_part->type = 'content';
  642. $this->parts[] = $mail_part;
  643. }
  644. // list as attachment as well
  645. if (!empty($mail_part->filename)) {
  646. $this->attachments[] = $mail_part;
  647. }
  648. }
  649. // ignore "virtual" protocol parts
  650. else if ($primary_type == 'protocol') {
  651. continue;
  652. }
  653. // part is Microsoft Outlook TNEF (winmail.dat)
  654. else if ($part_mimetype == 'application/ms-tnef') {
  655. $tnef_parts = (array) $this->tnef_decode($mail_part);
  656. foreach ($tnef_parts as $tpart) {
  657. $this->mime_parts[$tpart->mime_id] = $tpart;
  658. $this->attachments[] = $tpart;
  659. }
  660. // add winmail.dat to the list if it's content is unknown
  661. if (empty($tnef_parts) && !empty($mail_part->filename)) {
  662. $this->mime_parts[$mail_part->mime_id] = $mail_part;
  663. $this->attachments[] = $mail_part;
  664. }
  665. }
  666. // part is a file/attachment
  667. else if (preg_match('/^(inline|attach)/', $mail_part->disposition) ||
  668. $mail_part->headers['content-id'] ||
  669. ($mail_part->filename &&
  670. (empty($mail_part->disposition) || preg_match('/^[a-z0-9!#$&.+^_-]+$/i', $mail_part->disposition)))
  671. ) {
  672. // skip apple resource forks
  673. if ($message_ctype_secondary == 'appledouble' && $secondary_type == 'applefile')
  674. continue;
  675. // part belongs to a related message and is linked
  676. if (preg_match('/^multipart\/(related|relative)/', $mimetype)
  677. && ($mail_part->headers['content-id'] || $mail_part->headers['content-location'])
  678. ) {
  679. if ($mail_part->headers['content-id'])
  680. $mail_part->content_id = preg_replace(array('/^</', '/>$/'), '', $mail_part->headers['content-id']);
  681. if ($mail_part->headers['content-location'])
  682. $mail_part->content_location = $mail_part->headers['content-base'] . $mail_part->headers['content-location'];
  683. $this->inline_parts[] = $mail_part;
  684. }
  685. // regular attachment with valid content type
  686. // (content-type name regexp according to RFC4288.4.2)
  687. else if (preg_match('/^[a-z0-9!#$&.+^_-]+\/[a-z0-9!#$&.+^_-]+$/i', $part_mimetype)) {
  688. $this->attachments[] = $mail_part;
  689. }
  690. // attachment with invalid content type
  691. // replace malformed content type with application/octet-stream (#1487767)
  692. else if ($mail_part->filename) {
  693. $mail_part->ctype_primary = 'application';
  694. $mail_part->ctype_secondary = 'octet-stream';
  695. $mail_part->mimetype = 'application/octet-stream';
  696. $this->attachments[] = $mail_part;
  697. }
  698. }
  699. // calendar part not marked as attachment (#1490325)
  700. else if ($part_mimetype == 'text/calendar') {
  701. if (!$mail_part->filename) {
  702. $mail_part->filename = 'calendar.ics';
  703. }
  704. $this->attachments[] = $mail_part;
  705. }
  706. }
  707. // if this was a related part try to resolve references
  708. if (preg_match('/^multipart\/(related|relative)/', $mimetype) && sizeof($this->inline_parts)) {
  709. $a_replaces = array();
  710. $img_regexp = '/^image\/(gif|jpe?g|png|tiff|bmp|svg)/';
  711. foreach ($this->inline_parts as $inline_object) {
  712. $part_url = $this->get_part_url($inline_object->mime_id, $inline_object->ctype_primary);
  713. if (isset($inline_object->content_id))
  714. $a_replaces['cid:'.$inline_object->content_id] = $part_url;
  715. if ($inline_object->content_location) {
  716. $a_replaces[$inline_object->content_location] = $part_url;
  717. }
  718. if (!empty($inline_object->filename)) {
  719. // MS Outlook sends sometimes non-related attachments as related
  720. // In this case multipart/related message has only one text part
  721. // We'll add all such attachments to the attachments list
  722. if (!isset($this->got_html_part)) {
  723. $this->attachments[] = $inline_object;
  724. }
  725. // MS Outlook sometimes also adds non-image attachments as related
  726. // We'll add all such attachments to the attachments list
  727. // Warning: some browsers support pdf in <img/>
  728. else if (!preg_match($img_regexp, $inline_object->mimetype)) {
  729. $this->attachments[] = $inline_object;
  730. }
  731. // @TODO: we should fetch HTML body and find attachment's content-id
  732. // to handle also image attachments without reference in the body
  733. // @TODO: should we list all image attachments in text mode?
  734. }
  735. }
  736. // add replace array to each content part
  737. // (will be applied later when part body is available)
  738. foreach ($this->parts as $i => $part) {
  739. if ($part->type == 'content')
  740. $this->parts[$i]->replaces = $a_replaces;
  741. }
  742. }
  743. }
  744. // message is a single part non-text
  745. else if ($structure->filename) {
  746. $this->attachments[] = $structure;
  747. }
  748. // message is a single part non-text (without filename)
  749. else if (preg_match('/application\//i', $mimetype)) {
  750. $this->attachments[] = $structure;
  751. }
  752. }
  753. /**
  754. * Fill aflat array with references to all parts, indexed by part numbers
  755. *
  756. * @param rcube_message_part $part Message body structure
  757. */
  758. private function get_mime_numbers(&$part)
  759. {
  760. if (strlen($part->mime_id))
  761. $this->mime_parts[$part->mime_id] = &$part;
  762. if (is_array($part->parts))
  763. for ($i=0; $i<count($part->parts); $i++)
  764. $this->get_mime_numbers($part->parts[$i]);
  765. }
  766. /**
  767. * Decode a Microsoft Outlook TNEF part (winmail.dat)
  768. *
  769. * @param rcube_message_part $part Message part to decode
  770. * @return array
  771. */
  772. function tnef_decode(&$part)
  773. {
  774. // @TODO: attachment may be huge, handle body via file
  775. $body = $this->get_part_body($part->mime_id);
  776. $tnef = new rcube_tnef_decoder;
  777. $tnef_arr = $tnef->decompress($body);
  778. $parts = array();
  779. unset($body);
  780. foreach ($tnef_arr as $pid => $winatt) {
  781. $tpart = new rcube_message_part;
  782. $tpart->filename = $this->fix_attachment_name(trim($winatt['name']), $part);
  783. $tpart->encoding = 'stream';
  784. $tpart->ctype_primary = trim(strtolower($winatt['type']));
  785. $tpart->ctype_secondary = trim(strtolower($winatt['subtype']));
  786. $tpart->mimetype = $tpart->ctype_primary . '/' . $tpart->ctype_secondary;
  787. $tpart->mime_id = 'winmail.' . $part->mime_id . '.' . $pid;
  788. $tpart->size = $winatt['size'];
  789. $tpart->body = $winatt['stream'];
  790. $parts[] = $tpart;
  791. unset($tnef_arr[$pid]);
  792. }
  793. return $parts;
  794. }
  795. /**
  796. * Parse message body for UUencoded attachments bodies
  797. *
  798. * @param rcube_message_part $part Message part to decode
  799. * @return array
  800. */
  801. function uu_decode(&$part)
  802. {
  803. // @TODO: messages may be huge, handle body via file
  804. $part->body = $this->get_part_body($part->mime_id);
  805. $parts = array();
  806. $pid = 0;
  807. // FIXME: line length is max.65?
  808. $uu_regexp_begin = '/begin [0-7]{3,4} ([^\r\n]+)\r?\n/s';
  809. $uu_regexp_end = '/`\r?\nend((\r?\n)|($))/s';
  810. while (preg_match($uu_regexp_begin, $part->body, $matches, PREG_OFFSET_CAPTURE)) {
  811. $startpos = $matches[0][1];
  812. if (!preg_match($uu_regexp_end, $part->body, $m, PREG_OFFSET_CAPTURE, $startpos)) {
  813. break;
  814. }
  815. $endpos = $m[0][1];
  816. $begin_len = strlen($matches[0][0]);
  817. $end_len = strlen($m[0][0]);
  818. // extract attachment body
  819. $filebody = substr($part->body, $startpos + $begin_len, $endpos - $startpos - $begin_len - 1);
  820. $filebody = str_replace("\r\n", "\n", $filebody);
  821. // remove attachment body from the message body
  822. $part->body = substr_replace($part->body, '', $startpos, $endpos + $end_len - $startpos);
  823. // mark body as modified so it will not be cached by rcube_imap_cache
  824. $part->body_modified = true;
  825. // add attachments to the structure
  826. $uupart = new rcube_message_part;
  827. $uupart->filename = trim($matches[1][0]);
  828. $uupart->encoding = 'stream';
  829. $uupart->body = convert_uudecode($filebody);
  830. $uupart->size = strlen($uupart->body);
  831. $uupart->mime_id = 'uu.' . $part->mime_id . '.' . $pid;
  832. $ctype = rcube_mime::file_content_type($uupart->body, $uupart->filename, 'application/octet-stream', true);
  833. $uupart->mimetype = $ctype;
  834. list($uupart->ctype_primary, $uupart->ctype_secondary) = explode('/', $ctype);
  835. $parts[] = $uupart;
  836. $pid++;
  837. }
  838. return $parts;
  839. }
  840. /**
  841. * Fix attachment name encoding if needed/possible
  842. */
  843. protected function fix_attachment_name($name, $part)
  844. {
  845. if ($name == rcube_charset::clean($name)) {
  846. return $name;
  847. }
  848. // find charset from part or its parent(s)
  849. if ($part->charset) {
  850. $charsets[] = $part->charset;
  851. }
  852. else {
  853. // check first part (common case)
  854. $n = strpos($part->mime_id, '.') ? preg_replace('/\.[0-9]+$/', '', $part->mime_id) . '.1' : 1;
  855. if (($_part = $this->mime_parts[$n]) && $_part->charset) {
  856. $charsets[] = $_part->charset;
  857. }
  858. // check parents' charset
  859. $items = explode('.', $part->mime_id);
  860. for ($i = count($items)-1; $i > 0; $i--) {
  861. $last = array_pop($items);
  862. $parent = $this->mime_parts[join('.', $items)];
  863. if ($parent && $parent->charset) {
  864. $charsets[] = $parent->charset;
  865. }
  866. }
  867. }
  868. if ($this->headers->charset) {
  869. $charsets[] = $this->headers->charset;
  870. }
  871. if (empty($charsets)) {
  872. $rcube = rcube::get_instance();
  873. $charsets[] = rcube_charset::detect($name, $rcube->config->get('default_charset', RCUBE_CHARSET));
  874. }
  875. foreach (array_unique($charsets) as $charset) {
  876. $_name = rcube_charset::convert($name, $charset);
  877. if ($_name == rcube_charset::clean($_name)) {
  878. if (!$part->charset) {
  879. $part->charset = $charset;
  880. }
  881. return $_name;
  882. }
  883. }
  884. return $name;
  885. }
  886. /**
  887. * Deprecated methods (to be removed)
  888. */
  889. public static function unfold_flowed($text)
  890. {
  891. return rcube_mime::unfold_flowed($text);
  892. }
  893. public static function format_flowed($text, $length = 72)
  894. {
  895. return rcube_mime::format_flowed($text, $length);
  896. }
  897. }