User-Login auf Controller umgestellt
[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 File::Basename;
16 use List::MoreUtils qw(all);
17 use List::Util qw(first);
18 use POSIX;
19 use SL::Auth;
20 use SL::Dispatcher::AuthHandler;
21 use SL::LXDebug;
22 use SL::LxOfficeConf;
23 use SL::Locale;
24 use SL::Common;
25 use SL::Form;
26 use SL::Helper::DateTime;
27 use SL::InstanceConfiguration;
28 use SL::Template::Plugin::HTMLFixes;
29
30 # Trailing new line is added so that Perl will not add the line
31 # number 'die' was called in.
32 use constant END_OF_REQUEST => "END-OF-REQUEST\n";
33
34 my %fcgi_file_cache;
35
36 sub new {
37   my ($class, $interface) = @_;
38
39   my $self           = bless {}, $class;
40   $self->{interface} = lc($interface || 'cgi');
41   $self->{auth_handler} = SL::Dispatcher::AuthHandler->new;
42
43   return $self;
44 }
45
46 sub interface_type {
47   my ($self) = @_;
48   return $self->{interface} eq 'cgi' ? 'CGI' : 'FastCGI';
49 }
50
51 sub pre_request_checks {
52   _check_for_old_config_files();
53
54   if (!$::auth->session_tables_present) {
55     if ($::form->{script} eq 'admin.pl') {
56       ::run();
57       ::end_of_request();
58     } else {
59       show_error('login_screen/auth_db_unreachable');
60     }
61   }
62 }
63
64 sub show_error {
65   $::lxdebug->enter_sub;
66   my $template             = shift;
67   my $error_type           = shift || '';
68   my %params               = @_;
69
70   $::myconfig{countrycode} = delete($params{countrycode}) || $::lx_office_conf{system}->{language};
71   $::locale                = Locale->new($::myconfig{countrycode});
72   $::form->{error}         = $::locale->text('The session is invalid or has expired.') if ($error_type eq 'session');
73   $::form->{error}         = $::locale->text('Incorrect password!')                    if ($error_type eq 'password');
74
75   $::form->header;
76   print $::form->parse_html_template($template, \%params);
77   $::lxdebug->leave_sub;
78
79   ::end_of_request();
80 }
81
82 sub pre_startup_setup {
83   my ($self) = @_;
84
85   SL::LxOfficeConf->read;
86
87   eval {
88     package main;
89     require "bin/mozilla/common.pl";
90     require "bin/mozilla/installationcheck.pl";
91   } or die $EVAL_ERROR;
92
93   # canonial globals. if it's not here, chances are it will get refactored someday.
94   {
95     no warnings 'once';
96     $::lxdebug     = LXDebug->new;
97     $::auth        = SL::Auth->new;
98     $::form        = undef;
99     %::myconfig    = ();
100     $::request     = undef;
101   }
102
103   $SIG{__WARN__} = sub {
104     $::lxdebug->warn(@_);
105   };
106
107   $self->_cache_file_modification_times;
108 }
109
110 sub pre_startup_checks {
111   ::verify_installation();
112 }
113
114 sub pre_startup {
115   my ($self) = @_;
116   $self->pre_startup_setup;
117   $self->pre_startup_checks;
118 }
119
120 sub require_main_code {
121   $::lxdebug->enter_sub;
122   my ($script, $suffix) = @_;
123
124   eval {
125     package main;
126     require "bin/mozilla/$script$suffix";
127   } or die $EVAL_ERROR;
128
129   if (-f "bin/mozilla/custom_$script$suffix") {
130     eval {
131       package main;
132       require "bin/mozilla/custom_$script$suffix";
133     };
134     $::form->error($EVAL_ERROR) if ($EVAL_ERROR);
135   }
136   if ($::form->{login} && -f "bin/mozilla/$::form->{login}_$script") {
137     eval {
138       package main;
139       require "bin/mozilla/$::form->{login}_$script";
140     };
141     $::form->error($EVAL_ERROR) if ($EVAL_ERROR);
142   }
143   $::lxdebug->leave_sub;
144 }
145
146 sub _require_controller {
147   my $controller =  shift;
148   $controller    =~ s|[^A-Za-z0-9_]||g;
149   $controller    =  "SL/Controller/${controller}";
150
151   eval {
152     package main;
153     require "${controller}.pm";
154   } or die $EVAL_ERROR;
155 }
156
157 sub _run_controller {
158   "SL::Controller::$_[0]"->new->_run_action($_[1]);
159 }
160
161 sub handle_request {
162   my $self         = shift;
163   $self->{request} = shift;
164
165   $::lxdebug->enter_sub;
166   $::lxdebug->begin_request;
167
168   my ($script, $path, $suffix, $script_name, $action, $routing_type);
169
170   $self->unrequire_bin_mozilla;
171
172   $::locale        = Locale->new($::lx_office_conf{system}->{language});
173   $::form          = Form->new;
174   $::instance_conf = SL::InstanceConfiguration->new;
175   $::request       = { cgi => CGI->new({}) };
176
177   my $session_result = $::auth->restore_session;
178   $::auth->create_or_refresh_session;
179
180   $::form->read_cgi_input;
181
182   eval { ($routing_type, $script_name, $action) = _route_request($ENV{SCRIPT_NAME}); 1; } or return;
183
184   if ($routing_type eq 'old') {
185     $::form->{action}  =  lc $::form->{action};
186     $::form->{action}  =~ s/( |-|,|\#)/_/g;
187
188    ($script, $path, $suffix) = fileparse($script_name, ".pl");
189     require_main_code($script, $suffix);
190
191     $::form->{script} = $script . $suffix;
192
193   } else {
194     _require_controller($script_name);
195     $::form->{script} = "controller.pl";
196   }
197
198   eval {
199     pre_request_checks();
200
201     $::form->error($::locale->text('System currently down for maintenance!')) if -e ($::lx_office_conf{paths}->{userspath} . "/nologin") && $script ne 'admin';
202
203     ($routing_type, $script, $script_name, $action) = qw(controller controller LoginScreen login) if ($script eq 'login') && ($action eq 'login');
204
205     if (($script eq 'login') && !$action) {
206       print $::request->{cgi}->redirect('controller.pl?action=LoginScreen/user_login');
207
208     } elsif ($script eq 'admin') {
209       $::form->{titlebar} = "kivitendo " . $::locale->text('Version') . " $::form->{version}";
210       ::run($session_result);
211
212     } else {
213       show_error('login_screen/user_login', 'session') if SL::Auth::SESSION_EXPIRED == $session_result;
214
215       my %auth_result = $self->{auth_handler}->handle(
216         routing_type => $routing_type,
217         script       => $script,
218         controller   => $script_name,
219         action       => $action,
220       );
221
222       delete @{ $::form }{ grep { m/^\{AUTH\}/ } keys %{ $::form } } unless $auth_result{keep_auth_vars};
223
224       if ($action) {
225         $::instance_conf->init if $auth_result{auth_level} eq 'user';
226
227         map { $::form->{$_} = $::myconfig{$_} } qw(charset)
228           unless $action eq 'save' && $::form->{type} eq 'preferences';
229
230         $::form->set_standard_title;
231         if ($routing_type eq 'old') {
232           ::call_sub('::' . $::locale->findsub($action));
233         } else {
234           _run_controller($script_name, $action);
235         }
236       } else {
237         $::form->error($::locale->text('action= not defined!'));
238       }
239     }
240
241     1;
242   } or do {
243     if ($EVAL_ERROR ne END_OF_REQUEST) {
244       print STDERR $EVAL_ERROR;
245       $::form->{label_error} = $::request->{cgi}->pre($EVAL_ERROR);
246       eval { show_error('generic/error') };
247     }
248   };
249
250   # cleanup
251   $::auth->save_session;
252   $::auth->expire_sessions;
253   $::auth->reset;
254
255   $::locale   = undef;
256   $::form     = undef;
257   $::myconfig = ();
258   $::request  = undef;
259   Form::disconnect_standard_dbh;
260
261   $::lxdebug->end_request;
262
263   $self->_watch_for_changed_files;
264
265   $::lxdebug->leave_sub;
266 }
267
268 sub unrequire_bin_mozilla {
269   my $self = shift;
270   return unless $self->_interface_is_fcgi;
271
272   for (keys %INC) {
273     next unless m#^bin/mozilla/#;
274     next if /\bcommon.pl$/;
275     next if /\binstallationcheck.pl$/;
276     delete $INC{$_};
277   }
278 }
279
280 sub _interface_is_fcgi {
281   my $self = shift;
282   return $self->{interface} =~ m/^(?:fastcgi|fcgid|fcgi)$/;
283 }
284
285 sub _route_request {
286   my $script_name = shift;
287
288   return $script_name =~ m/dispatcher\.pl$/ ? ('old',        _route_dispatcher_request())
289        : $script_name =~ m/controller\.pl/  ? ('controller', _route_controller_request())
290        :                                      ('old',        $script_name, $::form->{action});
291 }
292
293 sub _route_dispatcher_request {
294   my $name_re = qr{[a-z]\w*};
295   my ($script_name, $action);
296
297   eval {
298     die "Unroutable request -- inavlid module name.\n" if !$::form->{M} || ($::form->{M} !~ m/^${name_re}$/);
299     $script_name = $::form->{M} . '.pl';
300
301     if ($::form->{A}) {
302       $action = $::form->{A};
303
304     } else {
305       $action = first { m/^A_${name_re}$/ } keys %{ $::form };
306       die "Unroutable request -- inavlid action name.\n" if !$action;
307
308       delete $::form->{$action};
309       $action = substr $action, 2;
310     }
311
312     delete @{$::form}{qw(M A)};
313
314     1;
315   } or do {
316     $::form->{label_error} = $::request->{cgi}->pre($EVAL_ERROR);
317     show_error('generic/error');
318   };
319
320   return ($script_name, $action);
321 }
322
323 sub _route_controller_request {
324   my ($controller, $action);
325
326   eval {
327     $::form->{action}      =~ m|^ ( [A-Z] [A-Za-z0-9_]* ) / ( [a-z] [a-z0-9_]* ) $|x || die "Unroutable request -- inavlid controller/action.\n";
328     ($controller, $action) =  ($1, $2);
329     delete $::form->{action};
330
331     1;
332   } or do {
333     $::form->{label_error} = $::request->{cgi}->pre($EVAL_ERROR);
334     show_error('generic/error');
335   };
336
337   return ($controller, $action);
338 }
339
340 sub _cache_file_modification_times {
341   my ($self) = @_;
342
343   return unless $self->_interface_is_fcgi && $::lx_office_conf{debug}->{restart_fcgi_process_on_changes};
344
345   require File::Find;
346   require POSIX;
347
348   my $wanted = sub {
349     return unless $File::Find::name =~ m/\.(?:pm|f?pl|html|conf|conf\.default)$/;
350     $fcgi_file_cache{ $File::Find::name } = (stat $File::Find::name)[9];
351   };
352
353   my $cwd = POSIX::getcwd();
354   File::Find::find($wanted, map { "${cwd}/${_}" } qw(config bin SL templates/webpages));
355   map { my $name = "${cwd}/${_}"; $fcgi_file_cache{$name} = (stat $name)[9] } qw(admin.pl dispatcher.fpl);
356 }
357
358 sub _watch_for_changed_files {
359   my ($self) = @_;
360
361   return unless $self->_interface_is_fcgi && $::lx_office_conf{debug}->{restart_fcgi_process_on_changes};
362
363   my $ok = all { (stat($_))[9] == $fcgi_file_cache{$_} } keys %fcgi_file_cache;
364   return if $ok;
365   $::lxdebug->message(LXDebug::DEBUG1(), "Program modifications detected. Restarting.");
366   exit;
367 }
368
369 sub get_standard_filehandles {
370   my $self = shift;
371
372   return $self->{interface} =~ m/f(?:ast)cgi/i ? $self->{request}->GetHandles() : (\*STDIN, \*STDOUT, \*STDERR);
373 }
374
375 sub _check_for_old_config_files {
376   my @old_files = grep { -f "config/${_}" } qw(authentication.pl console.conf lx-erp.conf lx-erp-local.conf);
377   return unless @old_files;
378
379   $::form->{title} = $::locale->text('Old configuration files');
380   $::form->header;
381   print $::form->parse_html_template('login_screen/old_configuration_files', { FILES => \@old_files });
382
383   ::end_of_request();
384 }
385
386 package main;
387
388 use strict;
389
390 sub end_of_request {
391   die SL::Dispatcher->END_OF_REQUEST;
392 }
393
394 1;