Optionaler, automatischer FCGI-Restart nach Request bei Programmänderungen
[kivitendo-erp.git] / SL / Dispatcher.pm
1 package SL::Dispatcher;
2
3 use strict;
4
5 BEGIN {
6   unshift @INC, "modules/override"; # Use our own versions of various modules (e.g. YAML).
7   push    @INC, "modules/fallback"; # Only use our own versions of modules if there's no system version.
8 }
9
10 use CGI qw( -no_xhtml);
11 use Config::Std;
12 use DateTime;
13 use Encode;
14 use English qw(-no_match_vars);
15 use File::Basename;
16 use List::MoreUtils qw(all);
17 use List::Util qw(first);
18 use POSIX;
19 use SL::Auth;
20 use SL::LXDebug;
21 use SL::LxOfficeConf;
22 use SL::Locale;
23 use SL::Common;
24 use SL::Form;
25 use SL::Helper::DateTime;
26 use SL::Template::Plugin::HTMLFixes;
27
28 # Trailing new line is added so that Perl will not add the line
29 # number 'die' was called in.
30 use constant END_OF_REQUEST => "END-OF-REQUEST\n";
31
32 my %fcgi_file_cache;
33
34 sub new {
35   my ($class, $interface) = @_;
36
37   my $self           = bless {}, $class;
38   $self->{interface} = lc($interface || 'cgi');
39
40   return $self;
41 }
42
43 sub interface_type {
44   my ($self) = @_;
45   return $self->{interface} eq 'cgi' ? 'CGI' : 'FastCGI';
46 }
47
48 sub pre_request_checks {
49   _check_for_old_config_files();
50
51   if (!$::auth->session_tables_present) {
52     if ($::form->{script} eq 'admin.pl') {
53       ::run();
54       ::end_of_request();
55     } else {
56       show_error('login/auth_db_unreachable');
57     }
58   }
59 }
60
61 sub show_error {
62   $::lxdebug->enter_sub;
63   my $template             = shift;
64   my $error_type           = shift || '';
65
66   $::locale                = Locale->new($::lx_office_conf{system}->{language});
67   $::form->{error}         = $::locale->text('The session is invalid or has expired.') if ($error_type eq 'session');
68   $::form->{error}         = $::locale->text('Incorrect password!.')                   if ($error_type eq 'password');
69   $::myconfig{countrycode} = $::lx_office_conf{system}->{language};
70   $::form->{stylesheet}    = 'css/lx-office-erp.css';
71
72   $::form->header;
73   print $::form->parse_html_template($template);
74   $::lxdebug->leave_sub;
75
76   ::end_of_request();
77 }
78
79 sub pre_startup_setup {
80   my ($self) = @_;
81
82   SL::LxOfficeConf->read;
83   _init_environment();
84
85   eval {
86     package main;
87     require "bin/mozilla/common.pl";
88     require "bin/mozilla/installationcheck.pl";
89   } or die $EVAL_ERROR;
90
91   # canonial globals. if it's not here, chances are it will get refactored someday.
92   {
93     no warnings 'once';
94     $::lxdebug     = LXDebug->new;
95     $::auth        = SL::Auth->new;
96     $::form        = undef;
97     %::myconfig    = ();
98     %::called_subs = (); # currently used for recursion detection
99   }
100
101   $SIG{__WARN__} = sub {
102     $::lxdebug->warn(@_);
103   };
104
105   $self->_cache_file_modification_times;
106 }
107
108 sub pre_startup_checks {
109   ::verify_installation();
110 }
111
112 sub pre_startup {
113   my ($self) = @_;
114   $self->pre_startup_setup;
115   $self->pre_startup_checks;
116 }
117
118 sub require_main_code {
119   $::lxdebug->enter_sub;
120   my ($script, $suffix) = @_;
121
122   eval {
123     package main;
124     require "bin/mozilla/$script$suffix";
125   } or die $EVAL_ERROR;
126
127   if (-f "bin/mozilla/custom_$script$suffix") {
128     eval {
129       package main;
130       require "bin/mozilla/custom_$script$suffix";
131     };
132     $::form->error($EVAL_ERROR) if ($EVAL_ERROR);
133   }
134   if ($::form->{login} && -f "bin/mozilla/$::form->{login}_$script") {
135     eval {
136       package main;
137       require "bin/mozilla/$::form->{login}_$script";
138     };
139     $::form->error($EVAL_ERROR) if ($EVAL_ERROR);
140   }
141   $::lxdebug->leave_sub;
142 }
143
144 sub _require_controller {
145   my $controller =  shift;
146   $controller    =~ s|[^A-Za-z0-9_]||g;
147
148   eval {
149     package main;
150     require "SL/Controller/${controller}.pm";
151   } or die $EVAL_ERROR;
152 }
153
154 sub _run_controller {
155   "SL::Controller::$_[0]"->new->_run_action($_[1]);
156 }
157
158 sub handle_request {
159   my $self         = shift;
160   $self->{request} = shift;
161
162   $::lxdebug->enter_sub;
163   $::lxdebug->begin_request;
164
165   my ($script, $path, $suffix, $script_name, $action, $routing_type);
166
167   $script_name = $ENV{SCRIPT_NAME};
168
169   $self->unrequire_bin_mozilla;
170
171   $::cgi         = CGI->new('');
172   $::locale      = Locale->new($::lx_office_conf{system}->{language});
173   $::form        = Form->new;
174   %::called_subs = ();
175
176   my $session_result = $::auth->restore_session;
177   $::auth->create_or_refresh_session;
178
179   $::form->read_cgi_input;
180
181   eval { ($routing_type, $script_name, $action) = _route_request($script_name); 1; } or return;
182
183   if ($routing_type eq 'old') {
184     $::form->{action}  =  lc $::form->{action};
185     $::form->{action}  =~ s/( |-|,|\#)/_/g;
186
187    ($script, $path, $suffix) = fileparse($script_name, ".pl");
188     require_main_code($script, $suffix);
189
190     $::form->{script} = $script . $suffix;
191
192   } else {
193     _require_controller($script_name);
194     $::form->{script} = "controller.pl";
195   }
196
197   eval {
198     pre_request_checks();
199
200     $::form->error($::locale->text('System currently down for maintenance!')) if -e ($::lx_office_conf{paths}->{userspath} . "/nologin") && $script ne 'admin';
201
202     if ($script eq 'login' or $script eq 'admin') {
203       $::form->{titlebar} = "Lx-Office " . $::locale->text('Version') . " $::form->{version}";
204       ::run($session_result);
205
206     } else {
207       show_error('login/password_error', 'session') if SL::Auth::SESSION_EXPIRED == $session_result;
208       %::myconfig = $::auth->read_user($::form->{login});
209
210       show_error('login/password_error', 'password') unless $::myconfig{login};
211
212       $::locale = Locale->new($::myconfig{countrycode});
213
214       show_error('login/password_error', 'password') if SL::Auth::OK != $::auth->authenticate($::form->{login}, $::form->{password});
215
216       $::auth->store_credentials_in_session(login => $::form->{login}, password => $::form->{password});
217       $::auth->create_or_refresh_session;
218       $::auth->delete_session_value('FLASH');
219       delete $::form->{password};
220
221       if ($action) {
222         map { $::form->{$_} = $::myconfig{$_} } qw(stylesheet charset)
223           unless $action eq 'save' && $::form->{type} eq 'preferences';
224
225         $::form->set_standard_title;
226         if ($routing_type eq 'old') {
227           ::call_sub('::' . $::locale->findsub($action));
228         } else {
229           _run_controller($script_name, $action);
230         }
231       } else {
232         $::form->error($::locale->text('action= not defined!'));
233       }
234     }
235
236     1;
237   } or do {
238     if ($EVAL_ERROR ne END_OF_REQUEST) {
239       print STDERR $EVAL_ERROR;
240       $::form->{label_error} = $::cgi->pre($EVAL_ERROR);
241       eval { show_error('generic/error') };
242     }
243   };
244
245   # cleanup
246   $::auth->save_session;
247   $::auth->expire_sessions;
248   $::auth->reset;
249
250   $::locale   = undef;
251   $::form     = undef;
252   $::myconfig = ();
253   Form::disconnect_standard_dbh;
254
255   $::lxdebug->end_request;
256
257   $self->_watch_for_changed_files;
258
259   $::lxdebug->leave_sub;
260 }
261
262 sub unrequire_bin_mozilla {
263   my $self = shift;
264   return unless $self->_interface_is_fcgi;
265
266   for (keys %INC) {
267     next unless m#^bin/mozilla/#;
268     next if /\bcommon.pl$/;
269     next if /\binstallationcheck.pl$/;
270     delete $INC{$_};
271   }
272 }
273
274 sub _interface_is_fcgi {
275   my $self = shift;
276   return $self->{interface} =~ m/^(?:fastcgi|fcgid|fcgi)$/;
277 }
278
279 sub _route_request {
280   my $script_name = shift;
281
282   return $script_name =~ m/dispatcher\.pl$/ ? ('old',        _route_dispatcher_request())
283        : $script_name =~ m/controller\.pl/  ? ('controller', _route_controller_request())
284        :                                      ('old',        $script_name, $::form->{action});
285 }
286
287 sub _route_dispatcher_request {
288   my $name_re = qr{[a-z]\w*};
289   my ($script_name, $action);
290
291   eval {
292     die "Unroutable request -- inavlid module name.\n" if !$::form->{M} || ($::form->{M} !~ m/^${name_re}$/);
293     $script_name = $::form->{M} . '.pl';
294
295     if ($::form->{A}) {
296       $action = $::form->{A};
297
298     } else {
299       $action = first { m/^A_${name_re}$/ } keys %{ $::form };
300       die "Unroutable request -- inavlid action name.\n" if !$action;
301
302       delete $::form->{$action};
303       $action = substr $action, 2;
304     }
305
306     delete @{$::form}{qw(M A)};
307
308     1;
309   } or do {
310     $::form->{label_error} = $::cgi->pre($EVAL_ERROR);
311     show_error('generic/error');
312   };
313
314   return ($script_name, $action);
315 }
316
317 sub _route_controller_request {
318   my ($controller, $action);
319
320   eval {
321     $::form->{action}      =~ m|^ ( [A-Z] [A-Za-z0-9_]* ) / ( [a-z] [a-z0-9_]* ) $|x || die "Unroutable request -- inavlid controller/action.\n";
322     ($controller, $action) =  ($1, $2);
323     delete $::form->{action};
324
325     1;
326   } or do {
327     $::form->{label_error} = $::cgi->pre($EVAL_ERROR);
328     show_error('generic/error');
329   };
330
331   return ($controller, $action);
332 }
333
334 sub _cache_file_modification_times {
335   my ($self) = @_;
336
337   return unless $self->_interface_is_fcgi && $::lx_office_conf{debug}->{restart_fcgi_process_on_changes};
338
339   require File::Find;
340   require POSIX;
341
342   my $wanted = sub {
343     return unless $File::Find::name =~ m/\.(?:pm|f?pl|html|conf|conf\.default)$/;
344     $fcgi_file_cache{ $File::Find::name } = (stat $File::Find::name)[9];
345   };
346
347   my $cwd = POSIX::getcwd();
348   File::Find::find($wanted, map { "${cwd}/${_}" } qw(config bin SL templates/webpages));
349   map { my $name = "${cwd}/${_}"; $fcgi_file_cache{$name} = (stat $name)[9] } qw(admin.pl dispatcher.fpl);
350 }
351
352 sub _watch_for_changed_files {
353   my ($self) = @_;
354
355   return unless $self->_interface_is_fcgi && $::lx_office_conf{debug}->{restart_fcgi_process_on_changes};
356
357   my $ok = all { (stat($_))[9] == $fcgi_file_cache{$_} } keys %fcgi_file_cache;
358   return if $ok;
359   $::lxdebug->message(LXDebug::DEBUG1(), "Program modifications detected. Restarting.");
360   exit;
361 }
362
363 sub get_standard_filehandles {
364   my $self = shift;
365
366   return $self->{interface} =~ m/f(?:ast)cgi/i ? $self->{request}->GetHandles() : (\*STDIN, \*STDOUT, \*STDERR);
367 }
368
369 sub _init_environment {
370   my %key_map = ( lib  => { name => 'PERL5LIB', append_path => 1 },
371                   path => { name => 'PATH',     append_path => 1 },
372                 );
373   my $cfg     = $::lx_office_conf{environment} || {};
374
375   while (my ($key, $value) = each %{ $cfg }) {
376     next unless $value;
377
378     my $info = $key_map{$key} || {};
379     $key     = $info->{name}  || $key;
380
381     if ($info->{append_path}) {
382       $value = ':' . $value unless $value =~ m/^:/ || !$ENV{$key};
383       $value = $ENV{$key} . $value;
384     }
385
386     $ENV{$key} = $value;
387   }
388 }
389
390 sub _check_for_old_config_files {
391   my @old_files = grep { -f "config/${_}" } qw(authentication.pl console.conf lx-erp.conf lx-erp-local.conf);
392   return unless @old_files;
393
394   $::form->{title}      = $::locale->text('Old configuration files');
395   $::form->{stylesheet} = 'lx-office-erp.css';
396   $::form->header;
397   print $::form->parse_html_template('login/old_configuration_files', { FILES => \@old_files });
398
399   ::end_of_request();
400 }
401
402 package main;
403
404 use strict;
405
406 sub end_of_request {
407   die SL::Dispatcher->END_OF_REQUEST;
408 }
409
410 1;