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