Template_Overlay.pm 15.3 KB
Newer Older
1
# BEGIN BPS TAGGED BLOCK {{{
2
# 
3
# COPYRIGHT:
Jesse Vincent's avatar
Jesse Vincent committed
4
# 
5
# This software is Copyright (c) 1996-2009 Best Practical Solutions, LLC
6
#                                          <jesse@bestpractical.com>
7
# 
8
9
10
11
# (Except where explicitly superseded by other copyright notices)
# 
# 
# LICENSE:
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.
17
18
19
20
21
22
# 
# 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.
# 
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.
28
29
30
31
32
33
34
35
36
# 
# 
# 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.)
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.
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;
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
72
73
no warnings qw(redefine);

74
use Text::Template;
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
75
76
use MIME::Entity;
use MIME::Parser;
77
use Scalar::Util 'blessed';
78

Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
79
80
81
82
83
84
sub _Accessible {
    my $self = shift;
    my %Cols = (
        id            => 'read',
        Name          => 'read/write',
        Description   => 'read/write',
85
        Type          => 'read/write',    #Type is one of Full or Simple
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
86
87
88
89
90
91
92
93
94
95
96
97
        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;
98
99
100
    
    unless ( $self->CurrentUserHasQueueRight('ModifyTemplate') ) {
        return ( 0, $self->loc('Permission Denied') );
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
101
    }
102
    return $self->SUPER::_Set( @_ );
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
103
104
105
106
}

=head2 _Value

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

Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
110
111
112
113
=cut

sub _Value {
    my $self  = shift;
114
115
116

    unless ( $self->CurrentUserHasQueueRight('ShowTemplate') ) {
        return undef;
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
117
    }
118
    return $self->__Value( @_ );
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
119
120
121

}

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

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

126
127
128
129
130
131
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.
Use L</LoadGlobalTemplate> and/or L<LoadQueueTemplate> to get
precise result.

Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
132
133
134
135
136
=cut

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

139
140
    if ( $identifier =~ /\D/ ) {
        return $self->LoadByCol( 'Name', $identifier );
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
141
    }
142
    return $self->LoadById( $identifier );
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
143
144
145
146
}

=head2 LoadGlobalTemplate NAME

Jesse Vincent's avatar
Jesse Vincent committed
147
Load the global template with the name NAME
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
148
149
150
151
152

=cut

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

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

Ruslan Zakirov's avatar
Ruslan Zakirov committed
158
=head2 LoadQueueTemplate (Queue => QUEUEID, Name => NAME)
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
159
160
161

Loads the Queue template named NAME for Queue QUEUE.

Ruslan Zakirov's avatar
Ruslan Zakirov committed
162
163
164
165
166
167
168
169
170
171
172
173
174
175
Note that this method doesn't load a global template with the same name
if template in the queue doesn't exist. THe following code can be used:

    $template->LoadQueueTemplate( Queue => $queue_id, Name => $template_name );
    unless ( $template->id ) {
        $template->LoadGlobalTemplate( $template_name );
        unless ( $template->id ) {
            # no template
            ...
        }
    }
    # ok, template either queue's or global
    ...

Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
176
177
178
179
180
181
=cut

sub LoadQueueTemplate {
    my $self = shift;
    my %args = (
        Queue => undef,
182
183
        Name  => undef,
        @_
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
184
185
    );

186
    return ( $self->LoadByCols( Name => $args{'Name'}, Queue => $args{'Queue'} ) );
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208

}

=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]',
209
        Type        => 'Full',
210
        Name        => undef,
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
211
212
213
        @_
    );

