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