The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.
%# BEGIN BPS TAGGED BLOCK {{{
%#
%# COPYRIGHT:
%#
%# This software is Copyright (c) 1996-2014 Best Practical Solutions, LLC
%#                                          <sales@bestpractical.com>
%#
%# (Except where explicitly superseded by other copyright notices)
%#
%#
%# LICENSE:
%#
%# This work is made available to you under the terms of Version 2 of
%# the GNU General Public License. A copy of that license should have
%# been provided with this software, but in any event can be snarfed
%# from www.gnu.org.
%#
%# This work is distributed in the hope that it will be useful, but
%# WITHOUT ANY WARRANTY; without even the implied warranty of
%# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
%# General Public License for more details.
%#
%# You should have received a copy of the GNU General Public License
%# along with this program; if not, write to the Free Software
%# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
%# 02110-1301 or visit their web page on the internet at
%# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html.
%#
%#
%# CONTRIBUTION SUBMISSION POLICY:
%#
%# (The following paragraph is not intended to limit the rights granted
%# to you to modify and distribute this software under the terms of
%# the GNU General Public License and is only of importance to you if
%# you choose to contribute your changes and enhancements to the
%# community by submitting them to Best Practical Solutions, LLC.)
%#
%# By intentionally submitting any modifications, corrections or
%# derivatives to this work, or any other work intended for use with
%# Request Tracker, to Best Practical Solutions, LLC, you confirm that
%# you are the copyright holder for those contributions and you grant
%# Best Practical Solutions,  LLC a nonexclusive, worldwide, irrevocable,
%# royalty-free, perpetual, license to use, copy, create derivative
%# works based on those contributions, and sublicense and distribute
%# those contributions and any derivatives thereof.
%#
%# END BPS TAGGED BLOCK }}}
<& /Elements/Header, 
    Title => $title &>
<& /Elements/Tabs &>

<& /Elements/ListActions, actions => \@Actions &>

<& /Dist/Elements/ShowBugtracker, Queue => $TicketObj->QueueObj &>
<& /Dist/Elements/ShowNotes, Queue => $TicketObj->QueueObj &>

<&| /Widgets/TitleBox, title => loc("Report information") &>
<& /Public/Bug/Elements/ShowSummary, Ticket => $TicketObj, Attachments => $attachments &>
</&>

<br />

% $m->callback(%ARGS, CallbackName => 'BeforeShowHistory', Ticket => $TicketObj);

<& /Ticket/Elements/ShowHistory , 
      Ticket => $TicketObj, 
      Tickets => $Tickets, 
      Collapsed => $ARGS{'Collapsed'}, 
      ShowHeaders => $ARGS{'ShowHeaders'},
      Attachments => $attachments,
      AttachmentContent => $attachment_content,
      URIFile     => RT->Config->Get('WebPath') . '/Public/Bug/Display.html',
      DisplayPath => RT->Config->Get('WebPath') . '/Public/Bug/Display.html?id='. $TicketObj->id,
      UpdatePath  => RT->Config->Get('WebPath') . '/Public/Bug/Update.html',
&> 

<%ARGS>
$id => undef
$Create => undef
$ShowHeaders => 0
$Collapsed => undef
$TicketObj => undef
</%ARGS>

<%INIT>
$m->callback(CallbackName => 'Initial', TicketObj => $TicketObj, ARGSRef => \%ARGS);

my (@Actions, $Tickets);

unless ($id || $TicketObj) {
    Abort('No ticket specified');
}

if ($ARGS{'id'} eq 'new') {
    # {{{ Create a new ticket
    
    my $Queue = new RT::Queue($session{'CurrentUser'});	
    unless ($Queue->Load($ARGS{'Queue'})) {
	Abort('Queue not found');
    }
    
    unless ($Queue->CurrentUserHasRight('CreateTicket')) {
	Abort('You have no permission to create tickets in that queue.');
    }
    ($TicketObj, @Actions) =
	CreateTicket(Attachments => $session{'Attachments'}, %ARGS);
    delete $session{'Attachments'};
    unless ($TicketObj->CurrentUserHasRight('ShowTicket')) {
	Abort("No permission to view newly created ticket #".$TicketObj->id.".");
	}
    # }}}
} else { 
    if (!$TicketObj) {

	$TicketObj = RT::Ticket->new($session{'CurrentUser'});

	$TicketObj = LoadTicket($ARGS{'id'});
	unless ($TicketObj->CurrentUserHasRight('ShowTicket')) {
	    Abort("No permission to view ticket");
	}
    }

    if (defined $ARGS{'Action'}) {
	if ($ARGS{'Action'} =~ /^(Steal|Kill|Take|SetTold)$/) {
	    my $action = $1;
	    my ($res, $msg)=$TicketObj->$action();
	    push(@Actions, $msg);
	}
    }

    $ARGS{'UpdateContent'} =~ s/\r\n/\n/g if defined $ARGS{'UpdateContent'};
    if ( $ARGS{'UpdateTimeWorked'} ||
	 $session{'Attachments'} || 
	 (   defined $ARGS{'UpdateContent'}
             && $ARGS{'UpdateContent'} ne ''
	     && $ARGS{'UpdateContent'} ne "-- \n"
	     . $session{'CurrentUser'}->UserObj->Signature )) {
	$ARGS{UpdateAttachments} = $session{'Attachments'};
	_UpdateMessage( ARGSRef   => \%ARGS,
			      Actions   => \@Actions,
			      TicketObj => $TicketObj );
	delete $session{'Attachments'};
    }
    #Process status updates
    my @BasicActions = ProcessTicketBasics(ARGSRef => \%ARGS, TicketObj=>$TicketObj);
    my @results = ProcessTicketLinks( TicketObj => $TicketObj, ARGSRef => \%ARGS);

    push (@Actions, @BasicActions, @results);
}

