Template.pm 27.7 KB
Newer Older
1
# BEGIN BPS TAGGED BLOCK {{{
Jesse Vincent's avatar
Jesse Vincent committed
2
#
3
# COPYRIGHT:
Jesse Vincent's avatar
Jesse Vincent committed
4
#
5
# This software is Copyright (c) 1996-2014 Best Practical Solutions, LLC
Kevin Falcone's avatar
Kevin Falcone committed
6
#                                          <sales@bestpractical.com>
Jesse Vincent's avatar
Jesse Vincent committed
7
#
8
# (Except where explicitly superseded by other copyright notices)
Jesse Vincent's avatar
Jesse Vincent committed
9
10
#
#
11
# LICENSE:
Jesse Vincent's avatar
Jesse Vincent committed
12
#
13
14
15
# 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
16
# from www.gnu.org.
Jesse Vincent's avatar
Jesse Vincent committed
17
#
18
19
20
21
# 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.
Jesse Vincent's avatar
Jesse Vincent committed
22
#
23
24
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
Jesse Vincent's avatar
Jesse Vincent committed
25
26
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 or visit their web page on the internet at
Ruslan Zakirov's avatar
Ruslan Zakirov committed
27
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html.
Jesse Vincent's avatar
Jesse Vincent committed
28
29
#
#
30
# CONTRIBUTION SUBMISSION POLICY:
Jesse Vincent's avatar
Jesse Vincent committed
31
#
32
33
34
35
36
# (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.)
Jesse Vincent's avatar
Jesse Vincent committed
37
#
38
39
40
41
42
43
44
45
# 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.
Jesse Vincent's avatar
Jesse Vincent committed
46
#
47
# END BPS TAGGED BLOCK }}}
48

Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# Portions Copyright 2000 Tobias Brox <tobix@cpan.org> 

=head1 NAME

  RT::Template - RT's template object

=head1 SYNOPSIS

  use RT::Template;

=head1 DESCRIPTION


=head1 METHODS


=cut

67
68
69

package RT::Template;

70
use strict;
Ruslan Zakirov's avatar
Ruslan Zakirov committed
71
use warnings;
72

73
use base 'RT::Record';
74

75
use RT::Queue;
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
76

77
use Text::Template;
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
78
79
use MIME::Entity;
use MIME::Parser;
80
use Scalar::Util 'blessed';
81

Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
82
83
84
85
86
87
sub _Accessible {
    my $self = shift;
    my %Cols = (
        id            => 'read',
        Name          => 'read/write',
        Description   => 'read/write',
88
        Type          => 'read/write',    #Type is one of Perl or Simple
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
89
90
91
92
93
94
95
96
97
98
99
100
        Content       => 'read/write',
        Queue         => 'read/write',
        Creator       => 'read/auto',
        Created       => 'read/auto',
        LastUpdatedBy => 'read/auto',
        LastUpdated   => 'read/auto'
    );
    return $self->SUPER::_Accessible( @_, %Cols );
}

sub _Set {
    my $self = shift;
101
102
103
104
105
    my %args = (
        Field => undef,
        Value => undef,
        @_,
    );
106
107
108
    
    unless ( $self->CurrentUserHasQueueRight('ModifyTemplate') ) {
        return ( 0, $self->loc('Permission Denied') );
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
109
    }
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128

    if (exists $args{Value}) {
        if ($args{Field} eq 'Queue') {
            if ($args{Value}) {
                # moving to another queue
                my $queue = RT::Queue->new( $self->CurrentUser );
                $queue->Load($args{Value});
                unless ($queue->Id and $queue->CurrentUserHasRight('ModifyTemplate')) {
                    return ( 0, $self->loc('Permission Denied') );
                }
            } else {
                # moving to global
                unless ($self->CurrentUser->HasRight( Object => RT->System, Right => 'ModifyTemplate' )) {
                    return ( 0, $self->loc('Permission Denied') );
                }
            }
        }
    }

129
    return $self->SUPER::_Set( @_ );
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
130
131
132
133
}

=head2 _Value

