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

Last change on this file since 9143 was 8904, checked in by jrm21, 19 years ago

need to do qp decoding before doing text_into_html so we don't keep
line breaks that disappear after decoding

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