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