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