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