alecpl
2011-09-07 80152b333ca5d856dcf09f5ca10a9ffd80ba117f
commit | author | age
8fa58e 1 <?php
T 2
3 /*
4  +-----------------------------------------------------------------------+
5  | program/include/rcube_message.php                                     |
6  |                                                                       |
e019f2 7  | This file is part of the Roundcube Webmail client                     |
f5e7b3 8  | Copyright (C) 2008-2010, The Roundcube Dev Team                       |
8fa58e 9  | Licensed under the GNU GPL                                            |
T 10  |                                                                       |
11  | PURPOSE:                                                              |
12  |   Logical representation of a mail message with all its data          |
13  |   and related functions                                               |
14  +-----------------------------------------------------------------------+
15  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
16  +-----------------------------------------------------------------------+
17
638fb8 18  $Id$
8fa58e 19
T 20 */
21
22
23 /**
45f56c 24  * Logical representation of a mail message with all its data
T 25  * and related functions
8fa58e 26  *
T 27  * @package    Mail
28  * @author     Thomas Bruederli <roundcube@gmail.com>
29  */
30 class rcube_message
31 {
5c461b 32     /**
A 33      * Instace of rcmail.
34      *
35      * @var rcmail
36      */
d311d8 37     private $app;
5c461b 38
A 39     /**
40      * Instance of imap class
41      *
42      * @var rcube_imap
43      */
d311d8 44     private $imap;
A 45     private $opt = array();
46     private $inline_parts = array();
47     private $parse_alternative = false;
2ae58f 48
d311d8 49     public $uid = null;
A 50     public $headers;
51     public $structure;
52     public $parts = array();
53     public $mime_parts = array();
54     public $attachments = array();
55     public $subject = '';
56     public $sender = null;
57     public $is_safe = false;
2ae58f 58
193fb4 59
d311d8 60     /**
A 61      * __construct
62      *
63      * Provide a uid, and parse message structure.
64      *
65      * @param string $uid The message UID.
66      *
67      * @uses rcmail::get_instance()
68      * @uses rcube_imap::decode_mime_string()
69      * @uses self::set_safe()
70      *
71      * @see self::$app, self::$imap, self::$opt, self::$structure
72      */
73     function __construct($uid)
8fa58e 74     {
d311d8 75         $this->app = rcmail::get_instance();
A 76         $this->imap = $this->app->imap;
103ddc 77         $this->imap->get_all_headers = true;
64e3e8 78
d311d8 79         $this->uid = $uid;
80152b 80         $this->headers = $this->imap->get_message($uid);
64e3e8 81
A 82         if (!$this->headers)
83             return;
8fa58e 84
d311d8 85         $this->subject = rcube_imap::decode_mime_string(
A 86             $this->headers->subject, $this->headers->charset);
87         list(, $this->sender) = each($this->imap->decode_address_list($this->headers->from));
64e3e8 88
d311d8 89         $this->set_safe((intval($_GET['_safe']) || $_SESSION['safe_messages'][$uid]));
A 90         $this->opt = array(
91             'safe' => $this->is_safe,
92             'prefer_html' => $this->app->config->get('prefer_html'),
93             'get_url' => rcmail_url('get', array(
94                 '_mbox' => $this->imap->get_mailbox_name(), '_uid' => $uid))
95         );
8fa58e 96
80152b 97         if (!empty($this->headers->structure)) {
A 98             $this->get_mime_numbers($this->headers->structure);
99             $this->parse_structure($this->headers->structure);
aa16b4 100         }
d311d8 101         else {
A 102             $this->body = $this->imap->get_body($uid);
103         }
104
105         // notify plugins and let them analyze this structured message object
106         $this->app->plugins->exec_hook('message_load', array('object' => $this));
107     }
2ae58f 108
A 109
d311d8 110     /**
A 111      * Return a (decoded) message header
112      *
5c461b 113      * @param string $name Header name
A 114      * @param bool   $row  Don't mime-decode the value
d311d8 115      * @return string Header value
A 116      */
117     public function get_header($name, $raw = false)
118     {
e25a35 119         if ($this->headers->$name)
A 120             $value = $this->headers->$name;
121         else if ($this->headers->others[$name])
122             $value = $this->headers->others[$name];
123
d311d8 124         return $raw ? $value : $this->imap->decode_header($value);
A 125     }
126
2ae58f 127
d311d8 128     /**
A 129      * Set is_safe var and session data
130      *
5c461b 131      * @param bool $safe enable/disable
d311d8 132      */
A 133     public function set_safe($safe = true)
134     {
135         $this->is_safe = $safe;
136         $_SESSION['safe_messages'][$this->uid] = $this->is_safe;
137     }
138
139
140     /**
141      * Compose a valid URL for getting a message part
142      *
5c461b 143      * @param string $mime_id Part MIME-ID
d311d8 144      * @return string URL or false if part does not exist
A 145      */
146     public function get_part_url($mime_id)
147     {
148         if ($this->mime_parts[$mime_id])
149             return $this->opt['get_url'] . '&_part=' . $mime_id;
aa16b4 150         else
d311d8 151             return false;
8fa58e 152     }
T 153
d311d8 154
A 155     /**
156      * Get content of a specific part of this message
157      *
5c461b 158      * @param string $mime_id Part MIME-ID
A 159      * @param resource $fp File pointer to save the message part
d311d8 160      * @return string Part content
A 161      */
162     public function get_part_content($mime_id, $fp=NULL)
163     {
164         if ($part = $this->mime_parts[$mime_id]) {
165             // stored in message structure (winmail/inline-uuencode)
166             if ($part->encoding == 'stream') {
167                 if ($fp) {
168                     fwrite($fp, $part->body);
169                 }
170                 return $fp ? true : $part->body;
171             }
172             // get from IMAP
173             return $this->imap->get_message_part($this->uid, $mime_id, $part, NULL, $fp);
174         } else
175             return null;
8fa58e 176     }
T 177
178
d311d8 179     /**
A 180      * Determine if the message contains a HTML part
181      *
182      * @return bool True if a HTML is available, False if not
183      */
184     function has_html_part()
185     {
186         // check all message parts
187         foreach ($this->parts as $pid => $part) {
188             $mimetype = strtolower($part->ctype_primary . '/' . $part->ctype_secondary);
189             if ($mimetype == 'text/html')
190                 return true;
191         }
192
193         return false;
194     }
195
196
197     /**
198      * Return the first HTML part of this message
199      *
200      * @return string HTML message part content
201      */
202     function first_html_part()
203     {
204         // check all message parts
205         foreach ($this->mime_parts as $mime_id => $part) {
206             $mimetype = strtolower($part->ctype_primary . '/' . $part->ctype_secondary);
207             if ($mimetype == 'text/html') {
208                 return $this->imap->get_message_part($this->uid, $mime_id, $part);
209             }
210         }
211     }
212
213
214     /**
215      * Return the first text part of this message
216      *
868deb 217      * @param rcube_message_part $part Reference to the part if found
d311d8 218      * @return string Plain text message/part content
A 219      */
868deb 220     function first_text_part(&$part=null)
d311d8 221     {
A 222         // no message structure, return complete body
223         if (empty($this->parts))
224             return $this->body;
225
226         // check all message parts
227         foreach ($this->mime_parts as $mime_id => $part) {
228             $mimetype = $part->ctype_primary . '/' . $part->ctype_secondary;
229
230             if ($mimetype == 'text/plain') {
868deb 231                 return $this->imap->get_message_part($this->uid, $mime_id, $part);
d311d8 232             }
A 233             else if ($mimetype == 'text/html') {
99b8c1 234                 $out = $this->imap->get_message_part($this->uid, $mime_id, $part);
d311d8 235
A 236                 // remove special chars encoding
237                 $trans = array_flip(get_html_translation_table(HTML_ENTITIES));
99b8c1 238                 $out = strtr($out, $trans);
d311d8 239
A 240                 // create instance of html2text class
99b8c1 241                 $txt = new html2text($out);
868deb 242                 return $txt->get_text();
d311d8 243             }
A 244         }
245
868deb 246         $part = null;
A 247         return null;
d311d8 248     }
A 249
250
251     /**
252      * Raad the message structure returend by the IMAP server
253      * and build flat lists of content parts and attachments
254      *
5c461b 255      * @param rcube_message_part $structure Message structure node
A 256      * @param bool               $recursive True when called recursively
d311d8 257      */
A 258     private function parse_structure($structure, $recursive = false)
259     {
260         // real content-type of message/rfc822 part
eef0da 261         if ($structure->mimetype == 'message/rfc822' && $structure->real_mimetype)
5ced9c 262             $mimetype = $structure->real_mimetype;
A 263         else
264             $mimetype = $structure->mimetype;
d311d8 265
A 266         // show message headers
267         if ($recursive && is_array($structure->headers) && isset($structure->headers['subject'])) {
268             $c = new stdClass;
269             $c->type = 'headers';
270             $c->headers = &$structure->headers;
271             $this->parts[] = $c;
272         }
5ced9c 273
A 274         // Allow plugins to handle message parts
275         $plugin = $this->app->plugins->exec_hook('message_part_structure',
276             array('object' => $this, 'structure' => $structure,
277                 'mimetype' => $mimetype, 'recursive' => $recursive));
278
279         if ($plugin['abort'])
280             return;
281
282         $structure = $plugin['structure'];
283         list($message_ctype_primary, $message_ctype_secondary) = explode('/', $plugin['mimetype']);
d311d8 284
A 285         // print body if message doesn't have multiple parts
286         if ($message_ctype_primary == 'text' && !$recursive) {
287             $structure->type = 'content';
288             $this->parts[] = &$structure;
8757f5 289
d311d8 290             // Parse simple (plain text) message body
A 291             if ($message_ctype_secondary == 'plain')
292                 foreach ((array)$this->uu_decode($structure) as $uupart) {
293                     $this->mime_parts[$uupart->mime_id] = $uupart;
294                     $this->attachments[] = $uupart;
295                 }
296         }
297         // the same for pgp signed messages
298         else if ($mimetype == 'application/pgp' && !$recursive) {
299             $structure->type = 'content';
300             $this->parts[] = &$structure;
301         }
302         // message contains alternative parts
303         else if ($mimetype == 'multipart/alternative' && is_array($structure->parts)) {
304             // get html/plaintext parts
305             $plain_part = $html_part = $print_part = $related_part = null;
306
307             foreach ($structure->parts as $p => $sub_part) {
308                 $sub_mimetype = $sub_part->mimetype;
8757f5 309
d311d8 310                 // check if sub part is
A 311                 if ($sub_mimetype == 'text/plain')
312                     $plain_part = $p;
313                 else if ($sub_mimetype == 'text/html')
314                     $html_part = $p;
315                 else if ($sub_mimetype == 'text/enriched')
316                     $enriched_part = $p;
317                 else if (in_array($sub_mimetype, array('multipart/related', 'multipart/mixed', 'multipart/alternative')))
318                     $related_part = $p;
319             }
320
321             // parse related part (alternative part could be in here)
322             if ($related_part !== null && !$this->parse_alternative) {
323                 $this->parse_alternative = true;
324                 $this->parse_structure($structure->parts[$related_part], true);
325                 $this->parse_alternative = false;
8757f5 326
d311d8 327                 // if plain part was found, we should unset it if html is preferred
A 328                 if ($this->opt['prefer_html'] && count($this->parts))
329                     $plain_part = null;
330             }
331
332             // choose html/plain part to print
333             if ($html_part !== null && $this->opt['prefer_html']) {
334                 $print_part = &$structure->parts[$html_part];
335             }
336             else if ($enriched_part !== null) {
337                 $print_part = &$structure->parts[$enriched_part];
338             }
339             else if ($plain_part !== null) {
340                 $print_part = &$structure->parts[$plain_part];
341             }
342
343             // add the right message body
344             if (is_object($print_part)) {
345                 $print_part->type = 'content';
346                 $this->parts[] = $print_part;
347             }
348             // show plaintext warning
349             else if ($html_part !== null && empty($this->parts)) {
350                 $c = new stdClass;
351                 $c->type            = 'content';
352                 $c->ctype_primary   = 'text';
353                 $c->ctype_secondary = 'plain';
354                 $c->body            = rcube_label('htmlmessage');
355
356                 $this->parts[] = $c;
357             }
358
359             // add html part as attachment
360             if ($html_part !== null && $structure->parts[$html_part] !== $print_part) {
361                 $html_part = &$structure->parts[$html_part];
362                 $html_part->filename = rcube_label('htmlmessage');
363                 $html_part->mimetype = 'text/html';
364
365                 $this->attachments[] = $html_part;
366             }
367         }
368         // this is an ecrypted message -> create a plaintext body with the according message
369         else if ($mimetype == 'multipart/encrypted') {
370             $p = new stdClass;
371             $p->type            = 'content';
372             $p->ctype_primary   = 'text';
373             $p->ctype_secondary = 'plain';
374             $p->body            = rcube_label('encryptedmessage');
375             $p->size            = strlen($p->body);
376         }
377         // message contains multiple parts
378         else if (is_array($structure->parts) && !empty($structure->parts)) {
379             // iterate over parts
380             for ($i=0; $i < count($structure->parts); $i++) {
381                 $mail_part      = &$structure->parts[$i];
382                 $primary_type   = $mail_part->ctype_primary;
383                 $secondary_type = $mail_part->ctype_secondary;
8fa58e 384
d311d8 385                 // real content-type of message/rfc822
A 386                 if ($mail_part->real_mimetype) {
387                     $part_orig_mimetype = $mail_part->mimetype;
388                     $part_mimetype = $mail_part->real_mimetype;
389                     list($primary_type, $secondary_type) = explode('/', $part_mimetype);
390                 }
391                 else
392                     $part_mimetype = $mail_part->mimetype;
6b6f2e 393
d311d8 394                 // multipart/alternative
A 395                 if ($primary_type == 'multipart') {
396                     $this->parse_structure($mail_part, true);
397
398                     // list message/rfc822 as attachment as well (mostly .eml)
399                     if ($part_orig_mimetype == 'message/rfc822' && !empty($mail_part->filename))
400                         $this->attachments[] = $mail_part;
401                 }
f22ea7 402                 // part text/[plain|html] or delivery status
d311d8 403                 else if ((($part_mimetype == 'text/plain' || $part_mimetype == 'text/html') && $mail_part->disposition != 'attachment') ||
f22ea7 404                     in_array($part_mimetype, array('message/delivery-status', 'text/rfc822-headers', 'message/disposition-notification'))
d311d8 405                 ) {
1a2f83 406                     // Allow plugins to handle also this part
A 407                     $plugin = $this->app->plugins->exec_hook('message_part_structure',
408                         array('object' => $this, 'structure' => $mail_part,
409                             'mimetype' => $part_mimetype, 'recursive' => true));
410
411                     if ($plugin['abort'])
412                         continue;
413
63f9de 414                     if ($part_mimetype == 'text/html') {
A 415                         $got_html_part = true;
416                     }
417
1a2f83 418                     $mail_part = $plugin['structure'];
A 419                     list($primary_type, $secondary_type) = explode('/', $plugin['mimetype']);
420
d311d8 421                     // add text part if it matches the prefs
A 422                     if (!$this->parse_alternative ||
423                         ($secondary_type == 'html' && $this->opt['prefer_html']) ||
424                         ($secondary_type == 'plain' && !$this->opt['prefer_html'])
425                     ) {
426                         $mail_part->type = 'content';
427                         $this->parts[] = $mail_part;
428                     }
fd371a 429
d311d8 430                     // list as attachment as well
A 431                     if (!empty($mail_part->filename))
432                         $this->attachments[] = $mail_part;
433                 }
434                 // part message/*
8757f5 435                 else if ($primary_type == 'message') {
d311d8 436                     $this->parse_structure($mail_part, true);
A 437
438                     // list as attachment as well (mostly .eml)
439                     if (!empty($mail_part->filename))
440                         $this->attachments[] = $mail_part;
441                 }
442                 // ignore "virtual" protocol parts
443                 else if ($primary_type == 'protocol') {
444                     continue;
445                 }
446                 // part is Microsoft Outlook TNEF (winmail.dat)
447                 else if ($part_mimetype == 'application/ms-tnef') {
448                     foreach ((array)$this->tnef_decode($mail_part) as $tpart) {
449                         $this->mime_parts[$tpart->mime_id] = $tpart;
450                         $this->attachments[] = $tpart;
451                     }
452                 }
453                 // part is a file/attachment
454                 else if (preg_match('/^(inline|attach)/', $mail_part->disposition) ||
8794f1 455                     $mail_part->headers['content-id'] ||
A 456                     ($mail_part->filename &&
457                         (empty($mail_part->disposition) || preg_match('/^[a-z0-9!#$&.+^_-]+$/i', $mail_part->disposition)))
d311d8 458                 ) {
A 459                     // skip apple resource forks
460                     if ($message_ctype_secondary == 'appledouble' && $secondary_type == 'applefile')
461                         continue;
462
463                     // part belongs to a related message and is linked
464                     if ($mimetype == 'multipart/related'
465                         && ($mail_part->headers['content-id'] || $mail_part->headers['content-location'])) {
466                         if ($mail_part->headers['content-id'])
467                             $mail_part->content_id = preg_replace(array('/^</', '/>$/'), '', $mail_part->headers['content-id']);
468                         if ($mail_part->headers['content-location'])
469                             $mail_part->content_location = $mail_part->headers['content-base'] . $mail_part->headers['content-location'];
470
471                         $this->inline_parts[] = $mail_part;
472                     }
473                     // attachment encapsulated within message/rfc822 part needs further decoding (#1486743)
474                     else if ($part_orig_mimetype == 'message/rfc822') {
475                         $this->parse_structure($mail_part, true);
fd371a 476
A 477                         // list as attachment as well (mostly .eml)
478                         if (!empty($mail_part->filename))
479                             $this->attachments[] = $mail_part;
d311d8 480                     }
b38925 481                     // regular attachment with valid content type
A 482                     // (content-type name regexp according to RFC4288.4.2)
2ae58f 483                     else if (preg_match('/^[a-z0-9!#$&.+^_-]+\/[a-z0-9!#$&.+^_-]+$/i', $part_mimetype)) {
d311d8 484                         if (!$mail_part->filename)
A 485                             $mail_part->filename = 'Part '.$mail_part->mime_id;
b38925 486
A 487                         $this->attachments[] = $mail_part;
488                     }
489                     // attachment with invalid content type
490                     // replace malformed content type with application/octet-stream (#1487767)
491                     else if ($mail_part->filename) {
492                         $mail_part->ctype_primary   = 'application';
493                         $mail_part->ctype_secondary = 'octet-stream';
494                         $mail_part->mimetype        = 'application/octet-stream';
495
d311d8 496                         $this->attachments[] = $mail_part;
A 497                     }
498                 }
8757f5 499                 // attachment part as message/rfc822 (#1488026)
A 500                 else if ($mail_part->mimetype == 'message/rfc822') {
501                     $this->parse_structure($mail_part);
502                 }
d311d8 503             }
A 504
505             // if this was a related part try to resolve references
506             if ($mimetype == 'multipart/related' && sizeof($this->inline_parts)) {
507                 $a_replaces = array();
89d19c 508                 $img_regexp = '/^image\/(gif|jpe?g|png|tiff|bmp|svg)/';
d311d8 509
A 510                 foreach ($this->inline_parts as $inline_object) {
511                     $part_url = $this->get_part_url($inline_object->mime_id);
512                     if ($inline_object->content_id)
513                         $a_replaces['cid:'.$inline_object->content_id] = $part_url;
63f9de 514                     if ($inline_object->content_location) {
d311d8 515                         $a_replaces[$inline_object->content_location] = $part_url;
63f9de 516                     }
89d19c 517
A 518                     if (!empty($inline_object->filename)) {
519                         // MS Outlook sends sometimes non-related attachments as related
520                         // In this case multipart/related message has only one text part
521                         // We'll add all such attachments to the attachments list
522                         if (!isset($got_html_part) && empty($inline_object->content_id)) {
523                             $this->attachments[] = $inline_object;
524                         }
525                         // MS Outlook sometimes also adds non-image attachments as related
526                         // We'll add all such attachments to the attachments list
527                         // Warning: some browsers support pdf in <img/>
528                         else if (!preg_match($img_regexp, $inline_object->mimetype)) {
529                             $this->attachments[] = $inline_object;
530                         }
531                         // @TODO: we should fetch HTML body and find attachment's content-id
532                         // to handle also image attachments without reference in the body
533                         // @TODO: should we list all image attachments in text mode?
02b6e6 534                     }
d311d8 535                 }
A 536
537                 // add replace array to each content part
538                 // (will be applied later when part body is available)
539                 foreach ($this->parts as $i => $part) {
540                     if ($part->type == 'content')
541                         $this->parts[$i]->replaces = $a_replaces;
542                 }
543             }
544         }
545         // message is a single part non-text
546         else if ($structure->filename) {
547             $this->attachments[] = $structure;
548         }
3e58bf 549         // message is a single part non-text (without filename)
A 550         else if (preg_match('/application\//i', $mimetype)) {
551             $structure->filename = 'Part '.$structure->mime_id;
552             $this->attachments[] = $structure;
553         }
6b6f2e 554     }
d311d8 555
A 556
557     /**
558      * Fill aflat array with references to all parts, indexed by part numbers
559      *
5c461b 560      * @param rcube_message_part $part Message body structure
d311d8 561      */
A 562     private function get_mime_numbers(&$part)
563     {
564         if (strlen($part->mime_id))
565             $this->mime_parts[$part->mime_id] = &$part;
f19d86 566
d311d8 567         if (is_array($part->parts))
A 568             for ($i=0; $i<count($part->parts); $i++)
569                 $this->get_mime_numbers($part->parts[$i]);
570     }
571
572
573     /**
574      * Decode a Microsoft Outlook TNEF part (winmail.dat)
575      *
5c461b 576      * @param rcube_message_part $part Message part to decode
A 577      * @return array
d311d8 578      */
A 579     function tnef_decode(&$part)
580     {
581         // @TODO: attachment may be huge, hadle it via file
582         if (!isset($part->body))
583             $part->body = $this->imap->get_message_part($this->uid, $part->mime_id, $part);
584
585         $parts = array();
f19d86 586         $tnef = new tnef_decoder;
A 587         $tnef_arr = $tnef->decompress($part->body);
d311d8 588
A 589         foreach ($tnef_arr as $pid => $winatt) {
590             $tpart = new rcube_message_part;
591
592             $tpart->filename        = trim($winatt['name']);
593             $tpart->encoding        = 'stream';
f19d86 594             $tpart->ctype_primary   = trim(strtolower($winatt['type']));
A 595             $tpart->ctype_secondary = trim(strtolower($winatt['subtype']));
d311d8 596             $tpart->mimetype        = $tpart->ctype_primary . '/' . $tpart->ctype_secondary;
A 597             $tpart->mime_id         = 'winmail.' . $part->mime_id . '.' . $pid;
598             $tpart->size            = $winatt['size'];
599             $tpart->body            = $winatt['stream'];
600
601             $parts[] = $tpart;
602             unset($tnef_arr[$pid]);
603         }
f19d86 604
d311d8 605         return $parts;
A 606     }
607
608
609     /**
610      * Parse message body for UUencoded attachments bodies
611      *
5c461b 612      * @param rcube_message_part $part Message part to decode
A 613      * @return array
d311d8 614      */
A 615     function uu_decode(&$part)
616     {
617         // @TODO: messages may be huge, hadle body via file
618         if (!isset($part->body))
619             $part->body = $this->imap->get_message_part($this->uid, $part->mime_id, $part);
620
621         $parts = array();
622         // FIXME: line length is max.65?
623         $uu_regexp = '/begin [0-7]{3,4} ([^\n]+)\n(([\x21-\x7E]{0,65}\n)+)`\nend/s';
624
625         if (preg_match_all($uu_regexp, $part->body, $matches, PREG_SET_ORDER)) {
626             // remove attachments bodies from the message body
627             $part->body = preg_replace($uu_regexp, '', $part->body);
628             // update message content-type
629             $part->ctype_primary   = 'multipart';
630             $part->ctype_secondary = 'mixed';
631             $part->mimetype        = $part->ctype_primary . '/' . $part->ctype_secondary;
632
633             // add attachments to the structure
634             foreach ($matches as $pid => $att) {
635                 $uupart = new rcube_message_part;
636
637                 $uupart->filename = trim($att[1]);
638                 $uupart->encoding = 'stream';
639                 $uupart->body     = convert_uudecode($att[2]);
640                 $uupart->size     = strlen($uupart->body);
641                 $uupart->mime_id  = 'uu.' . $part->mime_id . '.' . $pid;
642
643                 $ctype = rc_mime_content_type($uupart->body, $uupart->filename, 'application/octet-stream', true);
644                 $uupart->mimetype = $ctype;
645                 list($uupart->ctype_primary, $uupart->ctype_secondary) = explode('/', $ctype);
646
647                 $parts[] = $uupart;
648                 unset($matches[$pid]);
649             }
650         }
f19d86 651
d311d8 652         return $parts;
A 653     }
654
655
656     /**
657      * Interpret a format=flowed message body according to RFC 2646
658      *
5c461b 659      * @param string  $text Raw body formatted as flowed text
d311d8 660      * @return string Interpreted text with unwrapped lines and stuffed space removed
A 661      */
662     public static function unfold_flowed($text)
663     {
99b8c1 664         $text = preg_split('/\r?\n/', $text);
A 665         $last = -1;
666         $q_level = 0;
667
668         foreach ($text as $idx => $line) {
669             if ($line[0] == '>' && preg_match('/^(>+\s*)/', $line, $regs)) {
670                 $q = strlen(str_replace(' ', '', $regs[0]));
671                 $line = substr($line, strlen($regs[0]));
672
f12d21 673                 if ($q == $q_level && $line
A 674                     && isset($text[$last])
99b8c1 675                     && $text[$last][strlen($text[$last])-1] == ' '
A 676                 ) {
677                     $text[$last] .= $line;
678                     unset($text[$idx]);
679                 }
680                 else {
681                     $last = $idx;
682                 }
683             }
684             else {
685                 $q = 0;
686                 if ($line == '-- ') {
687                     $last = $idx;
688                 }
689                 else {
690                     // remove space-stuffing
691                     $line = preg_replace('/^\s/', '', $line);
692
f12d21 693                     if (isset($text[$last]) && $line
99b8c1 694                         && $text[$last] != '-- '
A 695                         && $text[$last][strlen($text[$last])-1] == ' '
696                     ) {
697                         $text[$last] .= $line;
698                         unset($text[$idx]);
699                     }
700                     else {
701                         $text[$idx] = $line;
702                         $last = $idx;
703                     }
704                 }
705             }
706             $q_level = $q;
707         }
708
709         return implode("\r\n", $text);
d311d8 710     }
A 711
712
713     /**
714      * Wrap the given text to comply with RFC 2646
5c461b 715      *
A 716      * @param string $text Text to wrap
717      * @param int $length Length
718      * @return string Wrapped text
d311d8 719      */
A 720     public static function format_flowed($text, $length = 72)
721     {
99b8c1 722         $text = preg_split('/\r?\n/', $text);
d311d8 723
99b8c1 724         foreach ($text as $idx => $line) {
A 725             if ($line != '-- ') {
726                 if ($line[0] == '>' && preg_match('/^(>+)/', $line, $regs)) {
727                     $prefix = $regs[0];
728                     $level = strlen($prefix);
729                     $line  = rtrim(substr($line, $level));
730                     $line  = $prefix . rc_wordwrap($line, $length - $level - 2, " \r\n$prefix ");
731                 }
6d1ae0 732                 else if ($line) {
dd0ae6 733                     $line = rc_wordwrap(rtrim($line), $length - 2, " \r\n");
A 734                     // space-stuffing
735                     $line = preg_replace('/(^|\r\n)(From| |>)/', '\\1 \\2', $line);
99b8c1 736                 }
A 737
738                 $text[$idx] = $line;
739             }
d311d8 740         }
99b8c1 741
A 742         return implode("\r\n", $text);
d311d8 743     }
6b6f2e 744
8fa58e 745 }