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

Last change on this file since 9961 was 9823, checked in by jrm21, 19 years ago

fix bug where we forgot to call a method with $self->

  • 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 {
631 $msg_text=$self->text_from_part($text);
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 $rfc822_formatted_body=text_into_html($message_part_body);
757 }
758 } else {
759 # message doesn't use MIME flags
760 $rfc822_formatted_body=text_into_html($message_part_body);
761 $rfc822_formatted_body =~ s@_@\\_@g;
762 }
763 # Add the returned text to the output
764 # don't put all the headers...
765# $message_part_headers =~ s/^(X\-.*|received|message\-id|return\-path):.*\n//img;
766 my $brief_headers=get_brief_headers($message_part_headers);
767 $return_text.=text_into_html($brief_headers);
768 $return_text.="</p><p>\n";
769 $return_text.=$rfc822_formatted_body;
770 $return_text.="</p>\n";
771 # end of message/rfc822
772 } elsif ($part_content_type =~ /multipart/) {
773 # recurse again
774
775 my $tmptext= $self->text_from_mime_message($part_content_type,
776 $part_content_info,
777 $part_body);
778 $return_text.=$tmptext;
779 } else {
780 # this part isn't text/* or another message...
781 if ($is_first_part) {
782 # this is the first part of a multipart, or only part!
783 $return_text="\n<p><hr><strong>&lt;&lt;attachment&gt;&gt;";
784 # add part info header
785 my $header_text="<br>Type: $part_content_type<br>\n";
786 $header_text.="Filename: $filename</strong></p>\n<p>\n";
787 $header_text =~ s@_@\\_@g;
788 $return_text.=$header_text;
789 }
790
791 # save attachment by default
792 if (!$self->{'ignore_attachments'}
793 && $filename ne "") { # this part has a file...
794 my $encoding="8bit";
795 if ($part_header =~
796 /^content-transfer-encoding:\s*(\w+)/mi ) {
797 $encoding=$1; $encoding =~ tr/A-Z/a-z/;
798 }
799 my $tmpdir=$ENV{'GSDLHOME'} . "/tmp";
800 my $save_filename=$filename;
801
802 # make sure we don't clobber files with same name;
803 # need to keep state between .mbx files
804 my $assoc_files=$self->{'assoc_filenames'};
805 if ($assoc_files->{$filename}) { # it's been set...
806 $assoc_files->{$filename}++;
807 $filename =~ m/(.+)\.(\w+)$/;
808 my ($filestem, $ext)=($1,$2);
809 $save_filename="${filestem}_"
810 . $assoc_files->{$filename} . ".$ext";
811 } else { # first file with this name
812 $assoc_files->{$filename}=1;
813 }
814 open (SAVE, ">$tmpdir/$save_filename") ||
815 warn "EMAILPlug: Can't save attachment as $tmpdir/$save_filename: $!";
816 my $part_text = $message_part;
817 $part_text =~ s/(.*?)\r?\n\r?\n//s; # remove header
818 if ($encoding eq "base64") {
819 print SAVE base64_decode($part_text);
820 } elsif ($encoding eq "quoted-printable") {
821 print SAVE qp_decode($part_text);
822 } else { # 7bit, 8bit, binary, etc...
823 print SAVE $part_text;
824 }
825 close SAVE;
826 my $doc_obj=$self->{'doc_obj'};
827 $doc_obj->associate_file("$tmpdir/$save_filename",
828 "$save_filename",
829 $part_content_type # mimetype
830 );
831 # clean up tmp area...
832 # Can't do this as it hasn't been copied/linked yet!!!
833# &util::rm("$tmpdir/$save_filename");
834 my $outhandle=$self->{'outhandle'};
835 print $outhandle "EMAILPlug: saving attachment \"$filename\"\n"; #
836
837 # be nice if "download" was a translatable macro :(
838 $return_text .="<a href=\"_httpdocimg_/$save_filename\">download</a>";
839 } # end of save attachment
840 } # end of !text/message part
841
842
843 return $return_text;
844}
845
846
847# Return only the "important" headers from a set of message headers
848sub get_brief_headers {
849 my $msg_header = shift;
850 my $brief_header = "";
851
852 # Order matters!
853 if ($msg_header =~ /^(From:.*)$/im) {$brief_header.="$1\n";}
854 if ($msg_header =~ /^(To:.*)$/im) {$brief_header.="$1\n";}
855 if ($msg_header =~ /^(Cc:.*)$/im) {$brief_header.="$1\n";}
856 if ($msg_header =~ /^(Subject:.*)$/im) {$brief_header.="$1\n";}
857 if ($msg_header =~ /^(Date:.*)$/im) {$brief_header.="$1\n";}
858
859 return $brief_header;
860}
861
862
863# Process a MIME part. Return "" if we can't decode it.
864# should only be called for parts with type "text/*" ?
865sub text_from_part {
866 my $self = shift;
867 my $text = shift || '';
868 my $part_header = $text;
869
870 # check for empty part header (leading blank line)
871 if ($text =~ /^\s*\r?\n/) {
872 $part_header="Content-type: text/plain; charset=us-ascii";
873 } else {
874 $part_header =~ s/\r?\n\r?\n(.*)$//s;
875 $text=$1; if (!defined($text)) {$text="";}
876 }
877 $part_header =~ s/\r?\n[\t ]+/ /gs; #unfold
878 $part_header =~ /content\-type:\s*([\w\.\-\/]+).*?charset=\"?([^\;\"\s]+)\"?/is;
879 my $type=$1;
880 my $charset=$2;
881 if (!defined($type)) {$type="";}
882 if (!defined($charset)) {$charset="ascii";}
883 my $encoding="";
884 if ($part_header =~ /^content\-transfer\-encoding:\s*([^\s]+)/mis) {
885 $encoding=$1; $encoding=~tr/A-Z/a-z/;
886 }
887 # Content-Transfer-Encoding is per-part
888 if ($encoding ne "") {
889 if ($encoding =~ /quoted\-printable/) {
890 $text=qp_decode($text);
891 } elsif ($encoding =~ /base64/) {
892 $text=base64_decode($text);
893 } elsif ($encoding !~ /[78]bit/) { # leave 7/8 bit as is.
894 # rfc2045 also allows binary, which we ignore (for now).
895 my $outhandle=$self->{'outhandle'};
896 print $outhandle "EMAILPlug: unknown transfer encoding: $encoding\n";
897 return "";
898 }
899 }
900 if ($type eq "text/html") {
901 # only get stuff between <body> tags, or <html> tags.
902 $text =~ s@^.*<html[^>]*>@@is;
903 $text =~ s@</html>.*$@@is;
904 $text =~ s/^.*?<body[^>]*>//si;
905 $text =~ s/<\/body>.*$//si;
906 }
907 elsif ($type eq "text/xml") {
908 $text=~s/</&lt;/g;$text=~s/>/&gt;/g;
909 $text="<pre>\n$text\n</pre>\n";
910 }
911 # convert to unicode
912 $self->convert2unicode($charset, \$text);
913
914 $text =~ s@_@\\_@g; # protect against GS macro language
915 return $text;
916}
917
918
919
920
921# decode quoted-printable text
922sub qp_decode {
923 my $text=shift;
924
925 # if a line ends with "=\s*", it is a soft line break, otherwise
926 # keep in any newline characters.
927
928 $text =~ s/=\s*\r?\n//mg;
929 $text =~ s/=([0-9A-Fa-f]{2})/chr (hex "0x$1")/eg;
930 return $text;
931}
932
933# decode base64 text. This is fairly slow (since it's interpreted perl rather
934# than compiled XS stuff like in the ::MIME modules, but this is more portable
935# for us at least).
936# see rfc2045 for description, but basically, bits 7 and 8 are set to zero;
937# 4 bytes of encoded text become 3 bytes of binary - remove 2 highest bits
938# from each encoded byte.
939
940
941sub base64_decode {
942 my $enc_text = shift;
943# A=>0, B=>1, ..., '+'=>62, '/'=>63
944# also '=' is used for padding at the end, but we remove it anyway.
945 my $mimechars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
946# map each MIME char into it's value, for more efficient lookup.
947 my %index;
948 map { $index{$_} = index ($mimechars, $_) } (split ('', $mimechars));
949# remove all non-base64 chars. eval to get variable in transliteration...
950# also remove '=' - we'll assume (!!) that there are no errors in the encoding
951 eval "\$enc_text =~ tr|$mimechars||cd";
952 my $decoded="";
953 while (length ($enc_text)>3)
954 {
955 my $fourchars=substr($enc_text,0,4,"");
956 my @chars=(split '',$fourchars);
957 $decoded.=chr( $index{$chars[0]} << 2 | $index{$chars[1]} >> 4);
958 $decoded.=chr( ($index{$chars[1]} & 15) << 4 | $index{$chars[2]} >> 2);
959 $decoded.=chr( ($index{$chars[2]} & 3 ) << 6 | $index{$chars[3]});
960 }
961# if there are any input chars left, there are either
962# 2 encoded bytes (-> 1 raw byte) left or 3 encoded (-> 2 raw) bytes left.
963 my @chars=(split '',$enc_text);
964 if (length($enc_text)) {
965 $decoded.=chr($index{$chars[0]} << 2 | (int $index{$chars[1]} >> 4));
966 }
967 if (length($enc_text)==3) {
968 $decoded.=chr( ($index{$chars[1]} & 15) << 4 | $index{$chars[2]} >> 2);
969 }
970 return $decoded;
971}
972
973sub convert2unicode {
974 my $self = shift(@_);
975 my ($charset, $textref) = @_;
976
977 if (!$$textref) {
978 # nothing to do!
979 return;
980 }
981
982 # first get our character encoding name in the right form.
983 $charset = "iso_8859_1" unless defined $charset;
984 $charset =~ tr/A-Z/a-z/; # lowercase
985 $charset =~ s/\-/_/g;
986 if ($charset =~ /gb_?2312/) { $charset="gb" }
987 # assumes EUC-KR, not ISO-2022 !?
988 $charset =~ s/^ks_c_5601_1987/korean/;
989 if ($charset eq 'utf_8') {$charset='utf8'}
990
991 my $outhandle = $self->{'outhandle'};
992
993 if ($charset eq "utf8") {
994 # no conversion needed, but lets check that it's valid utf8
995 # see utf-8 manpage for valid ranges
996 $$textref =~ m/^/g; # to set \G
997 my $badbytesfound=0;
998 while ($$textref =~ m!\G.*?([\x80-\xff]+)!sg) {
999 my $highbytes=$1;
1000 my $highbyteslength=length($highbytes);
1001 # replace any non utf8 complaint bytes
1002 $highbytes =~ /^/g; # set pos()
1003 while ($highbytes =~
1004 m!\G (?: [\xc0-\xdf][\x80-\xbf] | # 2 byte utf-8
1005 [\xe0-\xef][\x80-\xbf]{2} | # 3 byte
1006 [\xf0-\xf7][\x80-\xbf]{3} | # 4 byte
1007 [\xf8-\xfb][\x80-\xbf]{4} | # 5 byte
1008 [\xfc-\xfd][\x80-\xbf]{5} # 6 byte
1009 )*([\x80-\xff])? !xg
1010 ) {
1011 my $badbyte=$1;
1012 if (!defined $badbyte) {next} # hit end of string
1013 my $pos=pos($highbytes);
1014 substr($highbytes, $pos-1, 1, "\xc2\x80");
1015 # update the position to continue searching (for \G)
1016 pos($highbytes) = $pos+1; # set to just after the \x80
1017 $badbytesfound=1;
1018 }
1019 if ($badbytesfound==1) {
1020 # claims to be utf8, but it isn't!
1021 print $outhandle "EMAILPlug: Headers claim utf-8 but bad bytes "
1022 . "detected and removed.\n";
1023
1024 my $replength=length($highbytes);
1025 my $textpos=pos($$textref);
1026 # replace bad bytes with good bytes
1027 substr( $$textref, $textpos-$replength,
1028 $replength, $highbytes);
1029 # update the position to continue searching (for \G)
1030 pos($$textref)=$textpos+($replength-$highbyteslength);
1031 }
1032 }
1033 return;
1034 }
1035
1036 # It appears that we can't always trust ascii text so we'll treat it
1037 # as iso-8859-1 (letting characters above 0x80 through without
1038 # converting them to utf-8 will result in invalid XML documents
1039 # which can't be parsed at build time).
1040 $charset = "iso_8859_1" if ($charset eq "us_ascii" || $charset eq "ascii");
1041
1042 if ($charset eq "iso_8859_1") {
1043 # test if the mailer lied, and it has win1252 chars in it...
1044 # 1252 has characters between 0x80 and 0x9f, 8859-1 doesn't
1045 if ($$textref =~ m/[\x80-\x9f]/) {
1046 print $outhandle "EMAILPlug: Headers claim ISO charset but MS ";
1047 print $outhandle "codepage 1252 detected.\n";
1048 $charset = "windows_1252";
1049 }
1050 }
1051 my $utf8_text=&unicode::unicode2utf8(&unicode::convert2unicode($charset,$textref));
1052
1053 if ($utf8_text ne "") {
1054 $$textref=$utf8_text;
1055 } else {
1056 # we didn't get any text... unsupported encoding perhaps? Or it is
1057 # empty anyway. We'll try to continue, assuming 8859-1. We could strip
1058 # characters out here if this causes problems...
1059 my $outhandle=$self->{'outhandle'};
1060 print $outhandle "EMAILPlug: falling back to iso-8859-1\n";
1061 $$textref=&unicode::unicode2utf8(&unicode::convert2unicode("iso_8859_1",$textref));
1062
1063 }
1064}
1065
1066
1067sub set_OID {
1068 my $self = shift (@_);
1069 my ($doc_obj, $id, $segment_number) = @_;
1070
1071 if ( exists $doc_obj->{'msgid'} ) {
1072 $doc_obj->set_OID($doc_obj->{'msgid'});
1073 } else {
1074 $doc_obj->set_OID("$id\_$segment_number");
1075 }
1076}
1077
1078
1079# Perl packages have to return true if they are run.
10801;
Note: See TracBrowser for help on using the repository browser.