214
    unless ( $args{'Queue'} ) {
215
        unless ( $self->CurrentUser->HasRight(Right =>'ModifyTemplate', Object => $RT::System) ) {
216
            return ( undef, $self->loc('Permission Denied') );
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
217
        }
218
        $args{'Queue'} = 0;
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
219
220
221
    }
    else {
        my $QueueObj = new RT::Queue( $self->CurrentUser );
222
        $QueueObj->Load( $args{'Queue'} ) || return ( undef, $self->loc('Invalid queue') );
223
    
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
224
        unless ( $QueueObj->CurrentUserHasRight('ModifyTemplate') ) {
225
            return ( undef, $self->loc('Permission Denied') );
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
226
        }
227
        $args{'Queue'} = $QueueObj->Id;
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
228
229
230
    }

    my $result = $self->SUPER::Create(
231
232
        Content     => $args{'Content'},
        Queue       => $args{'Queue'},
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
233
        Description => $args{'Description'},
234
        Name        => $args{'Name'},
235
        Type        => $args{'Type'},
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
    );

    return ($result);

}

=head2 Delete

Delete this template.

=cut

sub Delete {
    my $self = shift;

251
    unless ( $self->CurrentUserHasQueueRight('ModifyTemplate') ) {
252
        return ( 0, $self->loc('Permission Denied') );
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
253
254
255
256
257
    }

    return ( $self->SUPER::Delete(@_) );
}

258
259
260
261
262
263
264
265
266
267
268
269
270
271
=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;
}

Ruslan Zakirov's avatar
Ruslan Zakirov committed
272
273
274
275
276
=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
277
278
279
280
281
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
282
283
=cut

Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
284
285
286
287
288
sub MIMEObj {
    my $self = shift;
    return ( $self->{'MIMEObj'} );
}

Kevin Riggle's avatar
Kevin Riggle committed
289
=head2 Parse
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
290

Ruslan Zakirov's avatar
Ruslan Zakirov committed
291
This routine performs L<Text::Template> parsing on the template and then
Ruslan Zakirov's avatar
Ruslan Zakirov committed
292
293
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.
294

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

Ruslan Zakirov's avatar
Ruslan Zakirov committed
299
300
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
301
302
303
304
305

=cut

sub Parse {
    my $self = shift;
306
307
    my ($rv, $msg);

Jesse Vincent's avatar
Jesse Vincent committed
308

309
310
311
312
313
314
315
316
    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(@_);
    }

317
318
    return ($rv, $msg) unless $rv;

319
    my $mime_type   = $self->MIMEObj->mime_type;
320
    if (defined $mime_type and $mime_type eq 'text/html') {
321
322
323
324
325
326
327
328
        $self->_DowngradeFromHTML(@_);
    }

    return ($rv, $msg);
}

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

Ruslan Zakirov's avatar
Ruslan Zakirov committed
330
331
332
    # clear prev MIME object
    $self->{'MIMEObj'} = undef;

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

337
338
339
340
341
342
343
344
345
346
    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
347
    my $parser = MIME::Parser->new();
348
349
350
    $parser->output_to_core(1);
    $parser->tmp_to_core(1);
    $parser->use_inner_files(1);
351

Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
352
353
    ### Should we forgive normally-fatal errors?
    $parser->ignore_errors(1);
354
355
356
    # MIME::Parser doesn't play well with perl strings
    utf8::encode($content);
    $self->{'MIMEObj'} = eval { $parser->parse_data( \$content ) };
357
358
    if ( my $error = $@ || $parser->last_error ) {
        $RT::Logger->error( "$error" );
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
359
360
361
362
        return ( 0, $error );
    }

    # Unfold all headers
363
    $self->{'MIMEObj'}->head->unfold;
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
364

365
    return ( 1, $self->loc("Template parsed") );
Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
366
367
368
369
370
371
372
373
374
375
376
377
378
379

}

# Perform Template substitutions on the template

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

380
    unless ( $self->CurrentUserHasQueueRight('ShowTemplate') ) {
381
        return (undef, $self->loc("Permission Denied"));
382
383
    }

384
385
    if ( $self->IsEmpty ) {
        return ( undef, $self->loc("Template is empty") );
386
387
    }

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

393
394
    $args{'Ticket'} = delete $args{'TicketObj'} if $args{'TicketObj'};
    $args{'Transaction'} = delete $args{'TransactionObj'} if $args{'TransactionObj'};
