Template-Toolkit-Konfiguration: Mitgeben, dass Templates in UTF-8 encodiert sind
[kivitendo-erp.git] / SL / Presenter.pm
1 package SL::Presenter;
2
3 use strict;
4
5 use parent qw(Rose::Object);
6
7 use Carp;
8 use Template;
9
10 use SL::Presenter::CustomerVendor;
11 use SL::Presenter::DeliveryOrder;
12 use SL::Presenter::EscapedText;
13 use SL::Presenter::Invoice;
14 use SL::Presenter::Order;
15 use SL::Presenter::Part;
16 use SL::Presenter::Project;
17 use SL::Presenter::Record;
18 use SL::Presenter::SepaExport;
19 use SL::Presenter::Text;
20 use SL::Presenter::Tag;
21
22 use Rose::Object::MakeMethods::Generic (
23   scalar => [ qw(need_reinit_widgets) ],
24 );
25
26 sub get {
27   return $::request->presenter;
28 }
29
30 sub render {
31   my $self               = shift;
32   my $template           = shift;
33   my ($options, %locals) = (@_ && ref($_[0])) ? @_ : ({ }, @_);
34
35   # Set defaults for all available options.
36   my %defaults = (
37     type       => 'html',
38     process    => 1,
39   );
40   $options->{$_} //= $defaults{$_} for keys %defaults;
41   $options->{type} = lc $options->{type};
42
43   # Check supplied options for validity.
44   foreach (keys %{ $options }) {
45     croak "Unsupported option: $_" unless $defaults{$_};
46   }
47
48   # Only certain types are supported.
49   croak "Unsupported type: " . $options->{type} unless $options->{type} =~ m/^(?:html|js|json|text)$/;
50
51   # The "template" argument must be a string or a reference to one.
52   $template = ${ $template }                                       if ((ref($template) || '') eq 'REF') && (ref(${ $template }) eq 'SL::Presenter::EscapedText');
53   croak "Unsupported 'template' reference type: " . ref($template) if ref($template) && (ref($template) !~ m/^(?:SCALAR|SL::Presenter::EscapedText)$/);
54
55   # Look for the file given by $template if $template is not a reference.
56   my $source;
57   if (!ref $template) {
58     my $ext = $options->{type} eq 'text' ? 'txt' : $options->{type};
59     $source = "templates/webpages/${template}.${ext}";
60     croak "Template file ${source} not found" unless -f $source;
61
62   } elsif (ref($template) eq 'SCALAR') {
63     # Normal scalar reference: hand over to Template
64     $source = $template;
65
66   } else {
67     # Instance of SL::Presenter::EscapedText. Get reference to its content.
68     $source = \$template->{text};
69   }
70
71   # If no processing is requested then return the content.
72   if (!$options->{process}) {
73     # If $template is a reference then don't try to read a file.
74     my $ref = ref $template;
75     return $template                                                                if $ref eq 'SL::Presenter::EscapedText';
76     return SL::Presenter::EscapedText->new(text => ${ $template }, is_escaped => 1) if $ref eq 'SCALAR';
77
78     # Otherwise return the file's content.
79     my $file    = IO::File->new($source, "r") || croak("Template file ${source} could not be read");
80     my $content = do { local $/ = ''; <$file> };
81     $file->close;
82
83     return SL::Presenter::EscapedText->new(text => $content, is_escaped => 1);
84   }
85
86   # Processing was requested. Set up all variables.
87   my %params = ( %locals,
88                  AUTH          => $::auth,
89                  FLASH         => $::form->{FLASH},
90                  FORM          => $::form,
91                  INSTANCE_CONF => $::instance_conf,
92                  LOCALE        => $::locale,
93                  LXCONFIG      => \%::lx_office_conf,
94                  LXDEBUG       => $::lxdebug,
95                  MYCONFIG      => \%::myconfig,
96                  PRESENTER     => $self,
97                );
98
99   my $output;
100   my $parser = $self->get_template;
101   $parser->process($source, \%params, \$output) || croak $parser->error;
102
103   return SL::Presenter::EscapedText->new(text => $output, is_escaped => 1);
104 }
105
106 sub get_template {
107   my ($self) = @_;
108
109   $self->{template} ||=
110     Template->new({ INTERPOLATE  => 0,
111                     EVAL_PERL    => 0,
112                     ABSOLUTE     => 1,
113                     CACHE_SIZE   => 0,
114                     PLUGIN_BASE  => 'SL::Template::Plugin',
115                     INCLUDE_PATH => '.:templates/webpages',
116                     COMPILE_EXT  => '.tcc',
117                     COMPILE_DIR  => $::lx_office_conf{paths}->{userspath} . '/templates-cache',
118                     ERROR        => 'templates/webpages/generic/exception.html',
119                     ENCODING     => 'utf8',
120                   }) || croak;
121
122   return $self->{template};
123 }
124
125 sub escape {
126   my ($self, $text) = @_;
127
128   return SL::Presenter::EscapedText->new(text => $text);
129 }
130
131 sub escaped_text {
132   my ($self, $text) = @_;
133
134   return SL::Presenter::EscapedText->new(text => $text, is_escaped => 1);
135 }
136
137 sub escape_js {
138   my ($self, $text) = @_;
139
140   $text =~ s|\\|\\\\|g;
141   $text =~ s|\"|\\\"|g;
142   $text =~ s|\n|\\n|g;
143
144   return SL::Presenter::EscapedText->new(text => $text, is_escaped => 1);
145 }
146
147 1;
148
149 __END__
150
151 =head1 NAME
152
153 SL::Presenter - presentation layer class
154
155 =head1 SYNOPSIS
156
157   use SL::Presenter;
158   my $presenter = SL::Presenter->get;
159
160   # Lower-level template parsing:
161   my $html = $presenter->render(
162     'presenter/dir/template.html',
163     var1 => 'value',
164   );
165
166   # Higher-level rendering of certain objects:
167   use SL::DB::Customer;
168
169   my $linked_customer_name = $presenter->customer($customer, display => 'table-cell');
170
171   # Render a list of links to sales/purchase records:
172   use SL::DB::Order;
173
174   my $quotation = SL::DB::Manager::Order->get_first(where => { quotation => 1 });
175   my $records   = $quotation->linked_records(direction => 'to');
176   my $html      = $presenter->grouped_record_list($records);
177
178 =head1 CLASS FUNCTIONS
179
180 =over 4
181
182 =item C<get>
183
184 Returns the global presenter object and creates it if it doesn't exist
185 already.
186
187 =back
188
189 =head1 INSTANCE FUNCTIONS
190
191 =over 4
192
193 =item C<render $template, [ $options, ] %locals>
194
195 Renders the template C<$template>. Provides other variables than
196 C<Form::parse_html_template> does.
197
198 C<$options>, if present, must be a hash reference. All remaining
199 parameters are slurped into C<%locals>.
200
201 This is the backend function that L<SL::Controller::Base/render>
202 calls. The big difference is that the presenter's L<render> function
203 always returns the input and never sends anything to the browser while
204 the controller's function usually sends the result to the
205 controller. Therefore the presenter's L<render> function does not use
206 all of the parameters for controlling the output that the controller's
207 function does.
208
209 What is rendered and how C<$template> is interpreted is determined
210 both by C<$template>'s reference type and by the supplied options.
211
212 If C<$template> is a normal scalar (not a reference) then it is meant
213 to be a template file name relative to the C<templates/webpages>
214 directory. The file name to use is determined by the C<type> option.
215
216 If C<$template> is a reference to a scalar then the referenced
217 scalar's content is used as the content to process. The C<type> option
218 is not considered in this case.
219
220 C<$template> can also be an instance of L<SL::Presenter::EscapedText>
221 or a reference to such an instance. Both of these cases are handled
222 the same way as if C<$template> were a reference to a scalar: its
223 content is processed, and C<type> is not considered.
224
225 Other reference types, unknown options and unknown arguments to the
226 C<type> option cause the function to L<croak>.
227
228 The following options are available:
229
230 =over 2
231
232 =item C<type>
233
234 The template type. Can be C<html> (the default), C<js> for JavaScript,
235 C<json> for JSON and C<text> for plain text content. Affects only the
236 extension that's added to the file name given with a non-reference
237 C<$template> argument.
238
239 =item C<process>
240
241 If trueish (which is also the default) it causes the template/content
242 to be processed by the Template toolkit. Otherwise the
243 template/content is returned as-is.
244
245 =back
246
247 If template processing is requested then the template has access to
248 the following variables:
249
250 =over 2
251
252 =item * C<AUTH> -- C<$::auth>
253
254 =item * C<FLASH> -- the flash instance (C<$::form-E<gt>{FLASH}>)
255
256 =item * C<FORM> -- C<$::form>
257
258 =item * C<INSTANCE_CONF> -- C<$::instance_conf>
259
260 =item * C<LOCALE> -- C<$::locale>
261
262 =item * C<LXCONFIG> -- all parameters from C<config/kivitendo.conf>
263 with the same name they appear in the file (first level is the
264 section, second the actual variable, e.g. C<system.language>,
265 C<features.webdav> etc)
266
267 =item * C<LXDEBUG> -- C<$::lxdebug>
268
269 =item * C<MYCONFIG> -- C<%::myconfig>
270
271 =item * C<SELF> -- the controller instance
272
273 =item * C<PRESENTER> -- the presenter instance the template is
274 rendered with
275
276 =item * All items from C<%locals>
277
278 =back
279
280 The function will always return the output and never send anything to
281 the browser.
282
283 Example: Render a HTML template with a certain title and a few locals
284
285   $presenter->render('todo/list',
286                      title      => 'List TODO items',
287                      TODO_ITEMS => SL::DB::Manager::Todo->get_all_sorted);
288
289 Example: Render a string and return its content for further processing
290 by the calling function.
291
292   my $content = $presenter->render(\'[% USE JavaScript %][% JavaScript.replace_with("#someid", "js/something") %]');
293
294 Example: Return the content of a JSON template file without processing
295 it at all:
296
297   my $template_content = $presenter->render(
298     'customer/contact',
299     { type => 'json', process => 0 }
300   );
301
302 =item C<escape $text>
303
304 Returns an HTML-escaped version of C<$text>. Instead of a string an
305 instance of the thin proxy-object L<SL::Presenter::EscapedText> is
306 returned.
307
308 It is safe to call C<escape> on an instance of
309 L<SL::Presenter::EscapedText>. This is a no-op (the same instance will
310 be returned).
311
312 =item C<escaped_text $text>
313
314 Returns an instance of L<SL::Presenter::EscapedText>. C<$text> is
315 assumed to be a string that has already been HTML-escaped.
316
317 It is safe to call C<escaped_text> on an instance of
318 L<SL::Presenter::EscapedText>. This is a no-op (the same instance will
319 be returned).
320
321 =item C<escape_js $text>
322
323 Returns a JavaScript-escaped version of C<$text>. Instead of a string
324 an instance of the thin proxy-object L<SL::Presenter::EscapedText> is
325 returned.
326
327 It is safe to call C<escape> on an instance of
328 L<SL::Presenter::EscapedText>. This is a no-op (the same instance will
329 be returned).
330
331 =item C<get_template>
332
333 Returns the global instance of L<Template> and creates it if it
334 doesn't exist already.
335
336 =back
337
338 =head1 AUTHOR
339
340 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>
341
342 =cut