source: trunk/gsdl/perllib/plugins/EMAILPlug.pm@ 2732

Last change on this file since 2732 was 2732, checked in by jrm21, 23 years ago

needed <pre> tags when using the text/plain part of a multipart message.

  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
File size: 21.4 KB
Line 
1###########################################################################
2#
3# EMAILPlug.pm - a plugin for parsing email files
4#
5# A component of the Greenstone digital library software
6# from the New Zealand Digital Library Project at the
7# University of Waikato, New Zealand.
8#
9# Copyright (C) 1999-2001 New Zealand Digital Library Project
10#
11# This program is free software; you can redistribute it and/or modify
12# it under the terms of the GNU General Public License as published by
13# the Free Software Foundation; either version 2 of the License, or
14# (at your option) any later version.
15#
16# This program is distributed in the hope that it will be useful,
17# but WITHOUT ANY WARRANTY; without even the implied warranty of
18# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19# GNU General Public License for more details.
20#
21# You should have received a copy of the GNU General Public License
22# along with this program; if not, write to the Free Software
23# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24#
25###########################################################################
26
27
28
29# EMAILPlug
30#
31# by Gordon Paynter ([email protected])
32#
33# Email plug reads email files. These are named with a simple
34# number (i.e. as they appear in maildir folders) or with the
35# extension .mbx (for mbox mail file format)
36#
37# Document text:
38# The document text consists of all the text
39# after the first blank line in the document.
40#
41# Metadata (not Dublin Core!):
42# $Headers All the header content
43# $Subject Subject: header
44# $To To: header
45# $From From: header
46# $FromName Name of sender (where available)
47# $FromAddr E-mail address of sender
48# $DateText Date: header
49# $Date Date: header in GSDL format (eg: 19990924)
50#
51#
52# John McPherson - June/July 2001
53# added (basic) MIME support and quoted-printable and base64 decodings.
54# Minor fixes for names that are actually email addresses (ie <...> was lost)
55#
56# See: * RFC 822 - ARPA Internet Text Messages
57# * RFC 2045 - Multipurpose Internet Mail Extensions (MIME) -part1
58# * RFC 2046 - MIME (part 2) Media Types (and multipart messages)
59# * RFC 2047 - MIME (part 3) Message Header Extensions
60# * RFC 1806 - Content Dispositions (ie inline/attachment)
61package EMAILPlug;
62
63use SplitPlug;
64
65use unicode;
66
67use sorttools;
68use util;
69
70
71# EMAILPlug is a sub-class of SplitPlug.
72
73sub BEGIN {
74 @ISA = ('SplitPlug');
75}
76
77# Create a new EMAILPlug object with which to parse a file.
78# Accomplished by creating a new BasPlug and using bless to
79# turn it into an EMAILPlug.
80
81sub new {
82 my ($class) = @_;
83 my $self = new BasPlug ("EMAILPlug", @_);
84 # this might not actually be true at read-time, but after processing
85 # it should all be utf8.
86 $self->{'input_encoding'}="utf8";
87 return bless $self, $class;
88}
89
90sub get_default_process_exp {
91 my $self = shift (@_);
92 # mbx/email for mailbox file format, \d+ for maildir (each message is
93 # in a separate file, with a unique number for filename)
94 return q@([\\/]\d+|\.(mbx|email))$@;
95}
96
97# This plugin splits the mbox mail files at lines starting with From<sp>
98sub get_default_split_exp {
99 return q^\nFrom .*\n^;
100}
101
102
103# do plugin specific processing of doc_obj
104sub process {
105
106 my $self = shift (@_);
107 my ($textref, $pluginfo, $base_dir, $file, $metadata, $doc_obj) = @_;
108 my $outhandle = $self->{'outhandle'};
109
110 # Check that we're dealing with a valid mail file
111 return undef unless (($$textref =~ /From:/m) || ($$textref =~ /To:/m));
112
113 # slightly more strict validity check, to prevent us from matching
114 # .so.x files ...
115 return undef unless (($$textref =~ /^From /) ||
116 ($$textref =~ /^[-A-Za-z]{2,100}:/m));
117
118 print $outhandle "EMAILPlug: processing $file\n"
119 if $self->{'verbosity'} > 1;
120
121 my $cursection = $doc_obj->get_top_section();
122
123 #
124 # Parse the document's text and extract metadata
125 #
126
127 # Protect backslashes
128 $$textref =~ s@\\@\\\\@g;
129
130 # Separate header from body of message
131 my $Headers = $$textref;
132 $Headers =~ s/\r?\n\r?\n(.*)$//s;
133 $$textref = $1;
134
135 # Unfold headers - see rfc822
136 $Headers =~ s/\r?\n[\t\ ]+/ /gs;
137 # Extract basic metadata from header
138 my @headers = ("From", "To", "Subject", "Date");
139 my %raw;
140 foreach my $name (@headers) {
141 $raw{$name} = "No $name value";
142 }
143
144 # Examine each line of the headers
145 my ($line, $name, $value);
146 my @parts;
147 foreach $line (split(/\n/, $Headers)) {
148
149 # Ignore lines with no content or which begin with whitespace
150 next unless ($line =~ /:/);
151 next if ($line =~ /^\s/);
152
153 # Find out what metadata is on this line
154 @parts = split(/:/, $line);
155 $name = shift @parts;
156# uppercase the first character according to the current locale
157 $name=~s/(.+)/\u$1/;
158 next unless $name;
159 next unless ($raw{$name});
160
161 # Find the value of that metadata
162 $value = join(":", @parts);
163 $value =~ s/^\s+//;
164 $value =~ s/\s+$//;
165
166 # decode headers if stored using =?<charset>?[BQ]?<data>?= (rfc2047)
167 if ($value =~ /=\?/) {
168 my $original_value=$value;
169 my $encoded=$value;
170 $value="";
171 while ($encoded =~ s/(.*?)=\?([^\?]*)\?([bq])\?([^\?]+)\?=\s*//i) {
172 my ($charset, $encoding, $data)=($2,$3,$4);
173 my $decoded_data;
174 $value.="$1"; # any leading chars
175 $data=~s/^\s*//; $data=~s/\s*$//; # strip whitespace from ends
176 chomp $data;
177 $encoding =~ tr/BQ/bq/;
178 if ($encoding eq "q") { # quoted printable
179 $decoded_data=qp_decode($data);
180 } else { # base 64
181 $decoded_data=base64_decode($data);
182 }
183 if (defined($charset)) {
184 $charset=~tr/A-Z/a-z/;
185 $charset=~s/\-/_/g;
186 $charset=~s/gb2312/gb/;
187 # assumes EUC-KR, not ISO-2022 !?
188 $charset=~s/ks_c_5601_1987/korean/;
189 } else {$charset="ascii";}
190 if ($charset eq "ascii" || $charset eq "us-ascii") {
191 # technically possible to have this explicitly...
192 $value.=$decoded_data;
193 } else {
194 my $utf8_text=&unicode::unicode2utf8
195 (
196 &unicode::convert2unicode($charset,\$decoded_data)
197 );
198 $value.=$utf8_text;
199 }
200 } # end of while loop
201 $value.=$encoded; # get any trailing characters
202 if ($value =~ /^\s*$/) { # we couldn't extract anything...
203 $value=original_value;
204 }
205 } # end of if =?...?=
206
207 # Store the metadata
208 $raw{$name} = $value;
209 }
210
211 # Extract the name and e-mail address from the From metadata
212 $frommeta = $raw{"From"};
213 my $fromnamemeta;
214 my $fromaddrmeta;
215
216 $frommeta =~ s/\s*$//; # Remove trailing space, if any
217
218 if ($frommeta =~ m/(.+)\s*<(.+)>/) {
219 $fromnamemeta=$1;
220 $fromaddrmeta=$2;
221 } elsif ($frommeta =~ m/(.+@.+)\s+\((.*)\)/) {
222 $fromnamemeta=$2;
223 $fromaddrmeta=$1;
224 }
225 if (!defined($fromaddrmeta)) {
226 $fromaddrmeta=$frommeta;
227 }
228 $fromaddrmeta=~s/<//; $fromaddrmeta=~s/>//;
229 # minor attempt to prevent spam-bots from harvesting addresses...
230 $fromaddrmeta=~s/@/&#64;/;
231 $doc_obj->add_utf8_metadata ($cursection, "FromAddr", $fromaddrmeta);
232
233 if (defined($fromnamemeta)) {
234 $fromnamemeta =~ s/\"//g;
235 }
236 else {
237 $fromnamemeta = $fromaddrmeta;
238 }
239 # if name is an address
240 $fromnamemeta =~ s/<//g; $fromnamemeta =~ s/>//g;
241 $fromnamemeta=~s/@/&#64\;/;
242 $doc_obj->add_utf8_metadata ($cursection, "FromName", $fromnamemeta);
243
244 # Escape < and > in the whole From field;
245 $raw{"From"}=$frommeta;
246
247 # Process Date information
248 if ($raw{"Date"} !~ /No Date/) {
249 $raw{"DateText"} = $raw{"Date"};
250
251 # Convert the date text to internal date format
252 $value = $raw{"Date"};
253 my ($day, $month, $year) = $value =~ /(\d?\d)\s([A-Z][a-z][a-z])\s(\d\d\d?\d?)/;
254 if ($year < 100) { $year += 1900; }
255 $raw{"Date"} = &sorttools::format_date($day, $month, $year);
256
257 } else {
258 # We have not extracted a date
259 $raw{"DateText"} = "Unknown.";
260 $raw{"Date"} = "19000000";
261 }
262
263 # Add extracted metadata to document object
264 foreach my $name (keys %raw) {
265 $value = $raw{$name};
266 if ($value) {
267 # assume subject, etc headers have no special HTML meaning.
268 $value =~ s@&@&amp\;@g;
269 $value =~ s/</&lt;/g; $value =~ s/>/&gt;/g;
270 $value = &text_into_html($value);
271 # escape [] so it isn't re-interpreted as metadata
272 $value =~ s/\[/&#91;/g; $value =~ s/\]/&#93;/g;
273 } else {
274 $value = "No $name field";
275 }
276 $doc_obj->add_utf8_metadata ($cursection, $name, $value);
277 }
278
279 my $mimetype="text/plain";
280 my $mimeinfo="";
281 # Do MIME and encoding stuff
282 if ($Headers =~ /^content\-type:\s*([\w\/\-]+)\s*\;?\s*(.+?)\s*$/mi)
283 {
284 $mimetype=$1;
285 $mimetype =~ tr/[A-Z]/[a-z]/;
286 $mimeinfo=$2;
287 }
288
289 my $transfer_encoding="7bit";
290 if ($Headers =~ /^content-transfer-encoding:\s*([^\s]+)\s*$/mi) {
291 $transfer_encoding=$1;
292 }
293 if ($mimetype ne "text/plain") {
294 $$textref=text_from_mime_message($mimetype,$mimeinfo,$$textref,
295 $outhandle);
296 } elsif ($transfer_encoding =~ /quoted\-printable/) {
297 $$textref=qp_decode($$textref);
298 } elsif ($transfer_encoding =~ /base64/) {
299 $$textref=base64_decode($$textref);
300 }
301
302
303 # Add "All headers" metadata
304 $Headers = &text_into_html($Headers);
305 $Headers = "No headers" unless ($Headers =~ /\w/);
306 $Headers =~ s/@/&#64\;/g;
307 # escape [] so it isn't re-interpreted as metadata
308 $Headers =~ s/\[/&#91;/g; $Headers =~ s/\]/&#93;/g;
309
310 $doc_obj->add_utf8_metadata ($cursection, "Headers", $Headers);
311
312 # Add text to document object
313 if ($mimetype eq "text/plain") {
314 $$textref = &text_into_html($$textref);
315 }
316 $$textref = "No message" unless ($$textref =~ /\w/);
317 $doc_obj->add_utf8_text($cursection, $$textref);
318
319 return 1;
320}
321
322
323# Convert a text string into HTML.
324#
325# The HTML is going to be inserted into a GML file, so
326# we have to be careful not to use symbols like ">",
327# which ocurs frequently in email messages (and use
328# &gt instead.
329#
330# This function also turns links and email addresses into hyperlinks,
331# and replaces carriage returns with <BR> tags (and multiple carriage
332# returns with <P> tags).
333
334
335sub text_into_html {
336 my ($text) = @_;
337
338 # Convert problem characters into HTML symbols
339 $text =~ s/&/&amp;/go;
340 $text =~ s/</&lt;/go;
341 $text =~ s/>/&gt;/go;
342 $text =~ s/\"/&quot;/go;
343
344 # convert email addresses and URIs into links
345# don't markup email addresses for now
346# $text =~ s/([\w\d\.\-]+@[\w\d\.\-]+)/<a href=\"mailto:$1\">$1<\/a>/g;
347
348 # assume hostnames are \.\w\- only, then might have a trailing '/.*'
349 # assume URI doesn't finish with a '.'
350 $text =~ s@((http|ftp|https)://[\w\-]+(\.[\w\-]+)*/?((&amp;|\.)?[\w\?\=\-_/~]+)*)@<a href=\"$1\">$1<\/a>@g;
351
352
353 # Clean up whitespace and convert \n charaters to <BR> or <P>
354 $text =~ s/ +/ /go;
355 $text =~ s/\s*$//o;
356 $text =~ s/^\s*//o;
357 $text =~ s/\n/\n<BR>/go;
358 $text =~ s/<BR>\s*<BR>/<P>/go;
359
360 return $text;
361}
362
363
364
365
366#Process a MIME message.
367# the textref we are given DOES NOT include the header.
368sub text_from_mime_message {
369 my ($mimetype,$mimeinfo,$text,$outhandle)=(@_);
370
371 # Check for multiparts - $mimeinfo will be a boundary
372 if ($mimetype =~ /multipart/) {
373 $boundary="";
374 if ($mimeinfo =~ m@boundary=(\"[^\"]+\"|[^\s]+)\s*$@im) {
375 $boundary=$1;
376 if ($boundary =~ m@^\"@) {
377 $boundary =~ s@^\"@@; $boundary =~ s@\"$@@;
378 }
379 } else {
380 print $outhandle "EMAILPlug: (warning) couldn't parse MIME boundary\n";
381 }
382 # parts start with "--$boundary"
383 # message ends with "--$boundary--"
384 # RFC says boundary is <70 chars, [A-Za-z'()+_,-./:=?], so escape any
385 # that perl might want to interpolate. Also allows spaces...
386 $boundary=~s/\\/\\\\/g;
387 $boundary=~s/([\?\+\.\(\)\:\/\'])/\\$1/g;
388 my @message_parts = split("\r?\n\-\-$boundary", "\n$text");
389 # remove first "part" and last "part" (final --)
390 shift @message_parts;
391 my $last=pop @message_parts;
392 # if our boundaries are a bit dodgy and we only found 1 part...
393 if (!defined($last)) {$last="";}
394 # make sure it is only -- and whitespace
395 if ($last !~ /^\-\-\s*$/ms) {
396 print $outhandle "EMAILPlug: (warning) last part of MIME message isn't empty\n";
397 }
398 foreach my $message_part (@message_parts) {
399 # remove the leading newline left from split.
400 $message_part=~s/^\r?\n//;
401 }
402 if ($mimetype eq "multipart/alternative") {
403 # check for an HTML version first, then TEXT, otherwise use first.
404 my $part_text="";
405 foreach my $message_part (@message_parts) {
406 if ($message_part =~ m@\s*content\-type:\s*text/html@mis)
407 {
408 # Use the HTML version
409 $part_text=text_from_part($message_part);
410 $mimetype="text/html";
411 last;
412 }
413 }
414 if ($part_text eq "") { # try getting a text part instead
415 foreach my $message_part (@message_parts) {
416 if ($message_part =~ m@^content\-type:\s*text/plain@mis)
417 {
418 # Use the plain version
419 $part_text=text_from_part($message_part);
420 if ($part_text =~/[^\s]/) {
421 $part_text="<pre>".$part_text."</pre>";
422 }
423 $mimetype="text/plain";
424 last;
425 }
426 }
427 }
428 if ($part_text eq "") { # use first part
429 $part_text=text_from_part(shift @message_parts);
430 }
431 if ($part_text eq "") { # we couldn't get anything!!!
432 # or it was an empty message...
433 # do nothing...
434 print $outhandle "EMAILPlug: no text - empty body?\n";
435 } else {
436 $text=$part_text;
437 }
438 } elsif ($mimetype =~ m@multipart/(mixed|digest|related)@) {
439 $text="";
440 foreach my $message_part (@message_parts) {
441 my $part_header=$message_part;
442 my $part_body;
443 if ($message_part=~ /^\s*\n/) {
444 # no header... use defaults
445 $part_body=$message_part;
446 $part_header="Content-type: text/plain; charset=us-ascii";
447 } elsif ($part_header=~s/\r?\n\r?\n(.*)$//sg) {
448 $part_body=$1;
449 } else {
450 # something's gone wrong...
451 $part_header="";
452 $part_body=$message_part;
453 }
454
455 $part_header =~ s/\r?\n[\t\ ]+/ /gs; #unfold
456 my $part_content_type="";
457 my $part_content_info="";
458 if ($mimetype eq "multipart/digest") {
459 # default type - RTFRFC!!
460 $part_content_type="message/rfc822";
461 }
462 if ($part_header =~ m@^content\-type:\s*([\w+/\-]+)\s*\;?\s*([^\s]*)@mi) {
463 $part_content_type=$1; $part_content_type =~ tr/A-Z/a-z/;
464 $part_content_info=$2;
465 }
466 my $filename="";
467 if ($part_header =~ m@name=\"?([\w\.\-\\/]+)\"?@mis) {
468 $filename=$1;
469 }
470
471 # disposition - either inline or attachment.
472 # NOT CURRENTLY USED - we display all text types instead...
473 # $part_header =~ /^content\-disposition:\s*([\w+])/mis;
474
475 # add <<attachment>> to each part except the first...
476 if ($text ne "") {
477 $text.="\n<p><hr><strong>&lt;&lt;attachment&gt;&gt;</>";
478 # add part info header
479 $text.="<br>Type: $part_content_type<br>\n";
480 if ($filename ne "") {
481 $text.="Filename: $filename\n";
482 }
483 $text.="</strong></p>\n";
484 }
485
486 if ($part_content_type =~ m@text/@)
487 {
488 my $part_text=text_from_part($message_part);
489 if ($part_content_type !~ m@text/(ht|x)ml@) {
490 $part_text=text_into_html($part_text);
491 }
492 if ($part_text eq "") {
493 $part_text='&lt;&lt;empty message&gt;&gt;';
494 }
495 $text.=$part_text;
496 } elsif ($part_content_type =~ m@message/rfc822@) {
497 # This is a forwarded message
498 my $message_part_headers=$part_body;
499 $message_part_headers =~ s/\r?\n[\t\ ]+/ /gs; #unfold
500 $message_part_headers=~s/\r?\n\r?\n(.*)$//s;
501 my $message_part_body=$1;
502
503 my $rfc822_formatted_body=""; # put result in here
504 if ($message_part_headers =~
505 /^content\-type:\s*([\w\/\-]+)\s*\;?\s*?([^\s]+)?\s*$/ims)
506 {
507 # The message header uses MIME flags
508 my $message_content_type=$1;
509 my $message_content_info=$2;
510 if (!defined($message_content_info)) {
511 $message_content_info="";
512 }
513 $message_content_type =~ tr/A-Z/a-z/;
514 if ($message_content_type =~ /multipart/) {
515 $rfc822_formatted_body=
516 text_from_mime_message($message_content_type,
517 $message_content_info,
518 $message_part_body,
519 $outhandle);
520 } else {
521 $message_part_body=text_from_part($part_body);
522 $rfc822_formatted_body=text_into_html($message_part_body);
523 }
524 } else {
525 # message doesn't use MIME flags
526 $rfc822_formatted_body=text_into_html($message_part_body);
527 }
528 # Add the returned text to the output
529 # don't put all the headers...
530 $message_part_headers =~ s/^(X\-.*|received|message\-id|return\-path):.*\n//img;
531 $text.=text_into_html($message_part_headers);
532 $text.="<p>\n";
533 $text.=$rfc822_formatted_body;
534 # end of message/rfc822
535 } elsif ($part_content_type =~ /multipart/) {
536 # recurse again
537 $tmptext=text_from_mime_message($part_content_type,
538 $part_content_info,
539 $part_body,
540 $outhandle);
541 $text.=$tmptext;
542 } elsif ($text eq "") {
543 # we can't do anything with this part, but if it's the first
544 # part then make sure it is mentioned..
545
546 $text.="\n<p><hr><strong>&lt;&lt;attachment&gt;&gt;</>";
547 # add part info header
548 $text.="<br>Type: $part_content_type<br>\n";
549 if ($filename ne "") {
550 $text.="Filename: $filename\n";
551 }
552 $text.="</strong></p>\n";
553 }
554 } # foreach message part.
555 } else {
556 # we can't handle this multipart type (not mixed or alternative)
557 # the RFC also mentions "parallel".
558 }
559 } # end of multipart
560 return $text;
561}
562
563
564
565
566
567
568# Process a MIME part. Return "" if we can't decode it.
569sub text_from_part {
570 my $text=shift;
571 my $part_header=$text;
572 # check for empty part header (leading blank line)
573 if ($text =~ /^\s*\r?\n/) {
574 $part_header="Content-type: text/plain; charset=us-ascii";
575 } else {
576 $part_header =~ s/\r?\n\r?\n(.*)$//s;
577 $text=$1; if (!defined($text)) {$text="";}
578 }
579 $part_header =~ s/\r?\n[\t ]+/ /gs; #unfold
580 $part_header =~ /content\-type:\s*([\w\/]+).*?charset=\"?([^\;\"\s]+)\"?/is;
581 my $type=$1;
582 my $charset=$2;
583 if (!defined($type)) {$type="";}
584 if (!defined($charset)) {$charset="ascii";}
585 my $encoding="";
586 if ($part_header =~ /^content\-transfer\-encoding:\s*([^\s]+)/mis) {
587 $encoding=$1; $encoding=~tr/A-Z/a-z/;
588 }
589 # Content-Transfer-Encoding is per-part
590 if ($encoding ne "") {
591 if ($encoding =~ /quoted\-printable/) {
592 $text=qp_decode($text);
593 } elsif ($encoding =~ /base64/) {
594 $text=base64_decode($text);
595 } elsif ($encoding !~ /[78]bit/) { # leave 7/8 bit as is.
596 # rfc2045 also allows binary, which we ignore (for now).
597 # maybe this shouldn't go to stderr, but anyway...
598 print STDERR "EMAILPlug: unknown encoding: $encoding\n";
599 return "";
600 }
601 }
602 if ($type eq "text/html") {
603 # only get stuff between <body> tags, or <html> tags.
604 $text =~ s@^.*<html[^>]*>@@is;
605 $text =~ s@</html>.*$@@is;
606 $text =~ s/^.*?<body[^>]*>//si;
607 $text =~ s/<\/body>.*$//si;
608 }
609 elsif ($type eq "text/xml") {
610 $text=~s/</&lt;/g;$text=~s/>/&gt;/g;
611 $text="<pre>\n$text\n</pre>\n";
612 }
613 # convert to unicode
614 # first get our character encoding name in the right form.
615 $charset=~tr/A-Z/a-z/;
616 $charset=~s/\-/_/g;
617 if ($charset ne "us_ascii" && $charset ne "ascii") {
618 $charset=~s/gb2312/gb/;
619 # assumes EUC-KR, not ISO-2022 !?
620 $charset=~s/ks_c_5601_1987/korean/;
621 my @unicode_array=&unicode::convert2unicode($charset,\$text);
622 my $utf8_text=&unicode::unicode2utf8(@unicode_array);
623 $text=$utf8_text;
624 }
625 return $text;
626}
627
628
629# decode quoted-printable text
630sub qp_decode {
631 my $text=shift;
632
633 my @lines=split('\n', $text);
634
635 # if a line ends with "=\s*", it is a soft line break, otherwise
636 # keep in any newline characters.
637 foreach my $line (@lines) {
638 if ($line =~ s/=\s*$//) {}
639 else {$line.="\n";}
640
641 if ($line =~ /=[0-9A-Fa-f]{2}/) { # it contains an escaped char
642 my @hexcode_segments=split('=',$line);
643 shift @hexcode_segments;
644 my @hexcodes;
645 foreach my $hexcode (@hexcode_segments) {
646 $hexcode =~ s/^(..).*$/$1/; # only need first 2 chars
647 chomp($hexcode); # just in case...
648 my $char=chr (hex "0x$hexcode");
649 $line =~ s/=$hexcode/$char/g;
650 }
651 }
652 }
653 $text= join('', @lines);
654 return $text;
655}
656
657# decode base64 text. This is fairly slow (since it's interpreted perl rather
658# than compiled XS stuff like in the ::MIME modules, but this is more portable
659# for us at least).
660# see rfc2045 for description, but basically, bits 7 and 8 are set to zero;
661# 4 bytes of encoded text become 3 bytes of binary - remove 2 highest bits
662# from each encoded byte.
663
664
665sub base64_decode {
666 my $enc_text = shift;
667# A=>0, B=>1, ..., '+'=>62, '/'=>63
668# also '=' is used for padding at the end, but we remove it anyway.
669 my $mimechars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
670# map each MIME char into it's value, for more efficient lookup.
671 my %index;
672 map { $index{$_} = index ($mimechars, $_) } (split ('', $mimechars));
673# remove all non-base64 chars. eval to get variable in transliteration...
674# also remove '=' - we'll assume (!!) that there are no errors in the encoding
675 eval "\$enc_text =~ tr|$mimechars||cd";
676 my $decoded="";
677 while (length ($enc_text)>3)
678 {
679 my $fourchars=substr($enc_text,0,4,"");
680 my @chars=(split '',$fourchars);
681 $decoded.=chr( $index{$chars[0]} << 2 | $index{$chars[1]} >> 4);
682 $decoded.=chr( ($index{$chars[1]} & 15) << 4 | $index{$chars[2]} >> 2);
683 $decoded.=chr( ($index{$chars[2]} & 3 ) << 6 | $index{$chars[3]});
684 }
685# if there are any input chars left, there are either
686# 2 encoded bytes (-> 1 raw byte) left or 3 encoded (-> 2 raw) bytes left.
687 my @chars=(split '',$enc_text);
688 if (length($enc_text)) {
689 $decoded.=chr($index{$chars[0]} << 2 | (int $index{$chars[1]} >> 4));
690 }
691 if (length($enc_text)==3) {
692 $decoded.=chr( ($index{$chars[1]} & 15) << 4 | $index{$chars[2]} >> 2);
693 }
694 return $decoded;
695}
696
697
698# Perl packages have to return true if they are run.
6991;
Note: See TracBrowser for help on using the repository browser.