Aleksander Machniak
2015-12-17 5579ef662197029afbf90d7bc2bfb5ba594475ac
commit | author | age
8fa58e 1 <?php
T 2
3 /*
4  +-----------------------------------------------------------------------+
e019f2 5  | This file is part of the Roundcube Webmail client                     |
f5e7b3 6  | Copyright (C) 2008-2010, The Roundcube Dev Team                       |
7fe381 7  |                                                                       |
T 8  | Licensed under the GNU General Public License version 3 or            |
9  | any later version with exceptions for skins & plugins.                |
10  | See the README file for a full license statement.                     |
8fa58e 11  |                                                                       |
T 12  | PURPOSE:                                                              |
13  |   Logical representation of a mail message with all its data          |
14  |   and related functions                                               |
15  +-----------------------------------------------------------------------+
16  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
17  +-----------------------------------------------------------------------+
18 */
19
20 /**
45f56c 21  * Logical representation of a mail message with all its data
T 22  * and related functions
8fa58e 23  *
9ab346 24  * @package    Framework
AM 25  * @subpackage Storage
8fa58e 26  * @author     Thomas Bruederli <roundcube@gmail.com>
T 27  */
28 class rcube_message
29 {
5c461b 30     /**
be98df 31      * Instace of framework class.
5c461b 32      *
be98df 33      * @var rcube
5c461b 34      */
d311d8 35     private $app;
5c461b 36
A 37     /**
8b92d2 38      * Instance of storage class
5c461b 39      *
8b92d2 40      * @var rcube_storage
5c461b 41      */
8b92d2 42     private $storage;
1c4f23 43
A 44     /**
45      * Instance of mime class
46      *
47      * @var rcube_mime
48      */
49     private $mime;
d311d8 50     private $opt = array();
A 51     private $parse_alternative = false;
2ae58f 52
10562d 53     public $uid;
AM 54     public $folder;
d311d8 55     public $headers;
A 56     public $parts = array();
57     public $mime_parts = array();
287eff 58     public $inline_parts = array();
d311d8 59     public $attachments = array();
A 60     public $subject = '';
61     public $sender = null;
62     public $is_safe = false;
2ae58f 63
193fb4 64
d311d8 65     /**
A 66      * __construct
67      *
68      * Provide a uid, and parse message structure.
69      *
10562d 70      * @param string $uid    The message UID.
AM 71      * @param string $folder Folder name
d311d8 72      *
8b92d2 73      * @see self::$app, self::$storage, self::$opt, self::$parts
d311d8 74      */
10562d 75     function __construct($uid, $folder = null)
8fa58e 76     {
1c4f23 77         $this->uid  = $uid;
0c2596 78         $this->app  = rcube::get_instance();
c321a9 79         $this->storage = $this->app->get_storage();
10562d 80         $this->folder  = strlen($folder) ? $folder : $this->storage->get_folder();
c321a9 81         $this->storage->set_options(array('all_headers' => true));
10562d 82
AM 83         // Set current folder
84         $this->storage->set_folder($this->folder);
64e3e8 85
c321a9 86         $this->headers = $this->storage->get_message($uid);
64e3e8 87
4fdaa0 88         if (!$this->headers) {
64e3e8 89             return;
4fdaa0 90         }
8fa58e 91
1c4f23 92         $this->mime = new rcube_mime($this->headers->charset);
A 93
4fdaa0 94         $this->subject = $this->headers->get('subject');
1c4f23 95         list(, $this->sender) = each($this->mime->decode_address_list($this->headers->from, 1));
64e3e8 96
f11142 97         $this->set_safe((intval($_GET['_safe']) || $_SESSION['safe_messages'][$this->folder.':'.$uid]));
d311d8 98         $this->opt = array(
A 99             'safe' => $this->is_safe,
100             'prefer_html' => $this->app->config->get('prefer_html'),
0c2596 101             'get_url' => $this->app->url(array(
A 102                 'action' => 'get',
103                 'mbox'   => $this->storage->get_folder(),
104                 'uid'    => $uid))
d311d8 105         );
8fa58e 106
80152b 107         if (!empty($this->headers->structure)) {
A 108             $this->get_mime_numbers($this->headers->structure);
109             $this->parse_structure($this->headers->structure);
aa16b4 110         }
d311d8 111         else {
c321a9 112             $this->body = $this->storage->get_body($uid);
d311d8 113         }
A 114
115         // notify plugins and let them analyze this structured message object
116         $this->app->plugins->exec_hook('message_load', array('object' => $this));
117     }
2ae58f 118
A 119
d311d8 120     /**
A 121      * Return a (decoded) message header
122      *
5c461b 123      * @param string $name Header name
A 124      * @param bool   $row  Don't mime-decode the value
d311d8 125      * @return string Header value
A 126      */
127     public function get_header($name, $raw = false)
128     {
4fdaa0 129         if (empty($this->headers)) {
1c4f23 130             return null;
4fdaa0 131         }
1c4f23 132
4fdaa0 133         return $this->headers->get($name, !$raw);
d311d8 134     }
A 135
2ae58f 136
d311d8 137     /**
A 138      * Set is_safe var and session data
139      *
5c461b 140      * @param bool $safe enable/disable
d311d8 141      */
A 142     public function set_safe($safe = true)
143     {
f11142 144         $_SESSION['safe_messages'][$this->folder.':'.$this->uid] = $this->is_safe = $safe;
d311d8 145     }
A 146
147
148     /**
149      * Compose a valid URL for getting a message part
150      *
5c461b 151      * @param string $mime_id Part MIME-ID
a021d6 152      * @param mixed  $embed Mimetype class for parts to be embedded
d311d8 153      * @return string URL or false if part does not exist
A 154      */
57486f 155     public function get_part_url($mime_id, $embed = false)
d311d8 156     {
A 157         if ($this->mime_parts[$mime_id])
a021d6 158             return $this->opt['get_url'] . '&_part=' . $mime_id . ($embed ? '&_embed=1&_mimeclass=' . $embed : '');
aa16b4 159         else
d311d8 160             return false;
8fa58e 161     }
T 162
d311d8 163
A 164     /**
165      * Get content of a specific part of this message
166      *
71950d 167      * @param string   $mime_id           Part MIME-ID
A 168      * @param resource $fp File           pointer to save the message part
169      * @param boolean  $skip_charset_conv Disables charset conversion
dff2c7 170      * @param int      $max_bytes         Only read this number of bytes
ae8533 171      * @param boolean  $formatted         Enables formatting of text/* parts bodies
71950d 172      *
d311d8 173      * @return string Part content
A 174      */
ae8533 175     public function get_part_content($mime_id, $fp = null, $skip_charset_conv = false, $max_bytes = 0, $formatted = true)
d311d8 176     {
A 177         if ($part = $this->mime_parts[$mime_id]) {
178             // stored in message structure (winmail/inline-uuencode)
8b92d2 179             if (!empty($part->body) || $part->encoding == 'stream') {
d311d8 180                 if ($fp) {
A 181                     fwrite($fp, $part->body);
182                 }
183                 return $fp ? true : $part->body;
184             }
10562d 185
d311d8 186             // get from IMAP
10562d 187             $this->storage->set_folder($this->folder);
AM 188
ae8533 189             return $this->storage->get_message_part($this->uid, $mime_id, $part,
AM 190                 NULL, $fp, $skip_charset_conv, $max_bytes, $formatted);
10562d 191         }
8fa58e 192     }
T 193
194
d311d8 195     /**
5c26bd 196      * Determine if the message contains a HTML part. This must to be
AM 197      * a real part not an attachment (or its part)
d311d8 198      *
5c26bd 199      * @param bool $enriched Enables checking for text/enriched parts too
33423a 200      *
d311d8 201      * @return bool True if a HTML is available, False if not
A 202      */
5c26bd 203     function has_html_part($enriched = false)
d311d8 204     {
A 205         // check all message parts
574928 206         foreach ($this->mime_parts as $part) {
52d0d9 207             if ($part->mimetype == 'text/html' || ($enriched && $part->mimetype == 'text/enriched')) {
0ef894 208                 // Skip if part is an attachment, don't use is_attachment() here
AM 209                 if ($part->filename) {
5c26bd 210                     continue;
AM 211                 }
33423a 212
5c26bd 213                 $level = explode('.', $part->mime_id);
f8101f 214                 $depth = count($level);
5c26bd 215
5a2d2a 216                 // Check if the part belongs to higher-level's multipart part
f8101f 217                 // this can be alternative/related/signed/encrypted or mixed
5c26bd 218                 while (array_pop($level) !== null) {
f8101f 219                     $parent_depth = count($level);
TB 220                     if (!$parent_depth) {
5c26bd 221                         return true;
33423a 222                     }
A 223
5c26bd 224                     $parent = $this->mime_parts[join('.', $level)];
f8101f 225                     if (!preg_match('/^multipart\/(alternative|related|signed|encrypted|mixed)$/', $parent->mimetype)
TB 226                         || ($parent->mimetype == 'multipart/mixed' && $parent_depth < $depth - 1)) {
5c26bd 227                         continue 2;
33423a 228                     }
A 229                 }
230
5c26bd 231                 if ($part->size) {
AM 232                     return true;
233                 }
234             }
235         }
236
237         return false;
238     }
239
240
241     /**
242      * Determine if the message contains a text/plain part. This must to be
243      * a real part not an attachment (or its part)
244      *
245      * @return bool True if a plain text part is available, False if not
246      */
247     function has_text_part()
248     {
249         // check all message parts
574928 250         foreach ($this->mime_parts as $part) {
5c26bd 251             if ($part->mimetype == 'text/plain') {
0ef894 252                 // Skip if part is an attachment, don't use is_attachment() here
AM 253                 if ($part->filename) {
5c26bd 254                     continue;
AM 255                 }
256
257                 $level = explode('.', $part->mime_id);
258
259                 // Check if the part belongs to higher-level's alternative/related
260                 while (array_pop($level) !== null) {
261                     if (!count($level)) {
262                         return true;
263                     }
264
265                     $parent = $this->mime_parts[join('.', $level)];
266                     if ($parent->mimetype != 'multipart/alternative' && $parent->mimetype != 'multipart/related') {
267                         continue 2;
268                     }
269                 }
270
271                 if ($part->size) {
272                     return true;
273                 }
33423a 274             }
d311d8 275         }
A 276
277         return false;
278     }
279
280
281     /**
282      * Return the first HTML part of this message
283      *
284      * @return string HTML message part content
285      */
286     function first_html_part()
287     {
288         // check all message parts
33423a 289         foreach ($this->mime_parts as $pid => $part) {
A 290             if ($part->mimetype == 'text/html') {
291                 return $this->get_part_content($pid);
d311d8 292             }
A 293         }
294     }
295
296
297     /**
298      * Return the first text part of this message
299      *
868deb 300      * @param rcube_message_part $part Reference to the part if found
d311d8 301      * @return string Plain text message/part content
A 302      */
868deb 303     function first_text_part(&$part=null)
d311d8 304     {
A 305         // no message structure, return complete body
306         if (empty($this->parts))
307             return $this->body;
308
309         // check all message parts
310         foreach ($this->mime_parts as $mime_id => $part) {
33423a 311             if ($part->mimetype == 'text/plain') {
8b92d2 312                 return $this->get_part_content($mime_id);
d311d8 313             }
33423a 314             else if ($part->mimetype == 'text/html') {
8b92d2 315                 $out = $this->get_part_content($mime_id);
d311d8 316
A 317                 // create instance of html2text class
66afd7 318                 $txt = new rcube_html2text($out);
868deb 319                 return $txt->get_text();
d311d8 320             }
A 321         }
322
868deb 323         $part = null;
A 324         return null;
d311d8 325     }
A 326
327
328     /**
3efc74 329      * Checks if part of the message is an attachment (or part of it)
AM 330      *
331      * @param rcube_message_part $part Message part
332      *
333      * @return bool True if the part is an attachment part
334      */
335     public function is_attachment($part)
336     {
337         foreach ($this->attachments as $att_part) {
338             if ($att_part->mime_id == $part->mime_id) {
339                 return true;
340             }
341
342             // check if the part is a subpart of another attachment part (message/rfc822)
343             if ($att_part->mimetype == 'message/rfc822') {
344                 if (in_array($part, (array)$att_part->parts)) {
345                     return true;
346                 }
347             }
348         }
349
350         return false;
351     }
352
353
354     /**
8b92d2 355      * Read the message structure returend by the IMAP server
d311d8 356      * and build flat lists of content parts and attachments
A 357      *
5c461b 358      * @param rcube_message_part $structure Message structure node
A 359      * @param bool               $recursive True when called recursively
d311d8 360      */
A 361     private function parse_structure($structure, $recursive = false)
362     {
363         // real content-type of message/rfc822 part
a8a72e 364         if ($structure->mimetype == 'message/rfc822' && $structure->real_mimetype) {
5ced9c 365             $mimetype = $structure->real_mimetype;
a8a72e 366
TB 367             // parse headers from message/rfc822 part
7ae7cd 368             if (!isset($structure->headers['subject']) && !isset($structure->headers['from'])) {
3725cf 369                 list($headers, ) = explode("\r\n\r\n", $this->get_part_content($structure->mime_id, null, true, 32768));
a8a72e 370                 $structure->headers = rcube_mime::parse_headers($headers);
TB 371             }
372         }
5ced9c 373         else
A 374             $mimetype = $structure->mimetype;
d311d8 375
A 376         // show message headers
ddfdd8 377         if ($recursive && is_array($structure->headers) &&
TB 378                 (isset($structure->headers['subject']) || $structure->headers['from'] || $structure->headers['to'])) {
d311d8 379             $c = new stdClass;
A 380             $c->type = 'headers';
c5d7c9 381             $c->headers = $structure->headers;
d311d8 382             $this->parts[] = $c;
A 383         }
5ced9c 384
A 385         // Allow plugins to handle message parts
386         $plugin = $this->app->plugins->exec_hook('message_part_structure',
387             array('object' => $this, 'structure' => $structure,
388                 'mimetype' => $mimetype, 'recursive' => $recursive));
389
390         if ($plugin['abort'])
391             return;
392
393         $structure = $plugin['structure'];
394         list($message_ctype_primary, $message_ctype_secondary) = explode('/', $plugin['mimetype']);
d311d8 395
A 396         // print body if message doesn't have multiple parts
397         if ($message_ctype_primary == 'text' && !$recursive) {
c23dc8 398             // parts with unsupported type add to attachments list
AM 399             if (!in_array($message_ctype_secondary, array('plain', 'html', 'enriched'))) {
400                 $this->attachments[] = $structure;
401                 return;
402             }
403
d311d8 404             $structure->type = 'content';
c5d7c9 405             $this->parts[] = $structure;
8757f5 406
d311d8 407             // Parse simple (plain text) message body
c23dc8 408             if ($message_ctype_secondary == 'plain') {
d311d8 409                 foreach ((array)$this->uu_decode($structure) as $uupart) {
A 410                     $this->mime_parts[$uupart->mime_id] = $uupart;
411                     $this->attachments[] = $uupart;
412                 }
c23dc8 413             }
d311d8 414         }
A 415         // the same for pgp signed messages
416         else if ($mimetype == 'application/pgp' && !$recursive) {
417             $structure->type = 'content';
c5d7c9 418             $this->parts[] = $structure;
d311d8 419         }
e730cd 420         // message contains (more than one!) alternative parts
A 421         else if ($mimetype == 'multipart/alternative'
422             && is_array($structure->parts) && count($structure->parts) > 1
423         ) {
c5d7c9 424             $plain_part   = null;
AM 425             $html_part    = null;
426             $print_part   = null;
427             $related_part = null;
428             $attach_part  = null;
d311d8 429
c5d7c9 430             // get html/plaintext parts, other add to attachments list
d311d8 431             foreach ($structure->parts as $p => $sub_part) {
A 432                 $sub_mimetype = $sub_part->mimetype;
cb0f03 433                 $is_multipart = preg_match('/^multipart\/(related|relative|mixed|alternative)/', $sub_mimetype);
8757f5 434
5fbfde 435                 // skip empty text parts
c5d7c9 436                 if (!$sub_part->size && !$is_multipart) {
5f4095 437                     continue;
5fbfde 438                 }
5f4095 439
170702 440                 // We've encountered (malformed) messages with more than
AM 441                 // one text/plain or text/html part here. There's no way to choose
442                 // which one is better, so we'll display first of them and add
443                 // others as attachments (#1489358)
444
d311d8 445                 // check if sub part is
c5d7c9 446                 if ($is_multipart)
AM 447                     $related_part = $p;
170702 448                 else if ($sub_mimetype == 'text/plain' && !$plain_part)
d311d8 449                     $plain_part = $p;
170702 450                 else if ($sub_mimetype == 'text/html' && !$html_part)
d311d8 451                     $html_part = $p;
170702 452                 else if ($sub_mimetype == 'text/enriched' && !$enriched_part)
d311d8 453                     $enriched_part = $p;
170702 454                 else {
AM 455                     // add unsupported/unrecognized parts to attachments list
456                     $this->attachments[] = $sub_part;
457                 }
d311d8 458             }
A 459
460             // parse related part (alternative part could be in here)
461             if ($related_part !== null && !$this->parse_alternative) {
462                 $this->parse_alternative = true;
463                 $this->parse_structure($structure->parts[$related_part], true);
464                 $this->parse_alternative = false;
8757f5 465
d311d8 466                 // if plain part was found, we should unset it if html is preferred
A 467                 if ($this->opt['prefer_html'] && count($this->parts))
468                     $plain_part = null;
469             }
470
471             // choose html/plain part to print
472             if ($html_part !== null && $this->opt['prefer_html']) {
c5d7c9 473                 $print_part = $structure->parts[$html_part];
d311d8 474             }
A 475             else if ($enriched_part !== null) {
c5d7c9 476                 $print_part = $structure->parts[$enriched_part];
d311d8 477             }
A 478             else if ($plain_part !== null) {
c5d7c9 479                 $print_part = $structure->parts[$plain_part];
d311d8 480             }
A 481
482             // add the right message body
483             if (is_object($print_part)) {
484                 $print_part->type = 'content';
485                 $this->parts[] = $print_part;
486             }
487             // show plaintext warning
488             else if ($html_part !== null && empty($this->parts)) {
489                 $c = new stdClass;
490                 $c->type            = 'content';
491                 $c->ctype_primary   = 'text';
492                 $c->ctype_secondary = 'plain';
0c2596 493                 $c->mimetype        = 'text/plain';
A 494                 $c->realtype        = 'text/html';
d311d8 495
A 496                 $this->parts[] = $c;
497             }
498         }
499         // this is an ecrypted message -> create a plaintext body with the according message
500         else if ($mimetype == 'multipart/encrypted') {
501             $p = new stdClass;
502             $p->type            = 'content';
503             $p->ctype_primary   = 'text';
504             $p->ctype_secondary = 'plain';
0c2596 505             $p->mimetype        = 'text/plain';
A 506             $p->realtype        = 'multipart/encrypted';
c054ec 507
A 508             $this->parts[] = $p;
d311d8 509         }
ee89c6 510         // this is an S/MIME ecrypted message -> create a plaintext body with the according message
AM 511         else if ($mimetype == 'application/pkcs7-mime') {
512             $p = new stdClass;
513             $p->type            = 'content';
514             $p->ctype_primary   = 'text';
515             $p->ctype_secondary = 'plain';
516             $p->mimetype        = 'text/plain';
517             $p->realtype        = 'application/pkcs7-mime';
518
519             $this->parts[] = $p;
520         }
d311d8 521         // message contains multiple parts
A 522         else if (is_array($structure->parts) && !empty($structure->parts)) {
523             // iterate over parts
524             for ($i=0; $i < count($structure->parts); $i++) {
525                 $mail_part      = &$structure->parts[$i];
526                 $primary_type   = $mail_part->ctype_primary;
527                 $secondary_type = $mail_part->ctype_secondary;
5579ef 528                 $part_mimetype  = $mail_part->mimetype;
8fa58e 529
5579ef 530                 // multipart/alternative or message/rfc822
AM 531                 if ($primary_type == 'multipart' || $part_mimetype == 'message/rfc822') {
d311d8 532                     $this->parse_structure($mail_part, true);
A 533
534                     // list message/rfc822 as attachment as well (mostly .eml)
5579ef 535                     if ($primary_type == 'message' && !empty($mail_part->filename)) {
d311d8 536                         $this->attachments[] = $mail_part;
5579ef 537                     }
d311d8 538                 }
f22ea7 539                 // part text/[plain|html] or delivery status
d311d8 540                 else if ((($part_mimetype == 'text/plain' || $part_mimetype == 'text/html') && $mail_part->disposition != 'attachment') ||
f22ea7 541                     in_array($part_mimetype, array('message/delivery-status', 'text/rfc822-headers', 'message/disposition-notification'))
d311d8 542                 ) {
1a2f83 543                     // Allow plugins to handle also this part
A 544                     $plugin = $this->app->plugins->exec_hook('message_part_structure',
545                         array('object' => $this, 'structure' => $mail_part,
546                             'mimetype' => $part_mimetype, 'recursive' => true));
547
5579ef 548                     if ($plugin['abort']) {
1a2f83 549                         continue;
5579ef 550                     }
1a2f83 551
9c299e 552                     if ($part_mimetype == 'text/html' && $mail_part->size) {
63f9de 553                         $got_html_part = true;
A 554                     }
555
1a2f83 556                     $mail_part = $plugin['structure'];
A 557                     list($primary_type, $secondary_type) = explode('/', $plugin['mimetype']);
558
d311d8 559                     // add text part if it matches the prefs
A 560                     if (!$this->parse_alternative ||
561                         ($secondary_type == 'html' && $this->opt['prefer_html']) ||
562                         ($secondary_type == 'plain' && !$this->opt['prefer_html'])
563                     ) {
564                         $mail_part->type = 'content';
565                         $this->parts[] = $mail_part;
566                     }
fd371a 567
d311d8 568                     // list as attachment as well
f7c11e 569                     if (!empty($mail_part->filename)) {
AM 570                         $this->attachments[] = $mail_part;
571                     }
d311d8 572                 }
A 573                 // ignore "virtual" protocol parts
574                 else if ($primary_type == 'protocol') {
575                     continue;
576                 }
577                 // part is Microsoft Outlook TNEF (winmail.dat)
578                 else if ($part_mimetype == 'application/ms-tnef') {
579                     foreach ((array)$this->tnef_decode($mail_part) as $tpart) {
580                         $this->mime_parts[$tpart->mime_id] = $tpart;
581                         $this->attachments[] = $tpart;
582                     }
583                 }
584                 // part is a file/attachment
585                 else if (preg_match('/^(inline|attach)/', $mail_part->disposition) ||
8794f1 586                     $mail_part->headers['content-id'] ||
A 587                     ($mail_part->filename &&
588                         (empty($mail_part->disposition) || preg_match('/^[a-z0-9!#$&.+^_-]+$/i', $mail_part->disposition)))
d311d8 589                 ) {
A 590                     // skip apple resource forks
591                     if ($message_ctype_secondary == 'appledouble' && $secondary_type == 'applefile')
592                         continue;
593
594                     // part belongs to a related message and is linked
cb0f03 595                     if (preg_match('/^multipart\/(related|relative)/', $mimetype)
5579ef 596                         && ($mail_part->headers['content-id'] || $mail_part->headers['content-location'])
AM 597                     ) {
d311d8 598                         if ($mail_part->headers['content-id'])
A 599                             $mail_part->content_id = preg_replace(array('/^</', '/>$/'), '', $mail_part->headers['content-id']);
600                         if ($mail_part->headers['content-location'])
601                             $mail_part->content_location = $mail_part->headers['content-base'] . $mail_part->headers['content-location'];
602
603                         $this->inline_parts[] = $mail_part;
604                     }
b38925 605                     // regular attachment with valid content type
A 606                     // (content-type name regexp according to RFC4288.4.2)
2ae58f 607                     else if (preg_match('/^[a-z0-9!#$&.+^_-]+\/[a-z0-9!#$&.+^_-]+$/i', $part_mimetype)) {
b38925 608                         $this->attachments[] = $mail_part;
A 609                     }
610                     // attachment with invalid content type
611                     // replace malformed content type with application/octet-stream (#1487767)
612                     else if ($mail_part->filename) {
613                         $mail_part->ctype_primary   = 'application';
614                         $mail_part->ctype_secondary = 'octet-stream';
615                         $mail_part->mimetype        = 'application/octet-stream';
616
d311d8 617                         $this->attachments[] = $mail_part;
A 618                     }
619                 }
5579ef 620                 // calendar part not marked as attachment (#1490325)
AM 621                 else if ($part_mimetype == 'text/calendar') {
622                     if (!$mail_part->filename) {
623                         $mail_part->filename = 'calendar.ics';
624                     }
625
626                     $this->attachments[] = $mail_part;
8757f5 627                 }
d311d8 628             }
A 629
630             // if this was a related part try to resolve references
cb0f03 631             if (preg_match('/^multipart\/(related|relative)/', $mimetype) && sizeof($this->inline_parts)) {
d311d8 632                 $a_replaces = array();
89d19c 633                 $img_regexp = '/^image\/(gif|jpe?g|png|tiff|bmp|svg)/';
d311d8 634
A 635                 foreach ($this->inline_parts as $inline_object) {
a021d6 636                     $part_url = $this->get_part_url($inline_object->mime_id, $inline_object->ctype_primary);
8cfba1 637                     if (isset($inline_object->content_id))
d311d8 638                         $a_replaces['cid:'.$inline_object->content_id] = $part_url;
63f9de 639                     if ($inline_object->content_location) {
d311d8 640                         $a_replaces[$inline_object->content_location] = $part_url;
63f9de 641                     }
89d19c 642
A 643                     if (!empty($inline_object->filename)) {
644                         // MS Outlook sends sometimes non-related attachments as related
645                         // In this case multipart/related message has only one text part
646                         // We'll add all such attachments to the attachments list
647                         if (!isset($got_html_part) && empty($inline_object->content_id)) {
648                             $this->attachments[] = $inline_object;
649                         }
650                         // MS Outlook sometimes also adds non-image attachments as related
651                         // We'll add all such attachments to the attachments list
652                         // Warning: some browsers support pdf in <img/>
653                         else if (!preg_match($img_regexp, $inline_object->mimetype)) {
654                             $this->attachments[] = $inline_object;
655                         }
656                         // @TODO: we should fetch HTML body and find attachment's content-id
657                         // to handle also image attachments without reference in the body
658                         // @TODO: should we list all image attachments in text mode?
02b6e6 659                     }
d311d8 660                 }
A 661
662                 // add replace array to each content part
663                 // (will be applied later when part body is available)
664                 foreach ($this->parts as $i => $part) {
665                     if ($part->type == 'content')
666                         $this->parts[$i]->replaces = $a_replaces;
667                 }
668             }
669         }
670         // message is a single part non-text
671         else if ($structure->filename) {
672             $this->attachments[] = $structure;
673         }
3e58bf 674         // message is a single part non-text (without filename)
A 675         else if (preg_match('/application\//i', $mimetype)) {
676             $this->attachments[] = $structure;
c5d7c9 677         }
AM 678     }
679
680
681     /**
d311d8 682      * Fill aflat array with references to all parts, indexed by part numbers
A 683      *
5c461b 684      * @param rcube_message_part $part Message body structure
d311d8 685      */
A 686     private function get_mime_numbers(&$part)
687     {
688         if (strlen($part->mime_id))
689             $this->mime_parts[$part->mime_id] = &$part;
f19d86 690
d311d8 691         if (is_array($part->parts))
A 692             for ($i=0; $i<count($part->parts); $i++)
693                 $this->get_mime_numbers($part->parts[$i]);
694     }
695
696
697     /**
698      * Decode a Microsoft Outlook TNEF part (winmail.dat)
699      *
5c461b 700      * @param rcube_message_part $part Message part to decode
A 701      * @return array
d311d8 702      */
A 703     function tnef_decode(&$part)
704     {
705         // @TODO: attachment may be huge, hadle it via file
10562d 706         if (!isset($part->body)) {
AM 707             $this->storage->set_folder($this->folder);
c321a9 708             $part->body = $this->storage->get_message_part($this->uid, $part->mime_id, $part);
10562d 709         }
d311d8 710
A 711         $parts = array();
f19d86 712         $tnef = new tnef_decoder;
A 713         $tnef_arr = $tnef->decompress($part->body);
d311d8 714
A 715         foreach ($tnef_arr as $pid => $winatt) {
716             $tpart = new rcube_message_part;
717
718             $tpart->filename        = trim($winatt['name']);
719             $tpart->encoding        = 'stream';
f19d86 720             $tpart->ctype_primary   = trim(strtolower($winatt['type']));
A 721             $tpart->ctype_secondary = trim(strtolower($winatt['subtype']));
d311d8 722             $tpart->mimetype        = $tpart->ctype_primary . '/' . $tpart->ctype_secondary;
A 723             $tpart->mime_id         = 'winmail.' . $part->mime_id . '.' . $pid;
724             $tpart->size            = $winatt['size'];
725             $tpart->body            = $winatt['stream'];
726
727             $parts[] = $tpart;
728             unset($tnef_arr[$pid]);
729         }
f19d86 730
d311d8 731         return $parts;
A 732     }
733
734
735     /**
736      * Parse message body for UUencoded attachments bodies
737      *
5c461b 738      * @param rcube_message_part $part Message part to decode
A 739      * @return array
d311d8 740      */
A 741     function uu_decode(&$part)
742     {
743         // @TODO: messages may be huge, hadle body via file
10562d 744         if (!isset($part->body)) {
AM 745             $this->storage->set_folder($this->folder);
c321a9 746             $part->body = $this->storage->get_message_part($this->uid, $part->mime_id, $part);
10562d 747         }
d311d8 748
A 749         $parts = array();
242d3c 750         
C 751         // uuencode regexp
752         $uu_regexp = '/^(begin [0-7]{3,4} ([^\n]+)\n)(([\x21-\x60]{0,65}\n){0,2})([\x21-\x60]{0,65}|`\nend)\s*\n/sm';
d311d8 753
A 754         if (preg_match_all($uu_regexp, $part->body, $matches, PREG_SET_ORDER)) {
14f22f 755             $uu_endstring = "`\nend\n";
d311d8 756
A 757             // add attachments to the structure
758             foreach ($matches as $pid => $att) {
242d3c 759                 // make sure we're looking at a uuencoded file, and not a false positive
C 760                 $uu_lines = explode("\n", $att[3]);
761                 foreach ($uu_lines as $uu_line) {
762                     if ( strlen($uu_line) == 0 ) {
763                         continue;
764                     }
765                     $line_len = (ord(substr($uu_line, 0, 1)) - 32) & 0x3F;
766                     $max_code_len = floor( ($line_len+2)/3 ) * 4;
767                     $min_code_len = ceil( $line_len/3 * 4);
768                     if ( strlen($uu_line)-1 < $min_code_len
769                          or strlen($uu_line)-1 > $max_code_len )
770                     {
771                         // illegal uuencode, break out of 'foreach $matches' loop
772                         break 2;
773                     }
774                 }
775
776                 $startpos = strpos($part->body, $att[0]) + strlen($att[1]);
793642 777                 $endpos   = strpos($part->body, $uu_endstring);
14f22f 778                 $filebody = substr($part->body, $startpos, $endpos-$startpos);
GB 779
780                 // remove attachments bodies from the message body
242d3c 781                 $uu_startpos = $startpos - strlen($att[1]);
C 782                 $part->body = substr_replace($part->body, "", $uu_startpos, $endpos+strlen($uu_endstring)-$uu_startpos);
783                 
d311d8 784                 $uupart = new rcube_message_part;
A 785
242d3c 786                 $uupart->filename = trim($att[2]);
d311d8 787                 $uupart->encoding = 'stream';
14f22f 788                 $uupart->body     = convert_uudecode($filebody);
d311d8 789                 $uupart->size     = strlen($uupart->body);
A 790                 $uupart->mime_id  = 'uu.' . $part->mime_id . '.' . $pid;
791
bbd636 792                 $ctype = rcube_mime::file_content_type($uupart->body, $uupart->filename, 'application/octet-stream', true);
d311d8 793                 $uupart->mimetype = $ctype;
A 794                 list($uupart->ctype_primary, $uupart->ctype_secondary) = explode('/', $ctype);
795
796                 $parts[] = $uupart;
797                 unset($matches[$pid]);
798             }
14f22f 799
793642 800             // mark body as modified so it will not be cached by rcube_imap_cache
AM 801             $part->body_modified = true;
d311d8 802         }
f19d86 803
d311d8 804         return $parts;
A 805     }
b91f04 806
T 807
808     /**
809      * Deprecated methods (to be removed)
810      */
811
812     public static function unfold_flowed($text)
813     {
814         return rcube_mime::unfold_flowed($text);
815     }
816
817     public static function format_flowed($text, $length = 72)
818     {
819         return rcube_mime::format_flowed($text, $length);
820     }
821
8fa58e 822 }