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