Locking in eigenes Modul verschieben
[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);
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       print $::request->{cgi}->redirect('controller.pl?action=LoginScreen/user_login');
253
254     } elsif ($script eq 'admin') {
255       ::run($session_result);
256
257     } else {
258       $self->redirect_to_login($script) if SL::Auth::SESSION_EXPIRED == $session_result;
259
260       my %auth_result = $self->{auth_handler}->handle(
261         routing_type => $routing_type,
262         script       => $script,
263         controller   => $script_name,
264         action       => $action,
265       );
266
267       ::end_of_request() unless $auth_result{auth_ok};
268
269       delete @{ $::form }{ grep { m/^\{AUTH\}/ } keys %{ $::form } } unless $auth_result{keep_auth_vars};
270
271       if ($action) {
272         $::instance_conf->init if $auth_result{auth_level} eq 'user';
273
274         map { $::form->{$_} = $::myconfig{$_} } qw(charset)
275           unless $action eq 'save' && $::form->{type} eq 'preferences';
276
277         $::form->set_standard_title;
278         if ($routing_type eq 'old') {
279           ::call_sub('::' . $::locale->findsub($action));
280         } else {
281           _run_controller($script_name, $action);
282         }
283       } else {
284         $::form->error($::locale->text('action= not defined!'));
285       }
286     }
287
288     1;
289   } or do {
290     if (substr($EVAL_ERROR, 0, length(END_OF_REQUEST())) ne END_OF_REQUEST()) {
291       my $error = $EVAL_ERROR;
292       print STDERR $error;
293
294       if ($::request->is_ajax) {
295         eval { render_error_ajax($error) };
296       } else {
297         $::form->{label_error} = $::request->{cgi}->pre($error);
298         chdir SL::System::Process::exe_dir;
299         eval { show_error('generic/error') };
300       }
301     }
302   };
303
304   $::form->footer;
305
306   # cleanup
307   $::auth->save_session;
308   $::auth->expire_sessions;
309   $::auth->reset;
310
311   $::locale   = undef;
312   $::form     = undef;
313   $::myconfig = ();
314   $::request  = undef;
315   Form::disconnect_standard_dbh;
316
317   $::lxdebug->end_request;
318
319   $self->_watch_for_changed_files;
320
321   $::lxdebug->leave_sub;
322 }
323
324 sub redirect_to_login {
325   my ($self, $script) = @_;
326   my $action          = $script =~ m/^admin/i ? 'Admin/login' : 'LoginScreen/user_login&error=session';
327   print $::request->cgi->redirect("controller.pl?action=${action}");
328   ::end_of_request();
329 }
330
331 sub unrequire_bin_mozilla {
332   my $self = shift;
333   return unless $self->_interface_is_fcgi;
334
335   for (keys %INC) {
336     next unless m#^bin/mozilla/#;
337     next if /\bcommon.pl$/;
338     next if /\binstallationcheck.pl$/;
339     delete $INC{$_};
340   }
341 }
342
343 sub _interface_is_fcgi {
344   my $self = shift;
345   return $self->{interface} =~ m/^(?:fastcgi|fcgid|fcgi)$/;
346 }
347
348 sub _route_request {
349   my $script_name = shift;
350
351   return $script_name =~ m/dispatcher\.pl$/ ? (type => 'old',        _route_dispatcher_request())
352        : $script_name =~ m/controller\.pl/  ? (type => 'controller', _route_controller_request())
353        :                                      (type => 'old',        controller => $script_name, action => $::form->{action});
354 }
355
356 sub _route_dispatcher_request {
357   my $name_re = qr{[a-z]\w*};
358   my ($script_name, $action);
359
360   eval {
361     die "Unroutable request -- inavlid module name.\n" if !$::form->{M} || ($::form->{M} !~ m/^${name_re}$/);
362     $script_name = $::form->{M} . '.pl';
363
364     if ($::form->{A}) {
365       $action = $::form->{A};
366
367     } else {
368       $action = first { m/^A_${name_re}$/ } keys %{ $::form };
369       die "Unroutable request -- inavlid action name.\n" if !$action;
370
371       delete $::form->{$action};
372       $action = substr $action, 2;
373     }
374
375     delete @{$::form}{qw(M A)};
376
377     1;
378   } or do {
379     $::form->{label_error} = $::request->{cgi}->pre($EVAL_ERROR);
380     show_error('generic/error');
381   };
382
383   return (controller => $script_name, action => $action);
384 }
385
386 sub _route_controller_request {
387   my ($controller, $action, $request_type);
388
389   eval {
390     $::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";
391     ($controller, $action) =  ($1, $2);
392     delete $::form->{action};
393
394     $request_type = $3 ? lc(substr($3, 1)) : 'html';
395
396     1;
397   } or do {
398     $::form->{label_error} = $::request->{cgi}->pre($EVAL_ERROR);
399     show_error('generic/error');
400   };
401
402   return (controller => $controller, action => $action, request_type => $request_type);
403 }
404
405 sub _cache_file_modification_times {
406   my ($self) = @_;
407
408   return unless $self->_interface_is_fcgi && $::lx_office_conf{debug}->{restart_fcgi_process_on_changes};
409
410   require File::Find;
411   require POSIX;
412
413   my $wanted = sub {
414     return unless $File::Find::name =~ m/\.(?:pm|f?pl|html|conf|conf\.default)$/;
415     $fcgi_file_cache{ $File::Find::name } = (stat $File::Find::name)[9];
416   };
417
418   my $cwd = POSIX::getcwd();
419   File::Find::find($wanted, map { "${cwd}/${_}" } qw(config bin SL templates/webpages));
420   map { my $name = "${cwd}/${_}"; $fcgi_file_cache{$name} = (stat $name)[9] } qw(admin.pl dispatcher.fpl);
421 }
422
423 sub _watch_for_changed_files {
424   my ($self) = @_;
425
426   return unless $self->_interface_is_fcgi && $::lx_office_conf{debug}->{restart_fcgi_process_on_changes};
427
428   my $ok = all { (stat($_))[9] == $fcgi_file_cache{$_} } keys %fcgi_file_cache;
429   return if $ok;
430   $::lxdebug->message(LXDebug::DEBUG1(), "Program modifications detected. Restarting.");
431   exit;
432 }
433
434 sub get_standard_filehandles {
435   my $self = shift;
436
437   return $self->{interface} =~ m/f(?:ast)cgi/i ? $self->{request}->GetHandles() : (\*STDIN, \*STDOUT, \*STDERR);
438 }
439
440 sub _check_for_old_config_files {
441   my @old_files = grep { -f "config/${_}" } qw(authentication.pl console.conf lx-erp.conf lx-erp-local.conf);
442   return unless @old_files;
443
444   $::form->{title} = $::locale->text('Old configuration files');
445   $::form->header;
446   print $::form->parse_html_template('login_screen/old_configuration_files', { FILES => \@old_files });
447
448   ::end_of_request();
449 }
450
451 package main;
452
453 use strict;
454
455 sub end_of_request {
456   die SL::Dispatcher->END_OF_REQUEST;
457 }
458
459 1;