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

Last change on this file since 2886 was 2886, checked in by jrm21, 22 years ago

Fixed some encoding issues - need to convert to utf-8 after un-base64ing
or un-quoted-printabling.

  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
File size: 22.5 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 $self->convert2unicode($charset, \$decoded_data);
194 $value .= $decoded_data;
195 } # end of while loop
196
197 # get any trailing characters
198 $self->convert2unicode("iso_8859_1", \$encoded);
199 $value.=$encoded;
200
201 if ($value =~ /^\s*$/) { # we couldn't extract anything...
202 $self->convert2unicode("iso_8859_1", \$original_value);
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 = &text_into_html($value);
269 # escape [] so it isn't re-interpreted as metadata
270 $value =~ s/\[/&#91;/g; $value =~ s/\]/&#93;/g;
271 } else {
272 $value = "No $name field";
273 }
274 $doc_obj->add_utf8_metadata ($cursection, $name, $value);
275 }
276
277 my $mimetype="text/plain";
278 my $mimeinfo="";
279 my $charset = "iso_8859_1";
280 # Do MIME and encoding stuff
281 if ($Headers =~ /^content\-type:\s*([\w\/\-]+)\s*\;?\s*(.+?)\s*$/mi)
282 {
283 $mimetype=$1;
284 $mimetype =~ tr/[A-Z]/[a-z]/;
285 $mimeinfo=$2;
286 if ($mimeinfo =~ /charset=\"([^\"]+)\"/) {
287 $charset = $1;
288 }
289 }
290
291 my $transfer_encoding="7bit";
292 if ($Headers =~ /^content-transfer-encoding:\s*([^\s]+)\s*$/mi) {
293 $transfer_encoding=$1;
294 }
295 if ($mimetype eq "text/html") {
296 $$textref= $self->text_from_part("$Headers\n$$textref");
297 } elsif ($mimetype ne "text/plain") {
298 $$textref= $self->text_from_mime_message($mimetype,$mimeinfo,$$textref,
299 $outhandle);
300 } elsif ($transfer_encoding =~ /quoted\-printable/) {
301 $$textref=qp_decode($$textref);
302 $self->convert2unicode($charset, $textref);
303 } elsif ($transfer_encoding =~ /base64/) {
304 $$textref=base64_decode($$textref);
305 $self->convert2unicode($charset, $textref);
306 } else {
307 $self->convert2unicode($charset, $textref);
308 }
309
310
311 # Add "All headers" metadata
312 $Headers = &text_into_html($Headers);
313
314 $Headers = "No headers" unless ($Headers =~ /\w/);
315 $Headers =~ s/@/&#64\;/g;
316 # escape [] so it isn't re-interpreted as metadata
317 $Headers =~ s/\[/&#91;/g; $Headers =~ s/\]/&#93;/g;
318
319 $doc_obj->add_utf8_metadata ($cursection, "Headers", $Headers);
320
321 # Add text to document object
322 if ($mimetype eq "text/plain") {
323 $$textref = &text_into_html($$textref);
324 }
325 $$textref = "No message" unless ($$textref =~ /\w/);
326 $doc_obj->add_utf8_text($cursection, $$textref);
327
328 return 1;
329}
330
331
332# Convert a text string into HTML.
333#
334# The HTML is going to be inserted into a GML file, so
335# we have to be careful not to use symbols like ">",
336# which ocurs frequently in email messages (and use
337# &gt instead.
338#
339# This function also turns links and email addresses into hyperlinks,
340# and replaces carriage returns with <BR> tags (and multiple carriage
341# returns with <P> tags).
342
343
344sub text_into_html {
345 my ($text) = @_;
346
347 # Convert problem characters into HTML symbols
348 $text =~ s/&/&amp;/go;
349 $text =~ s/</&lt;/go;
350 $text =~ s/>/&gt;/go;
351 $text =~ s/\"/&quot;/go;
352
353 # convert email addresses and URIs into links
354# don't markup email addresses for now
355# $text =~ s/([\w\d\.\-]+@[\w\d\.\-]+)/<a href=\"mailto:$1\">$1<\/a>/g;
356
357 # assume hostnames are \.\w\- only, then might have a trailing '/.*'
358 # assume URI doesn't finish with a '.'
359 $text =~ s@((http|ftp|https)://[\w\-]+(\.[\w\-]+)*/?((&amp;|\.)?[\w\?\=\-_/~]+)*)@<a href=\"$1\">$1<\/a>@g;
360
361
362 # Clean up whitespace and convert \n charaters to <BR> or <P>
363 $text =~ s/ +/ /go;
364 $text =~ s/\s*$//o;
365 $text =~ s/^\s*//o;
366 $text =~ s/\n/\n<BR>/go;
367 $text =~ s/<BR>\s*<BR>/<P>/go;
368
369 return $text;
370}
371
372
373
374
375#Process a MIME message.
376# the textref we are given DOES NOT include the header.
377sub text_from_mime_message {
378 my $self = shift(@_);
379 my ($mimetype,$mimeinfo,$text,$outhandle)=(@_);
380
381 # Check for multiparts - $mimeinfo will be a boundary
382 if ($mimetype =~ /multipart/) {
383 $boundary="";
384 if ($mimeinfo =~ m@boundary=(\"[^\"]+\"|[^\s]+)\s*$@im) {
385 $boundary=$1;
386 if ($boundary =~ m@^\"@) {
387 $boundary =~ s@^\"@@; $boundary =~ s@\"$@@;
388 }
389 } else {
390 print $outhandle "EMAILPlug: (warning) couldn't parse MIME boundary\n";
391 }
392 # parts start with "--$boundary"
393 # message ends with "--$boundary--"
394 # RFC says boundary is <70 chars, [A-Za-z'()+_,-./:=?], so escape any
395 # that perl might want to interpolate. Also allows spaces...
396 $boundary=~s/\\/\\\\/g;
397 $boundary=~s/([\?\+\.\(\)\:\/\'])/\\$1/g;
398 my @message_parts = split("\r?\n\-\-$boundary", "\n$text");
399 # remove first "part" and last "part" (final --)
400 shift @message_parts;
401 my $last=pop @message_parts;
402 # if our boundaries are a bit dodgy and we only found 1 part...
403 if (!defined($last)) {$last="";}
404 # make sure it is only -- and whitespace
405 if ($last !~ /^\-\-\s*$/ms) {
406 print $outhandle "EMAILPlug: (warning) last part of MIME message isn't empty\n";
407 }
408 foreach my $message_part (@message_parts) {
409 # remove the leading newline left from split.
410 $message_part=~s/^\r?\n//;
411 }
412 if ($mimetype eq "multipart/alternative") {
413 # check for an HTML version first, then TEXT, otherwise use first.
414 my $part_text="";
415 foreach my $message_part (@message_parts) {
416 if ($message_part =~ m@\s*content\-type:\s*text/html@mis)
417 {
418 # Use the HTML version
419 $part_text= $self->text_from_part($message_part);
420 $mimetype="text/html";
421 last;
422 }
423 }
424 if ($part_text eq "") { # try getting a text part instead
425 foreach my $message_part (@message_parts) {
426 if ($message_part =~ m@^content\-type:\s*text/plain@mis)
427 {
428 # Use the plain version
429 $part_text= $self->text_from_part($message_part);
430 if ($part_text =~/[^\s]/) {
431 $part_text="<pre>".$part_text."</pre>";
432 }
433 $mimetype="text/plain";
434 last;
435 }
436 }
437 }
438 if ($part_text eq "") { # use first part
439 $part_text= $self->text_from_part(shift @message_parts);
440 }
441 if ($part_text eq "") { # we couldn't get anything!!!
442 # or it was an empty message...
443 # do nothing...
444 print $outhandle "EMAILPlug: no text - empty body?\n";
445 } else {
446 $text=$part_text;
447 }
448 } elsif ($mimetype =~ m@multipart/(mixed|digest|related)@) {
449 $text="";
450 foreach my $message_part (@message_parts) {
451 my $part_header=$message_part;
452 my $part_body;
453 if ($message_part=~ /^\s*\n/) {
454 # no header... use defaults
455 $part_body=$message_part;
456 $part_header="Content-type: text/plain; charset=us-ascii";
457 } elsif ($part_header=~s/\r?\n\r?\n(.*)$//sg) {
458 $part_body=$1;
459 } else {
460 # something's gone wrong...
461 $part_header="";
462 $part_body=$message_part;
463 }
464
465 $part_header =~ s/\r?\n[\t\ ]+/ /gs; #unfold
466 my $part_content_type="";
467 my $part_content_info="";
468 if ($mimetype eq "multipart/digest") {
469 # default type - RTFRFC!!
470 $part_content_type="message/rfc822";
471 }
472 if ($part_header =~ m@^content\-type:\s*([\w+/\-]+)\s*\;?\s*(.*?)\s*$@mi) {
473 $part_content_type=$1; $part_content_type =~ tr/A-Z/a-z/;
474 $part_content_info=$2;
475 }
476 my $filename="";
477 if ($part_header =~ m@name=\"?([\w\.\-\\/]+)\"?@mis) {
478 $filename=$1;
479 }
480
481 # disposition - either inline or attachment.
482 # NOT CURRENTLY USED - we display all text types instead...
483 # $part_header =~ /^content\-disposition:\s*([\w+])/mis;
484
485 # add <<attachment>> to each part except the first...
486 if ($text ne "") {
487 $text.="\n<p><hr><strong>&lt;&lt;attachment&gt;&gt;</>";
488 # add part info header
489 $text.="<br>Type: $part_content_type<br>\n";
490 if ($filename ne "") {
491 $text.="Filename: $filename\n";
492 }
493 $text.="</strong></p>\n";
494 }
495
496 if ($part_content_type =~ m@text/@)
497 {
498 my $part_text= $self->text_from_part($message_part);
499 if ($part_content_type !~ m@text/(ht|x)ml@) {
500 $part_text=text_into_html($part_text);
501 }
502 if ($part_text eq "") {
503 $part_text='&lt;&lt;empty message&gt;&gt;';
504 }
505 $text.=$part_text;
506 } elsif ($part_content_type =~ m@message/rfc822@) {
507 # This is a forwarded message
508 my $message_part_headers=$part_body;
509 $message_part_headers =~ s/\r?\n[\t\ ]+/ /gs; #unfold
510 $message_part_headers=~s/\r?\n\r?\n(.*)$//s;
511 my $message_part_body=$1;
512
513 my $rfc822_formatted_body=""; # put result in here
514 if ($message_part_headers =~
515 /^content\-type:\s*([\w\/\-]+)\s*\;?\s*(.*?)\s*$/ims)
516 {
517 # The message header uses MIME flags
518 my $message_content_type=$1;
519 my $message_content_info=$2;
520 if (!defined($message_content_info)) {
521 $message_content_info="";
522 }
523 $message_content_type =~ tr/A-Z/a-z/;
524 if ($message_content_type =~ /multipart/) {
525 $rfc822_formatted_body=
526 $self->text_from_mime_message($message_content_type,
527 $message_content_info,
528 $message_part_body,
529 $outhandle);
530 } else {
531 $message_part_body= $self->text_from_part($part_body);
532 $rfc822_formatted_body=text_into_html($message_part_body);
533 }
534 } else {
535 # message doesn't use MIME flags
536 $rfc822_formatted_body=text_into_html($message_part_body);
537 }
538 # Add the returned text to the output
539 # don't put all the headers...
540 $message_part_headers =~ s/^(X\-.*|received|message\-id|return\-path):.*\n//img;
541 $text.=text_into_html($message_part_headers);
542 $text.="<p>\n";
543 $text.=$rfc822_formatted_body;
544 # end of message/rfc822
545 } elsif ($part_content_type =~ /multipart/) {
546 # recurse again
547
548 $tmptext= $self->text_from_mime_message($part_content_type,
549 $part_content_info,
550 $part_body,
551 $outhandle);
552 $text.=$tmptext;
553 } elsif ($text eq "") {
554 # we can't do anything with this part, but if it's the first
555 # part then make sure it is mentioned..
556
557 $text.="\n<p><hr><strong>&lt;&lt;attachment&gt;&gt;</>";
558 # add part info header
559 $text.="<br>Type: $part_content_type<br>\n";
560 if ($filename ne "") {
561 $text.="Filename: $filename\n";
562 }
563 $text.="</strong></p>\n";
564 }
565 } # foreach message part.
566 } else {
567 # we can't handle this multipart type (not mixed or alternative)
568 # the RFC also mentions "parallel".
569 }
570 } # end of ($mimetype !~ multipart)
571 else {
572 # we don't do any processing of the content.
573 }
574
575 return $text;
576}
577
578
579
580
581
582
583# Process a MIME part. Return "" if we can't decode it.
584sub text_from_part {
585 my $self = shift(@_);
586 my $text=shift;
587 my $part_header=$text;
588 # check for empty part header (leading blank line)
589 if ($text =~ /^\s*\r?\n/) {
590 $part_header="Content-type: text/plain; charset=us-ascii";
591 } else {
592 $part_header =~ s/\r?\n\r?\n(.*)$//s;
593 $text=$1; if (!defined($text)) {$text="";}
594 }
595 $part_header =~ s/\r?\n[\t ]+/ /gs; #unfold
596 $part_header =~ /content\-type:\s*([\w\/]+).*?charset=\"?([^\;\"\s]+)\"?/is;
597 my $type=$1;
598 my $charset=$2;
599 if (!defined($type)) {$type="";}
600 if (!defined($charset)) {$charset="ascii";}
601 my $encoding="";
602 if ($part_header =~ /^content\-transfer\-encoding:\s*([^\s]+)/mis) {
603 $encoding=$1; $encoding=~tr/A-Z/a-z/;
604 }
605 # Content-Transfer-Encoding is per-part
606 if ($encoding ne "") {
607 if ($encoding =~ /quoted\-printable/) {
608 $text=qp_decode($text);
609 } elsif ($encoding =~ /base64/) {
610 $text=base64_decode($text);
611 } elsif ($encoding !~ /[78]bit/) { # leave 7/8 bit as is.
612 # rfc2045 also allows binary, which we ignore (for now).
613 # maybe this shouldn't go to stderr, but anyway...
614 print STDERR "EMAILPlug: unknown encoding: $encoding\n";
615 return "";
616 }
617 }
618 if ($type eq "text/html") {
619 # only get stuff between <body> tags, or <html> tags.
620 $text =~ s@^.*<html[^>]*>@@is;
621 $text =~ s@</html>.*$@@is;
622 $text =~ s/^.*?<body[^>]*>//si;
623 $text =~ s/<\/body>.*$//si;
624 }
625 elsif ($type eq "text/xml") {
626 $text=~s/</&lt;/g;$text=~s/>/&gt;/g;
627 $text="<pre>\n$text\n</pre>\n";
628 }
629 # convert to unicode
630 $self->convert2unicode($charset, \$text);
631 return $text;
632}
633
634
635# decode quoted-printable text
636sub qp_decode {
637 my $text=shift;
638
639 my @lines=split('\n', $text);
640
641 # if a line ends with "=\s*", it is a soft line break, otherwise
642 # keep in any newline characters.
643 foreach my $line (@lines) {
644 if ($line !~ s/=\s*$//) {$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
702sub convert2unicode {
703 my $self = shift(@_);
704 my ($charset, $textref) = @_;
705
706 # first get our character encoding name in the right form.
707 $charset = "iso_8859_1" unless defined $charset;
708 $charset=~tr/A-Z/a-z/;
709 $charset=~s/\-/_/g;
710 $charset=~s/gb2312/gb/;
711 # assumes EUC-KR, not ISO-2022 !?
712 $charset=~s/ks_c_5601_1987/korean/;
713
714 # It appears that we can't always trust ascii text so we'll treat it
715 # as iso-8859-1 (letting characters above 0x80 through without
716 # converting them to utf-8 will result in invalid XML documents
717 # which can't be parsed at build time).
718 $charset = "iso_8859_1" if ($charset eq "us_ascii" || $charset eq "ascii");
719
720 $$textref=&unicode::unicode2utf8(&unicode::convert2unicode($charset,$textref));
721}
722
723
724# Perl packages have to return true if they are run.
7251;
Note: See TracBrowser for help on using the repository browser.