$::request als globale Variable eingeführt.
[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   $::form->{stylesheet}    = 'css/lx-office-erp.css';
72
73   $::form->header;
74   print $::form->parse_html_template($template);
75   $::lxdebug->leave_sub;
76
77   ::end_of_request();
78 }
79
80 sub pre_startup_setup {
81   my ($self) = @_;
82
83   SL::LxOfficeConf->read;
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     $::request     = undef;
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   $::instance_conf = SL::InstanceConfiguration->new;
175   $::request       = { };
176
177   my $session_result = $::auth->restore_session;
178   $::auth->create_or_refresh_session;
179
180   $::form->read_cgi_input;
181
182   eval { ($routing_type, $script_name, $action) = _route_request($script_name); 1; } or return;
183
184   if ($routing_type eq 'old') {
185     $::form->{action}  =  lc $::form->{action};
186     $::form->{action}  =~ s/( |-|,|\#)/_/g;
187
188    ($script, $path, $suffix) = fileparse($script_name, ".pl");
189     require_main_code($script, $suffix);
190
191     $::form->{script} = $script . $suffix;
192
193   } else {
194     _require_controller($script_name);
195     $::form->{script} = "controller.pl";
196   }
197
198   eval {
199     pre_request_checks();
200
201     $::form->error($::locale->text('System currently down for maintenance!')) if -e ($::lx_office_conf{paths}->{userspath} . "/nologin") && $script ne 'admin';
202
203     if ($script eq 'login' or $script eq 'admin') {
204       $::form->{titlebar} = "Lx-Office " . $::locale->text('Version') . " $::form->{version}";
205       ::run($session_result);
206
207     } else {
208       show_error('login/password_error', 'session') if SL::Auth::SESSION_EXPIRED == $session_result;
209       %::myconfig = $::auth->read_user($::form->{login});
210
211       show_error('login/password_error', 'password') unless $::myconfig{login};
212
213       $::locale = Locale->new($::myconfig{countrycode});
214
215       show_error('login/password_error', 'password') if SL::Auth::OK != $::auth->authenticate($::form->{login}, $::form->{password});
216
217       $::auth->store_credentials_in_session(login => $::form->{login}, password => $::form->{password});
218       $::auth->create_or_refresh_session;
219       $::auth->delete_session_value('FLASH');
220       delete $::form->{password};
221
222       if ($action) {
223         $::instance_conf->init;
224
225         map { $::form->{$_} = $::myconfig{$_} } qw(stylesheet charset)
226           unless $action eq 'save' && $::form->{type} eq 'preferences';
227
228         $::form->set_standard_title;
229         if ($routing_type eq 'old') {
230           ::call_sub('::' . $::locale->findsub($action));
231         } else {
232           _run_controller($script_name, $action);
233         }
234       } else {
235         $::form->error($::locale->text('action= not defined!'));
236       }
237     }
238
239     1;
240   } or do {
241     if ($EVAL_ERROR ne END_OF_REQUEST) {
242       print STDERR $EVAL_ERROR;
243       $::form->{label_error} = $::cgi->pre($EVAL_ERROR);
244       eval { show_error('generic/error') };
245     }
246   };
247
248   # cleanup
249   $::auth->save_session;
250   $::auth->expire_sessions;
251   $::auth->reset;
252
253   $::locale   = undef;
254   $::form     = undef;
255   $::myconfig = ();
256   $::request  = undef;
257   Form::disconnect_standard_dbh;
258
259   $::lxdebug->end_request;
260
261   $self->_watch_for_changed_files;
262
263   $::lxdebug->leave_sub;
264 }
265
266 sub unrequire_bin_mozilla {
267   my $self = shift;
268   return unless $self->_interface_is_fcgi;
269
270   for (keys %INC) {
271     next unless m#^bin/mozilla/#;
272     next if /\bcommon.pl$/;
273     next if /\binstallationcheck.pl$/;
274     delete $INC{$_};
275   }
276 }
277
278 sub _interface_is_fcgi {
279   my $self = shift;
280   return $self->{interface} =~ m/^(?:fastcgi|fcgid|fcgi)$/;
281 }
282
283 sub _route_request {
284   my $script_name = shift;
285
286   return $script_name =~ m/dispatcher\.pl$/ ? ('old',        _route_dispatcher_request())
287        : $script_name =~ m/controller\.pl/  ? ('controller', _route_controller_request())
288        :                                      ('old',        $script_name, $::form->{action});
289 }
290
291 sub _route_dispatcher_request {
292   my $name_re = qr{[a-z]\w*};
293   my ($script_name, $action);
294
295   eval {
296     die "Unroutable request -- inavlid module name.\n" if !$::form->{M} || ($::form->{M} !~ m/^${name_re}$/);
297     $script_name = $::form->{M} . '.pl';
298
299     if ($::form->{A}) {
300       $action = $::form->{A};
301
302     } else {
303       $action = first { m/^A_${name_re}$/ } keys %{ $::form };
304       die "Unroutable request -- inavlid action name.\n" if !$action;
305
306       delete $::form->{$action};
307       $action = substr $action, 2;
308     }
309
310     delete @{$::form}{qw(M A)};
311
312     1;
313   } or do {
314     $::form->{label_error} = $::cgi->pre($EVAL_ERROR);
315     show_error('generic/error');
316   };
317
318   return ($script_name, $action);
319 }
320
321 sub _route_controller_request {
322   my ($controller, $action);
323
324   eval {
325     $::form->{action}      =~ m|^ ( [A-Z] [A-Za-z0-9_]* ) / ( [a-z] [a-z0-9_]* ) $|x || die "Unroutable request -- inavlid controller/action.\n";
326     ($controller, $action) =  ($1, $2);
327     delete $::form->{action};
328
329     1;
330   } or do {
331     $::form->{label_error} = $::cgi->pre($EVAL_ERROR);
332     show_error('generic/error');
333   };
334
335   return ($controller, $action);
336 }
337
338 sub _cache_file_modification_times {
339   my ($self) = @_;
340
341   return unless $self->_interface_is_fcgi && $::lx_office_conf{debug}->{restart_fcgi_process_on_changes};
342
343   require File::Find;
344   require POSIX;
345
346   my $wanted = sub {
347     return unless $File::Find::name =~ m/\.(?:pm|f?pl|html|conf|conf\.default)$/;
348     $fcgi_file_cache{ $File::Find::name } = (stat $File::Find::name)[9];
349   };
350
351   my $cwd = POSIX::getcwd();
352   File::Find::find($wanted, map { "${cwd}/${_}" } qw(config bin SL templates/webpages));
353   map { my $name = "${cwd}/${_}"; $fcgi_file_cache{$name} = (stat $name)[9] } qw(admin.pl dispatcher.fpl);
354 }
355
356 sub _watch_for_changed_files {
357   my ($self) = @_;
358
359   return unless $self->_interface_is_fcgi && $::lx_office_conf{debug}->{restart_fcgi_process_on_changes};
360
361   my $ok = all { (stat($_))[9] == $fcgi_file_cache{$_} } keys %fcgi_file_cache;
362   return if $ok;
363   $::lxdebug->message(LXDebug::DEBUG1(), "Program modifications detected. Restarting.");
364   exit;
365 }
366
367 sub get_standard_filehandles {
368   my $self = shift;
369
370   return $self->{interface} =~ m/f(?:ast)cgi/i ? $self->{request}->GetHandles() : (\*STDIN, \*STDOUT, \*STDERR);
371 }
372
373 sub _check_for_old_config_files {
374   my @old_files = grep { -f "config/${_}" } qw(authentication.pl console.conf lx-erp.conf lx-erp-local.conf);
375   return unless @old_files;
376
377   $::form->{title}      = $::locale->text('Old configuration files');
378   $::form->{stylesheet} = 'lx-office-erp.css';
379   $::form->header;
380   print $::form->parse_html_template('login/old_configuration_files', { FILES => \@old_files });
381
382   ::end_of_request();
383 }
384
385 package main;
386
387 use strict;
388
389 sub end_of_request {
390   die SL::Dispatcher->END_OF_REQUEST;
391 }
392
393 1;