import rt 3.6.6
[freeside.git] / rt / lib / RT / Interface / Email.pm
1 # BEGIN BPS TAGGED BLOCK {{{
2
3 # COPYRIGHT:
4 #  
5 # This software is Copyright (c) 1996-2007 Best Practical Solutions, LLC 
6 #                                          <jesse@bestpractical.com>
7
8 # (Except where explicitly superseded by other copyright notices)
9
10
11 # LICENSE:
12
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
16 # from www.gnu.org.
17
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.
22
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/copyleft/gpl.html.
28
29
30 # CONTRIBUTION SUBMISSION POLICY:
31
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.)
37
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.
46
47 # END BPS TAGGED BLOCK }}}
48 package RT::Interface::Email;
49
50 use strict;
51 use Mail::Address;
52 use MIME::Entity;
53 use RT::EmailParser;
54 use File::Temp;
55 use UNIVERSAL::require;
56
57 BEGIN {
58     use Exporter ();
59     use vars qw ( @ISA @EXPORT_OK);
60
61     # set the version for version checking
62     our $VERSION = 2.0;
63
64     @ISA = qw(Exporter);
65
66     # your exported package globals go here,
67     # as well as any optionally exported functions
68     @EXPORT_OK = qw(
69         &CreateUser
70         &GetMessageContent
71         &CheckForLoops
72         &CheckForSuspiciousSender
73         &CheckForAutoGenerated
74         &CheckForBounce
75         &MailError
76         &ParseCcAddressesFromHead
77         &ParseSenderAddressFromHead
78         &ParseErrorsToAddressFromHead
79         &ParseAddressFromHeader
80         &Gateway);
81
82 }
83
84 =head1 NAME
85
86   RT::Interface::Email - helper functions for parsing email sent to RT
87
88 =head1 SYNOPSIS
89
90   use lib "!!RT_LIB_PATH!!";
91   use lib "!!RT_ETC_PATH!!";
92
93   use RT::Interface::Email  qw(Gateway CreateUser);
94
95 =head1 DESCRIPTION
96
97
98 =begin testing
99
100 ok(require RT::Interface::Email);
101
102 =end testing
103
104
105 =head1 METHODS
106
107 =cut
108
109 # {{{ sub CheckForLoops
110
111 sub CheckForLoops {
112     my $head = shift;
113
114     #If this instance of RT sent it our, we don't want to take it in
115     my $RTLoop = $head->get("X-RT-Loop-Prevention") || "";
116     chomp($RTLoop);    #remove that newline
117     if ( $RTLoop eq "$RT::rtname" ) {
118         return (1);
119     }
120
121     # TODO: We might not trap the case where RT instance A sends a mail
122     # to RT instance B which sends a mail to ...
123     return (undef);
124 }
125
126 # }}}
127
128 # {{{ sub CheckForSuspiciousSender
129
130 sub CheckForSuspiciousSender {
131     my $head = shift;
132
133     #if it's from a postmaster or mailer daemon, it's likely a bounce.
134
135     #TODO: better algorithms needed here - there is no standards for
136     #bounces, so it's very difficult to separate them from anything
137     #else.  At the other hand, the Return-To address is only ment to be
138     #used as an error channel, we might want to put up a separate
139     #Return-To address which is treated differently.
140
141     #TODO: search through the whole email and find the right Ticket ID.
142
143     my ( $From, $junk ) = ParseSenderAddressFromHead($head);
144
145     if (   ( $From =~ /^mailer-daemon\@/i )
146         or ( $From =~ /^postmaster\@/i ) )
147     {
148         return (1);
149
150     }
151
152     return (undef);
153
154 }
155
156 # }}}
157
158 # {{{ sub CheckForAutoGenerated
159 sub CheckForAutoGenerated {
160     my $head = shift;
161
162     my $Precedence = $head->get("Precedence") || "";
163     if ( $Precedence =~ /^(bulk|junk)/i ) {
164         return (1);
165     }
166
167     # First Class mailer uses this as a clue.
168     my $FCJunk = $head->get("X-FC-Machinegenerated") || "";
169     if ( $FCJunk =~ /^true/i ) {
170         return (1);
171     }
172
173     return (0);
174 }
175
176 # }}}
177
178 # {{{ sub CheckForBounce
179 sub CheckForBounce {
180     my $head = shift;
181
182     my $ReturnPath = $head->get("Return-path") || "";
183     return ( $ReturnPath =~ /<>/ );
184 }
185
186 # }}}
187
188 # {{{ IsRTAddress
189
190 =head2 IsRTAddress ADDRESS
191
192 Takes a single parameter, an email address. 
193 Returns true if that address matches the $RTAddressRegexp.  
194 Returns false, otherwise.
195
196 =cut
197
198 sub IsRTAddress {
199     my $address = shift || '';
200
201     # Example: the following rule would tell RT not to Cc
202     #   "tickets@noc.example.com"
203     if ( defined($RT::RTAddressRegexp)
204         && $address =~ /$RT::RTAddressRegexp/i )
205     {
206         return (1);
207     } else {
208         return (undef);
209     }
210 }
211
212 # }}}
213
214 # {{{ CullRTAddresses
215
216 =head2 CullRTAddresses ARRAY
217
218 Takes a single argument, an array of email addresses.
219 Returns the same array with any IsRTAddress()es weeded out.
220
221 =cut
222
223 sub CullRTAddresses {
224     return grep !IsRTAddress($_), @_;
225 }
226
227 # }}}
228
229 # {{{ sub MailError
230 sub MailError {
231     my %args = (
232         To          => $RT::OwnerEmail,
233         Bcc         => undef,
234         From        => $RT::CorrespondAddress,
235         Subject     => 'There has been an error',
236         Explanation => 'Unexplained error',
237         MIMEObj     => undef,
238         Attach      => undef,
239         LogLevel    => 'crit',
240         @_
241     );
242
243     $RT::Logger->log(
244         level   => $args{'LogLevel'},
245         message => $args{'Explanation'}
246     );
247     # the colons are necessary to make ->build include non-standard headers
248     my $entity = MIME::Entity->build(
249         Type                   => "multipart/mixed",
250         From                   => $args{'From'},
251         Bcc                    => $args{'Bcc'},
252         To                     => $args{'To'},
253         Subject                => $args{'Subject'},
254         'Precedence:'             => 'bulk',
255         'X-RT-Loop-Prevention:' => $RT::rtname,
256         'In-Reply-To:'          => $args{'MIMEObj'} ? $args{'MIMEObj'}->head->get('Message-Id') : undef
257     );
258
259     $entity->attach( Data => $args{'Explanation'} . "\n" );
260
261     my $mimeobj = $args{'MIMEObj'};
262     if ($mimeobj) {
263         $mimeobj->sync_headers();
264         $entity->add_part($mimeobj);
265     }
266
267     if ( $args{'Attach'} ) {
268         $entity->attach( Data => $args{'Attach'}, Type => 'message/rfc822' );
269
270     }
271
272     if ( $RT::MailCommand eq 'sendmailpipe' ) {
273         open( MAIL,
274             "|$RT::SendmailPath $RT::SendmailBounceArguments $RT::SendmailArguments"
275             )
276             || return (0);
277         print MAIL $entity->as_string;
278         close(MAIL);
279     } else {
280         $entity->send( $RT::MailCommand, $RT::MailParams );
281     }
282 }
283
284 # }}}
285
286 # {{{ Create User
287
288 sub CreateUser {
289     my ( $Username, $Address, $Name, $ErrorsTo, $entity ) = @_;
290     my $NewUser = RT::User->new($RT::SystemUser);
291
292     my ( $Val, $Message ) = $NewUser->Create(
293         Name => ( $Username || $Address ),
294         EmailAddress => $Address,
295         RealName     => $Name,
296         Password     => undef,
297         Privileged   => 0,
298         Comments     => 'Autocreated on ticket submission'
299     );
300
301     unless ($Val) {
302
303         # Deal with the race condition of two account creations at once
304         if ($Username) {
305             $NewUser->LoadByName($Username);
306         }
307
308         unless ( $NewUser->Id ) {
309             $NewUser->LoadByEmail($Address);
310         }
311
312         unless ( $NewUser->Id ) {
313             MailError(
314                 To          => $ErrorsTo,
315                 Subject     => "User could not be created",
316                 Explanation =>
317                     "User creation failed in mailgateway: $Message",
318                 MIMEObj  => $entity,
319                 LogLevel => 'crit'
320             );
321         }
322     }
323
324     #Load the new user object
325     my $CurrentUser = RT::CurrentUser->new();
326     $CurrentUser->LoadByEmail($Address);
327
328     unless ( $CurrentUser->id ) {
329         $RT::Logger->warning(
330             "Couldn't load user '$Address'." . "giving up" );
331         MailError(
332             To          => $ErrorsTo,
333             Subject     => "User could not be loaded",
334             Explanation =>
335                 "User  '$Address' could not be loaded in the mail gateway",
336             MIMEObj  => $entity,
337             LogLevel => 'crit'
338         );
339     }
340
341     return $CurrentUser;
342 }
343
344 # }}}
345
346 # {{{ ParseCcAddressesFromHead
347
348 =head2 ParseCcAddressesFromHead HASHREF
349
350 Takes a hashref object containing QueueObj, Head and CurrentUser objects.
351 Returns a list of all email addresses in the To and Cc 
352 headers b<except> the current Queue\'s email addresses, the CurrentUser\'s 
353 email address  and anything that the configuration sub RT::IsRTAddress matches.
354
355 =cut
356
357 sub ParseCcAddressesFromHead {
358     my %args = (
359         Head        => undef,
360         QueueObj    => undef,
361         CurrentUser => undef,
362         @_
363     );
364
365     my (@Addresses);
366
367     my @ToObjs = Mail::Address->parse( $args{'Head'}->get('To') );
368     my @CcObjs = Mail::Address->parse( $args{'Head'}->get('Cc') );
369
370     foreach my $AddrObj ( @ToObjs, @CcObjs ) {
371         my $Address = $AddrObj->address;
372         $Address = $args{'CurrentUser'}
373             ->UserObj->CanonicalizeEmailAddress($Address);
374         next if ( $args{'CurrentUser'}->EmailAddress   =~ /^\Q$Address\E$/i );
375         next if ( $args{'QueueObj'}->CorrespondAddress =~ /^\Q$Address\E$/i );
376         next if ( $args{'QueueObj'}->CommentAddress    =~ /^\Q$Address\E$/i );
377         next if ( RT::EmailParser->IsRTAddress($Address) );
378
379         push( @Addresses, $Address );
380     }
381     return (@Addresses);
382 }
383
384 # }}}
385
386 # {{{ ParseSenderAdddressFromHead
387
388 =head2 ParseSenderAddressFromHead
389
390 Takes a MIME::Header object. Returns a tuple: (user@host, friendly name) 
391 of the From (evaluated in order of Reply-To:, From:, Sender)
392
393 =cut
394
395 sub ParseSenderAddressFromHead {
396     my $head = shift;
397
398     #Figure out who's sending this message.
399     foreach my $header ('Reply-To', 'From', 'Sender') {
400         my $From = $head->get($header);
401         my ($addr, $name) = ParseAddressFromHeader($From);
402         # only return if the address is not empty
403         return ($addr, $name) if $addr;
404     }
405
406     return (undef, undef);
407 }
408 # }}}
409
410 # {{{ ParseErrorsToAdddressFromHead
411
412 =head2 ParseErrorsToAddressFromHead
413
414 Takes a MIME::Header object. Return a single value : user@host
415 of the From (evaluated in order of Return-path:,Errors-To:,Reply-To:,
416 From:, Sender)
417
418 =cut
419
420 sub ParseErrorsToAddressFromHead {
421     my $head = shift;
422
423     #Figure out who's sending this message.
424
425     foreach my $header ( 'Errors-To', 'Reply-To', 'From', 'Sender' ) {
426
427         # If there's a header of that name
428         my $headerobj = $head->get($header);
429         if ($headerobj) {
430             my ( $addr, $name ) = ParseAddressFromHeader($headerobj);
431
432             # If it's got actual useful content...
433             return ($addr) if ($addr);
434         }
435     }
436 }
437
438 # }}}
439
440 # {{{ ParseAddressFromHeader
441
442 =head2 ParseAddressFromHeader ADDRESS
443
444 Takes an address from $head->get('Line') and returns a tuple: user@host, friendly name
445
446 =cut
447
448 sub ParseAddressFromHeader {
449     my $Addr = shift;
450
451     # Some broken mailers send:  ""Vincent, Jesse"" <jesse@fsck.com>. Hate
452     $Addr =~ s/\"\"(.*?)\"\"/\"$1\"/g;                                                                                                                                                  
453     my @Addresses = Mail::Address->parse($Addr);
454
455     my ($AddrObj) = grep ref $_, @Addresses;
456     unless ( $AddrObj ) {
457         return ( undef, undef );
458     }
459
460     my $Name = ( $AddrObj->phrase || $AddrObj->comment || $AddrObj->address );
461
462     #Lets take the from and load a user object.
463     my $Address = $AddrObj->address;
464
465     return ( $Address, $Name );
466 }
467
468 # }}}
469
470 # {{{ sub ParseTicketId
471
472 sub ParseTicketId {
473     my $Subject = shift;
474     my $id;
475
476     my $test_name = $RT::EmailSubjectTagRegex || qr/\Q$RT::rtname\E/i;
477
478     if ( $Subject =~ s/\[$test_name\s+\#(\d+)\s*\]//i ) {
479         my $id = $1;
480         $RT::Logger->debug("Found a ticket ID. It's $id");
481         return ($id);
482     } else {
483         return (undef);
484     }
485 }
486
487 # }}}
488
489 =head2 Gateway ARGSREF
490
491
492 Takes parameters:
493
494     action
495     queue
496     message
497
498
499 This performs all the "guts" of the mail rt-mailgate program, and is
500 designed to be called from the web interface with a message, user
501 object, and so on.
502
503 Can also take an optional 'ticket' parameter; this ticket id overrides
504 any ticket id found in the subject.
505
506 Returns:
507
508     An array of:
509     
510     (status code, message, optional ticket object)
511
512     status code is a numeric value.
513
514       for temporary failures, the status code should be -75
515
516       for permanent failures which are handled by RT, the status code 
517       should be 0
518     
519       for succces, the status code should be 1
520
521
522
523 =cut
524
525 sub Gateway {
526     my $argsref = shift;
527     my %args    = (
528         action  => 'correspond',
529         queue   => '1',
530         ticket  => undef,
531         message => undef,
532         %$argsref
533     );
534
535     my $SystemTicket;
536     my $Right;
537
538     # Validate the action
539     my ( $status, @actions ) = IsCorrectAction( $args{'action'} );
540     unless ($status) {
541         return (
542             -75,
543             "Invalid 'action' parameter "
544                 . $actions[0]
545                 . " for queue "
546                 . $args{'queue'},
547             undef
548         );
549     }
550
551     my $parser = RT::EmailParser->new();
552     $parser->SmartParseMIMEEntityFromScalar( Message => $args{'message'} );
553     my $Message = $parser->Entity();
554
555     unless ($Message) {
556         MailError(
557             To          => $RT::OwnerEmail,
558             Subject     => "RT Bounce: Unparseable message",
559             Explanation => "RT couldn't process the message below",
560             Attach      => $args{'message'}
561         );
562
563         return ( 0,
564             "Failed to parse this message. Something is likely badly wrong with the message"
565         );
566     }
567
568     my $head = $Message->head;
569
570     my $ErrorsTo = ParseErrorsToAddressFromHead($head);
571
572     my $MessageId = $head->get('Message-ID')
573         || "<no-message-id-" . time . rand(2000) . "\@.$RT::Organization>";
574
575     #Pull apart the subject line
576     my $Subject = $head->get('Subject') || '';
577     chomp $Subject;
578     
579     # {{{ Lets check for mail loops of various sorts.
580     my ($should_store_machine_generated_message, $IsALoop, $result);
581     ( $should_store_machine_generated_message, $ErrorsTo, $result, $IsALoop ) =
582       _HandleMachineGeneratedMail(
583         Message  => $Message,
584         ErrorsTo => $ErrorsTo,
585         Subject  => $Subject,
586         MessageId => $MessageId
587     );
588
589     # Do not pass loop messages to MailPlugins, to make sure the loop
590     # is broken, unless $RT::StoreLoops is set.
591     if ($IsALoop && !$should_store_machine_generated_message) {
592         return ( 0, $result, undef );
593     }
594
595     $args{'ticket'} ||= ParseTicketId($Subject);
596
597     $SystemTicket = RT::Ticket->new($RT::SystemUser);
598     $SystemTicket->Load( $args{'ticket'} ) if ( $args{'ticket'} ) ;
599     if ( $SystemTicket->id ) {
600         $Right = 'ReplyToTicket';
601     } else {
602         $Right = 'CreateTicket';
603     }
604
605     #Set up a queue object
606     my $SystemQueueObj = RT::Queue->new($RT::SystemUser);
607     $SystemQueueObj->Load( $args{'queue'} );
608
609     # We can safely have no queue of we have a known-good ticket
610     unless ( $SystemTicket->id || $SystemQueueObj->id ) {
611         return ( -75, "RT couldn't find the queue: " . $args{'queue'}, undef );
612     }
613
614     # Authentication Level ($AuthStat)
615     # -1 - Get out.  this user has been explicitly declined
616     # 0 - User may not do anything (Not used at the moment)
617     # 1 - Normal user
618     # 2 - User is allowed to specify status updates etc. a la enhanced-mailgate
619     my ( $CurrentUser, $AuthStat, $error );
620
621     # Initalize AuthStat so comparisons work correctly
622     $AuthStat = -9999999;
623
624     push @RT::MailPlugins, "Auth::MailFrom" unless @RT::MailPlugins;
625
626     # if plugin returns AuthStat -2 we skip action
627     # NOTE: this is experimental API and it would be changed
628     my %skip_action = ();
629
630     # Since this needs loading, no matter what
631     foreach (@RT::MailPlugins) {
632         my ($Code, $NewAuthStat);
633         if ( ref($_) eq "CODE" ) {
634             $Code = $_;
635         } else {
636             my $Class = $_;
637             $Class = "RT::Interface::Email::" . $Class
638                 unless $Class =~ /^RT::Interface::Email::/;
639             $Class->require or
640                 do { $RT::Logger->error("Couldn't load $Class: $@"); next };
641
642             no strict 'refs';
643             unless ( defined( $Code = *{ $Class . "::GetCurrentUser" }{CODE} ) ) {
644                 $RT::Logger->crit( "No 'GetCurrentUser' function found in '$Class' module");
645                 next;
646             }
647         }
648
649         foreach my $action (@actions) {
650             ( $CurrentUser, $NewAuthStat ) = $Code->(
651                 Message       => $Message,
652                 RawMessageRef => \$args{'message'},
653                 CurrentUser   => $CurrentUser,
654                 AuthLevel     => $AuthStat,
655                 Action        => $action,
656                 Ticket        => $SystemTicket,
657                 Queue         => $SystemQueueObj
658             );
659
660 # You get the highest level of authentication you were assigned, unless you get the magic -1
661 # If a module returns a "-1" then we discard the ticket, so.
662             $AuthStat = $NewAuthStat
663                 if ( $NewAuthStat > $AuthStat or $NewAuthStat == -1 or $NewAuthStat == -2 );
664
665             last if $AuthStat == -1;
666             $skip_action{$action}++ if $AuthStat == -2;
667         }
668
669         # strip actions we should skip
670         @actions = grep !$skip_action{$_}, @actions if $AuthStat == -2;
671         last unless @actions;
672
673         last if $AuthStat == -1;
674     }
675     # {{{ If authentication fails and no new user was created, get out.
676     if ( !$CurrentUser || !$CurrentUser->id || $AuthStat == -1 ) {
677
678         # If the plugins refused to create one, they lose.
679         unless ( $AuthStat == -1 ) {
680             _NoAuthorizedUserFound(
681                 Right     => $Right,
682                 Message   => $Message,
683                 Requestor => $ErrorsTo,
684                 Queue     => $args{'queue'}
685             );
686
687         }
688         return ( 0, "Could not load a valid user", undef );
689     }
690
691     # If we got a user, but they don't have the right to say things
692     if ( $AuthStat == 0 ) {
693         MailError(
694             To          => $ErrorsTo,
695             Subject     => "Permission Denied",
696             Explanation =>
697                 "You do not have permission to communicate with RT",
698             MIMEObj => $Message
699         );
700         return (
701             0,
702             "$ErrorsTo tried to submit a message to "
703                 . $args{'Queue'}
704                 . " without permission.",
705             undef
706         );
707     }
708
709
710     unless ($should_store_machine_generated_message) {
711         return ( 0, $result, undef );
712     }
713     
714     # if plugin's updated SystemTicket then update arguments
715     $args{'ticket'} = $SystemTicket->Id if $SystemTicket && $SystemTicket->Id;
716
717     my $Ticket = RT::Ticket->new($CurrentUser);
718
719     if ( !$args{'ticket'} && grep /^(comment|correspond)$/, @actions )
720     {
721
722         my @Cc;
723         my @Requestors = ( $CurrentUser->id );
724
725         if ($RT::ParseNewMessageForTicketCcs) {
726             @Cc = ParseCcAddressesFromHead(
727                 Head        => $head,
728                 CurrentUser => $CurrentUser,
729                 QueueObj    => $SystemQueueObj
730             );
731         }
732
733         my ( $id, $Transaction, $ErrStr ) = $Ticket->Create(
734             Queue     => $SystemQueueObj->Id,
735             Subject   => $Subject,
736             Requestor => \@Requestors,
737             Cc        => \@Cc,
738             MIMEObj   => $Message
739         );
740         if ( $id == 0 ) {
741             MailError(
742                 To          => $ErrorsTo,
743                 Subject     => "Ticket creation failed: $Subject",
744                 Explanation => $ErrStr,
745                 MIMEObj     => $Message
746             );
747             return ( 0, "Ticket creation failed: $ErrStr", $Ticket );
748         }
749
750         # strip comments&corresponds from the actions we don't need
751         # to record them if we've created the ticket just now
752         @actions = grep !/^(comment|correspond)$/, @actions;
753         $args{'ticket'} = $id;
754
755     } elsif ( $args{'ticket'} ) {
756
757         $Ticket->Load( $args{'ticket'} );
758         unless ( $Ticket->Id ) {
759             my $error = "Could not find a ticket with id " . $args{'ticket'};
760             MailError(
761                 To          => $ErrorsTo,
762                 Subject     => "Message not recorded: $Subject",
763                 Explanation => $error,
764                 MIMEObj     => $Message
765             );
766
767             return ( 0, $error );
768         }
769         $args{'ticket'} = $Ticket->id;
770     } else {
771         return ( 1, "Success", $Ticket );
772     }
773
774     # }}}
775     foreach my $action (@actions) {
776
777         #   If the action is comment, add a comment.
778         if ( $action =~ /^(?:comment|correspond)$/i ) {
779             my $method = ucfirst lc $action;
780             my ( $status, $msg ) = $Ticket->$method( MIMEObj => $Message );
781             unless ($status) {
782
783                 #Warn the sender that we couldn't actually submit the comment.
784                 MailError(
785                     To          => $ErrorsTo,
786                     Subject     => "Message not recorded: $Subject",
787                     Explanation => $msg,
788                     MIMEObj     => $Message
789                 );
790                 return ( 0, "Message not recorded: $msg", $Ticket );
791             }
792         } elsif ($RT::UnsafeEmailCommands) {
793             my ( $status, $msg ) = _RunUnsafeAction(
794                 Action      => $action,
795                 ErrorsTo    => $ErrorsTo,
796                 Message     => $Message,
797                 Ticket      => $Ticket,
798                 CurrentUser => $CurrentUser,
799             );
800             return ($status, $msg, $Ticket) unless $status == 1;
801         }
802     }
803     return ( 1, "Success", $Ticket );
804 }
805
806 sub _RunUnsafeAction {
807     my %args = (
808         Action      => undef,
809         ErrorsTo    => undef,
810         Message     => undef,
811         Ticket      => undef,
812         CurrentUser => undef,
813         @_
814     );
815
816     if ( $args{'Action'} =~ /^take$/i ) {
817         my ( $status, $msg ) = $args{'Ticket'}->SetOwner( $args{'CurrentUser'}->id );
818         unless ($status) {
819             MailError(
820                 To          => $args{'ErrorsTo'},
821                 Subject     => "Ticket not taken",
822                 Explanation => $msg,
823                 MIMEObj     => $args{'Message'}
824             );
825             return ( 0, "Ticket not taken" );
826         }
827     } elsif ( $args{'Action'} =~ /^resolve$/i ) {
828         my ( $status, $msg ) = $args{'Ticket'}->SetStatus('resolved');
829         unless ($status) {
830
831             #Warn the sender that we couldn't actually submit the comment.
832             MailError(
833                 To          => $args{'ErrorsTo'},
834                 Subject     => "Ticket not resolved",
835                 Explanation => $msg,
836                 MIMEObj     => $args{'Message'}
837             );
838             return ( 0, "Ticket not resolved" );
839         }
840     } else {
841         return ( 0, "Not supported unsafe action $args{'Action'}", $args{'Ticket'} );
842     }
843     return ( 1, "Success" );
844 }
845
846 =head2 _NoAuthorizedUserFound
847
848 Emails the RT Owner and the requestor when the auth plugins return "No auth user found"
849
850 =cut
851
852 sub _NoAuthorizedUserFound {
853     my %args = (
854         Right     => undef,
855         Message   => undef,
856         Requestor => undef,
857         Queue     => undef,
858         @_
859     );
860
861     # Notify the RT Admin of the failure.
862     MailError(
863         To          => $RT::OwnerEmail,
864         Subject     => "Could not load a valid user",
865         Explanation => <<EOT,
866 RT could not load a valid user, and RT's configuration does not allow
867 for the creation of a new user for this email (@{[$args{Requestor}]}).
868
869 You might need to grant 'Everyone' the right '@{[$args{Right}]}' for the
870 queue @{[$args{'Queue'}]}.
871
872 EOT
873         MIMEObj  => $args{'Message'},
874         LogLevel => 'error'
875     );
876
877     # Also notify the requestor that his request has been dropped.
878     if ($args{'Requestor'} ne $RT::OwnerEmail) {
879     MailError(
880         To          => $args{'Requestor'},
881         Subject     => "Could not load a valid user",
882         Explanation => <<EOT,
883 RT could not load a valid user, and RT's configuration does not allow
884 for the creation of a new user for your email.
885
886 EOT
887         MIMEObj  => $args{'Message'},
888         LogLevel => 'error'
889     );
890     }
891 }
892
893 =head2 _HandleMachineGeneratedMail
894
895 Takes named params:
896     Message
897     ErrorsTo
898     Subject
899
900 Checks the message to see if it's a bounce, if it looks like a loop, if it's autogenerated, etc.
901 Returns a triple of ("Should we continue (boolean)", "New value for $ErrorsTo", "Status message",
902 "This message appears to be a loop (boolean)" );
903
904 =cut
905
906 sub _HandleMachineGeneratedMail {
907     my %args = ( Message => undef, ErrorsTo => undef, Subject => undef, MessageId => undef, @_ );
908     my $head = $args{'Message'}->head;
909     my $ErrorsTo = $args{'ErrorsTo'};
910
911     my $IsBounce = CheckForBounce($head);
912
913     my $IsAutoGenerated = CheckForAutoGenerated($head);
914
915     my $IsSuspiciousSender = CheckForSuspiciousSender($head);
916
917     my $IsALoop = CheckForLoops($head);
918
919     my $SquelchReplies = 0;
920
921     #If the message is autogenerated, we need to know, so we can not
922     # send mail to the sender
923     if ( $IsBounce || $IsSuspiciousSender || $IsAutoGenerated || $IsALoop ) {
924         $SquelchReplies = 1;
925         $ErrorsTo       = $RT::OwnerEmail;
926     }
927
928     # Warn someone if it's a loop, before we drop it on the ground
929     if ($IsALoop) {
930         $RT::Logger->crit("RT Received mail (".$args{MessageId}.") from itself.");
931
932         #Should we mail it to RTOwner?
933         if ($RT::LoopsToRTOwner) {
934             MailError(
935                 To          => $RT::OwnerEmail,
936                 Subject     => "RT Bounce: ".$args{'Subject'},
937                 Explanation => "RT thinks this message may be a bounce",
938                 MIMEObj     => $args{Message}
939             );
940         }
941
942         #Do we actually want to store it?
943         return ( 0, $ErrorsTo, "Message Bounced", $IsALoop ) unless ($RT::StoreLoops);
944     }
945
946     # Squelch replies if necessary
947     # Don't let the user stuff the RT-Squelch-Replies-To header.
948     if ( $head->get('RT-Squelch-Replies-To') ) {
949         $head->add(
950             'RT-Relocated-Squelch-Replies-To',
951             $head->get('RT-Squelch-Replies-To')
952         );
953         $head->delete('RT-Squelch-Replies-To');
954     }
955
956     if ($SquelchReplies) {
957
958         # Squelch replies to the sender, and also leave a clue to
959         # allow us to squelch ALL outbound messages. This way we
960         # can punt the logic of "what to do when we get a bounce"
961         # to the scrip. We might want to notify nobody. Or just
962         # the RT Owner. Or maybe all Privileged watchers.
963         my ( $Sender, $junk ) = ParseSenderAddressFromHead($head);
964         $head->add( 'RT-Squelch-Replies-To',    $Sender );
965         $head->add( 'RT-DetectedAutoGenerated', 'true' );
966     }
967     return ( 1, $ErrorsTo, "Handled machine detection", $IsALoop );
968 }
969
970 =head2 IsCorrectAction
971
972 Returns a list of valid actions we've found for this message
973
974 =cut
975
976 sub IsCorrectAction {
977     my $action = shift;
978     my @actions = grep $_, split /-/, $action;
979     return ( 0, '(no value)' ) unless @actions;
980     foreach (@actions) {
981         return ( 0, $_ ) unless /^(?:comment|correspond|take|resolve)$/;
982     }
983     return ( 1, @actions );
984 }
985
986 eval "require RT::Interface::Email_Vendor";
987 die $@ if ( $@ && $@ !~ qr{^Can't locate RT/Interface/Email_Vendor.pm} );
988 eval "require RT::Interface::Email_Local";
989 die $@ if ( $@ && $@ !~ qr{^Can't locate RT/Interface/Email_Local.pm} );
990
991 1;