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

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

oops - left off a '$' at end of a pattern match.

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