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