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