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