epic-s6ts
[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::EscapedText qw(is_escaped);
11
12 use Rose::Object::MakeMethods::Generic (
13   scalar => [ qw(need_reinit_widgets) ],
14 );
15
16 sub get {
17   return $::request->presenter;
18 }
19
20 sub render {
21   my $self               = shift;
22   my $template           = shift;
23   my ($options, %locals) = (@_ && ref($_[0])) ? @_ : ({ }, @_);
24
25   # Set defaults for all available options.
26   my %defaults = (
27     type       => 'html',
28     process    => 1,
29   );
30   $options->{$_} //= $defaults{$_} for keys %defaults;
31   $options->{type} = lc $options->{type};
32
33   # Check supplied options for validity.
34   foreach (keys %{ $options }) {
35     croak "Unsupported option: $_" unless $defaults{$_};
36   }
37
38   # Only certain types are supported.
39   croak "Unsupported type: " . $options->{type} unless $options->{type} =~ m/^(?:html|js|json|text)$/;
40
41   # The "template" argument must be a string or a reference to one.
42   $template = ${ $template }                                       if ((ref($template) || '') eq 'REF') && (ref(${ $template }) eq 'SL::Presenter::EscapedText');
43   croak "Unsupported 'template' reference type: " . ref($template) if ref($template) && (ref($template) !~ m/^(?:SCALAR|SL::Presenter::EscapedText)$/);
44
45   # Look for the file given by $template if $template is not a reference.
46   my $source;
47   if (!ref $template) {
48     my $webpages_path = $::request->layout->webpages_path;
49
50     my $ext = $options->{type} eq 'text' ? 'txt' : $options->{type};
51     $source = "${webpages_path}/${template}.${ext}";
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 is_escaped(${ $template }) 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 is_escaped($content);
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 is_escaped($output);
96 }
97
98 sub get_template {
99   my ($self) = @_;
100
101   my $webpages_path = $::request->layout->webpages_path;
102
103   # Make locales.pl parse generic/exception.html, too:
104   # $::form->parse_html_template("generic/exception")
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 => ".:$webpages_path",
112                     COMPILE_EXT  => '.tcc',
113                     COMPILE_DIR  => $::lx_office_conf{paths}->{userspath} . '/templates-cache',
114                     ERROR        => "${webpages_path}/generic/exception.html",
115                     ENCODING     => 'utf8',
116                   }) || croak;
117
118   return $self->{template};
119 }
120
121 1;
122
123 __END__
124
125 =head1 NAME
126
127 SL::Presenter - presentation layer class
128
129 =head1 SYNOPSIS
130
131   use SL::Presenter;
132   my $presenter = SL::Presenter->get;
133
134   # Lower-level template parsing:
135   my $html = $presenter->render(
136     'presenter/dir/template.html',
137     var1 => 'value',
138   );
139
140   # Higher-level rendering of certain objects:
141   use SL::DB::Customer;
142
143   my $linked_customer_name = $customer->presenter->customer(display => 'table-cell');
144
145   # Render a list of links to sales/purchase records:
146   use SL::DB::Order;
147   use SL::Presenter::Record qw(grouped_record_list);
148
149   my $quotation = SL::DB::Manager::Order->get_first(where => { quotation => 1 });
150   my $records   = $quotation->linked_records(direction => 'to');
151   my $html      = grouped_record_list($records);
152
153 =head1 CLASS FUNCTIONS
154
155 =over 4
156
157 =item C<get>
158
159 Returns the global presenter object and creates it if it doesn't exist
160 already.
161
162 =back
163
164 =head1 INSTANCE FUNCTIONS
165
166 =over 4
167
168 =item C<render $template, [ $options, ] %locals>
169
170 Renders the template C<$template>. Provides other variables than
171 C<Form::parse_html_template> does.
172
173 C<$options>, if present, must be a hash reference. All remaining
174 parameters are slurped into C<%locals>.
175
176 This is the backend function that L<SL::Controller::Base/render>
177 calls. The big difference is that the presenter's L<render> function
178 always returns the input and never sends anything to the browser while
179 the controller's function usually sends the result to the
180 controller. Therefore the presenter's L<render> function does not use
181 all of the parameters for controlling the output that the controller's
182 function does.
183
184 What is rendered and how C<$template> is interpreted is determined
185 both by C<$template>'s reference type and by the supplied options.
186
187 If C<$template> is a normal scalar (not a reference) then it is meant
188 to be a template file name relative to the C<templates/webpages>
189 directory. The file name to use is determined by the C<type> option.
190
191 If C<$template> is a reference to a scalar then the referenced
192 scalar's content is used as the content to process. The C<type> option
193 is not considered in this case.
194
195 C<$template> can also be an instance of L<SL::Presenter::EscapedText>
196 or a reference to such an instance. Both of these cases are handled
197 the same way as if C<$template> were a reference to a scalar: its
198 content is processed, and C<type> is not considered.
199
200 Other reference types, unknown options and unknown arguments to the
201 C<type> option cause the function to L<croak>.
202
203 The following options are available:
204
205 =over 2
206
207 =item C<type>
208
209 The template type. Can be C<html> (the default), C<js> for JavaScript,
210 C<json> for JSON and C<text> for plain text content. Affects only the
211 extension that's added to the file name given with a non-reference
212 C<$template> argument.
213
214 =item C<process>
215
216 If trueish (which is also the default) it causes the template/content
217 to be processed by the Template toolkit. Otherwise the
218 template/content is returned as-is.
219
220 =back
221
222 If template processing is requested then the template has access to
223 the following variables:
224
225 =over 2
226
227 =item * C<AUTH> -- C<$::auth>
228
229 =item * C<FLASH> -- the flash instance (C<$::form-E<gt>{FLASH}>)
230
231 =item * C<FORM> -- C<$::form>
232
233 =item * C<INSTANCE_CONF> -- C<$::instance_conf>
234
235 =item * C<LOCALE> -- C<$::locale>
236
237 =item * C<LXCONFIG> -- all parameters from C<config/kivitendo.conf>
238 with the same name they appear in the file (first level is the
239 section, second the actual variable, e.g. C<system.language>,
240 C<features.webdav> etc)
241
242 =item * C<LXDEBUG> -- C<$::lxdebug>
243
244 =item * C<MYCONFIG> -- C<%::myconfig>
245
246 =item * C<SELF> -- the controller instance
247
248 =item * C<PRESENTER> -- the presenter instance the template is
249 rendered with
250
251 =item * All items from C<%locals>
252
253 =back
254
255 The function will always return the output and never send anything to
256 the browser.
257
258 Example: Render a HTML template with a certain title and a few locals
259
260   $presenter->render('todo/list',
261                      title      => 'List TODO items',
262                      TODO_ITEMS => SL::DB::Manager::Todo->get_all_sorted);
263
264 Example: Render a string and return its content for further processing
265 by the calling function.
266
267   my $content = $presenter->render(\'[% USE JavaScript %][% JavaScript.replace_with("#someid", "js/something") %]');
268
269 Example: Return the content of a JSON template file without processing
270 it at all:
271
272   my $template_content = $presenter->render(
273     'customer/contact',
274     { type => 'json', process => 0 }
275   );
276
277 =item C<get_template>
278
279 Returns the global instance of L<Template> and creates it if it
280 doesn't exist already.
281
282 =back
283
284 =head1 AUTHOR
285
286 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>
287
288 =cut