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