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