Ruslan Zakirov's avatar
Ruslan Zakirov committed
134
135
Takes the name of a table column. Returns its value as a string,
if the user passes an ACL check, otherwise returns undef.
136

Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
137
138
139
140
=cut

sub _Value {
    my $self  = shift;
141

142
    unless ( $self->CurrentUserCanRead() ) {
143
        return undef;
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
144
    }
145
    return $self->__Value( @_ );
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
146
147
148

}

Shawn M Moore's avatar
Shawn M Moore committed
149
=head2 Load <identifier>
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
150

Ruslan Zakirov's avatar
Ruslan Zakirov committed
151
Load a template, either by number or by name.
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
152

153
154
155
Note that loading templates by name using this method B<is
ambiguous>. Several queues may have template with the same name
and as well global template with the same name may exist.
156
Use L</LoadByName>, L</LoadGlobalTemplate> or L<LoadQueueTemplate> to get
157
158
precise result.

Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
159
160
161
162
163
=cut

sub Load {
    my $self       = shift;
    my $identifier = shift;
164
    return undef unless $identifier;
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
165

166
167
    if ( $identifier =~ /\D/ ) {
        return $self->LoadByCol( 'Name', $identifier );
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
168
    }
169
    return $self->LoadById( $identifier );
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
170
171
}

172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
=head2 LoadByName

Takes Name and Queue arguments. Tries to load queue specific template
first, then global. If Queue argument is omitted then global template
is tried, not template with the name in any queue.

=cut

sub LoadByName {
    my $self = shift;
    my %args = (
        Queue => undef,
        Name  => undef,
        @_
    );
    my $queue = $args{'Queue'};
    if ( blessed $queue ) {
        $queue = $queue->id;
190
    } elsif ( defined $queue and $queue =~ /\D/ ) {
191
192
193
194
195
196
197
198
199
200
201
202
        my $tmp = RT::Queue->new( $self->CurrentUser );
        $tmp->Load($queue);
        $queue = $tmp->id;
    }

    return $self->LoadGlobalTemplate( $args{'Name'} ) unless $queue;

    $self->LoadQueueTemplate( Queue => $queue, Name => $args{'Name'} );
    return $self->id if $self->id;
    return $self->LoadGlobalTemplate( $args{'Name'} );
}

Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
203
204
=head2 LoadGlobalTemplate NAME

Jesse Vincent's avatar
Jesse Vincent committed
205
Load the global template with the name NAME
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
206
207
208
209
210

=cut

sub LoadGlobalTemplate {
    my $self = shift;
Ruslan Zakirov's avatar
Ruslan Zakirov committed
211
    my $name = shift;
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
212

Ruslan Zakirov's avatar
Ruslan Zakirov committed
213
    return ( $self->LoadQueueTemplate( Queue => 0, Name => $name ) );
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
214
215
}

Ruslan Zakirov's avatar
Ruslan Zakirov committed
216
=head2 LoadQueueTemplate (Queue => QUEUEID, Name => NAME)
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
217
218
219

Loads the Queue template named NAME for Queue QUEUE.

Ruslan Zakirov's avatar
Ruslan Zakirov committed
220
Note that this method doesn't load a global template with the same name
221
if template in the queue doesn't exist. Use L</LoadByName>.
Ruslan Zakirov's avatar
Ruslan Zakirov committed
222

Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
223
224
225
226
227
228
=cut

sub LoadQueueTemplate {
    my $self = shift;
    my %args = (
        Queue => undef,
229
230
        Name  => undef,
        @_
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
231
232
    );

233
    return ( $self->LoadByCols( Name => $args{'Name'}, Queue => $args{'Queue'} ) );
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255

}

=head2 Create

Takes a paramhash of Content, Queue, Name and Description.
Name should be a unique string identifying this Template.
Description and Content should be the template's title and content.
Queue should be 0 for a global template and the queue # for a queue-specific 
template.

Returns the Template's id # if the create was successful. Returns undef for
unknown database failure.

=cut

