Auch das Installationsbasisverzeichnis in @INC aufnehmen
[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       eval { show_error('generic/error') };
257     }
258   };
259
260   # cleanup
261   $::auth->save_session;
262   $::auth->expire_sessions;
263   $::auth->reset;
264
265   $::locale   = undef;
266   $::form     = undef;
267   $::myconfig = ();
268   $::request  = undef;
269   Form::disconnect_standard_dbh;
270
271   $::lxdebug->end_request;
272
273   $self->_watch_for_changed_files;
274
275   $::lxdebug->leave_sub;
276 }
277
278 sub unrequire_bin_mozilla {
279   my $self = shift;
280   return unless $self->_interface_is_fcgi;
281
282   for (keys %INC) {
283     next unless m#^bin/mozilla/#;
284     next if /\bcommon.pl$/;
285     next if /\binstallationcheck.pl$/;
286     delete $INC{$_};
287   }
288 }
289
290 sub _interface_is_fcgi {
291   my $self = shift;
292   return $self->{interface} =~ m/^(?:fastcgi|fcgid|fcgi)$/;
293 }
294
295 sub _route_request {
296   my $script_name = shift;
297
298   return $script_name =~ m/dispatcher\.pl$/ ? ('old',        _route_dispatcher_request())
299        : $script_name =~ m/controller\.pl/  ? ('controller', _route_controller_request())
300        :                                      ('old',        $script_name, $::form->{action});
301 }
302
303 sub _route_dispatcher_request {
304   my $name_re = qr{[a-z]\w*};
305   my ($script_name, $action);
306
307   eval {
308     die "Unroutable request -- inavlid module name.\n" if !$::form->{M} || ($::form->{M} !~ m/^${name_re}$/);
309     $script_name = $::form->{M} . '.pl';
310
311     if ($::form->{A}) {
312       $action = $::form->{A};
313
314     } else {
315       $action = first { m/^A_${name_re}$/ } keys %{ $::form };
316       die "Unroutable request -- inavlid action name.\n" if !$action;
317
318       delete $::form->{$action};
319       $action = substr $action, 2;
320     }
321
322     delete @{$::form}{qw(M A)};
323
324     1;
325   } or do {
326     $::form->{label_error} = $::request->{cgi}->pre($EVAL_ERROR);
327     show_error('generic/error');
328   };
329
330   return ($script_name, $action);
331 }
332
333 sub _route_controller_request {
334   my ($controller, $action);
335
336   eval {
337     $::form->{action}      =~ m|^ ( [A-Z] [A-Za-z0-9_]* ) / ( [a-z] [a-z0-9_]* ) $|x || die "Unroutable request -- inavlid controller/action.\n";
338     ($controller, $action) =  ($1, $2);
339     delete $::form->{action};
340
341     1;
342   } or do {
343     $::form->{label_error} = $::request->{cgi}->pre($EVAL_ERROR);
344     show_error('generic/error');
345   };
346
347   return ($controller, $action);
348 }
349
350 sub _cache_file_modification_times {
351   my ($self) = @_;
352
353   return unless $self->_interface_is_fcgi && $::lx_office_conf{debug}->{restart_fcgi_process_on_changes};
354
355   require File::Find;
356   require POSIX;
357
358   my $wanted = sub {
359     return unless $File::Find::name =~ m/\.(?:pm|f?pl|html|conf|conf\.default)$/;
360     $fcgi_file_cache{ $File::Find::name } = (stat $File::Find::name)[9];
361   };
362
363   my $cwd = POSIX::getcwd();
364   File::Find::find($wanted, map { "${cwd}/${_}" } qw(config bin SL templates/webpages));
365   map { my $name = "${cwd}/${_}"; $fcgi_file_cache{$name} = (stat $name)[9] } qw(admin.pl dispatcher.fpl);
366 }
367
368 sub _watch_for_changed_files {
369   my ($self) = @_;
370
371   return unless $self->_interface_is_fcgi && $::lx_office_conf{debug}->{restart_fcgi_process_on_changes};
372
373   my $ok = all { (stat($_))[9] == $fcgi_file_cache{$_} } keys %fcgi_file_cache;
374   return if $ok;
375   $::lxdebug->message(LXDebug::DEBUG1(), "Program modifications detected. Restarting.");
376   exit;
377 }
378
379 sub get_standard_filehandles {
380   my $self = shift;
381
382   return $self->{interface} =~ m/f(?:ast)cgi/i ? $self->{request}->GetHandles() : (\*STDIN, \*STDOUT, \*STDERR);
383 }
384
385 sub _check_for_old_config_files {
386   my @old_files = grep { -f "config/${_}" } qw(authentication.pl console.conf lx-erp.conf lx-erp-local.conf);
387   return unless @old_files;
388
389   $::form->{title} = $::locale->text('Old configuration files');
390   $::form->header;
391   print $::form->parse_html_template('login_screen/old_configuration_files', { FILES => \@old_files });
392
393   ::end_of_request();
394 }
395
396 package main;
397
398 use strict;
399
400 sub end_of_request {
401   die SL::Dispatcher->END_OF_REQUEST;
402 }
403
404 1;