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