sub Create {
    my $self = shift;
    my %args = (
        Content     => undef,
        Queue       => 0,
        Description => '[no description]',
256
        Type        => 'Perl',
257
        Name        => undef,
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
258
259
260
        @_
    );

Shawn M Moore's avatar
Shawn M Moore committed
261
    if ( $args{Type} eq 'Perl' && !$self->CurrentUser->HasRight(Right => 'ExecuteCode', Object => $RT::System) ) {
262
263
264
        return ( undef, $self->loc('Permission Denied') );
    }

265
    unless ( $args{'Queue'} ) {
266
        unless ( $self->CurrentUser->HasRight(Right =>'ModifyTemplate', Object => $RT::System) ) {
267
            return ( undef, $self->loc('Permission Denied') );
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
268
        }
269
        $args{'Queue'} = 0;
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
270
271
    }
    else {
272
        my $QueueObj = RT::Queue->new( $self->CurrentUser );
273
        $QueueObj->Load( $args{'Queue'} ) || return ( undef, $self->loc('Invalid queue') );
274
    
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
275
        unless ( $QueueObj->CurrentUserHasRight('ModifyTemplate') ) {
276
            return ( undef, $self->loc('Permission Denied') );
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
277
        }
278
        $args{'Queue'} = $QueueObj->Id;
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
279
280
    }

281
282
283
284
285
286
    return ( undef, $self->loc('Name is required') )
        unless $args{Name};

    {
        my $tmp = $self->new( RT->SystemUser );
        $tmp->LoadByCols( Name => $args{'Name'}, Queue => $args{'Queue'} );
Alex Vandiver's avatar
Alex Vandiver committed
287
        return ( undef, $self->loc('A Template with that name already exists') )
288
289
290
            if $tmp->id;
    }

291
    my ( $result, $msg ) = $self->SUPER::Create(
292
293
        Content     => $args{'Content'},
        Queue       => $args{'Queue'},
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
294
        Description => $args{'Description'},
295
        Name        => $args{'Name'},
296
        Type        => $args{'Type'},
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
297
298
    );

299
    if ( wantarray ) {
Kevin Falcone's avatar
Kevin Falcone committed
300
        return ( $result, $msg );
301
    } else {
Kevin Falcone's avatar
Kevin Falcone committed
302
        return ( $result );
303
    }
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
304
305
306
307
308
309
310
311
312
313
314
315

}

=head2 Delete

Delete this template.

=cut

sub Delete {
    my $self = shift;

316
    unless ( $self->CurrentUserHasQueueRight('ModifyTemplate') ) {
317
        return ( 0, $self->loc('Permission Denied') );
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
318
319
    }

320
    if ( !$self->IsOverride && $self->UsedBy->Count ) {
321
322
323
        return ( 0, $self->loc('Template is in use') );
    }

Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
324
325
326
    return ( $self->SUPER::Delete(@_) );
}

327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
=head2 UsedBy

Returns L<RT::Scrips> limitted to scrips that use this template. Takes
into account that template can be overriden in a queue.

=cut

sub UsedBy {
    my $self = shift;

    my $scrips = RT::Scrips->new( $self->CurrentUser );
    $scrips->LimitByTemplate( $self );
    return $scrips;
}

342
343
344
345
346
347
348
349
350
351
352
353
354
355
=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;
}

356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
=head2 IsOverride

Returns true if it's queue specific template and there is global
template with the same name.

=cut

sub IsOverride {
    my $self = shift;
    return 0 unless $self->Queue;

    my $template = RT::Template->new( $self->CurrentUser );
    $template->LoadGlobalTemplate( $self->Name );
    return $template->id;
}


Ruslan Zakirov's avatar
Ruslan Zakirov committed
373
374
375
376
377
=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.

Ruslan Zakirov's avatar
Ruslan Zakirov committed
378
379
380
381
382
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.

Ruslan Zakirov's avatar
Ruslan Zakirov committed
383
384
=cut

Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
385
386
387
388
389
sub MIMEObj {
    my $self = shift;
    return ( $self->{'MIMEObj'} );
}

Kevin Riggle's avatar
Kevin Riggle committed
390
=head2 Parse
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
391

Ruslan Zakirov's avatar
Ruslan Zakirov committed
392
This routine performs L<Text::Template> parsing on the template and then
Ruslan Zakirov's avatar
Ruslan Zakirov committed
393
394
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.
395

