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