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