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