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