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