Ruslan Zakirov's avatar
Ruslan Zakirov committed
396
Takes a hash containing Argument, TicketObj, and TransactionObj and other
Ruslan Zakirov's avatar
Ruslan Zakirov committed
397
398
arguments that will be available in the template's code. TicketObj and
TransactionObj are not mandatory, but highly recommended.
399

Ruslan Zakirov's avatar
Ruslan Zakirov committed
400
401
It returns a tuple of (val, message). If val is false, the message contains
an error message.
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
402
403
404
405
406

=cut

sub Parse {
    my $self = shift;
407
408
    my ($rv, $msg);

Jesse Vincent's avatar
Jesse Vincent committed
409

410
    if (not $self->IsEmpty and $self->Content =~ m{^Content-Type:\s+text/html\b}im) {
411
412
413
414
415
416
417
        local $RT::Transaction::PreferredContentType = 'text/html';
        ($rv, $msg) = $self->_Parse(@_);
    }
    else {
        ($rv, $msg) = $self->_Parse(@_);
    }

418
419
    return ($rv, $msg) unless $rv;

420
    my $mime_type   = $self->MIMEObj->mime_type;
421
    if (defined $mime_type and $mime_type eq 'text/html') {
422
423
424
425
426
427
428
429
        $self->_DowngradeFromHTML(@_);
    }

    return ($rv, $msg);
}

sub _Parse {
    my $self = shift;
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
430

Ruslan Zakirov's avatar
Ruslan Zakirov committed
431
432
433
    # clear prev MIME object
    $self->{'MIMEObj'} = undef;

Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
434
    #We're passing in whatever we were passed. it's destined for _ParseContent
435
    my ($content, $msg) = $self->_ParseContent(@_);
436
    return ( 0, $msg ) unless defined $content && length $content;
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
437

438
439
440
441
442
443
444
445
446
447
    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;
    }

Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
448
    my $parser = MIME::Parser->new();
449
450
451
    $parser->output_to_core(1);
    $parser->tmp_to_core(1);
    $parser->use_inner_files(1);
452

Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
453
454
    ### Should we forgive normally-fatal errors?
    $parser->ignore_errors(1);
455
456
    # Always provide bytes, not characters, to MIME objects
    $content = Encode::encode( 'UTF-8', $content );
457
    $self->{'MIMEObj'} = eval { $parser->parse_data( \$content ) };
458
459
    if ( my $error = $@ || $parser->last_error ) {
        $RT::Logger->error( "$error" );
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
460
461
462
463
        return ( 0, $error );
    }

    # Unfold all headers
464
    $self->{'MIMEObj'}->head->unfold;
465
    $self->{'MIMEObj'}->head->modify(1);
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
466

467
    return ( 1, $self->loc("Template parsed") );
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
468
469
470
471
472
473
474
475
476
477
478
479
480
481

}

# Perform Template substitutions on the template

sub _ParseContent {
    my $self = shift;
    my %args = (
        Argument       => undef,
        TicketObj      => undef,
        TransactionObj => undef,
        @_
    );

482
    unless ( $self->CurrentUserCanRead() ) {
483
        return (undef, $self->loc("Permission Denied"));
484
485
    }

486
487
    if ( $self->IsEmpty ) {
        return ( undef, $self->loc("Template is empty") );
488
489
    }

490
    my $content = $self->SUPER::_Value('Content');
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
491
492
493
494
    # We need to untaint the content of the template, since we'll be working
    # with it
    $content =~ s/^(.*)$/$1/;

495
496
    $args{'Ticket'} = delete $args{'TicketObj'} if $args{'TicketObj'};
    $args{'Transaction'} = delete $args{'TransactionObj'} if $args{'TransactionObj'};
Ruslan Zakirov's avatar
Ruslan Zakirov committed
497
498
    $args{'Requestor'} = eval { $args{'Ticket'}->Requestors->UserMembersObj->First->Name }
        if $args{'Ticket'};
Ruslan Zakirov's avatar
Ruslan Zakirov committed
499
500
501
502
503
504
505
506
    $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(@_) };
    }

