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