source: github/program/include/rcube_message.php @ 5ced9ca0

HEADcourier-fixdev-browser-capabilitiespdorelease-0.6release-0.7release-0.8
Last change on this file since 5ced9ca0 was 5ced9ca0, checked in by alecpl <alec@…>, 3 years ago
  • Replace message_part_encrypted hook with more generic message_part_structure
  • Property mode set to 100644
File size: 22.9 KB
Line 
1<?php
2
3/*
4 +-----------------------------------------------------------------------+
5 | program/include/rcube_message.php                                     |
6 |                                                                       |
7 | This file is part of the RoundCube Webmail client                     |
8 | Copyright (C) 2008-2010, RoundCube Dev. - Switzerland                 |
9 | Licensed under the GNU GPL                                            |
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 $Id$
19
20*/
21
22
23/**
24 * Logical representation of a mail message with all its data
25 * and related functions
26 *
27 * @package    Mail
28 * @author     Thomas Bruederli <roundcube@gmail.com>
29 */
30class rcube_message
31{
32    private $app;
33    private $imap;
34    private $opt = array();
35    private $inline_parts = array();
36    private $parse_alternative = false;
37 
38    public $uid = null;
39    public $headers;
40    public $structure;
41    public $parts = array();
42    public $mime_parts = array();
43    public $attachments = array();
44    public $subject = '';
45    public $sender = null;
46    public $is_safe = false;
47 
48
49    /**
50     * __construct
51     *
52     * Provide a uid, and parse message structure.
53     *
54     * @param string $uid The message UID.
55     *
56     * @uses rcmail::get_instance()
57     * @uses rcube_imap::decode_mime_string()
58     * @uses self::set_safe()
59     *
60     * @see self::$app, self::$imap, self::$opt, self::$structure
61     */
62    function __construct($uid)
63    {
64        $this->app = rcmail::get_instance();
65        $this->imap = $this->app->imap;
66
67        $this->uid = $uid;
68        $this->headers = $this->imap->get_headers($uid, NULL, true, true);
69
70        if (!$this->headers)
71            return;
72
73        $this->subject = rcube_imap::decode_mime_string(
74            $this->headers->subject, $this->headers->charset);
75        list(, $this->sender) = each($this->imap->decode_address_list($this->headers->from));
76
77        $this->set_safe((intval($_GET['_safe']) || $_SESSION['safe_messages'][$uid]));
78        $this->opt = array(
79            'safe' => $this->is_safe,
80            'prefer_html' => $this->app->config->get('prefer_html'),
81            'get_url' => rcmail_url('get', array(
82                '_mbox' => $this->imap->get_mailbox_name(), '_uid' => $uid))
83        );
84
85        if ($this->structure = $this->imap->get_structure($uid, $this->headers->body_structure)) {
86            $this->get_mime_numbers($this->structure);
87            $this->parse_structure($this->structure);
88        }
89        else {
90            $this->body = $this->imap->get_body($uid);
91        }
92
93        // notify plugins and let them analyze this structured message object
94        $this->app->plugins->exec_hook('message_load', array('object' => $this));
95    }
96 
97 
98    /**
99     * Return a (decoded) message header
100     *
101     * @param string Header name
102     * @param bool   Don't mime-decode the value
103     * @return string Header value
104     */
105    public function get_header($name, $raw = false)
106    {
107        $value = $this->headers->$name;
108        return $raw ? $value : $this->imap->decode_header($value);
109    }
110
111 
112    /**
113     * Set is_safe var and session data
114     *
115     * @param bool enable/disable
116     */
117    public function set_safe($safe = true)
118    {
119        $this->is_safe = $safe;
120        $_SESSION['safe_messages'][$this->uid] = $this->is_safe;
121    }
122
123
124    /**
125     * Compose a valid URL for getting a message part
126     *
127     * @param string Part MIME-ID
128     * @return string URL or false if part does not exist
129     */
130    public function get_part_url($mime_id)
131    {
132        if ($this->mime_parts[$mime_id])
133            return $this->opt['get_url'] . '&_part=' . $mime_id;
134        else
135            return false;
136    }
137
138
139    /**
140     * Get content of a specific part of this message
141     *
142     * @param string Part MIME-ID
143     * @param resource File pointer to save the message part
144     * @return string Part content
145     */
146    public function get_part_content($mime_id, $fp=NULL)
147    {
148        if ($part = $this->mime_parts[$mime_id]) {
149            // stored in message structure (winmail/inline-uuencode)
150            if ($part->encoding == 'stream') {
151                if ($fp) {
152                    fwrite($fp, $part->body);
153                }
154                return $fp ? true : $part->body;
155            }
156            // get from IMAP
157            return $this->imap->get_message_part($this->uid, $mime_id, $part, NULL, $fp);
158        } else
159            return null;
160    }
161
162
163    /**
164     * Determine if the message contains a HTML part
165     *
166     * @return bool True if a HTML is available, False if not
167     */
168    function has_html_part()
169    {
170        // check all message parts
171        foreach ($this->parts as $pid => $part) {
172            $mimetype = strtolower($part->ctype_primary . '/' . $part->ctype_secondary);
173            if ($mimetype == 'text/html')
174                return true;
175        }
176
177        return false;
178    }
179
180
181    /**
182     * Return the first HTML part of this message
183     *
184     * @return string HTML message part content
185     */
186    function first_html_part()
187    {
188        // check all message parts
189        foreach ($this->mime_parts as $mime_id => $part) {
190            $mimetype = strtolower($part->ctype_primary . '/' . $part->ctype_secondary);
191            if ($mimetype == 'text/html') {
192                return $this->imap->get_message_part($this->uid, $mime_id, $part);
193            }
194        }
195    }
196
197
198    /**
199     * Return the first text part of this message
200     *
201     * @return string Plain text message/part content
202     */
203    function first_text_part()
204    {
205        // no message structure, return complete body
206        if (empty($this->parts))
207            return $this->body;
208
209        $out = null;
210
211        // check all message parts
212        foreach ($this->mime_parts as $mime_id => $part) {
213            $mimetype = $part->ctype_primary . '/' . $part->ctype_secondary;
214
215            if ($mimetype == 'text/plain') {
216                $out = $this->imap->get_message_part($this->uid, $mime_id, $part);
217       
218                // re-format format=flowed content
219                if ($part->ctype_secondary == 'plain' && $part->ctype_parameters['format'] == 'flowed')
220                    $out = self::unfold_flowed($out);
221                break;
222            }
223            else if ($mimetype == 'text/html') {
224                $html_part = $this->imap->get_message_part($this->uid, $mime_id, $part);
225
226                // remove special chars encoding
227                $trans = array_flip(get_html_translation_table(HTML_ENTITIES));
228                $html_part = strtr($html_part, $trans);
229
230                // create instance of html2text class
231                $txt = new html2text($html_part);
232                $out = $txt->get_text();
233                break;
234            }
235        }
236
237        return $out;
238    }
239
240
241    /**
242     * Raad the message structure returend by the IMAP server
243     * and build flat lists of content parts and attachments
244     *
245     * @param object rcube_message_part Message structure node
246     * @param bool  True when called recursively
247     */
248    private function parse_structure($structure, $recursive = false)
249    {
250        // real content-type of message/rfc822 part
251        if ($mimetype == 'message/rfc822' && $structure->real_mimetype)
252            $mimetype = $structure->real_mimetype;
253        else
254            $mimetype = $structure->mimetype;
255
256        // show message headers
257        if ($recursive && is_array($structure->headers) && isset($structure->headers['subject'])) {
258            $c = new stdClass;
259            $c->type = 'headers';
260            $c->headers = &$structure->headers;
261            $this->parts[] = $c;
262        }
263
264        // Allow plugins to handle message parts
265        $plugin = $this->app->plugins->exec_hook('message_part_structure',
266            array('object' => $this, 'structure' => $structure,
267                'mimetype' => $mimetype, 'recursive' => $recursive));
268
269        if ($plugin['abort'])
270            return;
271
272        $structure = $plugin['structure'];
273        list($message_ctype_primary, $message_ctype_secondary) = explode('/', $plugin['mimetype']);
274
275        // print body if message doesn't have multiple parts
276        if ($message_ctype_primary == 'text' && !$recursive) {
277            $structure->type = 'content';
278            $this->parts[] = &$structure;
279           
280            // Parse simple (plain text) message body
281            if ($message_ctype_secondary == 'plain')
282                foreach ((array)$this->uu_decode($structure) as $uupart) {
283                    $this->mime_parts[$uupart->mime_id] = $uupart;
284                    $this->attachments[] = $uupart;
285                }
286        }
287        // the same for pgp signed messages
288        else if ($mimetype == 'application/pgp' && !$recursive) {
289            $structure->type = 'content';
290            $this->parts[] = &$structure;
291        }
292        // message contains alternative parts
293        else if ($mimetype == 'multipart/alternative' && is_array($structure->parts)) {
294            // get html/plaintext parts
295            $plain_part = $html_part = $print_part = $related_part = null;
296
297            foreach ($structure->parts as $p => $sub_part) {
298                $sub_mimetype = $sub_part->mimetype;
299       
300                // check if sub part is
301                if ($sub_mimetype == 'text/plain')
302                    $plain_part = $p;
303                else if ($sub_mimetype == 'text/html')
304                    $html_part = $p;
305                else if ($sub_mimetype == 'text/enriched')
306                    $enriched_part = $p;
307                else if (in_array($sub_mimetype, array('multipart/related', 'multipart/mixed', 'multipart/alternative')))
308                    $related_part = $p;
309            }
310
311            // parse related part (alternative part could be in here)
312            if ($related_part !== null && !$this->parse_alternative) {
313                $this->parse_alternative = true;
314                $this->parse_structure($structure->parts[$related_part], true);
315                $this->parse_alternative = false;
316       
317                // if plain part was found, we should unset it if html is preferred
318                if ($this->opt['prefer_html'] && count($this->parts))
319                    $plain_part = null;
320            }
321
322            // choose html/plain part to print
323            if ($html_part !== null && $this->opt['prefer_html']) {
324                $print_part = &$structure->parts[$html_part];
325            }
326            else if ($enriched_part !== null) {
327                $print_part = &$structure->parts[$enriched_part];
328            }
329            else if ($plain_part !== null) {
330                $print_part = &$structure->parts[$plain_part];
331            }
332
333            // add the right message body
334            if (is_object($print_part)) {
335                $print_part->type = 'content';
336                $this->parts[] = $print_part;
337            }
338            // show plaintext warning
339            else if ($html_part !== null && empty($this->parts)) {
340                $c = new stdClass;
341                $c->type            = 'content';
342                $c->ctype_primary   = 'text';
343                $c->ctype_secondary = 'plain';
344                $c->body            = rcube_label('htmlmessage');
345
346                $this->parts[] = $c;
347            }
348
349            // add html part as attachment
350            if ($html_part !== null && $structure->parts[$html_part] !== $print_part) {
351                $html_part = &$structure->parts[$html_part];
352                $html_part->filename = rcube_label('htmlmessage');
353                $html_part->mimetype = 'text/html';
354
355                $this->attachments[] = $html_part;
356            }
357        }
358        // this is an ecrypted message -> create a plaintext body with the according message
359        else if ($mimetype == 'multipart/encrypted') {
360            $p = new stdClass;
361            $p->type            = 'content';
362            $p->ctype_primary   = 'text';
363            $p->ctype_secondary = 'plain';
364            $p->body            = rcube_label('encryptedmessage');
365            $p->size            = strlen($p->body);
366        }
367        // message contains multiple parts
368        else if (is_array($structure->parts) && !empty($structure->parts)) {
369            // iterate over parts
370            for ($i=0; $i < count($structure->parts); $i++) {
371                $mail_part      = &$structure->parts[$i];
372                $primary_type   = $mail_part->ctype_primary;
373                $secondary_type = $mail_part->ctype_secondary;
374
375                // real content-type of message/rfc822
376                if ($mail_part->real_mimetype) {
377                    $part_orig_mimetype = $mail_part->mimetype;
378                    $part_mimetype = $mail_part->real_mimetype;
379                    list($primary_type, $secondary_type) = explode('/', $part_mimetype);
380                }
381                else
382                    $part_mimetype = $mail_part->mimetype;
383
384                // multipart/alternative
385                if ($primary_type == 'multipart') {
386                    $this->parse_structure($mail_part, true);
387
388                    // list message/rfc822 as attachment as well (mostly .eml)
389                    if ($part_orig_mimetype == 'message/rfc822' && !empty($mail_part->filename))
390                        $this->attachments[] = $mail_part;
391                }
392                // part text/[plain|html] OR message/delivery-status
393                else if ((($part_mimetype == 'text/plain' || $part_mimetype == 'text/html') && $mail_part->disposition != 'attachment') ||
394                    $part_mimetype == 'message/delivery-status' || $part_mimetype == 'message/disposition-notification'
395                ) {
396                    // add text part if it matches the prefs
397                    if (!$this->parse_alternative ||
398                        ($secondary_type == 'html' && $this->opt['prefer_html']) ||
399                        ($secondary_type == 'plain' && !$this->opt['prefer_html'])
400                    ) {
401                        $mail_part->type = 'content';
402                        $this->parts[] = $mail_part;
403                    }
404         
405                    // list as attachment as well
406                    if (!empty($mail_part->filename))
407                        $this->attachments[] = $mail_part;
408                }
409                // part message/*
410                else if ($primary_type=='message') {
411                    $this->parse_structure($mail_part, true);
412
413                    // list as attachment as well (mostly .eml)
414                    if (!empty($mail_part->filename))
415                        $this->attachments[] = $mail_part;
416                }
417                // ignore "virtual" protocol parts
418                else if ($primary_type == 'protocol') {
419                    continue;
420                }
421                // part is Microsoft Outlook TNEF (winmail.dat)
422                else if ($part_mimetype == 'application/ms-tnef') {
423                    foreach ((array)$this->tnef_decode($mail_part) as $tpart) {
424                        $this->mime_parts[$tpart->mime_id] = $tpart;
425                        $this->attachments[] = $tpart;
426                    }
427                }
428                // part is a file/attachment
429                else if (preg_match('/^(inline|attach)/', $mail_part->disposition) ||
430                    $mail_part->headers['content-id'] || (empty($mail_part->disposition) && $mail_part->filename)
431                ) {
432                    // skip apple resource forks
433                    if ($message_ctype_secondary == 'appledouble' && $secondary_type == 'applefile')
434                        continue;
435
436                    // part belongs to a related message and is linked
437                    if ($mimetype == 'multipart/related'
438                        && ($mail_part->headers['content-id'] || $mail_part->headers['content-location'])) {
439                        if ($mail_part->headers['content-id'])
440                            $mail_part->content_id = preg_replace(array('/^</', '/>$/'), '', $mail_part->headers['content-id']);
441                        if ($mail_part->headers['content-location'])
442                            $mail_part->content_location = $mail_part->headers['content-base'] . $mail_part->headers['content-location'];
443
444                        $this->inline_parts[] = $mail_part;
445                    }
446                    // attachment encapsulated within message/rfc822 part needs further decoding (#1486743)
447                    else if ($part_orig_mimetype == 'message/rfc822') {
448                        $this->parse_structure($mail_part, true);
449                    }
450                    // is a regular attachment
451                    else if (preg_match('!^[a-z0-9-.+]+/[a-z0-9-.+]+$!i', $part_mimetype)) {
452                        if (!$mail_part->filename)
453                            $mail_part->filename = 'Part '.$mail_part->mime_id;
454                        $this->attachments[] = $mail_part;
455                    }
456                }
457            }
458
459            // if this was a related part try to resolve references
460            if ($mimetype == 'multipart/related' && sizeof($this->inline_parts)) {
461                $a_replaces = array();
462
463                foreach ($this->inline_parts as $inline_object) {
464                    $part_url = $this->get_part_url($inline_object->mime_id);
465                    if ($inline_object->content_id)
466                        $a_replaces['cid:'.$inline_object->content_id] = $part_url;
467                    if ($inline_object->content_location)
468                        $a_replaces[$inline_object->content_location] = $part_url;
469                }
470
471                // add replace array to each content part
472                // (will be applied later when part body is available)
473                foreach ($this->parts as $i => $part) {
474                    if ($part->type == 'content')
475                        $this->parts[$i]->replaces = $a_replaces;
476                }
477            }
478        }
479        // message is a single part non-text
480        else if ($structure->filename) {
481            $this->attachments[] = $structure;
482        }
483        // message is a single part non-text (without filename)
484        else if (preg_match('/application\//i', $mimetype)) {
485            $structure->filename = 'Part '.$structure->mime_id;
486            $this->attachments[] = $structure;
487        }
488    }
489
490
491    /**
492     * Fill aflat array with references to all parts, indexed by part numbers
493     *
494     * @param object rcube_message_part Message body structure
495     */
496    private function get_mime_numbers(&$part)
497    {
498        if (strlen($part->mime_id))
499            $this->mime_parts[$part->mime_id] = &$part;
500
501        if (is_array($part->parts))
502            for ($i=0; $i<count($part->parts); $i++)
503                $this->get_mime_numbers($part->parts[$i]);
504    }
505
506
507    /**
508     * Decode a Microsoft Outlook TNEF part (winmail.dat)
509     *
510     * @param object rcube_message_part Message part to decode
511     */
512    function tnef_decode(&$part)
513    {
514        // @TODO: attachment may be huge, hadle it via file
515        if (!isset($part->body))
516            $part->body = $this->imap->get_message_part($this->uid, $part->mime_id, $part);
517
518        $parts = array();
519        $tnef = new tnef_decoder;
520        $tnef_arr = $tnef->decompress($part->body);
521
522        foreach ($tnef_arr as $pid => $winatt) {
523            $tpart = new rcube_message_part;
524
525            $tpart->filename        = trim($winatt['name']);
526            $tpart->encoding        = 'stream';
527            $tpart->ctype_primary   = trim(strtolower($winatt['type']));
528            $tpart->ctype_secondary = trim(strtolower($winatt['subtype']));
529            $tpart->mimetype        = $tpart->ctype_primary . '/' . $tpart->ctype_secondary;
530            $tpart->mime_id         = 'winmail.' . $part->mime_id . '.' . $pid;
531            $tpart->size            = $winatt['size'];
532            $tpart->body            = $winatt['stream'];
533
534            $parts[] = $tpart;
535            unset($tnef_arr[$pid]);
536        }
537
538        return $parts;
539    }
540
541
542    /**
543     * Parse message body for UUencoded attachments bodies
544     *
545     * @param object rcube_message_part Message part to decode
546     */
547    function uu_decode(&$part)
548    {
549        // @TODO: messages may be huge, hadle body via file
550        if (!isset($part->body))
551            $part->body = $this->imap->get_message_part($this->uid, $part->mime_id, $part);
552
553        $parts = array();
554        // FIXME: line length is max.65?
555        $uu_regexp = '/begin [0-7]{3,4} ([^\n]+)\n(([\x21-\x7E]{0,65}\n)+)`\nend/s';
556
557        if (preg_match_all($uu_regexp, $part->body, $matches, PREG_SET_ORDER)) {
558            // remove attachments bodies from the message body
559            $part->body = preg_replace($uu_regexp, '', $part->body);
560            // update message content-type
561            $part->ctype_primary   = 'multipart';
562            $part->ctype_secondary = 'mixed';
563            $part->mimetype        = $part->ctype_primary . '/' . $part->ctype_secondary;
564
565            // add attachments to the structure
566            foreach ($matches as $pid => $att) {
567                $uupart = new rcube_message_part;
568
569                $uupart->filename = trim($att[1]);
570                $uupart->encoding = 'stream';
571                $uupart->body     = convert_uudecode($att[2]);
572                $uupart->size     = strlen($uupart->body);
573                $uupart->mime_id  = 'uu.' . $part->mime_id . '.' . $pid;
574
575                $ctype = rc_mime_content_type($uupart->body, $uupart->filename, 'application/octet-stream', true);
576                $uupart->mimetype = $ctype;
577                list($uupart->ctype_primary, $uupart->ctype_secondary) = explode('/', $ctype);
578
579                $parts[] = $uupart;
580                unset($matches[$pid]);
581            }
582        }
583
584        return $parts;
585    }
586
587
588    /**
589     * Interpret a format=flowed message body according to RFC 2646
590     *
591     * @param string  Raw body formatted as flowed text
592     * @return string Interpreted text with unwrapped lines and stuffed space removed
593     */
594    public static function unfold_flowed($text)
595    {
596        return preg_replace(
597            array('/-- (\r?\n)/',   '/^ /m',  '/(.) \r?\n/',  '/--%SIGEND%(\r?\n)/'),
598            array('--%SIGEND%\\1',  '',       '\\1 ',         '-- \\1'),
599            $text);
600    }
601
602
603    /**
604     * Wrap the given text to comply with RFC 2646
605     */
606    public static function format_flowed($text, $length = 72)
607    {
608        $out = '';
609   
610        foreach (preg_split('/\r?\n/', trim($text)) as $line) {
611            // don't wrap quoted lines (to avoid wrapping problems)
612            if ($line[0] != '>')
613                $line = rc_wordwrap(rtrim($line), $length - 1, " \r\n");
614
615            $out .= $line . "\r\n";
616        }
617   
618        return $out;
619    }
620
621}
Note: See TracBrowser for help on using the repository browser.