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