source: subversion/trunk/roundcubemail/program/include/rcube_message.php @ 6074

Last change on this file since 6074 was 6074, checked in by alec, 14 months ago
  • Add 3rd argument to rcube_message::get_part_content() to skip charset conversion
  • Property svn:keywords set to Id
File size: 26.6 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, The Roundcube Dev Team                       |
9 |                                                                       |
10 | Licensed under the GNU General Public License version 3 or            |
11 | any later version with exceptions for skins & plugins.                |
12 | See the README file for a full license statement.                     |
13 |                                                                       |
14 | PURPOSE:                                                              |
15 |   Logical representation of a mail message with all its data          |
16 |   and related functions                                               |
17 +-----------------------------------------------------------------------+
18 | Author: Thomas Bruederli <roundcube@gmail.com>                        |
19 +-----------------------------------------------------------------------+
20
21 $Id$
22
23*/
24
25
26/**
27 * Logical representation of a mail message with all its data
28 * and related functions
29 *
30 * @package    Mail
31 * @author     Thomas Bruederli <roundcube@gmail.com>
32 */
33class rcube_message
34{
35    /**
36     * Instace of rcmail.
37     *
38     * @var rcmail
39     */
40    private $app;
41
42    /**
43     * Instance of storage class
44     *
45     * @var rcube_storage
46     */
47    private $storage;
48
49    /**
50     * Instance of mime class
51     *
52     * @var rcube_mime
53     */
54    private $mime;
55    private $opt = array();
56    private $inline_parts = array();
57    private $parse_alternative = false;
58
59    public $uid = null;
60    public $headers;
61    public $parts = array();
62    public $mime_parts = array();
63    public $attachments = array();
64    public $subject = '';
65    public $sender = null;
66    public $is_safe = false;
67
68
69    /**
70     * __construct
71     *
72     * Provide a uid, and parse message structure.
73     *
74     * @param string $uid The message UID.
75     *
76     * @see self::$app, self::$storage, self::$opt, self::$parts
77     */
78    function __construct($uid)
79    {
80        $this->uid  = $uid;
81        $this->app  = rcube::get_instance();
82        $this->storage = $this->app->get_storage();
83        $this->storage->set_options(array('all_headers' => true));
84
85        $this->headers = $this->storage->get_message($uid);
86
87        if (!$this->headers)
88            return;
89
90        $this->mime = new rcube_mime($this->headers->charset);
91
92        $this->subject = $this->mime->decode_mime_string($this->headers->subject);
93        list(, $this->sender) = each($this->mime->decode_address_list($this->headers->from, 1));
94
95        $this->set_safe((intval($_GET['_safe']) || $_SESSION['safe_messages'][$uid]));
96        $this->opt = array(
97            'safe' => $this->is_safe,
98            'prefer_html' => $this->app->config->get('prefer_html'),
99            'get_url' => $this->app->url(array(
100                'action' => 'get',
101                'mbox'   => $this->storage->get_folder(),
102                'uid'    => $uid))
103        );
104
105        if (!empty($this->headers->structure)) {
106            $this->get_mime_numbers($this->headers->structure);
107            $this->parse_structure($this->headers->structure);
108        }
109        else {
110            $this->body = $this->storage->get_body($uid);
111        }
112
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
118    /**
119     * Return a (decoded) message header
120     *
121     * @param string $name Header name
122     * @param bool   $row  Don't mime-decode the value
123     * @return string Header value
124     */
125    public function get_header($name, $raw = false)
126    {
127        if (empty($this->headers))
128            return null;
129
130        if ($this->headers->$name)
131            $value = $this->headers->$name;
132        else if ($this->headers->others[$name])
133            $value = $this->headers->others[$name];
134
135        return $raw ? $value : $this->mime->decode_header($value);
136    }
137
138
139    /**
140     * Set is_safe var and session data
141     *
142     * @param bool $safe enable/disable
143     */
144    public function set_safe($safe = true)
145    {
146        $this->is_safe = $safe;
147        $_SESSION['safe_messages'][$this->uid] = $this->is_safe;
148    }
149
150
151    /**
152     * Compose a valid URL for getting a message part
153     *
154     * @param string $mime_id Part MIME-ID
155     * @return string URL or false if part does not exist
156     */
157    public function get_part_url($mime_id, $embed = false)
158    {
159        if ($this->mime_parts[$mime_id])
160            return $this->opt['get_url'] . '&_part=' . $mime_id . ($embed ? '&_embed=1' : '');
161        else
162            return false;
163    }
164
165
166    /**
167     * Get content of a specific part of this message
168     *
169     * @param string   $mime_id           Part MIME-ID
170     * @param resource $fp File           pointer to save the message part
171     * @param boolean  $skip_charset_conv Disables charset conversion
172     *
173     * @return string Part content
174     */
175    public function get_part_content($mime_id, $fp = null, $skip_charset_conv = false)
176    {
177        if ($part = $this->mime_parts[$mime_id]) {
178            // stored in message structure (winmail/inline-uuencode)
179            if (!empty($part->body) || $part->encoding == 'stream') {
180                if ($fp) {
181                    fwrite($fp, $part->body);
182                }
183                return $fp ? true : $part->body;
184            }
185            // get from IMAP
186            return $this->storage->get_message_part($this->uid, $mime_id, $part, NULL, $fp, $skip_charset_conv);
187        } else
188            return null;
189    }
190
191
192    /**
193     * Determine if the message contains a HTML part
194     *
195     * @param bool $recursive Enables checking in all levels of the structure
196     *
197     * @return bool True if a HTML is available, False if not
198     */
199    function has_html_part($recursive = true)
200    {
201        // check all message parts
202        foreach ($this->parts as $part) {
203            if ($part->mimetype == 'text/html') {
204                // Level check, we'll skip e.g. HTML attachments
205                if (!$recursive) {
206                    $level = explode('.', $part->mime_id);
207
208                    // Level too high
209                    if (count($level) > 2) {
210                        continue;
211                    }
212
213                    // HTML part can be on the lower level, if not...
214                    if (count($level) > 1) {
215                        // It can be an alternative or related message part
216                        $parent = $this->mime_parts[0];
217                        if ($parent->mimetype != 'multipart/alternative' && $parent->mimetype != 'multipart/related') {
218                            continue;
219                        }
220                    }
221                }
222
223                return true;
224            }
225        }
226
227        return false;
228    }
229
230
231    /**
232     * Return the first HTML part of this message
233     *
234     * @return string HTML message part content
235     */
236    function first_html_part()
237    {
238        // check all message parts
239        foreach ($this->mime_parts as $pid => $part) {
240            if ($part->mimetype == 'text/html') {
241                return $this->get_part_content($pid);
242            }
243        }
244    }
245
246
247    /**
248     * Return the first text part of this message
249     *
250     * @param rcube_message_part $part Reference to the part if found
251     * @return string Plain text message/part content
252     */
253    function first_text_part(&$part=null)
254    {
255        // no message structure, return complete body
256        if (empty($this->parts))
257            return $this->body;
258
259        // check all message parts
260        foreach ($this->mime_parts as $mime_id => $part) {
261            if ($part->mimetype == 'text/plain') {
262                return $this->get_part_content($mime_id);
263            }
264            else if ($part->mimetype == 'text/html') {
265                $out = $this->get_part_content($mime_id);
266
267                // remove special chars encoding
268                $trans = array_flip(get_html_translation_table(HTML_ENTITIES));
269                $out = strtr($out, $trans);
270
271                // create instance of html2text class
272                $txt = new html2text($out);
273                return $txt->get_text();
274            }
275        }
276
277        $part = null;
278        return null;
279    }
280
281
282    /**
283     * Read the message structure returend by the IMAP server
284     * and build flat lists of content parts and attachments
285     *
286     * @param rcube_message_part $structure Message structure node
287     * @param bool               $recursive True when called recursively
288     */
289    private function parse_structure($structure, $recursive = false)
290    {
291        // real content-type of message/rfc822 part
292        if ($structure->mimetype == 'message/rfc822' && $structure->real_mimetype)
293            $mimetype = $structure->real_mimetype;
294        else
295            $mimetype = $structure->mimetype;
296
297        // show message headers
298        if ($recursive && is_array($structure->headers) && isset($structure->headers['subject'])) {
299            $c = new stdClass;
300            $c->type = 'headers';
301            $c->headers = &$structure->headers;
302            $this->parts[] = $c;
303        }
304
305        // Allow plugins to handle message parts
306        $plugin = $this->app->plugins->exec_hook('message_part_structure',
307            array('object' => $this, 'structure' => $structure,
308                'mimetype' => $mimetype, 'recursive' => $recursive));
309
310        if ($plugin['abort'])
311            return;
312
313        $structure = $plugin['structure'];
314        list($message_ctype_primary, $message_ctype_secondary) = explode('/', $plugin['mimetype']);
315
316        // print body if message doesn't have multiple parts
317        if ($message_ctype_primary == 'text' && !$recursive) {
318            $structure->type = 'content';
319            $this->parts[] = &$structure;
320
321            // Parse simple (plain text) message body
322            if ($message_ctype_secondary == 'plain')
323                foreach ((array)$this->uu_decode($structure) as $uupart) {
324                    $this->mime_parts[$uupart->mime_id] = $uupart;
325                    $this->attachments[] = $uupart;
326                }
327        }
328        // the same for pgp signed messages
329        else if ($mimetype == 'application/pgp' && !$recursive) {
330            $structure->type = 'content';
331            $this->parts[] = &$structure;
332        }
333        // message contains (more than one!) alternative parts
334        else if ($mimetype == 'multipart/alternative'
335            && is_array($structure->parts) && count($structure->parts) > 1
336        ) {
337            // get html/plaintext parts
338            $plain_part = $html_part = $print_part = $related_part = null;
339
340            foreach ($structure->parts as $p => $sub_part) {
341                $sub_mimetype = $sub_part->mimetype;
342
343                // check if sub part is
344                if ($sub_mimetype == 'text/plain')
345                    $plain_part = $p;
346                else if ($sub_mimetype == 'text/html')
347                    $html_part = $p;
348                else if ($sub_mimetype == 'text/enriched')
349                    $enriched_part = $p;
350                else if (in_array($sub_mimetype, array('multipart/related', 'multipart/mixed', 'multipart/alternative')))
351                    $related_part = $p;
352            }
353
354            // parse related part (alternative part could be in here)
355            if ($related_part !== null && !$this->parse_alternative) {
356                $this->parse_alternative = true;
357                $this->parse_structure($structure->parts[$related_part], true);
358                $this->parse_alternative = false;
359
360                // if plain part was found, we should unset it if html is preferred
361                if ($this->opt['prefer_html'] && count($this->parts))
362                    $plain_part = null;
363            }
364
365            // choose html/plain part to print
366            if ($html_part !== null && $this->opt['prefer_html']) {
367                $print_part = &$structure->parts[$html_part];
368            }
369            else if ($enriched_part !== null) {
370                $print_part = &$structure->parts[$enriched_part];
371            }
372            else if ($plain_part !== null) {
373                $print_part = &$structure->parts[$plain_part];
374            }
375
376            // add the right message body
377            if (is_object($print_part)) {
378                $print_part->type = 'content';
379                $this->parts[] = $print_part;
380            }
381            // show plaintext warning
382            else if ($html_part !== null && empty($this->parts)) {
383                $c = new stdClass;
384                $c->type            = 'content';
385                $c->ctype_primary   = 'text';
386                $c->ctype_secondary = 'plain';
387                $c->mimetype        = 'text/plain';
388                $c->realtype        = 'text/html';
389
390                $this->parts[] = $c;
391            }
392
393            // add html part as attachment
394            if ($html_part !== null && $structure->parts[$html_part] !== $print_part) {
395                $html_part = &$structure->parts[$html_part];
396                $html_part->mimetype = 'text/html';
397
398                $this->attachments[] = $html_part;
399            }
400        }
401        // this is an ecrypted message -> create a plaintext body with the according message
402        else if ($mimetype == 'multipart/encrypted') {
403            $p = new stdClass;
404            $p->type            = 'content';
405            $p->ctype_primary   = 'text';
406            $p->ctype_secondary = 'plain';
407            $p->mimetype        = 'text/plain';
408            $p->realtype        = 'multipart/encrypted';
409
410            $this->parts[] = $p;
411        }
412        // message contains multiple parts
413        else if (is_array($structure->parts) && !empty($structure->parts)) {
414            // iterate over parts
415            for ($i=0; $i < count($structure->parts); $i++) {
416                $mail_part      = &$structure->parts[$i];
417                $primary_type   = $mail_part->ctype_primary;
418                $secondary_type = $mail_part->ctype_secondary;
419
420                // real content-type of message/rfc822
421                if ($mail_part->real_mimetype) {
422                    $part_orig_mimetype = $mail_part->mimetype;
423                    $part_mimetype = $mail_part->real_mimetype;
424                    list($primary_type, $secondary_type) = explode('/', $part_mimetype);
425                }
426                else
427                    $part_mimetype = $mail_part->mimetype;
428
429                // multipart/alternative
430                if ($primary_type == 'multipart') {
431                    $this->parse_structure($mail_part, true);
432
433                    // list message/rfc822 as attachment as well (mostly .eml)
434                    if ($part_orig_mimetype == 'message/rfc822' && !empty($mail_part->filename))
435                        $this->attachments[] = $mail_part;
436                }
437                // part text/[plain|html] or delivery status
438                else if ((($part_mimetype == 'text/plain' || $part_mimetype == 'text/html') && $mail_part->disposition != 'attachment') ||
439                    in_array($part_mimetype, array('message/delivery-status', 'text/rfc822-headers', 'message/disposition-notification'))
440                ) {
441                    // Allow plugins to handle also this part
442                    $plugin = $this->app->plugins->exec_hook('message_part_structure',
443                        array('object' => $this, 'structure' => $mail_part,
444                            'mimetype' => $part_mimetype, 'recursive' => true));
445
446                    if ($plugin['abort'])
447                        continue;
448
449                    if ($part_mimetype == 'text/html') {
450                        $got_html_part = true;
451                    }
452
453                    $mail_part = $plugin['structure'];
454                    list($primary_type, $secondary_type) = explode('/', $plugin['mimetype']);
455
456                    // add text part if it matches the prefs
457                    if (!$this->parse_alternative ||
458                        ($secondary_type == 'html' && $this->opt['prefer_html']) ||
459                        ($secondary_type == 'plain' && !$this->opt['prefer_html'])
460                    ) {
461                        $mail_part->type = 'content';
462                        $this->parts[] = $mail_part;
463                    }
464
465                    // list as attachment as well
466                    if (!empty($mail_part->filename))
467                        $this->attachments[] = $mail_part;
468                }
469                // part message/*
470                else if ($primary_type == 'message') {
471                    $this->parse_structure($mail_part, true);
472
473                    // list as attachment as well (mostly .eml)
474                    if (!empty($mail_part->filename))
475                        $this->attachments[] = $mail_part;
476                }
477                // ignore "virtual" protocol parts
478                else if ($primary_type == 'protocol') {
479                    continue;
480                }
481                // part is Microsoft Outlook TNEF (winmail.dat)
482                else if ($part_mimetype == 'application/ms-tnef') {
483                    foreach ((array)$this->tnef_decode($mail_part) as $tpart) {
484                        $this->mime_parts[$tpart->mime_id] = $tpart;
485                        $this->attachments[] = $tpart;
486                    }
487                }
488                // part is a file/attachment
489                else if (preg_match('/^(inline|attach)/', $mail_part->disposition) ||
490                    $mail_part->headers['content-id'] ||
491                    ($mail_part->filename &&
492                        (empty($mail_part->disposition) || preg_match('/^[a-z0-9!#$&.+^_-]+$/i', $mail_part->disposition)))
493                ) {
494                    // skip apple resource forks
495                    if ($message_ctype_secondary == 'appledouble' && $secondary_type == 'applefile')
496                        continue;
497
498                    // part belongs to a related message and is linked
499                    if ($mimetype == 'multipart/related'
500                        && ($mail_part->headers['content-id'] || $mail_part->headers['content-location'])) {
501                        if ($mail_part->headers['content-id'])
502                            $mail_part->content_id = preg_replace(array('/^</', '/>$/'), '', $mail_part->headers['content-id']);
503                        if ($mail_part->headers['content-location'])
504                            $mail_part->content_location = $mail_part->headers['content-base'] . $mail_part->headers['content-location'];
505
506                        $this->inline_parts[] = $mail_part;
507                    }
508                    // attachment encapsulated within message/rfc822 part needs further decoding (#1486743)
509                    else if ($part_orig_mimetype == 'message/rfc822') {
510                        $this->parse_structure($mail_part, true);
511
512                        // list as attachment as well (mostly .eml)
513                        if (!empty($mail_part->filename))
514                            $this->attachments[] = $mail_part;
515                    }
516                    // regular attachment with valid content type
517                    // (content-type name regexp according to RFC4288.4.2)
518                    else if (preg_match('/^[a-z0-9!#$&.+^_-]+\/[a-z0-9!#$&.+^_-]+$/i', $part_mimetype)) {
519                        if (!$mail_part->filename)
520                            $mail_part->filename = 'Part '.$mail_part->mime_id;
521
522                        $this->attachments[] = $mail_part;
523                    }
524                    // attachment with invalid content type
525                    // replace malformed content type with application/octet-stream (#1487767)
526                    else if ($mail_part->filename) {
527                        $mail_part->ctype_primary   = 'application';
528                        $mail_part->ctype_secondary = 'octet-stream';
529                        $mail_part->mimetype        = 'application/octet-stream';
530
531                        $this->attachments[] = $mail_part;
532                    }
533                }
534                // attachment part as message/rfc822 (#1488026)
535                else if ($mail_part->mimetype == 'message/rfc822') {
536                    $this->parse_structure($mail_part);
537                }
538            }
539
540            // if this was a related part try to resolve references
541            if ($mimetype == 'multipart/related' && sizeof($this->inline_parts)) {
542                $a_replaces = array();
543                $img_regexp = '/^image\/(gif|jpe?g|png|tiff|bmp|svg)/';
544
545                foreach ($this->inline_parts as $inline_object) {
546                    $part_url = $this->get_part_url($inline_object->mime_id, true);
547                    if ($inline_object->content_id)
548                        $a_replaces['cid:'.$inline_object->content_id] = $part_url;
549                    if ($inline_object->content_location) {
550                        $a_replaces[$inline_object->content_location] = $part_url;
551                    }
552
553                    if (!empty($inline_object->filename)) {
554                        // MS Outlook sends sometimes non-related attachments as related
555                        // In this case multipart/related message has only one text part
556                        // We'll add all such attachments to the attachments list
557                        if (!isset($got_html_part) && empty($inline_object->content_id)) {
558                            $this->attachments[] = $inline_object;
559                        }
560                        // MS Outlook sometimes also adds non-image attachments as related
561                        // We'll add all such attachments to the attachments list
562                        // Warning: some browsers support pdf in <img/>
563                        else if (!preg_match($img_regexp, $inline_object->mimetype)) {
564                            $this->attachments[] = $inline_object;
565                        }
566                        // @TODO: we should fetch HTML body and find attachment's content-id
567                        // to handle also image attachments without reference in the body
568                        // @TODO: should we list all image attachments in text mode?
569                    }
570                }
571
572                // add replace array to each content part
573                // (will be applied later when part body is available)
574                foreach ($this->parts as $i => $part) {
575                    if ($part->type == 'content')
576                        $this->parts[$i]->replaces = $a_replaces;
577                }
578            }
579        }
580        // message is a single part non-text
581        else if ($structure->filename) {
582            $this->attachments[] = $structure;
583        }
584        // message is a single part non-text (without filename)
585        else if (preg_match('/application\//i', $mimetype)) {
586            $structure->filename = 'Part '.$structure->mime_id;
587            $this->attachments[] = $structure;
588        }
589    }
590
591
592    /**
593     * Fill aflat array with references to all parts, indexed by part numbers
594     *
595     * @param rcube_message_part $part Message body structure
596     */
597    private function get_mime_numbers(&$part)
598    {
599        if (strlen($part->mime_id))
600            $this->mime_parts[$part->mime_id] = &$part;
601
602        if (is_array($part->parts))
603            for ($i=0; $i<count($part->parts); $i++)
604                $this->get_mime_numbers($part->parts[$i]);
605    }
606
607
608    /**
609     * Decode a Microsoft Outlook TNEF part (winmail.dat)
610     *
611     * @param rcube_message_part $part Message part to decode
612     * @return array
613     */
614    function tnef_decode(&$part)
615    {
616        // @TODO: attachment may be huge, hadle it via file
617        if (!isset($part->body))
618            $part->body = $this->storage->get_message_part($this->uid, $part->mime_id, $part);
619
620        $parts = array();
621        $tnef = new tnef_decoder;
622        $tnef_arr = $tnef->decompress($part->body);
623
624        foreach ($tnef_arr as $pid => $winatt) {
625            $tpart = new rcube_message_part;
626
627            $tpart->filename        = trim($winatt['name']);
628            $tpart->encoding        = 'stream';
629            $tpart->ctype_primary   = trim(strtolower($winatt['type']));
630            $tpart->ctype_secondary = trim(strtolower($winatt['subtype']));
631            $tpart->mimetype        = $tpart->ctype_primary . '/' . $tpart->ctype_secondary;
632            $tpart->mime_id         = 'winmail.' . $part->mime_id . '.' . $pid;
633            $tpart->size            = $winatt['size'];
634            $tpart->body            = $winatt['stream'];
635
636            $parts[] = $tpart;
637            unset($tnef_arr[$pid]);
638        }
639
640        return $parts;
641    }
642
643
644    /**
645     * Parse message body for UUencoded attachments bodies
646     *
647     * @param rcube_message_part $part Message part to decode
648     * @return array
649     */
650    function uu_decode(&$part)
651    {
652        // @TODO: messages may be huge, hadle body via file
653        if (!isset($part->body))
654            $part->body = $this->storage->get_message_part($this->uid, $part->mime_id, $part);
655
656        $parts = array();
657        // FIXME: line length is max.65?
658        $uu_regexp = '/begin [0-7]{3,4} ([^\n]+)\n(([\x21-\x7E]{0,65}\n)+)`\nend/s';
659
660        if (preg_match_all($uu_regexp, $part->body, $matches, PREG_SET_ORDER)) {
661            // remove attachments bodies from the message body
662            $part->body = preg_replace($uu_regexp, '', $part->body);
663            // update message content-type
664            $part->ctype_primary   = 'multipart';
665            $part->ctype_secondary = 'mixed';
666            $part->mimetype        = $part->ctype_primary . '/' . $part->ctype_secondary;
667
668            // add attachments to the structure
669            foreach ($matches as $pid => $att) {
670                $uupart = new rcube_message_part;
671
672                $uupart->filename = trim($att[1]);
673                $uupart->encoding = 'stream';
674                $uupart->body     = convert_uudecode($att[2]);
675                $uupart->size     = strlen($uupart->body);
676                $uupart->mime_id  = 'uu.' . $part->mime_id . '.' . $pid;
677
678                $ctype = rcube_mime::content_type($uupart->body, $uupart->filename, 'application/octet-stream', true);
679                $uupart->mimetype = $ctype;
680                list($uupart->ctype_primary, $uupart->ctype_secondary) = explode('/', $ctype);
681
682                $parts[] = $uupart;
683                unset($matches[$pid]);
684            }
685        }
686
687        return $parts;
688    }
689
690
691    /**
692     * Deprecated methods (to be removed)
693     */
694
695    public static function unfold_flowed($text)
696    {
697        return rcube_mime::unfold_flowed($text);
698    }
699
700    public static function format_flowed($text, $length = 72)
701    {
702        return rcube_mime::format_flowed($text, $length);
703    }
704
705}
Note: See TracBrowser for help on using the repository browser.