507
508
    if ($self->Type eq 'Perl') {
        return $self->_ParseContentPerl(
509
510
511
512
513
514
515
516
517
518
519
520
            Content      => $content,
            TemplateArgs => \%args,
        );
    }
    else {
        return $self->_ParseContentSimple(
            Content      => $content,
            TemplateArgs => \%args,
        );
    }
}

521
522
# uses Text::Template for Perl templates
sub _ParseContentPerl {
523
524
525
526
527
528
    my $self = shift;
    my %args = (
        Content      => undef,
        TemplateArgs => {},
        @_,
    );
529

530
531
532
    foreach my $key ( keys %{ $args{TemplateArgs} } ) {
        my $val = $args{TemplateArgs}{ $key };
        next unless ref $val;
533
        next if ref($val) =~ /^(ARRAY|HASH|SCALAR|CODE)$/;
534
535
536
        $args{TemplateArgs}{ $key } = \$val;
    }

537
538
539
540
    my $template = Text::Template->new(
        TYPE   => 'STRING',
        SOURCE => $args{Content},
    );
541
542
543
544
545
546
    my ($ok) = $template->compile;
    unless ($ok) {
        $RT::Logger->error("Template parsing error in @{[$self->Name]} (#@{[$self->id]}): $Text::Template::ERROR");
        return ( undef, $self->loc('Template parsing error: [_1]', $Text::Template::ERROR) );
    }

547
    my $is_broken = 0;
548
    my $retval = $template->fill_in(
549
        HASH => $args{TemplateArgs},
550
551
552
553
554
555
        BROKEN => sub {
            my (%args) = @_;
            $RT::Logger->error("Template parsing error: $args{error}")
                unless $args{error} =~ /^Died at /; # ignore intentional die()
            $is_broken++;
            return undef;
556
        },
557
    );
558
    return ( undef, $self->loc('Template parsing error') ) if $is_broken;
559

Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
560
561
562
    return ($retval);
}

563
564
565
566
567
568
569
570
sub _ParseContentSimple {
    my $self = shift;
    my %args = (
        Content      => undef,
        TemplateArgs => {},
        @_,
    );

571
572
    $self->_MassageSimpleTemplateArgs(%args);

Shawn M Moore's avatar
Shawn M Moore committed
573
574
575
576
    my $template = Text::Template->new(
        TYPE   => 'STRING',
        SOURCE => $args{Content},
    );
577
    my ($ok) = $template->compile;
578
    return ( undef, $self->loc('Template parsing error: [_1]', $Text::Template::ERROR) ) if !$ok;
Shawn M Moore's avatar
Shawn M Moore committed
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603

    # 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
604
            if (!defined $fi_res) {
Shawn M Moore's avatar
Shawn M Moore committed
605
606
607
608
609
610
611
612
613
614
615
616
617
                $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;
618
619
}

620
621
622
623
624
625
626
627
628
629
sub _MassageSimpleTemplateArgs {
    my $self = shift;
    my %args = (
        TemplateArgs => {},
        @_,
    );

    my $template_args = $args{TemplateArgs};

    if (my $ticket = $template_args->{Ticket}) {
Shawn M Moore's avatar
Shawn M Moore committed
630
        for my $column (qw/Id Subject Type InitialPriority FinalPriority Priority TimeEstimated TimeWorked Status TimeLeft Told Starts Started Due Resolved RequestorAddresses AdminCcAddresses CcAddresses/) {
631
632
            $template_args->{"Ticket".$column} = $ticket->$column;
        }
633
634
635
636
637
638
639

        $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;
640
641
642

        my $cfs = $ticket->CustomFields;
        while (my $cf = $cfs->Next) {
643
644
645
646
            my $simple = $cf->Name;
            $simple =~ s/\W//g;
            $template_args->{"TicketCF" . $simple}
                = $ticket->CustomFieldValuesAsString($cf->Name);
647
        }
648
649
650
    }

    if (my $txn = $template_args->{Transaction}) {
Shawn M Moore's avatar
Shawn M Moore committed
651
        for my $column (qw/Id TimeTaken Type Field OldValue NewValue Data Content Subject Description BriefDescription/) {
652
653
            $template_args->{"Transaction".$column} = $txn->$column;
        }
Shawn M Moore's avatar
Shawn M Moore committed
654
655
656

        my $cfs = $txn->CustomFields;
        while (my $cf = $cfs->Next) {
657
658
659
660
            my $simple = $cf->Name;
            $simple =~ s/\W//g;
            $template_args->{"TransactionCF" . $simple}
                = $txn->CustomFieldValuesAsString($cf->Name);
Shawn M Moore's avatar
Shawn M Moore committed
661
        }
662
663
664
    }
}

665
666
667
668
sub _DowngradeFromHTML {
    my $self = shift;
    my $orig_entity = $self->MIMEObj;

669
670
671
    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' );
672
673
674
675

    $orig_entity->head->mime_attr( "Content-Type" => 'text/html' );
    $orig_entity->head->mime_attr( "Content-Type.charset" => 'utf-8' );

676
    require Encode;
677
    my $body = $new_entity->bodyhandle->as_string;
678
    $body = Encode::decode( "UTF-8", $body );
679
    my $html = RT::Interface::Email::ConvertHTMLToText( $body );
680
    $html = Encode::encode( "UTF-8", $html );
681
682
683
    return unless defined $html;

    $new_entity->bodyhandle(MIME::Body::InCore->new( \$html ));
684

685
    $orig_entity->make_multipart('alternative', Force => 1);
686
687
688
    $orig_entity->add_part($new_entity, 0); # plain comes before html
    $self->{MIMEObj} = $orig_entity;

689
    return;
690
691
}

Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
692
693
694
695
696
697
698
699
700
701
702
=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(@_) );
}

