4 +-----------------------------------------------------------------------+
5 | program/include/rcube_message.php |
7 | This file is part of the Roundcube Webmail client |
8 | Copyright (C) 2008-2010, Roundcube Dev. - Switzerland |
9 | Licensed under the GNU GPL |
12 | Logical representation of a mail message with all its data |
13 | and related functions |
14 +-----------------------------------------------------------------------+
15 | Author: Thomas Bruederli <roundcube@gmail.com> |
16 +-----------------------------------------------------------------------+
18 $Id: rcube_message.php 4288 2010-11-29 09:54:15Z alec $
24 * Logical representation of a mail message with all its data
25 * and related functions
28 * @author Thomas Bruederli <roundcube@gmail.com>
40 * Instance of imap class
45 private $opt = array();
46 private $inline_parts = array();
47 private $parse_alternative = false;
52 public $parts = array();
53 public $mime_parts = array();
54 public $attachments = array();
56 public $sender = null;
57 public $is_safe = false;
63 * Provide a uid, and parse message structure.
65 * @param string $uid The message UID.
67 * @uses rcmail::get_instance()
68 * @uses rcube_imap::decode_mime_string()
69 * @uses self::set_safe()
71 * @see self::$app, self::$imap, self::$opt, self::$structure
73 function __construct($uid)
75 $this->app = rcmail::get_instance();
76 $this->imap = $this->app->imap;
77 $this->imap->get_all_headers = true;
80 $this->headers = $this->imap->get_headers($uid, NULL, true, true);
85 $this->subject = rcube_imap::decode_mime_string(
86 $this->headers->subject, $this->headers->charset);
87 list(, $this->sender) = each($this->imap->decode_address_list($this->headers->from));
89 $this->set_safe((intval($_GET['_safe']) || $_SESSION['safe_messages'][$uid]));
91 'safe' => $this->is_safe,
92 'prefer_html' => $this->app->config->get('prefer_html'),
93 'get_url' => rcmail_url('get', array(
94 '_mbox' => $this->imap->get_mailbox_name(), '_uid' => $uid))
97 if ($this->structure = $this->imap->get_structure($uid, $this->headers->body_structure)) {
98 $this->get_mime_numbers($this->structure);
99 $this->parse_structure($this->structure);
102 $this->body = $this->imap->get_body($uid);
105 // notify plugins and let them analyze this structured message object
106 $this->app->plugins->exec_hook('message_load', array('object' => $this));
111 * Return a (decoded) message header
113 * @param string $name Header name
114 * @param bool $row Don't mime-decode the value
115 * @return string Header value
117 public function get_header($name, $raw = false)
119 if ($this->headers->$name)
120 $value = $this->headers->$name;
121 else if ($this->headers->others[$name])
122 $value = $this->headers->others[$name];
124 return $raw ? $value : $this->imap->decode_header($value);
129 * Set is_safe var and session data
131 * @param bool $safe enable/disable
133 public function set_safe($safe = true)
135 $this->is_safe = $safe;
136 $_SESSION['safe_messages'][$this->uid] = $this->is_safe;
141 * Compose a valid URL for getting a message part
143 * @param string $mime_id Part MIME-ID
144 * @return string URL or false if part does not exist
146 public function get_part_url($mime_id)
148 if ($this->mime_parts[$mime_id])
149 return $this->opt['get_url'] . '&_part=' . $mime_id;
156 * Get content of a specific part of this message
158 * @param string $mime_id Part MIME-ID
159 * @param resource $fp File pointer to save the message part
160 * @return string Part content
162 public function get_part_content($mime_id, $fp=NULL)
164 if ($part = $this->mime_parts[$mime_id]) {
165 // stored in message structure (winmail/inline-uuencode)
166 if ($part->encoding == 'stream') {
168 fwrite($fp, $part->body);
170 return $fp ? true : $part->body;
173 return $this->imap->get_message_part($this->uid, $mime_id, $part, NULL, $fp);
180 * Determine if the message contains a HTML part
182 * @return bool True if a HTML is available, False if not
184 function has_html_part()
186 // check all message parts
187 foreach ($this->parts as $pid => $part) {
188 $mimetype = strtolower($part->ctype_primary . '/' . $part->ctype_secondary);
189 if ($mimetype == 'text/html')
198 * Return the first HTML part of this message
200 * @return string HTML message part content
202 function first_html_part()
204 // check all message parts
205 foreach ($this->mime_parts as $mime_id => $part) {
206 $mimetype = strtolower($part->ctype_primary . '/' . $part->ctype_secondary);
207 if ($mimetype == 'text/html') {
208 return $this->imap->get_message_part($this->uid, $mime_id, $part);
215 * Return the first text part of this message
217 * @param rcube_message_part $part Reference to the part if found
218 * @return string Plain text message/part content
220 function first_text_part(&$part=null)
222 // no message structure, return complete body
223 if (empty($this->parts))
226 // check all message parts
227 foreach ($this->mime_parts as $mime_id => $part) {
228 $mimetype = $part->ctype_primary . '/' . $part->ctype_secondary;
230 if ($mimetype == 'text/plain') {
231 return $this->imap->get_message_part($this->uid, $mime_id, $part);
233 else if ($mimetype == 'text/html') {
234 $out = $this->imap->get_message_part($this->uid, $mime_id, $part);
236 // remove special chars encoding
237 $trans = array_flip(get_html_translation_table(HTML_ENTITIES));
238 $out = strtr($out, $trans);
240 // create instance of html2text class
241 $txt = new html2text($out);
242 return $txt->get_text();
252 * Raad the message structure returend by the IMAP server
253 * and build flat lists of content parts and attachments
255 * @param rcube_message_part $structure Message structure node
256 * @param bool $recursive True when called recursively
258 private function parse_structure($structure, $recursive = false)
260 // real content-type of message/rfc822 part
261 if ($structure->mimetype == 'message/rfc822' && $structure->real_mimetype)
262 $mimetype = $structure->real_mimetype;
264 $mimetype = $structure->mimetype;
266 // show message headers
267 if ($recursive && is_array($structure->headers) && isset($structure->headers['subject'])) {
269 $c->type = 'headers';
270 $c->headers = &$structure->headers;
274 // Allow plugins to handle message parts
275 $plugin = $this->app->plugins->exec_hook('message_part_structure',
276 array('object' => $this, 'structure' => $structure,
277 'mimetype' => $mimetype, 'recursive' => $recursive));
279 if ($plugin['abort'])
282 $structure = $plugin['structure'];
283 list($message_ctype_primary, $message_ctype_secondary) = explode('/', $plugin['mimetype']);
285 // print body if message doesn't have multiple parts
286 if ($message_ctype_primary == 'text' && !$recursive) {
287 $structure->type = 'content';
288 $this->parts[] = &$structure;
290 // Parse simple (plain text) message body
291 if ($message_ctype_secondary == 'plain')
292 foreach ((array)$this->uu_decode($structure) as $uupart) {
293 $this->mime_parts[$uupart->mime_id] = $uupart;
294 $this->attachments[] = $uupart;
297 // the same for pgp signed messages
298 else if ($mimetype == 'application/pgp' && !$recursive) {
299 $structure->type = 'content';
300 $this->parts[] = &$structure;
302 // message contains alternative parts
303 else if ($mimetype == 'multipart/alternative' && is_array($structure->parts)) {
304 // get html/plaintext parts
305 $plain_part = $html_part = $print_part = $related_part = null;
307 foreach ($structure->parts as $p => $sub_part) {
308 $sub_mimetype = $sub_part->mimetype;
310 // check if sub part is
311 if ($sub_mimetype == 'text/plain')
313 else if ($sub_mimetype == 'text/html')
315 else if ($sub_mimetype == 'text/enriched')
317 else if (in_array($sub_mimetype, array('multipart/related', 'multipart/mixed', 'multipart/alternative')))
321 // parse related part (alternative part could be in here)
322 if ($related_part !== null && !$this->parse_alternative) {
323 $this->parse_alternative = true;
324 $this->parse_structure($structure->parts[$related_part], true);
325 $this->parse_alternative = false;
327 // if plain part was found, we should unset it if html is preferred
328 if ($this->opt['prefer_html'] && count($this->parts))
332 // choose html/plain part to print
333 if ($html_part !== null && $this->opt['prefer_html']) {
334 $print_part = &$structure->parts[$html_part];
336 else if ($enriched_part !== null) {
337 $print_part = &$structure->parts[$enriched_part];
339 else if ($plain_part !== null) {
340 $print_part = &$structure->parts[$plain_part];
343 // add the right message body
344 if (is_object($print_part)) {
345 $print_part->type = 'content';
346 $this->parts[] = $print_part;
348 // show plaintext warning
349 else if ($html_part !== null && empty($this->parts)) {
351 $c->type = 'content';
352 $c->ctype_primary = 'text';
353 $c->ctype_secondary = 'plain';
354 $c->body = rcube_label('htmlmessage');
359 // add html part as attachment
360 if ($html_part !== null && $structure->parts[$html_part] !== $print_part) {
361 $html_part = &$structure->parts[$html_part];
362 $html_part->filename = rcube_label('htmlmessage');
363 $html_part->mimetype = 'text/html';
365 $this->attachments[] = $html_part;
368 // this is an ecrypted message -> create a plaintext body with the according message
369 else if ($mimetype == 'multipart/encrypted') {
371 $p->type = 'content';
372 $p->ctype_primary = 'text';
373 $p->ctype_secondary = 'plain';
374 $p->body = rcube_label('encryptedmessage');
375 $p->size = strlen($p->body);
377 // message contains multiple parts
378 else if (is_array($structure->parts) && !empty($structure->parts)) {
379 // iterate over parts
380 for ($i=0; $i < count($structure->parts); $i++) {
381 $mail_part = &$structure->parts[$i];
382 $primary_type = $mail_part->ctype_primary;
383 $secondary_type = $mail_part->ctype_secondary;
385 // real content-type of message/rfc822
386 if ($mail_part->real_mimetype) {
387 $part_orig_mimetype = $mail_part->mimetype;
388 $part_mimetype = $mail_part->real_mimetype;
389 list($primary_type, $secondary_type) = explode('/', $part_mimetype);
392 $part_mimetype = $mail_part->mimetype;
394 // multipart/alternative
395 if ($primary_type == 'multipart') {
396 $this->parse_structure($mail_part, true);
398 // list message/rfc822 as attachment as well (mostly .eml)
399 if ($part_orig_mimetype == 'message/rfc822' && !empty($mail_part->filename))
400 $this->attachments[] = $mail_part;
402 // part text/[plain|html] or delivery status
403 else if ((($part_mimetype == 'text/plain' || $part_mimetype == 'text/html') && $mail_part->disposition != 'attachment') ||
404 in_array($part_mimetype, array('message/delivery-status', 'text/rfc822-headers', 'message/disposition-notification'))
406 // Allow plugins to handle also this part
407 $plugin = $this->app->plugins->exec_hook('message_part_structure',
408 array('object' => $this, 'structure' => $mail_part,
409 'mimetype' => $part_mimetype, 'recursive' => true));
411 if ($plugin['abort'])
414 if ($part_mimetype == 'text/html') {
415 $got_html_part = true;
418 $mail_part = $plugin['structure'];
419 list($primary_type, $secondary_type) = explode('/', $plugin['mimetype']);
421 // add text part if it matches the prefs
422 if (!$this->parse_alternative ||
423 ($secondary_type == 'html' && $this->opt['prefer_html']) ||
424 ($secondary_type == 'plain' && !$this->opt['prefer_html'])
426 $mail_part->type = 'content';
427 $this->parts[] = $mail_part;
430 // list as attachment as well
431 if (!empty($mail_part->filename))
432 $this->attachments[] = $mail_part;
435 else if ($primary_type=='message') {
436 $this->parse_structure($mail_part, true);
438 // list as attachment as well (mostly .eml)
439 if (!empty($mail_part->filename))
440 $this->attachments[] = $mail_part;
442 // ignore "virtual" protocol parts
443 else if ($primary_type == 'protocol') {
446 // part is Microsoft Outlook TNEF (winmail.dat)
447 else if ($part_mimetype == 'application/ms-tnef') {
448 foreach ((array)$this->tnef_decode($mail_part) as $tpart) {
449 $this->mime_parts[$tpart->mime_id] = $tpart;
450 $this->attachments[] = $tpart;
453 // part is a file/attachment
454 else if (preg_match('/^(inline|attach)/', $mail_part->disposition) ||
455 $mail_part->headers['content-id'] ||
456 ($mail_part->filename &&
457 (empty($mail_part->disposition) || preg_match('/^[a-z0-9!#$&.+^_-]+$/i', $mail_part->disposition)))
459 // skip apple resource forks
460 if ($message_ctype_secondary == 'appledouble' && $secondary_type == 'applefile')
463 // part belongs to a related message and is linked
464 if ($mimetype == 'multipart/related'
465 && ($mail_part->headers['content-id'] || $mail_part->headers['content-location'])) {
466 if ($mail_part->headers['content-id'])
467 $mail_part->content_id = preg_replace(array('/^</', '/>$/'), '', $mail_part->headers['content-id']);
468 if ($mail_part->headers['content-location'])
469 $mail_part->content_location = $mail_part->headers['content-base'] . $mail_part->headers['content-location'];
471 $this->inline_parts[] = $mail_part;
473 // attachment encapsulated within message/rfc822 part needs further decoding (#1486743)
474 else if ($part_orig_mimetype == 'message/rfc822') {
475 $this->parse_structure($mail_part, true);
477 // list as attachment as well (mostly .eml)
478 if (!empty($mail_part->filename))
479 $this->attachments[] = $mail_part;
481 // is a regular attachment (content-type name regexp according to RFC4288.4.2)
482 else if (preg_match('/^[a-z0-9!#$&.+^_-]+\/[a-z0-9!#$&.+^_-]+$/i', $part_mimetype)) {
483 if (!$mail_part->filename)
484 $mail_part->filename = 'Part '.$mail_part->mime_id;
485 $this->attachments[] = $mail_part;
490 // if this was a related part try to resolve references
491 if ($mimetype == 'multipart/related' && sizeof($this->inline_parts)) {
492 $a_replaces = array();
494 foreach ($this->inline_parts as $inline_object) {
495 $part_url = $this->get_part_url($inline_object->mime_id);
496 if ($inline_object->content_id)
497 $a_replaces['cid:'.$inline_object->content_id] = $part_url;
498 if ($inline_object->content_location) {
499 $a_replaces[$inline_object->content_location] = $part_url;
501 // MS Outlook sends sometimes non-related attachments as related
502 // In this case multipart/related message has only one text part
503 // We'll add all such attachments to the attachments list
504 if (!isset($got_html_part) && empty($inline_object->content_id)
505 && !empty($inline_object->filename)
507 $this->attachments[] = $inline_object;
511 // add replace array to each content part
512 // (will be applied later when part body is available)
513 foreach ($this->parts as $i => $part) {
514 if ($part->type == 'content')
515 $this->parts[$i]->replaces = $a_replaces;
519 // message is a single part non-text
520 else if ($structure->filename) {
521 $this->attachments[] = $structure;
523 // message is a single part non-text (without filename)
524 else if (preg_match('/application\//i', $mimetype)) {
525 $structure->filename = 'Part '.$structure->mime_id;
526 $this->attachments[] = $structure;
532 * Fill aflat array with references to all parts, indexed by part numbers
534 * @param rcube_message_part $part Message body structure
536 private function get_mime_numbers(&$part)
538 if (strlen($part->mime_id))
539 $this->mime_parts[$part->mime_id] = &$part;
541 if (is_array($part->parts))
542 for ($i=0; $i<count($part->parts); $i++)
543 $this->get_mime_numbers($part->parts[$i]);
548 * Decode a Microsoft Outlook TNEF part (winmail.dat)
550 * @param rcube_message_part $part Message part to decode
553 function tnef_decode(&$part)
555 // @TODO: attachment may be huge, hadle it via file
556 if (!isset($part->body))
557 $part->body = $this->imap->get_message_part($this->uid, $part->mime_id, $part);
560 $tnef = new tnef_decoder;
561 $tnef_arr = $tnef->decompress($part->body);
563 foreach ($tnef_arr as $pid => $winatt) {
564 $tpart = new rcube_message_part;
566 $tpart->filename = trim($winatt['name']);
567 $tpart->encoding = 'stream';
568 $tpart->ctype_primary = trim(strtolower($winatt['type']));
569 $tpart->ctype_secondary = trim(strtolower($winatt['subtype']));
570 $tpart->mimetype = $tpart->ctype_primary . '/' . $tpart->ctype_secondary;
571 $tpart->mime_id = 'winmail.' . $part->mime_id . '.' . $pid;
572 $tpart->size = $winatt['size'];
573 $tpart->body = $winatt['stream'];
576 unset($tnef_arr[$pid]);
584 * Parse message body for UUencoded attachments bodies
586 * @param rcube_message_part $part Message part to decode
589 function uu_decode(&$part)
591 // @TODO: messages may be huge, hadle body via file
592 if (!isset($part->body))
593 $part->body = $this->imap->get_message_part($this->uid, $part->mime_id, $part);
596 // FIXME: line length is max.65?
597 $uu_regexp = '/begin [0-7]{3,4} ([^\n]+)\n(([\x21-\x7E]{0,65}\n)+)`\nend/s';
599 if (preg_match_all($uu_regexp, $part->body, $matches, PREG_SET_ORDER)) {
600 // remove attachments bodies from the message body
601 $part->body = preg_replace($uu_regexp, '', $part->body);
602 // update message content-type
603 $part->ctype_primary = 'multipart';
604 $part->ctype_secondary = 'mixed';
605 $part->mimetype = $part->ctype_primary . '/' . $part->ctype_secondary;
607 // add attachments to the structure
608 foreach ($matches as $pid => $att) {
609 $uupart = new rcube_message_part;
611 $uupart->filename = trim($att[1]);
612 $uupart->encoding = 'stream';
613 $uupart->body = convert_uudecode($att[2]);
614 $uupart->size = strlen($uupart->body);
615 $uupart->mime_id = 'uu.' . $part->mime_id . '.' . $pid;
617 $ctype = rc_mime_content_type($uupart->body, $uupart->filename, 'application/octet-stream', true);
618 $uupart->mimetype = $ctype;
619 list($uupart->ctype_primary, $uupart->ctype_secondary) = explode('/', $ctype);
622 unset($matches[$pid]);
631 * Interpret a format=flowed message body according to RFC 2646
633 * @param string $text Raw body formatted as flowed text
634 * @return string Interpreted text with unwrapped lines and stuffed space removed
636 public static function unfold_flowed($text)
638 $text = preg_split('/\r?\n/', $text);
642 foreach ($text as $idx => $line) {
643 if ($line[0] == '>' && preg_match('/^(>+\s*)/', $line, $regs)) {
644 $q = strlen(str_replace(' ', '', $regs[0]));
645 $line = substr($line, strlen($regs[0]));
647 if ($q == $q_level && $line
648 && isset($text[$last])
649 && $text[$last][strlen($text[$last])-1] == ' '
651 $text[$last] .= $line;
660 if ($line == '-- ') {
664 // remove space-stuffing
665 $line = preg_replace('/^\s/', '', $line);
667 if (isset($text[$last]) && $line
668 && $text[$last] != '-- '
669 && $text[$last][strlen($text[$last])-1] == ' '
671 $text[$last] .= $line;
683 return implode("\r\n", $text);
688 * Wrap the given text to comply with RFC 2646
690 * @param string $text Text to wrap
691 * @param int $length Length
692 * @return string Wrapped text
694 public static function format_flowed($text, $length = 72)
696 $text = preg_split('/\r?\n/', $text);
698 foreach ($text as $idx => $line) {
699 if ($line != '-- ') {
700 if ($line[0] == '>' && preg_match('/^(>+)/', $line, $regs)) {
702 $level = strlen($prefix);
703 $line = rtrim(substr($line, $level));
704 $line = $prefix . rc_wordwrap($line, $length - $level - 2, " \r\n$prefix ");
707 $line = ' ' . rc_wordwrap(rtrim($line), $length - 2, " \r\n ");
714 return implode("\r\n", $text);