Globale Variable $::menufile entfernt
[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($::lx_office_conf{system}->{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} = $::lx_office_conf{system}->{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     $::lxdebug     = LXDebug->new;
92     $::auth        = SL::Auth->new;
93     $::form        = undef;
94     %::myconfig    = ();
95     %::called_subs = (); # currently used for recursion detection
96   }
97
98   $SIG{__WARN__} = sub {
99     $::lxdebug->warn(@_);
100   }
101 }
102
103 sub pre_startup_checks {
104   ::verify_installation();
105 }
106
107 sub pre_startup {
108   pre_startup_setup();
109   pre_startup_checks();
110 }
111
112 sub require_main_code {
113   $::lxdebug->enter_sub;
114   my ($script, $suffix) = @_;
115
116   eval {
117     package main;
118     require "bin/mozilla/$script$suffix";
119   } or die $EVAL_ERROR;
120
121   if (-f "bin/mozilla/custom_$script$suffix") {
122     eval {
123       package main;
124       require "bin/mozilla/custom_$script$suffix";
125     };
126     $::form->error($EVAL_ERROR) if ($EVAL_ERROR);
127   }
128   if ($::form->{login} && -f "bin/mozilla/$::form->{login}_$script") {
129     eval {
130       package main;
131       require "bin/mozilla/$::form->{login}_$script";
132     };
133     $::form->error($EVAL_ERROR) if ($EVAL_ERROR);
134   }
135   $::lxdebug->leave_sub;
136 }
137
138 sub _require_controller {
139   my $controller =  shift;
140   $controller    =~ s|[^A-Za-z0-9_]||g;
141
142   eval {
143     package main;
144     require "SL/Controller/${controller}.pm";
145   } or die $EVAL_ERROR;
146 }
147
148 sub _run_controller {
149   "SL::Controller::$_[0]"->new->_run_action($_[1]);
150 }
151
152 sub handle_request {
153   my $self         = shift;
154   $self->{request} = shift;
155
156   $::lxdebug->enter_sub;
157   $::lxdebug->begin_request;
158
159   my ($script, $path, $suffix, $script_name, $action, $routing_type);
160
161   $script_name = $ENV{SCRIPT_NAME};
162
163   $self->unrequire_bin_mozilla;
164
165   $::cgi         = CGI->new('');
166   $::locale      = Locale->new($::lx_office_conf{system}->{language});
167   $::form        = Form->new;
168   %::called_subs = ();
169
170   eval { ($routing_type, $script_name, $action) = _route_request($script_name); 1; } or return;
171
172   if ($routing_type eq 'old') {
173     $::form->{action}  =  lc $::form->{action};
174     $::form->{action}  =~ s/( |-|,|\#)/_/g;
175
176    ($script, $path, $suffix) = fileparse($script_name, ".pl");
177     require_main_code($script, $suffix);
178
179     $::form->{script} = $script . $suffix;
180
181   } else {
182     _require_controller($script_name);
183     $::form->{script} = "controller.pl";
184   }
185
186   pre_request_checks();
187
188   eval {
189     my $session_result = $::auth->restore_session;
190     $::auth->create_or_refresh_session;
191
192     $::form->error($::locale->text('System currently down for maintenance!')) if -e ($::lx_office_conf{paths}->{userspath} . "/nologin") && $script ne 'admin';
193
194     if ($script eq 'login' or $script eq 'admin' or $script eq 'kopf') {
195       $::form->{titlebar} = "Lx-Office " . $::locale->text('Version') . " $::form->{version}";
196       ::run($session_result);
197
198     } else {
199       show_error('login/password_error', 'session') if SL::Auth::SESSION_EXPIRED == $session_result;
200       %::myconfig = $::auth->read_user($::form->{login});
201
202       show_error('login/password_error', 'password') unless $::myconfig{login};
203
204       $::locale = Locale->new($::myconfig{countrycode});
205
206       show_error('login/password_error', 'password') if SL::Auth::OK != $::auth->authenticate($::form->{login}, $::form->{password}, 0);
207
208       $::auth->set_session_value('login', $::form->{login}, 'password', $::form->{password});
209       $::auth->create_or_refresh_session;
210       $::auth->delete_session_value('FLASH')->save_session();
211       delete $::form->{password};
212
213       if ($action) {
214         map { $::form->{$_} = $::myconfig{$_} } qw(stylesheet charset)
215           unless $action eq 'save' && $::form->{type} eq 'preferences';
216
217         $::form->set_standard_title;
218         if ($routing_type eq 'old') {
219           ::call_sub('::' . $::locale->findsub($action));
220         } else {
221           _run_controller($script_name, $action);
222         }
223       } else {
224         $::form->error($::locale->text('action= not defined!'));
225       }
226     }
227
228     1;
229   } or do {
230     if ($EVAL_ERROR ne END_OF_REQUEST) {
231       $::form->{label_error} = $::cgi->pre($EVAL_ERROR);
232       eval { show_error('generic/error') };
233     }
234   };
235
236   # cleanup
237   $::locale   = undef;
238   $::form     = undef;
239   $::myconfig = ();
240   Form::disconnect_standard_dbh unless $self->_interface_is_fcgi;
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 _decode_recursively {
325   my ($obj) = @_;
326
327   while (my ($key, $value) = each %{ $obj }) {
328     if (ref($value) eq 'HASH') {
329       _decode_recursively($value);
330     } else {
331       $obj->{$key} = decode('UTF-8', $value);
332     }
333   }
334 }
335
336 sub _init_environment {
337   my %key_map = ( lib  => { name => 'PERL5LIB', append_path => 1 },
338                   path => { name => 'PATH',     append_path => 1 },
339                 );
340   my $cfg     = $::lx_office_conf{environment} || {};
341
342   while (my ($key, $value) = each %{ $cfg }) {
343     next unless $value;
344
345     my $info = $key_map{$key} || {};
346     $key     = $info->{name}  || $key;
347
348     if ($info->{append_path}) {
349       $value = ':' . $value unless $value =~ m/^:/ || !$ENV{$key};
350       $value = $ENV{$key} . $value;
351     }
352
353     $ENV{$key} = $value;
354   }
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;