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