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