1 package SL::Controller::Base;
5 use parent qw(Rose::Object);
9 use List::Util qw(first);
12 # public/helper functions
18 return $_[0] if (scalar(@_) == 1) && !ref($_[0]);
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);
26 return "controller.pl?${query}";
31 my $url = $self->url_for(@_);
33 if ($self->delay_flash_on_redirect) {
34 require SL::Helper::Flash;
35 SL::Helper::Flash::delay_flash();
38 print $::request->{cgi}->redirect($url);
44 my ($options, %locals) = (@_ && ref($_[0])) ? @_ : ({ }, @_);
46 $options->{type} = lc($options->{type} || 'html');
47 $options->{no_layout} = 1 if $options->{type} eq 'js';
50 if ($options->{inline}) {
53 } elsif($options->{raw}) {
57 $source = "templates/webpages/${template}." . $options->{type};
58 croak "Template file ${source} not found" unless -f $source;
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';
66 print $::form->create_http_response(content_type => $content_type,
67 charset => $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET());
70 $::form->{title} = $locals{title} if $locals{title};
75 my %params = ( %locals,
77 FLASH => $::form->{FLASH},
79 INSTANCE_CONF => $::instance_conf,
81 LXCONFIG => \%::lx_office_conf,
82 LXDEBUG => $::lxdebug,
83 MYCONFIG => \%::myconfig,
88 if (!$options->{raw}) {
89 my $parser = $self->_template_obj;
90 $parser->process($source, \%params, \$output) || croak $parser->error;
95 print $output unless $options->{inline} || $options->{no_output};
101 my ($self, $file_name, %params) = @_;
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;
108 print $::form->create_http_response(content_type => $content_type,
109 content_disposition => 'attachment; filename="' . $attachment_name . '"',
110 content_length => -s $file);
112 $::locale->with_raw_io(\*STDOUT, sub { print while <$file> });
117 # Before/after run hooks
121 _add_hook('before', @_);
125 _add_hook('after', @_);
131 my ($when, $class, $sub, %params) = @_;
133 foreach my $key (qw(only except)) {
134 $params{$key} = { map { ( $_ => 1 ) } @{ $params{$key} } } if $params{$key};
137 my $idx = "${when}/${class}";
138 $hooks{$idx} ||= [ ];
139 push @{ $hooks{$idx} }, { %params, code => $sub };
143 my ($self, $when, $action) = @_;
145 my $idx = "${when}/" . ref($self);
147 foreach my $hook (@{ $hooks{$idx} || [] }) {
148 next if ($hook->{only } && !$hook->{only }->{$action})
149 || ($hook->{except} && $hook->{except}->{$action});
151 if (ref($hook->{code}) eq 'CODE') {
152 $hook->{code}->($self);
154 my $sub = $hook->{code};
161 # behaviour. override these
164 sub delay_flash_on_redirect {
169 # private functions -- for use in Base only
175 my $sub = "action_${action}";
177 return $self->_dispatch(@_) if $action eq 'dispatch';
179 $::form->error("Invalid action '${action}' for controller " . ref($self)) if !$self->can($sub);
181 $self->_run_hooks('before', $action);
183 $self->_run_hooks('after', $action);
186 sub _controller_name {
187 return (split(/::/, ref($_[0])))[-1];
194 my @actions = map { s/^action_//; $_ } grep { m/^action_/ } keys %{ ref($self) . "::" };
195 my $action = first { $::form->{"action_${_}"} } @actions;
196 my $sub = "action_${action}";
198 if ($self->can($sub)) {
199 $self->_run_hooks('before', $action);
201 $self->_run_hooks('after', $action);
203 $::form->error($::locale->text('Oops. No valid action found to dispatch. Please report this case to the Lx-Office team.'));
210 $self->{__basepriv_template_obj} ||=
211 Template->new({ INTERPOLATE => 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',
221 return $self->{__basepriv_template_obj};
230 SL::Controller::Base - base class for all action controllers
236 This is a base class for all action controllers. Action controllers
237 provide subs that are callable by special URLs.
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.
243 This base class is derived from L<Rose::Object>.
247 The URLs have the following properties:
253 The script part of the URL must be C<controller.pl>.
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>.
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.
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.
279 =head2 INDIRECT DISPATCHING
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>.
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.
292 Usage from a template usually looks like this:
294 <form method="POST" action="controller.pl">
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">
301 The dispatching is handled by the function L</_dispatch>.
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.
309 Hooks are run in the order they're added.
311 The return value of the hooks is discarded.
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
319 __PACKAGE__->run_before('things_to_do_before_edit_and_save', only => [ 'edit', 'save' ]);
323 =head2 PUBLIC HELPER FUNCTIONS
325 These functions are supposed to be called by sub-classed controllers.
329 =item C<render $template, [ $options, ] %locals>
331 Renders the template C<$template>. Provides other variables than
332 C<Form::parse_html_template> does.
334 C<$options>, if present, must be a hash reference. All remaining
335 parameters are slurped into C<%locals>.
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>.
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
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.
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
356 If C<< $options->{partial} >> or C<< $options->{inline} >> is trueish
357 then neither the HTTP response header nor the standard HTML header is
360 Otherwise at least the HTTP response header will be generated based on
361 the template type (C<< $options->{type} >>).
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
369 The template itself has access to the following variables:
373 =item * C<AUTH> -- C<$::auth>
375 =item * C<FORM> -- C<$::form>
377 =item * C<LOCALE> -- C<$::locale>
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)
384 =item * C<LXDEBUG> -- C<$::lxdebug>
386 =item * C<MYCONFIG> -- C<%::myconfig>
388 =item * C<SELF> -- the controller instance
390 =item * All items from C<%locals>
394 Unless C<< $options->{inline} >> is trueish the function will send the
395 output to the browser.
397 The function will always return the output.
399 Example: Render a HTML template with a certain title and a few locals
401 $self->render('todo/list',
402 title => 'List TODO items',
403 TODO_ITEMS => SL::DB::Manager::Todo->get_all_sorted);
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>.
408 my $content = $self->render('[% USE JavaScript %][% JavaScript.replace_with("#someid", "js/something") %]',
409 { type => 'js', inline => 1 });
411 Example: Render a JavaScript template and send it to the
412 browser. Typical use for actions called via AJAX:
414 $self->render('todo/single_item', { type => 'js' },
415 item => $employee->most_important_todo_item);
417 =item C<send_file $file_name, [%params]>
419 Sends the file C<$file_name> to the browser including appropriate HTTP
420 headers for a download. C<%params> can include the following:
424 =item * C<type> -- the file's content type; defaults to
425 'application/octet_stream'
427 =item * C<name> -- the name presented to the browser; defaults to
432 =item C<url_for $url>
434 =item C<url_for $params>
436 =item C<url_for %params>
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
442 Otherwise the parameters are given either as a single hash ref
443 parameter or as a normal hash.
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>.
449 The action to call is given by C<$params{action}>. It defaults to
452 All other key/value pairs in C<%params> are appended as GET parameters
455 Usage from a template might look like this:
457 <a href="[% SELF.url_for(controller => 'Message', action => 'new', recipient_id => 42) %]">create new message</a>
459 =item C<redirect_to %url_params>
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
465 =item C<run_before $sub, %params>
467 =item C<run_after $sub, %params>
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>.
474 C<%params> can contain two possible values that restrict the code to
475 be run only for certain actions:
479 =item C<< only => \@list >>
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
485 =item C<< except => \@list >>
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>).
493 If neither restriction is used then the code will be run for any
496 The hook's return values are discarded.
498 =item delay_flash_on_redirect
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.
506 =head2 PRIVATE FUNCTIONS
508 These functions are supposed to be used from this base class only.
512 =item C<_controller_name>
514 Returns the name of the curernt controller package without the
515 C<SL::Controller::> prefix.
519 Implements the method lookup for indirect dispatching mentioned in the
520 section L</INDIRECT DISPATCHING>.
522 =item C<_run_action $action>
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
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.
537 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>