2
0

rcube_message.php 41 KB

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