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