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