703
704
705
706
707
708
709
710
711
712
713
=head2 SetQueue

Changing queue is not implemented.

=cut

sub SetQueue {
    my $self = shift;
    return ( undef, $self->loc('Changing queue is not implemented') );
}

714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
=head2 SetName

Change name of the template.

=cut

sub SetName {
    my $self = shift;
    my $value = shift;

    return ( undef, $self->loc('Name is required') )
        unless $value;

    return $self->_Set( Field => 'Name', Value => $value )
        if lc($self->Name) eq lc($value);

    my $tmp = $self->new( RT->SystemUser );
    $tmp->LoadByCols( Name => $value, Queue => $self->Queue );
Alex Vandiver's avatar
Alex Vandiver committed
732
    return ( undef, $self->loc('A Template with that name already exists') )
733
734
735
736
737
        if $tmp->id;

    return $self->_Set( Field => 'Name', Value => $value );
}

738
739
=head2 SetType

Shawn M Moore's avatar
Shawn M Moore committed
740
If setting Type to Perl, require the ExecuteCode right.
741
742
743
744
745
746
747

=cut

sub SetType {
    my $self    = shift;
    my $NewType = shift;

Shawn M Moore's avatar
Shawn M Moore committed
748
    if ($NewType eq 'Perl' && !$self->CurrentUser->HasRight(Right => 'ExecuteCode', Object => $RT::System)) {
749
750
751
752
753
754
        return ( undef, $self->loc('Permission Denied') );
    }

    return $self->_Set( Field => 'Type', Value => $NewType );
}

755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
=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 );
}

772
773
774
775
776
777
sub _UpdateAttributes {
    my $self = shift;
    my %args = (
        NewValues => {},
        @_,
    );
778

779
    my $type = $args{NewValues}{Type} || $self->Type;
780

781
782
783
784
785
    # forbid updating content when the (possibly new) value of Type is Perl
    if ($type eq 'Perl' && exists $args{NewValues}{Content}) {
        if (!$self->CurrentUser->HasRight(Right => 'ExecuteCode', Object => $RT::System)) {
            return $self->loc('Permission Denied');
        }
786
787
    }

788
    return $self->SUPER::_UpdateAttributes(%args);
789
790
}

791
792
=head2 CompileCheck

793
If the template's Type is Perl, then compile check all the codeblocks to see if
794
795
796
797
798
799
800
801
802
803
they are syntactically valid. We eval them in a codeblock to avoid actually
executing the code.

Returns an (ok, message) pair.

=cut

