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

Last change on this file since 10121 was 9971, checked in by jrm21, 19 years ago

text_from_part now takes an optional parameter with the part's headers.
tidied in a few places.

  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
File size: 34.7 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-2002 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 (optional, not stored by default)
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# $Title made up of Subject, Date and Sender (for default formatting)
52#
53#
54# John McPherson - June/July 2001
55# added (basic) MIME support and quoted-printable and base64 decodings.
56# Minor fixes for names that are actually email addresses (ie <...> was lost)
57#
58# See: * RFC 822 - ARPA Internet Text Messages
59# * RFC 2045 - Multipurpose Internet Mail Extensions (MIME) -part1
60# * RFC 2046 - MIME (part 2) Media Types (and multipart messages)
61# * RFC 2047 - MIME (part 3) Message Header Extensions
62# * RFC 1806 - Content Dispositions (ie inline/attachment)
63
64# 12/05/02 Added usage datastructure - John Thompson
65
66use strict;
67no strict "refs"; # so we can use a variable as a filehandle for print $out
68
69package EMAILPlug;
70
71use SplitPlug;
72# EMAILPlug is a sub-class of SplitPlug.
73@EMAILPlug::ISA = ('SplitPlug');
74
75use unicode; # gs conv functions
76use gsprintf 'gsprintf'; # translations
77
78use sorttools;
79use util;
80
81
82
83my $arguments =
84 [ { 'name' => "process_exp",
85 'desc' => "{BasPlug.process_exp}",
86 'type' => "regexp",
87 'reqd' => "no",
88 'deft' => &get_default_process_exp() },
89 { 'name' => "no_attachments",
90 'desc' => "{EMAILPlug.no_attachments}",
91 'type' => "flag",
92 'reqd' => "no" },
93 { 'name' => "headers",
94 'desc' => "{EMAILPlug.headers}",
95 'type' => "flag",
96 'reqd' => "no" },
97 { 'name' => "split_exp",
98 'desc' => "{EMAILPlug.split_exp}",
99 'type' => "regexp",
100 'reqd' => "no",
101 'deft' => &get_default_split_exp() }
102 ];
103
104my $options = { 'name' => "EMAILPlug",
105 'desc' => "{EMAILPlug.desc}",
106 'abstract' => "no",
107 'inherits' => "yes",
108 'args' => $arguments };
109
110# Create a new EMAILPlug object with which to parse a file.
111# Accomplished by creating a new BasPlug and using bless to
112# turn it into an EMAILPlug.
113
114sub new {
115 my ($class) = @_;
116 my $self = new BasPlug ($class, @_);
117 $self->{'plugin_type'} = "EMAILPlug";
118 # 14-05-02 To allow for proper inheritance of arguments - John Thompson
119 my $option_list = $self->{'option_list'};
120 push( @{$option_list}, $options );
121
122 if (!parsargv::parse(\@_,
123 q^split_exp/.*/^, \$self->{'split_exp'},
124 q^no_attachments^, \$self->{'ignore_attachments'},
125 q^headers^, \$self->{'header_metadata'},
126 "allow_extra_options")) {
127 print STDERR "\nIncorrect options passed to $class.";
128 print STDERR "\nCheck your collect.cfg configuration file\n";
129 $self->print_txt_usage(""); # Use default resource bundle
130 die "\n";
131 }
132 $self->{'assoc_filenames'} = {}; # to save attach names so we don't clobber
133
134 # this might not actually be true at read-time, but after processing
135 # it should all be utf8.
136 $self->{'input_encoding'}="utf8";
137 return bless $self, $class;
138}
139
140sub get_default_process_exp {
141 my $self = shift (@_);
142 # mbx/email for mailbox file format, \d+ for maildir (each message is
143 # in a separate file, with a unique number for filename)
144 # mozilla and IE will save individual mbx format files with a ".eml" ext.
145 return q@([\\/]\d+|\.(mbx|email|eml))$@;
146}
147
148# This plugin splits the mbox mail files at lines starting with From<sp>
149# It is supposed to be "\n\nFrom ", but this isn't always used.
150# add \d{4} so that the line ends in a year (in case the text has an
151# unescaped "From " at the start of a line).
152sub get_default_split_exp {
153 return q^\nFrom .*\d{4}\n^;
154
155}
156
157
158# do plugin specific processing of doc_obj
159sub process {
160
161 my $self = shift (@_);
162 my ($textref, $pluginfo, $base_dir, $file, $metadata, $doc_obj, $gli) = @_;
163 my $outhandle = $self->{'outhandle'};
164
165 # Check that we're dealing with a valid mail file
166 # mbox message files start with "From "
167 # maildir messages usually start with Return-Path and Delivered-To
168 # mh is very similar to maildir
169 my $startoffile=substr($$textref,0,256);
170 if (($startoffile !~ /^(From )/) &&
171 ($startoffile !~ /^(From|To|Envelope.*|Received|Return-Path|Date|Subject|Content\-.*|MIME-Version|Forwarded):/im)) {
172 return undef;
173 }
174
175
176 print STDERR "<Processing n='$file' p='EMAILPlug'>\n" if ($gli);
177
178 gsprintf($outhandle, "EMAILPlug: {common.processing} $file\n")
179 if $self->{'verbosity'} > 1;
180
181 my $cursection = $doc_obj->get_top_section();
182
183 #
184 # Parse the document's text and extract metadata
185 #
186
187 # Protect backslashes
188 $$textref =~ s@\\@\\\\@g;
189
190 # Separate header from body of message
191 my $Headers = $$textref;
192 $Headers =~ s/\r?\n\r?\n(.*)$//s;
193 $$textref = $1;
194 $Headers .= "\n";
195
196 # Unfold headers - see rfc822
197 $Headers =~ s/\r?\n[\t\ ]+/ /gs;
198 # Extract basic metadata from header
199 my @headers = ("From", "To", "Subject", "Date");
200 my %raw;
201 foreach my $name (@headers) {
202 $raw{$name} = "No $name value";
203 }
204
205 # Get a default encoding for the header - RFC says should be ascii...
206 my $default_header_encoding="iso_8859_1";
207
208 # We don't know what character set is the user's default...
209 # We could use textcat to guess... for now we'll look at mime content-type
210# if ($Headers =~ /([[:^ascii:]])/) {
211# }
212 if ($Headers =~ /^Content\-type:.*charset=\"?([a-z0-9\-_]+)/mi) {
213 $default_header_encoding=$1;
214 $default_header_encoding =~ s@\-@_@g;
215 $default_header_encoding =~ tr/A-Z/a-z/;
216 }
217
218
219 # Examine each line of the headers
220 my ($line, $name, $value);
221 my @parts;
222 foreach $line (split(/\n/, $Headers)) {
223
224 # Ignore lines with no content or which begin with whitespace
225 next unless ($line =~ /:/);
226 next if ($line =~ /^\s/);
227
228 # Find out what metadata is on this line
229 @parts = split(/:/, $line);
230 $name = shift @parts;
231 # get fieldname in canonical form - first cap, then lower case.
232 $name =~ tr/A-Z/a-z/;
233 # uppercase the first character according to the current locale
234 $name=~s/(.+)/\u$1/;
235 next unless $name;
236 next unless ($raw{$name});
237
238 # Find the value of that metadata
239 $value = join(":", @parts);
240 $value =~ s/^\s+//;
241 $value =~ s/\s+$//;
242 # decode headers if stored using =?<charset>?[BQ]?<data>?= (rfc2047)
243 if ($value =~ /=\?.*\?[BbQq]\?.*\?=/) {
244 my $original_value=$value;
245 my $encoded=$value;
246 $value="";
247 # we should ignore spaces between consecutive encoded-texts
248 $encoded =~ s@\?=\s+=\?@\?==\?@g;
249 while ($encoded =~ s/(.*?)=\?([^\?]*)\?([bq])\?([^\?]+)\?=//i) {
250 my ($charset, $encoding, $data)=($2,$3,$4);
251 my ($decoded_data);
252 $value.="$1"; # any leading chars
253 $data=~s/^\s*//; $data=~s/\s*$//; # strip whitespace from ends
254 chomp $data;
255 $encoding =~ tr/BQ/bq/;
256 if ($encoding eq "q") { # quoted printable
257 $data =~ s/_/\ /g; # from rfc2047 (sec 4.2.2)
258 $decoded_data=qp_decode($data);
259 # qp_decode adds \n, which is default for body text
260 chomp($decoded_data);
261 } else { # base 64
262 $decoded_data=base64_decode($data);
263 }
264 $self->convert2unicode($charset, \$decoded_data);
265 $value .= $decoded_data;
266 } # end of while loop
267
268 # get any trailing characters
269 $self->convert2unicode($default_header_encoding, \$encoded);
270 $value.=$encoded;
271
272 if ($value =~ /^\s*$/) { # we couldn't extract anything...
273 $self->convert2unicode($default_header_encoding,
274 \$original_value);
275 $value=$original_value;
276 }
277 } # end of if =?...?=
278
279 # In the absense of other charset information, assume the
280 # header is the default (usually "iso_8859_1") and convert to unicode.
281 else {
282 $self->convert2unicode($default_header_encoding, \$value);
283 }
284
285 # Store the metadata
286 $value =~ s@_@\\_@g; # protect against GS macro language
287 $raw{$name} = $value;
288 }
289
290 # Extract the name and e-mail address from the From metadata
291 my $frommeta = $raw{"From"};
292 my $fromnamemeta;
293 my $fromaddrmeta;
294
295 $frommeta =~ s/\s*$//; # Remove trailing space, if any
296
297 if ($frommeta =~ m/(.+)\s*<(.+)>/) {
298 $fromnamemeta=$1;
299 $fromaddrmeta=$2;
300 } elsif ($frommeta =~ m/(.+@.+)\s+\((.*)\)/) {
301 $fromnamemeta=$2;
302 $fromaddrmeta=$1;
303 }
304 if (!defined($fromaddrmeta)) {
305 $fromaddrmeta=$frommeta;
306 }
307 $fromaddrmeta=~s/<//; $fromaddrmeta=~s/>//;
308 # minor attempt to prevent spam-bots from harvesting addresses...
309 $fromaddrmeta=~s/@/&#64;/;
310
311 $doc_obj->add_utf8_metadata ($cursection, "FromAddr", $fromaddrmeta);
312
313 if (defined($fromnamemeta) && $fromnamemeta) { # must be > 0 long
314 $fromnamemeta =~ s/\"//g; # remove quotes
315 $fromnamemeta =~ s/\s+$//; # remove trailing whitespace
316 }
317 else {
318 $fromnamemeta = $fromaddrmeta;
319 }
320 # if name is an address
321 $fromnamemeta =~ s/<//g; $fromnamemeta =~ s/>//g;
322 $fromnamemeta=~s/@/&#64\;/;
323 $doc_obj->add_utf8_metadata ($cursection, "FromName", $fromnamemeta);
324
325 $raw{"From"}=$frommeta;
326
327 # Process Date information
328 if ($raw{"Date"} !~ /No Date/) {
329 $raw{"DateText"} = $raw{"Date"};
330
331 # Convert the date text to internal date format
332 $value = $raw{"Date"};
333 my ($day, $month, $year) = $value =~ /(\d?\d)\s([A-Z][a-z][a-z])\s(\d\d\d?\d?)/;
334 # make some assumptions about the year formatting...
335 # some (old) software thinks 2001 is 101, some think 2001 is 01
336 if ($year < 20) { $year += 2000; } # assume not really 1920...
337 elsif ($year < 150) { $year += 1900; } # assume not really 2150...
338 $raw{"Date"} = &sorttools::format_date($day, $month, $year);
339
340 } else {
341 # We have not extracted a date
342 $raw{"DateText"} = "Unknown.";
343 $raw{"Date"} = "19000000";
344 }
345
346 # Add extracted metadata to document object
347 foreach my $name (keys %raw) {
348 $value = $raw{$name};
349 if ($value) {
350 # assume subject, etc headers have no special HTML meaning.
351 $value = &text_into_html($value);
352 # escape [] so it isn't re-interpreted as metadata
353 $value =~ s/\[/&#91;/g; $value =~ s/\]/&#93;/g;
354 } else {
355 $value = "No $name field";
356 }
357 $doc_obj->add_utf8_metadata ($cursection, $name, $value);
358 }
359
360
361 # extract a message ID from the headers, if there is one, and we'll use
362 # that as the greenstone doc ID. Having a predictable ID means we can
363 # link to other messages, eg from In-Reply-To or References headers...
364 if ($Headers =~ m@^Message-ID:(.+)$@mi) {
365 my $id=escape_msg_id($1);
366 $doc_obj->{'msgid'}=$id;
367 }
368 # link to another message, if this is a reply
369 if ($Headers =~ m@^In-Reply-To:(.+)$@mi) {
370 my $id=escape_msg_id($1);
371 $doc_obj->add_utf8_metadata ($cursection, 'InReplyTo', $id);
372 } elsif ($Headers =~ m@^References:.*\s([^\s]+)$@mi) {
373 # References can have multiple, get the last one
374 my $id=escape_msg_id($1);
375 # not necessarily in-reply-to, but same thread...
376 $doc_obj->add_utf8_metadata ($cursection, 'InReplyTo', $id);
377 }
378
379
380
381 my $mimetype="text/plain";
382 my $mimeinfo="";
383 my $charset = $default_header_encoding;
384 # Do MIME and encoding stuff. Allow \s in mimeinfo in case there is
385 # more than one parameter given to Content-type.
386 # eg: Content-type: text/plain; charset="us-ascii"; format="flowed"
387 if ($Headers =~ m@^content\-type:\s*([\w\.\-/]+)\s*(\;\s*.+)?\s*$@mi)
388 {
389 $mimetype=$1;
390 $mimetype =~ tr/[A-Z]/[a-z]/;
391
392 if ($mimetype eq "text") { # for pre-RFC2045 messages (c. 1996)
393 $mimetype = "text/plain";
394 }
395
396 $mimeinfo=$2;
397 if (!defined $mimeinfo) {
398 $mimeinfo="";
399 } else { # strip leading and trailing stuff
400 $mimeinfo =~ s/^\;\s*//;
401 $mimeinfo =~ s/\s*$//;
402 }
403 if ($mimeinfo =~ /charset=\"([^\"]+)\"/i) {
404 $charset = $1;
405 }
406 }
407
408 my $transfer_encoding="7bit";
409 if ($Headers =~ /^content-transfer-encoding:\s*([^\s]+)\s*$/mi) {
410 $transfer_encoding=$1;
411 }
412
413 if ($mimetype eq "text/html") {
414 $$textref= $self->text_from_part($$textref, $Headers);
415 } elsif ($mimetype ne "text/plain") {
416 $self->{'doc_obj'} = $doc_obj; # in case we need to associate files...
417 $$textref=$self->text_from_mime_message($mimetype,$mimeinfo,$$textref);
418 } else { # mimetype eq text/plain
419
420 if ($transfer_encoding =~ /quoted\-printable/) {
421 $$textref=qp_decode($$textref);
422 } elsif ($transfer_encoding =~ /base64/) {
423 $$textref=base64_decode($$textref);
424 }
425 $self->convert2unicode($charset, $textref);
426
427 $$textref = &text_into_html($$textref);
428 $$textref =~ s@_@\\_@g; # protect against GS macro language
429
430 }
431
432
433 if ($self->{'header_metadata'} && $self->{'header_metadata'} == 1) {
434 # Add "All headers" metadata
435 $Headers = &text_into_html($Headers);
436
437 $Headers = "No headers" unless ($Headers =~ /\w/);
438 $Headers =~ s/@/&#64\;/g;
439 # escape [] so it isn't re-interpreted as metadata
440 $Headers =~ s/\[/&#91;/g; $Headers =~ s/\]/&#93;/g;
441 $self->convert2unicode($charset, \$Headers);
442
443 $Headers =~ s@_@\\_@g; # protect against GS macro language
444 $doc_obj->add_utf8_metadata ($cursection, "Headers", $Headers);
445 }
446
447
448 # Add Title metadata
449 my $Title = text_into_html($raw{'Subject'});
450 $Title .= "<br>From: " . text_into_html($fromnamemeta);
451 $Title .= "<br>Date: " . text_into_html($raw{'DateText'});
452 $Title =~ s/\[/&#91;/g; $Title =~ s/\]/&#93;/g;
453
454 $doc_obj->add_utf8_metadata ($cursection, "Title", $Title);
455
456 # Add FileFormat metadata
457 $doc_obj->add_metadata($cursection, "FileFormat", "EMAIL");
458
459 # Add text to document object
460 $$textref = "No message" unless ($$textref =~ /\w/);
461
462 $doc_obj->add_utf8_text($cursection, $$textref);
463
464 return 1;
465}
466
467
468# Convert a text string into HTML.
469#
470# The HTML is going to be inserted into a GML file, so
471# we have to be careful not to use symbols like ">",
472# which ocurs frequently in email messages (and use
473# &gt instead.
474#
475# This function also turns links and email addresses into hyperlinks,
476# and replaces carriage returns with <BR> tags (and multiple carriage
477# returns with <P> tags).
478
479
480sub text_into_html {
481 my ($text) = @_;
482
483 # Convert problem characters into HTML symbols
484 $text =~ s/&/&amp;/g;
485 $text =~ s/</&lt;/g;
486 $text =~ s/>/&gt;/g;
487 $text =~ s/\"/&quot;/g;
488
489 # convert email addresses and URIs into links
490# don't markup email addresses for now
491# $text =~ s/([\w\d\.\-]+@[\w\d\.\-]+)/<a href=\"mailto:$1\">$1<\/a>/g;
492
493 # try to munge email addresses a little bit...
494 $text =~ s/@/&#64;/;
495 # assume hostnames are \.\w\- only, then might have a trailing '/.*'
496 # assume URI doesn't finish with a '.'
497 $text =~ s@((http|ftp|https)://[\w\-]+(\.[\w\-]+)*/?((&amp;|\.)?[\w\?\=\-_/~]+)*(\#[\w\.\-_]*)?)@<a href=\"$1\">$1<\/a>@g;
498
499
500 # Clean up whitespace and convert \n charaters to <BR> or <P>
501 $text =~ s/ +/ /g;
502 $text =~ s/\s*$//g;
503 $text =~ s/^\s*//g;
504 $text =~ s/\n/\n<br>/g;
505 $text =~ s/<br>\s*<br>/<p>/gi;
506
507 return $text;
508}
509
510
511
512
513#Process a MIME message.
514# the textref we are given DOES NOT include the header.
515sub text_from_mime_message {
516 my $self = shift(@_);
517 my ($mimetype,$mimeinfo,$text)=(@_);
518 my $outhandle=$self->{'outhandle'};
519 # Check for multiparts - $mimeinfo will be a boundary
520 if ($mimetype =~ /multipart/) {
521 my $boundary="";
522 if ($mimeinfo =~ m@boundary=(\"[^\"]+\"|[^\s]+)\s*$@im) {
523 $boundary=$1;
524 if ($boundary =~ m@^\"@) {
525 $boundary =~ s@^\"@@; $boundary =~ s@\"$@@;
526 }
527 } else {
528 print $outhandle "EMAILPlug: (warning) couldn't parse MIME boundary\n";
529 }
530 # parts start with "--$boundary"
531 # message ends with "--$boundary--"
532 # RFC says boundary is <70 chars, [A-Za-z'()+_,-./:=?], so escape any
533 # that perl might want to interpolate. Also allows spaces...
534 $boundary=~s/\\/\\\\/g;
535 $boundary=~s/([\?\+\.\(\)\:\/\'])/\\$1/g;
536 my @message_parts = split("\r?\n\-\-$boundary", "\n$text");
537 # remove first "part" and last "part" (final --)
538 shift @message_parts;
539 my $last=pop @message_parts;
540 # if our boundaries are a bit dodgy and we only found 1 part...
541 if (!defined($last)) {$last="";}
542 # make sure it is only -- and whitespace
543 if ($last !~ /^\-\-\s*$/ms) {
544 print $outhandle "EMAILPlug: (warning) last part of MIME message isn't empty\n";
545 }
546 foreach my $message_part (@message_parts) {
547 # remove the leading newline left from split.
548 $message_part=~s/^\r?\n//;
549 }
550 if ($mimetype eq "multipart/alternative") {
551 # check for an HTML version first, then TEXT, otherwise use first.
552 my $part_text="";
553 foreach my $message_part (@message_parts) {
554 if ($message_part =~ m@\s*content\-type:\s*text/html@mis)
555 {
556 # Use the HTML version
557 $part_text= $self->text_from_part($message_part);
558 $mimetype="text/html";
559 last;
560 }
561 }
562 if ($part_text eq "") { # try getting a text part instead
563 foreach my $message_part (@message_parts) {
564 if ($message_part =~ m@^content\-type:\s*text/plain@mis)
565 {
566 # Use the plain version
567 $part_text= $self->text_from_part($message_part);
568 if ($part_text =~/[^\s]/) {
569 $part_text = text_into_html($part_text);
570 }
571 $mimetype="text/plain";
572 last;
573 }
574 }
575 }
576 if ($part_text eq "") { #use first part (no html/text part found)
577 $part_text = $self->text_from_part(shift @message_parts);
578 $part_text = text_into_html($part_text);
579 }
580 if ($part_text eq "") { # we couldn't get anything!!!
581 # or it was an empty message...
582 # do nothing...
583 gsprintf($outhandle, "{BasPlug.empty_file} - empty body?\n");
584 } else {
585 $text = $part_text;
586 }
587 } elsif ($mimetype =~ m@multipart/(mixed|digest|related|signed)@) {
588 $text = "";
589 # signed is for PGP/GPG messages... the last part is a hash
590 if ($mimetype =~ m@multipart/signed@) {
591 pop @message_parts;
592 }
593 my $is_first_part=1;
594 foreach my $message_part (@message_parts) {
595 if ($is_first_part && $text ne "") {$is_first_part=0;}
596
597 if ($mimetype eq "multipart/digest") {
598 # default type - RTFRFC!! Set if not already set
599 $message_part =~ m@^(.*)\n\r?\n@s;
600 my $part_header=$1;
601 if ($part_header !~ m@^content-type@mi) {
602 $message_part="Content-type: message/rfc822\n"
603 . $message_part; # prepend default type
604 }
605 }
606
607 $text .= $self->process_multipart_part($message_part,
608 $is_first_part);
609 } # foreach message part.
610 } else {
611 # we can't handle this multipart type (not mixed or alternative)
612 # the RFC also mentions "parallel".
613 }
614 } # end of ($mimetype =~ multipart)
615 elsif ($mimetype =~ m@message/rfc822@) {
616 my $msg_header = $text;
617 $msg_header =~ s/\r?\n\r?\n(.*)$//s;
618 $text = $1;
619
620 if ($msg_header =~ /^content\-type:\s*([\w\.\-\/]+)\s*\;?\s*(.+?)\s*$/mi)
621 {
622 $mimetype=$1;
623 $mimeinfo=$2;
624 $mimetype =~ tr/[A-Z]/[a-z]/;
625
626 my $msg_text;
627 if ($mimetype =~ m@multipart/@) {
628 $msg_text = text_from_mime_message($self, $mimetype, $mimeinfo,
629 $text);
630 } else {
631 $msg_text=$self->text_from_part($text,$msg_header);
632 }
633
634 my $brief_header=text_into_html(get_brief_headers($msg_header));
635 $text= "\n<b>&lt;&lt;attached message&gt;&gt;</b><br>";
636 $text.= "<table><tr><td width=\"5%\"> </td>\n";
637 $text.="<td>" . $brief_header . "\n</p>" . $msg_text
638 . "</td></tr></table>";
639 }
640 } else {
641 # we don't do any processing of the content.
642 }
643
644 return $text;
645}
646
647
648
649# used for turning a message id into a more friendly string for greenstone
650sub escape_msg_id {
651#msgid
652 my $id=shift;
653 chomp $id; $id =~ s!\s!!g; # remove spaces
654 $id =~ s![<>\[\]]!!g; # remove [ ] < and >
655 $id =~ s![_&]!-!g; # replace symbols that might cause problems
656 $id =~ s!@!-!g; # replace @ symbol, to avoid spambots
657 return $id;
658}
659
660
661
662sub process_multipart_part {
663 my $self = shift;
664 my $message_part = shift;
665 my $is_first_part = shift;
666
667 my $return_text="";
668 my $part_header=$message_part;
669 my $part_body;
670 if ($message_part=~ /^\s*\n/) {
671 # no header... use defaults
672 $part_body=$message_part;
673 $part_header="Content-type: text/plain; charset=us-ascii";
674 } elsif ($part_header=~s/\r?\n\r?\n(.*)$//s) {
675 $part_body=$1;
676 } else {
677 # something's gone wrong...
678 $part_header="";
679 $part_body=$message_part;
680 }
681
682 $part_header =~ s/\r?\n[\t\ ]+/ /gs; #unfold
683 my $part_content_type="";
684 my $part_content_info="";
685
686 if ($part_header =~ m@^content\-type:\s*([\w\.\-/]+)\s*(\;.*)?$@mi) {
687 $part_content_type=$1; $part_content_type =~ tr/A-Z/a-z/;
688 $part_content_info=$2;
689 if (!defined($part_content_info)) {
690 $part_content_info="";
691 } else {
692 $part_content_info =~ s/^\;\s*//;
693 $part_content_info =~ s/\s*$//;
694 }
695 }
696 my $filename="";
697 if ($part_header =~ m@name=\"?([^\"\n]+)\"?@mis) {
698 $filename=$1;
699 $filename =~ s@\r?\s*$@@; # remove trailing space, if any
700 }
701
702 # disposition - either inline or attachment.
703 # NOT CURRENTLY USED - we display all text types instead...
704 # $part_header =~ /^content\-disposition:\s*([\w+])/mis;
705
706 # add <<attachment>> to each part except the first...
707 if (!$is_first_part) {
708 $return_text.="\n<p><hr><strong>&lt;&lt;attachment&gt;&gt;";
709 # add part info header
710 my $header_text="<br>Type: $part_content_type<br>\n";
711 if ($filename ne "") {
712 $header_text.="Filename: $filename\n";
713 }
714 $header_text =~ s@_@\\_@g;
715 $return_text.=$header_text . "</strong></p>\n<p>\n";
716 }
717
718 if ($part_content_type =~ m@text/@)
719 {
720 my $part_text= $self->text_from_part($message_part);
721 if ($part_content_type !~ m@text/(ht|x)ml@) {
722 $part_text = text_into_html($part_text);
723 }
724 if ($part_text eq "") {
725 $part_text = ' ';
726 }
727 $return_text .= $part_text;
728 } elsif ($part_content_type =~ m@message/rfc822@) {
729 # This is a forwarded message
730 my $message_part_headers=$part_body;
731 $message_part_headers=~s/\r?\n\r?\n(.*)$//s;
732 my $message_part_body=$1;
733 $message_part_headers =~ s/\r?\n[\t\ ]+/ /gs; #unfold
734
735 my $rfc822_formatted_body=""; # put result in here
736 if ($message_part_headers =~
737 /^content\-type:\s*([\w\.\-\/]+)\s*(\;.*)?$/ims)
738 {
739 # The message header uses MIME flags
740 my $message_content_type=$1;
741 my $message_content_info=$2;
742 if (!defined($message_content_info)) {
743 $message_content_info="";
744 } else {
745 $message_content_info =~ s/^\;\s*//;
746 $message_content_info =~ s/\s*$//;
747 }
748 $message_content_type =~ tr/A-Z/a-z/;
749 if ($message_content_type =~ /multipart/) {
750 $rfc822_formatted_body=
751 $self->text_from_mime_message($message_content_type,
752 $message_content_info,
753 $message_part_body);
754 } else {
755 $message_part_body=$self->text_from_part($part_body,
756 $message_part_headers);
757 $rfc822_formatted_body=text_into_html($message_part_body);
758 }
759 } else {
760 # message doesn't use MIME flags
761 $rfc822_formatted_body=text_into_html($message_part_body);
762 $rfc822_formatted_body =~ s@_@\\_@g;
763 }
764 # Add the returned text to the output
765 # don't put all the headers...
766# $message_part_headers =~ s/^(X\-.*|received|message\-id|return\-path):.*\n//img;
767 my $brief_headers=get_brief_headers($message_part_headers);
768 $return_text.=text_into_html($brief_headers);
769 $return_text.="</p><p>\n";
770 $return_text.=$rfc822_formatted_body;
771 $return_text.="</p>\n";
772 # end of message/rfc822
773 } elsif ($part_content_type =~ /multipart/) {
774 # recurse again
775
776 my $tmptext= $self->text_from_mime_message($part_content_type,
777 $part_content_info,
778 $part_body);
779 $return_text.=$tmptext;
780 } else {
781 # this part isn't text/* or another message...
782 if ($is_first_part) {
783 # this is the first part of a multipart, or only part!
784 $return_text="\n<p><hr><strong>&lt;&lt;attachment&gt;&gt;";
785 # add part info header
786 my $header_text="<br>Type: $part_content_type<br>\n";
787 $header_text.="Filename: $filename</strong></p>\n<p>\n";
788 $header_text =~ s@_@\\_@g;
789 $return_text.=$header_text;
790 }
791
792 # save attachment by default
793 if (!$self->{'ignore_attachments'}
794 && $filename ne "") { # this part has a file...
795 my $encoding="8bit";
796 if ($part_header =~
797 /^content-transfer-encoding:\s*(\w+)/mi ) {
798 $encoding=$1; $encoding =~ tr/A-Z/a-z/;
799 }
800 my $tmpdir=$ENV{'GSDLHOME'} . "/tmp";
801 my $save_filename=$filename;
802
803 # make sure we don't clobber files with same name;
804 # need to keep state between .mbx files
805 my $assoc_files=$self->{'assoc_filenames'};
806 if ($assoc_files->{$filename}) { # it's been set...
807 $assoc_files->{$filename}++;
808 $filename =~ m/(.+)\.(\w+)$/;
809 my ($filestem, $ext)=($1,$2);
810 $save_filename="${filestem}_"
811 . $assoc_files->{$filename} . ".$ext";
812 } else { # first file with this name
813 $assoc_files->{$filename}=1;
814 }
815 open (SAVE, ">$tmpdir/$save_filename") ||
816 warn "EMAILPlug: Can't save attachment as $tmpdir/$save_filename: $!";
817 my $part_text = $message_part;
818 $part_text =~ s/(.*?)\r?\n\r?\n//s; # remove header
819 if ($encoding eq "base64") {
820 print SAVE base64_decode($part_text);
821 } elsif ($encoding eq "quoted-printable") {
822 print SAVE qp_decode($part_text);
823 } else { # 7bit, 8bit, binary, etc...
824 print SAVE $part_text;
825 }
826 close SAVE;
827 my $doc_obj=$self->{'doc_obj'};
828 $doc_obj->associate_file("$tmpdir/$save_filename",
829 "$save_filename",
830 $part_content_type # mimetype
831 );
832 # clean up tmp area...
833 # Can't do this as it hasn't been copied/linked yet!!!
834# &util::rm("$tmpdir/$save_filename");
835 my $outhandle=$self->{'outhandle'};
836 print $outhandle "EMAILPlug: saving attachment \"$filename\"\n"; #
837
838 # be nice if "download" was a translatable macro :(
839 $return_text .="<a href=\"_httpdocimg_/$save_filename\">download</a>";
840 } # end of save attachment
841 } # end of !text/message part
842
843
844 return $return_text;
845}
846
847
848# Return only the "important" headers from a set of message headers
849sub get_brief_headers {
850 my $msg_header = shift;
851 my $brief_header = "";
852
853 # Order matters!
854 if ($msg_header =~ /^(From:.*)$/im) {$brief_header.="$1\n";}
855 if ($msg_header =~ /^(To:.*)$/im) {$brief_header.="$1\n";}
856 if ($msg_header =~ /^(Cc:.*)$/im) {$brief_header.="$1\n";}
857 if ($msg_header =~ /^(Subject:.*)$/im) {$brief_header.="$1\n";}
858 if ($msg_header =~ /^(Date:.*)$/im) {$brief_header.="$1\n";}
859
860 return $brief_header;
861}
862
863
864# Process a MIME part. Return "" if we can't decode it.
865# should only be called for parts with type "text/*" ?
866# Either pass the entire mime part (including the part's header),
867# or pass the mime part's text and optionally the part's header.
868sub text_from_part {
869 my $self = shift;
870 my $text = shift || '';
871 my $part_header = shift;
872
873 my $type="text/plain"; # default, overridden from part header
874 my $charset="ascii"; # default, overridden from part header
875
876 if (! $part_header) { # no header argument was given. check the body
877 $part_header = $text;
878 # check for empty part header (leading blank line)
879 if ($text =~ /^\s*\r?\n/) {
880 $part_header="Content-type: text/plain; charset=us-ascii";
881 } else {
882 $part_header =~ s/\r?\n\r?\n(.*)$//s;
883 $text=$1; if (!defined($text)) {$text="";}
884 }
885 $part_header =~ s/\r?\n[\t ]+/ /gs; #unfold
886 }
887
888 if ($part_header =~
889 /content\-type:\s*([\w\.\-\/]+).*?charset=\"?([^\;\"\s]+)\"?/is) {
890 $type=$1;
891 $charset=$2;
892 }
893 my $encoding="";
894 if ($part_header =~ /^content\-transfer\-encoding:\s*([^\s]+)/mis) {
895 $encoding=$1; $encoding=~tr/A-Z/a-z/;
896 }
897 # Content-Transfer-Encoding is per-part
898 if ($encoding ne "") {
899 if ($encoding =~ /quoted\-printable/) {
900 $text=qp_decode($text);
901 } elsif ($encoding =~ /base64/) {
902 $text=base64_decode($text);
903 } elsif ($encoding !~ /[78]bit/) { # leave 7/8 bit as is.
904 # rfc2045 also allows binary, which we ignore (for now).
905 my $outhandle=$self->{'outhandle'};
906 print $outhandle "EMAILPlug: unknown transfer encoding: $encoding\n";
907 return "";
908 }
909 }
910 if ($type eq "text/html") {
911 # only get stuff between <body> tags, or <html> tags.
912 $text =~ s@^.*<html[^>]*>@@is;
913 $text =~ s@</html>.*$@@is;
914 $text =~ s/^.*?<body[^>]*>//si;
915 $text =~ s/<\/body>.*$//si;
916 }
917 elsif ($type eq "text/xml") {
918 $text=~s/</&lt;/g;$text=~s/>/&gt;/g;
919 $text="<pre>\n$text\n</pre>\n";
920 }
921 # convert to unicode
922 $self->convert2unicode($charset, \$text);
923
924 $text =~ s@_@\\_@g; # protect against GS macro language
925 return $text;
926}
927
928
929
930
931# decode quoted-printable text
932sub qp_decode {
933 my $text=shift;
934
935 # if a line ends with "=\s*", it is a soft line break, otherwise
936 # keep in any newline characters.
937
938 $text =~ s/=\s*\r?\n//mg;
939 $text =~ s/=([0-9A-Fa-f]{2})/chr (hex "0x$1")/eg;
940 return $text;
941}
942
943# decode base64 text. This is fairly slow (since it's interpreted perl rather
944# than compiled XS stuff like in the ::MIME modules, but this is more portable
945# for us at least).
946# see rfc2045 for description, but basically, bits 7 and 8 are set to zero;
947# 4 bytes of encoded text become 3 bytes of binary - remove 2 highest bits
948# from each encoded byte.
949
950
951sub base64_decode {
952 my $enc_text = shift;
953# A=>0, B=>1, ..., '+'=>62, '/'=>63
954# also '=' is used for padding at the end, but we remove it anyway.
955 my $mimechars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
956# map each MIME char into it's value, for more efficient lookup.
957 my %index;
958 map { $index{$_} = index ($mimechars, $_) } (split ('', $mimechars));
959# remove all non-base64 chars. eval to get variable in transliteration...
960# also remove '=' - we'll assume (!!) that there are no errors in the encoding
961 eval "\$enc_text =~ tr|$mimechars||cd";
962 my $decoded="";
963 while (length ($enc_text)>3)
964 {
965 my $fourchars=substr($enc_text,0,4,"");
966 my @chars=(split '',$fourchars);
967 $decoded.=chr( $index{$chars[0]} << 2 | $index{$chars[1]} >> 4);
968 $decoded.=chr( ($index{$chars[1]} & 15) << 4 | $index{$chars[2]} >> 2);
969 $decoded.=chr( ($index{$chars[2]} & 3 ) << 6 | $index{$chars[3]});
970 }
971# if there are any input chars left, there are either
972# 2 encoded bytes (-> 1 raw byte) left or 3 encoded (-> 2 raw) bytes left.
973 my @chars=(split '',$enc_text);
974 if (length($enc_text)) {
975 $decoded.=chr($index{$chars[0]} << 2 | (int $index{$chars[1]} >> 4));
976 }
977 if (length($enc_text)==3) {
978 $decoded.=chr( ($index{$chars[1]} & 15) << 4 | $index{$chars[2]} >> 2);
979 }
980 return $decoded;
981}
982
983sub convert2unicode {
984 my $self = shift(@_);
985 my ($charset, $textref) = @_;
986
987 if (!$$textref) {
988 # nothing to do!
989 return;
990 }
991
992 # first get our character encoding name in the right form.
993 $charset = "iso_8859_1" unless defined $charset;
994 $charset =~ tr/A-Z/a-z/; # lowercase
995 $charset =~ s/\-/_/g;
996 if ($charset =~ /gb_?2312/) { $charset="gb" }
997 # assumes EUC-KR, not ISO-2022 !?
998 $charset =~ s/^ks_c_5601_1987/korean/;
999 if ($charset eq 'utf_8') {$charset='utf8'}
1000
1001 my $outhandle = $self->{'outhandle'};
1002
1003 if ($charset eq "utf8") {
1004 # no conversion needed, but lets check that it's valid utf8
1005 # see utf-8 manpage for valid ranges
1006 $$textref =~ m/^/g; # to set \G
1007 my $badbytesfound=0;
1008 while ($$textref =~ m!\G.*?([\x80-\xff]+)!sg) {
1009 my $highbytes=$1;
1010 my $highbyteslength=length($highbytes);
1011 # replace any non utf8 complaint bytes
1012 $highbytes =~ /^/g; # set pos()
1013 while ($highbytes =~
1014 m!\G (?: [\xc0-\xdf][\x80-\xbf] | # 2 byte utf-8
1015 [\xe0-\xef][\x80-\xbf]{2} | # 3 byte
1016 [\xf0-\xf7][\x80-\xbf]{3} | # 4 byte
1017 [\xf8-\xfb][\x80-\xbf]{4} | # 5 byte
1018 [\xfc-\xfd][\x80-\xbf]{5} # 6 byte
1019 )*([\x80-\xff])? !xg
1020 ) {
1021 my $badbyte=$1;
1022 if (!defined $badbyte) {next} # hit end of string
1023 my $pos=pos($highbytes);
1024 substr($highbytes, $pos-1, 1, "\xc2\x80");
1025 # update the position to continue searching (for \G)
1026 pos($highbytes) = $pos+1; # set to just after the \x80
1027 $badbytesfound=1;
1028 }
1029 if ($badbytesfound==1) {
1030 # claims to be utf8, but it isn't!
1031 print $outhandle "EMAILPlug: Headers claim utf-8 but bad bytes "
1032 . "detected and removed.\n";
1033
1034 my $replength=length($highbytes);
1035 my $textpos=pos($$textref);
1036 # replace bad bytes with good bytes
1037 substr( $$textref, $textpos-$replength,
1038 $replength, $highbytes);
1039 # update the position to continue searching (for \G)
1040 pos($$textref)=$textpos+($replength-$highbyteslength);
1041 }
1042 }
1043 return;
1044 }
1045
1046 # It appears that we can't always trust ascii text so we'll treat it
1047 # as iso-8859-1 (letting characters above 0x80 through without
1048 # converting them to utf-8 will result in invalid XML documents
1049 # which can't be parsed at build time).
1050 $charset = "iso_8859_1" if ($charset eq "us_ascii" || $charset eq "ascii");
1051
1052 if ($charset eq "iso_8859_1") {
1053 # test if the mailer lied, and it has win1252 chars in it...
1054 # 1252 has characters between 0x80 and 0x9f, 8859-1 doesn't
1055 if ($$textref =~ m/[\x80-\x9f]/) {
1056 print $outhandle "EMAILPlug: Headers claim ISO charset but MS ";
1057 print $outhandle "codepage 1252 detected.\n";
1058 $charset = "windows_1252";
1059 }
1060 }
1061 my $utf8_text=&unicode::unicode2utf8(&unicode::convert2unicode($charset,$textref));
1062
1063 if ($utf8_text ne "") {
1064 $$textref=$utf8_text;
1065 } else {
1066 # we didn't get any text... unsupported encoding perhaps? Or it is
1067 # empty anyway. We'll try to continue, assuming 8859-1. We could strip
1068 # characters out here if this causes problems...
1069 my $outhandle=$self->{'outhandle'};
1070 print $outhandle "EMAILPlug: falling back to iso-8859-1\n";
1071 $$textref=&unicode::unicode2utf8(&unicode::convert2unicode("iso_8859_1",$textref));
1072
1073 }
1074}
1075
1076
1077sub set_OID {
1078 my $self = shift (@_);
1079 my ($doc_obj, $id, $segment_number) = @_;
1080
1081 if ( exists $doc_obj->{'msgid'} ) {
1082 $doc_obj->set_OID($doc_obj->{'msgid'});
1083 } else {
1084 $doc_obj->set_OID("$id\_$segment_number");
1085 }
1086}
1087
1088
1089# Perl packages have to return true if they are run.
10901;
Note: See TracBrowser for help on using the repository browser.