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