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