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