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