sub CompileCheck {
    my $self = shift;

Shawn M Moore's avatar
Shawn M Moore committed
804
    return (1, $self->loc("Template does not include Perl code"))
805
        unless $self->Type eq 'Perl';
806

807
808
809
    my $content = $self->Content;
    $content = '' if !defined($content);

810
811
    my $template = Text::Template->new(
        TYPE   => 'STRING',
812
        SOURCE => $content,
813
    );
814
815
    my ($ok) = $template->compile;
    return ( undef, $self->loc('Template parsing error: [_1]', $Text::Template::ERROR) ) if !$ok;
816
817
818
819
820
821

    # copied from Text::Template::fill_in and refactored to be compile checks
    foreach my $fi_item (@{$template->{SOURCE}}) {
        my ($fi_type, $fi_text, $fi_lineno) = @$fi_item;
        next unless $fi_type eq 'PROG';

822
823
824
825
        do {
            no strict 'vars';
            eval "sub { $fi_text }";
        };
826
827
828
829
830
831
832
833
834
835
836
        next if !$@;

        my $error = $@;

        # provide a (hopefully) useful line number for the error, but clean up
        # all the other extraneous garbage
        $error =~ s/\(eval \d+\) line (\d+).*/"template line " . ($1+$fi_lineno-1)/es;

        return (0, $self->loc("Couldn't compile template codeblock '[_1]': [_2]", $fi_text, $error));
    }

Shawn M Moore's avatar
Shawn M Moore committed
837
    return (1, $self->loc("Template compiles"));
838
}
839

840
841
842
843
844
845
=head2 CurrentUserCanRead

=cut

sub CurrentUserCanRead {
    my $self =shift;
846
847
848
849
850
851
852

    return 1 if $self->CurrentUserHasQueueRight('ShowTemplate');

    return $self->CurrentUser->HasRight( Right =>'ShowGlobalTemplates', Object => $RT::System )
        if !$self->QueueObj->Id;

    return;
853
854
}

Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
855
1;
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898

sub Table {'Templates'}






=head2 id

Returns the current value of id.
(In the database, id is stored as int(11).)


=cut


=head2 Queue

Returns the current value of Queue.
(In the database, Queue is stored as int(11).)



=head2 SetQueue VALUE


Set Queue to VALUE.
Returns (1, 'Status message') on success and (0, 'Error Message') on failure.
(In the database, Queue will be stored as a int(11).)


=cut


=head2 QueueObj

Returns the Queue Object which has the id returned by Queue


=cut

sub QueueObj {
899
900
901
902
    my $self = shift;
    my $Queue =  RT::Queue->new($self->CurrentUser);
    $Queue->Load($self->__Value('Queue'));
    return($Queue);
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
}

=head2 Name

Returns the current value of Name.
(In the database, Name is stored as varchar(200).)



=head2 SetName VALUE


Set Name to VALUE.
Returns (1, 'Status message') on success and (0, 'Error Message') on failure.
(In the database, Name will be stored as a varchar(200).)


=cut


=head2 Description

Returns the current value of Description.
(In the database, Description is stored as varchar(255).)



=head2 SetDescription VALUE


Set Description to VALUE.
Returns (1, 'Status message') on success and (0, 'Error Message') on failure.
(In the database, Description will be stored as a varchar(255).)


=cut


=head2 Type

Returns the current value of Type.
(In the database, Type is stored as varchar(16).)



=head2 SetType VALUE


Set Type to VALUE.
Returns (1, 'Status message') on success and (0, 'Error Message') on failure.
(In the database, Type will be stored as a varchar(16).)


=cut


=head2 Content

Returns the current value of Content.
(In the database, Content is stored as text.)



=head2 SetContent VALUE


Set Content to VALUE.
Returns (1, 'Status message') on success and (0, 'Error Message') on failure.
(In the database, Content will be stored as a text.)


=cut


=head2 LastUpdated

Returns the current value of LastUpdated.
(In the database, LastUpdated is stored as datetime.)


=cut


=head2 LastUpdatedBy

Returns the current value of LastUpdatedBy.
(In the database, LastUpdatedBy is stored as int(11).)


=cut


=head2 Creator

Returns the current value of Creator.
(In the database, Creator is stored as int(11).)