Ruslan Zakirov's avatar
Ruslan Zakirov committed
395
396
    $args{'Requestor'} = eval { $args{'Ticket'}->Requestors->UserMembersObj->First->Name }
        if $args{'Ticket'};
Ruslan Zakirov's avatar
Ruslan Zakirov committed
397
398
399
400
401
402
403
404
    $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(@_) };
    }

405
406
407
408
409
410
411
    foreach my $key ( keys %args ) {
        next unless ref $args{ $key };
        next if ref $args{ $key } =~ /^(ARRAY|HASH|SCALAR|CODE)$/;
        my $val = $args{ $key };
        $args{ $key } = \$val;
    }

412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
    if ($self->Type eq 'Full') {
        return $self->_ParseContentFull(
            Content      => $content,
            TemplateArgs => \%args,
        );
    }
    else {
        return $self->_ParseContentSimple(
            Content      => $content,
            TemplateArgs => \%args,
        );
    }
}

# uses Text::Template for Full templates
sub _ParseContentFull {
    my $self = shift;
    my %args = (
        Content      => undef,
        TemplateArgs => {},
        @_,
    );
434

435
436
437
438
    my $template = Text::Template->new(
        TYPE   => 'STRING',
        SOURCE => $args{Content},
    );
439
    my $is_broken = 0;
440
    my $retval = $template->fill_in(
441
        HASH => $args{TemplateArgs},
442
443
444
445
446
447
        BROKEN => sub {
            my (%args) = @_;
            $RT::Logger->error("Template parsing error: $args{error}")
                unless $args{error} =~ /^Died at /; # ignore intentional die()
            $is_broken++;
            return undef;
448
        },
449
    );
450
    return ( undef, $self->loc('Template parsing error') ) if $is_broken;
451

Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
452
453
454
    return ($retval);
}

455
456
457
458
459
460
461
462
sub _ParseContentSimple {
    my $self = shift;
    my %args = (
        Content      => undef,
        TemplateArgs => {},
        @_,
    );

Shawn M Moore's avatar
Shawn M Moore committed
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
    my $template = Text::Template->new(
        TYPE   => 'STRING',
        SOURCE => $args{Content},
    );
    $template->compile;

    # 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 $interpolated;

            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};
                    $interpolated = 1;
                }
            }
            # otherwise if it looks like a method call...
            # XXX: this should be locked down otherwise you could say
            # $TicketObj->Steal or something similarly ugly
            elsif (my ($obj, $method) = $fi_text =~ /^\$(\w+)->(\w+)$/) {
498
                if (blessed($args{TemplateArgs}{$obj}) && $args{TemplateArgs}{$obj}->can($method)) {
Shawn M Moore's avatar
Shawn M Moore committed
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
                    $fi_res = $args{TemplateArgs}{$obj}->$method;
                    $interpolated = 1;
                }
            }

            # if there was no substitution then just reinsert the codeblock
            if (!$interpolated) {
                $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;
519
520
}

521
522
523
524
sub _DowngradeFromHTML {
    my $self = shift;
    my $orig_entity = $self->MIMEObj;

525
526
527
    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' );
528
529
530
531
532
533
534

    $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;
Ruslan Zakirov's avatar
Ruslan Zakirov committed
535
536
537
538
539
540
541
542
543
544
    my $tree = HTML::TreeBuilder->new_from_content(
        $new_entity->bodyhandle->as_string
    );
    $new_entity->bodyhandle(MIME::Body::InCore->new(
        \(scalar HTML::FormatText->new(
            leftmargin  => 0,
            rightmargin => 78,
        )->format( $tree ))
    ));
    $tree->delete;
545
546
547
548

    $orig_entity->add_part($new_entity, 0); # plain comes before html
    $self->{MIMEObj} = $orig_entity;

549
    return;
550
551
}

Jesse Vincent's avatar
rt.2.1  
Jesse Vincent committed
552
553
554
555
556
557
558
559
560
561
562
563
=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(@_) );
}

1;