285bfcee494a9a2ecea6ab5a95ba97ffd34287f9
[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
11 #
12 # public/helper functions
13 #
14
15 sub url_for {
16   my $self = shift;
17
18   return $_[0] if (scalar(@_) == 1) && !ref($_[0]);
19
20   my %params      = ref($_[0]) eq 'HASH' ? %{ $_[0] } : @_;
21   my $controller  = delete($params{controller}) || $self->_controller_name;
22   my $action      = delete($params{action})     || 'dispatch';
23   $params{action} = "${controller}/${action}";
24   my $query       = join('&', map { $::form->escape($_) . '=' . $::form->escape($params{$_}) } keys %params);
25
26   return "controller.pl?${query}";
27 }
28
29 sub redirect_to {
30   my $self = shift;
31   my $url  = $self->url_for(@_);
32
33   if ($self->delay_flash_on_redirect) {
34     require SL::Helper::Flash;
35     SL::Helper::Flash::delay_flash();
36   }
37
38   print $::request->{cgi}->redirect($url);
39 }
40
41 sub render {
42   my $self               = shift;
43   my $template           = shift;
44   my ($options, %locals) = (@_ && ref($_[0])) ? @_ : ({ }, @_);
45
46   $options->{type}       = lc($options->{type} || 'html');
47   $options->{no_layout}  = 1 if $options->{type} eq 'js';
48
49   my $source;
50   if ($options->{inline}) {
51     $source = \$template;
52
53   } elsif($options->{raw}) {
54     $source =  $template;
55
56   } else {
57     $source = "templates/webpages/${template}." . $options->{type};
58     croak "Template file ${source} not found" unless -f $source;
59   }
60
61   if (!$options->{partial} && !$options->{inline} && !$::form->{header}) {
62     if ($options->{no_layout}) {
63       $::form->{header} = 1;
64       my $content_type  = $options->{type} eq 'js' ? 'text/javascript' : 'text/html';
65
66       print $::form->create_http_response(content_type => $content_type,
67                                           charset      => $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET());
68
69     } else {
70       $::form->{title} = $locals{title} if $locals{title};
71       $::form->header;
72     }
73   }
74
75   my %params = ( %locals,
76                  AUTH          => $::auth,
77                  FLASH         => $::form->{FLASH},
78                  FORM          => $::form,
79                  INSTANCE_CONF => $::instance_conf,
80                  LOCALE        => $::locale,
81                  LXCONFIG      => \%::lx_office_conf,
82                  LXDEBUG       => $::lxdebug,
83                  MYCONFIG      => \%::myconfig,
84                  SELF          => $self,
85                );
86
87   my $output;
88   if (!$options->{raw}) {
89     my $parser = $self->_template_obj;
90     $parser->process($source, \%params, \$output) || croak $parser->error;
91   } else {
92     $output = $$source;
93   }
94
95   print $output unless $options->{inline} || $options->{no_output};
96
97   return $output;
98 }
99
100 sub send_file {
101   my ($self, $file_name, %params) = @_;
102
103   my $file            = IO::File->new($file_name, 'r') || croak("Cannot open file '${file_name}'");
104   my $content_type    =  $params{type} || 'application/octet_stream';
105   my $attachment_name =  $params{name} || $file_name;
106   $attachment_name    =~ s:.*//::g;
107
108   print $::form->create_http_response(content_type        => $content_type,
109                                       content_disposition => 'attachment; filename="' . $attachment_name . '"',
110                                       content_length      => -s $file);
111
112   $::locale->with_raw_io(\*STDOUT, sub { print while <$file> });
113   $file->close;
114 }
115
116 #
117 # Before/after run hooks
118 #
119
120 sub run_before {
121   _add_hook('before', @_);
122 }
123
124 sub run_after {
125   _add_hook('after', @_);
126 }
127
128 my %hooks;
129
130 sub _add_hook {
131   my ($when, $class, $sub, %params) = @_;
132
133   foreach my $key (qw(only except)) {
134     $params{$key} = { map { ( $_ => 1 ) } @{ $params{$key} } } if $params{$key};
135   }
136
137   my $idx = "${when}/${class}";
138   $hooks{$idx} ||= [ ];
139   push @{ $hooks{$idx} }, { %params, code => $sub };
140 }
141
142 sub _run_hooks {
143   my ($self, $when, $action) = @_;
144
145   my $idx = "${when}/" . ref($self);
146
147   foreach my $hook (@{ $hooks{$idx} || [] }) {
148     next if ($hook->{only  } && !$hook->{only  }->{$action})
149          || ($hook->{except} &&  $hook->{except}->{$action});
150
151     if (ref($hook->{code}) eq 'CODE') {
152       $hook->{code}->($self);
153     } else {
154       my $sub = $hook->{code};
155       $self->$sub;
156     }
157   }
158 }
159
160 #
161 #  behaviour. override these
162 #
163
164 sub delay_flash_on_redirect {
165   0;
166 }
167
168 #
169 # private functions -- for use in Base only
170 #
171
172 sub _run_action {
173   my $self   = shift;
174   my $action = shift;
175   my $sub    = "action_${action}";
176
177   return $self->_dispatch(@_) if $action eq 'dispatch';
178
179   $::form->error("Invalid action '${action}' for controller " . ref($self)) if !$self->can($sub);
180
181   $self->_run_hooks('before', $action);
182   $self->$sub(@_);
183   $self->_run_hooks('after', $action);
184 }
185
186 sub _controller_name {
187   return (split(/::/, ref($_[0])))[-1];
188 }
189
190 sub _dispatch {
191   my $self    = shift;
192
193   no strict 'refs';
194   my @actions = map { s/^action_//; $_ } grep { m/^action_/ } keys %{ ref($self) . "::" };
195   my $action  = first { $::form->{"action_${_}"} } @actions;
196   my $sub     = "action_${action}";
197
198   if ($self->can($sub)) {
199     $self->_run_hooks('before', $action);
200     $self->$sub(@_);
201     $self->_run_hooks('after', $action);
202   } else {
203     $::form->error($::locale->text('Oops. No valid action found to dispatch. Please report this case to the Lx-Office team.'));
204   }
205 }
206
207 sub _template_obj {
208   my ($self) = @_;
209
210   $self->{__basepriv_template_obj} ||=
211     Template->new({ INTERPOLATE  => 0,
212                     EVAL_PERL    => 0,
213                     ABSOLUTE     => 1,
214                     CACHE_SIZE   => 0,
215                     PLUGIN_BASE  => 'SL::Template::Plugin',
216                     INCLUDE_PATH => '.:templates/webpages',
217                     COMPILE_EXT  => '.tcc',
218                     COMPILE_DIR  => $::lx_office_conf{paths}->{userspath} . '/templates-cache',
219                   }) || croak;
220
221   return $self->{__basepriv_template_obj};
222 }
223
224 1;
225
226 __END__
227
228 =head1 NAME
229
230 SL::Controller::Base - base class for all action controllers
231
232 =head1 SYNOPSIS
233
234 =head2 OVERVIEW
235
236 This is a base class for all action controllers. Action controllers
237 provide subs that are callable by special URLs.
238
239 For each request made to the web server an instance of the controller
240 will be created. After the request has been served that instance will
241 handed over to garbage collection.
242
243 This base class is derived from L<Rose::Object>.
244
245 =head2 CONVENTIONS
246
247 The URLs have the following properties:
248
249 =over 2
250
251 =item *
252
253 The script part of the URL must be C<controller.pl>.
254
255 =item *
256
257 There must be a GET or POST parameter named C<action> containing the
258 name of the controller and the sub to call separated by C</>,
259 e.g. C<Message/list>.
260
261 =item *
262
263 The controller name is the package's name without the
264 C<SL::Controller::> prefix. At the moment only packages in the
265 C<SL::Controller> namespace are valid; sub-namespaces are not
266 allowed. The package name must start with an upper-case letter.
267
268 =item *
269
270 The sub part of the C<action> parameter is the name of the sub to
271 call. However, the sub's name is automatically prefixed with
272 C<action_>. Therefore for the example C<Message/list> the sub
273 C<SL::DB::Message::action_list> would be called. This in turn means
274 that subs whose name does not start with C<action_> cannot be invoked
275 directly via the URL.
276
277 =back
278
279 =head2 INDIRECT DISPATCHING
280
281 In the case that there are several submit buttons on a page it is
282 often impractical to have a single C<action> parameter match up
283 properly. For such a case a special dispatcher method is available. In
284 that case the C<action> parameter of the URL must be
285 C<Controller/dispatch>.
286
287 The C<SL::Controller::Base::_dispatch> method will iterate over all
288 subs in the controller package whose names start with C<action_>. The
289 first one for which there's a GET or POST parameter with the same name
290 and that's trueish is called.
291
292 Usage from a template usually looks like this:
293
294   <form method="POST" action="controller.pl">
295     ...
296     <input type="hidden" name="action" value="Message/dispatch">
297     <input type="submit" name="action_mark_as_read" value="Mark messages as read">
298     <input type="submit" name="action_delete" value="Delete messages">
299   </form>
300
301 The dispatching is handled by the function L</_dispatch>.
302
303 =head2 HOOKS
304
305 Hooks are functions that are called before or after the controller's
306 action is called. The controller package defines the hooks, and those
307 hooks themselves are run as instance methods.
308
309 Hooks are run in the order they're added.
310
311 The return value of the hooks is discarded.
312
313 Hooks can be defined to run for all actions, for only specific actions
314 or for all actions except a list of actions. Each entry is the action
315 name, not the sub's name. Therefore in order to run a hook before one
316 of the subs C<action_edit> or C<action_save> is called the following
317 code can be used:
318
319   __PACKAGE__->run_before('things_to_do_before_edit_and_save', only => [ 'edit', 'save' ]);
320
321 =head1 FUNCTIONS
322
323 =head2 PUBLIC HELPER FUNCTIONS
324
325 These functions are supposed to be called by sub-classed controllers.
326
327 =over 4
328
329 =item C<render $template, [ $options, ] %locals>
330
331 Renders the template C<$template>. Provides other variables than
332 C<Form::parse_html_template> does.
333
334 C<$options>, if present, must be a hash reference. All remaining
335 parameters are slurped into C<%locals>.
336
337 What is rendered and how C<$template> is interpreted is determined by
338 the options I<type>, I<inline>, I<partial> and I<no_layout>.
339
340 If C<< $options->{inline} >> is trueish then C<$template> is a string
341 containing the template code to interprete. Additionally the output
342 will not be sent to the browser. Instead it is only returned to the
343 caller.
344
345 If C<< $options->{raw} >> is trueish, the function will treat the input as
346 already parsed, and will not filter the input through Template. Unlike
347 C<inline>, the input is taked as a reference.
348
349 If C<< $options->{inline} >> is falsish then C<$template> is
350 interpreted as the name of a template file. It is prefixed with
351 "templates/webpages/" and postfixed with a file extension based on
352 C<< $options->{type} >>. C<< $options->{type} >> can be either C<html>
353 or C<js> and defaults to C<html>. An exception will be thrown if that
354 file does not exist.
355
356 If C<< $options->{partial} >> or C<< $options->{inline} >> is trueish
357 then neither the HTTP response header nor the standard HTML header is
358 generated.
359
360 Otherwise at least the HTTP response header will be generated based on
361 the template type (C<< $options->{type} >>).
362
363 If the template type is C<html> then the standard HTML header will be
364 output via C<< $::form->header >> with C<< $::form->{title} >> set to
365 C<$locals{title}> (the latter only if C<$locals{title}> is
366 trueish). Setting C<< $options->{no_layout} >> to trueish will prevent
367 this.
368
369 The template itself has access to the following variables:
370
371 =over 2
372
373 =item * C<AUTH> -- C<$::auth>
374
375 =item * C<FORM> -- C<$::form>
376
377 =item * C<LOCALE> -- C<$::locale>
378
379 =item * C<LXCONFIG> -- all parameters from C<config/lx_office.conf>
380 with the same name they appear in the file (first level is the
381 section, second the actual variable, e.g. C<system.dbcharset>,
382 C<features.webdav> etc)
383
384 =item * C<LXDEBUG> -- C<$::lxdebug>
385
386 =item * C<MYCONFIG> -- C<%::myconfig>
387
388 =item * C<SELF> -- the controller instance
389
390 =item * All items from C<%locals>
391
392 =back
393
394 Unless C<< $options->{inline} >> is trueish the function will send the
395 output to the browser.
396
397 The function will always return the output.
398
399 Example: Render a HTML template with a certain title and a few locals
400
401   $self->render('todo/list',
402                 title      => 'List TODO items',
403                 TODO_ITEMS => SL::DB::Manager::Todo->get_all_sorted);
404
405 Example: Render a string and return its content for further processing
406 by the calling function. No header is generated due to C<inline>.
407
408   my $content = $self->render('[% USE JavaScript %][% JavaScript.replace_with("#someid", "js/something") %]',
409                               { type => 'js', inline => 1 });
410
411 Example: Render a JavaScript template and send it to the
412 browser. Typical use for actions called via AJAX:
413
414   $self->render('todo/single_item', { type => 'js' },
415                 item => $employee->most_important_todo_item);
416
417 =item C<send_file $file_name, [%params]>
418
419 Sends the file C<$file_name> to the browser including appropriate HTTP
420 headers for a download. C<%params> can include the following:
421
422 =over 2
423
424 =item * C<type> -- the file's content type; defaults to
425 'application/octet_stream'
426
427 =item * C<name> -- the name presented to the browser; defaults to
428 C<$file_name>
429
430 =back
431
432 =item C<url_for $url>
433
434 =item C<url_for $params>
435
436 =item C<url_for %params>
437
438 Creates an URL for the given parameters suitable for calling an action
439 controller. If there's only one scalar parameter then it is returned
440 verbatim.
441
442 Otherwise the parameters are given either as a single hash ref
443 parameter or as a normal hash.
444
445 The controller to call is given by C<$params{controller}>. It defaults
446 to the current controller as returned by
447 L</_controller_name>.
448
449 The action to call is given by C<$params{action}>. It defaults to
450 C<dispatch>.
451
452 All other key/value pairs in C<%params> are appended as GET parameters
453 to the URL.
454
455 Usage from a template might look like this:
456
457   <a href="[% SELF.url_for(controller => 'Message', action => 'new', recipient_id => 42) %]">create new message</a>
458
459 =item C<redirect_to %url_params>
460
461 Redirects the browser to a new URL by outputting a HTTP redirect
462 header. The URL is generated by calling L</url_for> with
463 C<%url_params>.
464
465 =item C<run_before $sub, %params>
466
467 =item C<run_after $sub, %params>
468
469 Adds a hook to run before or after certain actions are run for the
470 current package. The code to run is C<$sub> which is either the name
471 of an instance method or a code reference. If it's the latter then the
472 first parameter will be C<$self>.
473
474 C<%params> can contain two possible values that restrict the code to
475 be run only for certain actions:
476
477 =over 2
478
479 =item C<< only => \@list >>
480
481 Only run the code for actions given in C<@list>. The entries are the
482 action names, not the names of the sub (so it's C<list> instead of
483 C<action_list>).
484
485 =item C<< except => \@list >>
486
487 Run the code for all actions but for those given in C<@list>. The
488 entries are the action names, not the names of the sub (so it's
489 C<list> instead of C<action_list>).
490
491 =back
492
493 If neither restriction is used then the code will be run for any
494 action.
495
496 The hook's return values are discarded.
497
498 =item delay_flash_on_redirect
499
500 May be overridden by a controller. If this method returns true, redirect_to
501 will delay all flash messages for the current request. Defaults to false for
502 compatibility reasons.
503
504 =back
505
506 =head2 PRIVATE FUNCTIONS
507
508 These functions are supposed to be used from this base class only.
509
510 =over 4
511
512 =item C<_controller_name>
513
514 Returns the name of the curernt controller package without the
515 C<SL::Controller::> prefix.
516
517 =item C<_dispatch>
518
519 Implements the method lookup for indirect dispatching mentioned in the
520 section L</INDIRECT DISPATCHING>.
521
522 =item C<_run_action $action>
523
524 Executes a sub based on the value of C<$action>. C<$action> is the sub
525 name part of the C<action> GET or POST parameter as described in
526 L</CONVENTIONS>.
527
528 If C<$action> equals C<dispatch> then the sub L</_dispatch> in this
529 base class is called for L</INDIRECT DISPATCHING>. Otherwise
530 C<$action> is prefixed with C<action_>, and that sub is called on the
531 current controller instance.
532
533 =back
534
535 =head1 AUTHOR
536
537 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>
538
539 =cut