Aleksander Machniak
2016-03-23 323fa20bc89edcd683bef1a170445f681305fc5c
commit | author | age
8fa58e 1 <?php
T 2
a95874 3 /**
8fa58e 4  +-----------------------------------------------------------------------+
e019f2 5  | This file is part of the Roundcube Webmail client                     |
48ba44 6  | Copyright (C) 2008-2014, The Roundcube Dev Team                       |
7fe381 7  |                                                                       |
T 8  | Licensed under the GNU General Public License version 3 or            |
9  | any later version with exceptions for skins & plugins.                |
10  | See the README file for a full license statement.                     |
8fa58e 11  |                                                                       |
T 12  | PURPOSE:                                                              |
13  |   Logical representation of a mail message with all its data          |
14  |   and related functions                                               |
15  +-----------------------------------------------------------------------+
16  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
17  +-----------------------------------------------------------------------+
18 */
19
20 /**
45f56c 21  * Logical representation of a mail message with all its data
T 22  * and related functions
8fa58e 23  *
9ab346 24  * @package    Framework
AM 25  * @subpackage Storage
8fa58e 26  * @author     Thomas Bruederli <roundcube@gmail.com>
T 27  */
28 class rcube_message
29 {
5c461b 30     /**
be98df 31      * Instace of framework class.
5c461b 32      *
be98df 33      * @var rcube
5c461b 34      */
d311d8 35     private $app;
5c461b 36
A 37     /**
8b92d2 38      * Instance of storage class
5c461b 39      *
8b92d2 40      * @var rcube_storage
5c461b 41      */
8b92d2 42     private $storage;
1c4f23 43
A 44     /**
45      * Instance of mime class
46      *
47      * @var rcube_mime
48      */
49     private $mime;
d311d8 50     private $opt = array();
A 51     private $parse_alternative = false;
2ae58f 52
10562d 53     public $uid;
AM 54     public $folder;
d311d8 55     public $headers;
9af8e2 56     public $sender;
323fa2 57     public $context;
9af8e2 58     public $parts        = array();
AM 59     public $mime_parts   = array();
287eff 60     public $inline_parts = array();
9af8e2 61     public $attachments  = array();
AM 62     public $subject      = '';
63     public $is_safe      = false;
48ba44 64
AM 65     const BODY_MAX_SIZE = 1048576; // 1MB
2ae58f 66
193fb4 67
d311d8 68     /**
A 69      * __construct
70      *
71      * Provide a uid, and parse message structure.
72      *
63e793 73      * @param string $uid     The message UID.
AM 74      * @param string $folder  Folder name
75      * @param bool   $is_safe Security flag
d311d8 76      *
8b92d2 77      * @see self::$app, self::$storage, self::$opt, self::$parts
d311d8 78      */
63e793 79     function __construct($uid, $folder = null, $is_safe = false)
8fa58e 80     {
e8cb51 81         // decode combined UID-folder identifier
323fa2 82         if (preg_match('/^[0-9.]+-.+/', $uid)) {
1d1fdc 83             list($uid, $folder) = explode('-', $uid, 2);
e8cb51 84         }
TB 85
323fa2 86         if (preg_match('/^([0-9]+)\.([0-9.]+)$/', $uid, $matches)) {
AM 87             $uid     = $matches[1];
88             $context = $matches[2];
89         }
90
63e793 91         $this->uid     = $uid;
323fa2 92         $this->context = $context;
63e793 93         $this->app     = rcube::get_instance();
c321a9 94         $this->storage = $this->app->get_storage();
10562d 95         $this->folder  = strlen($folder) ? $folder : $this->storage->get_folder();
AM 96
97         // Set current folder
98         $this->storage->set_folder($this->folder);
63e793 99         $this->storage->set_options(array('all_headers' => true));
64e3e8 100
c321a9 101         $this->headers = $this->storage->get_message($uid);
64e3e8 102
4fdaa0 103         if (!$this->headers) {
64e3e8 104             return;
4fdaa0 105         }
64e3e8 106
63e793 107         $this->set_safe($is_safe || $_SESSION['safe_messages'][$this->folder.':'.$uid]);
d311d8 108         $this->opt = array(
59d11d 109             'safe'        => $this->is_safe,
d311d8 110             'prefer_html' => $this->app->config->get('prefer_html'),
59d11d 111             'get_url'     => $this->app->url(array(
AM 112                     'action' => 'get',
113                     'mbox'   => $this->folder,
4a4088 114                     'uid'    => $uid),
TB 115                 false, false, true)
d311d8 116         );
8fa58e 117
80152b 118         if (!empty($this->headers->structure)) {
A 119             $this->get_mime_numbers($this->headers->structure);
120             $this->parse_structure($this->headers->structure);
aa16b4 121         }
323fa2 122         else if ($this->context === null) {
c321a9 123             $this->body = $this->storage->get_body($uid);
d311d8 124         }
323fa2 125
AM 126         $this->mime    = new rcube_mime($this->headers->charset);
127         $this->subject = $this->headers->get('subject');
128         list(, $this->sender) = each($this->mime->decode_address_list($this->headers->from, 1));
d311d8 129
A 130         // notify plugins and let them analyze this structured message object
131         $this->app->plugins->exec_hook('message_load', array('object' => $this));
132     }
2ae58f 133
d311d8 134     /**
A 135      * Return a (decoded) message header
136      *
5c461b 137      * @param string $name Header name
A 138      * @param bool   $row  Don't mime-decode the value
d311d8 139      * @return string Header value
A 140      */
141     public function get_header($name, $raw = false)
142     {
4fdaa0 143         if (empty($this->headers)) {
1c4f23 144             return null;
4fdaa0 145         }
1c4f23 146
4fdaa0 147         return $this->headers->get($name, !$raw);
d311d8 148     }
A 149
150     /**
151      * Set is_safe var and session data
152      *
5c461b 153      * @param bool $safe enable/disable
d311d8 154      */
A 155     public function set_safe($safe = true)
156     {
f11142 157         $_SESSION['safe_messages'][$this->folder.':'.$this->uid] = $this->is_safe = $safe;
d311d8 158     }
A 159
160     /**
161      * Compose a valid URL for getting a message part
162      *
5c461b 163      * @param string $mime_id Part MIME-ID
a021d6 164      * @param mixed  $embed Mimetype class for parts to be embedded
d311d8 165      * @return string URL or false if part does not exist
A 166      */
57486f 167     public function get_part_url($mime_id, $embed = false)
d311d8 168     {
A 169         if ($this->mime_parts[$mime_id])
a021d6 170             return $this->opt['get_url'] . '&_part=' . $mime_id . ($embed ? '&_embed=1&_mimeclass=' . $embed : '');
aa16b4 171         else
d311d8 172             return false;
8fa58e 173     }
d311d8 174
A 175     /**
176      * Get content of a specific part of this message
177      *
71950d 178      * @param string   $mime_id           Part MIME-ID
A 179      * @param resource $fp File           pointer to save the message part
180      * @param boolean  $skip_charset_conv Disables charset conversion
dff2c7 181      * @param int      $max_bytes         Only read this number of bytes
ae8533 182      * @param boolean  $formatted         Enables formatting of text/* parts bodies
71950d 183      *
d311d8 184      * @return string Part content
48ba44 185      * @deprecated
d311d8 186      */
ae8533 187     public function get_part_content($mime_id, $fp = null, $skip_charset_conv = false, $max_bytes = 0, $formatted = true)
d311d8 188     {
A 189         if ($part = $this->mime_parts[$mime_id]) {
190             // stored in message structure (winmail/inline-uuencode)
8b92d2 191             if (!empty($part->body) || $part->encoding == 'stream') {
d311d8 192                 if ($fp) {
A 193                     fwrite($fp, $part->body);
194                 }
195                 return $fp ? true : $part->body;
196             }
10562d 197
d311d8 198             // get from IMAP
10562d 199             $this->storage->set_folder($this->folder);
AM 200
ae8533 201             return $this->storage->get_message_part($this->uid, $mime_id, $part,
AM 202                 NULL, $fp, $skip_charset_conv, $max_bytes, $formatted);
10562d 203         }
48ba44 204     }
AM 205
206     /**
207      * Get content of a specific part of this message
208      *
209      * @param string  $mime_id   Part ID
210      * @param boolean $formatted Enables formatting of text/* parts bodies
211      * @param int     $max_bytes Only return/read this number of bytes
212      * @param mixed   $mode      NULL to return a string, -1 to print body
213      *                           or file pointer to save the body into
214      *
215      * @return string|bool Part content or operation status
216      */
217     public function get_part_body($mime_id, $formatted = false, $max_bytes = 0, $mode = null)
218     {
219         if (!($part = $this->mime_parts[$mime_id])) {
220             return;
221         }
9af8e2 222
AM 223         // allow plugins to modify part body
224         $plugin = $this->app->plugins->exec_hook('message_part_body',
225             array('object' => $this, 'part' => $part));
48ba44 226
AM 227         // only text parts can be formatted
228         $formatted = $formatted && $part->ctype_primary == 'text';
229
230         // part body not fetched yet... save in memory if it's small enough
231         if ($part->body === null && is_numeric($mime_id) && $part->size < self::BODY_MAX_SIZE) {
d93019 232             $this->storage->set_folder($this->folder);
48ba44 233             // Warning: body here should be always unformatted
AM 234             $part->body = $this->storage->get_message_part($this->uid, $mime_id, $part,
235                 null, null, true, 0, false);
236         }
237
238         // body stored in message structure (winmail/inline-uuencode)
239         if ($part->body !== null || $part->encoding == 'stream') {
240             $body = $part->body;
241
242             if ($formatted && $body) {
243                 $body = self::format_part_body($body, $part, $this->headers->charset);
244             }
245
246             if ($max_bytes && strlen($body) > $max_bytes) {
247                 $body = substr($body, 0, $max_bytes);
248             }
249
250             if (is_resource($mode)) {
251                 if ($body !== false) {
252                     fwrite($mode, $body);
253                     rewind($mode);
254                 }
255
256                 return $body !== false;
257             }
258
259             if ($mode === -1) {
260                 if ($body !== false) {
261                     print($body);
262                 }
263
264                 return $body !== false;
265             }
266
267             return $body;
268         }
269
270         // get the body from IMAP
271         $this->storage->set_folder($this->folder);
272
273         $body = $this->storage->get_message_part($this->uid, $mime_id, $part,
68c41f 274             $mode === -1, is_resource($mode) ? $mode : null,
AM 275             !($mode && $formatted), $max_bytes, $mode && $formatted);
48ba44 276
AM 277         if (is_resource($mode)) {
278             rewind($mode);
279             return $body !== false;
280         }
281
68c41f 282         if (!$mode && $body && $formatted) {
AM 283             $body = self::format_part_body($body, $part, $this->headers->charset);
284         }
285
48ba44 286         return $body;
AM 287     }
288
289     /**
290      * Format text message part for display
291      *
292      * @param string             $body            Part body
293      * @param rcube_message_part $part            Part object
294      * @param string             $default_charset Fallback charset if part charset is not specified
295      *
296      * @return string Formatted body
297      */
298     public static function format_part_body($body, $part, $default_charset = null)
299     {
300         // remove useless characters
301         $body = preg_replace('/[\t\r\0\x0B]+\n/', "\n", $body);
302
303         // remove NULL characters if any (#1486189)
304         if (strpos($body, "\x00") !== false) {
305             $body = str_replace("\x00", '', $body);
306         }
307
308         // detect charset...
309         if (!$part->charset || strtoupper($part->charset) == 'US-ASCII') {
310             // try to extract charset information from HTML meta tag (#1488125)
311             if ($part->ctype_secondary == 'html' && preg_match('/<meta[^>]+charset=([a-z0-9-_]+)/i', $body, $m)) {
312                 $part->charset = strtoupper($m[1]);
313             }
314             else if ($default_charset) {
315                 $part->charset = $default_charset;
316             }
317             else {
318                 $rcube         = rcube::get_instance();
319                 $part->charset = $rcube->config->get('default_charset', RCUBE_CHARSET);
320             }
321         }
322
323         // ..convert charset encoding
324         $body = rcube_charset::convert($body, $part->charset);
325
326         return $body;
8fa58e 327     }
T 328
d311d8 329     /**
5c26bd 330      * Determine if the message contains a HTML part. This must to be
AM 331      * a real part not an attachment (or its part)
d311d8 332      *
b92a66 333      * @param bool               $enriched Enables checking for text/enriched parts too
AM 334      * @param rcube_message_part &$part    Reference to the part if found
33423a 335      *
d311d8 336      * @return bool True if a HTML is available, False if not
A 337      */
b92a66 338     public function has_html_part($enriched = false, &$part = null)
d311d8 339     {
A 340         // check all message parts
574928 341         foreach ($this->mime_parts as $part) {
323fa2 342             if (!$this->check_context($part)) {
AM 343                 continue;
344             }
345
52d0d9 346             if ($part->mimetype == 'text/html' || ($enriched && $part->mimetype == 'text/enriched')) {
0ef894 347                 // Skip if part is an attachment, don't use is_attachment() here
AM 348                 if ($part->filename) {
5c26bd 349                     continue;
AM 350                 }
33423a 351
5c26bd 352                 $level = explode('.', $part->mime_id);
f8101f 353                 $depth = count($level);
4c0cb9 354                 $last  = '';
5c26bd 355
5a2d2a 356                 // Check if the part belongs to higher-level's multipart part
f8101f 357                 // this can be alternative/related/signed/encrypted or mixed
5c26bd 358                 while (array_pop($level) !== null) {
f8101f 359                     $parent_depth = count($level);
TB 360                     if (!$parent_depth) {
5c26bd 361                         return true;
33423a 362                     }
A 363
4c0cb9 364                     $parent    = $this->mime_parts[join('.', $level)];
AM 365                     $max_delta = $depth - (1 + ($last == 'multipart/alternative' ? 1 : 0));
366                     $last      = $parent->mimetype;
367
f8101f 368                     if (!preg_match('/^multipart\/(alternative|related|signed|encrypted|mixed)$/', $parent->mimetype)
4c0cb9 369                         || ($parent->mimetype == 'multipart/mixed' && $parent_depth < $max_delta)) {
5c26bd 370                         continue 2;
33423a 371                     }
A 372                 }
373
5c26bd 374                 if ($part->size) {
AM 375                     return true;
376                 }
377             }
378         }
379
b92a66 380         $part = null;
AM 381
5c26bd 382         return false;
AM 383     }
384
385     /**
386      * Determine if the message contains a text/plain part. This must to be
387      * a real part not an attachment (or its part)
388      *
b92a66 389      * @param rcube_message_part &$part Reference to the part if found
AM 390      *
5c26bd 391      * @return bool True if a plain text part is available, False if not
AM 392      */
b92a66 393     public function has_text_part(&$part = null)
5c26bd 394     {
AM 395         // check all message parts
574928 396         foreach ($this->mime_parts as $part) {
5c26bd 397             if ($part->mimetype == 'text/plain') {
0ef894 398                 // Skip if part is an attachment, don't use is_attachment() here
AM 399                 if ($part->filename) {
323fa2 400                     continue;
AM 401                 }
402
403                 if (!$this->check_context($part)) {
5c26bd 404                     continue;
AM 405                 }
406
407                 $level = explode('.', $part->mime_id);
408
409                 // Check if the part belongs to higher-level's alternative/related
410                 while (array_pop($level) !== null) {
411                     if (!count($level)) {
412                         return true;
413                     }
414
415                     $parent = $this->mime_parts[join('.', $level)];
416                     if ($parent->mimetype != 'multipart/alternative' && $parent->mimetype != 'multipart/related') {
417                         continue 2;
418                     }
419                 }
420
421                 if ($part->size) {
422                     return true;
423                 }
33423a 424             }
d311d8 425         }
A 426
b92a66 427         $part = null;
AM 428
d311d8 429         return false;
A 430     }
431
432     /**
433      * Return the first HTML part of this message
434      *
b92a66 435      * @param rcube_message_part &$part    Reference to the part if found
AM 436      * @param bool               $enriched Enables checking for text/enriched parts too
437      *
d311d8 438      * @return string HTML message part content
A 439      */
b92a66 440     public function first_html_part(&$part = null, $enriched = false)
d311d8 441     {
b92a66 442         if ($this->has_html_part($enriched, $part)) {
AM 443             $body = $this->get_part_body($part->mime_id, true);
444
445             if ($part->mimetype == 'text/enriched') {
446                 $body = rcube_enriched::to_html($body);
d311d8 447             }
b92a66 448
AM 449             return $body;
d311d8 450         }
A 451     }
452
453     /**
b92a66 454      * Return the first text part of this message.
AM 455      * If there's no text/plain part but $strict=true and text/html part
456      * exists, it will be returned in text/plain format.
d311d8 457      *
b92a66 458      * @param rcube_message_part &$part  Reference to the part if found
AM 459      * @param bool               $strict Check only text/plain parts
460      *
d311d8 461      * @return string Plain text message/part content
A 462      */
b92a66 463     public function first_text_part(&$part = null, $strict = false)
d311d8 464     {
A 465         // no message structure, return complete body
b92a66 466         if (empty($this->parts)) {
d311d8 467             return $this->body;
A 468         }
469
b92a66 470         if ($this->has_text_part($part)) {
AM 471             return $this->get_part_body($part->mime_id, true);
472         }
473
474         if (!$strict && ($body = $this->first_html_part($part, true))) {
475             // create instance of html2text class
476             $h2t  = new rcube_html2text($body);
477             return $h2t->get_text();
478         }
d311d8 479     }
A 480
481     /**
3efc74 482      * Checks if part of the message is an attachment (or part of it)
AM 483      *
484      * @param rcube_message_part $part Message part
485      *
486      * @return bool True if the part is an attachment part
487      */
488     public function is_attachment($part)
489     {
490         foreach ($this->attachments as $att_part) {
491             if ($att_part->mime_id == $part->mime_id) {
492                 return true;
493             }
494
495             // check if the part is a subpart of another attachment part (message/rfc822)
496             if ($att_part->mimetype == 'message/rfc822') {
497                 if (in_array($part, (array)$att_part->parts)) {
498                     return true;
499                 }
500             }
501         }
502
503         return false;
504     }
505
506     /**
f7f75f 507      * In a multipart/encrypted encrypted message,
TB 508      * find the encrypted message payload part.
509      *
510      * @return rcube_message_part
511      */
512     public function get_multipart_encrypted_part()
513     {
514         foreach ($this->mime_parts as $mime_id => $mpart) {
515             if ($mpart->mimetype == 'multipart/encrypted') {
516                 $this->pgp_mime = true;
517             }
518             if ($this->pgp_mime && ($mpart->mimetype == 'application/octet-stream' ||
519                     (!empty($mpart->filename) && $mpart->filename != 'version.txt'))) {
520                 $this->encrypted_part = $mime_id;
521                 return $mpart;
522             }
523         }
524
525         return false;
526     }
527
528     /**
8b92d2 529      * Read the message structure returend by the IMAP server
d311d8 530      * and build flat lists of content parts and attachments
A 531      *
5c461b 532      * @param rcube_message_part $structure Message structure node
A 533      * @param bool               $recursive True when called recursively
d311d8 534      */
A 535     private function parse_structure($structure, $recursive = false)
536     {
537         // real content-type of message/rfc822 part
a8a72e 538         if ($structure->mimetype == 'message/rfc822' && $structure->real_mimetype) {
5ced9c 539             $mimetype = $structure->real_mimetype;
a8a72e 540
TB 541             // parse headers from message/rfc822 part
7ae7cd 542             if (!isset($structure->headers['subject']) && !isset($structure->headers['from'])) {
48ba44 543                 list($headers, ) = explode("\r\n\r\n", $this->get_part_body($structure->mime_id, false, 32768));
a8a72e 544                 $structure->headers = rcube_mime::parse_headers($headers);
323fa2 545
AM 546                 if ($this->context == $structure->mime_id) {
547                     $this->headers = rcube_message_header::from_array($structure->headers);
548                 }
a8a72e 549             }
TB 550         }
9af8e2 551         else {
5ced9c 552             $mimetype = $structure->mimetype;
9af8e2 553         }
d311d8 554
A 555         // show message headers
ddfdd8 556         if ($recursive && is_array($structure->headers) &&
323fa2 557             (isset($structure->headers['subject']) || $structure->headers['from'] || $structure->headers['to'])
AM 558         ) {
d311d8 559             $c = new stdClass;
A 560             $c->type = 'headers';
c5d7c9 561             $c->headers = $structure->headers;
323fa2 562             $this->add_part($c);
d311d8 563         }
5ced9c 564
A 565         // Allow plugins to handle message parts
566         $plugin = $this->app->plugins->exec_hook('message_part_structure',
567             array('object' => $this, 'structure' => $structure,
568                 'mimetype' => $mimetype, 'recursive' => $recursive));
569
9af8e2 570         if ($plugin['abort']) {
5ced9c 571             return;
9af8e2 572         }
5ced9c 573
A 574         $structure = $plugin['structure'];
9af8e2 575         $mimetype  = $plugin['mimetype'];
AM 576         $recursive = $plugin['recursive'];
577
578         list($message_ctype_primary, $message_ctype_secondary) = explode('/', $mimetype);
d311d8 579
A 580         // print body if message doesn't have multiple parts
581         if ($message_ctype_primary == 'text' && !$recursive) {
c23dc8 582             // parts with unsupported type add to attachments list
AM 583             if (!in_array($message_ctype_secondary, array('plain', 'html', 'enriched'))) {
323fa2 584                 $this->add_part($structure, 'attachment');
c23dc8 585                 return;
AM 586             }
587
d311d8 588             $structure->type = 'content';
323fa2 589             $this->add_part($structure);
8757f5 590
d311d8 591             // Parse simple (plain text) message body
c23dc8 592             if ($message_ctype_secondary == 'plain') {
d311d8 593                 foreach ((array)$this->uu_decode($structure) as $uupart) {
A 594                     $this->mime_parts[$uupart->mime_id] = $uupart;
323fa2 595                     $this->add_part($uupart, 'attachment');
d311d8 596                 }
c23dc8 597             }
d311d8 598         }
A 599         // the same for pgp signed messages
600         else if ($mimetype == 'application/pgp' && !$recursive) {
601             $structure->type = 'content';
323fa2 602             $this->add_part($structure);
d311d8 603         }
e730cd 604         // message contains (more than one!) alternative parts
A 605         else if ($mimetype == 'multipart/alternative'
606             && is_array($structure->parts) && count($structure->parts) > 1
607         ) {
c5d7c9 608             // get html/plaintext parts, other add to attachments list
d311d8 609             foreach ($structure->parts as $p => $sub_part) {
A 610                 $sub_mimetype = $sub_part->mimetype;
cb0f03 611                 $is_multipart = preg_match('/^multipart\/(related|relative|mixed|alternative)/', $sub_mimetype);
8757f5 612
5fbfde 613                 // skip empty text parts
c5d7c9 614                 if (!$sub_part->size && !$is_multipart) {
5f4095 615                     continue;
5fbfde 616                 }
5f4095 617
170702 618                 // We've encountered (malformed) messages with more than
AM 619                 // one text/plain or text/html part here. There's no way to choose
620                 // which one is better, so we'll display first of them and add
621                 // others as attachments (#1489358)
622
d311d8 623                 // check if sub part is
c5d7c9 624                 if ($is_multipart)
AM 625                     $related_part = $p;
170702 626                 else if ($sub_mimetype == 'text/plain' && !$plain_part)
d311d8 627                     $plain_part = $p;
5b737d 628                 else if ($sub_mimetype == 'text/html' && !$html_part) {
d311d8 629                     $html_part = $p;
5b737d 630                     $this->got_html_part = true;
AM 631                 }
170702 632                 else if ($sub_mimetype == 'text/enriched' && !$enriched_part)
d311d8 633                     $enriched_part = $p;
170702 634                 else {
AM 635                     // add unsupported/unrecognized parts to attachments list
323fa2 636                     $this->add_part($sub_part, 'attachment');
170702 637                 }
d311d8 638             }
A 639
640             // parse related part (alternative part could be in here)
641             if ($related_part !== null && !$this->parse_alternative) {
642                 $this->parse_alternative = true;
643                 $this->parse_structure($structure->parts[$related_part], true);
644                 $this->parse_alternative = false;
8757f5 645
d311d8 646                 // if plain part was found, we should unset it if html is preferred
A 647                 if ($this->opt['prefer_html'] && count($this->parts))
648                     $plain_part = null;
649             }
650
651             // choose html/plain part to print
652             if ($html_part !== null && $this->opt['prefer_html']) {
c5d7c9 653                 $print_part = $structure->parts[$html_part];
d311d8 654             }
A 655             else if ($enriched_part !== null) {
c5d7c9 656                 $print_part = $structure->parts[$enriched_part];
d311d8 657             }
A 658             else if ($plain_part !== null) {
c5d7c9 659                 $print_part = $structure->parts[$plain_part];
d311d8 660             }
A 661
662             // add the right message body
663             if (is_object($print_part)) {
664                 $print_part->type = 'content';
323fa2 665                 $this->add_part($print_part);
d311d8 666             }
A 667             // show plaintext warning
668             else if ($html_part !== null && empty($this->parts)) {
669                 $c = new stdClass;
670                 $c->type            = 'content';
671                 $c->ctype_primary   = 'text';
672                 $c->ctype_secondary = 'plain';
0c2596 673                 $c->mimetype        = 'text/plain';
A 674                 $c->realtype        = 'text/html';
d311d8 675
323fa2 676                 $this->add_part($c);
d311d8 677             }
A 678         }
679         // this is an ecrypted message -> create a plaintext body with the according message
680         else if ($mimetype == 'multipart/encrypted') {
681             $p = new stdClass;
682             $p->type            = 'content';
683             $p->ctype_primary   = 'text';
684             $p->ctype_secondary = 'plain';
0c2596 685             $p->mimetype        = 'text/plain';
A 686             $p->realtype        = 'multipart/encrypted';
ef2915 687             $p->mime_id         = $structure->mime_id;
c054ec 688
323fa2 689             $this->add_part($p);
ef2915 690
TB 691             // add encrypted payload part as attachment
692             if (is_array($structure->parts)) {
693                 for ($i=0; $i < count($structure->parts); $i++) {
694                     $subpart = $structure->parts[$i];
695                     if ($subpart->mimetype == 'application/octet-stream' || !empty($subpart->filename)) {
323fa2 696                         $this->add_part($subpart, 'attachment');
ef2915 697                     }
TB 698                 }
699             }
d311d8 700         }
ee89c6 701         // this is an S/MIME ecrypted message -> create a plaintext body with the according message
AM 702         else if ($mimetype == 'application/pkcs7-mime') {
703             $p = new stdClass;
704             $p->type            = 'content';
705             $p->ctype_primary   = 'text';
706             $p->ctype_secondary = 'plain';
707             $p->mimetype        = 'text/plain';
708             $p->realtype        = 'application/pkcs7-mime';
ef2915 709             $p->mime_id         = $structure->mime_id;
ee89c6 710
323fa2 711             $this->add_part($p);
ef2915 712
TB 713             if (!empty($structure->filename)) {
323fa2 714                 $this->add_part($structure, 'attachment');
ef2915 715             }
ee89c6 716         }
d311d8 717         // message contains multiple parts
A 718         else if (is_array($structure->parts) && !empty($structure->parts)) {
719             // iterate over parts
720             for ($i=0; $i < count($structure->parts); $i++) {
721                 $mail_part      = &$structure->parts[$i];
722                 $primary_type   = $mail_part->ctype_primary;
723                 $secondary_type = $mail_part->ctype_secondary;
be3460 724                 $part_mimetype  = $mail_part->mimetype;
8fa58e 725
be3460 726                 // multipart/alternative or message/rfc822
AM 727                 if ($primary_type == 'multipart' || $part_mimetype == 'message/rfc822') {
d311d8 728                     $this->parse_structure($mail_part, true);
A 729
730                     // list message/rfc822 as attachment as well (mostly .eml)
be3460 731                     if ($primary_type == 'message' && !empty($mail_part->filename)) {
323fa2 732                         $this->add_part($mail_part, 'attachment');
be3460 733                     }
d311d8 734                 }
f22ea7 735                 // part text/[plain|html] or delivery status
d311d8 736                 else if ((($part_mimetype == 'text/plain' || $part_mimetype == 'text/html') && $mail_part->disposition != 'attachment') ||
f22ea7 737                     in_array($part_mimetype, array('message/delivery-status', 'text/rfc822-headers', 'message/disposition-notification'))
d311d8 738                 ) {
1a2f83 739                     // Allow plugins to handle also this part
A 740                     $plugin = $this->app->plugins->exec_hook('message_part_structure',
741                         array('object' => $this, 'structure' => $mail_part,
742                             'mimetype' => $part_mimetype, 'recursive' => true));
743
be3460 744                     if ($plugin['abort']) {
1a2f83 745                         continue;
be3460 746                     }
1a2f83 747
9c299e 748                     if ($part_mimetype == 'text/html' && $mail_part->size) {
5b737d 749                         $this->got_html_part = true;
63f9de 750                     }
A 751
1a2f83 752                     $mail_part = $plugin['structure'];
A 753                     list($primary_type, $secondary_type) = explode('/', $plugin['mimetype']);
754
d311d8 755                     // add text part if it matches the prefs
A 756                     if (!$this->parse_alternative ||
757                         ($secondary_type == 'html' && $this->opt['prefer_html']) ||
758                         ($secondary_type == 'plain' && !$this->opt['prefer_html'])
759                     ) {
760                         $mail_part->type = 'content';
323fa2 761                         $this->add_part($mail_part);
d311d8 762                     }
fd371a 763
d311d8 764                     // list as attachment as well
f7c11e 765                     if (!empty($mail_part->filename)) {
323fa2 766                         $this->add_part($mail_part, 'attachment');
f7c11e 767                     }
d311d8 768                 }
A 769                 // ignore "virtual" protocol parts
770                 else if ($primary_type == 'protocol') {
771                     continue;
772                 }
773                 // part is Microsoft Outlook TNEF (winmail.dat)
774                 else if ($part_mimetype == 'application/ms-tnef') {
292292 775                     $tnef_parts = (array) $this->tnef_decode($mail_part);
AM 776                     foreach ($tnef_parts as $tpart) {
d311d8 777                         $this->mime_parts[$tpart->mime_id] = $tpart;
323fa2 778                         $this->add_part($tpart, 'attachment');
d311d8 779                     }
292292 780
AM 781                     // add winmail.dat to the list if it's content is unknown
782                     if (empty($tnef_parts) && !empty($mail_part->filename)) {
783                         $this->mime_parts[$mail_part->mime_id] = $mail_part;
323fa2 784                         $this->add_part($mail_part, 'attachment');
292292 785                     }
d311d8 786                 }
A 787                 // part is a file/attachment
788                 else if (preg_match('/^(inline|attach)/', $mail_part->disposition) ||
8794f1 789                     $mail_part->headers['content-id'] ||
A 790                     ($mail_part->filename &&
791                         (empty($mail_part->disposition) || preg_match('/^[a-z0-9!#$&.+^_-]+$/i', $mail_part->disposition)))
d311d8 792                 ) {
A 793                     // skip apple resource forks
794                     if ($message_ctype_secondary == 'appledouble' && $secondary_type == 'applefile')
795                         continue;
796
797                     // part belongs to a related message and is linked
cb0f03 798                     if (preg_match('/^multipart\/(related|relative)/', $mimetype)
be3460 799                         && ($mail_part->headers['content-id'] || $mail_part->headers['content-location'])
AM 800                     ) {
d311d8 801                         if ($mail_part->headers['content-id'])
A 802                             $mail_part->content_id = preg_replace(array('/^</', '/>$/'), '', $mail_part->headers['content-id']);
803                         if ($mail_part->headers['content-location'])
804                             $mail_part->content_location = $mail_part->headers['content-base'] . $mail_part->headers['content-location'];
805
323fa2 806                         $this->add_part($mail_part, 'inline');
d311d8 807                     }
b38925 808                     // regular attachment with valid content type
A 809                     // (content-type name regexp according to RFC4288.4.2)
2ae58f 810                     else if (preg_match('/^[a-z0-9!#$&.+^_-]+\/[a-z0-9!#$&.+^_-]+$/i', $part_mimetype)) {
323fa2 811                         $this->add_part($mail_part, 'attachment');
b38925 812                     }
A 813                     // attachment with invalid content type
814                     // replace malformed content type with application/octet-stream (#1487767)
815                     else if ($mail_part->filename) {
816                         $mail_part->ctype_primary   = 'application';
817                         $mail_part->ctype_secondary = 'octet-stream';
818                         $mail_part->mimetype        = 'application/octet-stream';
819
323fa2 820                         $this->add_part($mail_part, 'attachment');
d311d8 821                     }
8757f5 822                 }
98e461 823                 // calendar part not marked as attachment (#1490325)
AM 824                 else if ($part_mimetype == 'text/calendar') {
825                     if (!$mail_part->filename) {
826                         $mail_part->filename = 'calendar.ics';
827                     }
828
323fa2 829                     $this->add_part($mail_part, 'attachment');
98e461 830                 }
d311d8 831             }
A 832
833             // if this was a related part try to resolve references
cb0f03 834             if (preg_match('/^multipart\/(related|relative)/', $mimetype) && sizeof($this->inline_parts)) {
d311d8 835                 $a_replaces = array();
89d19c 836                 $img_regexp = '/^image\/(gif|jpe?g|png|tiff|bmp|svg)/';
d311d8 837
A 838                 foreach ($this->inline_parts as $inline_object) {
a021d6 839                     $part_url = $this->get_part_url($inline_object->mime_id, $inline_object->ctype_primary);
8cfba1 840                     if (isset($inline_object->content_id))
d311d8 841                         $a_replaces['cid:'.$inline_object->content_id] = $part_url;
63f9de 842                     if ($inline_object->content_location) {
d311d8 843                         $a_replaces[$inline_object->content_location] = $part_url;
63f9de 844                     }
89d19c 845
A 846                     if (!empty($inline_object->filename)) {
847                         // MS Outlook sends sometimes non-related attachments as related
848                         // In this case multipart/related message has only one text part
849                         // We'll add all such attachments to the attachments list
5b737d 850                         if (!isset($this->got_html_part)) {
323fa2 851                             $this->add_part($inline_object, 'attachment');
89d19c 852                         }
A 853                         // MS Outlook sometimes also adds non-image attachments as related
854                         // We'll add all such attachments to the attachments list
855                         // Warning: some browsers support pdf in <img/>
856                         else if (!preg_match($img_regexp, $inline_object->mimetype)) {
323fa2 857                             $this->add_part($inline_object, 'attachment');
89d19c 858                         }
A 859                         // @TODO: we should fetch HTML body and find attachment's content-id
860                         // to handle also image attachments without reference in the body
861                         // @TODO: should we list all image attachments in text mode?
02b6e6 862                     }
d311d8 863                 }
A 864
865                 // add replace array to each content part
866                 // (will be applied later when part body is available)
867                 foreach ($this->parts as $i => $part) {
868                     if ($part->type == 'content')
869                         $this->parts[$i]->replaces = $a_replaces;
870                 }
871             }
872         }
873         // message is a single part non-text
874         else if ($structure->filename) {
323fa2 875             $this->add_part($structure, $attachment);
d311d8 876         }
3e58bf 877         // message is a single part non-text (without filename)
A 878         else if (preg_match('/application\//i', $mimetype)) {
323fa2 879             $this->add_part($structure, 'attachment');
c5d7c9 880         }
AM 881     }
882
883     /**
323fa2 884      * Fill a flat array with references to all parts, indexed by part numbers
d311d8 885      *
5c461b 886      * @param rcube_message_part $part Message body structure
d311d8 887      */
A 888     private function get_mime_numbers(&$part)
889     {
890         if (strlen($part->mime_id))
891             $this->mime_parts[$part->mime_id] = &$part;
f19d86 892
d311d8 893         if (is_array($part->parts))
A 894             for ($i=0; $i<count($part->parts); $i++)
895                 $this->get_mime_numbers($part->parts[$i]);
896     }
897
898     /**
323fa2 899      * Add a part to object parts array(s) (with context check)
AM 900      */
901     private function add_part($part, $type = null)
902     {
903         if ($this->check_context($part)) {
904             switch ($type) {
905                 case 'inline': $this->inline_parts[] = $part; break;
906                 case 'attachment': $this->attachments[] = $part; break;
907                 default: $this->parts[] = $part; break;
908             }
909         }
910     }
911
912     /**
913      * Check if specified part belongs to the current context
914      */
915     private function check_context($part)
916     {
917         return $this->context === null || strpos($part->mime_id, $this->context . '.') === 0;
918     }
919
920     /**
d311d8 921      * Decode a Microsoft Outlook TNEF part (winmail.dat)
A 922      *
5c461b 923      * @param rcube_message_part $part Message part to decode
A 924      * @return array
d311d8 925      */
A 926     function tnef_decode(&$part)
927     {
48ba44 928         // @TODO: attachment may be huge, handle body via file
AM 929         $body     = $this->get_part_body($part->mime_id);
2883fc 930         $tnef     = new rcube_tnef_decoder;
48ba44 931         $tnef_arr = $tnef->decompress($body);
AM 932         $parts    = array();
d311d8 933
48ba44 934         unset($body);
d311d8 935
A 936         foreach ($tnef_arr as $pid => $winatt) {
937             $tpart = new rcube_message_part;
938
2da830 939             $tpart->filename        = $this->fix_attachment_name(trim($winatt['name']), $part);
d311d8 940             $tpart->encoding        = 'stream';
f19d86 941             $tpart->ctype_primary   = trim(strtolower($winatt['type']));
A 942             $tpart->ctype_secondary = trim(strtolower($winatt['subtype']));
d311d8 943             $tpart->mimetype        = $tpart->ctype_primary . '/' . $tpart->ctype_secondary;
A 944             $tpart->mime_id         = 'winmail.' . $part->mime_id . '.' . $pid;
945             $tpart->size            = $winatt['size'];
946             $tpart->body            = $winatt['stream'];
947
948             $parts[] = $tpart;
949             unset($tnef_arr[$pid]);
950         }
f19d86 951
d311d8 952         return $parts;
A 953     }
954
955     /**
956      * Parse message body for UUencoded attachments bodies
957      *
5c461b 958      * @param rcube_message_part $part Message part to decode
A 959      * @return array
d311d8 960      */
A 961     function uu_decode(&$part)
962     {
48ba44 963         // @TODO: messages may be huge, handle body via file
AM 964         $part->body = $this->get_part_body($part->mime_id);
965         $parts      = array();
966         $pid        = 0;
d311d8 967
A 968         // FIXME: line length is max.65?
48ba44 969         $uu_regexp_begin = '/begin [0-7]{3,4} ([^\r\n]+)\r?\n/s';
AM 970         $uu_regexp_end   = '/`\r?\nend((\r?\n)|($))/s';
d311d8 971
48ba44 972         while (preg_match($uu_regexp_begin, $part->body, $matches, PREG_OFFSET_CAPTURE)) {
AM 973             $startpos = $matches[0][1];
d311d8 974
48ba44 975             if (!preg_match($uu_regexp_end, $part->body, $m, PREG_OFFSET_CAPTURE, $startpos)) {
AM 976                 break;
d311d8 977             }
14f22f 978
48ba44 979             $endpos    = $m[0][1];
AM 980             $begin_len = strlen($matches[0][0]);
981             $end_len   = strlen($m[0][0]);
982
983             // extract attachment body
984             $filebody = substr($part->body, $startpos + $begin_len, $endpos - $startpos - $begin_len - 1);
985             $filebody = str_replace("\r\n", "\n", $filebody);
986
987             // remove attachment body from the message body
988             $part->body = substr_replace($part->body, '', $startpos, $endpos + $end_len - $startpos);
2268aa 989             // mark body as modified so it will not be cached by rcube_imap_cache
AM 990             $part->body_modified = true;
48ba44 991
AM 992             // add attachments to the structure
993             $uupart = new rcube_message_part;
994             $uupart->filename = trim($matches[1][0]);
995             $uupart->encoding = 'stream';
996             $uupart->body     = convert_uudecode($filebody);
997             $uupart->size     = strlen($uupart->body);
998             $uupart->mime_id  = 'uu.' . $part->mime_id . '.' . $pid;
999
1000             $ctype = rcube_mime::file_content_type($uupart->body, $uupart->filename, 'application/octet-stream', true);
1001             $uupart->mimetype = $ctype;
1002             list($uupart->ctype_primary, $uupart->ctype_secondary) = explode('/', $ctype);
1003
1004             $parts[] = $uupart;
1005             $pid++;
d311d8 1006         }
f19d86 1007
d311d8 1008         return $parts;
A 1009     }
b91f04 1010
2da830 1011     /**
AM 1012      * Fix attachment name encoding if needed/possible
1013      */
1014     protected function fix_attachment_name($name, $part)
1015     {
1016         if ($name == rcube_charset::clean($name)) {
1017             return $name;
1018         }
1019
1020         // find charset from part or its parent(s)
1021         if ($part->charset) {
1022             $charsets[] = $part->charset;
1023         }
1024         else {
1025             // check first part (common case)
1026             $n = strpos($part->mime_id, '.') ? preg_replace('/\.[0-9]+$/', '', $part->mime_id) . '.1' : 1;
1027             if (($_part = $this->mime_parts[$n]) && $_part->charset) {
1028                 $charsets[] = $_part->charset;
1029             }
1030
1031             // check parents' charset
1032             $items = explode('.', $part->mime_id);
1033             for ($i = count($items)-1; $i > 0; $i--) {
1034                 $last   = array_pop($items);
1035                 $parent = $this->mime_parts[join('.', $items)];
1036
1037                 if ($parent && $parent->charset) {
1038                     $charsets[] = $parent->charset;
1039                 }
1040             }
1041         }
1042
1043         if ($this->headers->charset) {
1044             $charsets[] = $this->headers->charset;
1045         }
1046
1047         if (empty($charsets)) {
1048             $rcube      = rcube::get_instance();
1049             $charsets[] = rcube_charset::detect($name, $rcube->config->get('default_charset', RCUBE_CHARSET));
1050         }
1051
1052         foreach (array_unique($charsets) as $charset) {
1053             $_name = rcube_charset::convert($name, $charset);
1054
1055             if ($_name == rcube_charset::clean($_name)) {
1056                 if (!$part->charset) {
1057                     $part->charset = $charset;
1058                 }
1059
1060                 return $_name;
1061             }
1062         }
1063
1064         return $name;
1065     }
b91f04 1066
T 1067     /**
1068      * Deprecated methods (to be removed)
1069      */
1070
1071     public static function unfold_flowed($text)
1072     {
1073         return rcube_mime::unfold_flowed($text);
1074     }
1075
1076     public static function format_flowed($text, $length = 72)
1077     {
1078         return rcube_mime::format_flowed($text, $length);
1079     }
8fa58e 1080 }