+ my %args = (
+ Content => undef,
+ Queue => 0,
+ Description => '[no description]',
+ Type => 'Perl',
+ Name => undef,
+ @_
+ );
+
+ if ( $args{Type} eq 'Perl' && !$self->CurrentUser->HasRight(Right => 'ExecuteCode', Object => $RT::System) ) {
+ return ( undef, $self->loc('Permission Denied') );
+ }
+
+ unless ( $args{'Queue'} ) {
+ unless ( $self->CurrentUser->HasRight(Right =>'ModifyTemplate', Object => $RT::System) ) {
+ return ( undef, $self->loc('Permission Denied') );
+ }
+ $args{'Queue'} = 0;
+ }
+ else {
+ my $QueueObj = RT::Queue->new( $self->CurrentUser );
+ $QueueObj->Load( $args{'Queue'} ) || return ( undef, $self->loc('Invalid queue') );
+
+ unless ( $QueueObj->CurrentUserHasRight('ModifyTemplate') ) {
+ return ( undef, $self->loc('Permission Denied') );
+ }
+ $args{'Queue'} = $QueueObj->Id;
+ }
+
+ my $result = $self->SUPER::Create(
+ Content => $args{'Content'},
+ Queue => $args{'Queue'},
+ Description => $args{'Description'},
+ Name => $args{'Name'},
+ Type => $args{'Type'},
+ );
+
+ return ($result);
+
+}
+
+=head2 Delete
+
+Delete this template.
+
+=cut
+
+sub Delete {
+ my $self = shift;
+
+ unless ( $self->CurrentUserHasQueueRight('ModifyTemplate') ) {
+ return ( 0, $self->loc('Permission Denied') );
+ }
+
+ return ( $self->SUPER::Delete(@_) );
+}
+
+=head2 IsEmpty
+
+Returns true value if content of the template is empty, otherwise
+returns false.
+
+=cut
+
+sub IsEmpty {
+ my $self = shift;
+ my $content = $self->Content;
+ return 0 if defined $content && length $content;
+ return 1;
+}
+
+=head2 MIMEObj
+
+Returns L<MIME::Entity> object parsed using L</Parse> method. Returns
+undef if last call to L</Parse> failed or never be called.
+
+Note that content of the template is UTF-8, but L<MIME::Parser> is not
+good at handling it and all data of the entity should be treated as
+octets and converted to perl strings using Encode::decode_utf8 or
+something else.
+
+=cut
+
+sub MIMEObj {
+ my $self = shift;
+ return ( $self->{'MIMEObj'} );
+}
+
+=head2 Parse
+
+This routine performs L<Text::Template> parsing on the template and then
+imports the results into a L<MIME::Entity> so we can really use it. Use
+L</MIMEObj> method to get the L<MIME::Entity> object.
+
+Takes a hash containing Argument, TicketObj, and TransactionObj and other
+arguments that will be available in the template's code. TicketObj and
+TransactionObj are not mandatory, but highly recommended.
+
+It returns a tuple of (val, message). If val is false, the message contains
+an error message.
+
+=cut
+
+sub Parse {
+ my $self = shift;
+ my ($rv, $msg);
+
+
+ if ($self->Content =~ m{^Content-Type:\s+text/html\b}im) {
+ local $RT::Transaction::PreferredContentType = 'text/html';
+ ($rv, $msg) = $self->_Parse(@_);
+ }
+ else {
+ ($rv, $msg) = $self->_Parse(@_);
+ }
+
+ return ($rv, $msg) unless $rv;
+
+ my $mime_type = $self->MIMEObj->mime_type;
+ if (defined $mime_type and $mime_type eq 'text/html') {
+ $self->_DowngradeFromHTML(@_);
+ }
+
+ return ($rv, $msg);
+}
+
+sub _Parse {
+ my $self = shift;
+
+ # clear prev MIME object
+ $self->{'MIMEObj'} = undef;
+
+ #We're passing in whatever we were passed. it's destined for _ParseContent
+ my ($content, $msg) = $self->_ParseContent(@_);
+ return ( 0, $msg ) unless defined $content && length $content;
+
+ if ( $content =~ /^\S/s && $content !~ /^\S+:/ ) {
+ $RT::Logger->error(
+ "Template #". $self->id ." has leading line that doesn't"
+ ." look like header field, if you don't want to override"
+ ." any headers and don't want to see this error message"
+ ." then leave first line of the template empty"
+ );
+ $content = "\n".$content;
+ }
+
+ my $parser = MIME::Parser->new();
+ $parser->output_to_core(1);
+ $parser->tmp_to_core(1);
+ $parser->use_inner_files(1);
+
+ ### Should we forgive normally-fatal errors?
+ $parser->ignore_errors(1);
+ # MIME::Parser doesn't play well with perl strings
+ utf8::encode($content);
+ $self->{'MIMEObj'} = eval { $parser->parse_data( \$content ) };
+ if ( my $error = $@ || $parser->last_error ) {
+ $RT::Logger->error( "$error" );
+ return ( 0, $error );
+ }
+
+ # Unfold all headers
+ $self->{'MIMEObj'}->head->unfold;
+
+ return ( 1, $self->loc("Template parsed") );
+
+}
+
+# Perform Template substitutions on the template
+
+sub _ParseContent {
+ my $self = shift;
+ my %args = (
+ Argument => undef,
+ TicketObj => undef,
+ TransactionObj => undef,
+ @_
+ );
+
+ unless ( $self->CurrentUserCanRead() ) {
+ return (undef, $self->loc("Permission Denied"));
+ }
+
+ if ( $self->IsEmpty ) {
+ return ( undef, $self->loc("Template is empty") );
+ }
+
+ my $content = $self->SUPER::_Value('Content');
+ # We need to untaint the content of the template, since we'll be working
+ # with it
+ $content =~ s/^(.*)$/$1/;
+
+ $args{'Ticket'} = delete $args{'TicketObj'} if $args{'TicketObj'};
+ $args{'Transaction'} = delete $args{'TransactionObj'} if $args{'TransactionObj'};
+ $args{'Requestor'} = eval { $args{'Ticket'}->Requestors->UserMembersObj->First->Name }
+ if $args{'Ticket'};
+ $args{'rtname'} = RT->Config->Get('rtname');
+ if ( $args{'Ticket'} ) {
+ my $t = $args{'Ticket'}; # avoid memory leak
+ $args{'loc'} = sub { $t->loc(@_) };
+ } else {
+ $args{'loc'} = sub { $self->loc(@_) };
+ }
+
+ if ($self->Type eq 'Perl') {
+ return $self->_ParseContentPerl(
+ Content => $content,
+ TemplateArgs => \%args,
+ );
+ }
+ else {
+ return $self->_ParseContentSimple(
+ Content => $content,
+ TemplateArgs => \%args,
+ );
+ }
+}
+
+# uses Text::Template for Perl templates
+sub _ParseContentPerl {
+ my $self = shift;
+ my %args = (
+ Content => undef,
+ TemplateArgs => {},
+ @_,
+ );
+
+ foreach my $key ( keys %{ $args{TemplateArgs} } ) {
+ my $val = $args{TemplateArgs}{ $key };
+ next unless ref $val;
+ next if ref $val =~ /^(ARRAY|HASH|SCALAR|CODE)$/;
+ $args{TemplateArgs}{ $key } = \$val;
+ }
+
+ my $template = Text::Template->new(
+ TYPE => 'STRING',
+ SOURCE => $args{Content},
+ );
+ my $is_broken = 0;
+ my $retval = $template->fill_in(
+ HASH => $args{TemplateArgs},
+ BROKEN => sub {
+ my (%args) = @_;
+ $RT::Logger->error("Template parsing error: $args{error}")
+ unless $args{error} =~ /^Died at /; # ignore intentional die()
+ $is_broken++;
+ return undef;
+ },
+ );
+ return ( undef, $self->loc('Template parsing error') ) if $is_broken;
+
+ return ($retval);
+}
+
+sub _ParseContentSimple {
+ my $self = shift;
+ my %args = (
+ Content => undef,
+ TemplateArgs => {},
+ @_,
+ );
+
+ $self->_MassageSimpleTemplateArgs(%args);
+
+ my $template = Text::Template->new(
+ TYPE => 'STRING',
+ SOURCE => $args{Content},
+ );
+ my ($ok) = $template->compile;
+ return ( undef, $self->loc('Template parsing error: [_1]', $Text::Template::ERROR) ) if !$ok;
+
+ # copied from Text::Template::fill_in and refactored to be simple variable
+ # interpolation
+ my $fi_r = '';
+ foreach my $fi_item (@{$template->{SOURCE}}) {
+ my ($fi_type, $fi_text, $fi_lineno) = @$fi_item;
+ if ($fi_type eq 'TEXT') {
+ $fi_r .= $fi_text;
+ } elsif ($fi_type eq 'PROG') {
+ my $fi_res;
+ my $original_fi_text = $fi_text;
+
+ # strip surrounding whitespace for simpler regexes
+ $fi_text =~ s/^\s+//;
+ $fi_text =~ s/\s+$//;
+
+ # if the codeblock is a simple $Variable lookup, use the value from
+ # the TemplateArgs hash...
+ if (my ($var) = $fi_text =~ /^\$(\w+)$/) {
+ if (exists $args{TemplateArgs}{$var}) {
+ $fi_res = $args{TemplateArgs}{$var};
+ }
+ }
+
+ # if there was no substitution then just reinsert the codeblock
+ if (!defined $fi_res) {
+ $fi_res = "{$original_fi_text}";
+ }
+
+ # If the value of the filled-in text really was undef,
+ # change it to an explicit empty string to avoid undefined
+ # value warnings later.
+ $fi_res = '' unless defined $fi_res;
+
+ $fi_r .= $fi_res;
+ }
+ }
+
+ return $fi_r;
+}
+
+sub _MassageSimpleTemplateArgs {
+ my $self = shift;
+ my %args = (
+ TemplateArgs => {},
+ @_,
+ );
+
+ my $template_args = $args{TemplateArgs};
+
+ if (my $ticket = $template_args->{Ticket}) {
+ for my $column (qw/Id Subject Type InitialPriority FinalPriority Priority TimeEstimated TimeWorked Status TimeLeft Told Starts Started Due Resolved RequestorAddresses AdminCcAddresses CcAddresses/) {
+ $template_args->{"Ticket".$column} = $ticket->$column;
+ }
+
+ $template_args->{"TicketQueueId"} = $ticket->Queue;
+ $template_args->{"TicketQueueName"} = $ticket->QueueObj->Name;
+
+ $template_args->{"TicketOwnerId"} = $ticket->Owner;
+ $template_args->{"TicketOwnerName"} = $ticket->OwnerObj->Name;
+ $template_args->{"TicketOwnerEmailAddress"} = $ticket->OwnerObj->EmailAddress;
+
+ my $cfs = $ticket->CustomFields;
+ while (my $cf = $cfs->Next) {
+ $template_args->{"TicketCF" . $cf->Name} = $ticket->CustomFieldValuesAsString($cf->Name);
+ }
+ }
+
+ if (my $txn = $template_args->{Transaction}) {
+ for my $column (qw/Id TimeTaken Type Field OldValue NewValue Data Content Subject Description BriefDescription/) {
+ $template_args->{"Transaction".$column} = $txn->$column;
+ }
+
+ my $cfs = $txn->CustomFields;
+ while (my $cf = $cfs->Next) {
+ $template_args->{"TransactionCF" . $cf->Name} = $txn->CustomFieldValuesAsString($cf->Name);
+ }
+ }
+}
+
+sub _DowngradeFromHTML {
+ my $self = shift;
+ my $orig_entity = $self->MIMEObj;
+
+ my $new_entity = $orig_entity->dup; # this will fail badly if we go away from InCore parsing
+ $new_entity->head->mime_attr( "Content-Type" => 'text/plain' );
+ $new_entity->head->mime_attr( "Content-Type.charset" => 'utf-8' );
+
+ $orig_entity->head->mime_attr( "Content-Type" => 'text/html' );
+ $orig_entity->head->mime_attr( "Content-Type.charset" => 'utf-8' );
+ $orig_entity->make_multipart('alternative', Force => 1);
+
+ require HTML::FormatText;
+ require HTML::TreeBuilder;
+ require Encode;
+ # need to decode_utf8, see the doc of MIMEObj method
+ my $tree = HTML::TreeBuilder->new_from_content(
+ Encode::decode_utf8($new_entity->bodyhandle->as_string)
+ );
+ $new_entity->bodyhandle(MIME::Body::InCore->new(
+ \(scalar HTML::FormatText->new(
+ leftmargin => 0,
+ rightmargin => 78,
+ )->format( $tree ))
+ ));
+ $tree->delete;
+
+ $orig_entity->add_part($new_entity, 0); # plain comes before html
+ $self->{MIMEObj} = $orig_entity;
+
+ return;
+}
+
+=head2 CurrentUserHasQueueRight
+
+Helper function to call the template's queue's CurrentUserHasQueueRight with the passed in args.
+
+=cut
+
+sub CurrentUserHasQueueRight {
+ my $self = shift;
+ return ( $self->QueueObj->CurrentUserHasRight(@_) );
+}
+
+=head2 SetType
+
+If setting Type to Perl, require the ExecuteCode right.
+
+=cut
+
+sub SetType {
+ my $self = shift;
+ my $NewType = shift;
+
+ if ($NewType eq 'Perl' && !$self->CurrentUser->HasRight(Right => 'ExecuteCode', Object => $RT::System)) {
+ return ( undef, $self->loc('Permission Denied') );
+ }
+
+ return $self->_Set( Field => 'Type', Value => $NewType );
+}
+
+=head2 SetContent
+
+If changing content and the type is Perl, require the ExecuteCode right.
+
+=cut
+
+sub SetContent {
+ my $self = shift;
+ my $NewContent = shift;
+
+ if ($self->Type eq 'Perl' && !$self->CurrentUser->HasRight(Right => 'ExecuteCode', Object => $RT::System)) {
+ return ( undef, $self->loc('Permission Denied') );
+ }
+
+ return $self->_Set( Field => 'Content', Value => $NewContent );
+}
+
+sub _UpdateAttributes {
+ my $self = shift;
+ my %args = (
+ NewValues => {},
+ @_,
+ );
+
+ my $type = $args{NewValues}{Type} || $self->Type;