1 # BEGIN BPS TAGGED BLOCK {{{
5 # This software is Copyright (c) 1996-2014 Best Practical Solutions, LLC
6 # <sales@bestpractical.com>
8 # (Except where explicitly superseded by other copyright notices)
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
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.
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/licenses/old-licenses/gpl-2.0.html.
30 # CONTRIBUTION SUBMISSION POLICY:
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.)
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.
47 # END BPS TAGGED BLOCK }}}
49 # Portions Copyright 2000 Tobias Brox <tobix@cpan.org>
53 RT::Template - RT's template object
78 use Scalar::Util 'blessed';
85 Description => 'read/write',
86 Type => 'read/write', #Type is one of Perl or Simple
87 Content => 'read/write',
88 Queue => 'read/write',
89 Creator => 'read/auto',
90 Created => 'read/auto',
91 LastUpdatedBy => 'read/auto',
92 LastUpdated => 'read/auto'
94 return $self->SUPER::_Accessible( @_, %Cols );
105 unless ( $self->CurrentUserHasQueueRight('ModifyTemplate') ) {
106 return ( 0, $self->loc('Permission Denied') );
109 if (exists $args{Value}) {
110 if ($args{Field} eq 'Queue') {
112 # moving to another queue
113 my $queue = RT::Queue->new( $self->CurrentUser );
114 $queue->Load($args{Value});
115 unless ($queue->Id and $queue->CurrentUserHasRight('ModifyTemplate')) {
116 return ( 0, $self->loc('Permission Denied') );
120 unless ($self->CurrentUser->HasRight( Object => RT->System, Right => 'ModifyTemplate' )) {
121 return ( 0, $self->loc('Permission Denied') );
127 return $self->SUPER::_Set( @_ );
132 Takes the name of a table column. Returns its value as a string,
133 if the user passes an ACL check, otherwise returns undef.
140 unless ( $self->CurrentUserCanRead() ) {
143 return $self->__Value( @_ );
147 =head2 Load <identifier>
149 Load a template, either by number or by name.
151 Note that loading templates by name using this method B<is
152 ambiguous>. Several queues may have template with the same name
153 and as well global template with the same name may exist.
154 Use L</LoadGlobalTemplate> and/or L<LoadQueueTemplate> to get
161 my $identifier = shift;
162 return undef unless $identifier;
164 if ( $identifier =~ /\D/ ) {
165 return $self->LoadByCol( 'Name', $identifier );
167 return $self->LoadById( $identifier );
170 =head2 LoadGlobalTemplate NAME
172 Load the global template with the name NAME
176 sub LoadGlobalTemplate {
180 return ( $self->LoadQueueTemplate( Queue => 0, Name => $name ) );
183 =head2 LoadQueueTemplate (Queue => QUEUEID, Name => NAME)
185 Loads the Queue template named NAME for Queue QUEUE.
187 Note that this method doesn't load a global template with the same name
188 if template in the queue doesn't exist. THe following code can be used:
190 $template->LoadQueueTemplate( Queue => $queue_id, Name => $template_name );
191 unless ( $template->id ) {
192 $template->LoadGlobalTemplate( $template_name );
193 unless ( $template->id ) {
198 # ok, template either queue's or global
203 sub LoadQueueTemplate {
211 return ( $self->LoadByCols( Name => $args{'Name'}, Queue => $args{'Queue'} ) );
217 Takes a paramhash of Content, Queue, Name and Description.
218 Name should be a unique string identifying this Template.
219 Description and Content should be the template's title and content.
220 Queue should be 0 for a global template and the queue # for a queue-specific
223 Returns the Template's id # if the create was successful. Returns undef for
224 unknown database failure.
233 Description => '[no description]',
239 if ( $args{Type} eq 'Perl' && !$self->CurrentUser->HasRight(Right => 'ExecuteCode', Object => $RT::System) ) {
240 return ( undef, $self->loc('Permission Denied') );
243 unless ( $args{'Queue'} ) {
244 unless ( $self->CurrentUser->HasRight(Right =>'ModifyTemplate', Object => $RT::System) ) {
245 return ( undef, $self->loc('Permission Denied') );
250 my $QueueObj = RT::Queue->new( $self->CurrentUser );
251 $QueueObj->Load( $args{'Queue'} ) || return ( undef, $self->loc('Invalid queue') );
253 unless ( $QueueObj->CurrentUserHasRight('ModifyTemplate') ) {
254 return ( undef, $self->loc('Permission Denied') );
256 $args{'Queue'} = $QueueObj->Id;
259 my ( $result, $msg ) = $self->SUPER::Create(
260 Content => $args{'Content'},
261 Queue => $args{'Queue'},
262 Description => $args{'Description'},
263 Name => $args{'Name'},
264 Type => $args{'Type'},
268 return ( $result, $msg );
277 Delete this template.
284 unless ( $self->CurrentUserHasQueueRight('ModifyTemplate') ) {
285 return ( 0, $self->loc('Permission Denied') );
288 return ( $self->SUPER::Delete(@_) );
293 Returns true value if content of the template is empty, otherwise
300 my $content = $self->Content;
301 return 0 if defined $content && length $content;
307 Returns L<MIME::Entity> object parsed using L</Parse> method. Returns
308 undef if last call to L</Parse> failed or never be called.
310 Note that content of the template is UTF-8, but L<MIME::Parser> is not
311 good at handling it and all data of the entity should be treated as
312 octets and converted to perl strings using Encode::decode_utf8 or
319 return ( $self->{'MIMEObj'} );
324 This routine performs L<Text::Template> parsing on the template and then
325 imports the results into a L<MIME::Entity> so we can really use it. Use
326 L</MIMEObj> method to get the L<MIME::Entity> object.
328 Takes a hash containing Argument, TicketObj, and TransactionObj and other
329 arguments that will be available in the template's code. TicketObj and
330 TransactionObj are not mandatory, but highly recommended.
332 It returns a tuple of (val, message). If val is false, the message contains
342 if (not $self->IsEmpty and $self->Content =~ m{^Content-Type:\s+text/html\b}im) {
343 local $RT::Transaction::PreferredContentType = 'text/html';
344 ($rv, $msg) = $self->_Parse(@_);
347 ($rv, $msg) = $self->_Parse(@_);
350 return ($rv, $msg) unless $rv;
352 my $mime_type = $self->MIMEObj->mime_type;
353 if (defined $mime_type and $mime_type eq 'text/html') {
354 $self->_DowngradeFromHTML(@_);
363 # clear prev MIME object
364 $self->{'MIMEObj'} = undef;
366 #We're passing in whatever we were passed. it's destined for _ParseContent
367 my ($content, $msg) = $self->_ParseContent(@_);
368 return ( 0, $msg ) unless defined $content && length $content;
370 if ( $content =~ /^\S/s && $content !~ /^\S+:/ ) {
372 "Template #". $self->id ." has leading line that doesn't"
373 ." look like header field, if you don't want to override"
374 ." any headers and don't want to see this error message"
375 ." then leave first line of the template empty"
377 $content = "\n".$content;
380 my $parser = MIME::Parser->new();
381 $parser->output_to_core(1);
382 $parser->tmp_to_core(1);
383 $parser->use_inner_files(1);
385 ### Should we forgive normally-fatal errors?
386 $parser->ignore_errors(1);
387 # MIME::Parser doesn't play well with perl strings
388 utf8::encode($content);
389 $self->{'MIMEObj'} = eval { $parser->parse_data( \$content ) };
390 if ( my $error = $@ || $parser->last_error ) {
391 $RT::Logger->error( "$error" );
392 return ( 0, $error );
396 $self->{'MIMEObj'}->head->unfold;
397 $self->{'MIMEObj'}->head->modify(1);
399 return ( 1, $self->loc("Template parsed") );
403 # Perform Template substitutions on the template
410 TransactionObj => undef,
414 unless ( $self->CurrentUserCanRead() ) {
415 return (undef, $self->loc("Permission Denied"));
418 if ( $self->IsEmpty ) {
419 return ( undef, $self->loc("Template is empty") );
422 my $content = $self->SUPER::_Value('Content');
423 # We need to untaint the content of the template, since we'll be working
425 $content =~ s/^(.*)$/$1/;
427 $args{'Ticket'} = delete $args{'TicketObj'} if $args{'TicketObj'};
428 $args{'Transaction'} = delete $args{'TransactionObj'} if $args{'TransactionObj'};
429 $args{'Requestor'} = eval { $args{'Ticket'}->Requestors->UserMembersObj->First->Name }
431 $args{'rtname'} = RT->Config->Get('rtname');
432 if ( $args{'Ticket'} ) {
433 my $t = $args{'Ticket'}; # avoid memory leak
434 $args{'loc'} = sub { $t->loc(@_) };
436 $args{'loc'} = sub { $self->loc(@_) };
439 if ($self->Type eq 'Perl') {
440 return $self->_ParseContentPerl(
442 TemplateArgs => \%args,
446 return $self->_ParseContentSimple(
448 TemplateArgs => \%args,
453 # uses Text::Template for Perl templates
454 sub _ParseContentPerl {
462 foreach my $key ( keys %{ $args{TemplateArgs} } ) {
463 my $val = $args{TemplateArgs}{ $key };
464 next unless ref $val;
465 next if ref($val) =~ /^(ARRAY|HASH|SCALAR|CODE)$/;
466 $args{TemplateArgs}{ $key } = \$val;
469 my $template = Text::Template->new(
471 SOURCE => $args{Content},
473 my ($ok) = $template->compile;
475 $RT::Logger->error("Template parsing error in @{[$self->Name]} (#@{[$self->id]}): $Text::Template::ERROR");
476 return ( undef, $self->loc('Template parsing error: [_1]', $Text::Template::ERROR) );
480 my $retval = $template->fill_in(
481 HASH => $args{TemplateArgs},
484 $RT::Logger->error("Template parsing error: $args{error}")
485 unless $args{error} =~ /^Died at /; # ignore intentional die()
490 return ( undef, $self->loc('Template parsing error') ) if $is_broken;
495 sub _ParseContentSimple {
503 $self->_MassageSimpleTemplateArgs(%args);
505 my $template = Text::Template->new(
507 SOURCE => $args{Content},
509 my ($ok) = $template->compile;
510 return ( undef, $self->loc('Template parsing error: [_1]', $Text::Template::ERROR) ) if !$ok;
512 # copied from Text::Template::fill_in and refactored to be simple variable
515 foreach my $fi_item (@{$template->{SOURCE}}) {
516 my ($fi_type, $fi_text, $fi_lineno) = @$fi_item;
517 if ($fi_type eq 'TEXT') {
519 } elsif ($fi_type eq 'PROG') {
521 my $original_fi_text = $fi_text;
523 # strip surrounding whitespace for simpler regexes
524 $fi_text =~ s/^\s+//;
525 $fi_text =~ s/\s+$//;
527 # if the codeblock is a simple $Variable lookup, use the value from
528 # the TemplateArgs hash...
529 if (my ($var) = $fi_text =~ /^\$(\w+)$/) {
530 if (exists $args{TemplateArgs}{$var}) {
531 $fi_res = $args{TemplateArgs}{$var};
535 # if there was no substitution then just reinsert the codeblock
536 if (!defined $fi_res) {
537 $fi_res = "{$original_fi_text}";
540 # If the value of the filled-in text really was undef,
541 # change it to an explicit empty string to avoid undefined
542 # value warnings later.
543 $fi_res = '' unless defined $fi_res;
552 sub _MassageSimpleTemplateArgs {
559 my $template_args = $args{TemplateArgs};
561 if (my $ticket = $template_args->{Ticket}) {
562 for my $column (qw/Id Subject Type InitialPriority FinalPriority Priority TimeEstimated TimeWorked Status TimeLeft Told Starts Started Due Resolved RequestorAddresses AdminCcAddresses CcAddresses/) {
563 $template_args->{"Ticket".$column} = $ticket->$column;
566 $template_args->{"TicketQueueId"} = $ticket->Queue;
567 $template_args->{"TicketQueueName"} = $ticket->QueueObj->Name;
569 $template_args->{"TicketOwnerId"} = $ticket->Owner;
570 $template_args->{"TicketOwnerName"} = $ticket->OwnerObj->Name;
571 $template_args->{"TicketOwnerEmailAddress"} = $ticket->OwnerObj->EmailAddress;
573 my $cfs = $ticket->CustomFields;
574 while (my $cf = $cfs->Next) {
575 $template_args->{"TicketCF" . $cf->Name} = $ticket->CustomFieldValuesAsString($cf->Name);
579 if (my $txn = $template_args->{Transaction}) {
580 for my $column (qw/Id TimeTaken Type Field OldValue NewValue Data Content Subject Description BriefDescription/) {
581 $template_args->{"Transaction".$column} = $txn->$column;
584 my $cfs = $txn->CustomFields;
585 while (my $cf = $cfs->Next) {
586 $template_args->{"TransactionCF" . $cf->Name} = $txn->CustomFieldValuesAsString($cf->Name);
591 sub _DowngradeFromHTML {
593 my $orig_entity = $self->MIMEObj;
595 my $new_entity = $orig_entity->dup; # this will fail badly if we go away from InCore parsing
596 $new_entity->head->mime_attr( "Content-Type" => 'text/plain' );
597 $new_entity->head->mime_attr( "Content-Type.charset" => 'utf-8' );
599 $orig_entity->head->mime_attr( "Content-Type" => 'text/html' );
600 $orig_entity->head->mime_attr( "Content-Type.charset" => 'utf-8' );
601 $orig_entity->make_multipart('alternative', Force => 1);
603 require HTML::FormatText;
604 require HTML::TreeBuilder;
606 # need to decode_utf8, see the doc of MIMEObj method
607 my $tree = HTML::TreeBuilder->new_from_content(
608 Encode::decode_utf8($new_entity->bodyhandle->as_string)
610 $new_entity->bodyhandle(MIME::Body::InCore->new(
611 \(scalar HTML::FormatText->new(
618 $orig_entity->add_part($new_entity, 0); # plain comes before html
619 $self->{MIMEObj} = $orig_entity;
624 =head2 CurrentUserHasQueueRight
626 Helper function to call the template's queue's CurrentUserHasQueueRight with the passed in args.
630 sub CurrentUserHasQueueRight {
632 return ( $self->QueueObj->CurrentUserHasRight(@_) );
637 If setting Type to Perl, require the ExecuteCode right.
645 if ($NewType eq 'Perl' && !$self->CurrentUser->HasRight(Right => 'ExecuteCode', Object => $RT::System)) {
646 return ( undef, $self->loc('Permission Denied') );
649 return $self->_Set( Field => 'Type', Value => $NewType );
654 If changing content and the type is Perl, require the ExecuteCode right.
660 my $NewContent = shift;
662 if ($self->Type eq 'Perl' && !$self->CurrentUser->HasRight(Right => 'ExecuteCode', Object => $RT::System)) {
663 return ( undef, $self->loc('Permission Denied') );
666 return $self->_Set( Field => 'Content', Value => $NewContent );
669 sub _UpdateAttributes {
676 my $type = $args{NewValues}{Type} || $self->Type;
678 # forbid updating content when the (possibly new) value of Type is Perl
679 if ($type eq 'Perl' && exists $args{NewValues}{Content}) {
680 if (!$self->CurrentUser->HasRight(Right => 'ExecuteCode', Object => $RT::System)) {
681 return $self->loc('Permission Denied');
685 return $self->SUPER::_UpdateAttributes(%args);
690 If the template's Type is Perl, then compile check all the codeblocks to see if
691 they are syntactically valid. We eval them in a codeblock to avoid actually
694 Returns an (ok, message) pair.
701 return (1, $self->loc("Template does not include Perl code"))
702 unless $self->Type eq 'Perl';
704 my $content = $self->Content;
705 $content = '' if !defined($content);
707 my $template = Text::Template->new(
711 my ($ok) = $template->compile;
712 return ( undef, $self->loc('Template parsing error: [_1]', $Text::Template::ERROR) ) if !$ok;
714 # copied from Text::Template::fill_in and refactored to be compile checks
715 foreach my $fi_item (@{$template->{SOURCE}}) {
716 my ($fi_type, $fi_text, $fi_lineno) = @$fi_item;
717 next unless $fi_type eq 'PROG';
721 eval "sub { $fi_text }";
727 # provide a (hopefully) useful line number for the error, but clean up
728 # all the other extraneous garbage
729 $error =~ s/\(eval \d+\) line (\d+).*/"template line " . ($1+$fi_lineno-1)/es;
731 return (0, $self->loc("Couldn't compile template codeblock '[_1]': [_2]", $fi_text, $error));
734 return (1, $self->loc("Template compiles"));
737 =head2 CurrentUserCanRead
741 sub CurrentUserCanRead {
744 return 1 if $self->CurrentUserHasQueueRight('ShowTemplate');
746 return $self->CurrentUser->HasRight( Right =>'ShowGlobalTemplates', Object => $RT::System )
747 if !$self->QueueObj->Id;
755 use base 'RT::Record';
757 sub Table {'Templates'}
766 Returns the current value of id.
767 (In the database, id is stored as int(11).)
775 Returns the current value of Queue.
776 (In the database, Queue is stored as int(11).)
780 =head2 SetQueue VALUE
784 Returns (1, 'Status message') on success and (0, 'Error Message') on failure.
785 (In the database, Queue will be stored as a int(11).)
793 Returns the Queue Object which has the id returned by Queue
800 my $Queue = RT::Queue->new($self->CurrentUser);
801 $Queue->Load($self->__Value('Queue'));
807 Returns the current value of Name.
808 (In the database, Name is stored as varchar(200).)
816 Returns (1, 'Status message') on success and (0, 'Error Message') on failure.
817 (In the database, Name will be stored as a varchar(200).)
825 Returns the current value of Description.
826 (In the database, Description is stored as varchar(255).)
830 =head2 SetDescription VALUE
833 Set Description to VALUE.
834 Returns (1, 'Status message') on success and (0, 'Error Message') on failure.
835 (In the database, Description will be stored as a varchar(255).)
843 Returns the current value of Type.
844 (In the database, Type is stored as varchar(16).)
852 Returns (1, 'Status message') on success and (0, 'Error Message') on failure.
853 (In the database, Type will be stored as a varchar(16).)
861 Returns the current value of Language.
862 (In the database, Language is stored as varchar(16).)
866 =head2 SetLanguage VALUE
869 Set Language to VALUE.
870 Returns (1, 'Status message') on success and (0, 'Error Message') on failure.
871 (In the database, Language will be stored as a varchar(16).)
879 Returns the current value of TranslationOf.
880 (In the database, TranslationOf is stored as int(11).)
884 =head2 SetTranslationOf VALUE
887 Set TranslationOf to VALUE.
888 Returns (1, 'Status message') on success and (0, 'Error Message') on failure.
889 (In the database, TranslationOf will be stored as a int(11).)
897 Returns the current value of Content.
898 (In the database, Content is stored as text.)
902 =head2 SetContent VALUE
905 Set Content to VALUE.
906 Returns (1, 'Status message') on success and (0, 'Error Message') on failure.
907 (In the database, Content will be stored as a text.)
915 Returns the current value of LastUpdated.
916 (In the database, LastUpdated is stored as datetime.)
924 Returns the current value of LastUpdatedBy.
925 (In the database, LastUpdatedBy is stored as int(11).)
933 Returns the current value of Creator.
934 (In the database, Creator is stored as int(11).)
942 Returns the current value of Created.
943 (In the database, Created is stored as datetime.)
950 sub _CoreAccessible {
954 {read => 1, sql_type => 4, length => 11, is_blob => 0, is_numeric => 1, type => 'int(11)', default => ''},
956 {read => 1, write => 1, sql_type => 4, length => 11, is_blob => 0, is_numeric => 1, type => 'int(11)', default => '0'},
958 {read => 1, write => 1, sql_type => 12, length => 200, is_blob => 0, is_numeric => 0, type => 'varchar(200)', default => ''},
960 {read => 1, write => 1, sql_type => 12, length => 255, is_blob => 0, is_numeric => 0, type => 'varchar(255)', default => ''},
962 {read => 1, write => 1, sql_type => 12, length => 16, is_blob => 0, is_numeric => 0, type => 'varchar(16)', default => ''},
964 {read => 1, write => 1, sql_type => 12, length => 16, is_blob => 0, is_numeric => 0, type => 'varchar(16)', default => ''},
966 {read => 1, write => 1, sql_type => 4, length => 11, is_blob => 0, is_numeric => 1, type => 'int(11)', default => '0'},
968 {read => 1, write => 1, sql_type => -4, length => 0, is_blob => 1, is_numeric => 0, type => 'text', default => ''},
970 {read => 1, auto => 1, sql_type => 11, length => 0, is_blob => 0, is_numeric => 0, type => 'datetime', default => ''},
972 {read => 1, auto => 1, sql_type => 4, length => 11, is_blob => 0, is_numeric => 1, type => 'int(11)', default => '0'},
974 {read => 1, auto => 1, sql_type => 4, length => 11, is_blob => 0, is_numeric => 1, type => 'int(11)', default => '0'},
976 {read => 1, auto => 1, sql_type => 11, length => 0, is_blob => 0, is_numeric => 0, type => 'datetime', default => ''},
981 RT::Base->_ImportOverlays();