SL::{Controller,Presenter}->render: $template kann auch ref auf Instanz von EscapedTe...
[kivitendo-erp.git] / SL / Controller / Base.pm
1 package SL::Controller::Base;
2
3 use strict;
4
5 use parent qw(Rose::Object);
6
7 use Carp;
8 use IO::File;
9 use List::Util qw(first);
10 use SL::Request qw(flatten);
11 use SL::MoreCommon qw(uri_encode);
12 use SL::Presenter;
13
14 use Rose::Object::MakeMethods::Generic
15 (
16   scalar => [ qw(action_name) ],
17 );
18
19 #
20 # public/helper functions
21 #
22
23 sub url_for {
24   my $self = shift;
25
26   return $_[0] if (scalar(@_) == 1) && !ref($_[0]);
27
28   my %params      = ref($_[0]) eq 'HASH' ? %{ $_[0] } : @_;
29   my $controller  = delete($params{controller}) || $self->controller_name;
30   my $action      = $params{action}             || 'dispatch';
31
32   my $script;
33   if ($controller =~ m/\.pl$/) {
34     # Old-style controller
35     $script = $controller;
36   } else {
37     $params{action} = "${controller}/${action}";
38     $script         = "controller.pl";
39   }
40
41   my $query       = join '&', map { uri_encode($_->[0]) . '=' . uri_encode($_->[1]) } @{ flatten(\%params) };
42
43   return "${script}?${query}";
44 }
45
46 sub redirect_to {
47   my $self = shift;
48   my $url  = $self->url_for(@_);
49
50   if ($self->delay_flash_on_redirect) {
51     require SL::Helper::Flash;
52     SL::Helper::Flash::delay_flash();
53   }
54
55   print $::request->{cgi}->redirect($url);
56 }
57
58 sub render {
59   my $self               = shift;
60   my $template           = shift;
61   my ($options, %locals) = (@_ && ref($_[0])) ? @_ : ({ }, @_);
62
63   # Set defaults for all available options.
64   my %defaults = (
65     type       => 'html',
66     output     => 1,
67     header     => 1,
68     layout     => 1,
69     process    => 1,
70   );
71   $options->{$_} //= $defaults{$_} for keys %defaults;
72   $options->{type} = lc $options->{type};
73
74   # Check supplied options for validity.
75   foreach (keys %{ $options }) {
76     croak "Unsupported option: $_" unless $defaults{$_};
77   }
78
79   # Only certain types are supported.
80   croak "Unsupported type: " . $options->{type} unless $options->{type} =~ m/^(?:html|js|json)$/;
81
82   # The "template" argument must be a string or a reference to one.
83   $template = ${ $template }                                       if ((ref($template) || '') eq 'REF') && (ref(${ $template }) eq 'SL::Presenter::EscapedText');
84   croak "Unsupported 'template' reference type: " . ref($template) if ref($template) && (ref($template) !~ m/^(?:SCALAR|SL::Presenter::EscapedText)$/);
85
86   # If all output is turned off then don't output the header either.
87   if (!$options->{output}) {
88     $options->{header} = 0;
89     $options->{layout} = 0;
90
91   } else {
92     # Layout only makes sense if we're outputting HTML.
93     $options->{layout} = 0 if $options->{type} ne 'html';
94   }
95
96   if ($options->{header}) {
97     # Output the HTTP response and the layout in case of HTML output.
98
99     if ($options->{layout}) {
100       $::form->{title} = $locals{title} if $locals{title};
101       $::form->header;
102
103     } else {
104       # No layout: just the standard HTTP response. Also notify
105       # $::form that the header has already been output so that
106       # $::form->header() won't output it again.
107       $::form->{header} = 1;
108       my $content_type  = $options->{type} eq 'html' ? 'text/html'
109                         : $options->{type} eq 'js'   ? 'text/javascript'
110                         :                              'application/json';
111
112       print $::form->create_http_response(content_type => $content_type,
113                                           charset      => $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET());
114     }
115   }
116
117   # Let the presenter do the rest of the work.
118   my $output = $self->presenter->render(
119     $template,
120     { type => $options->{type}, process => $options->{process} },
121     %locals,
122     SELF => $self,
123   );
124
125   # Print the output if wanted.
126   print $output if $options->{output};
127
128   return $output;
129 }
130
131 sub send_file {
132   my ($self, $file_name, %params) = @_;
133
134   my $file            = IO::File->new($file_name, 'r') || croak("Cannot open file '${file_name}'");
135   my $content_type    =  $params{type} || 'application/octet_stream';
136   my $attachment_name =  $params{name} || $file_name;
137   $attachment_name    =~ s:.*//::g;
138
139   print $::form->create_http_response(content_type        => $content_type,
140                                       content_disposition => 'attachment; filename="' . $attachment_name . '"',
141                                       content_length      => -s $file);
142
143   $::locale->with_raw_io(\*STDOUT, sub { print while <$file> });
144   $file->close;
145 }
146
147 sub presenter {
148   return SL::Presenter->get;
149 }
150
151 sub controller_name {
152   my $class = ref($_[0]) || $_[0];
153   $class    =~ s/^SL::Controller:://;
154   return $class;
155 }
156
157 #
158 # Before/after run hooks
159 #
160
161 sub run_before {
162   _add_hook('before', @_);
163 }
164
165 sub run_after {
166   _add_hook('after', @_);
167 }
168
169 my %hooks;
170
171 sub _add_hook {
172   my ($when, $class, $sub, %params) = @_;
173
174   foreach my $key (qw(only except)) {
175     $params{$key} = { map { ( $_ => 1 ) } @{ $params{$key} } } if $params{$key};
176   }
177
178   my $idx = "${when}/${class}";
179   $hooks{$idx} ||= [ ];
180   push @{ $hooks{$idx} }, { %params, code => $sub };
181 }
182
183 sub _run_hooks {
184   my ($self, $when, $action) = @_;
185
186   my $idx = "${when}/" . ref($self);
187
188   foreach my $hook (@{ $hooks{$idx} || [] }) {
189     next if ($hook->{only  } && !$hook->{only  }->{$action})
190          || ($hook->{except} &&  $hook->{except}->{$action});
191
192     if (ref($hook->{code}) eq 'CODE') {
193       $hook->{code}->($self, $action);
194     } else {
195       my $sub = $hook->{code};
196       $self->$sub($action);
197     }
198   }
199 }
200
201 #
202 #  behaviour. override these
203 #
204
205 sub delay_flash_on_redirect {
206   0;
207 }
208
209 sub get_auth_level {
210   # Ignore the 'action' parameter.
211   return 'user';
212 }
213
214 sub keep_auth_vars_in_form {
215   return 0;
216 }
217
218 #
219 # private functions -- for use in Base only
220 #
221
222 sub _run_action {
223   my $self   = shift;
224   my $action = shift;
225   my $sub    = "action_${action}";
226
227   return $self->_dispatch(@_) if $action eq 'dispatch';
228
229   $::form->error("Invalid action '${action}' for controller " . ref($self)) if !$self->can($sub);
230
231   $self->action_name($action);
232   $self->_run_hooks('before', $action);
233   $self->$sub(@_);
234   $self->_run_hooks('after', $action);
235 }
236
237 sub _dispatch {
238   my $self    = shift;
239
240   no strict 'refs';
241   my @actions = map { s/^action_//; $_ } grep { m/^action_/ } keys %{ ref($self) . "::" };
242   my $action  = first { $::form->{"action_${_}"} } @actions;
243   my $sub     = "action_${action}";
244
245   if ($self->can($sub)) {
246     $self->action_name($action);
247     $self->_run_hooks('before', $action);
248     $self->$sub(@_);
249     $self->_run_hooks('after', $action);
250   } else {
251     $::form->error($::locale->text('Oops. No valid action found to dispatch. Please report this case to the kivitendo team.'));
252   }
253 }
254
255 1;
256
257 __END__
258
259 =head1 NAME
260
261 SL::Controller::Base - base class for all action controllers
262
263 =head1 SYNOPSIS
264
265 =head2 OVERVIEW
266
267 This is a base class for all action controllers. Action controllers
268 provide subs that are callable by special URLs.
269
270 For each request made to the web server an instance of the controller
271 will be created. After the request has been served that instance will
272 handed over to garbage collection.
273
274 This base class is derived from L<Rose::Object>.
275
276 =head2 CONVENTIONS
277
278 The URLs have the following properties:
279
280 =over 2
281
282 =item *
283
284 The script part of the URL must be C<controller.pl>.
285
286 =item *
287
288 There must be a GET or POST parameter named C<action> containing the
289 name of the controller and the sub to call separated by C</>,
290 e.g. C<Message/list>.
291
292 =item *
293
294 The controller name is the package's name without the
295 C<SL::Controller::> prefix. At the moment only packages in the
296 C<SL::Controller> namespace are valid; sub-namespaces are not
297 allowed. The package name must start with an upper-case letter.
298
299 =item *
300
301 The sub part of the C<action> parameter is the name of the sub to
302 call. However, the sub's name is automatically prefixed with
303 C<action_>. Therefore for the example C<Message/list> the sub
304 C<SL::DB::Message::action_list> would be called. This in turn means
305 that subs whose name does not start with C<action_> cannot be invoked
306 directly via the URL.
307
308 =back
309
310 =head2 INDIRECT DISPATCHING
311
312 In the case that there are several submit buttons on a page it is
313 often impractical to have a single C<action> parameter match up
314 properly. For such a case a special dispatcher method is available. In
315 that case the C<action> parameter of the URL must be
316 C<Controller/dispatch>.
317
318 The C<SL::Controller::Base::_dispatch> method will iterate over all
319 subs in the controller package whose names start with C<action_>. The
320 first one for which there's a GET or POST parameter with the same name
321 and that's trueish is called.
322
323 Usage from a template usually looks like this:
324
325   <form method="POST" action="controller.pl">
326     ...
327     <input type="hidden" name="action" value="Message/dispatch">
328     <input type="submit" name="action_mark_as_read" value="Mark messages as read">
329     <input type="submit" name="action_delete" value="Delete messages">
330   </form>
331
332 The dispatching is handled by the function L</_dispatch>.
333
334 =head2 HOOKS
335
336 Hooks are functions that are called before or after the controller's
337 action is called. The controller package defines the hooks, and those
338 hooks themselves are run as instance methods.
339
340 Hooks are run in the order they're added.
341
342 The hooks receive a single parameter: the name of the action that is
343 about to be called (for C<before> hooks) / was called (for C<after>
344 hooks).
345
346 The return value of the hooks is discarded.
347
348 Hooks can be defined to run for all actions, for only specific actions
349 or for all actions except a list of actions. Each entry is the action
350 name, not the sub's name. Therefore in order to run a hook before one
351 of the subs C<action_edit> or C<action_save> is called the following
352 code can be used:
353
354   __PACKAGE__->run_before('things_to_do_before_edit_and_save', only => [ 'edit', 'save' ]);
355
356 =head1 FUNCTIONS
357
358 =head2 PUBLIC HELPER FUNCTIONS
359
360 These functions are supposed to be called by sub-classed controllers.
361
362 =over 4
363
364 =item C<render $template, [ $options, ] %locals>
365
366 Renders the template C<$template>. Provides other variables than
367 C<Form::parse_html_template> does.
368
369 C<$options>, if present, must be a hash reference. All remaining
370 parameters are slurped into C<%locals>.
371
372 What is rendered and how C<$template> is interpreted is determined
373 both by C<$template>'s reference type and by the supplied options. The
374 actual rendering is handled by L<SL::Presenter/render>.
375
376 If C<$template> is a normal scalar (not a reference) then it is meant
377 to be a template file name relative to the C<templates/webpages>
378 directory. The file name to use is determined by the C<type> option.
379
380 If C<$template> is a reference to a scalar then the referenced
381 scalar's content is used as the content to process. The C<type> option
382 is not considered in this case.
383
384 Other reference types, unknown options and unknown arguments to the
385 C<type> option cause the function to L<croak>.
386
387 The following options are available (defaults: C<type> = 'html',
388 C<process> = 1, C<output> = 1, C<header> = 1, C<layout> = 1):
389
390 =over 2
391
392 =item C<type>
393
394 The template type. Can be C<html> (the default), C<js> for JavaScript
395 or C<json> for JSON content. Affects the extension that's added to the
396 file name given with a non-reference C<$template> argument, the
397 content type HTTP header that is output and whether or not the layout
398 will be output as well (see description of C<layout> below).
399
400 =item C<process>
401
402 If trueish (which is also the default) it causes the template/content
403 to be processed by the Template toolkit. Otherwise the
404 template/content is output as-is.
405
406 =item C<output>
407
408 If trueish (the default) then the generated output will be sent to the
409 browser in addition to being returned. If falsish then the options
410 C<header> and C<layout> are set to 0 as well.
411
412 =item C<header>
413
414 Determines whether or not to output the HTTP response
415 headers. Defaults to the same value that C<output> is set to. If set
416 to falsish then the layout is not output either.
417
418 =item C<layout>
419
420 Determines whether or not the basic HTML layout structure should be
421 output (HTML header, common JavaScript and stylesheet inclusions, menu
422 etc.). Defaults to 0 if C<type> is not C<html> and to the same value
423 C<header> is set to otherwise.
424
425 =back
426
427 The template itself has access to several variables. These are listed
428 in the documentation to L<SL::Presenter/render>.
429
430 The function will always return the output.
431
432 Example: Render a HTML template with a certain title and a few locals
433
434   $self->render('todo/list',
435                 title      => 'List TODO items',
436                 TODO_ITEMS => SL::DB::Manager::Todo->get_all_sorted);
437
438 Example: Render a string and return its content for further processing
439 by the calling function. No header is generated due to C<output>.
440
441   my $content = $self->render(\'[% USE JavaScript %][% JavaScript.replace_with("#someid", "js/something") %]',
442                               { output => 0 });
443
444 Example: Render a JavaScript template
445 "templates/webpages/todo/single_item.js" and send it to the
446 browser. Typical use for actions called via AJAX:
447
448   $self->render('todo/single_item', { type => 'js' },
449                 item => $employee->most_important_todo_item);
450
451 =item C<send_file $file_name, [%params]>
452
453 Sends the file C<$file_name> to the browser including appropriate HTTP
454 headers for a download. C<%params> can include the following:
455
456 =over 2
457
458 =item * C<type> -- the file's content type; defaults to
459 'application/octet_stream'
460
461 =item * C<name> -- the name presented to the browser; defaults to
462 C<$file_name>
463
464 =back
465
466 =item C<url_for $url>
467
468 =item C<url_for $params>
469
470 =item C<url_for %params>
471
472 Creates an URL for the given parameters suitable for calling an action
473 controller. If there's only one scalar parameter then it is returned
474 verbatim.
475
476 Otherwise the parameters are given either as a single hash ref
477 parameter or as a normal hash.
478
479 The controller to call is given by C<$params{controller}>. It defaults
480 to the current controller as returned by
481 L</controller_name>.
482
483 The action to call is given by C<$params{action}>. It defaults to
484 C<dispatch>.
485
486 All other key/value pairs in C<%params> are appended as GET parameters
487 to the URL.
488
489 Usage from a template might look like this:
490
491   <a href="[% SELF.url_for(controller => 'Message', action => 'new', recipient_id => 42) %]">create new message</a>
492
493 =item C<redirect_to %url_params>
494
495 Redirects the browser to a new URL by outputting a HTTP redirect
496 header. The URL is generated by calling L</url_for> with
497 C<%url_params>.
498
499 =item C<run_before $sub, %params>
500
501 =item C<run_after $sub, %params>
502
503 Adds a hook to run before or after certain actions are run for the
504 current package. The code to run is C<$sub> which is either the name
505 of an instance method or a code reference. If it's the latter then the
506 first parameter will be C<$self>.
507
508 C<%params> can contain two possible values that restrict the code to
509 be run only for certain actions:
510
511 =over 2
512
513 =item C<< only => \@list >>
514
515 Only run the code for actions given in C<@list>. The entries are the
516 action names, not the names of the sub (so it's C<list> instead of
517 C<action_list>).
518
519 =item C<< except => \@list >>
520
521 Run the code for all actions but for those given in C<@list>. The
522 entries are the action names, not the names of the sub (so it's
523 C<list> instead of C<action_list>).
524
525 =back
526
527 If neither restriction is used then the code will be run for any
528 action.
529
530 The hook's return values are discarded.
531
532 =item C<delay_flash_on_redirect>
533
534 May be overridden by a controller. If this method returns true, redirect_to
535 will delay all flash messages for the current request. Defaults to false for
536 compatibility reasons.
537
538 =item C<get_auth_level $action>
539
540 May be overridden by a controller. Determines what kind of
541 authentication is required for a particular action. Must return either
542 C<admin> (which means that authentication as an admin is required),
543 C<user> (authentication as a normal user suffices) with a possible
544 future value C<none> (which would require no authentication but is not
545 yet implemented).
546
547 =item C<keep_auth_vars_in_form>
548
549 May be overridden by a controller. If falsish (the default) all form
550 variables whose name starts with C<{AUTH}> are removed before the
551 request is routed. Only controllers that handle login requests
552 themselves should return trueish for this function.
553
554 =item C<controller_name>
555
556 Returns the name of the curernt controller package without the
557 C<SL::Controller::> prefix. This method can be called both as a class
558 method and an instance method.
559
560 =item C<action_name>
561
562 Returns the name of the currently executing action. If the dispatcher
563 mechanism was used then this is not C<dispatch> but the actual method
564 name the dispatching resolved to.
565
566 =item C<presenter>
567
568 Returns the global presenter object by calling
569 L<SL::Presenter/get>.
570
571 =back
572
573 =head2 PRIVATE FUNCTIONS
574
575 These functions are supposed to be used from this base class only.
576
577 =over 4
578
579 =item C<_dispatch>
580
581 Implements the method lookup for indirect dispatching mentioned in the
582 section L</INDIRECT DISPATCHING>.
583
584 =item C<_run_action $action>
585
586 Executes a sub based on the value of C<$action>. C<$action> is the sub
587 name part of the C<action> GET or POST parameter as described in
588 L</CONVENTIONS>.
589
590 If C<$action> equals C<dispatch> then the sub L</_dispatch> in this
591 base class is called for L</INDIRECT DISPATCHING>. Otherwise
592 C<$action> is prefixed with C<action_>, and that sub is called on the
593 current controller instance.
594
595 =back
596
597 =head1 AUTHOR
598
599 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>
600
601 =cut