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 41KB

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