]> git.donarmstrong.com Git - roundcube.git/blob - program/include/rcube_message.php
667657b5e9d925b15bb7778837f3854f6c26276e
[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 5261 2011-09-21 12:22:40Z 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 $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;
58
59
60     /**
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)
74     {
75         $this->app = rcmail::get_instance();
76         $this->imap = $this->app->imap;
77         $this->imap->get_all_headers = true;
78
79         $this->uid = $uid;
80         $this->headers = $this->imap->get_headers($uid, NULL, true, true);
81
82         if (!$this->headers)
83             return;
84
85         $this->subject = rcube_imap::decode_mime_string(
86             $this->headers->subject, $this->headers->charset);
87         list(, $this->sender) = each($this->imap->decode_address_list($this->headers->from));
88
89         $this->set_safe((intval($_GET['_safe']) || $_SESSION['safe_messages'][$uid]));
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         );
96
97         if ($this->structure = $this->imap->get_structure($uid, $this->headers->body_structure)) {
98             $this->get_mime_numbers($this->structure);
99             $this->parse_structure($this->structure);
100         }
101         else {
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     }
108
109
110     /**
111      * Return a (decoded) message header
112      *
113      * @param string $name Header name
114      * @param bool   $row  Don't mime-decode the value
115      * @return string Header value
116      */
117     public function get_header($name, $raw = false)
118     {
119         if ($this->headers->$name)
120             $value = $this->headers->$name;
121         else if ($this->headers->others[$name])
122             $value = $this->headers->others[$name];
123
124         return $raw ? $value : $this->imap->decode_header($value);
125     }
126
127
128     /**
129      * Set is_safe var and session data
130      *
131      * @param bool $safe enable/disable
132      */
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      *
143      * @param string $mime_id Part MIME-ID
144      * @return string URL or false if part does not exist
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;
150         else
151             return false;
152     }
153
154
155     /**
156      * Get content of a specific part of this message
157      *
158      * @param string $mime_id Part MIME-ID
159      * @param resource $fp File pointer to save the message part
160      * @return string Part content
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;
176     }
177
178
179     /**
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      *
217      * @param rcube_message_part $part Reference to the part if found
218      * @return string Plain text message/part content
219      */
220     function first_text_part(&$part=null)
221     {
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') {
231                 return $this->imap->get_message_part($this->uid, $mime_id, $part);
232             }
233             else if ($mimetype == 'text/html') {
234                 $out = $this->imap->get_message_part($this->uid, $mime_id, $part);
235
236                 // remove special chars encoding
237                 $trans = array_flip(get_html_translation_table(HTML_ENTITIES));
238                 $out = strtr($out, $trans);
239
240                 // create instance of html2text class
241                 $txt = new html2text($out);
242                 return $txt->get_text();
243             }
244         }
245
246         $part = null;
247         return null;
248     }
249
250
251     /**
252      * Raad the message structure returend by the IMAP server
253      * and build flat lists of content parts and attachments
254      *
255      * @param rcube_message_part $structure Message structure node
256      * @param bool               $recursive True when called recursively
257      */
258     private function parse_structure($structure, $recursive = false)
259     {
260         // real content-type of message/rfc822 part
261         if ($structure->mimetype == 'message/rfc822' && $structure->real_mimetype)
262             $mimetype = $structure->real_mimetype;
263         else
264             $mimetype = $structure->mimetype;
265
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         }
273
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']);
284
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;
289
290             // Parse simple (plain text) message body
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;
309
310                 // check if sub part is
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;
326
327                 // if plain part was found, we should unset it if html is preferred
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             $this->parts[] = $p;
378         }
379         // message contains multiple parts
380         else if (is_array($structure->parts) && !empty($structure->parts)) {
381             // iterate over parts
382             for ($i=0; $i < count($structure->parts); $i++) {
383                 $mail_part      = &$structure->parts[$i];
384                 $primary_type   = $mail_part->ctype_primary;
385                 $secondary_type = $mail_part->ctype_secondary;
386
387                 // real content-type of message/rfc822
388                 if ($mail_part->real_mimetype) {
389                     $part_orig_mimetype = $mail_part->mimetype;
390                     $part_mimetype = $mail_part->real_mimetype;
391                     list($primary_type, $secondary_type) = explode('/', $part_mimetype);
392                 }
393                 else
394                     $part_mimetype = $mail_part->mimetype;
395
396                 // multipart/alternative
397                 if ($primary_type == 'multipart') {
398                     $this->parse_structure($mail_part, true);
399
400                     // list message/rfc822 as attachment as well (mostly .eml)
401                     if ($part_orig_mimetype == 'message/rfc822' && !empty($mail_part->filename))
402                         $this->attachments[] = $mail_part;
403                 }
404                 // part text/[plain|html] or delivery status
405                 else if ((($part_mimetype == 'text/plain' || $part_mimetype == 'text/html') && $mail_part->disposition != 'attachment') ||
406                     in_array($part_mimetype, array('message/delivery-status', 'text/rfc822-headers', 'message/disposition-notification'))
407                 ) {
408                     // Allow plugins to handle also this part
409                     $plugin = $this->app->plugins->exec_hook('message_part_structure',
410                         array('object' => $this, 'structure' => $mail_part,
411                             'mimetype' => $part_mimetype, 'recursive' => true));
412
413                     if ($plugin['abort'])
414                         continue;
415
416                     if ($part_mimetype == 'text/html') {
417                         $got_html_part = true;
418                     }
419
420                     $mail_part = $plugin['structure'];
421                     list($primary_type, $secondary_type) = explode('/', $plugin['mimetype']);
422
423                     // add text part if it matches the prefs
424                     if (!$this->parse_alternative ||
425                         ($secondary_type == 'html' && $this->opt['prefer_html']) ||
426                         ($secondary_type == 'plain' && !$this->opt['prefer_html'])
427                     ) {
428                         $mail_part->type = 'content';
429                         $this->parts[] = $mail_part;
430                     }
431
432                     // list as attachment as well
433                     if (!empty($mail_part->filename))
434                         $this->attachments[] = $mail_part;
435                 }
436                 // part message/*
437                 else if ($primary_type == 'message') {
438                     $this->parse_structure($mail_part, true);
439
440                     // list as attachment as well (mostly .eml)
441                     if (!empty($mail_part->filename))
442                         $this->attachments[] = $mail_part;
443                 }
444                 // ignore "virtual" protocol parts
445                 else if ($primary_type == 'protocol') {
446                     continue;
447                 }
448                 // part is Microsoft Outlook TNEF (winmail.dat)
449                 else if ($part_mimetype == 'application/ms-tnef') {
450                     foreach ((array)$this->tnef_decode($mail_part) as $tpart) {
451                         $this->mime_parts[$tpart->mime_id] = $tpart;
452                         $this->attachments[] = $tpart;
453                     }
454                 }
455                 // part is a file/attachment
456                 else if (preg_match('/^(inline|attach)/', $mail_part->disposition) ||
457                     $mail_part->headers['content-id'] ||
458                     ($mail_part->filename &&
459                         (empty($mail_part->disposition) || preg_match('/^[a-z0-9!#$&.+^_-]+$/i', $mail_part->disposition)))
460                 ) {
461                     // skip apple resource forks
462                     if ($message_ctype_secondary == 'appledouble' && $secondary_type == 'applefile')
463                         continue;
464
465                     // part belongs to a related message and is linked
466                     if ($mimetype == 'multipart/related'
467                         && ($mail_part->headers['content-id'] || $mail_part->headers['content-location'])) {
468                         if ($mail_part->headers['content-id'])
469                             $mail_part->content_id = preg_replace(array('/^</', '/>$/'), '', $mail_part->headers['content-id']);
470                         if ($mail_part->headers['content-location'])
471                             $mail_part->content_location = $mail_part->headers['content-base'] . $mail_part->headers['content-location'];
472
473                         $this->inline_parts[] = $mail_part;
474                     }
475                     // attachment encapsulated within message/rfc822 part needs further decoding (#1486743)
476                     else if ($part_orig_mimetype == 'message/rfc822') {
477                         $this->parse_structure($mail_part, true);
478
479                         // list as attachment as well (mostly .eml)
480                         if (!empty($mail_part->filename))
481                             $this->attachments[] = $mail_part;
482                     }
483                     // regular attachment with valid content type
484                     // (content-type name regexp according to RFC4288.4.2)
485                     else if (preg_match('/^[a-z0-9!#$&.+^_-]+\/[a-z0-9!#$&.+^_-]+$/i', $part_mimetype)) {
486                         if (!$mail_part->filename)
487                             $mail_part->filename = 'Part '.$mail_part->mime_id;
488
489                         $this->attachments[] = $mail_part;
490                     }
491                     // attachment with invalid content type
492                     // replace malformed content type with application/octet-stream (#1487767)
493                     else if ($mail_part->filename) {
494                         $mail_part->ctype_primary   = 'application';
495                         $mail_part->ctype_secondary = 'octet-stream';
496                         $mail_part->mimetype        = 'application/octet-stream';
497
498                         $this->attachments[] = $mail_part;
499                     }
500                 }
501                 // attachment part as message/rfc822 (#1488026)
502                 else if ($mail_part->mimetype == 'message/rfc822') {
503                     $this->parse_structure($mail_part);
504                 }
505             }
506
507             // if this was a related part try to resolve references
508             if ($mimetype == 'multipart/related' && sizeof($this->inline_parts)) {
509                 $a_replaces = array();
510                 $img_regexp = '/^image\/(gif|jpe?g|png|tiff|bmp|svg)/';
511
512                 foreach ($this->inline_parts as $inline_object) {
513                     $part_url = $this->get_part_url($inline_object->mime_id);
514                     if ($inline_object->content_id)
515                         $a_replaces['cid:'.$inline_object->content_id] = $part_url;
516                     if ($inline_object->content_location) {
517                         $a_replaces[$inline_object->content_location] = $part_url;
518                     }
519
520                     if (!empty($inline_object->filename)) {
521                         // MS Outlook sends sometimes non-related attachments as related
522                         // In this case multipart/related message has only one text part
523                         // We'll add all such attachments to the attachments list
524                         if (!isset($got_html_part) && empty($inline_object->content_id)) {
525                             $this->attachments[] = $inline_object;
526                         }
527                         // MS Outlook sometimes also adds non-image attachments as related
528                         // We'll add all such attachments to the attachments list
529                         // Warning: some browsers support pdf in <img/>
530                         else if (!preg_match($img_regexp, $inline_object->mimetype)) {
531                             $this->attachments[] = $inline_object;
532                         }
533                         // @TODO: we should fetch HTML body and find attachment's content-id
534                         // to handle also image attachments without reference in the body
535                         // @TODO: should we list all image attachments in text mode?
536                     }
537                 }
538
539                 // add replace array to each content part
540                 // (will be applied later when part body is available)
541                 foreach ($this->parts as $i => $part) {
542                     if ($part->type == 'content')
543                         $this->parts[$i]->replaces = $a_replaces;
544                 }
545             }
546         }
547         // message is a single part non-text
548         else if ($structure->filename) {
549             $this->attachments[] = $structure;
550         }
551         // message is a single part non-text (without filename)
552         else if (preg_match('/application\//i', $mimetype)) {
553             $structure->filename = 'Part '.$structure->mime_id;
554             $this->attachments[] = $structure;
555         }
556     }
557
558
559     /**
560      * Fill aflat array with references to all parts, indexed by part numbers
561      *
562      * @param rcube_message_part $part Message body structure
563      */
564     private function get_mime_numbers(&$part)
565     {
566         if (strlen($part->mime_id))
567             $this->mime_parts[$part->mime_id] = &$part;
568
569         if (is_array($part->parts))
570             for ($i=0; $i<count($part->parts); $i++)
571                 $this->get_mime_numbers($part->parts[$i]);
572     }
573
574
575     /**
576      * Decode a Microsoft Outlook TNEF part (winmail.dat)
577      *
578      * @param rcube_message_part $part Message part to decode
579      * @return array
580      */
581     function tnef_decode(&$part)
582     {
583         // @TODO: attachment may be huge, hadle it via file
584         if (!isset($part->body))
585             $part->body = $this->imap->get_message_part($this->uid, $part->mime_id, $part);
586
587         $parts = array();
588         $tnef = new tnef_decoder;
589         $tnef_arr = $tnef->decompress($part->body);
590
591         foreach ($tnef_arr as $pid => $winatt) {
592             $tpart = new rcube_message_part;
593
594             $tpart->filename        = trim($winatt['name']);
595             $tpart->encoding        = 'stream';
596             $tpart->ctype_primary   = trim(strtolower($winatt['type']));
597             $tpart->ctype_secondary = trim(strtolower($winatt['subtype']));
598             $tpart->mimetype        = $tpart->ctype_primary . '/' . $tpart->ctype_secondary;
599             $tpart->mime_id         = 'winmail.' . $part->mime_id . '.' . $pid;
600             $tpart->size            = $winatt['size'];
601             $tpart->body            = $winatt['stream'];
602
603             $parts[] = $tpart;
604             unset($tnef_arr[$pid]);
605         }
606
607         return $parts;
608     }
609
610
611     /**
612      * Parse message body for UUencoded attachments bodies
613      *
614      * @param rcube_message_part $part Message part to decode
615      * @return array
616      */
617     function uu_decode(&$part)
618     {
619         // @TODO: messages may be huge, hadle body via file
620         if (!isset($part->body))
621             $part->body = $this->imap->get_message_part($this->uid, $part->mime_id, $part);
622
623         $parts = array();
624         // FIXME: line length is max.65?
625         $uu_regexp = '/begin [0-7]{3,4} ([^\n]+)\n(([\x21-\x7E]{0,65}\n)+)`\nend/s';
626
627         if (preg_match_all($uu_regexp, $part->body, $matches, PREG_SET_ORDER)) {
628             // remove attachments bodies from the message body
629             $part->body = preg_replace($uu_regexp, '', $part->body);
630             // update message content-type
631             $part->ctype_primary   = 'multipart';
632             $part->ctype_secondary = 'mixed';
633             $part->mimetype        = $part->ctype_primary . '/' . $part->ctype_secondary;
634
635             // add attachments to the structure
636             foreach ($matches as $pid => $att) {
637                 $uupart = new rcube_message_part;
638
639                 $uupart->filename = trim($att[1]);
640                 $uupart->encoding = 'stream';
641                 $uupart->body     = convert_uudecode($att[2]);
642                 $uupart->size     = strlen($uupart->body);
643                 $uupart->mime_id  = 'uu.' . $part->mime_id . '.' . $pid;
644
645                 $ctype = rc_mime_content_type($uupart->body, $uupart->filename, 'application/octet-stream', true);
646                 $uupart->mimetype = $ctype;
647                 list($uupart->ctype_primary, $uupart->ctype_secondary) = explode('/', $ctype);
648
649                 $parts[] = $uupart;
650                 unset($matches[$pid]);
651             }
652         }
653
654         return $parts;
655     }
656
657
658     /**
659      * Interpret a format=flowed message body according to RFC 2646
660      *
661      * @param string  $text Raw body formatted as flowed text
662      * @return string Interpreted text with unwrapped lines and stuffed space removed
663      */
664     public static function unfold_flowed($text)
665     {
666         $text = preg_split('/\r?\n/', $text);
667         $last = -1;
668         $q_level = 0;
669
670         foreach ($text as $idx => $line) {
671             if ($line[0] == '>' && preg_match('/^(>+\s*)/', $line, $regs)) {
672                 $q = strlen(str_replace(' ', '', $regs[0]));
673                 $line = substr($line, strlen($regs[0]));
674
675                 if ($q == $q_level && $line
676                     && isset($text[$last])
677                     && $text[$last][strlen($text[$last])-1] == ' '
678                 ) {
679                     $text[$last] .= $line;
680                     unset($text[$idx]);
681                 }
682                 else {
683                     $last = $idx;
684                 }
685             }
686             else {
687                 $q = 0;
688                 if ($line == '-- ') {
689                     $last = $idx;
690                 }
691                 else {
692                     // remove space-stuffing
693                     $line = preg_replace('/^\s/', '', $line);
694
695                     if (isset($text[$last]) && $line
696                         && $text[$last] != '-- '
697                         && $text[$last][strlen($text[$last])-1] == ' '
698                     ) {
699                         $text[$last] .= $line;
700                         unset($text[$idx]);
701                     }
702                     else {
703                         $text[$idx] = $line;
704                         $last = $idx;
705                     }
706                 }
707             }
708             $q_level = $q;
709         }
710
711         return implode("\r\n", $text);
712     }
713
714
715     /**
716      * Wrap the given text to comply with RFC 2646
717      *
718      * @param string $text Text to wrap
719      * @param int $length Length
720      * @return string Wrapped text
721      */
722     public static function format_flowed($text, $length = 72)
723     {
724         $text = preg_split('/\r?\n/', $text);
725
726         foreach ($text as $idx => $line) {
727             if ($line != '-- ') {
728                 if ($line[0] == '>' && preg_match('/^(>+)/', $line, $regs)) {
729                     $prefix = $regs[0];
730                     $level = strlen($prefix);
731                     $line  = rtrim(substr($line, $level));
732                     $line  = $prefix . rc_wordwrap($line, $length - $level - 2, " \r\n$prefix ");
733                 }
734                 else if ($line) {
735                     $line = rc_wordwrap(rtrim($line), $length - 2, " \r\n");
736                     // space-stuffing
737                     $line = preg_replace('/(^|\r\n)(From| |>)/', '\\1 \\2', $line);
738                 }
739
740                 $text[$idx] = $line;
741             }
742         }
743
744         return implode("\r\n", $text);
745     }
746
747 }