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

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

oops - left a debugging statement in there.

  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
File size: 21.6 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 # this isn't quite right yet regarding spaces between encoded-texts
172 # (see examples, section 8. of rfc).
173 while ($encoded =~ s/(.*?)=\?([^\?]*)\?([bq])\?([^\?]+)\?=\s*//i) {
174 my ($charset, $encoding, $data)=($2,$3,$4);
175 my $decoded_data;
176 $value.="$1"; # any leading chars
177 $data=~s/^\s*//; $data=~s/\s*$//; # strip whitespace from ends
178 chomp $data;
179 $encoding =~ tr/BQ/bq/;
180 if ($encoding eq "q") { # quoted printable
181 $data =~ s/_/\ /g; # from rfc2047 (sec 4.2.2)
182 $decoded_data=qp_decode($data);
183 } else { # base 64
184 $decoded_data=base64_decode($data);
185 }
186 if (defined($charset)) {
187 $charset=~tr/A-Z/a-z/;
188 $charset=~s/\-/_/g;
189 $charset=~s/gb2312/gb/;
190 # assumes EUC-KR, not ISO-2022 !?
191 $charset=~s/ks_c_5601_1987/korean/;
192 } else {$charset="ascii";}
193 if ($charset eq "ascii" || $charset eq "us_ascii") {
194 # technically possible to have this explicitly...
195 $value.=$decoded_data;
196 } else {
197 my $utf8_text=&unicode::unicode2utf8
198 (
199 &unicode::convert2unicode($charset,\$decoded_data)
200 );
201 $value.=$utf8_text;
202 }
203 } # end of while loop
204 $value.=$encoded; # get any trailing characters
205 if ($value =~ /^\s*$/) { # we couldn't extract anything...
206 $value=original_value;
207 }
208 } # end of if =?...?=
209
210 # Store the metadata
211 $raw{$name} = $value;
212 }
213
214 # Extract the name and e-mail address from the From metadata
215 $frommeta = $raw{"From"};
216 my $fromnamemeta;
217 my $fromaddrmeta;
218
219 $frommeta =~ s/\s*$//; # Remove trailing space, if any
220
221 if ($frommeta =~ m/(.+)\s*<(.+)>/) {
222 $fromnamemeta=$1;
223 $fromaddrmeta=$2;
224 } elsif ($frommeta =~ m/(.+@.+)\s+\((.*)\)/) {
225 $fromnamemeta=$2;
226 $fromaddrmeta=$1;
227 }
228 if (!defined($fromaddrmeta)) {
229 $fromaddrmeta=$frommeta;
230 }
231 $fromaddrmeta=~s/<//; $fromaddrmeta=~s/>//;
232 # minor attempt to prevent spam-bots from harvesting addresses...
233 $fromaddrmeta=~s/@/&#64;/;
234 $doc_obj->add_utf8_metadata ($cursection, "FromAddr", $fromaddrmeta);
235
236 if (defined($fromnamemeta)) {
237 $fromnamemeta =~ s/\"//g;
238 }
239 else {
240 $fromnamemeta = $fromaddrmeta;
241 }
242 # if name is an address
243 $fromnamemeta =~ s/<//g; $fromnamemeta =~ s/>//g;
244 $fromnamemeta=~s/@/&#64\;/;
245 $doc_obj->add_utf8_metadata ($cursection, "FromName", $fromnamemeta);
246
247 # Escape < and > in the whole From field;
248 $raw{"From"}=$frommeta;
249
250 # Process Date information
251 if ($raw{"Date"} !~ /No Date/) {
252 $raw{"DateText"} = $raw{"Date"};
253
254 # Convert the date text to internal date format
255 $value = $raw{"Date"};
256 my ($day, $month, $year) = $value =~ /(\d?\d)\s([A-Z][a-z][a-z])\s(\d\d\d?\d?)/;
257 if ($year < 100) { $year += 1900; }
258 $raw{"Date"} = &sorttools::format_date($day, $month, $year);
259
260 } else {
261 # We have not extracted a date
262 $raw{"DateText"} = "Unknown.";
263 $raw{"Date"} = "19000000";
264 }
265
266 # Add extracted metadata to document object
267 foreach my $name (keys %raw) {
268 $value = $raw{$name};
269 if ($value) {
270 # assume subject, etc headers have no special HTML meaning.
271 $value =~ s@&@&amp\;@g;
272 $value =~ s/</&lt;/g; $value =~ s/>/&gt;/g;
273 $value = &text_into_html($value);
274 # escape [] so it isn't re-interpreted as metadata
275 $value =~ s/\[/&#91;/g; $value =~ s/\]/&#93;/g;
276 } else {
277 $value = "No $name field";
278 }
279 $doc_obj->add_utf8_metadata ($cursection, $name, $value);
280 }
281
282 my $mimetype="text/plain";
283 my $mimeinfo="";
284 # Do MIME and encoding stuff
285 if ($Headers =~ /^content\-type:\s*([\w\/\-]+)\s*\;?\s*(.+?)\s*$/mi)
286 {
287 $mimetype=$1;
288 $mimetype =~ tr/[A-Z]/[a-z]/;
289 $mimeinfo=$2;
290 }
291
292 my $transfer_encoding="7bit";
293 if ($Headers =~ /^content-transfer-encoding:\s*([^\s]+)\s*$/mi) {
294 $transfer_encoding=$1;
295 }
296 if ($mimetype ne "text/plain") {
297 $$textref=text_from_mime_message($mimetype,$mimeinfo,$$textref,
298 $outhandle);
299 } elsif ($transfer_encoding =~ /quoted\-printable/) {
300 $$textref=qp_decode($$textref);
301 } elsif ($transfer_encoding =~ /base64/) {
302 $$textref=base64_decode($$textref);
303 }
304
305
306 # Add "All headers" metadata
307 $Headers = &text_into_html($Headers);
308 $Headers =~ s/&([lg])t\;/&amp\;$1t\;/g;
309
310 $Headers = "No headers" unless ($Headers =~ /\w/);
311 $Headers =~ s/@/&#64\;/g;
312 # escape [] so it isn't re-interpreted as metadata
313 $Headers =~ s/\[/&#91;/g; $Headers =~ s/\]/&#93;/g;
314
315 $doc_obj->add_utf8_metadata ($cursection, "Headers", $Headers);
316
317 # Add text to document object
318 if ($mimetype eq "text/plain") {
319 $$textref = &text_into_html($$textref);
320 }
321 $$textref = "No message" unless ($$textref =~ /\w/);
322 $doc_obj->add_utf8_text($cursection, $$textref);
323
324 return 1;
325}
326
327
328# Convert a text string into HTML.
329#
330# The HTML is going to be inserted into a GML file, so
331# we have to be careful not to use symbols like ">",
332# which ocurs frequently in email messages (and use
333# &gt instead.
334#
335# This function also turns links and email addresses into hyperlinks,
336# and replaces carriage returns with <BR> tags (and multiple carriage
337# returns with <P> tags).
338
339
340sub text_into_html {
341 my ($text) = @_;
342
343 # Convert problem characters into HTML symbols
344 $text =~ s/&/&amp;/go;
345 $text =~ s/</&lt;/go;
346 $text =~ s/>/&gt;/go;
347 $text =~ s/\"/&quot;/go;
348
349 # convert email addresses and URIs into links
350# don't markup email addresses for now
351# $text =~ s/([\w\d\.\-]+@[\w\d\.\-]+)/<a href=\"mailto:$1\">$1<\/a>/g;
352
353 # assume hostnames are \.\w\- only, then might have a trailing '/.*'
354 # assume URI doesn't finish with a '.'
355 $text =~ s@((http|ftp|https)://[\w\-]+(\.[\w\-]+)*/?((&amp;|\.)?[\w\?\=\-_/~]+)*)@<a href=\"$1\">$1<\/a>@g;
356
357
358 # Clean up whitespace and convert \n charaters to <BR> or <P>
359 $text =~ s/ +/ /go;
360 $text =~ s/\s*$//o;
361 $text =~ s/^\s*//o;
362 $text =~ s/\n/\n<BR>/go;
363 $text =~ s/<BR>\s*<BR>/<P>/go;
364
365 return $text;
366}
367
368
369
370
371#Process a MIME message.
372# the textref we are given DOES NOT include the header.
373sub text_from_mime_message {
374 my ($mimetype,$mimeinfo,$text,$outhandle)=(@_);
375
376 # Check for multiparts - $mimeinfo will be a boundary
377 if ($mimetype =~ /multipart/) {
378 $boundary="";
379 if ($mimeinfo =~ m@boundary=(\"[^\"]+\"|[^\s]+)\s*$@im) {
380 $boundary=$1;
381 if ($boundary =~ m@^\"@) {
382 $boundary =~ s@^\"@@; $boundary =~ s@\"$@@;
383 }
384 } else {
385 print $outhandle "EMAILPlug: (warning) couldn't parse MIME boundary\n";
386 }
387 # parts start with "--$boundary"
388 # message ends with "--$boundary--"
389 # RFC says boundary is <70 chars, [A-Za-z'()+_,-./:=?], so escape any
390 # that perl might want to interpolate. Also allows spaces...
391 $boundary=~s/\\/\\\\/g;
392 $boundary=~s/([\?\+\.\(\)\:\/\'])/\\$1/g;
393 my @message_parts = split("\r?\n\-\-$boundary", "\n$text");
394 # remove first "part" and last "part" (final --)
395 shift @message_parts;
396 my $last=pop @message_parts;
397 # if our boundaries are a bit dodgy and we only found 1 part...
398 if (!defined($last)) {$last="";}
399 # make sure it is only -- and whitespace
400 if ($last !~ /^\-\-\s*$/ms) {
401 print $outhandle "EMAILPlug: (warning) last part of MIME message isn't empty\n";
402 }
403 foreach my $message_part (@message_parts) {
404 # remove the leading newline left from split.
405 $message_part=~s/^\r?\n//;
406 }
407 if ($mimetype eq "multipart/alternative") {
408 # check for an HTML version first, then TEXT, otherwise use first.
409 my $part_text="";
410 foreach my $message_part (@message_parts) {
411 if ($message_part =~ m@\s*content\-type:\s*text/html@mis)
412 {
413 # Use the HTML version
414 $part_text=text_from_part($message_part);
415 $mimetype="text/html";
416 last;
417 }
418 }
419 if ($part_text eq "") { # try getting a text part instead
420 foreach my $message_part (@message_parts) {
421 if ($message_part =~ m@^content\-type:\s*text/plain@mis)
422 {
423 # Use the plain version
424 $part_text=text_from_part($message_part);
425 if ($part_text =~/[^\s]/) {
426 $part_text="<pre>".$part_text."</pre>";
427 }
428 $mimetype="text/plain";
429 last;
430 }
431 }
432 }
433 if ($part_text eq "") { # use first part
434 $part_text=text_from_part(shift @message_parts);
435 }
436 if ($part_text eq "") { # we couldn't get anything!!!
437 # or it was an empty message...
438 # do nothing...
439 print $outhandle "EMAILPlug: no text - empty body?\n";
440 } else {
441 $text=$part_text;
442 }
443 } elsif ($mimetype =~ m@multipart/(mixed|digest|related)@) {
444 $text="";
445 foreach my $message_part (@message_parts) {
446 my $part_header=$message_part;
447 my $part_body;
448 if ($message_part=~ /^\s*\n/) {
449 # no header... use defaults
450 $part_body=$message_part;
451 $part_header="Content-type: text/plain; charset=us-ascii";
452 } elsif ($part_header=~s/\r?\n\r?\n(.*)$//sg) {
453 $part_body=$1;
454 } else {
455 # something's gone wrong...
456 $part_header="";
457 $part_body=$message_part;
458 }
459
460 $part_header =~ s/\r?\n[\t\ ]+/ /gs; #unfold
461 my $part_content_type="";
462 my $part_content_info="";
463 if ($mimetype eq "multipart/digest") {
464 # default type - RTFRFC!!
465 $part_content_type="message/rfc822";
466 }
467 if ($part_header =~ m@^content\-type:\s*([\w+/\-]+)\s*\;?\s*([^\s]*)@mi) {
468 $part_content_type=$1; $part_content_type =~ tr/A-Z/a-z/;
469 $part_content_info=$2;
470 }
471 my $filename="";
472 if ($part_header =~ m@name=\"?([\w\.\-\\/]+)\"?@mis) {
473 $filename=$1;
474 }
475
476 # disposition - either inline or attachment.
477 # NOT CURRENTLY USED - we display all text types instead...
478 # $part_header =~ /^content\-disposition:\s*([\w+])/mis;
479
480 # add <<attachment>> to each part except the first...
481 if ($text ne "") {
482 $text.="\n<p><hr><strong>&lt;&lt;attachment&gt;&gt;</>";
483 # add part info header
484 $text.="<br>Type: $part_content_type<br>\n";
485 if ($filename ne "") {
486 $text.="Filename: $filename\n";
487 }
488 $text.="</strong></p>\n";
489 }
490
491 if ($part_content_type =~ m@text/@)
492 {
493 my $part_text=text_from_part($message_part);
494 if ($part_content_type !~ m@text/(ht|x)ml@) {
495 $part_text=text_into_html($part_text);
496 }
497 if ($part_text eq "") {
498 $part_text='&lt;&lt;empty message&gt;&gt;';
499 }
500 $text.=$part_text;
501 } elsif ($part_content_type =~ m@message/rfc822@) {
502 # This is a forwarded message
503 my $message_part_headers=$part_body;
504 $message_part_headers =~ s/\r?\n[\t\ ]+/ /gs; #unfold
505 $message_part_headers=~s/\r?\n\r?\n(.*)$//s;
506 my $message_part_body=$1;
507
508 my $rfc822_formatted_body=""; # put result in here
509 if ($message_part_headers =~
510 /^content\-type:\s*([\w\/\-]+)\s*\;?\s*?([^\s]+)?\s*$/ims)
511 {
512 # The message header uses MIME flags
513 my $message_content_type=$1;
514 my $message_content_info=$2;
515 if (!defined($message_content_info)) {
516 $message_content_info="";
517 }
518 $message_content_type =~ tr/A-Z/a-z/;
519 if ($message_content_type =~ /multipart/) {
520 $rfc822_formatted_body=
521 text_from_mime_message($message_content_type,
522 $message_content_info,
523 $message_part_body,
524 $outhandle);
525 } else {
526 $message_part_body=text_from_part($part_body);
527 $rfc822_formatted_body=text_into_html($message_part_body);
528 }
529 } else {
530 # message doesn't use MIME flags
531 $rfc822_formatted_body=text_into_html($message_part_body);
532 }
533 # Add the returned text to the output
534 # don't put all the headers...
535 $message_part_headers =~ s/^(X\-.*|received|message\-id|return\-path):.*\n//img;
536 $text.=text_into_html($message_part_headers);
537 $text.="<p>\n";
538 $text.=$rfc822_formatted_body;
539 # end of message/rfc822
540 } elsif ($part_content_type =~ /multipart/) {
541 # recurse again
542 $tmptext=text_from_mime_message($part_content_type,
543 $part_content_info,
544 $part_body,
545 $outhandle);
546 $text.=$tmptext;
547 } elsif ($text eq "") {
548 # we can't do anything with this part, but if it's the first
549 # part then make sure it is mentioned..
550
551 $text.="\n<p><hr><strong>&lt;&lt;attachment&gt;&gt;</>";
552 # add part info header
553 $text.="<br>Type: $part_content_type<br>\n";
554 if ($filename ne "") {
555 $text.="Filename: $filename\n";
556 }
557 $text.="</strong></p>\n";
558 }
559 } # foreach message part.
560 } else {
561 # we can't handle this multipart type (not mixed or alternative)
562 # the RFC also mentions "parallel".
563 }
564 } # end of multipart
565 return $text;
566}
567
568
569
570
571
572
573# Process a MIME part. Return "" if we can't decode it.
574sub text_from_part {
575 my $text=shift;
576 my $part_header=$text;
577 # check for empty part header (leading blank line)
578 if ($text =~ /^\s*\r?\n/) {
579 $part_header="Content-type: text/plain; charset=us-ascii";
580 } else {
581 $part_header =~ s/\r?\n\r?\n(.*)$//s;
582 $text=$1; if (!defined($text)) {$text="";}
583 }
584 $part_header =~ s/\r?\n[\t ]+/ /gs; #unfold
585 $part_header =~ /content\-type:\s*([\w\/]+).*?charset=\"?([^\;\"\s]+)\"?/is;
586 my $type=$1;
587 my $charset=$2;
588 if (!defined($type)) {$type="";}
589 if (!defined($charset)) {$charset="ascii";}
590 my $encoding="";
591 if ($part_header =~ /^content\-transfer\-encoding:\s*([^\s]+)/mis) {
592 $encoding=$1; $encoding=~tr/A-Z/a-z/;
593 }
594 # Content-Transfer-Encoding is per-part
595 if ($encoding ne "") {
596 if ($encoding =~ /quoted\-printable/) {
597 $text=qp_decode($text);
598 } elsif ($encoding =~ /base64/) {
599 $text=base64_decode($text);
600 } elsif ($encoding !~ /[78]bit/) { # leave 7/8 bit as is.
601 # rfc2045 also allows binary, which we ignore (for now).
602 # maybe this shouldn't go to stderr, but anyway...
603 print STDERR "EMAILPlug: unknown encoding: $encoding\n";
604 return "";
605 }
606 }
607 if ($type eq "text/html") {
608 # only get stuff between <body> tags, or <html> tags.
609 $text =~ s@^.*<html[^>]*>@@is;
610 $text =~ s@</html>.*$@@is;
611 $text =~ s/^.*?<body[^>]*>//si;
612 $text =~ s/<\/body>.*$//si;
613 }
614 elsif ($type eq "text/xml") {
615 $text=~s/</&lt;/g;$text=~s/>/&gt;/g;
616 $text="<pre>\n$text\n</pre>\n";
617 }
618 # convert to unicode
619 # first get our character encoding name in the right form.
620 $charset=~tr/A-Z/a-z/;
621 $charset=~s/\-/_/g;
622 if ($charset ne "us_ascii" && $charset ne "ascii") {
623 $charset=~s/gb2312/gb/;
624 # assumes EUC-KR, not ISO-2022 !?
625 $charset=~s/ks_c_5601_1987/korean/;
626 my @unicode_array=&unicode::convert2unicode($charset,\$text);
627 my $utf8_text=&unicode::unicode2utf8(@unicode_array);
628 $text=$utf8_text;
629 }
630 return $text;
631}
632
633
634# decode quoted-printable text
635sub qp_decode {
636 my $text=shift;
637
638 my @lines=split('\n', $text);
639
640 # if a line ends with "=\s*", it is a soft line break, otherwise
641 # keep in any newline characters.
642 foreach my $line (@lines) {
643 if ($line =~ s/=\s*$//) {}
644 else {$line.="\n";}
645
646 if ($line =~ /=[0-9A-Fa-f]{2}/) { # it contains an escaped char
647 my @hexcode_segments=split('=',$line);
648 shift @hexcode_segments;
649 my @hexcodes;
650 foreach my $hexcode (@hexcode_segments) {
651 $hexcode =~ s/^(..).*$/$1/; # only need first 2 chars
652 chomp($hexcode); # just in case...
653 my $char=chr (hex "0x$hexcode");
654 $line =~ s/=$hexcode/$char/g;
655 }
656 }
657 }
658 $text= join('', @lines);
659 return $text;
660}
661
662# decode base64 text. This is fairly slow (since it's interpreted perl rather
663# than compiled XS stuff like in the ::MIME modules, but this is more portable
664# for us at least).
665# see rfc2045 for description, but basically, bits 7 and 8 are set to zero;
666# 4 bytes of encoded text become 3 bytes of binary - remove 2 highest bits
667# from each encoded byte.
668
669
670sub base64_decode {
671 my $enc_text = shift;
672# A=>0, B=>1, ..., '+'=>62, '/'=>63
673# also '=' is used for padding at the end, but we remove it anyway.
674 my $mimechars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
675# map each MIME char into it's value, for more efficient lookup.
676 my %index;
677 map { $index{$_} = index ($mimechars, $_) } (split ('', $mimechars));
678# remove all non-base64 chars. eval to get variable in transliteration...
679# also remove '=' - we'll assume (!!) that there are no errors in the encoding
680 eval "\$enc_text =~ tr|$mimechars||cd";
681 my $decoded="";
682 while (length ($enc_text)>3)
683 {
684 my $fourchars=substr($enc_text,0,4,"");
685 my @chars=(split '',$fourchars);
686 $decoded.=chr( $index{$chars[0]} << 2 | $index{$chars[1]} >> 4);
687 $decoded.=chr( ($index{$chars[1]} & 15) << 4 | $index{$chars[2]} >> 2);
688 $decoded.=chr( ($index{$chars[2]} & 3 ) << 6 | $index{$chars[3]});
689 }
690# if there are any input chars left, there are either
691# 2 encoded bytes (-> 1 raw byte) left or 3 encoded (-> 2 raw) bytes left.
692 my @chars=(split '',$enc_text);
693 if (length($enc_text)) {
694 $decoded.=chr($index{$chars[0]} << 2 | (int $index{$chars[1]} >> 4));
695 }
696 if (length($enc_text)==3) {
697 $decoded.=chr( ($index{$chars[1]} & 15) << 4 | $index{$chars[2]} >> 2);
698 }
699 return $decoded;
700}
701
702
703# Perl packages have to return true if they are run.
7041;
Note: See TracBrowser for help on using the repository browser.