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);
22 use SL::ArchiveZipFixes;
24 use SL::Dispatcher::AuthHandler;
31 use SL::Helper::DateTime;
32 use SL::InstanceConfiguration;
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 SL::ArchiveZipFixes->apply_fixes;
55 # Initialize character type locale to be UTF-8 instead of C:
56 foreach my $locale (qw(de_DE.UTF-8 en_US.UTF-8)) {
57 last if setlocale('LC_CTYPE', $locale);
65 return $self->{interface} eq 'cgi' ? 'CGI' : 'FastCGI';
68 sub is_admin_request {
70 return ($params{script} eq 'admin.pl') || (($params{routing_type} eq 'controller') && ($params{script_name} eq 'Admin'));
73 sub pre_request_checks {
76 _check_for_old_config_files();
78 if (!$::auth->session_tables_present && !is_admin_request(%params)) {
79 show_error('login_screen/auth_db_unreachable');
82 if ($::request->type !~ m/^ (?: html | js | json ) $/x) {
83 die $::locale->text("Invalid request type '#1'", $::request->type);
87 sub pre_request_initialization {
88 my ($self, %params) = @_;
90 $self->unrequire_bin_mozilla;
92 $::locale = Locale->new($::lx_office_conf{system}->{language});
94 $::instance_conf = SL::InstanceConfiguration->new;
95 $::request = SL::Request->new(
97 layout => SL::Layout::None->new,
100 my $session_result = $::auth->restore_session;
101 $::auth->create_or_refresh_session;
103 if ($params{client}) {
104 $::auth->set_client($params{client}) || die("cannot find client " . $params{client});
106 if ($params{login}) {
107 die "cannot find user " . $params{login} unless %::myconfig = $::auth->read_user(login => $params{login});
108 die "cannot find locale for user " . $params{login} unless $::locale = Locale->new($::myconfig{countrycode});
110 $::form->{login} = $params{login}; # normaly implicit at login
114 return $session_result;
117 sub render_error_ajax {
122 ->render(SL::Controller::Base->new);
126 $::lxdebug->enter_sub;
127 my $template = shift;
128 my $error_type = shift || '';
131 $::myconfig{countrycode} = delete($params{countrycode}) || $::lx_office_conf{system}->{language};
132 $::locale = Locale->new($::myconfig{countrycode});
133 $::form->{error} = $::locale->text('The session is invalid or has expired.') if ($error_type eq 'session');
134 $::form->{error} = $::locale->text('Incorrect password!') if ($error_type eq 'password');
135 $::form->{error} = $::locale->text('The action is missing or invalid.') if ($error_type eq 'action');
137 return render_error_ajax($::form->{error}) if $::request->is_ajax;
140 print $::form->parse_html_template($template, \%params);
141 $::lxdebug->leave_sub;
146 sub pre_startup_setup {
149 SL::LxOfficeConf->read;
153 require "bin/mozilla/common.pl";
154 require "bin/mozilla/installationcheck.pl";
155 } or die $EVAL_ERROR;
157 # canonial globals. if it's not here, chances are it will get refactored someday.
160 $::lxdebug = LXDebug->new;
161 $::auth = SL::Auth->new;
164 %::myconfig = User->get_default_myconfig;
167 $SIG{__WARN__} = sub {
168 $::lxdebug->warn(@_);
171 $SIG{__DIE__} = sub { Carp::confess( @_ ) } if $::lx_office_conf{debug}->{backtrace_on_die};
173 $self->_cache_file_modification_times;
176 sub pre_startup_checks {
177 ::verify_installation();
182 $self->pre_startup_setup;
183 $self->pre_startup_checks;
186 sub require_main_code {
187 $::lxdebug->enter_sub;
188 my ($script, $suffix) = @_;
192 require "bin/mozilla/$script$suffix";
193 } or die $EVAL_ERROR;
195 if (-f "bin/mozilla/custom_$script$suffix") {
198 require "bin/mozilla/custom_$script$suffix";
200 $::form->error($EVAL_ERROR) if ($EVAL_ERROR);
202 if ($::form->{login} && -f "bin/mozilla/$::form->{login}_$script") {
205 require "bin/mozilla/$::form->{login}_$script";
207 $::form->error($EVAL_ERROR) if ($EVAL_ERROR);
209 $::lxdebug->leave_sub;
212 sub _require_controller {
213 my $controller = shift;
214 $controller =~ s|[^A-Za-z0-9_]||g;
215 $controller = "SL/Controller/${controller}";
219 require "${controller}.pm";
220 } or die $EVAL_ERROR;
223 sub _run_controller {
224 "SL::Controller::$_[0]"->new->_run_action($_[1]);
227 sub handle_all_requests {
230 my $request = FCGI::Request();
231 while ($request->Accept() >= 0) {
232 $self->handle_request($request);
234 $self->restart_after_request(1) if $self->_interface_is_fcgi && SL::System::Process::memory_usage_is_too_high();
235 $request->LastCall if $self->restart_after_request;
238 exec $0 if $self->restart_after_request;
243 $self->{request} = shift;
245 $::lxdebug->enter_sub;
246 $::lxdebug->begin_request;
248 my ($script, $path, $suffix, $script_name, $action, $routing_type);
250 my $session_result = $self->pre_request_initialization;
252 $::form->read_cgi_input;
255 eval { %routing = $self->_route_request($ENV{SCRIPT_NAME}); 1; } or return;
256 ($routing_type, $script_name, $action) = @routing{qw(type controller action)};
257 $::lxdebug->log_request($routing_type, $script_name, $action);
259 $::request->type(lc($routing{request_type} || 'html'));
261 if ($routing_type eq 'old') {
262 $::form->{action} = lc $::form->{action};
263 $::form->{action} =~ s/( |-|,|\#)/_/g;
265 ($script, $path, $suffix) = fileparse($script_name, ".pl");
266 require_main_code($script, $suffix) unless $script eq 'admin';
268 $::form->{script} = $script . $suffix;
271 _require_controller($script_name);
272 $::form->{script} = "controller.pl";
276 pre_request_checks(script => $script, action => $action, routing_type => $routing_type, script_name => $script_name);
278 if ( SL::System::InstallationLock->is_locked
279 && !is_admin_request(script => $script, script_name => $script_name, routing_type => $routing_type)) {
280 $::form->error($::locale->text('System currently down for maintenance!'));
283 # For compatibility with a lot of database upgrade scripts etc:
284 # Re-write request to old 'login.pl?action=login' to new
285 # 'LoginScreen' controller. Make sure to load its code!
286 if (($script eq 'login') && ($action eq 'login')) {
287 ($routing_type, $script, $script_name, $action) = qw(controller controller LoginScreen login);
288 _require_controller('LoginScreen');
291 if ( (($script eq 'login') && !$action)
292 || ($script eq 'admin')
293 || (SL::Auth::SESSION_EXPIRED() == $session_result)) {
294 $self->redirect_to_login(script => $script, error => 'session');
298 my %auth_result = $self->{auth_handler}->handle(
299 routing_type => $routing_type,
301 controller => $script_name,
305 $self->end_request unless $auth_result{auth_ok};
307 delete @{ $::form }{ grep { m/^\{AUTH\}/ } keys %{ $::form } } unless $auth_result{keep_auth_vars};
310 $::form->set_standard_title;
311 if ($routing_type eq 'old') {
312 ::call_sub('::' . $::locale->findsub($action));
314 _run_controller($script_name, $action);
317 $::form->error($::locale->text('action= not defined!'));
322 if (substr($EVAL_ERROR, 0, length(END_OF_REQUEST())) ne END_OF_REQUEST()) {
323 my $error = $EVAL_ERROR;
326 if ($::request->is_ajax) {
327 eval { render_error_ajax($error) };
329 $::form->{label_error} = $::request->{cgi}->pre($error);
330 chdir SL::System::Process::exe_dir;
331 eval { show_error('generic/error') };
338 if ($self->_interface_is_fcgi) {
339 # fcgi? send send reponse on its way before cleanup.
340 $self->{request}->Flush;
341 $self->{request}->Finish;
344 $::lxdebug->end_request(routing_type => $routing_type, script_name => $script_name, action => $action);
347 $::auth->save_session;
348 $::auth->expire_sessions;
356 SL::DBConnect::Cache->reset_all;
358 $self->_watch_for_changed_files;
360 $::lxdebug->leave_sub;
363 sub redirect_to_login {
364 my ($self, %params) = @_;
365 my $action = ($params{script} // '') =~ m/^admin/i ? 'Admin/login' : 'LoginScreen/user_login';
366 $action .= '&error=' . $params{error} if $params{error};
368 print $::request->cgi->redirect("controller.pl?action=${action}");
372 sub unrequire_bin_mozilla {
374 return unless $self->_interface_is_fcgi;
377 next unless m#^bin/mozilla/#;
378 next if /\bcommon.pl$/;
379 next if /\binstallationcheck.pl$/;
384 sub _interface_is_fcgi {
386 return $self->{interface} =~ m/^(?:fastcgi|fcgid|fcgi)$/;
390 my ($self, $script_name) = @_;
392 return $script_name =~ m/dispatcher\.pl$/ ? (type => 'old', $self->_route_dispatcher_request)
393 : $script_name =~ m/controller\.pl/ ? (type => 'controller', $self->_route_controller_request)
394 : (type => 'old', controller => $script_name, action => $::form->{action});
397 sub _route_dispatcher_request {
399 my $name_re = qr{[a-z]\w*};
400 my ($script_name, $action);
403 die "Unroutable request -- invalid module name.\n" if !$::form->{M} || ($::form->{M} !~ m/^${name_re}$/);
404 $script_name = $::form->{M} . '.pl';
407 $action = $::form->{A};
410 $action = first { m/^A_${name_re}$/ } keys %{ $::form };
411 die "Unroutable request -- invalid action name.\n" if !$action;
413 delete $::form->{$action};
414 $action = substr $action, 2;
417 delete @{$::form}{qw(M A)};
421 $::form->{label_error} = $::request->{cgi}->pre($EVAL_ERROR);
422 show_error('generic/error');
425 return (controller => $script_name, action => $action);
428 sub _route_controller_request {
430 my ($controller, $action, $request_type);
433 # Redirect simple requests to controller.pl without any GET/POST
434 # param to the login page.
435 $self->redirect_to_login(error => 'action') if !$::form->{action};
437 # Show an error if the »action« parameter doesn't match the
438 # pattern »Controller/action«.
439 $::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";
440 ($controller, $action) = ($1, $2);
441 delete $::form->{action};
443 $request_type = $3 ? lc(substr($3, 1)) : 'html';
447 $::form->{label_error} = $::request->{cgi}->pre($EVAL_ERROR);
448 show_error('generic/error');
451 return (controller => $controller, action => $action, request_type => $request_type);
454 sub _cache_file_modification_times {
457 return unless $self->_interface_is_fcgi && $::lx_office_conf{debug}->{restart_fcgi_process_on_changes};
463 return unless $File::Find::name =~ m/\.(?:pm|f?pl|html|conf|conf\.default)$/;
464 $fcgi_file_cache{ $File::Find::name } = (stat $File::Find::name)[9];
467 my $cwd = POSIX::getcwd();
468 File::Find::find($wanted, map { "${cwd}/${_}" } qw(config bin SL templates/webpages));
469 map { my $name = "${cwd}/${_}"; $fcgi_file_cache{$name} = (stat $name)[9] } qw(admin.pl dispatcher.fpl);
472 sub _watch_for_changed_files {
475 return unless $self->_interface_is_fcgi && $::lx_office_conf{debug}->{restart_fcgi_process_on_changes};
477 my $ok = all { (stat($_))[9] == $fcgi_file_cache{$_} } keys %fcgi_file_cache;
479 $::lxdebug->message(LXDebug::DEBUG1(), "Program modifications detected. Restarting.");
480 $self->restart_after_request(1);
483 sub get_standard_filehandles {
486 return $self->{interface} =~ m/f(?:ast)cgi/i ? $self->{request}->GetHandles() : (\*STDIN, \*STDOUT, \*STDERR);
489 sub _check_for_old_config_files {
490 my @old_files = grep { -f "config/${_}" } qw(authentication.pl console.conf lx-erp.conf lx-erp-local.conf);
491 return unless @old_files;
493 $::form->{title} = $::locale->text('Old configuration files');
495 print $::form->parse_html_template('login_screen/old_configuration_files', { FILES => \@old_files });
501 die SL::Dispatcher->END_OF_REQUEST;