]> git.donarmstrong.com Git - debbugs.git/blob - Debbugs/MIME.pm
[project @ 2005-07-30 03:22:36 by don]
[debbugs.git] / Debbugs / MIME.pm
1 package Debbugs::MIME;
2
3 use strict;
4
5 use base qw(Exporter);
6 use vars qw($VERSION @EXPORT_OK);
7
8 BEGIN {
9     $VERSION = 1.00;
10
11     @EXPORT_OK = qw(parse decode_rfc1522 encode_rfc1522 convert_to_utf8);
12 }
13
14 use File::Path;
15 use MIME::Parser;
16
17 # for decode_rfc1522
18 use MIME::WordDecoder qw();
19 use Encode qw(decode encode is_utf8);
20
21 # for encode_rfc1522
22 use MIME::Words qw();
23
24 sub getmailbody ($);
25 sub getmailbody ($)
26 {
27     my $entity = shift;
28     my $type = $entity->effective_type;
29     if ($type eq 'text/plain' or
30             ($type =~ m#text/# and $type ne 'text/html') or
31             $type eq 'application/pgp') {
32         return $entity->bodyhandle;
33     } elsif ($type eq 'multipart/alternative') {
34         # RFC 2046 says we should use the last part we recognize.
35         for my $part (reverse $entity->parts) {
36             my $ret = getmailbody($part);
37             return $ret if $ret;
38         }
39     } else {
40         # For other multipart types, we just pretend they're
41         # multipart/mixed and run through in order.
42         for my $part ($entity->parts) {
43             my $ret = getmailbody($part);
44             return $ret if $ret;
45         }
46     }
47     return undef;
48 }
49
50 sub parse ($)
51 {
52     # header and decoded body respectively
53     my (@headerlines, @bodylines);
54
55     my $parser = new MIME::Parser;
56     mkdir "mime.tmp.$$", 0777;
57     $parser->output_under("mime.tmp.$$");
58     my $entity = eval { $parser->parse_data($_[0]) };
59
60     if ($entity and $entity->head->tags) {
61         @headerlines = @{$entity->head->header};
62         chomp @headerlines;
63
64         my $entity_body = getmailbody($entity);
65         @bodylines = $entity_body ? $entity_body->as_lines() : ();
66         chomp @bodylines;
67     } else {
68         # Legacy pre-MIME code, kept around in case MIME::Parser fails.
69         my @msg = split /\n/, $_[0];
70         my $i;
71
72         for ($i = 0; $i <= $#msg; ++$i) {
73             $_ = $msg[$i];
74             last unless length;
75             while ($msg[$i + 1] =~ /^\s/) {
76                 ++$i;
77                 $_ .= "\n" . $msg[$i];
78             }
79             push @headerlines, $_;
80         }
81
82         @bodylines = @msg[$i .. $#msg];
83     }
84
85     rmtree "mime.tmp.$$", 0, 1;
86
87     # Remove blank lines.
88     shift @bodylines while @bodylines and $bodylines[0] !~ /\S/;
89
90     # Strip off RFC2440-style PGP clearsigning.
91     if (@bodylines and $bodylines[0] =~ /^-----BEGIN PGP SIGNED/) {
92         shift @bodylines while @bodylines and length $bodylines[0];
93         shift @bodylines while @bodylines and $bodylines[0] !~ /\S/;
94         for my $findsig (0 .. $#bodylines) {
95             if ($bodylines[$findsig] =~ /^-----BEGIN PGP SIGNATURE/) {
96                 $#bodylines = $findsig - 1;
97                 last;
98             }
99         }
100         map { s/^- // } @bodylines;
101     }
102
103     return { header => [@headerlines], body => [@bodylines]};
104 }
105
106 # Bug #61342 et al.
107
108 sub convert_to_utf8 {
109      my ($data, $charset) = @_;
110      # raw data just gets returned (that's the charset WordDecorder
111      # uses when it doesn't know what to do)
112      return $data if $charset eq 'raw' or is_utf8($data,1);
113      my $result;
114      eval {
115           # this encode/decode madness is to make sure that the data
116           # really is valid utf8 and that the is_utf8 flag is off.
117           $result = encode("utf8",decode($charset,$data))
118      };
119      if ($@) {
120           warn "Unable to decode charset; '$charset' and '$data': $@";
121           return $data;
122      }
123      return $result;
124 }
125
126
127 =head2 decode_rfc1522
128
129     decode_rfc1522('=?iso-8859-1?Q?D=F6n_Armstr=F3ng?= <don@donarmstrong.com>')
130
131 Turn RFC-1522 names into the UTF-8 equivalent.
132
133 =cut
134
135 BEGIN {
136     # Set up the default RFC1522 decoder, which turns all charsets that
137     # are supported into the appropriate UTF-8 charset.
138     MIME::WordDecoder->default(new MIME::WordDecoder(
139         ['*' => \&convert_to_utf8,
140         ]));
141 }
142
143 sub decode_rfc1522 ($)
144 {
145     my ($string) = @_;
146
147     # unmime calls the default MIME::WordDecoder handler set up at
148     # initialization time.
149     return MIME::WordDecoder::unmime($string);
150 }
151
152 sub encode_rfc1522 ($)
153 {
154 #    my ($string) = @_;
155 #
156 #    return MIME::Words::encode_mimewords($string, Charset => 'UTF-8');
157
158 # This function was stolen brazenly from a patched version of
159 # MIME::Words (fix for http://rt.cpan.org/NoAuth/Bug.html?id=13027)
160 #
161 # The patch has been modified slightly to only encode things that
162 # should be encoded, and not eat up every single character.
163
164     my ($rawstr) = @_;
165     my $charset  = 'UTF-8';
166     my $encoding = 'q';
167
168     my $NONPRINT = "\\x00-\\x1F\\x7F-\\xFF"; 
169
170     my $result = "";
171     my $current = $rawstr;
172
173     while ($current ne "") {
174       if ($current =~ s/^(([^$NONPRINT]|\s)+)//) {
175         # safe chars (w/spaces) are handled as-is
176         $result .= $1;
177         next;
178       } elsif ($current =~ s/^(([$NONPRINT]|\s)+)//) {
179         # unsafe chars (w/spaces) are encoded
180         my $unsafe_chars = $1;
181       CHUNK75:
182         while ($unsafe_chars ne "") {
183
184           my $full_len = length($unsafe_chars);
185           my $len = 1;
186           my $prev_encoded = "";
187
188           while ($len <= $full_len) {
189             # we try to encode next beginning of unsafe string
190             my $possible = substr $unsafe_chars, 0, $len;
191             my $encoded = MIME::Words::encode_mimeword($possible, $encoding, $charset);
192
193             if (length($encoded) < 75) {
194               # if it could be encoded in specified maximum length, try
195               # bigger beginning...
196               $prev_encoded = $encoded;
197             } else {
198               #
199               # ...otherwise, add encoded chunk which still fits, and
200               # restart with rest of unsafe string
201               $result .= $prev_encoded;
202               $prev_encoded = "";
203               substr $unsafe_chars, 0, $len - 1, "";
204               next CHUNK75;
205             }
206
207             # if we have reached the end of the string, add final
208             # encoded chunk
209             if ($len == $full_len) {
210               $result .= $encoded;
211               last CHUNK75;
212             }
213
214             $len++;
215           }
216         }
217       }
218     }
219     return $result;
220 }
221
222 1;