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