source: subversion/branches/release-0.8/program/include/rcube_message.php @ 6087

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