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