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