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

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

1) Non-ascii characters should now work for any encoding handled by Greenstone
(uses unicode.pm now).

2) RFC 2047 - Message Header Extensions parsing in place. Eg
From: =?<charset>?B?<BASE64ENCODING==>?=

  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
File size: 21.2 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 =~ /boundary=\"?([^"]+)\"?\s*$/im) {
375 $boundary=$1;
376 }
377 # parts start with "--$boundary"
378 # message ends with "--$boundary--"
379 # RFC says boundary is <70 chars, [A-Za-z'()+_,-./:=?], so escape any
380 # that perl might want to interpolate. Also allows spaces...
381 $boundary=~s/\\/\\\\/g;
382 $boundary=~s/([\?\+\.\(\)\:\/\'])/\\$1/g;
383 my @message_parts = split("\r?\n\-\-$boundary", "\n$text");
384 # remove first "part" and last "part" (final --)
385 shift @message_parts;
386 my $last=pop @message_parts;
387 # if our boundaries are a bit dodgy and we only found 1 part...
388 if (!defined($last)) {$last="";}
389 # make sure it is only -- and whitespace
390 if ($last !~ /^\-\-\s*$/ms) {
391 print $outhandle "EMAILPlug: (warning) last part of MIME message isn't empty\n";
392 }
393 foreach my $message_part (@message_parts) {
394 # remove the leading newline left from split.
395 $message_part=~s/^\r?\n//;
396 }
397 if ($mimetype eq "multipart/alternative") {
398 # check for an HTML version first, then TEXT, otherwise use first.
399 my $part_text="";
400 foreach my $message_part (@message_parts) {
401 if ($message_part =~ m@\s*content\-type:\s*text/html@mis)
402 {
403 # Use the HTML version
404 $part_text=text_from_part($message_part);
405 $mimetype="text/html";
406 last;
407 }
408 }
409 if ($part_text eq "") { # try getting a text part instead
410 foreach my $message_part (@message_parts) {
411 if ($message_part =~ m@^content\-type:\s*text/plain@mis)
412 {
413 # Use the plain version
414 $part_text=text_from_part($message_part);
415 $mimetype="text/plain";
416 last;
417 }
418 }
419 }
420 if ($part_text eq "") { # use first part
421 $part_text=text_from_part(shift @message_parts);
422 }
423 if ($part_text eq "") { # we couldn't get anything!!!
424 # or it was an empty message...
425 # do nothing...
426 print $outhandle "EMAILPlug: no text - empty body?\n";
427 } else {
428 $text=$part_text;
429 }
430 } elsif ($mimetype =~ m@multipart/(mixed|digest|related)@) {
431 $text="";
432 foreach my $message_part (@message_parts) {
433 my $part_header=$message_part;
434 my $part_body;
435 if ($message_part=~ /^\s*\n/) {
436 # no header... use defaults
437 $part_body=$message_part;
438 $part_header="Content-type: text/plain; charset=us-ascii";
439 } elsif ($part_header=~s/\r?\n\r?\n(.*)$//sg) {
440 $part_body=$1;
441 } else {
442 # something's gone wrong...
443 $part_header="";
444 $part_body=$message_part;
445 }
446
447 $part_header =~ s/\r?\n[\t\ ]+/ /gs; #unfold
448 my $part_content_type="";
449 my $part_content_info="";
450 if ($mimetype eq "multipart/digest") {
451 # default type - RTFRFC!!
452 $part_content_type="message/rfc822";
453 }
454 if ($part_header =~ m@^content\-type:\s*([\w+/\-]+)\s*\;?\s*([^\s]*)@mi) {
455 $part_content_type=$1; $part_content_type =~ tr/A-Z/a-z/;
456 $part_content_info=$2;
457 }
458 my $filename="";
459 if ($part_header =~ m@name=\"?([\w\.\-\\/]+)\"?@mis) {
460 $filename=$1;
461 }
462
463 # disposition - either inline or attachment.
464 # NOT CURRENTLY USED - we display all text types instead...
465 # $part_header =~ /^content\-disposition:\s*([\w+])/mis;
466
467 # add <<attachment>> to each part except the first...
468 if ($text ne "") {
469 $text.="\n<p><hr><strong>&lt;&lt;attachment&gt;&gt;</>";
470 # add part info header
471 $text.="<br>Type: $part_content_type<br>\n";
472 if ($filename ne "") {
473 $text.="Filename: $filename\n";
474 }
475 $text.="</strong></p>\n";
476 }
477
478 if ($part_content_type =~ m@text/@)
479 {
480 my $part_text=text_from_part($message_part);
481 if ($part_content_type !~ m@text/(ht|x)ml@) {
482 $part_text=text_into_html($part_text);
483 }
484 if ($part_text eq "") {
485 $part_text='&lt;&lt;empty message&gt;&gt;';
486 }
487 $text.=$part_text;
488 } elsif ($part_content_type =~ m@message/rfc822@) {
489 # This is a forwarded message
490 my $message_part_headers=$part_body;
491 $message_part_headers =~ s/\r?\n[\t\ ]+/ /gs; #unfold
492 $message_part_headers=~s/\r?\n\r?\n(.*)$//s;
493 my $message_part_body=$1;
494
495 my $rfc822_formatted_body=""; # put result in here
496 if ($message_part_headers =~
497 /^content\-type:\s*([\w\/\-]+)\s*\;?\s*?([^\s]+)?\s*$/ims)
498 {
499 # The message header uses MIME flags
500 my $message_content_type=$1;
501 my $message_content_info=$2;
502 if (!defined($message_content_info)) {
503 $message_content_info="";
504 }
505 $message_content_type =~ tr/A-Z/a-z/;
506 if ($message_content_type =~ /multipart/) {
507 $rfc822_formatted_body=
508 text_from_mime_message($message_content_type,
509 $message_content_info,
510 $message_part_body,
511 $outhandle);
512 } else {
513 $message_part_body=text_from_part($part_body);
514 $rfc822_formatted_body=text_into_html($message_part_body);
515 }
516 } else {
517 # message doesn't use MIME flags
518 $rfc822_formatted_body=text_into_html($message_part_body);
519 }
520 # Add the returned text to the output
521 # don't put all the headers...
522 $message_part_headers =~ s/^(X\-.*|received|message\-id|return\-path):.*\n//img;
523 $text.=text_into_html($message_part_headers);
524 $text.="<p>\n";
525 $text.=$rfc822_formatted_body;
526 # end of message/rfc822
527 } elsif ($part_content_type =~ /multipart/) {
528 # recurse again
529 $tmptext=text_from_mime_message($part_content_type,
530 $part_content_info,
531 $part_body,
532 $outhandle);
533 $text.=$tmptext;
534 } elsif ($text eq "") {
535 # we can't do anything with this part, but if it's the first
536 # part then make sure it is mentioned..
537
538 $text.="\n<p><hr><strong>&lt;&lt;attachment&gt;&gt;</>";
539 # add part info header
540 $text.="<br>Type: $part_content_type<br>\n";
541 if ($filename ne "") {
542 $text.="Filename: $filename\n";
543 }
544 $text.="</strong></p>\n";
545 }
546 } # foreach message part.
547 } else {
548 # we can't handle this multipart type (not mixed or alternative)
549 # the RFC also mentions "parallel".
550 }
551 } # end of multipart
552 return $text;
553}
554
555
556
557
558
559
560# Process a MIME part. Return "" if we can't decode it.
561sub text_from_part {
562 my $text=shift;
563 my $part_header=$text;
564 # check for empty part header (leading blank line)
565 if ($text =~ /^\s*\r?\n/) {
566 $part_header="Content-type: text/plain; charset=us-ascii";
567 } else {
568 $part_header =~ s/\r?\n\r?\n(.*)$//s;
569 $text=$1; if (!defined($text)) {$text="";}
570 }
571 $part_header =~ s/\r?\n[\t ]+/ /gs; #unfold
572 $part_header =~ /content\-type:\s*([\w\/]+).*?charset=\"?([^\;\"\s]+)\"?/is;
573 my $type=$1;
574 my $charset=$2;
575 if (!defined($type)) {$type="";}
576 if (!defined($charset)) {$charset="ascii";}
577 my $encoding="";
578 if ($part_header =~ /^content\-transfer\-encoding:\s*([^\s]+)/mis) {
579 $encoding=$1; $encoding=~tr/A-Z/a-z/;
580 }
581 # Content-Transfer-Encoding is per-part
582 if ($encoding ne "") {
583 if ($encoding =~ /quoted\-printable/) {
584 $text=qp_decode($text);
585 } elsif ($encoding =~ /base64/) {
586 $text=base64_decode($text);
587 } elsif ($encoding !~ /[78]bit/) { # leave 7/8 bit as is.
588 # rfc2045 also allows binary, which we ignore (for now).
589 # maybe this shouldn't go to stderr, but anyway...
590 print STDERR "EMAILPlug: unknown encoding: $encoding\n";
591 return "";
592 }
593 }
594 if ($type eq "text/html") {
595 # only get stuff between <body> tags, or <html> tags.
596 $text =~ s@^.*<html[^>]*>@@is;
597 $text =~ s@</html>.*$@@is;
598 $text =~ s/^.*?<body[^>]*>//si;
599 $text =~ s/<\/body>.*$//si;
600 }
601 elsif ($type eq "text/xml") {
602 $text=~s/</&lt;/g;$text=~s/>/&gt;/g;
603 $text="<pre>\n$text\n</pre>\n";
604 }
605 # convert to unicode
606 # first get our character encoding name in the right form.
607 $charset=~tr/A-Z/a-z/;
608 $charset=~s/\-/_/g;
609 if ($charset ne "us_ascii" && $charset ne "ascii") {
610 $charset=~s/gb2312/gb/;
611 # assumes EUC-KR, not ISO-2022 !?
612 $charset=~s/ks_c_5601_1987/korean/;
613 my @unicode_array=&unicode::convert2unicode($charset,\$text);
614 my $utf8_text=&unicode::unicode2utf8(@unicode_array);
615 $text=$utf8_text;
616 }
617 return $text;
618}
619
620
621# decode quoted-printable text
622sub qp_decode {
623 my $text=shift;
624
625 my @lines=split('\n', $text);
626
627 # if a line ends with "=\s*", it is a soft line break, otherwise
628 # keep in any newline characters.
629 foreach my $line (@lines) {
630 if ($line =~ s/=\s*$//) {}
631 else {$line.="\n";}
632
633 if ($line =~ /=[0-9A-Fa-f]{2}/) { # it contains an escaped char
634 my @hexcode_segments=split('=',$line);
635 shift @hexcode_segments;
636 my @hexcodes;
637 foreach my $hexcode (@hexcode_segments) {
638 $hexcode =~ s/^(..).*$/$1/; # only need first 2 chars
639 chomp($hexcode); # just in case...
640 my $char=chr (hex "0x$hexcode");
641 $line =~ s/=$hexcode/$char/g;
642 }
643 }
644 }
645 $text= join('', @lines);
646 return $text;
647}
648
649# decode base64 text. This is fairly slow (since it's interpreted perl rather
650# than compiled XS stuff like in the ::MIME modules, but this is more portable
651# for us at least).
652# see rfc2045 for description, but basically, bits 7 and 8 are set to zero;
653# 4 bytes of encoded text become 3 bytes of binary - remove 2 highest bits
654# from each encoded byte.
655
656
657sub base64_decode {
658 my $enc_text = shift;
659# A=>0, B=>1, ..., '+'=>62, '/'=>63
660# also '=' is used for padding at the end, but we remove it anyway.
661 my $mimechars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
662# map each MIME char into it's value, for more efficient lookup.
663 my %index;
664 map { $index{$_} = index ($mimechars, $_) } (split ('', $mimechars));
665# remove all non-base64 chars. eval to get variable in transliteration...
666# also remove '=' - we'll assume (!!) that there are no errors in the encoding
667 eval "\$enc_text =~ tr|$mimechars||cd";
668 my $decoded="";
669 while (length ($enc_text)>3)
670 {
671 my $fourchars=substr($enc_text,0,4,"");
672 my @chars=(split '',$fourchars);
673 $decoded.=chr( $index{$chars[0]} << 2 | $index{$chars[1]} >> 4);
674 $decoded.=chr( ($index{$chars[1]} & 15) << 4 | $index{$chars[2]} >> 2);
675 $decoded.=chr( ($index{$chars[2]} & 3 ) << 6 | $index{$chars[3]});
676 }
677# if there are any input chars left, there are either
678# 2 encoded bytes (-> 1 raw byte) left or 3 encoded (-> 2 raw) bytes left.
679 my @chars=(split '',$enc_text);
680 if (length($enc_text)) {
681 $decoded.=chr($index{$chars[0]} << 2 | (int $index{$chars[1]} >> 4));
682 }
683 if (length($enc_text)==3) {
684 $decoded.=chr( ($index{$chars[1]} & 15) << 4 | $index{$chars[2]} >> 2);
685 }
686 return $decoded;
687}
688
689
690# Perl packages have to return true if they are run.
6911;
Note: See TracBrowser for help on using the repository browser.