[Rt-commit] r5240 - in RT-Extension-CommandByEmail: .

ruz at bestpractical.com ruz at bestpractical.com
Tue May 16 21:54:52 EDT 2006


Author: ruz
Date: Tue May 16 21:54:51 2006
New Revision: 5240

Added:
   RT-Extension-CommandByEmail/INSTALL
   RT-Extension-CommandByEmail/patch/
   RT-Extension-CommandByEmail/patch/command_by_email-0.1-RT-3.4.5.patch
Modified:
   RT-Extension-CommandByEmail/README

Log:
* installation instructions
* README update
* patch for RT-3.4.5

Added: RT-Extension-CommandByEmail/INSTALL
==============================================================================
--- (empty file)
+++ RT-Extension-CommandByEmail/INSTALL	Tue May 16 21:54:51 2006
@@ -0,0 +1,28 @@
+INSTALLATION
+
+To install this module, run the following commands:
+
+    perl Makefile.PL
+    make
+    make install
+
+PATCH
+
+This extension requres patching RT. Patch(es) is in patch directory.
+Apply patch with following commands:
+
+    cd /opt/rt3
+    patch -p0 <path/to/patch/command_by_mail-<patch version>-RT-<rt version>.patch
+
+You MUST apply patch in order to use this extension. Use patch with greatest <patch version>,
+old patches would be shipped with distribution to help you revert old patch(es) and apply new
+one on upgrades.
+
+CONFIGURE
+
+Add 'Filter::TakeAction' to the list of mail plugins in the RT config. Restart web server.
+Note that extension should be pushed into list after Auth::MailFrom or similar plugin that
+loads current user object.
+
+Enjoy.
+

Modified: RT-Extension-CommandByEmail/README
==============================================================================
--- RT-Extension-CommandByEmail/README	(original)
+++ RT-Extension-CommandByEmail/README	Tue May 16 21:54:51 2006
@@ -1,35 +1,8 @@
 RT-Extension-CommandByMail version 0.0.1
 
-[ REPLACE THIS...
-
-  The README is used to introduce the module and provide instructions on
-  how to install the module, any machine dependencies it may have (for
-  example C compilers and installed libraries) and any other information
-  that should be understood before the module is installed.
-
-  A README file is required for CPAN modules since CPAN extracts the
-  README file from a module distribution so that people browsing the
-  archive can use it get an idea of the modules uses. It is usually a
-  good idea to provide version information here so that people can
-  decide whether fixes for the module are worth downloading.
-]
-
-
 INSTALLATION
 
-To install this module, run the following commands:
-
-    perl Makefile.PL
-    make
-    make test
-    make install
-
-
-
-DEPENDENCIES
-
-None.
-
+Read INSTALL file to get more info about installation.
 
 COPYRIGHT AND LICENCE
 

