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