mhtxtplain.pl untested

filter: Statementstmt 0.0% 0 / 324 Branchbran 0.0% 0 / 156 Conditioncond 0.0% 0 / 39 MC/DCmcdc 0.0% 0 / 24 Subroutinesub 0.0% 0 / 16 Podpod 0.0% 0 / 10 totaltotal 0.0% 0 / 569 CC 79 SCAR 80.4
CC
79
Cov
0%
filter
4422.0
_break_line
72.0
break_lines
30.0
CRAP 3113.2
1 ##---------------------------------------------------------------------------##
2 ## File:
3 ## $Id: mhtxtplain.pl,v 2.48 2010/12/31 20:34:00 ehood Exp $
4 ## Author:
5 ## Earl Hood mhonarc@mhonarc.org
6 ## Description:
7 ## Library defines routine to filter text/plain body parts to HTML
8 ## for MHonArc.
9 ## Filter routine can be registered with the following:
10 ## <MIMEFILTERS>
11 ## text/plain:m2h_text_plain'filter:mhtxtplain.pl
12 ## </MIMEFILTERS>
13 ##---------------------------------------------------------------------------##
14 ## MHonArc -- Internet mail-to-HTML converter
15 ## Copyright (C) 1995-2005 Earl Hood, mhonarc@mhonarc.org
16 ##
17 ## This program is free software; you can redistribute it and/or modify
18 ## it under the terms of the GNU General Public License as published by
19 ## the Free Software Foundation; either version 2 of the License, or
20 ## (at your option) any later version.
21 ##
22 ## This program is distributed in the hope that it will be useful,
23 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
24 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 ## GNU General Public License for more details.
26 ##
27 ## You should have received a copy of the GNU General Public License
28 ## along with this program; if not, write to the Free Software
29 ## Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
30 ## 02111-1307, USA
31 ##---------------------------------------------------------------------------##
32  
33 package m2h_text_plain;
34  
35 require 'readmail.pl';
36  
37 sub Q_FIXED() { 0; }
38 sub Q_SIMPLE() { 1; }
39 sub Q_FANCY() { 2; }
40 sub Q_FLOWED() { 3; }
41  
42 $UrlExp =
43 $readmail::UrlRxStr
44 . q/[^\s\(\)\|<>"'\0-\037]+/
45 . q/[^\.?!;,"'\|\[\]\(\)\s<>\0-\037]/;
46 $HUrlExp =
47 $readmail::UrlRxStr
48 . q/(?:&(?![gl]t;)|[^\s\(\)\|<>"'\&\0-\037])+/
49 . q/[^\.?!;,"'\|\[\]\(\)\s<>\&\0-\037]/;
50 $QuoteChars = '[>]';
51 $HQuoteChars = '&gt;';
52  
53 $StartFlowedQuote =
54 '<blockquote style="border-left: #5555EE solid 0.2em; '
55 . 'margin: 0em; padding-left: 0.85em">';
56 $EndFlowedQuote = "</blockquote>";
57 $StartFixedQuote = '<pre style="margin: 0em;">';
58 $EndFixedQuote = '</pre>';
59  
60 ##---------------------------------------------------------------------------##
61 ## Text/plain filter for mhonarc. The following filter arguments
62 ## are recognized ($args):
63 ##
64 ## asis=set1:set2:...
65 ## Colon separated lists of charsets to leave as-is.
66 ## Only HTML special characters will be converted into
67 ## entities.
68 ##
69 ## attachcheck Honor attachment disposition. By default,
70 ## all text/plain data is displayed inline on
71 ## the message page. If attachcheck is specified
72 ## and Content-Disposition specifies the data as
73 ## an attachment, the data is saved to a file
74 ## with a link to it from the message page.
75 ##
76 ## disableflowed
77 ## Ignore flowed formatting for message text
78 ## denoted with flowed formatting.
79 ##
80 ## fancyquote Highlight quoted text with vertical bar in left
81 ## margin.
82 ##
83 ## inlineexts="ext1,ext2,..."
84 ## A comma separated list of message specified filename
85 ## extensions to treat as inline data.
86 ## Applicable only when uudecode options specified.
87 ##
88 ## htmlcheck Check if message is actually an HTML message
89 ## (to get around abhorrent MUAs). The message
90 ## is treated as HTML if the first non-whitespace
91 ## data looks like the start of an HTML document.
92 ##
93 ## keepspace Preserve whitespace if nonfixed
94 ##
95 ## link="scheme1,scheme2,..."
96 ## A comma separate list of URL schemes to hyperlink.
97 ## Only URL with the given schemes will be linked.
98 ##
99 ## nolink="scheme1,scheme2,..."
100 ## A comma separate list of URL schemes to not
101 ## hyperlink. URLs with the given scheme will not
102 ## converted into hyperlinks.
103 ##
104 ## nourl Do not hyperlink URLs.
105 ##
106 ## nonfixed Use normal typeface
107 ##
108 ## maxwidth=# Set the maximum width of lines. Lines exceeding
109 ## the maxwidth will be broken up across multiple lines.
110 ##
111 ## quote Italicize quoted message text
112 ##
113 ## quoteclass CSS classname for quoted text in flowed data or
114 ## if fancyquote specified. Overrides builtin style.
115 ##
116 ## subdir Place derived files in a subdirectory (only
117 ## applicable if uudecode is specified).
118 ##
119 ## target=name Set TARGET attribute for links if converting URLs
120 ## to links. Defaults to _top.
121 ##
122 ## usename Use filename specified in uuencoded data when
123 ## converting uuencoded data. This option is only
124 ## applicable of uudecode is specified.
125 ##
126 ## uudecode Decoded any embedded uuencoded data.
127 ##
128 ## All arguments should be separated by at least one space
129 ##
130 sub filter {
131 my ($fields, $data, $isdecode, $args) = @_;
132 local ($_);
133  
134 ## Parse arguments
135 $args = "" unless defined($args);
136  
137 ## Check if content-disposition should be checked
138 if ($args =~ /\battachcheck\b/i) {
139 my ($disp, $nameparm, $raw) =
140 readmail::MAILhead_get_disposition($fields);
141 if ($disp =~ /\battachment\b/i) {
142 require 'mhexternal.pl';
143 return (
144 m2h_external::filter(
145 $fields, $data, $isdecode,
146 readmail::get_filter_args('m2h_external::filter')
147 )
148 );
149 }
150 }
151  
152 ## Check if decoding uuencoded data. The implementation chosen here
153 ## for decoding uuencoded data was done so when uudecode is not
154 ## specified, there is no extra overhead (besides the $args check for
155 ## uudecode). However, when uudecode is specified, more overhead may
156 ## exist over other potential implementations.
157 ## I.e. We only try to penalize performance when uudecode is specified.
158 if ($args =~ s/\buudecode\b//ig) {
159 # $args has uudecode stripped out for recursive calls
160 my $subdir = $args =~ /\bsubdir\b/i;
161 my $atdir = $subdir ? $mhonarc::MsgPrefix . $mhonarc::MHAmsgnum : "";
162  
163 # Make sure we have needed routines
164 my $decoder = readmail::load_decoder("uuencode");
165 if (!defined($decoder) || !defined(&$decoder)) {
166 require 'base64.pl';
167 $decoder = \&base64::uudecode;
168 }
169 require 'mhmimetypes.pl';
170  
171 # Grab any filename extensions that imply inlining
172 my $inlineexts = '';
173 if ($args =~ /\binlineexts=(\S+)/) {
174 $inlineexts = ',' . lc($1) . ',';
175 $inlineexts =~ s/['"]//g;
176 }
177 my $usename = $args =~ /\busename\b/;
178  
179 my ($pdata);
180 my ($inext, $uddata, $file, $urlfile);
181 my @files = ();
182 my $ret = "";
183 my $i = 0;
184  
185 # <CR><LF> => <LF> to make parsing easier
186 $$data =~ s/\r\n/\n/g;
187  
188 # Split on uuencoded data. For text portions, recursively call
189 # filter to convert text data: makes it easier to handle all
190 # the various formatting options.
191 foreach $pdata (
192 split(/^(begin\s+\d\d\d\s+[^\n]+\n[!-M].*?\nend\n)/sm, $$data)) {
193 if ($i % 2) { # uuencoded data
194 # extract filename extension
195 ($file) = $pdata =~ /^begin\s+\d\d\d\s+([^\n]+)/;
196 if ($file =~ /\.(\w+)$/) { $inext = $1; }
197 else { $inext = ""; }
198  
199 # decode data
200 $uddata = &$decoder($pdata);
201  
202 # save to file
203 if (readmail::MAILis_excluded('application/octet-stream')) {
204 $ret .= &$readmail::ExcludedPartFunc($file);
205  
206 } elsif ($file =~ /\.s?html?$/i) {
207 my @ha = do_html($fields, \$uddata, 1, $args);
208 $ret .= shift(@ha);
209 push(@files, @ha);
210  
211 } else {
212 push(
213 @files,
214 mhonarc::write_attachment(
215 'application/octet-stream',
216 \$uddata,
217 { '-dirpath' => $atdir,
218 '-filename' => ($usename ? $file : ''),
219 '-ext' => $inext
220 }
221 )
222 );
223 $urlfile = mhonarc::htmlize($files[$#files]);
224  
225 # create link to file
226 if (index($inlineexts, ',' . lc($inext) . ',') >= $[) {
227 $ret .= qq|<a href="$urlfile"><img src="$urlfile">|
228 . qq|</a><br>\n|;
229 } else {
230 $ret .=
231 qq|<a href="$urlfile">|
232 . mhonarc::htmlize($file)
233 . qq|</a><br>\n|;
234 }
235 }
236  
237 } elsif ($pdata =~ /\S/) { # plain text
238 my (@subret) = filter($fields, \$pdata, $isdecode, $args);
239 $ret .= shift @subret;
240 push(@files, @subret);
241 }
242 ++$i;
243 }
244  
245 ## Done with uudecode
246 $ret = ' ' if $ret eq '';
247 return ($ret, @files);
248 }
249  
250 ## Check for HTML data if requested
251 if ( $args =~ s/\bhtmlcheck\b//i
252 && $$data =~ /\A\s*<(?:html\b|x-html\b|!doctype\s+html\s)/i) {
253 return do_html($fields, $data, $isdecode, $args);
254 }
255  
256 my ($charset, $nourl, $igncharset, $nonfixed,
257 $keepspace, $maxwidth, $target, $xhtml
258 );
259 my (%asis) = ();
260  
261 $nourl = ($mhonarc::NOURL || ($args =~ /\bnourl\b/i));
262 $nonfixed = ($args =~ /\bnonfixed\b/i);
263 $keepspace = ($args =~ /\bkeepspace\b/i);
264 if ($args =~ /\bmaxwidth=(\d+)/i) { $maxwidth = $1; }
265 else { $maxwidth = 0; }
266 $target = "";
267 if ($args =~ /\btarget="([^"]+)"/i) { $target = $1; }
268 elsif ($args =~ /\btarget=(\S+)/i) { $target = $1; }
269 $target =~ s/['"]//g;
270  
271 if ($target) {
272 $target = qq/target="$target"/;
273 }
274  
275 ## Grab charset parameter
276 $charset = $fields->{'x-mha-charset'};
277  
278 ## Grab format parameter (if defined)
279 my $textformat = 'fixed';
280 if ( ($args !~ /\bdisableflowed\b/i)
281 && (defined($fields->{'content-type'}[0]))
282 && ($fields->{'content-type'}[0] =~ /\bformat\s*=\s*([^\s;]+)/i)) {
283 $textformat = lc $1;
284 $textformat =~ s/['";\s]//g;
285 }
286  
287 my $startq = "";
288 my $endq = "";
289 my $startfixq = "";
290 my $endfixq = "";
291 my $css_class = "";
292 if ($args =~ /\bquoteclass=(\S+)/i) {
293 $css_class = $1;
294 $css_class =~ s/[^\w\.\-]//g;
295 }
296  
297 my $quote_style = Q_FIXED;
298 my $fancyquote = $args =~ /\bfancyquote\b/i;
299 if ($fancyquote || ($textformat eq 'flowed')) {
300 $quote_style = ($textformat eq 'flowed') ? Q_FLOWED : Q_FANCY;
301 $startq =
302 ($css_class)
303 ? qq|<blockquote class="$css_class">|
304 : $StartFlowedQuote;
305 $endq = $EndFlowedQuote;
306 if (!$nonfixed) {
307 $startfixq = $StartFixedQuote;
308 $endfixq = $EndFixedQuote;
309 }
310  
311 } elsif ($args =~ /\bquote\b/i) {
312 $quote_style = Q_SIMPLE;
313 }
314  
315 ## Check if certain charsets should be left alone
316 if ($args =~ /\basis=(\S+)/i) {
317 my $t = lc $1;
318 $t =~ s/['"]//g;
319 local ($_);
320 foreach (split(':', $t)) { $asis{$_} = 1; }
321 }
322  
323 ## Check MIMECharSetConverters if charset should be left alone
324 my ($charcnv, $real_charset_name) =
325 readmail::MAILload_charset_converter($charset);
326 if (defined($charcnv) && $charcnv eq '-decode-') {
327 $asis{$charset} = 1;
328 }
329  
330 ## Fixup any EOL mess
331 $$data =~ s/\r?\n/\n/g;
332 $$data =~ s/\r/\n/g;
333  
334 ## Check if max-width set
335 if (($maxwidth > 0) && ($quote_style != Q_FLOWED)) {
336 break_lines($data, $charset, $maxwidth);
337 }
338  
339 ## Convert data according to charset
340 if (!$asis{$charset}) {
341 # Registered in CHARSETCONVERTERS
342 if (defined($charcnv) && defined(&$charcnv)) {
343 $$data = &$charcnv($$data, $real_charset_name);
344  
345 # Other
346 } else {
347 warn qq/\n/,
348 qq/Warning: Unrecognized character set: $charset\n/,
349 qq/ Message-Id: <$mhonarc::MHAmsgid>\n/,
350 qq/ Message Subject: /, $fields->{'x-mha-subject'},
351 qq/\n/,
352 qq/ Message Number: $mhonarc::MHAmsgnum\n/;
353 mhonarc::htmlize($data);
354 }
355  
356 } else {
357 mhonarc::htmlize($data);
358 }
359  
360 # XXX: Initial algorithms for flowed and fancy processing
361 # used the s/// operator. However, for large messages, this could
362 # cause perl to crash (seg fault) (verified with perl v5.6.1 and
363 # v5.8.0). Hence, code changed to use m//g and substr(), which
364 # appears to avoid perl crashing (ehood, Dec 2002).
365 #
366 # To fix bug #12512, flowed code changed to process each quote
367 # chunk line-by-line instead of as one entity. The reason is
368 # that RFC-2646 does not define a "paragraph" by two consective
369 # CRLF sequences but by flowed vs non-flowed, which can occur
370 # with no blank lines in between (ehood, May 2005).
371 #
372 # Initial code for format=flowed contributed by Ken Hirsch (May 2002),
373 # but it has drastically changes since then.
374 #
375 # text/plain; format=flowed defined in RFC-2646
376  
377 if ($quote_style == Q_FLOWED) {
378 my ($chunk, $qd, $offset);
379 my $currdepth = 0;
380 my $ret = '';
381 $$data =~ s!^</?x-flowed>\n!!mg;
382 while (length($$data) > 0) {
383 # Divide message into chunks by "quote-depth",
384 # which is the number of leading > signs
385 ($qd) = $$data =~ /^((?:&gt;)*)/;
386 $chunk = '';
387 pos($$data) = 0;
388 if ($qd eq '') {
389 # Non-quoted text: We special case this since we can
390 # use a fixed pattern to grab the chunk.
391 if ($$data =~ /^(?=&gt;)/mgo) {
392 $offset = pos($$data);
393 $chunk = substr($$data, 0, $offset);
394 substr($$data, 0, $offset) = '';
395 } else {
396 $chunk = $$data;
397 $$data = '';
398 }
399 $chunk =~ s/^[ ]//mg; # remove space-stuffing
400  
401 } else {
402 # Quoted text: It would be nice to not have
403 # to compile a new pattern each time.
404 if ($$data =~ /^(?!$qd(?!&gt;))/mg) {
405 $offset = pos($$data);
406 $chunk = substr($$data, 0, $offset);
407 substr($$data, 0, $offset) = '';
408 } else {
409 $chunk = $$data;
410 $$data = '';
411 }
412 $chunk =~ s/^$qd ?//mg; # remove quote indi and space-stuffing
413 }
414 $chunk =~ s/^-- $/--/mg; # special case for '-- '
415  
416 # Parse chunk line at a time to determine how it is rendered.
417 my $new_chunk = "";
418 my $line = "";
419 my $inflow = 0;
420 my $infixed = 0;
421 FLOWED_LINE: while ($chunk ne "") {
422 # Grab next line: Pattern should always match.
423 $chunk =~ s/(\A.*(?:\n|\Z))//;
424 $line = $1;
425 if ($line =~ /[ ]\n\Z/) {
426 # Have a flowed line
427 $inflow = 1;
428 if ($infixed) {
429 $new_chunk .= $endfixq;
430 $infixed = 0;
431 }
432 if ($nonfixed) {
433 $new_chunk .= $line;
434 } else {
435 $new_chunk .= '<tt>' . $line . '</tt>';
436 }
437 next FLOWED_LINE;
438 }
439 if ($inflow) {
440 # Last line of flowed text may not have SP CRLF
441 if ($nonfixed) {
442 $new_chunk .= $line . "<br>";
443 } else {
444 $new_chunk .= '<tt>' . $line . '</tt>';
445 }
446 $inflow = 0;
447 next FLOWED_LINE;
448 }
449 # Fixed line
450 if (!$infixed) {
451 # Begin fixed rendering if at start
452 $new_chunk .= $startfixq . "\n";
453 $infixed = 1;
454 $inflow = 0;
455 }
456 if ($maxwidth > 0) {
457 # Fixed lines should be clipped to specified max.
458 $line = break_lines($line, $charset, $maxwidth, 1);
459 }
460 if ($nonfixed) {
461 # Proportional font desired
462 $line =~ s/(\n)/<br>$1/g;
463 if ($keepspace) {
464 $line =~ s/^(.*)$/&preserve_space($1)/gem;
465 }
466 }
467 $new_chunk .= $line;
468  
469 } # End: FLOWED_LINE: while()
470  
471 # Make sure to close tags
472 if ($infixed) {
473 $new_chunk .= $endfixq;
474 }
475  
476 # Add quote markup
477 my $newdepth = length($qd) / length('&gt;');
478 if ($currdepth < $newdepth) {
479 $new_chunk = $startq x ($newdepth - $currdepth) . $new_chunk;
480 } elsif ($currdepth > $newdepth) {
481 $new_chunk = $endq x ($currdepth - $newdepth) . $new_chunk;
482 }
483 $currdepth = $newdepth;
484 $ret .= $new_chunk;
485 }
486 if ($currdepth > 0) {
487 $ret .= $endq x $currdepth;
488 }
489  
490 $$data = $ret;
491  
492 } elsif ($quote_style == Q_FANCY) {
493 # Fancy quoting supports alternative quote characters besides
494 # '>' as defined by ${HQuoteChars}.
495 my ($chunk, $qd, $qd_re, $offset);
496 my $currdepth = 0;
497 my $ret = '';
498  
499 # Compress '>'s to have no spacing, makes latter patterns
500 # simplier.
501 $$data =~ s/(?:^[ ]?|\G)(${HQuoteChars})[ ]?/$1/gmo;
502 while (length($$data) > 0) {
503 ($qd) = $$data =~ /\A((?:${HQuoteChars})*)/o;
504 $chunk = '';
505 pos($$data) = 0;
506 if ($qd eq '') {
507 # Non-quoted text: We special case this since we can
508 # use a fixed pattern to grab the chunk.
509 if ($$data =~ /^(?=${HQuoteChars})/mgo) {
510 $offset = pos($$data);
511 $chunk = substr($$data, 0, $offset);
512 substr($$data, 0, $offset) = '';
513 } else {
514 $chunk = $$data;
515 $$data = '';
516 }
517 } else {
518 # Quoted text: Make sure any regex specials are escaped
519 # before using in pattern. It would be nice to not have
520 # to compile a new pattern each time.
521 $qd_re = "\Q$qd\E";
522 if ($$data =~ /^(?!$qd_re(?!${HQuoteChars}))/mg) {
523 $offset = pos($$data);
524 $chunk = substr($$data, 0, $offset);
525 substr($$data, 0, $offset) = '';
526 } else {
527 $chunk = $$data;
528 $$data = '';
529 }
530 $chunk =~ s/^$qd_re//mg;
531 }
532 if ($nonfixed) {
533 $chunk =~ s/(\n)/<br>$1/g;
534 if ($keepspace) {
535 $chunk =~ s/^(.*)$/&preserve_space($1)/gem;
536 }
537 } else {
538 # GUI browsers ignore first \n after <pre>, so we double it
539 # to make sure a blank line is rendered
540 $chunk =~ s/\A\n/\n\n/;
541 $chunk = $startfixq . $chunk . $endfixq;
542 }
543  
544 $qd =~ s/\s+//g;
545 my $newdepth = html_length($qd);
546 if ($currdepth < $newdepth) {
547 $chunk = $startq x ($newdepth - $currdepth) . $chunk;
548 } elsif ($currdepth > $newdepth) {
549 $chunk = $endq x ($currdepth - $newdepth) . $chunk;
550 }
551 $currdepth = $newdepth;
552 $ret .= $chunk;
553 }
554 if ($currdepth > 0) {
555 $ret .= $endq x $currdepth;
556 }
557  
558 $$data = $ret;
559  
560 } else {
561 ## Check for simple quoting
562 if ($quote_style == Q_SIMPLE) {
563 $$data =~ s@^( ?${HQuoteChars})(.*)$@$1<i>$2</i>@gom;
564 }
565  
566 ## Check if using nonfixed font
567 if ($nonfixed) {
568 $$data =~ s/(\r?\n)/<br>$1/g;
569 if ($keepspace) {
570 $$data =~ s/^(.*)$/&preserve_space($1)/gem;
571 }
572 } else {
573 $$data = '<pre>' . $$data . '</pre>';
574 }
575 }
576  
577 ## Convert URLs to hyperlinks
578 if (!$nourl) {
579 my $nolink = undef;
580 my $link = undef;
581 if ($args =~ /\bnolink\s*=(\S+)/) {
582 $nolink = lc(',' . $1 . ',');
583 $nolink =~ s/['"]//g;
584 }
585 if ($args =~ /\blink\s*=(\S+)/) {
586 $link = lc(',' . $1 . ',');
587 $link =~ s/['"]//g;
588 }
589 $$data =~ s{
590 ($HUrlExp)
591 }{
592 if (!defined($nolink) && !defined($link)) {
593 join('', '<a ', $target, ' rel="nofollow" href="',
594 $1, '">', $1, '</a>');
595 } else {
596 my $url_match = $1;
597 my $scheme;
598 $url_match =~ /^([^:]+)/;
599 $scheme = ',' . lc($1) . ',';
600 if ((defined($nolink) && (index($nolink, $scheme) >= $[)) ||
601 (defined($link) && (index($link, $scheme) < $[)))
602 {
603 $url_match;
604 } else {
605 join('', '<a ', $target, ' rel="nofollow" href="',
606 $url_match, '">', $url_match, '</a>');
607 }
608 }
609 }gxeso;
610 }
611  
612 $$data = ' ' if $$data eq '';
613 ($$data);
614 }
615  
616 ##---------------------------------------------------------------------------##
617  
618 sub do_html {
619 my ($fields, $data, $isdecode, $args) = @_;
620 if (readmail::MAILis_excluded('text/html')) {
621 return (&$readmail::ExcludedPartFunc('text/plain HTML'));
622 }
623 my $html_filter = readmail::load_filter('text/html');
624 if (defined($html_filter) && defined(&$html_filter)) {
625 return (
626 &$html_filter(
627 $fields, $data,
628 $isdecode,
629 readmail::get_filter_args(
630 'text/html', 'text/*', $html_filter
631 )
632 )
633 );
634 } else {
635 require 'mhtxthtml.pl';
636 return (
637 m2h_text_html::filter(
638 $fields, $data,
639 $isdecode,
640 readmail::get_filter_args(
641 'text/html', 'text/*', 'm2h_text_html::filter'
642 )
643 )
644 );
645 }
646  
647 }
648  
649 ##---------------------------------------------------------------------------##
650  
651 sub preserve_space {
652 my ($str) = shift;
653  
654 1 while $str =~
655 s/^([^\t]*)(\t+)/$1 . ' ' x (length($2) * 8 - length($1) % 8)/e;
656 $str =~ s/ /\&nbsp;/g;
657 $str;
658 }
659  
660 ##---------------------------------------------------------------------------##
661  
662 sub break_lines {
663 my $data_in = shift;
664 my $charset = shift;
665 my $maxwidth = shift;
666 my $is_html = shift; # hack for flowed processing
667 return unless $maxwidth > 0;
668  
669 my $data = ref($data_in) ? $data_in : \$data_in;
670 my $do_encode = 0;
671 eval {
672 require Encode;
673 # Only translate to Perl's utf-8 if not an 8-bit charset.
674 # No harm if done for 8-bit, but try to avoid unnecesary
675 # overhead. Translation done so line breaking is done
676 # on characters, not octets.
677 if ( $charset !~ /us-ascii/i
678 && $charset !~ /8859/i
679 && !Encode::is_utf8($$data)) {
680 $$data = Encode::decode($charset, $$data);
681 $do_encode = 1;
682 }
683 };
684 $$data =~ s{
685 ^(.*)$
686 }{
687 _break_line($1, ($is_html ? $maxwidth+(length($1)-html_length($1))
688 : $maxwidth))
689 }gemx;
690 if ($do_encode) {
691 # Translate back to current encoding.
692 $$data = Encode::encode($charset, $$data);
693 }
694 $$data;
695 }
696  
697 sub _break_line {
698 my ($str) = shift;
699 my ($width) = shift;
700 my ($q, $new) = ('', '');
701 my ($try, $trywidth, $len);
702  
703 ## Translate tabs to spaces
704 1 while $str =~
705 s/^([^\t]*)(\t+)/$1 . ' ' x (length($2) * 8 - length($1) % 8)/e;
706  
707 ## Do nothing if str <= width
708 return $str if length($str) <= $width;
709  
710 ## See if str begins with a quote char
711 if ($str =~ s/^([ ]?(?:$QuoteChars[ ]?)+)//o) {
712 $q = $1;
713 if (length($q) >= $width) {
714 # too many quote chars, so treat line as-is
715 $str = $q . $str;
716 } else {
717 $width -= length($q);
718 }
719 }
720  
721 ## Create new string by breaking up str
722 while ($str ne "") {
723  
724 # If $str less than width, break out
725 if (length($str) <= $width) {
726 $new .= $q . $str;
727 last;
728 }
729  
730 # handle case where no-whitespace line larger than width
731 if (($str =~ /^(\S+)/) && (($len = length($1)) >= $width)) {
732 $new .= $q . $1;
733 substr($str, 0, $len) = "";
734 next;
735 }
736  
737 # Break string at whitespace
738 $try = '';
739 $trywidth = $width;
740 $try = substr($str, 0, $trywidth);
741 if ($try =~ /(\S+)$/) {
742 $trywidth -= length($1);
743 $new .= $q . substr($str, 0, $trywidth);
744 } else {
745 $new .= $q . $try;
746 }
747 substr($str, 0, $trywidth) = '';
748  
749 } continue {
750 $new .= "\n" if $str;
751 }
752 $new;
753 }
754  
755 sub html_length {
756 local $_;
757 my $len = length($_[0]);
758 foreach ($_[0] =~ /(\&[^;]+);/g) {
759 $len -= length($_);
760 }
761 $len;
762 }
763  
764 ##---------------------------------------------------------------------------##
765 1;