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