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