1 package SL::Dispatcher;
5 # Force scripts/locales.pl to parse these templates:
6 # parse_html_template('login_screen/auth_db_unreachable')
7 # parse_html_template('login_screen/user_login')
8 # parse_html_template('generic/error')
11 use CGI qw( -no_xhtml);
15 use English qw(-no_match_vars);
19 use List::MoreUtils qw(all);
20 use List::Util qw(first);
21 use POSIX qw(setlocale);
23 use SL::Dispatcher::AuthHandler;
30 use SL::Helper::DateTime;
31 use SL::InstanceConfiguration;
32 use SL::MoreCommon qw(uri_encode);
33 use SL::Template::Plugin::HTMLFixes;
36 use Rose::Object::MakeMethods::Generic (
37 scalar => [ qw(restart_after_request) ],
40 # Trailing new line is added so that Perl will not add the line
41 # number 'die' was called in.
42 use constant END_OF_REQUEST => "END-OF-REQUEST\n";
47 my ($class, $interface) = @_;
49 my $self = bless {}, $class;
50 $self->{interface} = lc($interface || 'cgi');
51 $self->{auth_handler} = SL::Dispatcher::AuthHandler->new;
53 # Initialize character type locale to be UTF-8 instead of C:
54 foreach my $locale (qw(de_DE.UTF-8 en_US.UTF-8)) {
55 last if setlocale('LC_CTYPE', $locale);
63 return $self->{interface} eq 'cgi' ? 'CGI' : 'FastCGI';
66 sub is_admin_request {
68 return ($params{script} eq 'admin.pl') || (($params{routing_type} eq 'controller') && ($params{script_name} eq 'Admin'));
71 sub pre_request_checks {
74 _check_for_old_config_files();
76 if (!$::auth->session_tables_present && !is_admin_request(%params)) {
77 show_error('login_screen/auth_db_unreachable');
80 if ($::request->type !~ m/^ (?: html | js | json ) $/x) {
81 die $::locale->text("Invalid request type '#1'", $::request->type);
85 sub pre_request_initialization {
86 my ($self, %params) = @_;
88 $self->unrequire_bin_mozilla;
90 $::locale = Locale->new($::lx_office_conf{system}->{language});
92 $::instance_conf = SL::InstanceConfiguration->new;
93 $::request = SL::Request->new(
95 layout => SL::Layout::None->new,
98 my $session_result = $::auth->restore_session;
99 $::auth->create_or_refresh_session;
101 if ($params{client}) {
102 $::auth->set_client($params{client}) || die("cannot find client " . $params{client});
104 if ($params{login}) {
105 die "cannot find user " . $params{login} unless %::myconfig = $::auth->read_user(login => $params{login});
106 die "cannot find locale for user " . $params{login} unless $::locale = Locale->new($::myconfig{countrycode});
108 $::form->{login} = $params{login}; # normaly implicit at login
112 return $session_result;
115 sub render_error_ajax {
120 ->render(SL::Controller::Base->new);
124 $::lxdebug->enter_sub;
125 my $template = shift;
126 my $error_type = shift || '';
129 $::myconfig{countrycode} = delete($params{countrycode}) || $::lx_office_conf{system}->{language};
130 $::locale = Locale->new($::myconfig{countrycode});
131 $::form->{error} = $::locale->text('The session is invalid or has expired.') if ($error_type eq 'session');
132 $::form->{error} = $::locale->text('Incorrect password!') if ($error_type eq 'password');
133 $::form->{error} = $::locale->text('The action is missing or invalid.') if ($error_type eq 'action');
135 return render_error_ajax($::form->{error}) if $::request->is_ajax;
138 print $::form->parse_html_template($template, \%params);
139 $::lxdebug->leave_sub;
144 sub pre_startup_setup {
147 SL::LxOfficeConf->read;
151 require "bin/mozilla/common.pl";
152 require "bin/mozilla/installationcheck.pl";
153 } or die $EVAL_ERROR;
155 # canonial globals. if it's not here, chances are it will get refactored someday.
158 $::lxdebug = LXDebug->new;
159 $::auth = SL::Auth->new;
162 %::myconfig = User->get_default_myconfig;
165 $SIG{__WARN__} = sub {
166 $::lxdebug->warn(@_);
169 $SIG{__DIE__} = sub { Carp::confess( @_ ) } if $::lx_office_conf{debug}->{backtrace_on_die};
171 $self->_cache_file_modification_times;
174 sub pre_startup_checks {
175 ::verify_installation();
180 $self->pre_startup_setup;
181 $self->pre_startup_checks;
184 sub require_main_code {
185 $::lxdebug->enter_sub;
186 my ($script, $suffix) = @_;
190 require "bin/mozilla/$script$suffix";
191 } or die $EVAL_ERROR;
193 if (-f "bin/mozilla/custom_$script$suffix") {
196 require "bin/mozilla/custom_$script$suffix";
198 $::form->error($EVAL_ERROR) if ($EVAL_ERROR);
200 if ($::form->{login} && -f "bin/mozilla/$::form->{login}_$script") {
203 require "bin/mozilla/$::form->{login}_$script";
205 $::form->error($EVAL_ERROR) if ($EVAL_ERROR);
207 $::lxdebug->leave_sub;
210 sub _require_controller {
211 my $controller = shift;
212 $controller =~ s|[^A-Za-z0-9_]||g;
213 $controller = "SL/Controller/${controller}";
217 require "${controller}.pm";
218 } or die $EVAL_ERROR;
221 sub _run_controller {
222 "SL::Controller::$_[0]"->new->_run_action($_[1]);
225 sub handle_all_requests {
228 my $request = FCGI::Request();
229 while ($request->Accept() >= 0) {
230 $self->handle_request($request);
232 $self->restart_after_request(1) if $self->_interface_is_fcgi && SL::System::Process::memory_usage_is_too_high();
233 $request->LastCall if $self->restart_after_request;
236 exec $0 if $self->restart_after_request;
241 $self->{request} = shift;
243 $::lxdebug->enter_sub;
244 $::lxdebug->begin_request;
246 my ($script, $path, $suffix, $script_name, $action, $routing_type);
248 my $session_result = $self->pre_request_initialization;
250 $::request->read_cgi_input($::form);
253 eval { %routing = $self->_route_request($ENV{SCRIPT_NAME}); 1; } or return;
254 ($routing_type, $script_name, $action) = @routing{qw(type controller action)};
255 $::lxdebug->log_request($routing_type, $script_name, $action);
257 $::request->type(lc($routing{request_type} || 'html'));
259 if ($routing_type eq 'old') {
260 $::form->{action} = lc $::form->{action};
261 $::form->{action} =~ s/( |-|,|\#)/_/g;
263 ($script, $path, $suffix) = fileparse($script_name, ".pl");
264 require_main_code($script, $suffix) unless $script eq 'admin';
266 $::form->{script} = $script . $suffix;
269 _require_controller($script_name);
270 $::form->{script} = "controller.pl";
274 pre_request_checks(script => $script, action => $action, routing_type => $routing_type, script_name => $script_name);
276 if ( SL::System::InstallationLock->is_locked
277 && !is_admin_request(script => $script, script_name => $script_name, routing_type => $routing_type)) {
278 $::form->error($::locale->text('System currently down for maintenance!'));
281 # For compatibility with a lot of database upgrade scripts etc:
282 # Re-write request to old 'login.pl?action=login' to new
283 # 'LoginScreen' controller. Make sure to load its code!
284 if (($script eq 'login') && ($action eq 'login')) {
285 ($routing_type, $script, $script_name, $action) = qw(controller controller LoginScreen login);
286 _require_controller('LoginScreen');
289 if ( (($script eq 'login') && !$action)
290 || ($script eq 'admin')
291 || (SL::Auth::SESSION_EXPIRED() == $session_result)) {
292 $self->handle_login_error(routing_type => $routing_type,
294 controller => $script_name,
299 my %auth_result = $self->{auth_handler}->handle(
300 routing_type => $routing_type,
302 controller => $script_name,
306 $self->end_request unless $auth_result{auth_ok};
308 delete @{ $::form }{ grep { m/^\{AUTH\}/ } keys %{ $::form } } unless $auth_result{keep_auth_vars};
311 $::form->set_standard_title;
312 if ($routing_type eq 'old') {
313 ::call_sub('::' . $::locale->findsub($action));
315 _run_controller($script_name, $action);
318 $::form->error($::locale->text('action= not defined!'));
323 if (substr($EVAL_ERROR, 0, length(END_OF_REQUEST())) ne END_OF_REQUEST()) {
324 my $error = $EVAL_ERROR;
327 if ($::request->is_ajax) {
328 eval { render_error_ajax($error) };
330 $::form->{label_error} = $::request->{cgi}->pre($error);
331 chdir SL::System::Process::exe_dir;
332 eval { show_error('generic/error') };
339 if ($self->_interface_is_fcgi) {
340 # fcgi? send send reponse on its way before cleanup.
341 $self->{request}->Flush;
342 $self->{request}->Finish;
345 $::lxdebug->end_request(routing_type => $routing_type, script_name => $script_name, action => $action);
348 $::auth->save_session;
349 $::auth->expire_sessions;
357 SL::DBConnect::Cache->reset_all;
359 $self->_watch_for_changed_files;
361 $::lxdebug->leave_sub;
364 sub reply_with_json_error {
365 my ($self, %params) = @_;
368 session => { code => '401 Unauthorized', text => 'session expired' },
369 password => { code => '401 Unauthorized', text => 'incorrect username or password' },
370 action => { code => '400 Bad request', text => 'incorrect or missing action' },
371 access => { code => '403 Forbidden', text => 'no permissions for accessing this function' },
372 _default => { code => '500 Internal server error', text => 'general server-side error' },
375 my $error = $errors{$params{error}} // $errors{_default};
376 my $reply = SL::JSON::to_json({ status => 'failed', error => $error->{text} });
378 print $::request->cgi->header(
379 -type => 'application/json',
381 -status => $error->{code},
389 sub handle_login_error {
390 my ($self, %params) = @_;
392 return $self->reply_with_json_error(error => $params{error}) if $::request->type eq 'json';
394 my $action = ($params{script} // '') =~ m/^admin/i ? 'Admin/login' : 'LoginScreen/user_login';
395 $action .= '&error=' . $params{error} if $params{error};
397 my $redirect_url = "controller.pl?action=${action}";
399 if ( $action =~ m/LoginScreen\/user_login/
401 && 'get' eq lc($ENV{REQUEST_METHOD})
402 && !_is_callback_blacklisted(map {$_ => $params{$_}} qw(routing_type script controller action) )
405 require SL::Controller::Base;
406 my $controller = SL::Controller::Base->new;
408 delete $params{error};
409 delete $params{routing_type};
410 delete @{ $::form }{ grep { m/^\{AUTH\}/ } keys %{ $::form } };
412 my $callback = $controller->url_for(%params, %{$::form});
413 $redirect_url .= '&callback=' . uri_encode($callback);
416 print $::request->cgi->redirect($redirect_url);
420 sub _is_callback_blacklisted {
423 # You can give a name only, then all actions are blackisted.
424 # Or you can give name and action, then only this action is blacklisted
426 # {name => 'is', action => 'edit'}
427 # {name => 'Project', action => 'edit'},
428 my @script_blacklist = (
433 my @controller_blacklist = (
435 {name => 'LoginScreen'},
438 my ($name, $blacklist);
439 if ('old' eq ($params{routing_type} // '')) {
440 $name = $params{script};
441 $blacklist = \@script_blacklist;
443 $name = $params{controller};
444 $blacklist = \@controller_blacklist;
447 foreach my $bl (@$blacklist) {
448 return 1 if _is_name_action_blacklisted($bl->{name}, $bl->{action}, $name, $params{action});
454 sub _is_name_action_blacklisted {
455 my ($blacklisted_name, $blacklisted_action, $name, $action) = @_;
457 return 1 if ($name // '') eq $blacklisted_name && !$blacklisted_action;
458 return 1 if ($name // '') eq $blacklisted_name && ($action // '') eq $blacklisted_action;
462 sub unrequire_bin_mozilla {
464 return unless $self->_interface_is_fcgi;
467 next unless m#^bin/mozilla/#;
468 next if /\bcommon.pl$/;
469 next if /\binstallationcheck.pl$/;
474 sub _interface_is_fcgi {
476 return $self->{interface} =~ m/^(?:fastcgi|fcgid|fcgi)$/;
480 my ($self, $script_name) = @_;
482 return $script_name =~ m/dispatcher\.pl$/ ? (type => 'old', $self->_route_dispatcher_request)
483 : $script_name =~ m/controller\.pl/ ? (type => 'controller', $self->_route_controller_request)
484 : (type => 'old', controller => $script_name, action => $::form->{action});
487 sub _route_dispatcher_request {
489 my $name_re = qr{[a-z]\w*};
490 my ($script_name, $action);
493 die "Unroutable request -- invalid module name.\n" if !$::form->{M} || ($::form->{M} !~ m/^${name_re}$/);
494 $script_name = $::form->{M} . '.pl';
497 $action = $::form->{A};
500 $action = first { m/^A_${name_re}$/ } keys %{ $::form };
501 die "Unroutable request -- invalid action name.\n" if !$action;
503 delete $::form->{$action};
504 $action = substr $action, 2;
507 delete @{$::form}{qw(M A)};
511 $::form->{label_error} = $::request->{cgi}->pre($EVAL_ERROR);
512 show_error('generic/error');
515 return (controller => $script_name, action => $action);
518 sub _route_controller_request {
520 my ($controller, $action, $request_type);
523 # Redirect simple requests to controller.pl without any GET/POST
524 # param to the login page.
525 $self->handle_login_error(error => 'action') if !$::form->{action};
527 # Show an error if the »action« parameter doesn't match the
528 # pattern »Controller/action«.
529 $::form->{action} =~ m|^ ( [A-Z] [A-Za-z0-9_]* ) / ( [a-z] [a-z0-9_]* ) ( \. [a-zA-Z]+ )? $|x || die "Unroutable request -- invalid controller/action.\n";
530 ($controller, $action) = ($1, $2);
531 delete $::form->{action};
533 $request_type = $3 ? lc(substr($3, 1)) : 'html';
537 $::form->{label_error} = $::request->{cgi}->pre($EVAL_ERROR);
538 show_error('generic/error');
541 return (controller => $controller, action => $action, request_type => $request_type);
544 sub _cache_file_modification_times {
547 return unless $self->_interface_is_fcgi && $::lx_office_conf{debug}->{restart_fcgi_process_on_changes};
553 return unless $File::Find::name =~ m/\.(?:pm|f?pl|html|conf|conf\.default)$/;
554 $fcgi_file_cache{ $File::Find::name } = (stat $File::Find::name)[9];
557 my $cwd = POSIX::getcwd();
558 File::Find::find($wanted, map { "${cwd}/${_}" } qw(config bin SL templates/webpages));
559 map { my $name = "${cwd}/${_}"; $fcgi_file_cache{$name} = (stat $name)[9] } qw(admin.pl dispatcher.fpl);
562 sub _watch_for_changed_files {
565 return unless $self->_interface_is_fcgi && $::lx_office_conf{debug}->{restart_fcgi_process_on_changes};
567 my $ok = all { (stat($_))[9] == $fcgi_file_cache{$_} } keys %fcgi_file_cache;
569 $::lxdebug->message(LXDebug::DEBUG1(), "Program modifications detected. Restarting.");
570 $self->restart_after_request(1);
573 sub get_standard_filehandles {
576 return $self->{interface} =~ m/f(?:ast)cgi/i ? $self->{request}->GetHandles() : (\*STDIN, \*STDOUT, \*STDERR);
579 sub _check_for_old_config_files {
580 my @old_files = grep { -f "config/${_}" } qw(authentication.pl console.conf lx-erp.conf lx-erp-local.conf);
581 return unless @old_files;
583 $::form->{title} = $::locale->text('Old configuration files');
585 print $::form->parse_html_template('login_screen/old_configuration_files', { FILES => \@old_files });
591 die SL::Dispatcher->END_OF_REQUEST;