1 package SL::Controller::Base;
 
   5 use parent qw(Rose::Object);
 
   9 use List::Util qw(first);
 
  10 use SL::Request qw(flatten);
 
  11 use SL::MoreCommon qw(uri_encode);
 
  14 use Rose::Object::MakeMethods::Generic
 
  16   scalar => [ qw(action_name) ],
 
  20 # public/helper functions
 
  26   return $_[0] if (scalar(@_) == 1) && !ref($_[0]);
 
  28   my %params      = ref($_[0]) eq 'HASH' ? %{ $_[0] } : @_;
 
  29   my $controller  = delete($params{controller}) || $self->controller_name;
 
  30   my $action      = $params{action}             || 'dispatch';
 
  33   if ($controller =~ m/\.pl$/) {
 
  34     # Old-style controller
 
  35     $script = $controller;
 
  37     $params{action} = "${controller}/${action}";
 
  38     $script         = "controller.pl";
 
  41   my $query       = join '&', map { uri_encode($_->[0]) . '=' . uri_encode($_->[1]) } @{ flatten(\%params) };
 
  43   return "${script}?${query}";
 
  48   my $url  = $self->url_for(@_);
 
  50   if ($self->delay_flash_on_redirect) {
 
  51     require SL::Helper::Flash;
 
  52     SL::Helper::Flash::delay_flash();
 
  55   return $self->render(SL::ClientJS->new->redirect_to($self->url_for(@_))) if $::request->is_ajax;
 
  57   print $::request->{cgi}->redirect($url);
 
  63   my ($options, %locals) = (@_ && ref($_[0])) ? @_ : ({ }, @_);
 
  65   # Special handling/shortcut for an instance of SL::ClientJS:
 
  66   return $self->render(\$template->to_json, { type => 'json' }) if ref($template) eq 'SL::ClientJS';
 
  68   # Set defaults for all available options.
 
  76   $options->{$_} //= $defaults{$_} for keys %defaults;
 
  77   $options->{type} = lc $options->{type};
 
  79   # Check supplied options for validity.
 
  80   foreach (keys %{ $options }) {
 
  81     croak "Unsupported option: $_" unless $defaults{$_};
 
  84   # Only certain types are supported.
 
  85   croak "Unsupported type: " . $options->{type} unless $options->{type} =~ m/^(?:html|js|json)$/;
 
  87   # The "template" argument must be a string or a reference to one.
 
  88   $template = ${ $template }                                       if ((ref($template) || '') eq 'REF') && (ref(${ $template }) eq 'SL::Presenter::EscapedText');
 
  89   croak "Unsupported 'template' reference type: " . ref($template) if ref($template) && (ref($template) !~ m/^(?:SCALAR|SL::Presenter::EscapedText)$/);
 
  91   # If all output is turned off then don't output the header either.
 
  92   if (!$options->{output}) {
 
  93     $options->{header} = 0;
 
  94     $options->{layout} = 0;
 
  97     # Layout only makes sense if we're outputting HTML.
 
  98     $options->{layout} = 0 if $options->{type} ne 'html';
 
 101   if ($options->{header}) {
 
 102     # Output the HTTP response and the layout in case of HTML output.
 
 104     if ($options->{layout}) {
 
 105       $::form->{title} = $locals{title} if $locals{title};
 
 109       # No layout: just the standard HTTP response. Also notify
 
 110       # $::form that the header has already been output so that
 
 111       # $::form->header() won't output it again.
 
 112       $::form->{header} = 1;
 
 113       my $content_type  = $options->{type} eq 'html' ? 'text/html'
 
 114                         : $options->{type} eq 'js'   ? 'text/javascript'
 
 115                         :                              'application/json';
 
 117       print $::form->create_http_response(content_type => $content_type,
 
 118                                           charset      => $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET());
 
 122   # Let the presenter do the rest of the work.
 
 123   my $output = $self->presenter->render(
 
 125     { type => $options->{type}, process => $options->{process} },
 
 130   # Print the output if wanted.
 
 131   print $output if $options->{output};
 
 137   my ($self, $file_name, %params) = @_;
 
 139   my $file            = IO::File->new($file_name, 'r') || croak("Cannot open file '${file_name}'");
 
 140   my $content_type    =  $params{type} || 'application/octet_stream';
 
 141   my $attachment_name =  $params{name} || $file_name;
 
 142   $attachment_name    =~ s:.*//::g;
 
 144   print $::form->create_http_response(content_type        => $content_type,
 
 145                                       content_disposition => 'attachment; filename="' . $attachment_name . '"',
 
 146                                       content_length      => -s $file);
 
 148   $::locale->with_raw_io(\*STDOUT, sub { print while <$file> });
 
 153   return SL::Presenter->get;
 
 156 sub controller_name {
 
 157   my $class = ref($_[0]) || $_[0];
 
 158   $class    =~ s/^SL::Controller:://;
 
 163 # Before/after run hooks
 
 167   _add_hook('before', @_);
 
 171   _add_hook('after', @_);
 
 177   my ($when, $class, $sub, %params) = @_;
 
 179   foreach my $key (qw(only except)) {
 
 180     $params{$key} = { map { ( $_ => 1 ) } @{ $params{$key} } } if $params{$key};
 
 183   my $idx = "${when}/${class}";
 
 184   $hooks{$idx} ||= [ ];
 
 185   push @{ $hooks{$idx} }, { %params, code => $sub };
 
 189   my ($self, $when, $action) = @_;
 
 191   my $idx = "${when}/" . ref($self);
 
 193   foreach my $hook (@{ $hooks{$idx} || [] }) {
 
 194     next if ($hook->{only  } && !$hook->{only  }->{$action})
 
 195          || ($hook->{except} &&  $hook->{except}->{$action});
 
 197     if (ref($hook->{code}) eq 'CODE') {
 
 198       $hook->{code}->($self, $action);
 
 200       my $sub = $hook->{code};
 
 201       $self->$sub($action);
 
 207 #  behaviour. override these
 
 210 sub delay_flash_on_redirect {
 
 215   # Ignore the 'action' parameter.
 
 219 sub keep_auth_vars_in_form {
 
 224 # private functions -- for use in Base only
 
 230   my $sub    = "action_${action}";
 
 232   return $self->_dispatch(@_) if $action eq 'dispatch';
 
 234   $::form->error("Invalid action '${action}' for controller " . ref($self)) if !$self->can($sub);
 
 236   $self->action_name($action);
 
 237   $self->_run_hooks('before', $action);
 
 239   $self->_run_hooks('after', $action);
 
 246   my @actions = map { s/^action_//; $_ } grep { m/^action_/ } keys %{ ref($self) . "::" };
 
 247   my $action  = first { $::form->{"action_${_}"} } @actions;
 
 248   my $sub     = "action_${action}";
 
 250   if ($self->can($sub)) {
 
 251     $self->action_name($action);
 
 252     $self->_run_hooks('before', $action);
 
 254     $self->_run_hooks('after', $action);
 
 256     $::form->error($::locale->text('Oops. No valid action found to dispatch. Please report this case to the kivitendo team.'));
 
 266 SL::Controller::Base - base class for all action controllers
 
 272 This is a base class for all action controllers. Action controllers
 
 273 provide subs that are callable by special URLs.
 
 275 For each request made to the web server an instance of the controller
 
 276 will be created. After the request has been served that instance will
 
 277 handed over to garbage collection.
 
 279 This base class is derived from L<Rose::Object>.
 
 283 The URLs have the following properties:
 
 289 The script part of the URL must be C<controller.pl>.
 
 293 There must be a GET or POST parameter named C<action> containing the
 
 294 name of the controller and the sub to call separated by C</>,
 
 295 e.g. C<Message/list>.
 
 299 The controller name is the package's name without the
 
 300 C<SL::Controller::> prefix. At the moment only packages in the
 
 301 C<SL::Controller> namespace are valid; sub-namespaces are not
 
 302 allowed. The package name must start with an upper-case letter.
 
 306 The sub part of the C<action> parameter is the name of the sub to
 
 307 call. However, the sub's name is automatically prefixed with
 
 308 C<action_>. Therefore for the example C<Message/list> the sub
 
 309 C<SL::DB::Message::action_list> would be called. This in turn means
 
 310 that subs whose name does not start with C<action_> cannot be invoked
 
 311 directly via the URL.
 
 315 =head2 INDIRECT DISPATCHING
 
 317 In the case that there are several submit buttons on a page it is
 
 318 often impractical to have a single C<action> parameter match up
 
 319 properly. For such a case a special dispatcher method is available. In
 
 320 that case the C<action> parameter of the URL must be
 
 321 C<Controller/dispatch>.
 
 323 The C<SL::Controller::Base::_dispatch> method will iterate over all
 
 324 subs in the controller package whose names start with C<action_>. The
 
 325 first one for which there's a GET or POST parameter with the same name
 
 326 and that's trueish is called.
 
 328 Usage from a template usually looks like this:
 
 330   <form method="POST" action="controller.pl">
 
 332     <input type="hidden" name="action" value="Message/dispatch">
 
 333     <input type="submit" name="action_mark_as_read" value="Mark messages as read">
 
 334     <input type="submit" name="action_delete" value="Delete messages">
 
 337 The dispatching is handled by the function L</_dispatch>.
 
 341 Hooks are functions that are called before or after the controller's
 
 342 action is called. The controller package defines the hooks, and those
 
 343 hooks themselves are run as instance methods.
 
 345 Hooks are run in the order they're added.
 
 347 The hooks receive a single parameter: the name of the action that is
 
 348 about to be called (for C<before> hooks) / was called (for C<after>
 
 351 The return value of the hooks is discarded.
 
 353 Hooks can be defined to run for all actions, for only specific actions
 
 354 or for all actions except a list of actions. Each entry is the action
 
 355 name, not the sub's name. Therefore in order to run a hook before one
 
 356 of the subs C<action_edit> or C<action_save> is called the following
 
 359   __PACKAGE__->run_before('things_to_do_before_edit_and_save', only => [ 'edit', 'save' ]);
 
 363 =head2 PUBLIC HELPER FUNCTIONS
 
 365 These functions are supposed to be called by sub-classed controllers.
 
 369 =item C<render $template, [ $options, ] %locals>
 
 371 Renders the template C<$template>. Provides other variables than
 
 372 C<Form::parse_html_template> does.
 
 374 C<$options>, if present, must be a hash reference. All remaining
 
 375 parameters are slurped into C<%locals>.
 
 377 What is rendered and how C<$template> is interpreted is determined
 
 378 both by C<$template>'s reference type and by the supplied options. The
 
 379 actual rendering is handled by L<SL::Presenter/render>.
 
 381 If C<$template> is a normal scalar (not a reference) then it is meant
 
 382 to be a template file name relative to the C<templates/webpages>
 
 383 directory. The file name to use is determined by the C<type> option.
 
 385 If C<$template> is a reference to a scalar then the referenced
 
 386 scalar's content is used as the content to process. The C<type> option
 
 387 is not considered in this case.
 
 389 C<$template> can also be an instance of L<SL::Presenter::EscapedText>
 
 390 or a reference to such an instance. Both of these cases are handled
 
 391 the same way as if C<$template> were a reference to a scalar: its
 
 392 content is processed, and C<type> is not considered.
 
 394 Other reference types, unknown options and unknown arguments to the
 
 395 C<type> option cause the function to L<croak>.
 
 397 The following options are available (defaults: C<type> = 'html',
 
 398 C<process> = 1, C<output> = 1, C<header> = 1, C<layout> = 1):
 
 404 The template type. Can be C<html> (the default), C<js> for JavaScript
 
 405 or C<json> for JSON content. Affects the extension that's added to the
 
 406 file name given with a non-reference C<$template> argument, the
 
 407 content type HTTP header that is output and whether or not the layout
 
 408 will be output as well (see description of C<layout> below).
 
 412 If trueish (which is also the default) it causes the template/content
 
 413 to be processed by the Template toolkit. Otherwise the
 
 414 template/content is output as-is.
 
 418 If trueish (the default) then the generated output will be sent to the
 
 419 browser in addition to being returned. If falsish then the options
 
 420 C<header> and C<layout> are set to 0 as well.
 
 424 Determines whether or not to output the HTTP response
 
 425 headers. Defaults to the same value that C<output> is set to. If set
 
 426 to falsish then the layout is not output either.
 
 430 Determines whether or not the basic HTML layout structure should be
 
 431 output (HTML header, common JavaScript and stylesheet inclusions, menu
 
 432 etc.). Defaults to 0 if C<type> is not C<html> and to the same value
 
 433 C<header> is set to otherwise.
 
 437 The template itself has access to several variables. These are listed
 
 438 in the documentation to L<SL::Presenter/render>.
 
 440 The function will always return the output.
 
 442 Example: Render a HTML template with a certain title and a few locals
 
 444   $self->render('todo/list',
 
 445                 title      => 'List TODO items',
 
 446                 TODO_ITEMS => SL::DB::Manager::Todo->get_all_sorted);
 
 448 Example: Render a string and return its content for further processing
 
 449 by the calling function. No header is generated due to C<output>.
 
 451   my $content = $self->render(\'[% USE JavaScript %][% JavaScript.replace_with("#someid", "js/something") %]',
 
 454 Example: Render a JavaScript template
 
 455 "templates/webpages/todo/single_item.js" and send it to the
 
 456 browser. Typical use for actions called via AJAX:
 
 458   $self->render('todo/single_item', { type => 'js' },
 
 459                 item => $employee->most_important_todo_item);
 
 461 =item C<send_file $file_name, [%params]>
 
 463 Sends the file C<$file_name> to the browser including appropriate HTTP
 
 464 headers for a download. C<%params> can include the following:
 
 468 =item * C<type> -- the file's content type; defaults to
 
 469 'application/octet_stream'
 
 471 =item * C<name> -- the name presented to the browser; defaults to
 
 476 =item C<url_for $url>
 
 478 =item C<url_for $params>
 
 480 =item C<url_for %params>
 
 482 Creates an URL for the given parameters suitable for calling an action
 
 483 controller. If there's only one scalar parameter then it is returned
 
 486 Otherwise the parameters are given either as a single hash ref
 
 487 parameter or as a normal hash.
 
 489 The controller to call is given by C<$params{controller}>. It defaults
 
 490 to the current controller as returned by
 
 493 The action to call is given by C<$params{action}>. It defaults to
 
 496 All other key/value pairs in C<%params> are appended as GET parameters
 
 499 Usage from a template might look like this:
 
 501   <a href="[% SELF.url_for(controller => 'Message', action => 'new', recipient_id => 42) %]">create new message</a>
 
 503 =item C<redirect_to %url_params>
 
 505 Redirects the browser to a new URL. The URL is generated by calling
 
 506 L</url_for> with C<%url_params>.
 
 508 This function implements the redirection depending on whether or not
 
 509 the current request is an AJAX request as determined by
 
 510 L<SL::Request/is_ajax>. If it is a normal request then it outputs a
 
 511 standard HTTP redirect header (HTTP code 302). If it is an AJAX
 
 512 request then it outputs an AJAX response suitable for the
 
 513 C<eval_json_result> function from the L<SL::ClientJS> module.
 
 515 =item C<run_before $sub, %params>
 
 517 =item C<run_after $sub, %params>
 
 519 Adds a hook to run before or after certain actions are run for the
 
 520 current package. The code to run is C<$sub> which is either the name
 
 521 of an instance method or a code reference. If it's the latter then the
 
 522 first parameter will be C<$self>.
 
 524 C<%params> can contain two possible values that restrict the code to
 
 525 be run only for certain actions:
 
 529 =item C<< only => \@list >>
 
 531 Only run the code for actions given in C<@list>. The entries are the
 
 532 action names, not the names of the sub (so it's C<list> instead of
 
 535 =item C<< except => \@list >>
 
 537 Run the code for all actions but for those given in C<@list>. The
 
 538 entries are the action names, not the names of the sub (so it's
 
 539 C<list> instead of C<action_list>).
 
 543 If neither restriction is used then the code will be run for any
 
 546 The hook's return values are discarded.
 
 548 =item C<delay_flash_on_redirect>
 
 550 May be overridden by a controller. If this method returns true, redirect_to
 
 551 will delay all flash messages for the current request. Defaults to false for
 
 552 compatibility reasons.
 
 554 =item C<get_auth_level $action>
 
 556 May be overridden by a controller. Determines what kind of
 
 557 authentication is required for a particular action. Must return either
 
 558 C<admin> (which means that authentication as an admin is required),
 
 559 C<user> (authentication as a normal user suffices) with a possible
 
 560 future value C<none> (which would require no authentication but is not
 
 563 =item C<keep_auth_vars_in_form>
 
 565 May be overridden by a controller. If falsish (the default) all form
 
 566 variables whose name starts with C<{AUTH}> are removed before the
 
 567 request is routed. Only controllers that handle login requests
 
 568 themselves should return trueish for this function.
 
 570 =item C<controller_name>
 
 572 Returns the name of the curernt controller package without the
 
 573 C<SL::Controller::> prefix. This method can be called both as a class
 
 574 method and an instance method.
 
 578 Returns the name of the currently executing action. If the dispatcher
 
 579 mechanism was used then this is not C<dispatch> but the actual method
 
 580 name the dispatching resolved to.
 
 584 Returns the global presenter object by calling
 
 585 L<SL::Presenter/get>.
 
 589 =head2 PRIVATE FUNCTIONS
 
 591 These functions are supposed to be used from this base class only.
 
 597 Implements the method lookup for indirect dispatching mentioned in the
 
 598 section L</INDIRECT DISPATCHING>.
 
 600 =item C<_run_action $action>
 
 602 Executes a sub based on the value of C<$action>. C<$action> is the sub
 
 603 name part of the C<action> GET or POST parameter as described in
 
 606 If C<$action> equals C<dispatch> then the sub L</_dispatch> in this
 
 607 base class is called for L</INDIRECT DISPATCHING>. Otherwise
 
 608 C<$action> is prefixed with C<action_>, and that sub is called on the
 
 609 current controller instance.
 
 615 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>