import rt 3.6.4
[freeside.git] / rt / lib / RT / Template_Overlay.pm
1 # BEGIN BPS TAGGED BLOCK {{{
2
3 # COPYRIGHT:
4 #  
5 # This software is Copyright (c) 1996-2007 Best Practical Solutions, LLC 
6 #                                          <jesse@bestpractical.com>
7
8 # (Except where explicitly superseded by other copyright notices)
9
10
11 # LICENSE:
12
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
16 # from www.gnu.org.
17
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.
22
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/copyleft/gpl.html.
28
29
30 # CONTRIBUTION SUBMISSION POLICY:
31
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.)
37
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.
46
47 # END BPS TAGGED BLOCK }}}
48 # Portions Copyright 2000 Tobias Brox <tobix@cpan.org> 
49
50 =head1 NAME
51
52   RT::Template - RT's template object
53
54 =head1 SYNOPSIS
55
56   use RT::Template;
57
58 =head1 DESCRIPTION
59
60
61 =head1 METHODS
62
63 =begin testing
64
65 ok(require RT::Template);
66
67 =end testing
68
69 =cut
70
71
72 package RT::Template;
73
74 use strict;
75 no warnings qw(redefine);
76
77 use Text::Template;
78 use MIME::Entity;
79 use MIME::Parser;
80 use File::Temp qw /tempdir/;
81
82
83 # {{{ sub _Accessible 
84
85 sub _Accessible {
86     my $self = shift;
87     my %Cols = (
88         id            => 'read',
89         Name          => 'read/write',
90         Description   => 'read/write',
91         Type          => 'read/write',    #Type is one of Action or Message
92         Content       => 'read/write',
93         Queue         => 'read/write',
94         Creator       => 'read/auto',
95         Created       => 'read/auto',
96         LastUpdatedBy => 'read/auto',
97         LastUpdated   => 'read/auto'
98     );
99     return $self->SUPER::_Accessible( @_, %Cols );
100 }
101
102 # }}}
103
104 # {{{ sub _Set
105
106 sub _Set {
107     my $self = shift;
108     
109     unless ( $self->CurrentUserHasQueueRight('ModifyTemplate') ) {
110         return ( 0, $self->loc('Permission Denied') );
111     }
112     return $self->SUPER::_Set( @_ );
113 }
114
115 # }}}
116
117 # {{{ sub _Value 
118
119 =head2 _Value
120
121 Takes the name of a table column.
122 Returns its value as a string, if the user passes an ACL check
123
124
125 =begin testing
126
127 my $t = RT::Template->new($RT::SystemUser);
128 $t->Create(Name => "Foo", Queue => 1);
129 my $t2 = RT::Template->new($RT::Nobody);
130 $t2->Load($t->Id);
131 ok($t2->QueueObj->id, "Got the template's queue objet");
132
133 =end testing
134
135
136
137 =cut
138
139 sub _Value {
140     my $self  = shift;
141
142     unless ( $self->CurrentUserHasQueueRight('ShowTemplate') ) {
143         return undef;
144     }
145     return $self->__Value( @_ );
146
147 }
148
149 # }}}
150
151 # {{{ sub Load
152
153 =head2 Load <identifer>
154
155 Load a template, either by number or by name
156
157 =cut
158
159 sub Load {
160     my $self       = shift;
161     my $identifier = shift;
162     return undef unless $identifier;
163
164     if ( $identifier =~ /\D/ ) {
165         return $self->LoadByCol( 'Name', $identifier );
166     }
167     return $self->LoadById( $identifier );
168 }
169
170 # }}}
171
172 # {{{ sub LoadGlobalTemplate
173
174 =head2 LoadGlobalTemplate NAME
175
176 Load the global template with the name NAME
177
178 =cut
179
180 sub LoadGlobalTemplate {
181     my $self = shift;
182     my $id   = shift;
183
184     return ( $self->LoadQueueTemplate( Queue => 0, Name => $id ) );
185 }
186
187 # }}}
188
189 # {{{ sub LoadQueueTemplate
190
191 =head2  LoadQueueTemplate (Queue => QUEUEID, Name => NAME)
192
193 Loads the Queue template named NAME for Queue QUEUE.
194
195 =cut
196
197 sub LoadQueueTemplate {
198     my $self = shift;
199     my %args = (
200         Queue => undef,
201         Name  => undef,
202         @_
203     );
204
205     return ( $self->LoadByCols( Name => $args{'Name'}, Queue => $args{'Queue'} ) );
206
207 }
208
209 # }}}
210
211 # {{{ sub Create
212
213 =head2 Create
214
215 Takes a paramhash of Content, Queue, Name and Description.
216 Name should be a unique string identifying this Template.
217 Description and Content should be the template's title and content.
218 Queue should be 0 for a global template and the queue # for a queue-specific 
219 template.
220
221 Returns the Template's id # if the create was successful. Returns undef for
222 unknown database failure.
223
224
225 =cut
226
227 sub Create {
228     my $self = shift;
229     my %args = (
230         Content     => undef,
231         Queue       => 0,
232         Description => '[no description]',
233         Type        => 'Action', #By default, template are 'Action' templates
234         Name        => undef,
235         @_
236     );
237
238     unless ( $args{'Queue'} ) {
239         unless ( $self->CurrentUser->HasRight(Right =>'ModifyTemplate', Object => $RT::System) ) {
240             return ( undef, $self->loc('Permission denied') );
241         }
242         $args{'Queue'} = 0;
243     }
244     else {
245         my $QueueObj = new RT::Queue( $self->CurrentUser );
246         $QueueObj->Load( $args{'Queue'} ) || return ( undef, $self->loc('Invalid queue') );
247     
248         unless ( $QueueObj->CurrentUserHasRight('ModifyTemplate') ) {
249             return ( undef, $self->loc('Permission denied') );
250         }
251         $args{'Queue'} = $QueueObj->Id;
252     }
253
254     my $result = $self->SUPER::Create(
255         Content     => $args{'Content'},
256         Queue       => $args{'Queue'},
257         Description => $args{'Description'},
258         Name        => $args{'Name'},
259     );
260
261     return ($result);
262
263 }
264
265 # }}}
266
267 # {{{ sub Delete
268
269 =head2 Delete
270
271 Delete this template.
272
273 =cut
274
275 sub Delete {
276     my $self = shift;
277
278     unless ( $self->CurrentUserHasQueueRight('ModifyTemplate') ) {
279         return ( 0, $self->loc('Permission Denied') );
280     }
281
282     return ( $self->SUPER::Delete(@_) );
283 }
284
285 # }}}
286
287 # {{{ sub MIMEObj
288 sub MIMEObj {
289     my $self = shift;
290     return ( $self->{'MIMEObj'} );
291 }
292
293 # }}}
294
295 # {{{ sub Parse 
296
297 =head2 Parse
298
299  This routine performs Text::Template parsing on the template and then
300  imports the results into a MIME::Entity so we can really use it
301
302  Takes a hash containing Argument, TicketObj, and TransactionObj.
303
304  It returns a tuple of (val, message)
305  If val is 0, the message contains an error message
306
307 =cut
308
309 sub Parse {
310     my $self = shift;
311
312     #We're passing in whatever we were passed. it's destined for _ParseContent
313     my ($content, $msg) = $self->_ParseContent(@_);
314     return ( 0, $msg ) unless defined $content;
315
316     #Lets build our mime Entity
317
318     my $parser = MIME::Parser->new();
319
320     # On some situations TMPDIR is non-writable. sad but true.
321     $parser->output_to_core(1);
322     $parser->tmp_to_core(1);
323
324     #If someone includes a message, don't extract it
325     $parser->extract_nested_messages(1);
326
327     # Set up the prefix for files with auto-generated names:
328     $parser->output_prefix("part");
329
330     # If content length is <= 50000 bytes, store each msg as in-core scalar;
331     # Else, write to a disk file (the default action):
332     $parser->output_to_core(50000);
333
334     ### Should we forgive normally-fatal errors?
335     $parser->ignore_errors(1);
336     $self->{'MIMEObj'} = eval { $parser->parse_data($content) };
337     if ( my $error = $@ || $parser->last_error ) {
338         $RT::Logger->error( "$error" );
339         return ( 0, $error );
340     }
341
342     # Unfold all headers
343     $self->{'MIMEObj'}->head->unfold;
344
345     return ( 1, $self->loc("Template parsed") );
346
347 }
348
349 # }}}
350
351 # {{{ sub _ParseContent
352
353 # Perform Template substitutions on the template
354
355 sub _ParseContent {
356     my $self = shift;
357     my %args = (
358         Argument       => undef,
359         TicketObj      => undef,
360         TransactionObj => undef,
361         @_
362     );
363
364     no warnings 'redefine';
365     local $T::Ticket      = $args{'TicketObj'};
366     local $T::Transaction = $args{'TransactionObj'};
367     local $T::Argument    = $args{'Argument'};
368     local $T::Requestor   = eval { $T::Ticket->Requestors->UserMembersObj->First->Name };
369     local $T::rtname      = $RT::rtname;
370     local *T::loc         = sub { $T::Ticket->loc(@_) };
371
372     my $content = $self->Content;
373     unless ( defined $content ) {
374         return ( undef, $self->loc("Permissions denied") );
375     }
376
377     # We need to untaint the content of the template, since we'll be working
378     # with it
379     $content =~ s/^(.*)$/$1/;
380     my $template = Text::Template->new(
381         TYPE   => 'STRING',
382         SOURCE => $content
383     );
384
385     my $is_broken = 0;
386     my $retval = $template->fill_in( PACKAGE => 'T', BROKEN => sub {
387         my (%args) = @_;
388         $RT::Logger->error("Template parsing error: $args{error}")
389             unless $args{error} =~ /^Died at /; # ignore intentional die()
390         $is_broken++;
391         return undef;
392     } );
393     return ( undef, $self->loc('Template parsing error') ) if $is_broken;
394
395     # MIME::Parser has problems dealing with high-bit utf8 data.
396     Encode::_utf8_off($retval);
397     return ($retval);
398 }
399
400 # }}}
401
402 # {{{ sub CurrentUserHasQueueRight
403
404 =head2 CurrentUserHasQueueRight
405
406 Helper function to call the template's queue's CurrentUserHasQueueRight with the passed in args.
407
408 =cut
409
410 sub CurrentUserHasQueueRight {
411     my $self = shift;
412     return ( $self->QueueObj->CurrentUserHasRight(@_) );
413 }
414
415 # }}}
416
417 1;