epic-ts
[kivitendo-erp.git] / SL / Dispatcher.pm
1 package SL::Dispatcher;
2
3 use strict;
4
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')
9
10 BEGIN {
11   use SL::System::Process;
12   my $exe_dir = SL::System::Process::exe_dir;
13
14   unshift @INC, "${exe_dir}/modules/override"; # Use our own versions of various modules (e.g. YAML).
15   push    @INC, "${exe_dir}/modules/fallback"; # Only use our own versions of modules if there's no system version.
16   unshift @INC, $exe_dir;
17 }
18
19 use Carp;
20 use CGI qw( -no_xhtml);
21 use Config::Std;
22 use DateTime;
23 use Encode;
24 use English qw(-no_match_vars);
25 use File::Basename;
26 use List::MoreUtils qw(all);
27 use List::Util qw(first);
28 use SL::ArchiveZipFixes;
29 use SL::Auth;
30 use SL::Dispatcher::AuthHandler;
31 use SL::LXDebug;
32 use SL::LxOfficeConf;
33 use SL::Locale;
34 use SL::ClientJS;
35 use SL::Common;
36 use SL::Form;
37 use SL::Helper::DateTime;
38 use SL::InstanceConfiguration;
39 use SL::Template::Plugin::HTMLFixes;
40 use SL::User;
41
42 # Trailing new line is added so that Perl will not add the line
43 # number 'die' was called in.
44 use constant END_OF_REQUEST => "END-OF-REQUEST\n";
45
46 my %fcgi_file_cache;
47
48 sub new {
49   my ($class, $interface) = @_;
50
51   my $self           = bless {}, $class;
52   $self->{interface} = lc($interface || 'cgi');
53   $self->{auth_handler} = SL::Dispatcher::AuthHandler->new;
54
55   SL::ArchiveZipFixes->apply_fixes;
56
57   return $self;
58 }
59
60 sub interface_type {
61   my ($self) = @_;
62   return $self->{interface} eq 'cgi' ? 'CGI' : 'FastCGI';
63 }
64
65 sub is_admin_request {
66   my %params = @_;
67   return ($params{script} eq 'admin.pl') || (($params{routing_type} eq 'controller') && ($params{script_name} eq 'Admin'));
68 }
69
70 sub pre_request_checks {
71   my (%params) = @_;
72
73   _check_for_old_config_files();
74
75   if (!$::auth->session_tables_present && !is_admin_request(%params)) {
76     show_error('login_screen/auth_db_unreachable');
77   }
78
79   if ($::request->type !~ m/^ (?: html | js | json ) $/x) {
80     die $::locale->text("Invalid request type '#1'", $::request->type);
81   }
82 }
83
84 sub pre_request_initialization {
85   my ($self, %params) = @_;
86
87   $self->unrequire_bin_mozilla;
88
89   $::locale        = Locale->new($::lx_office_conf{system}->{language});
90   $::form          = Form->new;
91   $::instance_conf = SL::InstanceConfiguration->new;
92   $::request       = SL::Request->new(
93     cgi            => CGI->new({}),
94     layout         => SL::Layout::None->new,
95   );
96
97   my $session_result = $::auth->restore_session;
98   $::auth->create_or_refresh_session;
99
100   if ($params{client}) {
101     $::auth->set_client($params{client}) || die("cannot find client " . $params{client});
102
103     if ($params{login}) {
104       die "cannot find user " . $params{login}            unless %::myconfig = $::auth->read_user(login => $params{login});
105       die "cannot find locale for user " . $params{login} unless $::locale   = Locale->new($::myconfig{countrycode});
106
107       $::form->{login} = $params{login}; # normaly implicit at login
108     }
109   }
110
111   return $session_result;
112 }
113
114 sub render_error_ajax {
115   my ($error) = @_;
116
117   SL::ClientJS->new
118     ->error($error)
119     ->render(SL::Controller::Base->new);
120 }
121
122 sub show_error {
123   $::lxdebug->enter_sub;
124   my $template             = shift;
125   my $error_type           = shift || '';
126   my %params               = @_;
127
128   $::myconfig{countrycode} = delete($params{countrycode}) || $::lx_office_conf{system}->{language};
129   $::locale                = Locale->new($::myconfig{countrycode});
130   $::form->{error}         = $::locale->text('The session is invalid or has expired.') if ($error_type eq 'session');
131   $::form->{error}         = $::locale->text('Incorrect password!')                    if ($error_type eq 'password');
132   $::form->{error}         = $::locale->text('The action is missing or invalid.')      if ($error_type eq 'action');
133
134   return render_error_ajax($::form->{error}) if $::request->is_ajax;
135
136   $::form->header;
137   print $::form->parse_html_template($template, \%params);
138   $::lxdebug->leave_sub;
139
140   ::end_of_request();
141 }
142
143 sub pre_startup_setup {
144   my ($self) = @_;
145
146   SL::LxOfficeConf->read;
147
148   eval {
149     package main;
150     require "bin/mozilla/common.pl";
151     require "bin/mozilla/installationcheck.pl";
152   } or die $EVAL_ERROR;
153
154   # canonial globals. if it's not here, chances are it will get refactored someday.
155   {
156     no warnings 'once';
157     $::lxdebug     = LXDebug->new;
158     $::auth        = SL::Auth->new;
159     $::form        = undef;
160     $::request     = undef;
161     %::myconfig    = User->get_default_myconfig;
162   }
163
164   $SIG{__WARN__} = sub {
165     $::lxdebug->warn(@_);
166   };
167
168   $SIG{__DIE__} = sub { Carp::confess( @_ ) } if $::lx_office_conf{debug}->{backtrace_on_die};
169
170   $self->_cache_file_modification_times;
171 }
172
173 sub pre_startup_checks {
174   ::verify_installation();
175 }
176
177 sub pre_startup {
178   my ($self) = @_;
179   $self->pre_startup_setup;
180   $self->pre_startup_checks;
181 }
182
183 sub require_main_code {
184   $::lxdebug->enter_sub;
185   my ($script, $suffix) = @_;
186
187   eval {
188     package main;
189     require "bin/mozilla/$script$suffix";
190   } or die $EVAL_ERROR;
191
192   if (-f "bin/mozilla/custom_$script$suffix") {
193     eval {
194       package main;
195       require "bin/mozilla/custom_$script$suffix";
196     };
197     $::form->error($EVAL_ERROR) if ($EVAL_ERROR);
198   }
199   if ($::form->{login} && -f "bin/mozilla/$::form->{login}_$script") {
200     eval {
201       package main;
202       require "bin/mozilla/$::form->{login}_$script";
203     };
204     $::form->error($EVAL_ERROR) if ($EVAL_ERROR);
205   }
206   $::lxdebug->leave_sub;
207 }
208
209 sub _require_controller {
210   my $controller =  shift;
211   $controller    =~ s|[^A-Za-z0-9_]||g;
212   $controller    =  "SL/Controller/${controller}";
213
214   eval {
215     package main;
216     require "${controller}.pm";
217   } or die $EVAL_ERROR;
218 }
219
220 sub _run_controller {
221   "SL::Controller::$_[0]"->new->_run_action($_[1]);
222 }
223
224 sub handle_request {
225   my $self         = shift;
226   $self->{request} = shift;
227
228   $::lxdebug->enter_sub;
229   $::lxdebug->begin_request;
230
231   my ($script, $path, $suffix, $script_name, $action, $routing_type);
232
233   my $session_result = $self->pre_request_initialization;
234
235   $::form->read_cgi_input;
236
237   my %routing;
238   eval { %routing = $self->_route_request($ENV{SCRIPT_NAME}); 1; } or return;
239   ($routing_type, $script_name, $action) = @routing{qw(type controller action)};
240   $::lxdebug->log_request($routing_type, $script_name, $action);
241
242   $::request->type(lc($routing{request_type} || 'html'));
243
244   if ($routing_type eq 'old') {
245     $::form->{action}  =  lc $::form->{action};
246     $::form->{action}  =~ s/( |-|,|\#)/_/g;
247
248    ($script, $path, $suffix) = fileparse($script_name, ".pl");
249     require_main_code($script, $suffix) unless $script eq 'admin';
250
251     $::form->{script} = $script . $suffix;
252
253   } else {
254     _require_controller($script_name);
255     $::form->{script} = "controller.pl";
256   }
257
258   eval {
259     pre_request_checks(script => $script, action => $action, routing_type => $routing_type, script_name => $script_name);
260
261     if (   SL::System::InstallationLock->is_locked
262         && !is_admin_request(script => $script, script_name => $script_name, routing_type => $routing_type)) {
263       $::form->error($::locale->text('System currently down for maintenance!'));
264     }
265
266     # For compatibility with a lot of database upgrade scripts etc:
267     # Re-write request to old 'login.pl?action=login' to new
268     # 'LoginScreen' controller. Make sure to load its code!
269     if (($script eq 'login') && ($action eq 'login')) {
270       ($routing_type, $script, $script_name, $action) = qw(controller controller LoginScreen login);
271       _require_controller('LoginScreen');
272     }
273
274     if (   (($script eq 'login') && !$action)
275         || ($script eq 'admin')
276         || (SL::Auth::SESSION_EXPIRED() == $session_result)) {
277       $self->redirect_to_login(script => $script, error => 'session');
278
279     }
280
281     my %auth_result = $self->{auth_handler}->handle(
282       routing_type => $routing_type,
283       script       => $script,
284       controller   => $script_name,
285       action       => $action,
286     );
287
288     ::end_of_request() unless $auth_result{auth_ok};
289
290     delete @{ $::form }{ grep { m/^\{AUTH\}/ } keys %{ $::form } } unless $auth_result{keep_auth_vars};
291
292     if ($action) {
293       $::form->set_standard_title;
294       if ($routing_type eq 'old') {
295         ::call_sub('::' . $::locale->findsub($action));
296       } else {
297         _run_controller($script_name, $action);
298       }
299     } else {
300       $::form->error($::locale->text('action= not defined!'));
301     }
302
303     1;
304   } or do {
305     if (substr($EVAL_ERROR, 0, length(END_OF_REQUEST())) ne END_OF_REQUEST()) {
306       my $error = $EVAL_ERROR;
307       print STDERR $error;
308
309       if ($::request->is_ajax) {
310         eval { render_error_ajax($error) };
311       } else {
312         $::form->{label_error} = $::request->{cgi}->pre($error);
313         chdir SL::System::Process::exe_dir;
314         eval { show_error('generic/error') };
315       }
316     }
317   };
318
319   $::form->footer;
320
321   if ($self->_interface_is_fcgi) {
322     # fcgi? send send reponse on its way before cleanup.
323     $self->{request}->Flush;
324     $self->{request}->Finish;
325   }
326
327   $::lxdebug->end_request;
328
329   # cleanup
330   $::auth->save_session;
331   $::auth->expire_sessions;
332   $::auth->reset;
333
334   $::locale   = undef;
335   $::form     = undef;
336   $::myconfig = ();
337   $::request  = undef;
338
339   SL::DBConnect::Cache->reset_all;
340   Form::disconnect_standard_dbh;
341
342   $self->_watch_for_changed_files;
343
344   $::lxdebug->leave_sub;
345 }
346
347 sub redirect_to_login {
348   my ($self, %params) = @_;
349   my $action          = ($params{script} // '') =~ m/^admin/i ? 'Admin/login' : 'LoginScreen/user_login';
350   $action            .= '&error=' . $params{error} if $params{error};
351
352   print $::request->cgi->redirect("controller.pl?action=${action}");
353   ::end_of_request();
354 }
355
356 sub unrequire_bin_mozilla {
357   my $self = shift;
358   return unless $self->_interface_is_fcgi;
359
360   for (keys %INC) {
361     next unless m#^bin/mozilla/#;
362     next if /\bcommon.pl$/;
363     next if /\binstallationcheck.pl$/;
364     delete $INC{$_};
365   }
366 }
367
368 sub _interface_is_fcgi {
369   my $self = shift;
370   return $self->{interface} =~ m/^(?:fastcgi|fcgid|fcgi)$/;
371 }
372
373 sub _route_request {
374   my ($self, $script_name) = @_;
375
376   return $script_name =~ m/dispatcher\.pl$/ ? (type => 'old',        $self->_route_dispatcher_request)
377        : $script_name =~ m/controller\.pl/  ? (type => 'controller', $self->_route_controller_request)
378        :                                      (type => 'old',        controller => $script_name, action => $::form->{action});
379 }
380
381 sub _route_dispatcher_request {
382   my ($self)  = @_;
383   my $name_re = qr{[a-z]\w*};
384   my ($script_name, $action);
385
386   eval {
387     die "Unroutable request -- invalid module name.\n" if !$::form->{M} || ($::form->{M} !~ m/^${name_re}$/);
388     $script_name = $::form->{M} . '.pl';
389
390     if ($::form->{A}) {
391       $action = $::form->{A};
392
393     } else {
394       $action = first { m/^A_${name_re}$/ } keys %{ $::form };
395       die "Unroutable request -- invalid action name.\n" if !$action;
396
397       delete $::form->{$action};
398       $action = substr $action, 2;
399     }
400
401     delete @{$::form}{qw(M A)};
402
403     1;
404   } or do {
405     $::form->{label_error} = $::request->{cgi}->pre($EVAL_ERROR);
406     show_error('generic/error');
407   };
408
409   return (controller => $script_name, action => $action);
410 }
411
412 sub _route_controller_request {
413   my ($self) = @_;
414   my ($controller, $action, $request_type);
415
416   eval {
417     # Redirect simple requests to controller.pl without any GET/POST
418     # param to the login page.
419     $self->redirect_to_login(error => 'action') if !$::form->{action};
420
421     # Show an error if the »action« parameter doesn't match the
422     # pattern »Controller/action«.
423     $::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";
424     ($controller, $action) =  ($1, $2);
425     delete $::form->{action};
426
427     $request_type = $3 ? lc(substr($3, 1)) : 'html';
428
429     1;
430   } or do {
431     $::form->{label_error} = $::request->{cgi}->pre($EVAL_ERROR);
432     show_error('generic/error');
433   };
434
435   return (controller => $controller, action => $action, request_type => $request_type);
436 }
437
438 sub _cache_file_modification_times {
439   my ($self) = @_;
440
441   return unless $self->_interface_is_fcgi && $::lx_office_conf{debug}->{restart_fcgi_process_on_changes};
442
443   require File::Find;
444   require POSIX;
445
446   my $wanted = sub {
447     return unless $File::Find::name =~ m/\.(?:pm|f?pl|html|conf|conf\.default)$/;
448     $fcgi_file_cache{ $File::Find::name } = (stat $File::Find::name)[9];
449   };
450
451   my $cwd = POSIX::getcwd();
452   File::Find::find($wanted, map { "${cwd}/${_}" } qw(config bin SL templates/webpages));
453   map { my $name = "${cwd}/${_}"; $fcgi_file_cache{$name} = (stat $name)[9] } qw(admin.pl dispatcher.fpl);
454 }
455
456 sub _watch_for_changed_files {
457   my ($self) = @_;
458
459   return unless $self->_interface_is_fcgi && $::lx_office_conf{debug}->{restart_fcgi_process_on_changes};
460
461   my $ok = all { (stat($_))[9] == $fcgi_file_cache{$_} } keys %fcgi_file_cache;
462   return if $ok;
463   $::lxdebug->message(LXDebug::DEBUG1(), "Program modifications detected. Restarting.");
464   exit;
465 }
466
467 sub get_standard_filehandles {
468   my $self = shift;
469
470   return $self->{interface} =~ m/f(?:ast)cgi/i ? $self->{request}->GetHandles() : (\*STDIN, \*STDOUT, \*STDERR);
471 }
472
473 sub _check_for_old_config_files {
474   my @old_files = grep { -f "config/${_}" } qw(authentication.pl console.conf lx-erp.conf lx-erp-local.conf);
475   return unless @old_files;
476
477   $::form->{title} = $::locale->text('Old configuration files');
478   $::form->header;
479   print $::form->parse_html_template('login_screen/old_configuration_files', { FILES => \@old_files });
480
481   ::end_of_request();
482 }
483
484 package main;
485
486 use strict;
487
488 sub end_of_request {
489   die SL::Dispatcher->END_OF_REQUEST;
490 }
491
492 1;