Merge branch 'master' of vc.linet-services.de:public/lx-office-erp
[kivitendo-erp.git] / SL / Dispatcher.pm
1 package SL::Dispatcher;
2
3 use strict;
4
5 BEGIN {
6   use SL::System::Process;
7   my $exe_dir = SL::System::Process::exe_dir;
8
9   unshift @INC, "${exe_dir}/modules/override"; # Use our own versions of various modules (e.g. YAML).
10   push    @INC, "${exe_dir}/modules/fallback"; # Only use our own versions of modules if there's no system version.
11   unshift @INC, $exe_dir;
12 }
13
14 use CGI qw( -no_xhtml);
15 use Config::Std;
16 use DateTime;
17 use Encode;
18 use English qw(-no_match_vars);
19 use File::Basename;
20 use List::MoreUtils qw(all);
21 use List::Util qw(first);
22 use POSIX;
23 use SL::Auth;
24 use SL::Dispatcher::AuthHandler;
25 use SL::LXDebug;
26 use SL::LxOfficeConf;
27 use SL::Locale;
28 use SL::Common;
29 use SL::Form;
30 use SL::Helper::DateTime;
31 use SL::InstanceConfiguration;
32 use SL::Template::Plugin::HTMLFixes;
33
34 # Trailing new line is added so that Perl will not add the line
35 # number 'die' was called in.
36 use constant END_OF_REQUEST => "END-OF-REQUEST\n";
37
38 my %fcgi_file_cache;
39
40 sub new {
41   my ($class, $interface) = @_;
42
43   my $self           = bless {}, $class;
44   $self->{interface} = lc($interface || 'cgi');
45   $self->{auth_handler} = SL::Dispatcher::AuthHandler->new;
46
47   return $self;
48 }
49
50 sub interface_type {
51   my ($self) = @_;
52   return $self->{interface} eq 'cgi' ? 'CGI' : 'FastCGI';
53 }
54
55 sub pre_request_checks {
56   _check_for_old_config_files();
57
58   if (!$::auth->session_tables_present) {
59     if ($::form->{script} eq 'admin.pl') {
60       ::run();
61       ::end_of_request();
62     } else {
63       show_error('login_screen/auth_db_unreachable');
64     }
65   }
66 }
67
68 sub show_error {
69   $::lxdebug->enter_sub;
70   my $template             = shift;
71   my $error_type           = shift || '';
72   my %params               = @_;
73
74   $::myconfig{countrycode} = delete($params{countrycode}) || $::lx_office_conf{system}->{language};
75   $::locale                = Locale->new($::myconfig{countrycode});
76   $::form->{error}         = $::locale->text('The session is invalid or has expired.') if ($error_type eq 'session');
77   $::form->{error}         = $::locale->text('Incorrect password!')                    if ($error_type eq 'password');
78
79   $::form->header;
80   print $::form->parse_html_template($template, \%params);
81   $::lxdebug->leave_sub;
82
83   ::end_of_request();
84 }
85
86 sub pre_startup_setup {
87   my ($self) = @_;
88
89   SL::LxOfficeConf->read;
90
91   eval {
92     package main;
93     require "bin/mozilla/common.pl";
94     require "bin/mozilla/installationcheck.pl";
95   } or die $EVAL_ERROR;
96
97   # canonial globals. if it's not here, chances are it will get refactored someday.
98   {
99     no warnings 'once';
100     $::lxdebug     = LXDebug->new;
101     $::auth        = SL::Auth->new;
102     $::form        = undef;
103     %::myconfig    = ();
104     $::request     = undef;
105   }
106
107   $SIG{__WARN__} = sub {
108     $::lxdebug->warn(@_);
109   };
110
111   $self->_cache_file_modification_times;
112 }
113
114 sub pre_startup_checks {
115   ::verify_installation();
116 }
117
118 sub pre_startup {
119   my ($self) = @_;
120   $self->pre_startup_setup;
121   $self->pre_startup_checks;
122 }
123
124 sub require_main_code {
125   $::lxdebug->enter_sub;
126   my ($script, $suffix) = @_;
127
128   eval {
129     package main;
130     require "bin/mozilla/$script$suffix";
131   } or die $EVAL_ERROR;
132
133   if (-f "bin/mozilla/custom_$script$suffix") {
134     eval {
135       package main;
136       require "bin/mozilla/custom_$script$suffix";
137     };
138     $::form->error($EVAL_ERROR) if ($EVAL_ERROR);
139   }
140   if ($::form->{login} && -f "bin/mozilla/$::form->{login}_$script") {
141     eval {
142       package main;
143       require "bin/mozilla/$::form->{login}_$script";
144     };
145     $::form->error($EVAL_ERROR) if ($EVAL_ERROR);
146   }
147   $::lxdebug->leave_sub;
148 }
149
150 sub _require_controller {
151   my $controller =  shift;
152   $controller    =~ s|[^A-Za-z0-9_]||g;
153   $controller    =  "SL/Controller/${controller}";
154
155   eval {
156     package main;
157     require "${controller}.pm";
158   } or die $EVAL_ERROR;
159 }
160
161 sub _run_controller {
162   "SL::Controller::$_[0]"->new->_run_action($_[1]);
163 }
164
165 sub handle_request {
166   my $self         = shift;
167   $self->{request} = shift;
168
169   $::lxdebug->enter_sub;
170   $::lxdebug->begin_request;
171
172   my ($script, $path, $suffix, $script_name, $action, $routing_type);
173
174   $self->unrequire_bin_mozilla;
175
176   $::locale        = Locale->new($::lx_office_conf{system}->{language});
177   $::form          = Form->new;
178   $::instance_conf = SL::InstanceConfiguration->new;
179   $::request       = { cgi => CGI->new({}) };
180
181   my $session_result = $::auth->restore_session;
182   $::auth->create_or_refresh_session;
183
184   $::form->read_cgi_input;
185
186   eval { ($routing_type, $script_name, $action) = _route_request($ENV{SCRIPT_NAME}); 1; } or return;
187
188   if ($routing_type eq 'old') {
189     $::form->{action}  =  lc $::form->{action};
190     $::form->{action}  =~ s/( |-|,|\#)/_/g;
191
192    ($script, $path, $suffix) = fileparse($script_name, ".pl");
193     require_main_code($script, $suffix);
194
195     $::form->{script} = $script . $suffix;
196
197   } else {
198     _require_controller($script_name);
199     $::form->{script} = "controller.pl";
200   }
201
202   eval {
203     pre_request_checks();
204
205     $::form->error($::locale->text('System currently down for maintenance!')) if -e ($::lx_office_conf{paths}->{userspath} . "/nologin") && $script ne 'admin';
206
207     # For compatibility with a lot of database upgrade scripts etc:
208     # Re-write request to old 'login.pl?action=login' to new
209     # 'LoginScreen' controller. Make sure to load its code!
210     if (($script eq 'login') && ($action eq 'login')) {
211       ($routing_type, $script, $script_name, $action) = qw(controller controller LoginScreen login);
212       _require_controller('LoginScreen');
213     }
214
215     if (($script eq 'login') && !$action) {
216       print $::request->{cgi}->redirect('controller.pl?action=LoginScreen/user_login');
217
218     } elsif ($script eq 'admin') {
219       $::form->{titlebar} = "kivitendo " . $::locale->text('Version') . " $::form->{version}";
220       ::run($session_result);
221
222     } else {
223       show_error('login_screen/user_login', 'session') if SL::Auth::SESSION_EXPIRED == $session_result;
224
225       my %auth_result = $self->{auth_handler}->handle(
226         routing_type => $routing_type,
227         script       => $script,
228         controller   => $script_name,
229         action       => $action,
230       );
231
232       delete @{ $::form }{ grep { m/^\{AUTH\}/ } keys %{ $::form } } unless $auth_result{keep_auth_vars};
233
234       if ($action) {
235         $::instance_conf->init if $auth_result{auth_level} eq 'user';
236
237         map { $::form->{$_} = $::myconfig{$_} } qw(charset)
238           unless $action eq 'save' && $::form->{type} eq 'preferences';
239
240         $::form->set_standard_title;
241         if ($routing_type eq 'old') {
242           ::call_sub('::' . $::locale->findsub($action));
243         } else {
244           _run_controller($script_name, $action);
245         }
246       } else {
247         $::form->error($::locale->text('action= not defined!'));
248       }
249     }
250
251     1;
252   } or do {
253     if ($EVAL_ERROR ne END_OF_REQUEST) {
254       print STDERR $EVAL_ERROR;
255       $::form->{label_error} = $::request->{cgi}->pre($EVAL_ERROR);
256       chdir SL::System::Process::exe_dir;
257       eval { show_error('generic/error') };
258     }
259   };
260
261   # cleanup
262   $::auth->save_session;
263   $::auth->expire_sessions;
264   $::auth->reset;
265
266   $::locale   = undef;
267   $::form     = undef;
268   $::myconfig = ();
269   $::request  = undef;
270   Form::disconnect_standard_dbh;
271
272   $::lxdebug->end_request;
273
274   $self->_watch_for_changed_files;
275
276   $::lxdebug->leave_sub;
277 }
278
279 sub unrequire_bin_mozilla {
280   my $self = shift;
281   return unless $self->_interface_is_fcgi;
282
283   for (keys %INC) {
284     next unless m#^bin/mozilla/#;
285     next if /\bcommon.pl$/;
286     next if /\binstallationcheck.pl$/;
287     delete $INC{$_};
288   }
289 }
290
291 sub _interface_is_fcgi {
292   my $self = shift;
293   return $self->{interface} =~ m/^(?:fastcgi|fcgid|fcgi)$/;
294 }
295
296 sub _route_request {
297   my $script_name = shift;
298
299   return $script_name =~ m/dispatcher\.pl$/ ? ('old',        _route_dispatcher_request())
300        : $script_name =~ m/controller\.pl/  ? ('controller', _route_controller_request())
301        :                                      ('old',        $script_name, $::form->{action});
302 }
303
304 sub _route_dispatcher_request {
305   my $name_re = qr{[a-z]\w*};
306   my ($script_name, $action);
307
308   eval {
309     die "Unroutable request -- inavlid module name.\n" if !$::form->{M} || ($::form->{M} !~ m/^${name_re}$/);
310     $script_name = $::form->{M} . '.pl';
311
312     if ($::form->{A}) {
313       $action = $::form->{A};
314
315     } else {
316       $action = first { m/^A_${name_re}$/ } keys %{ $::form };
317       die "Unroutable request -- inavlid action name.\n" if !$action;
318
319       delete $::form->{$action};
320       $action = substr $action, 2;
321     }
322
323     delete @{$::form}{qw(M A)};
324
325     1;
326   } or do {
327     $::form->{label_error} = $::request->{cgi}->pre($EVAL_ERROR);
328     show_error('generic/error');
329   };
330
331   return ($script_name, $action);
332 }
333
334 sub _route_controller_request {
335   my ($controller, $action);
336
337   eval {
338     $::form->{action}      =~ m|^ ( [A-Z] [A-Za-z0-9_]* ) / ( [a-z] [a-z0-9_]* ) $|x || die "Unroutable request -- inavlid controller/action.\n";
339     ($controller, $action) =  ($1, $2);
340     delete $::form->{action};
341
342     1;
343   } or do {
344     $::form->{label_error} = $::request->{cgi}->pre($EVAL_ERROR);
345     show_error('generic/error');
346   };
347
348   return ($controller, $action);
349 }
350
351 sub _cache_file_modification_times {
352   my ($self) = @_;
353
354   return unless $self->_interface_is_fcgi && $::lx_office_conf{debug}->{restart_fcgi_process_on_changes};
355
356   require File::Find;
357   require POSIX;
358
359   my $wanted = sub {
360     return unless $File::Find::name =~ m/\.(?:pm|f?pl|html|conf|conf\.default)$/;
361     $fcgi_file_cache{ $File::Find::name } = (stat $File::Find::name)[9];
362   };
363
364   my $cwd = POSIX::getcwd();
365   File::Find::find($wanted, map { "${cwd}/${_}" } qw(config bin SL templates/webpages));
366   map { my $name = "${cwd}/${_}"; $fcgi_file_cache{$name} = (stat $name)[9] } qw(admin.pl dispatcher.fpl);
367 }
368
369 sub _watch_for_changed_files {
370   my ($self) = @_;
371
372   return unless $self->_interface_is_fcgi && $::lx_office_conf{debug}->{restart_fcgi_process_on_changes};
373
374   my $ok = all { (stat($_))[9] == $fcgi_file_cache{$_} } keys %fcgi_file_cache;
375   return if $ok;
376   $::lxdebug->message(LXDebug::DEBUG1(), "Program modifications detected. Restarting.");
377   exit;
378 }
379
380 sub get_standard_filehandles {
381   my $self = shift;
382
383   return $self->{interface} =~ m/f(?:ast)cgi/i ? $self->{request}->GetHandles() : (\*STDIN, \*STDOUT, \*STDERR);
384 }
385
386 sub _check_for_old_config_files {
387   my @old_files = grep { -f "config/${_}" } qw(authentication.pl console.conf lx-erp.conf lx-erp-local.conf);
388   return unless @old_files;
389
390   $::form->{title} = $::locale->text('Old configuration files');
391   $::form->header;
392   print $::form->parse_html_template('login_screen/old_configuration_files', { FILES => \@old_files });
393
394   ::end_of_request();
395 }
396
397 package main;
398
399 use strict;
400
401 sub end_of_request {
402   die SL::Dispatcher->END_OF_REQUEST;
403 }
404
405 1;