1 # BEGIN BPS TAGGED BLOCK {{{
5 # This software is Copyright (c) 1996-2009 Best Practical Solutions, LLC
6 # <jesse@bestpractical.com>
8 # (Except where explicitly superseded by other copyright notices)
13 # This work is made available to you under the terms of Version 2 of
14 # the GNU General Public License. A copy of that license should have
15 # been provided with this software, but in any event can be snarfed
18 # This work is distributed in the hope that it will be useful, but
19 # WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21 # General Public License for more details.
23 # You should have received a copy of the GNU General Public License
24 # along with this program; if not, write to the Free Software
25 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
26 # 02110-1301 or visit their web page on the internet at
27 # http://www.gnu.org/licenses/old-licenses/gpl-2.0.html.
30 # CONTRIBUTION SUBMISSION POLICY:
32 # (The following paragraph is not intended to limit the rights granted
33 # to you to modify and distribute this software under the terms of
34 # the GNU General Public License and is only of importance to you if
35 # you choose to contribute your changes and enhancements to the
36 # community by submitting them to Best Practical Solutions, LLC.)
38 # By intentionally submitting any modifications, corrections or
39 # derivatives to this work, or any other work intended for use with
40 # Request Tracker, to Best Practical Solutions, LLC, you confirm that
41 # you are the copyright holder for those contributions and you grant
42 # Best Practical Solutions, LLC a nonexclusive, worldwide, irrevocable,
43 # royalty-free, perpetual, license to use, copy, create derivative
44 # works based on those contributions, and sublicense and distribute
45 # those contributions and any derivatives thereof.
47 # END BPS TAGGED BLOCK }}}
49 package RT::EmailParser;
52 use base qw/RT::Base/;
61 use File::Temp qw/tempdir/;
65 RT::EmailParser - helper functions for parsing parts from incoming
80 Returns a new RT::EmailParser object
86 my $class = ref($proto) || $proto;
88 bless ($self, $class);
93 =head2 SmartParseMIMEEntityFromScalar Message => SCALAR_REF [, Decode => BOOL, Exact => BOOL ] }
95 Parse a message stored in a scalar from scalar_ref.
99 sub SmartParseMIMEEntityFromScalar {
101 my %args = ( Message => undef, Decode => 1, Exact => 0, @_ );
104 my ( $fh, $temp_file );
107 # on NFS and NTFS, it is possible that tempfile() conflicts
108 # with other processes, causing a race condition. we try to
109 # accommodate this by pausing and retrying.
111 if ( $fh, $temp_file ) =
112 eval { File::Temp::tempfile( undef, UNLINK => 0 ) };
120 print $fh $args{'Message'};
122 if ( -f $temp_file ) {
124 # We have to trust the temp file's name -- untaint it
125 $temp_file =~ /(.*)/;
126 my $entity = $self->ParseMIMEEntityFromFile( $1, $args{'Decode'}, $args{'Exact'} );
133 #If for some reason we weren't able to parse the message using a temp file
134 # try it with a scalar
135 if ( $@ || !$self->Entity ) {
136 return $self->ParseMIMEEntityFromScalar( $args{'Message'}, $args{'Decode'}, $args{'Exact'} );
142 =head2 ParseMIMEEntityFromSTDIN
144 Parse a message from standard input
148 sub ParseMIMEEntityFromSTDIN {
150 return $self->ParseMIMEEntityFromFileHandle(\*STDIN, @_);
153 =head2 ParseMIMEEntityFromScalar $message
155 Takes either a scalar or a reference to a scalar which contains a stringified MIME message.
158 Returns true if it wins.
159 Returns false if it loses.
163 sub ParseMIMEEntityFromScalar {
165 return $self->_ParseMIMEEntity( shift, 'parse_data', @_ );
168 =head2 ParseMIMEEntityFromFilehandle *FH
170 Parses a mime entity from a filehandle passed in as an argument
174 sub ParseMIMEEntityFromFileHandle {
176 return $self->_ParseMIMEEntity( shift, 'parse', @_ );
179 =head2 ParseMIMEEntityFromFile
181 Parses a mime entity from a filename passed in as an argument
185 sub ParseMIMEEntityFromFile {
187 return $self->_ParseMIMEEntity( shift, 'parse_open', @_ );
191 sub _ParseMIMEEntity {
195 my $postprocess = (@_ ? shift : 1);
198 # Create a new parser object:
199 my $parser = MIME::Parser->new();
200 $self->_SetupMIMEParser($parser);
201 $parser->decode_bodies(0) if $exact;
203 # TODO: XXX 3.0 we really need to wrap this in an eval { }
204 unless ( $self->{'entity'} = $parser->$method($message) ) {
205 $RT::Logger->crit("Couldn't parse MIME stream and extract the submessages");
206 # Try again, this time without extracting nested messages
207 $parser->extract_nested_messages(0);
208 unless ( $self->{'entity'} = $parser->$method($message) ) {
209 $RT::Logger->crit("couldn't parse MIME stream");
214 $self->_PostProcessNewEntity if $postprocess;
216 return $self->{'entity'};
221 return unless $self->{'entity'};
223 my @parts = $self->{'entity'}->parts_DFS;
224 $self->_DecodeBody($_) foreach @parts;
231 my $old = $entity->bodyhandle or return;
232 return unless $old->is_encoded;
234 require MIME::Decoder;
235 my $encoding = $entity->head->mime_encoding;
236 my $decoder = new MIME::Decoder $encoding;
237 unless ( $decoder ) {
238 $RT::Logger->error("Couldn't find decoder for '$encoding', switching to binary");
244 # XXX: use InCore for now, but later must switch to files
245 my $new = new MIME::Body::InCore;
249 my $source = $old->open('r') or die "couldn't open body: $!";
250 my $destination = $new->open('w') or die "couldn't open body: $!";
253 eval { $decoder->decode($source, $destination) };
254 $RT::Logger->error($@) if $@;
256 $source->close or die "can't close: $!";
257 $destination->close or die "can't close: $!";
259 $entity->bodyhandle( $new );
262 =head2 _PostProcessNewEntity
264 cleans up and postprocesses a newly parsed MIME Entity
268 sub _PostProcessNewEntity {
271 #Now we've got a parsed mime object.
273 # Unfold headers that are have embedded newlines
274 # Better do this before conversion or it will break
275 # with multiline encoded Subject (RFC2047) (fsck.com #5594)
278 # try to convert text parts into utf-8 charset
279 RT::I18N::SetMIMEEntityToEncoding($self->{'entity'}, 'utf-8');
282 =head2 ParseCcAddressesFromHead HASHREF
284 Takes a hashref object containing QueueObj, Head and CurrentUser objects.
285 Returns a list of all email addresses in the To and Cc
286 headers b<except> the current Queue\'s email addresses, the CurrentUser\'s
287 email address and anything that the RT->Config->Get('RTAddressRegexp') matches.
291 sub ParseCcAddressesFromHead {
295 CurrentUser => undef,
301 my @ToObjs = Email::Address->parse( $self->Head->get('To') );
302 my @CcObjs = Email::Address->parse( $self->Head->get('Cc') );
304 foreach my $AddrObj ( @ToObjs, @CcObjs ) {
305 my $Address = $AddrObj->address;
306 my $user = RT::User->new($RT::SystemUser);
307 $Address = $user->CanonicalizeEmailAddress($Address);
308 next if lc $args{'CurrentUser'}->EmailAddress eq lc $Address;
309 next if $self->IsRTAddress($Address);
311 push ( @Addresses, $Address );
317 =head2 IsRTaddress ADDRESS
319 Takes a single parameter, an email address.
320 Returns true if that address matches the C<RTAddressRegexp> config option.
321 Returns false, otherwise.
330 if ( my $address_re = RT->Config->Get('RTAddressRegexp') ) {
331 return $address =~ /$address_re/i ? 1 : undef;
334 # we don't warn here, but do in config check
335 if ( my $correspond_address = RT->Config->Get('CorrespondAddress') ) {
336 return 1 if lc $correspond_address eq lc $address;
338 if ( my $comment_address = RT->Config->Get('CommentAddress') ) {
339 return 1 if lc $comment_address eq lc $address;
342 my $queue = RT::Queue->new( $RT::SystemUser );
343 $queue->LoadByCols( CorrespondAddress => $address );
344 return 1 if $queue->id;
346 $queue->LoadByCols( CommentAddress => $address );
347 return 1 if $queue->id;
353 =head2 CullRTAddresses ARRAY
355 Takes a single argument, an array of email addresses.
356 Returns the same array with any IsRTAddress()es weeded out.
361 sub CullRTAddresses {
366 foreach my $addr( @addresses ) {
367 # We use the class instead of the instance
368 # because sloppy code calls this method
370 push (@addrlist, $addr) unless RT::EmailParser->IsRTAddress($addr);
379 # LookupExternalUserInfo is a site-definable method for synchronizing
380 # incoming users with an external data source.
382 # This routine takes a tuple of EmailAddress and FriendlyName
383 # EmailAddress is the user's email address, ususally taken from
384 # an email message's From: header.
385 # FriendlyName is a freeform string, ususally taken from the "comment"
386 # portion of an email message's From: header.
388 # If you define an AutoRejectRequest template, RT will use this
389 # template for the rejection message.
392 =head2 LookupExternalUserInfo
394 LookupExternalUserInfo is a site-definable method for synchronizing
395 incoming users with an external data source.
397 This routine takes a tuple of EmailAddress and FriendlyName
398 EmailAddress is the user's email address, ususally taken from
399 an email message's From: header.
400 FriendlyName is a freeform string, ususally taken from the "comment"
401 portion of an email message's From: header.
403 It returns (FoundInExternalDatabase, ParamHash);
405 FoundInExternalDatabase must be set to 1 before return if the user
406 was found in the external database.
408 ParamHash is a Perl parameter hash which can contain at least the
409 following fields. These fields are used to populate RT's users
410 database when the user is created.
412 EmailAddress is the email address that RT should use for this user.
413 Name is the 'Name' attribute RT should use for this user.
414 'Name' is used for things like access control and user lookups.
415 RealName is what RT should display as the user's name when displaying
420 sub LookupExternalUserInfo {
422 my $EmailAddress = shift;
423 my $RealName = shift;
425 my $FoundInExternalDatabase = 1;
428 #Name is the RT username you want to use for this user.
429 $params{'Name'} = $EmailAddress;
430 $params{'EmailAddress'} = $EmailAddress;
431 $params{'RealName'} = $RealName;
433 # See RT's contributed code for examples.
434 # http://www.fsck.com/pub/rt/contrib/
435 return ($FoundInExternalDatabase, %params);
440 Return the parsed head from this message
446 return $self->Entity->head;
451 Return the parsed Entity from this message
457 return $self->{'entity'};
462 =head2 _SetupMIMEParser $parser
464 A private instance method which sets up a mime parser to do its job
469 ## TODO: Does it make sense storing to disk at all? After all, we
470 ## need to put each msg as an in-core scalar before saving it to
471 ## the database, don't we?
473 ## At the same time, we should make sure that we nuke attachments
474 ## Over max size and return them
476 sub _SetupMIMEParser {
480 # Set up output directory for files; we use $RT::VarPath instead
481 # of File::Spec->tmpdir (e.g., /tmp) beacuse it isn't always
484 if ( -w $RT::VarPath ) {
485 $tmpdir = File::Temp::tempdir( DIR => $RT::VarPath, CLEANUP => 1 );
486 } elsif (-w File::Spec->tmpdir) {
487 $tmpdir = File::Temp::tempdir( TMPDIR => 1, CLEANUP => 1 );
489 $RT::Logger->crit("Neither the RT var directory ($RT::VarPath) nor the system tmpdir (@{[File::Spec->tmpdir]}) are writable; falling back to in-memory parsing!");
492 #If someone includes a message, extract it
493 $parser->extract_nested_messages(1);
494 $parser->extract_uuencode(1); ### default is false
497 # If we got a writable tmpdir, write to disk
498 push ( @{ $self->{'AttachmentDirs'} ||= [] }, $tmpdir );
499 $parser->output_dir($tmpdir);
500 $parser->filer->ignore_filename(1);
502 # Set up the prefix for files with auto-generated names:
503 $parser->output_prefix("part");
505 # From the MIME::Parser docs:
506 # "Normally, tmpfiles are created when needed during parsing, and destroyed automatically when they go out of scope"
507 # Turns out that the default is to recycle tempfiles
508 # Temp files should never be recycled, especially when running under perl taint checking
510 $parser->tmp_recycling(0) if $parser->can('tmp_recycling');
512 # Otherwise, fall back to storing it in memory
513 $parser->output_to_core(1);
514 $parser->tmp_to_core(1);
515 $parser->use_inner_files(1);
520 =head2 ParseEmailAddress string
522 Returns a list of Email::Address objects
523 Works around the bug that Email::Address 1.889 and earlier
524 doesn't handle local-only email addresses (when users pass
525 in just usernames on the RT system in fields that expect
528 We don't handle the case of
529 bob, fred@bestpractical.com
530 because we don't want to fail parsing
531 bob, "Falcone, Fred" <fred@bestpractical.com>
532 The next release of Email::Address will have a new method
533 we can use that removes the bandaid
537 sub ParseEmailAddress {
539 my $address_string = shift;
541 $address_string =~ s/^\s+|\s+$//g;
544 # if it looks like a username / local only email
545 if ($address_string !~ /@/ && $address_string =~ /^\w+$/) {
546 my $user = RT::User->new( $RT::SystemUser );
547 my ($id, $msg) = $user->Load($address_string);
549 push @addresses, Email::Address->new($user->Name,$user->EmailAddress);
551 $RT::Logger->error("Unable to parse an email address from $address_string: $msg");
554 @addresses = Email::Address->parse($address_string);
564 File::Path::rmtree([@{$self->{'AttachmentDirs'}}],0,1)
565 if $self->{'AttachmentDirs'};
570 eval "require RT::EmailParser_Vendor";
571 die $@ if ($@ && $@ !~ qr{^Can't locate RT/EmailParser_Vendor.pm});
572 eval "require RT::EmailParser_Local";
573 die $@ if ($@ && $@ !~ qr{^Can't locate RT/EmailParser_Local.pm});