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 # public/helper functions
20 return $_[0] if (scalar(@_) == 1) && !ref($_[0]);
22 my %params = ref($_[0]) eq 'HASH' ? %{ $_[0] } : @_;
23 my $controller = delete($params{controller}) || $self->_controller_name;
24 my $action = $params{action} || 'dispatch';
27 if ($controller =~ m/\.pl$/) {
28 # Old-style controller
29 $script = $controller;
31 $params{action} = "${controller}/${action}";
32 $script = "controller.pl";
35 my $query = join '&', map { uri_encode($_->[0]) . '=' . uri_encode($_->[1]) } @{ flatten(\%params) };
37 return "${script}?${query}";
42 my $url = $self->url_for(@_);
44 if ($self->delay_flash_on_redirect) {
45 require SL::Helper::Flash;
46 SL::Helper::Flash::delay_flash();
49 print $::request->{cgi}->redirect($url);
55 my ($options, %locals) = (@_ && ref($_[0])) ? @_ : ({ }, @_);
57 $options->{type} = lc($options->{type} || 'html');
58 $options->{no_layout} = 1 if $options->{type} eq 'js';
61 if ($options->{inline}) {
64 } elsif($options->{raw}) {
68 $source = "templates/webpages/${template}." . $options->{type};
69 croak "Template file ${source} not found" unless -f $source;
72 if (!$options->{partial} && !$options->{inline} && !$::form->{header}) {
73 if ($options->{no_layout}) {
74 $::form->{header} = 1;
75 my $content_type = $options->{type} eq 'js' ? 'text/javascript' : 'text/html';
77 print $::form->create_http_response(content_type => $content_type,
78 charset => $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET());
81 $::form->{title} = $locals{title} if $locals{title};
86 my %params = ( %locals,
88 FLASH => $::form->{FLASH},
90 INSTANCE_CONF => $::instance_conf,
92 LXCONFIG => \%::lx_office_conf,
93 LXDEBUG => $::lxdebug,
94 MYCONFIG => \%::myconfig,
99 if (!$options->{raw}) {
100 my $parser = $self->_template_obj;
101 $parser->process($source, \%params, \$output) || croak $parser->error;
106 print $output unless $options->{inline} || $options->{no_output};
112 my ($self, $file_name, %params) = @_;
114 my $file = IO::File->new($file_name, 'r') || croak("Cannot open file '${file_name}'");
115 my $content_type = $params{type} || 'application/octet_stream';
116 my $attachment_name = $params{name} || $file_name;
117 $attachment_name =~ s:.*//::g;
119 print $::form->create_http_response(content_type => $content_type,
120 content_disposition => 'attachment; filename="' . $attachment_name . '"',
121 content_length => -s $file);
123 $::locale->with_raw_io(\*STDOUT, sub { print while <$file> });
128 # Before/after run hooks
132 _add_hook('before', @_);
136 _add_hook('after', @_);
142 my ($when, $class, $sub, %params) = @_;
144 foreach my $key (qw(only except)) {
145 $params{$key} = { map { ( $_ => 1 ) } @{ $params{$key} } } if $params{$key};
148 my $idx = "${when}/${class}";
149 $hooks{$idx} ||= [ ];
150 push @{ $hooks{$idx} }, { %params, code => $sub };
154 my ($self, $when, $action) = @_;
156 my $idx = "${when}/" . ref($self);
158 foreach my $hook (@{ $hooks{$idx} || [] }) {
159 next if ($hook->{only } && !$hook->{only }->{$action})
160 || ($hook->{except} && $hook->{except}->{$action});
162 if (ref($hook->{code}) eq 'CODE') {
163 $hook->{code}->($self, $action);
165 my $sub = $hook->{code};
166 $self->$sub($action);
172 # behaviour. override these
175 sub delay_flash_on_redirect {
180 # Ignore the 'action' parameter.
184 sub keep_auth_vars_in_form {
189 # private functions -- for use in Base only
195 my $sub = "action_${action}";
197 return $self->_dispatch(@_) if $action eq 'dispatch';
199 $::form->error("Invalid action '${action}' for controller " . ref($self)) if !$self->can($sub);
201 $self->_run_hooks('before', $action);
203 $self->_run_hooks('after', $action);
206 sub _controller_name {
207 my $class = ref($_[0]) || $_[0];
208 $class =~ s/^SL::Controller:://;
216 my @actions = map { s/^action_//; $_ } grep { m/^action_/ } keys %{ ref($self) . "::" };
217 my $action = first { $::form->{"action_${_}"} } @actions;
218 my $sub = "action_${action}";
220 if ($self->can($sub)) {
221 $self->_run_hooks('before', $action);
223 $self->_run_hooks('after', $action);
225 $::form->error($::locale->text('Oops. No valid action found to dispatch. Please report this case to the Lx-Office team.'));
232 $self->{__basepriv_template_obj} ||=
233 Template->new({ INTERPOLATE => 0,
237 PLUGIN_BASE => 'SL::Template::Plugin',
238 INCLUDE_PATH => '.:templates/webpages',
239 COMPILE_EXT => '.tcc',
240 COMPILE_DIR => $::lx_office_conf{paths}->{userspath} . '/templates-cache',
243 return $self->{__basepriv_template_obj};
252 SL::Controller::Base - base class for all action controllers
258 This is a base class for all action controllers. Action controllers
259 provide subs that are callable by special URLs.
261 For each request made to the web server an instance of the controller
262 will be created. After the request has been served that instance will
263 handed over to garbage collection.
265 This base class is derived from L<Rose::Object>.
269 The URLs have the following properties:
275 The script part of the URL must be C<controller.pl>.
279 There must be a GET or POST parameter named C<action> containing the
280 name of the controller and the sub to call separated by C</>,
281 e.g. C<Message/list>.
285 The controller name is the package's name without the
286 C<SL::Controller::> prefix. At the moment only packages in the
287 C<SL::Controller> namespace are valid; sub-namespaces are not
288 allowed. The package name must start with an upper-case letter.
292 The sub part of the C<action> parameter is the name of the sub to
293 call. However, the sub's name is automatically prefixed with
294 C<action_>. Therefore for the example C<Message/list> the sub
295 C<SL::DB::Message::action_list> would be called. This in turn means
296 that subs whose name does not start with C<action_> cannot be invoked
297 directly via the URL.
301 =head2 INDIRECT DISPATCHING
303 In the case that there are several submit buttons on a page it is
304 often impractical to have a single C<action> parameter match up
305 properly. For such a case a special dispatcher method is available. In
306 that case the C<action> parameter of the URL must be
307 C<Controller/dispatch>.
309 The C<SL::Controller::Base::_dispatch> method will iterate over all
310 subs in the controller package whose names start with C<action_>. The
311 first one for which there's a GET or POST parameter with the same name
312 and that's trueish is called.
314 Usage from a template usually looks like this:
316 <form method="POST" action="controller.pl">
318 <input type="hidden" name="action" value="Message/dispatch">
319 <input type="submit" name="action_mark_as_read" value="Mark messages as read">
320 <input type="submit" name="action_delete" value="Delete messages">
323 The dispatching is handled by the function L</_dispatch>.
327 Hooks are functions that are called before or after the controller's
328 action is called. The controller package defines the hooks, and those
329 hooks themselves are run as instance methods.
331 Hooks are run in the order they're added.
333 The hooks receive a single parameter: the name of the action that is
334 about to be called (for C<before> hooks) / was called (for C<after>
337 The return value of the hooks is discarded.
339 Hooks can be defined to run for all actions, for only specific actions
340 or for all actions except a list of actions. Each entry is the action
341 name, not the sub's name. Therefore in order to run a hook before one
342 of the subs C<action_edit> or C<action_save> is called the following
345 __PACKAGE__->run_before('things_to_do_before_edit_and_save', only => [ 'edit', 'save' ]);
349 =head2 PUBLIC HELPER FUNCTIONS
351 These functions are supposed to be called by sub-classed controllers.
355 =item C<render $template, [ $options, ] %locals>
357 Renders the template C<$template>. Provides other variables than
358 C<Form::parse_html_template> does.
360 C<$options>, if present, must be a hash reference. All remaining
361 parameters are slurped into C<%locals>.
363 What is rendered and how C<$template> is interpreted is determined by
364 the options I<type>, I<inline>, I<partial> and I<no_layout>.
366 If C<< $options->{inline} >> is trueish then C<$template> is a string
367 containing the template code to interprete. Additionally the output
368 will not be sent to the browser. Instead it is only returned to the
371 If C<< $options->{raw} >> is trueish, the function will treat the input as
372 already parsed, and will not filter the input through Template. Unlike
373 C<inline>, the input is taked as a reference.
375 If C<< $options->{inline} >> is falsish then C<$template> is
376 interpreted as the name of a template file. It is prefixed with
377 "templates/webpages/" and postfixed with a file extension based on
378 C<< $options->{type} >>. C<< $options->{type} >> can be either C<html>
379 or C<js> and defaults to C<html>. An exception will be thrown if that
382 If C<< $options->{partial} >> or C<< $options->{inline} >> is trueish
383 then neither the HTTP response header nor the standard HTML header is
386 Otherwise at least the HTTP response header will be generated based on
387 the template type (C<< $options->{type} >>).
389 If the template type is C<html> then the standard HTML header will be
390 output via C<< $::form->header >> with C<< $::form->{title} >> set to
391 C<$locals{title}> (the latter only if C<$locals{title}> is
392 trueish). Setting C<< $options->{no_layout} >> to trueish will prevent
395 The template itself has access to the following variables:
399 =item * C<AUTH> -- C<$::auth>
401 =item * C<FORM> -- C<$::form>
403 =item * C<LOCALE> -- C<$::locale>
405 =item * C<LXCONFIG> -- all parameters from C<config/lx_office.conf>
406 with the same name they appear in the file (first level is the
407 section, second the actual variable, e.g. C<system.dbcharset>,
408 C<features.webdav> etc)
410 =item * C<LXDEBUG> -- C<$::lxdebug>
412 =item * C<MYCONFIG> -- C<%::myconfig>
414 =item * C<SELF> -- the controller instance
416 =item * All items from C<%locals>
420 Unless C<< $options->{inline} >> is trueish the function will send the
421 output to the browser.
423 The function will always return the output.
425 Example: Render a HTML template with a certain title and a few locals
427 $self->render('todo/list',
428 title => 'List TODO items',
429 TODO_ITEMS => SL::DB::Manager::Todo->get_all_sorted);
431 Example: Render a string and return its content for further processing
432 by the calling function. No header is generated due to C<inline>.
434 my $content = $self->render('[% USE JavaScript %][% JavaScript.replace_with("#someid", "js/something") %]',
435 { type => 'js', inline => 1 });
437 Example: Render a JavaScript template and send it to the
438 browser. Typical use for actions called via AJAX:
440 $self->render('todo/single_item', { type => 'js' },
441 item => $employee->most_important_todo_item);
443 =item C<send_file $file_name, [%params]>
445 Sends the file C<$file_name> to the browser including appropriate HTTP
446 headers for a download. C<%params> can include the following:
450 =item * C<type> -- the file's content type; defaults to
451 'application/octet_stream'
453 =item * C<name> -- the name presented to the browser; defaults to
458 =item C<url_for $url>
460 =item C<url_for $params>
462 =item C<url_for %params>
464 Creates an URL for the given parameters suitable for calling an action
465 controller. If there's only one scalar parameter then it is returned
468 Otherwise the parameters are given either as a single hash ref
469 parameter or as a normal hash.
471 The controller to call is given by C<$params{controller}>. It defaults
472 to the current controller as returned by
473 L</_controller_name>.
475 The action to call is given by C<$params{action}>. It defaults to
478 All other key/value pairs in C<%params> are appended as GET parameters
481 Usage from a template might look like this:
483 <a href="[% SELF.url_for(controller => 'Message', action => 'new', recipient_id => 42) %]">create new message</a>
485 =item C<redirect_to %url_params>
487 Redirects the browser to a new URL by outputting a HTTP redirect
488 header. The URL is generated by calling L</url_for> with
491 =item C<run_before $sub, %params>
493 =item C<run_after $sub, %params>
495 Adds a hook to run before or after certain actions are run for the
496 current package. The code to run is C<$sub> which is either the name
497 of an instance method or a code reference. If it's the latter then the
498 first parameter will be C<$self>.
500 C<%params> can contain two possible values that restrict the code to
501 be run only for certain actions:
505 =item C<< only => \@list >>
507 Only run the code for actions given in C<@list>. The entries are the
508 action names, not the names of the sub (so it's C<list> instead of
511 =item C<< except => \@list >>
513 Run the code for all actions but for those given in C<@list>. The
514 entries are the action names, not the names of the sub (so it's
515 C<list> instead of C<action_list>).
519 If neither restriction is used then the code will be run for any
522 The hook's return values are discarded.
524 =item C<delay_flash_on_redirect>
526 May be overridden by a controller. If this method returns true, redirect_to
527 will delay all flash messages for the current request. Defaults to false for
528 compatibility reasons.
530 =item C<get_auth_level $action>
532 May be overridden by a controller. Determines what kind of
533 authentication is required for a particular action. Must return either
534 C<admin> (which means that authentication as an admin is required),
535 C<user> (authentication as a normal user suffices) with a possible
536 future value C<none> (which would require no authentication but is not
539 =item C<keep_auth_vars_in_form>
541 May be overridden by a controller. If falsish (the default) all form
542 variables whose name starts with C<{AUTH}> are removed before the
543 request is routed. Only controllers that handle login requests
544 themselves should return trueish for this function.
548 =head2 PRIVATE FUNCTIONS
550 These functions are supposed to be used from this base class only.
554 =item C<_controller_name>
556 Returns the name of the curernt controller package without the
557 C<SL::Controller::> prefix.
561 Implements the method lookup for indirect dispatching mentioned in the
562 section L</INDIRECT DISPATCHING>.
564 =item C<_run_action $action>
566 Executes a sub based on the value of C<$action>. C<$action> is the sub
567 name part of the C<action> GET or POST parameter as described in
570 If C<$action> equals C<dispatch> then the sub L</_dispatch> in this
571 base class is called for L</INDIRECT DISPATCHING>. Otherwise
572 C<$action> is prefixed with C<action_>, and that sub is called on the
573 current controller instance.
579 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>