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