]> git.donarmstrong.com Git - debbugs.git/blob - Debbugs/MIME.pm
[project @ 2006-02-05 01:43:18 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 create_mime_message);
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 encode_utf8 decode_utf8 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 =head2 create_mime_message
107
108      create_mime_message([To=>'don@debian.org'],$body,[$attach1, $attach2]);
109
110 Creates a MIME encoded message with headers given by the first
111 argument, and a message given by the second.
112
113 Optional attachments can be specified in the third arrayref argument.
114
115 Headers are passed directly to MIME::Entity::build, the message is the
116 first attachment.
117
118 Each of the elements of the attachment arrayref is attached as an
119 rfc822 message if it is a scalar or an arrayref; otherwise if it is a
120 hashref, the contents are passed as an argument to
121 MIME::Entity::attach
122
123 =cut
124
125 sub create_mime_message{
126      my ($headers,$body,$attachments) = @_;
127      $attachments = [] if not defined $attachments;
128
129      die "The first argument to create_mime_message must be an arrayref" unless ref($headers) eq 'ARRAY';
130      die "The third argument to create_mime_message must be an arrayref" unless ref($attachments) eq 'ARRAY';
131
132      # Build the message
133      my $msg = MIME::Entity->build(@{$headers},
134                                    Data    => $body
135                                   );
136
137      # Attach the attachments
138      for my $attachment (@{$attachments}) {
139           if (ref($attachment) eq 'HASH') {
140                $msg->attach(%{$attachment});
141           }
142           else {
143                # This is *craptacular*, but because various MTAs
144                # (sendmail and exim4, at least) appear to eat From
145                # lines in message/rfc822 attachments, we need to make
146                # sure the From line is the first thing in the
147                # attachement, not the second, so if it gets eaten, the
148                # headers don't collide into the body.
149                if (ref($attachment) eq 'ARRAY' and $attachment->[1] =~ /^From /) {
150                     # make a copy so that we don't screw up anything
151                     # that is expecting this arrayref to stay constant
152                     $attachment = [@{$attachment}];
153                     # flip the From and Received lines around
154                     @{$attachment}[qw(1 0)] = @{$attachment}[qw(0 1)];
155                }
156                elsif (not ref($attachment)) {
157                     # It's a scalar
158                     $attachment =~ s/^(Received:[^\n]+\n)(From [^\n]+\n)/$2$1/s;
159                }
160                $msg->attach(Type => 'message/rfc822',
161                             Data => $attachment,
162                             Encoding => '7bit',
163                            );
164           }
165      }
166      return $msg->as_string;
167 }
168
169
170 # Bug #61342 et al.
171
172 sub convert_to_utf8 {
173      my ($data, $charset) = @_;
174      # raw data just gets returned (that's the charset WordDecorder
175      # uses when it doesn't know what to do)
176      return $data if $charset eq 'raw' or is_utf8($data,1);
177      my $result;
178      eval {
179           # this encode/decode madness is to make sure that the data
180           # really is valid utf8 and that the is_utf8 flag is off.
181           $result = encode("utf8",decode($charset,$data))
182      };
183      if ($@) {
184           warn "Unable to decode charset; '$charset' and '$data': $@";
185           return $data;
186      }
187      return $result;
188 }
189
190
191 =head2 decode_rfc1522
192
193     decode_rfc1522('=?iso-8859-1?Q?D=F6n_Armstr=F3ng?= <don@donarmstrong.com>')
194
195 Turn RFC-1522 names into the UTF-8 equivalent.
196
197 =cut
198
199 BEGIN {
200     # Set up the default RFC1522 decoder, which turns all charsets that
201     # are supported into the appropriate UTF-8 charset.
202     MIME::WordDecoder->default(new MIME::WordDecoder(
203         ['*' => \&convert_to_utf8,
204         ]));
205 }
206
207 sub decode_rfc1522 ($)
208 {
209     my ($string) = @_;
210
211     # unmime calls the default MIME::WordDecoder handler set up at
212     # initialization time.
213     return MIME::WordDecoder::unmime($string);
214 }
215
216 =head2 encode_rfc1522
217
218      encode_rfc1522('Dön Armströng <don@donarmstrong.com>')
219
220 Encodes headers according to the RFC1522 standard by calling
221 MIME::Words::encode_mimeword on distinct words as appropriate.
222
223 =cut
224
225 # We cannot use MIME::Words::encode_mimewords because that function
226 # does not handle spaces properly at all.
227
228 sub encode_rfc1522 ($) {
229      my ($rawstr) = @_;
230
231      # We process words in reverse so we can preserve spacing between
232      # encoded words. This regex splits on word|nonword boundaries and
233      # nonword|nonword boundaries.
234      my @words = reverse split /(?:(?<=[\s\n])|(?=[\s\n]))/m, $rawstr;
235
236      my $previous_word_encoded = 0;
237      my $string = '';
238      for my $word (@words) {
239           if ($word !~ m#[\x00-\x1F\x7F-\xFF]#o and $word ne ' ') {
240                $string = $word.$string;
241                $previous_word_encoded=0;
242           }
243           elsif ($word =~ /^[\s\n]$/) {
244                $string = $word.$string;
245                $previous_word_encoded = 0 if $word eq "\n";
246           }
247           else {
248                my $encoded = MIME::Words::encode_mimeword($word, 'q', 'UTF-8');
249                # RFC 1522 mandates that segments be at most 76 characters
250                # long. If that's the case, we split the word up into 10
251                # character pieces and encode it. We must use the Encode
252                # magic here to avoid breaking on bit boundaries here.
253                if (length $encoded > 75) {
254                     # Turn utf8 into the internal perl representation
255                     # so . is a character, not a byte.
256                     my $tempstr = decode_utf8($word,Encode::FB_DEFAULT);
257                     my @encoded;
258                     # Strip it into 10 character long segments, and encode
259                     # the segments
260                     # XXX It's possible that these segments are > 76 characters
261                     while ($tempstr =~ s/(.{1,10})$//) {
262                          # turn the character back into the utf8 representation.
263                          my $tempword = encode_utf8($1);
264                          # It may actually be better to eventually use
265                          # the base64 encoding here, but I'm not sure
266                          # if that's as widely supported as quoted
267                          # printable.
268                          unshift @encoded, MIME::Words::encode_mimeword($tempword,'q','UTF-8');
269                     }
270                     $encoded = join(" ",@encoded);
271                     # If the previous word was encoded, we must
272                     # include a trailing _ that gets encoded as a
273                     # space.
274                     $encoded =~ s/\?\=$/_\?\=/ if $previous_word_encoded;
275                     $string = $encoded.$string;
276                }
277                else {
278                     # If the previous word was encoded, we must
279                     # include a trailing _ that gets encoded as a
280                     # space.
281                     $encoded =~ s/\?\=$/_\?\=/ if $previous_word_encoded;
282                     $string = $encoded.$string;
283                }
284                $previous_word_encoded = 1;
285           }
286      }
287      return $string;
288 }
289
290 1;