Added: RT-Extension-CommandByEmail/patch/command_by_email-0.1-RT-3.4.5.patch
==============================================================================
--- (empty file)
+++ RT-Extension-CommandByEmail/patch/command_by_email-0.1-RT-3.4.5.patch	Tue May 16 21:54:51 2006
@@ -0,0 +1,967 @@
+--- lib/RT/Interface/Email.pm	(revision 1627)
++++ lib/RT/Interface/Email.pm	(local)
+@@ -50,13 +50,14 @@
+ use MIME::Entity;
+ use RT::EmailParser;
+ use File::Temp;
++use UNIVERSAL::require;
+ 
+ BEGIN {
+     use Exporter ();
+-    use vars qw ($VERSION  @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
++    use vars qw ( @ISA @EXPORT_OK);
+     
+     # set the version for version checking
+-    $VERSION = do { my @r = (q$Revision: 1.2 $ =~ /\d+/g); sprintf "%d."."%02d" x $#r, @r }; # must be all one line, for MakeMaker
++    our $VERSION = 2.0;
+     
+     @ISA         = qw(Exporter);
+     
+@@ -111,8 +111,8 @@
+     
+     #If this instance of RT sent it our, we don't want to take it in
+     my $RTLoop = $head->get("X-RT-Loop-Prevention") || "";
+-    chomp ($RTLoop); #remove that newline
+-    if ($RTLoop eq "$RT::rtname") {
++    chomp($RTLoop);    #remove that newline
++    if ( $RTLoop eq "$RT::rtname" ) {
+ 	return (1);
+     }
+     
+@@ -138,10 +138,11 @@
+     
+     #TODO: search through the whole email and find the right Ticket ID.
+ 
+-    my ($From, $junk) = ParseSenderAddressFromHead($head);
++    my ( $From, $junk ) = ParseSenderAddressFromHead($head);
+     
+-    if (($From =~ /^mailer-daemon\@/i) or
+-	($From =~ /^postmaster\@/i)){
++    if (   ( $From =~ /^mailer-daemon\@/i )
++        or ( $From =~ /^postmaster\@/i ) )
++    {
+ 	return (1);
+ 	
+     }
+@@ -156,14 +157,14 @@
+ sub CheckForAutoGenerated {
+     my $head = shift;
+     
+-    my $Precedence = $head->get("Precedence") || "" ;
+-    if ($Precedence =~ /^(bulk|junk)/i) {
++    my $Precedence = $head->get("Precedence") || "";
++    if ( $Precedence =~ /^(bulk|junk)/i ) {
+ 	return (1);
+     }
+     
+     # First Class mailer uses this as a clue.
+     my $FCJunk = $head->get("X-FC-Machinegenerated") || "";
+-    if ($FCJunk =~ /^true/i) {
++    if ( $FCJunk =~ /^true/i ) {
+         return (1);
+     }
+ 
+@@ -176,8 +177,8 @@
+ sub CheckForBounce {
+     my $head = shift;
+    
+-    my $ReturnPath = $head->get("Return-path") || "" ;
+-    return ($ReturnPath =~ /<>/);
++    my $ReturnPath = $head->get("Return-path") || "";
++    return ( $ReturnPath =~ /<>/ );
+ }
+ 
+ # }}}
+@@ -197,9 +198,10 @@
+ 
+     # Example: the following rule would tell RT not to Cc 
+     #   "tickets at noc.example.com"
+-    if ( defined($RT::RTAddressRegexp) &&
+-                       $address =~ /$RT::RTAddressRegexp/i ) {
+-        return(1);
++    if ( defined($RT::RTAddressRegexp)
++        && $address =~ /$RT::RTAddressRegexp/i )
++    {
++        return (1);
+     } else {
+         return (undef);
+     }
+@@ -217,14 +219,15 @@
+ =cut
+ 
+ sub CullRTAddresses {
+-    return (grep { IsRTAddress($_) } @_);
++    return ( grep { IsRTAddress($_) } @_ );
+ }
+ 
+ # }}}
+ 
+ # {{{ sub MailError 
+ sub MailError {
+-    my %args = (To => $RT::OwnerEmail,
++    my %args = (
++        To          => $RT::OwnerEmail,
+ 		Bcc => undef,
+ 		From => $RT::CorrespondAddress,
+ 		Subject => 'There has been an error',
+@@ -232,13 +235,15 @@
+ 		MIMEObj => undef,
+         Attach => undef,
+ 		LogLevel => 'crit',
+-		@_);
+-
++        @_
++    );
+ 
+-    $RT::Logger->log(level => $args{'LogLevel'}, 
++    $RT::Logger->log(
++        level   => $args{'LogLevel'},
+ 		     message => $args{'Explanation'}
+ 		    );
+-    my $entity = MIME::Entity->build( Type  =>"multipart/mixed",
++    my $entity = MIME::Entity->build(
++        Type                   => "multipart/mixed",
+ 				      From => $args{'From'},
+ 				      Bcc => $args{'Bcc'},
+ 				      To => $args{'To'},
+@@ -247,7 +252,7 @@
+ 				      'X-RT-Loop-Prevention' => $RT::rtname,
+ 				    );
+ 
+-    $entity->attach(  Data => $args{'Explanation'}."\n");
++    $entity->attach( Data => $args{'Explanation'} . "\n" );
+     
+     my $mimeobj = $args{'MIMEObj'};
+     if ($mimeobj) {
+@@ -255,18 +260,20 @@
+         $entity->add_part($mimeobj);
+     }
+    
+-    if ($args{'Attach'}) {
+-        $entity->attach(Data => $args{'Attach'}, Type => 'message/rfc822');
++    if ( $args{'Attach'} ) {
++        $entity->attach( Data => $args{'Attach'}, Type => 'message/rfc822' );
+ 
+     }
+ 
+-    if ($RT::MailCommand eq 'sendmailpipe') {
+-        open (MAIL, "|$RT::SendmailPath $RT::SendmailBounceArguments $RT::SendmailArguments") || return(0);
++    if ( $RT::MailCommand eq 'sendmailpipe' ) {
++        open( MAIL,
++            "|$RT::SendmailPath $RT::SendmailBounceArguments $RT::SendmailArguments"
++            )
++            || return (0);
+         print MAIL $entity->as_string;
+         close(MAIL);
+-    }
+-    else {
+-    	$entity->send($RT::MailCommand, $RT::MailParams);
++    } else {
++        $entity->send( $RT::MailCommand, $RT::MailParams );
+     }
+ }
+ 
+@@ -275,11 +282,11 @@
+ # {{{ Create User
+ 
+ sub CreateUser {
+-    my ($Username, $Address, $Name, $ErrorsTo, $entity) = @_;
++    my ( $Username, $Address, $Name, $ErrorsTo, $entity ) = @_;
+     my $NewUser = RT::User->new($RT::SystemUser);
+ 
+-    my ($Val, $Message) = 
+-      $NewUser->Create(Name => ($Username || $Address),
++    my ( $Val, $Message ) = $NewUser->Create(
++        Name => ( $Username || $Address ),
+                        EmailAddress => $Address,
+                        RealName => $Name,
+                        Password => undef,
+@@ -295,14 +302,16 @@
+             $NewUser->LoadByName($Username);
+         }
+         
+-        unless ($NewUser->Id) {
++        unless ( $NewUser->Id ) {
+             $NewUser->LoadByEmail($Address);
+         }
+         
+-        unless ($NewUser->Id) {  
+-            MailError( To => $ErrorsTo,
++        unless ( $NewUser->Id ) {
++            MailError(
++                To          => $ErrorsTo,
+                        Subject => "User could not be created",
+-                       Explanation => "User creation failed in mailgateway: $Message",
++                Explanation =>
++                    "User creation failed in mailgateway: $Message",
+                        MIMEObj => $entity,
+                        LogLevel => 'crit'
+                      );
+@@ -313,11 +322,14 @@
+     my $CurrentUser = RT::CurrentUser->new();
+     $CurrentUser->LoadByEmail($Address);
+ 
+-    unless ($CurrentUser->id) {
+-            $RT::Logger->warning("Couldn't load user '$Address'.".  "giving up");
+-                MailError( To => $ErrorsTo,
++    unless ( $CurrentUser->id ) {
++        $RT::Logger->warning(
++            "Couldn't load user '$Address'." . "giving up" );
++        MailError(
++            To          => $ErrorsTo,
+                            Subject => "User could not be loaded",
+-                           Explanation => "User  '$Address' could not be loaded in the mail gateway",
++            Explanation =>
++                "User  '$Address' could not be loaded in the mail gateway",
+                            MIMEObj => $entity,
+                            LogLevel => 'crit'
+                      );
+@@ -339,25 +352,28 @@
+ =cut
+   
+ sub ParseCcAddressesFromHead {
+-    my %args = ( Head => undef,
++    my %args = (
++        Head        => undef,
+ 		 QueueObj => undef,
+ 		 CurrentUser => undef,
+-		 @_ );
++        @_
++    );
+     
+     my (@Addresses);
+         
+-    my @ToObjs = Mail::Address->parse($args{'Head'}->get('To'));
+-    my @CcObjs = Mail::Address->parse($args{'Head'}->get('Cc'));
++    my @ToObjs = Mail::Address->parse( $args{'Head'}->get('To') );
++    my @CcObjs = Mail::Address->parse( $args{'Head'}->get('Cc') );
+     
+-    foreach my $AddrObj (@ToObjs, @CcObjs) {
++    foreach my $AddrObj ( @ToObjs, @CcObjs ) {
+ 	my $Address = $AddrObj->address;
+-	$Address = $args{'CurrentUser'}->UserObj->CanonicalizeEmailAddress($Address);
+- 	next if ($args{'CurrentUser'}->EmailAddress =~ /^\Q$Address\E$/i);
+-	next if ($args{'QueueObj'}->CorrespondAddress =~ /^\Q$Address\E$/i);
+-	next if ($args{'QueueObj'}->CommentAddress =~ /^\Q$Address\E$/i);
+-	next if (RT::EmailParser->IsRTAddress($Address));
++        $Address = $args{'CurrentUser'}
++            ->UserObj->CanonicalizeEmailAddress($Address);
++        next if ( $args{'CurrentUser'}->EmailAddress   =~ /^\Q$Address\E$/i );
++        next if ( $args{'QueueObj'}->CorrespondAddress =~ /^\Q$Address\E$/i );
++        next if ( $args{'QueueObj'}->CommentAddress    =~ /^\Q$Address\E$/i );
++        next if ( RT::EmailParser->IsRTAddress($Address) );
+ 	
+-	push (@Addresses, $Address);
++        push( @Addresses, $Address );
+     }
+     return (@Addresses);
+ }
+@@ -376,12 +391,14 @@
+ 
+ sub ParseSenderAddressFromHead {
+     my $head = shift;
++
+     #Figure out who's sending this message.
+-    my $From = $head->get('Reply-To') || 
+-      $head->get('From') || 
+-	$head->get('Sender');
+-    return (ParseAddressFromHeader($From));
++    my $From = $head->get('Reply-To')
++        || $head->get('From')
++        || $head->get('Sender');
++    return ( ParseAddressFromHeader($From) );
+ }
++
+ # }}}
+ 
+ # {{{ ParseErrorsToAdddressFromHead
+@@ -396,13 +413,18 @@
+ 
+ sub ParseErrorsToAddressFromHead {
+     my $head = shift;
++
+     #Figure out who's sending this message.
+ 
+-    foreach my $header ('Return-path', 'Errors-To' , 'Reply-To', 'From', 'Sender' ) {
++    foreach my $header ( 'Return-path', 'Errors-To', 'Reply-To', 'From',
++        'Sender' )
++    {
++
+ 	# If there's a header of that name
+ 	my $headerobj = $head->get($header);
+ 	if ($headerobj) {
+-		my ($addr, $name ) = ParseAddressFromHeader($headerobj);
++            my ( $addr, $name ) = ParseAddressFromHeader($headerobj);
++
+ 		# If it's got actual useful content...
+ 		return ($addr) if ($addr);
+ 	}
+@@ -418,27 +441,25 @@
+ 
+ =cut
+ 
+-
+-sub ParseAddressFromHeader{
++sub ParseAddressFromHeader {
+     my $Addr = shift;
+     
+-    # Perl 5.8.0 breaks when doing regex matches on utf8
+-    Encode::_utf8_off($Addr) if $] == 5.008;
+     my @Addresses = Mail::Address->parse($Addr);
+     
+     my $AddrObj = $Addresses[0];
+ 
+-    unless (ref($AddrObj)) {
+-	return(undef,undef);
++    unless ( ref($AddrObj) ) {
++        return ( undef, undef );
+     }
+  
+-    my $Name =  ($AddrObj->phrase || $AddrObj->comment || $AddrObj->address);
++    my $Name = ( $AddrObj->phrase || $AddrObj->comment || $AddrObj->address );
+     
+     #Lets take the from and load a user object.
+     my $Address = $AddrObj->address;
+ 
+-    return ($Address, $Name);
++    return ( $Address, $Name );
+ }
++
+ # }}}
+ 
+ # {{{ sub ParseTicketId 
+@@ -454,8 +474,7 @@
+         my $id = $1;
+         $RT::Logger->debug("Found a ticket ID. It's $id");
+         return ($id);
+-    }
+-    else {
++    } else {
+         return (undef);
+     }
+ }
+@@ -501,28 +519,35 @@
+ 
+ sub Gateway {
+     my $argsref = shift;
++    my %args    = (
++        action  => 'correspond',
++        queue   => '1',
++        ticket  => undef,
++        message => undef,
++        %$argsref
++    );
+ 
+-    my %args = %$argsref;
+-
+-    # Set some reasonable defaults
+-    $args{'action'} ||= 'correspond';
+-    $args{'queue'}  ||= '1';
++    my $SystemTicket;
++    my $Right;
+ 
+     # Validate the action
+-    my ($status, @actions) = IsCorrectAction( $args{'action'} );
+-    unless ( $status ) {
+-
+-        # Can't safely loc this. What object do we loc around?
+-        $RT::Logger->crit("Mail gateway called with an invalid action paramenter '".$actions[0]."' for queue '".$args{'queue'}."'");
+-
+-        return ( -75, "Invalid 'action' parameter", undef );
++    my ( $status, @actions ) = IsCorrectAction( $args{'action'} );
++    unless ($status) {
++        return (
++            -75,
++            "Invalid 'action' parameter "
++                . $actions[0]
++                . " for queue "
++                . $args{'queue'},
++            undef
++        );
+     }
+ 
+     my $parser = RT::EmailParser->new();
++    $parser->SmartParseMIMEEntityFromScalar( Message => $args{'message'} );
++    my $Message = $parser->Entity();
+ 
+-    $parser->SmartParseMIMEEntityFromScalar( Message => $args{'message'});
+-
+-    if (!$parser->Entity()) {
++    unless ($Message) {
+         MailError(
+             To          => $RT::OwnerEmail,
+             Subject     => "RT Bounce: Unparseable message",
+@@ -530,17 +555,13 @@
+             Attach     => $args{'message'}
+         );
+ 
+-        return(0,"Failed to parse this message. Something is likely badly wrong with the message");
++        return ( 0,
++            "Failed to parse this message. Something is likely badly wrong with the message"
++        );
+     }
+ 
+-    my $Message = $parser->Entity();
+     my $head    = $Message->head;
+ 
+-    my ( $CurrentUser, $AuthStat, $error );
+-
+-    # Initalize AuthStat so comparisons work correctly
+-    $AuthStat = -9999999;
+-
+     my $ErrorsTo = ParseErrorsToAddressFromHead($head);
+ 
+     my $MessageId = $head->get('Message-ID')
+@@ -552,13 +573,12 @@
+ 
+     $args{'ticket'} ||= ParseTicketId($Subject);
+ 
+-    my $SystemTicket;
+-    my $Right = 'CreateTicket';
+-    if ( $args{'ticket'} ) {
+         $SystemTicket = RT::Ticket->new($RT::SystemUser);
+-        $SystemTicket->Load( $args{'ticket'} );
+-	# if there's an existing ticket, this must be a reply
++    $SystemTicket->Load( $args{'ticket'} ) if ( $args{'ticket'} ) ;
++    if ( $SystemTicket->id ) {
+ 	$Right = 'ReplyToTicket';
++    } else {
++        $Right = 'CreateTicket';
+     }
+ 
+     #Set up a queue object
+@@ -566,42 +586,45 @@
+     $SystemQueueObj->Load( $args{'queue'} );
+ 
+     # We can safely have no queue of we have a known-good ticket
+-    unless ( $args{'ticket'} || $SystemQueueObj->id ) {
++    unless ( $SystemTicket->id || $SystemQueueObj->id ) {
+         return ( -75, "RT couldn't find the queue: " . $args{'queue'}, undef );
+     }
+ 
+-    # Authentication Level
++   # Authentication Level ($AuthStat)
+     # -1 - Get out.  this user has been explicitly declined
+     # 0 - User may not do anything (Not used at the moment)
+     # 1 - Normal user
+     # 2 - User is allowed to specify status updates etc. a la enhanced-mailgate
++    my ( $CurrentUser, $AuthStat, $error );
++
++    # Initalize AuthStat so comparisons work correctly
++    $AuthStat = -9999999;
+ 
+     push @RT::MailPlugins, "Auth::MailFrom" unless @RT::MailPlugins;
+ 
+-    # Since this needs loading, no matter what
++    # if plugin returns AuthStat -2 we skip action
++    # NOTE: this is experimental API and it would be changed
++    my %skip_action = ();
+ 
++    # Since this needs loading, no matter what
+     foreach (@RT::MailPlugins) {
+-        my $Code;
+-        my $NewAuthStat;
++        my ($Code, $Class, $NewAuthStat);
+         if ( ref($_) eq "CODE" ) {
+             $Code = $_;
+-        }
+-        else {
+-            $_ = "RT::Interface::Email::".$_ unless $_ =~ /^RT::Interface::Email::/;
+-            eval "require $_;";
+-            if ($@) {
+-                $RT::Logger->crit("Couldn't load module '$_': $@");
+-                next;
++        } else {
++            $Class = "RT::Interface::Email::" . $_
++                unless $_ =~ /^RT::Interface::Email::/;
++            $Class->require or
++                do { $RT::Logger->error("Couldn't load $Class: $@"); next };
+             }
+             no strict 'refs';
+-            if ( !defined( $Code = *{ $_ . "::GetCurrentUser" }{CODE} ) ) {
+-                $RT::Logger->crit("No GetCurrentUser code found in $_ module");
++            if ( !defined( $Code = *{ $Class . "::GetCurrentUser" }{CODE} ) ) {
++                $RT::Logger->crit( "No GetCurrentUser code found in $Class module");
+                 next;
+             }
+-        }
+ 
+-	foreach my $action ( @actions ) {
+ 
++        foreach my $action (@actions) {
+             ( $CurrentUser, $NewAuthStat ) = $Code->(
+                 Message     => $Message,
+                 RawMessageRef => \$args{'message'},
+@@ -612,14 +635,13 @@
+                 Queue       => $SystemQueueObj
+             );
+ 
+-
+-            # If a module returns a "-1" then we discard the ticket, so.
+-            $AuthStat = -1 if $NewAuthStat == -1;
+-
+-            # You get the highest level of authentication you were assigned.
+-            $AuthStat = $NewAuthStat if $NewAuthStat > $AuthStat;
++# You get the highest level of authentication you were assigned, unless you get the magic -1
++# If a module returns a "-1" then we discard the ticket, so.
++            $AuthStat = $NewAuthStat
++                if ( $NewAuthStat > $AuthStat or $NewAuthStat == -1 or $NewAuthStat == -2 );
+ 
+             last if $AuthStat == -1;
++            $skip_action{$action}++ if $AuthStat == -2;
+ 	}
+ 
+         last if $AuthStat == -1;
+@@ -624,132 +646,60 @@
+ 
+         last if $AuthStat == -1;
+     }
+-
+     # {{{ If authentication fails and no new user was created, get out.
+-    if ( !$CurrentUser or !$CurrentUser->Id or $AuthStat == -1 ) {
++    if ( !$CurrentUser || !$CurrentUser->id || $AuthStat == -1 ) {
+ 
+         # If the plugins refused to create one, they lose.
+         unless ( $AuthStat == -1 ) {
+-
+-            # Notify the RT Admin of the failure.
+-            # XXX Should this be configurable?
+-            MailError(
+-                To          => $RT::OwnerEmail,
+-                Subject     => "Could not load a valid user",
+-                Explanation => <<EOT,
+-RT could not load a valid user, and RT's configuration does not allow
+-for the creation of a new user for this email ($ErrorsTo).
+-
+-You might need to grant 'Everyone' the right '$Right' for the
+-queue @{[$args{'queue'}]}.
+-
+-EOT
+-                MIMEObj  => $Message,
+-                LogLevel => 'error'
++            _NoAuthorizedUserFound(
++                Right     => $Right,
++                Message   => $Message,
++                Requestor => $ErrorsTo,
++                Queue     => $args{'queue'}
+             );
+ 
+-            # Also notify the requestor that his request has been dropped.
+-            MailError(
+-                To          => $ErrorsTo,
+-                Subject     => "Could not load a valid user",
+-                Explanation => <<EOT,
+-RT could not load a valid user, and RT's configuration does not allow
+-for the creation of a new user for your email.
+-
+-EOT
+-                MIMEObj  => $Message,
+-                LogLevel => 'error'
+-            );
+         }
+         return ( 0, "Could not load a valid user", undef );
+     }
+ 
+-    # }}}
+-
+-    # {{{ Lets check for mail loops of various sorts.
+-    my $IsBounce = CheckForBounce($head);
+-
+-    my $IsAutoGenerated = CheckForAutoGenerated($head);
+-
+-    my $IsSuspiciousSender = CheckForSuspiciousSender($head);
+-
+-    my $IsALoop = CheckForLoops($head);
+-
+-    my $SquelchReplies = 0;
+-
+-    #If the message is autogenerated, we need to know, so we can not
+-    # send mail to the sender
+-    if ( $IsBounce || $IsSuspiciousSender || $IsAutoGenerated || $IsALoop ) {
+-        $SquelchReplies = 1;
+-        $ErrorsTo       = $RT::OwnerEmail;
+-    }
+-
+-    # }}}
+-
+-    # {{{ Drop it if it's disallowed
++    # If we got a user, but they don't have the right to say things
+     if ( $AuthStat == 0 ) {
+         MailError(
+             To          => $ErrorsTo,
+             Subject     => "Permission Denied",
+-            Explanation => "You do not have permission to communicate with RT",
++            Explanation =>
++                "You do not have permission to communicate with RT",
+             MIMEObj     => $Message
+         );
+-    }
+-
+-    # }}}
+-    # {{{ Warn someone  if it's a loop
+-
+-    # Warn someone if it's a loop, before we drop it on the ground
+-    if ($IsALoop) {
+-        $RT::Logger->crit("RT Recieved mail ($MessageId) from itself.");
+-
+-        #Should we mail it to RTOwner?
+-        if ($RT::LoopsToRTOwner) {
+-            MailError(
+-                To          => $RT::OwnerEmail,
+-                Subject     => "RT Bounce: $Subject",
+-                Explanation => "RT thinks this message may be a bounce",
+-                MIMEObj     => $Message
++        return (
++            0,
++            "$ErrorsTo tried to submit a message to "
++                . $args{'Queue'}
++                . " without permission.",
++            undef
+             );
+         }
+ 
+-        #Do we actually want to store it?
+-        return ( 0, "Message Bounced", undef ) unless ($RT::StoreLoops);
+-    }
+-
+-    # }}}
+-
+-    # {{{ Squelch replies if necessary
+-    # Don't let the user stuff the RT-Squelch-Replies-To header.
+-    if ( $head->get('RT-Squelch-Replies-To') ) {
+-        $head->add(
+-            'RT-Relocated-Squelch-Replies-To',
+-            $head->get('RT-Squelch-Replies-To')
++    # {{{ Lets check for mail loops of various sorts.
++    my ($continue, $result);
++     ( $continue, $ErrorsTo, $result ) = _HandleMachineGeneratedMail(
++        Message  => $Message,
++        ErrorsTo => $ErrorsTo,
++        Subject  => $Subject,
++        MessageId => $MessageId
+         );
+-        $head->delete('RT-Squelch-Replies-To');
+-    }
+ 
+-    if ($SquelchReplies) {
+-
+-        # Squelch replies to the sender, and also leave a clue to
+-        # allow us to squelch ALL outbound messages. This way we
+-        # can punt the logic of "what to do when we get a bounce"
+-        # to the scrip. We might want to notify nobody. Or just
+-        # the RT Owner. Or maybe all Privileged watchers.
+-        my ( $Sender, $junk ) = ParseSenderAddressFromHead($head);
+-        $head->add( 'RT-Squelch-Replies-To', $Sender );
+-        $head->add( 'RT-DetectedAutoGenerated', 'true' );
++    unless ($continue) {
++        return ( 0, $result, undef );
+     }
+ 
+-    # }}}
+-
+     my $Ticket = RT::Ticket->new($CurrentUser);
+ 
+-    # {{{ If we don't have a ticket Id, we're creating a new ticket
+-    if ( (!$SystemTicket || !$SystemTicket->Id) && 
+-           grep /^(comment|correspond)$/, @actions ) {
+-
+-        # {{{ Create a new ticket
++    if (( !$SystemTicket || !$SystemTicket->Id )
++        && grep /^(comment|correspond)$/ && !$skip_action{$_},
++        @actions
++        )
++    {
+ 
+         my @Cc;
+         my @Requestors = ( $CurrentUser->id );
+@@ -776,38 +726,40 @@
+                 Explanation => $ErrStr,
+                 MIMEObj     => $Message
+             );
+-            $RT::Logger->error("Create failed: $id / $Transaction / $ErrStr ");
+-            return ( 0, "Ticket creation failed", $Ticket );
++            return ( 0, "Ticket creation failed: $ErrStr", $Ticket );
+         }
+-	# strip comments&corresponds from the actions we don't need record twice
++
++# strip comments&corresponds from the actions we don't need to record them if we've created the ticket just now
+ 	@actions = grep !/^(comment|correspond)$/, @actions;
+ 	$args{'ticket'} = $id;
+ 
+-        # }}}
+-    }
++    } else {
+ 
+-    $Ticket->Load( $args{'ticket'} );
++        $Ticket->Load( $SystemTicket->id );
+     unless ( $Ticket->Id ) {
+-        my $message = "Could not find a ticket with id " . $args{'ticket'};
++            my $error = "Could not find a ticket with id " . $SystemTicket->id || $args{'ticket'};
+         MailError(
+             To          => $ErrorsTo,
+             Subject     => "Message not recorded",
+-            Explanation => $message,
++                Explanation => $error,
+             MIMEObj     => $Message
+         );
+     
+-        return ( 0, $message );
++            return ( 0, $error );
++        }
+     }
+ 
+     # }}}
+-    foreach my $action( @actions ) {
++    foreach my $action (@actions) {
++        next if $skip_action{ $action };
++
+         #   If the action is comment, add a comment.
+-        if ( $action =~ /^(comment|correspond)$/i ) {
++        if ( $action =~ /^(?:comment|correspond)$/i ) {
+             my ( $status, $msg );
+             if ( $action =~ /^correspond$/i ) {
+-                ( $status, $msg ) = $Ticket->Correspond( MIMEObj => $Message );
+-            }
+-            else {
++                ( $status, $msg )
++                    = $Ticket->Correspond( MIMEObj => $Message );
++            } else {
+                 ( $status, $msg ) = $Ticket->Comment( MIMEObj => $Message );
+             }
+             unless ($status) {
+@@ -821,77 +773,196 @@
+                 );
+                 return ( 0, "Message not recorded", $Ticket );
+             }
++        } elsif ($RT::UnsafeEmailCommands) {
++            return _RunUnsafeAction(
++                Action      => $action,
++                ErrorsTo    => $ErrorsTo,
++                Message     => $Message,
++                Ticket      => $Ticket,
++                CurrentUser => $CurrentUser
++            );
++        }
+         }
+-        elsif ($RT::UnsafeEmailCommands && $action =~ /^take$/i ) {
+-            my ( $status, $msg ) = $Ticket->SetOwner( $CurrentUser->id );
+-            unless ($status) {
++    return ( 1, "Success", $Ticket );
++}
+     
+-                #Warn the sender that we couldn't actually submit the comment.
++sub _RunUnsafeAction {
++    my %args = (
++        Action      => undef,
++        ErrorsTo    => undef,
++        Message     => undef,
++        Ticket      => undef,
++        CurrentUser => undef,
++        @_
++    );
++
++    if ( $args{'Action'} =~ /^take$/i ) {
++        my ( $status, $msg ) = $args{'Ticket'}->SetOwner( $args{'CurrentUser'}->id );
++        unless ($status) {
+                 MailError(
+-                    To          => $ErrorsTo,
++                To          => $args{'ErrorsTo'},
+                     Subject     => "Ticket not taken",
+                     Explanation => $msg,
+-                    MIMEObj     => $Message
++                MIMEObj     => $args{'Message'}
+                 );
+-                return ( 0, "Ticket not taken", $Ticket );
+-            }
++            return ( 0, "Ticket not taken", $args{'Ticket'} );
+         }
+-        elsif ( $RT::UnsafeEmailCommands && $action =~ /^resolve$/i ) {
+-            my ( $status, $msg ) = $Ticket->SetStatus( 'resolved' );
++    } elsif ( $args{'Action'} =~ /^resolve$/i ) {
++        my ( $status, $msg ) = $args{'Ticket'}->SetStatus('resolved');
+             unless ($status) {
++
+                 #Warn the sender that we couldn't actually submit the comment.
+                 MailError(
+-                    To          => $ErrorsTo,
++                To          => $args{'ErrorsTo'},
+                     Subject     => "Ticket not resolved",
+                     Explanation => $msg,
+-                    MIMEObj     => $Message
++                MIMEObj     => $args{'Message'}
+                 );
+-                return ( 0, "Ticket not resolved", $Ticket );
++            return ( 0, "Ticket not resolved", $args{'Ticket'} );
+             }
+         }
++    return ( 0, 'Unknown action' );
++}
+     
+-        else {
++=head2 _NoAuthorizedUserFound
+     
+-            #Return mail to the sender with an error
++Emails the RT Owner and the requestor when the auth plugins return "No auth user found"
++
++=cut
++
++sub _NoAuthorizedUserFound {
++    my %args = (
++        Right     => undef,
++        Message   => undef,
++        Requestor => undef,
++        Queue     => undef,
++        @_
++    );
++
++    # Notify the RT Admin of the failure.
+             MailError(
+-                To          => $ErrorsTo,
+-                Subject     => "RT Configuration error",
+-                Explanation => "'"
+-                  . $args{'action'}
+-                  . "' not a recognized action."
+-                  . " Your RT administrator has misconfigured "
+-                  . "the mail aliases which invoke RT",
+-                MIMEObj => $Message
++        To          => $RT::OwnerEmail,
++        Subject     => "Could not load a valid user",
++        Explanation => <<EOT,
++RT could not load a valid user, and RT's configuration does not allow
++for the creation of a new user for this email (@{[$args{Requestor}]}).
++
++You might need to grant 'Everyone' the right '@{[$args{Right}]}' for the
++queue @{[$args{'Queue'}]}.
++
++EOT
++        MIMEObj  => $args{'Message'},
++        LogLevel => 'error'
+             );
+-            $RT::Logger->crit( $args{'action'} . " type unknown for $MessageId" );
+-            return (
+-                -75,
+-                "Configuration error: "
+-                  . $args{'action'}
+-                  . " not a recognized action",
+-                $Ticket
++
++    # Also notify the requestor that his request has been dropped.
++    MailError(
++        To          => $args{'Requestor'},
++        Subject     => "Could not load a valid user",
++        Explanation => <<EOT,
++RT could not load a valid user, and RT's configuration does not allow
++for the creation of a new user for your email.
++
++EOT
++        MIMEObj  => $args{'Message'},
++        LogLevel => 'error'
+             );
++}
++
++=head2 _HandleMachineGeneratedMail
++
++Takes named params:
++    Message
++    ErrorsTo
++    Subject
++
++Checks the message to see if it's a bounce, if it looks like a loop, if it's autogenerated, etc.
++Returns a triple of ("Should we continue (boolean)", "New value for $ErrorsTo", "Status message");
++
++=cut
++
++sub _HandleMachineGeneratedMail {
++    my %args = ( Message => undef, ErrorsTo => undef, Subject => undef, MessageId => undef, @_ );
++    my $head = $args{'Message'}->head;
++    my $ErrorsTo = $args{'ErrorsTo'};
++
++    my $IsBounce = CheckForBounce($head);
++
++    my $IsAutoGenerated = CheckForAutoGenerated($head);
++
++    my $IsSuspiciousSender = CheckForSuspiciousSender($head);
+     
++    my $IsALoop = CheckForLoops($head);
++
++    my $SquelchReplies = 0;
++
++    #If the message is autogenerated, we need to know, so we can not
++    # send mail to the sender
++    if ( $IsBounce || $IsSuspiciousSender || $IsAutoGenerated || $IsALoop ) {
++        $SquelchReplies = 1;
++        $ErrorsTo       = $RT::OwnerEmail;
+         }
++
++    # Warn someone if it's a loop, before we drop it on the ground
++    if ($IsALoop) {
++        $RT::Logger->crit("RT Recieved mail (".$args{MessageId}.") from itself.");
++
++        #Should we mail it to RTOwner?
++        if ($RT::LoopsToRTOwner) {
++            MailError(
++                To          => $RT::OwnerEmail,
++                Subject     => "RT Bounce: ".$args{'Subject'},
++                Explanation => "RT thinks this message may be a bounce",
++                MIMEObj     => $args{Message}
++            );
+     }
+ 
+-    return ( 1, "Success", $Ticket );
++        #Do we actually want to store it?
++        return ( 0, $ErrorsTo, "Message Bounced" ) unless ($RT::StoreLoops);
++    }
++
++    # Squelch replies if necessary
++    # Don't let the user stuff the RT-Squelch-Replies-To header.
++    if ( $head->get('RT-Squelch-Replies-To') ) {
++        $head->add(
++            'RT-Relocated-Squelch-Replies-To',
++            $head->get('RT-Squelch-Replies-To')
++        );
++        $head->delete('RT-Squelch-Replies-To');
++    }
++
++    if ($SquelchReplies) {
++
++        # Squelch replies to the sender, and also leave a clue to
++        # allow us to squelch ALL outbound messages. This way we
++        # can punt the logic of "what to do when we get a bounce"
++        # to the scrip. We might want to notify nobody. Or just
++        # the RT Owner. Or maybe all Privileged watchers.
++        my ( $Sender, $junk ) = ParseSenderAddressFromHead($head);
++        $head->add( 'RT-Squelch-Replies-To',    $Sender );
++        $head->add( 'RT-DetectedAutoGenerated', 'true' );
++    }
++    return ( 1, $ErrorsTo, "Handled machine detection" );
+ }
+ 
+-sub IsCorrectAction
+-{
++=head2 IsCorrectAction
++
++Returns a list of valid actions we've found for this message
++
++=cut
++
++sub IsCorrectAction {
+ 	my $action = shift;
+ 	my @actions = split /-/, $action;
+-	foreach ( @actions ) {
+-		return (0, $_) unless /^(?:comment|correspond|take|resolve)$/;
++    foreach (@actions) {
++        return ( 0, $_ ) unless /^(?:comment|correspond|take|resolve)$/;
+ 	}
+-	return (1, @actions);
++    return ( 1, @actions );
+ }
+ 
+-
+ eval "require RT::Interface::Email_Vendor";
+-die $@ if ($@ && $@ !~ qr{^Can't locate RT/Interface/Email_Vendor.pm});
++die $@ if ( $@ && $@ !~ qr{^Can't locate RT/Interface/Email_Vendor.pm} );
+ eval "require RT::Interface::Email_Local";
+-die $@ if ($@ && $@ !~ qr{^Can't locate RT/Interface/Email_Local.pm});
++die $@ if ( $@ && $@ !~ qr{^Can't locate RT/Interface/Email_Local.pm} );
+ 
+ 1;


More information about the Rt-commit mailing list