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