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