# This code does automatic redirection if any updates happen. 
# It doesn't work for the client.



if (@Actions) {
    # We've done something, so we need to clear the decks to avoid 
    # resubmission on refresh.
    # But we need to store Actions somewhere too, so we don't lose them.
    $session{"Actions"} = \@Actions;
    $m->redirect( $RT::WebPath ."/Ticket/Display.html?id=".$TicketObj->id);
    $m->abort();
    $RT::Logger->error("Aborted. Should never be called");
}

$m->callback(CallbackName => 'BeforeDisplay',
	 TicketObj => \$TicketObj, Tickets => \$Tickets, ARGSRef => \%ARGS);


my $attachments = $m->comp('/Ticket/Elements/FindAttachments', Ticket => $TicketObj, Tickets => $Tickets);
my $attachment_content = $m->comp('/Ticket/Elements/LoadTextAttachments', Ticket => $TicketObj);

my $title = loc(
    "Bug #[_1] for [_2]: [_3]",
    $TicketObj->Id, $TicketObj->QueueObj->Name, $TicketObj->Subject
);

sub _UpdateMessage {
    # Modified version of RT::Interface::Web::ProcessUpdateMessage()
    #TODO document what else this takes.
    my %args = (
        ARGSRef   => undef,
        Actions   => undef,
        TicketObj => undef,
        @_
    );

    #Make the update content have no 'weird' newlines in it
    if (   $args{ARGSRef}->{'UpdateContent'}
        || $args{ARGSRef}->{'UpdateAttachments'} )
    {

        if (
            $args{ARGSRef}->{'UpdateSubject'} eq $args{'TicketObj'}->Subject() )
        {
            $args{ARGSRef}->{'UpdateSubject'} = undef;
        }

        my %mime = (
            Subject => $args{ARGSRef}->{'UpdateSubject'},
            Body    => $args{ARGSRef}->{'UpdateContent'},
        );

        $mime{'From'} = $args{ARGSRef}->{'UpdateSender'}
            if defined $args{ARGSRef}->{'UpdateSender'};

        my $Message = MakeMIMEEntity(%mime);

        $Message->head->add( 'Message-ID' => 
              "<rt-"
              . $RT::VERSION . "-"
              . $$ . "-"
              . CORE::time() . "-"
              . int(rand(2000)) . "."
              . $args{'TicketObj'}->id . "-"
              . "0" . "-"  # Scrip
              . "0" . "@"  # Email sent
              . $RT::Organization
              . ">" );
        my $old_txn = RT::Transaction->new( $session{'CurrentUser'} );
        if ( $args{ARGSRef}->{'QuoteTransaction'} ) {
            $old_txn->Load( $args{ARGSRef}->{'QuoteTransaction'} );
        }
        else {
            $old_txn = $args{TicketObj}->Transactions->First();
        }

        if ( $old_txn->Message && $old_txn->Message->First ) {
            my @in_reply_to = split(/\s+/m, $old_txn->Message->First->GetHeader('In-Reply-To') || '');  
            my @references = split(/\s+/m, $old_txn->Message->First->GetHeader('References') || '' );  
            my @msgid = split(/\s+/m,$old_txn->Message->First->GetHeader('Message-ID') || ''); 
            my @rtmsgid = split(/\s+/m,$old_txn->Message->First->GetHeader('RT-Message-ID') || ''); 

            $Message->head->replace( 'In-Reply-To', join (' ', @rtmsgid ? @rtmsgid : @msgid));
            $Message->head->replace( 'References', join(' ', @references, @msgid, @rtmsgid));
        }

    if ( $args{ARGSRef}->{'UpdateAttachments'} ) {
        $Message->make_multipart;
        $Message->add_part($_)
          foreach values %{ $args{ARGSRef}->{'UpdateAttachments'} };
    }

    if ( $args{ARGSRef}->{'UpdateType'} eq 'response' ) {
        my ( $Transaction, $Description, $Object ) =
          $args{TicketObj}->Correspond(
            CcMessageTo  => $args{ARGSRef}->{'UpdateCc'},
            BccMessageTo => $args{ARGSRef}->{'UpdateBcc'},
            MIMEObj      => $Message,
          );
        push( @{ $args{Actions} }, $Description );
        $Object->UpdateCustomFields( ARGSRef => $args{ARGSRef} ) if $Object;
    }
    else {
        push(
            @{ $args{'Actions'} },
            loc("Update type was neither correspondence nor comment.") . " "
              . loc("Update not recorded.")
        );
    }
    }
}
</%INIT>