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