import rt 3.6.4
[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     my $From = $head->get('Reply-To')
400         || $head->get('From')
401         || $head->get('Sender');
402     return ( ParseAddressFromHeader($From) );
403 }
404
405 # }}}
406
407 # {{{ ParseErrorsToAdddressFromHead
408
409 =head2 ParseErrorsToAddressFromHead
410
411 Takes a MIME::Header object. Return a single value : user@host
412 of the From (evaluated in order of Return-path:,Errors-To:,Reply-To:,
413 From:, Sender)
414
415 =cut
416
417 sub ParseErrorsToAddressFromHead {
418     my $head = shift;
419
420     #Figure out who's sending this message.
421
422     foreach my $header ( 'Errors-To', 'Reply-To', 'From', 'Sender' ) {
423
424         # If there's a header of that name
425         my $headerobj = $head->get($header);
426         if ($headerobj) {
427             my ( $addr, $name ) = ParseAddressFromHeader($headerobj);
428
429             # If it's got actual useful content...
430             return ($addr) if ($addr);
431         }
432     }
433 }
434
435 # }}}
436
437 # {{{ ParseAddressFromHeader
438
439 =head2 ParseAddressFromHeader ADDRESS
440
441 Takes an address from $head->get('Line') and returns a tuple: user@host, friendly name
442
443 =cut
444
445 sub ParseAddressFromHeader {
446     my $Addr = shift;
447
448     # Some broken mailers send:  ""Vincent, Jesse"" <jesse@fsck.com>. Hate
449     $Addr =~ s/\"\"(.*?)\"\"/\"$1\"/g;                                                                                                                                                  
450     my @Addresses = Mail::Address->parse($Addr);
451
452     my ($AddrObj) = grep ref $_, @Addresses;
453     unless ( $AddrObj ) {
454         return ( undef, undef );
455     }
456
457     my $Name = ( $AddrObj->phrase || $AddrObj->comment || $AddrObj->address );
458
459     #Lets take the from and load a user object.
460     my $Address = $AddrObj->address;
461
462     return ( $Address, $Name );
463 }
464
465 # }}}
466
467 # {{{ sub ParseTicketId
468
469 sub ParseTicketId {
470     my $Subject = shift;
471     my $id;
472
473     my $test_name = $RT::EmailSubjectTagRegex || qr/\Q$RT::rtname\E/i;
474
475     if ( $Subject =~ s/\[$test_name\s+\#(\d+)\s*\]//i ) {
476         my $id = $1;
477         $RT::Logger->debug("Found a ticket ID. It's $id");
478         return ($id);
479     } else {
480         return (undef);
481     }
482 }
483
484 # }}}
485
486 =head2 Gateway ARGSREF
487
488
489 Takes parameters:
490
491     action
492     queue
493     message
494
495
496 This performs all the "guts" of the mail rt-mailgate program, and is
497 designed to be called from the web interface with a message, user
498 object, and so on.
499
500 Can also take an optional 'ticket' parameter; this ticket id overrides
501 any ticket id found in the subject.
502
503 Returns:
504
505     An array of:
506     
507     (status code, message, optional ticket object)
508
509     status code is a numeric value.
510
511       for temporary failures, the status code should be -75
512
513       for permanent failures which are handled by RT, the status code 
514       should be 0
515     
516       for succces, the status code should be 1
517
518
519
520 =cut
521
522 sub Gateway {
523     my $argsref = shift;
524     my %args    = (
525         action  => 'correspond',
526         queue   => '1',
527         ticket  => undef,
528         message => undef,
529         %$argsref
530     );
531
532     my $SystemTicket;
533     my $Right;
534
535     # Validate the action
536     my ( $status, @actions ) = IsCorrectAction( $args{'action'} );
537     unless ($status) {
538         return (
539             -75,
540             "Invalid 'action' parameter "
541                 . $actions[0]
542                 . " for queue "
543                 . $args{'queue'},
544             undef
545         );
546     }
547
548     my $parser = RT::EmailParser->new();
549     $parser->SmartParseMIMEEntityFromScalar( Message => $args{'message'} );
550     my $Message = $parser->Entity();
551
552     unless ($Message) {
553         MailError(
554             To          => $RT::OwnerEmail,
555             Subject     => "RT Bounce: Unparseable message",
556             Explanation => "RT couldn't process the message below",
557             Attach      => $args{'message'}
558         );
559
560         return ( 0,
561             "Failed to parse this message. Something is likely badly wrong with the message"
562         );
563     }
564
565     my $head = $Message->head;
566
567     my $ErrorsTo = ParseErrorsToAddressFromHead($head);
568
569     my $MessageId = $head->get('Message-ID')
570         || "<no-message-id-" . time . rand(2000) . "\@.$RT::Organization>";
571
572     #Pull apart the subject line
573     my $Subject = $head->get('Subject') || '';
574     chomp $Subject;
575     
576     # {{{ Lets check for mail loops of various sorts.
577     my ($should_store_machine_generated_message, $IsALoop, $result);
578     ( $should_store_machine_generated_message, $ErrorsTo, $result, $IsALoop ) =
579       _HandleMachineGeneratedMail(
580         Message  => $Message,
581         ErrorsTo => $ErrorsTo,
582         Subject  => $Subject,
583         MessageId => $MessageId
584     );
585
586     # Do not pass loop messages to MailPlugins, to make sure the loop
587     # is broken, unless $RT::StoreLoops is set.
588     if ($IsALoop && !$should_store_machine_generated_message) {
589         return ( 0, $result, undef );
590     }
591
592     $args{'ticket'} ||= ParseTicketId($Subject);
593
594     $SystemTicket = RT::Ticket->new($RT::SystemUser);
595     $SystemTicket->Load( $args{'ticket'} ) if ( $args{'ticket'} ) ;
596     if ( $SystemTicket->id ) {
597         $Right = 'ReplyToTicket';
598     } else {
599         $Right = 'CreateTicket';
600     }
601
602     #Set up a queue object
603     my $SystemQueueObj = RT::Queue->new($RT::SystemUser);
604     $SystemQueueObj->Load( $args{'queue'} );
605
606     # We can safely have no queue of we have a known-good ticket
607     unless ( $SystemTicket->id || $SystemQueueObj->id ) {
608         return ( -75, "RT couldn't find the queue: " . $args{'queue'}, undef );
609     }
610
611     # Authentication Level ($AuthStat)
612     # -1 - Get out.  this user has been explicitly declined
613     # 0 - User may not do anything (Not used at the moment)
614     # 1 - Normal user
615     # 2 - User is allowed to specify status updates etc. a la enhanced-mailgate
616     my ( $CurrentUser, $AuthStat, $error );
617
618     # Initalize AuthStat so comparisons work correctly
619     $AuthStat = -9999999;
620
621     push @RT::MailPlugins, "Auth::MailFrom" unless @RT::MailPlugins;
622
623     # if plugin returns AuthStat -2 we skip action
624     # NOTE: this is experimental API and it would be changed
625     my %skip_action = ();
626
627     # Since this needs loading, no matter what
628     foreach (@RT::MailPlugins) {
629         my ($Code, $NewAuthStat);
630         if ( ref($_) eq "CODE" ) {
631             $Code = $_;
632         } else {
633             my $Class = $_;
634             $Class = "RT::Interface::Email::" . $Class
635                 unless $Class =~ /^RT::Interface::Email::/;
636             $Class->require or
637                 do { $RT::Logger->error("Couldn't load $Class: $@"); next };
638
639             no strict 'refs';
640             unless ( defined( $Code = *{ $Class . "::GetCurrentUser" }{CODE} ) ) {
641                 $RT::Logger->crit( "No 'GetCurrentUser' function found in '$Class' module");
642                 next;
643             }
644         }
645
646         foreach my $action (@actions) {
647             ( $CurrentUser, $NewAuthStat ) = $Code->(
648                 Message       => $Message,
649                 RawMessageRef => \$args{'message'},
650                 CurrentUser   => $CurrentUser,
651                 AuthLevel     => $AuthStat,
652                 Action        => $action,
653                 Ticket        => $SystemTicket,
654                 Queue         => $SystemQueueObj
655             );
656
657 # You get the highest level of authentication you were assigned, unless you get the magic -1
658 # If a module returns a "-1" then we discard the ticket, so.
659             $AuthStat = $NewAuthStat
660                 if ( $NewAuthStat > $AuthStat or $NewAuthStat == -1 or $NewAuthStat == -2 );
661
662             last if $AuthStat == -1;
663             $skip_action{$action}++ if $AuthStat == -2;
664         }
665
666         # strip actions we should skip
667         @actions = grep !$skip_action{$_}, @actions if $AuthStat == -2;
668         last unless @actions;
669
670         last if $AuthStat == -1;
671     }
672     # {{{ If authentication fails and no new user was created, get out.
673     if ( !$CurrentUser || !$CurrentUser->id || $AuthStat == -1 ) {
674
675         # If the plugins refused to create one, they lose.
676         unless ( $AuthStat == -1 ) {
677             _NoAuthorizedUserFound(
678                 Right     => $Right,
679                 Message   => $Message,
680                 Requestor => $ErrorsTo,
681                 Queue     => $args{'queue'}
682             );
683
684         }
685         return ( 0, "Could not load a valid user", undef );
686     }
687
688     # If we got a user, but they don't have the right to say things
689     if ( $AuthStat == 0 ) {
690         MailError(
691             To          => $ErrorsTo,
692             Subject     => "Permission Denied",
693             Explanation =>
694                 "You do not have permission to communicate with RT",
695             MIMEObj => $Message
696         );
697         return (
698             0,
699             "$ErrorsTo tried to submit a message to "
700                 . $args{'Queue'}
701                 . " without permission.",
702             undef
703         );
704     }
705
706
707     unless ($should_store_machine_generated_message) {
708         return ( 0, $result, undef );
709     }
710     
711     # if plugin's updated SystemTicket then update arguments
712     $args{'ticket'} = $SystemTicket->Id if $SystemTicket && $SystemTicket->Id;
713
714     my $Ticket = RT::Ticket->new($CurrentUser);
715
716     if ( !$args{'ticket'} && grep /^(comment|correspond)$/, @actions )
717     {
718
719         my @Cc;
720         my @Requestors = ( $CurrentUser->id );
721
722         if ($RT::ParseNewMessageForTicketCcs) {
723             @Cc = ParseCcAddressesFromHead(
724                 Head        => $head,
725                 CurrentUser => $CurrentUser,
726                 QueueObj    => $SystemQueueObj
727             );
728         }
729
730         my ( $id, $Transaction, $ErrStr ) = $Ticket->Create(
731             Queue     => $SystemQueueObj->Id,
732             Subject   => $Subject,
733             Requestor => \@Requestors,
734             Cc        => \@Cc,
735             MIMEObj   => $Message
736         );
737         if ( $id == 0 ) {
738             MailError(
739                 To          => $ErrorsTo,
740                 Subject     => "Ticket creation failed: $Subject",
741                 Explanation => $ErrStr,
742                 MIMEObj     => $Message
743             );
744             return ( 0, "Ticket creation failed: $ErrStr", $Ticket );
745         }
746
747         # strip comments&corresponds from the actions we don't need
748         # to record them if we've created the ticket just now
749         @actions = grep !/^(comment|correspond)$/, @actions;
750         $args{'ticket'} = $id;
751
752     } elsif ( $args{'ticket'} ) {
753
754         $Ticket->Load( $args{'ticket'} );
755         unless ( $Ticket->Id ) {
756             my $error = "Could not find a ticket with id " . $args{'ticket'};
757             MailError(
758                 To          => $ErrorsTo,
759                 Subject     => "Message not recorded: $Subject",
760                 Explanation => $error,
761                 MIMEObj     => $Message
762             );
763
764             return ( 0, $error );
765         }
766         $args{'ticket'} = $Ticket->id;
767     } else {
768         return ( 1, "Success", $Ticket );
769     }
770
771     # }}}
772     foreach my $action (@actions) {
773
774         #   If the action is comment, add a comment.
775         if ( $action =~ /^(?:comment|correspond)$/i ) {
776             my $method = ucfirst lc $action;
777             my ( $status, $msg ) = $Ticket->$method( MIMEObj => $Message );
778             unless ($status) {
779
780                 #Warn the sender that we couldn't actually submit the comment.
781                 MailError(
782                     To          => $ErrorsTo,
783                     Subject     => "Message not recorded: $Subject",
784                     Explanation => $msg,
785                     MIMEObj     => $Message
786                 );
787                 return ( 0, "Message not recorded: $msg", $Ticket );
788             }
789         } elsif ($RT::UnsafeEmailCommands) {
790             my ( $status, $msg ) = _RunUnsafeAction(
791                 Action      => $action,
792                 ErrorsTo    => $ErrorsTo,
793                 Message     => $Message,
794                 Ticket      => $Ticket,
795                 CurrentUser => $CurrentUser,
796             );
797             return ($status, $msg, $Ticket) unless $status == 1;
798         }
799     }
800     return ( 1, "Success", $Ticket );
801 }
802
803 sub _RunUnsafeAction {
804     my %args = (
805         Action      => undef,
806         ErrorsTo    => undef,
807         Message     => undef,
808         Ticket      => undef,
809         CurrentUser => undef,
810         @_
811     );
812
813     if ( $args{'Action'} =~ /^take$/i ) {
814         my ( $status, $msg ) = $args{'Ticket'}->SetOwner( $args{'CurrentUser'}->id );
815         unless ($status) {
816             MailError(
817                 To          => $args{'ErrorsTo'},
818                 Subject     => "Ticket not taken",
819                 Explanation => $msg,
820                 MIMEObj     => $args{'Message'}
821             );
822             return ( 0, "Ticket not taken" );
823         }
824     } elsif ( $args{'Action'} =~ /^resolve$/i ) {
825         my ( $status, $msg ) = $args{'Ticket'}->SetStatus('resolved');
826         unless ($status) {
827
828             #Warn the sender that we couldn't actually submit the comment.
829             MailError(
830                 To          => $args{'ErrorsTo'},
831                 Subject     => "Ticket not resolved",
832                 Explanation => $msg,
833                 MIMEObj     => $args{'Message'}
834             );
835             return ( 0, "Ticket not resolved" );
836         }
837     } else {
838         return ( 0, "Not supported unsafe action $args{'Action'}", $args{'Ticket'} );
839     }
840     return ( 1, "Success" );
841 }
842
843 =head2 _NoAuthorizedUserFound
844
845 Emails the RT Owner and the requestor when the auth plugins return "No auth user found"
846
847 =cut
848
849 sub _NoAuthorizedUserFound {
850     my %args = (
851         Right     => undef,
852         Message   => undef,
853         Requestor => undef,
854         Queue     => undef,
855         @_
856     );
857
858     # Notify the RT Admin of the failure.
859     MailError(
860         To          => $RT::OwnerEmail,
861         Subject     => "Could not load a valid user",
862         Explanation => <<EOT,
863 RT could not load a valid user, and RT's configuration does not allow
864 for the creation of a new user for this email (@{[$args{Requestor}]}).
865
866 You might need to grant 'Everyone' the right '@{[$args{Right}]}' for the
867 queue @{[$args{'Queue'}]}.
868
869 EOT
870         MIMEObj  => $args{'Message'},
871         LogLevel => 'error'
872     );
873
874     # Also notify the requestor that his request has been dropped.
875     if ($args{'Requestor'} ne $RT::OwnerEmail) {
876     MailError(
877         To          => $args{'Requestor'},
878         Subject     => "Could not load a valid user",
879         Explanation => <<EOT,
880 RT could not load a valid user, and RT's configuration does not allow
881 for the creation of a new user for your email.
882
883 EOT
884         MIMEObj  => $args{'Message'},
885         LogLevel => 'error'
886     );
887     }
888 }
889
890 =head2 _HandleMachineGeneratedMail
891
892 Takes named params:
893     Message
894     ErrorsTo
895     Subject
896
897 Checks the message to see if it's a bounce, if it looks like a loop, if it's autogenerated, etc.
898 Returns a triple of ("Should we continue (boolean)", "New value for $ErrorsTo", "Status message",
899 "This message appears to be a loop (boolean)" );
900
901 =cut
902
903 sub _HandleMachineGeneratedMail {
904     my %args = ( Message => undef, ErrorsTo => undef, Subject => undef, MessageId => undef, @_ );
905     my $head = $args{'Message'}->head;
906     my $ErrorsTo = $args{'ErrorsTo'};
907
908     my $IsBounce = CheckForBounce($head);
909
910     my $IsAutoGenerated = CheckForAutoGenerated($head);
911
912     my $IsSuspiciousSender = CheckForSuspiciousSender($head);
913
914     my $IsALoop = CheckForLoops($head);
915
916     my $SquelchReplies = 0;
917
918     #If the message is autogenerated, we need to know, so we can not
919     # send mail to the sender
920     if ( $IsBounce || $IsSuspiciousSender || $IsAutoGenerated || $IsALoop ) {
921         $SquelchReplies = 1;
922         $ErrorsTo       = $RT::OwnerEmail;
923     }
924
925     # Warn someone if it's a loop, before we drop it on the ground
926     if ($IsALoop) {
927         $RT::Logger->crit("RT Received mail (".$args{MessageId}.") from itself.");
928
929         #Should we mail it to RTOwner?
930         if ($RT::LoopsToRTOwner) {
931             MailError(
932                 To          => $RT::OwnerEmail,
933                 Subject     => "RT Bounce: ".$args{'Subject'},
934                 Explanation => "RT thinks this message may be a bounce",
935                 MIMEObj     => $args{Message}
936             );
937         }
938
939         #Do we actually want to store it?
940         return ( 0, $ErrorsTo, "Message Bounced", $IsALoop ) unless ($RT::StoreLoops);
941     }
942
943     # Squelch replies if necessary
944     # Don't let the user stuff the RT-Squelch-Replies-To header.
945     if ( $head->get('RT-Squelch-Replies-To') ) {
946         $head->add(
947             'RT-Relocated-Squelch-Replies-To',
948             $head->get('RT-Squelch-Replies-To')
949         );
950         $head->delete('RT-Squelch-Replies-To');
951     }
952
953     if ($SquelchReplies) {
954
955         # Squelch replies to the sender, and also leave a clue to
956         # allow us to squelch ALL outbound messages. This way we
957         # can punt the logic of "what to do when we get a bounce"
958         # to the scrip. We might want to notify nobody. Or just
959         # the RT Owner. Or maybe all Privileged watchers.
960         my ( $Sender, $junk ) = ParseSenderAddressFromHead($head);
961         $head->add( 'RT-Squelch-Replies-To',    $Sender );
962         $head->add( 'RT-DetectedAutoGenerated', 'true' );
963     }
964     return ( 1, $ErrorsTo, "Handled machine detection", $IsALoop );
965 }
966
967 =head2 IsCorrectAction
968
969 Returns a list of valid actions we've found for this message
970
971 =cut
972
973 sub IsCorrectAction {
974     my $action = shift;
975     my @actions = grep $_, split /-/, $action;
976     return ( 0, '(no value)' ) unless @actions;
977     foreach (@actions) {
978         return ( 0, $_ ) unless /^(?:comment|correspond|take|resolve)$/;
979     }
980     return ( 1, @actions );
981 }
982
983 eval "require RT::Interface::Email_Vendor";
984 die $@ if ( $@ && $@ !~ qr{^Can't locate RT/Interface/Email_Vendor.pm} );
985 eval "require RT::Interface::Email_Local";
986 die $@ if ( $@ && $@ !~ qr{^Can't locate RT/Interface/Email_Local.pm} );
987
988 1;