Presenter: Sub-Presenter auf Funktional geƤndert
[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 $ext = $options->{type} eq 'text' ? 'txt' : $options->{type};
49     $source = "templates/webpages/${template}.${ext}";
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     my $ref = ref $template;
65     return $template                  if $ref eq 'SL::Presenter::EscapedText';
66     return is_escaped(${ $template }) if $ref eq 'SCALAR';
67
68     # Otherwise return the file's content.
69     my $file    = IO::File->new($source, "r") || croak("Template file ${source} could not be read");
70     my $content = do { local $/ = ''; <$file> };
71     $file->close;
72
73     return is_escaped($content);
74   }
75
76   # Processing was requested. Set up all variables.
77   my %params = ( %locals,
78                  AUTH          => $::auth,
79                  FLASH         => $::form->{FLASH},
80                  FORM          => $::form,
81                  INSTANCE_CONF => $::instance_conf,
82                  LOCALE        => $::locale,
83                  LXCONFIG      => \%::lx_office_conf,
84                  LXDEBUG       => $::lxdebug,
85                  MYCONFIG      => \%::myconfig,
86                  PRESENTER     => $self,
87                );
88
89   my $output;
90   my $parser = $self->get_template;
91   $parser->process($source, \%params, \$output) || croak $parser->error;
92
93   return is_escaped($output);
94 }
95
96 sub get_template {
97   my ($self) = @_;
98
99   # Make locales.pl parse generic/exception.html, too:
100   # $::form->parse_html_template("generic/exception")
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                     ENCODING     => 'utf8',
112                   }) || croak;
113
114   return $self->{template};
115 }
116
117 1;
118
119 __END__
120
121 =head1 NAME
122
123 SL::Presenter - presentation layer class
124
125 =head1 SYNOPSIS
126
127   use SL::Presenter;
128   my $presenter = SL::Presenter->get;
129
130   # Lower-level template parsing:
131   my $html = $presenter->render(
132     'presenter/dir/template.html',
133     var1 => 'value',
134   );
135
136   # Higher-level rendering of certain objects:
137   use SL::DB::Customer;
138
139   my $linked_customer_name = $customer->presenter->customer(display => 'table-cell');
140
141   # Render a list of links to sales/purchase records:
142   use SL::DB::Order;
143   use SL::Presenter::Record qw(grouped_record_list);
144
145   my $quotation = SL::DB::Manager::Order->get_first(where => { quotation => 1 });
146   my $records   = $quotation->linked_records(direction => 'to');
147   my $html      = grouped_record_list($records);
148
149 =head1 CLASS FUNCTIONS
150
151 =over 4
152
153 =item C<get>
154
155 Returns the global presenter object and creates it if it doesn't exist
156 already.
157
158 =back
159
160 =head1 INSTANCE FUNCTIONS
161
162 =over 4
163
164 =item C<render $template, [ $options, ] %locals>
165
166 Renders the template C<$template>. Provides other variables than
167 C<Form::parse_html_template> does.
168
169 C<$options>, if present, must be a hash reference. All remaining
170 parameters are slurped into C<%locals>.
171
172 This is the backend function that L<SL::Controller::Base/render>
173 calls. The big difference is that the presenter's L<render> function
174 always returns the input and never sends anything to the browser while
175 the controller's function usually sends the result to the
176 controller. Therefore the presenter's L<render> function does not use
177 all of the parameters for controlling the output that the controller's
178 function does.
179
180 What is rendered and how C<$template> is interpreted is determined
181 both by C<$template>'s reference type and by the supplied options.
182
183 If C<$template> is a normal scalar (not a reference) then it is meant
184 to be a template file name relative to the C<templates/webpages>
185 directory. The file name to use is determined by the C<type> option.
186
187 If C<$template> is a reference to a scalar then the referenced
188 scalar's content is used as the content to process. The C<type> option
189 is not considered in this case.
190
191 C<$template> can also be an instance of L<SL::Presenter::EscapedText>
192 or a reference to such an instance. Both of these cases are handled
193 the same way as if C<$template> were a reference to a scalar: its
194 content is processed, and C<type> is not considered.
195
196 Other reference types, unknown options and unknown arguments to the
197 C<type> option cause the function to L<croak>.
198
199 The following options are available:
200
201 =over 2
202
203 =item C<type>
204
205 The template type. Can be C<html> (the default), C<js> for JavaScript,
206 C<json> for JSON and C<text> for plain text content. Affects only the
207 extension that's added to the file name given with a non-reference
208 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<FLASH> -- the flash instance (C<$::form-E<gt>{FLASH}>)
226
227 =item * C<FORM> -- C<$::form>
228
229 =item * C<INSTANCE_CONF> -- C<$::instance_conf>
230
231 =item * C<LOCALE> -- C<$::locale>
232
233 =item * C<LXCONFIG> -- all parameters from C<config/kivitendo.conf>
234 with the same name they appear in the file (first level is the
235 section, second the actual variable, e.g. C<system.language>,
236 C<features.webdav> etc)
237
238 =item * C<LXDEBUG> -- C<$::lxdebug>
239
240 =item * C<MYCONFIG> -- C<%::myconfig>
241
242 =item * C<SELF> -- the controller instance
243
244 =item * C<PRESENTER> -- the presenter instance the template is
245 rendered with
246
247 =item * All items from C<%locals>
248
249 =back
250
251 The function will always return the output and never send anything to
252 the browser.
253
254 Example: Render a HTML template with a certain title and a few locals
255
256   $presenter->render('todo/list',
257                      title      => 'List TODO items',
258                      TODO_ITEMS => SL::DB::Manager::Todo->get_all_sorted);
259
260 Example: Render a string and return its content for further processing
261 by the calling function.
262
263   my $content = $presenter->render(\'[% USE JavaScript %][% JavaScript.replace_with("#someid", "js/something") %]');
264
265 Example: Return the content of a JSON template file without processing
266 it at all:
267
268   my $template_content = $presenter->render(
269     'customer/contact',
270     { type => 'json', process => 0 }
271   );
272
273 =item C<get_template>
274
275 Returns the global instance of L<Template> and creates it if it
276 doesn't exist already.
277
278 =back
279
280 =head1 AUTHOR
281
282 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>
283
284 =cut