Login: Callback nur bauen bei GET-Request und wenn action vorhanden
[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 use Carp;
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 FCGI;
17 use File::Basename;
18 use IO::File;
19 use List::MoreUtils qw(all);
20 use List::Util qw(first);
21 use POSIX qw(setlocale);
22 use SL::ArchiveZipFixes;
23 use SL::Auth;
24 use SL::Dispatcher::AuthHandler;
25 use SL::LXDebug;
26 use SL::LxOfficeConf;
27 use SL::Locale;
28 use SL::ClientJS;
29 use SL::Common;
30 use SL::Form;
31 use SL::Helper::DateTime;
32 use SL::InstanceConfiguration;
33 use SL::MoreCommon qw(uri_encode);
34 use SL::Template::Plugin::HTMLFixes;
35 use SL::User;
36
37 use Rose::Object::MakeMethods::Generic (
38   scalar => [ qw(restart_after_request) ],
39 );
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   SL::ArchiveZipFixes->apply_fixes;
55
56   # Initialize character type locale to be UTF-8 instead of C:
57   foreach my $locale (qw(de_DE.UTF-8 en_US.UTF-8)) {
58     last if setlocale('LC_CTYPE', $locale);
59   }
60
61   return $self;
62 }
63
64 sub interface_type {
65   my ($self) = @_;
66   return $self->{interface} eq 'cgi' ? 'CGI' : 'FastCGI';
67 }
68
69 sub is_admin_request {
70   my %params = @_;
71   return ($params{script} eq 'admin.pl') || (($params{routing_type} eq 'controller') && ($params{script_name} eq 'Admin'));
72 }
73
74 sub pre_request_checks {
75   my (%params) = @_;
76
77   _check_for_old_config_files();
78
79   if (!$::auth->session_tables_present && !is_admin_request(%params)) {
80     show_error('login_screen/auth_db_unreachable');
81   }
82
83   if ($::request->type !~ m/^ (?: html | js | json ) $/x) {
84     die $::locale->text("Invalid request type '#1'", $::request->type);
85   }
86 }
87
88 sub pre_request_initialization {
89   my ($self, %params) = @_;
90
91   $self->unrequire_bin_mozilla;
92
93   $::locale        = Locale->new($::lx_office_conf{system}->{language});
94   $::form          = Form->new;
95   $::instance_conf = SL::InstanceConfiguration->new;
96   $::request       = SL::Request->new(
97     cgi            => CGI->new({}),
98     layout         => SL::Layout::None->new,
99   );
100
101   my $session_result = $::auth->restore_session;
102   $::auth->create_or_refresh_session;
103
104   if ($params{client}) {
105     $::auth->set_client($params{client}) || die("cannot find client " . $params{client});
106
107     if ($params{login}) {
108       die "cannot find user " . $params{login}            unless %::myconfig = $::auth->read_user(login => $params{login});
109       die "cannot find locale for user " . $params{login} unless $::locale   = Locale->new($::myconfig{countrycode});
110
111       $::form->{login} = $params{login}; # normaly implicit at login
112     }
113   }
114
115   return $session_result;
116 }
117
118 sub render_error_ajax {
119   my ($error) = @_;
120
121   SL::ClientJS->new
122     ->error($error)
123     ->render(SL::Controller::Base->new);
124 }
125
126 sub show_error {
127   $::lxdebug->enter_sub;
128   my $template             = shift;
129   my $error_type           = shift || '';
130   my %params               = @_;
131
132   $::myconfig{countrycode} = delete($params{countrycode}) || $::lx_office_conf{system}->{language};
133   $::locale                = Locale->new($::myconfig{countrycode});
134   $::form->{error}         = $::locale->text('The session is invalid or has expired.') if ($error_type eq 'session');
135   $::form->{error}         = $::locale->text('Incorrect password!')                    if ($error_type eq 'password');
136   $::form->{error}         = $::locale->text('The action is missing or invalid.')      if ($error_type eq 'action');
137
138   return render_error_ajax($::form->{error}) if $::request->is_ajax;
139
140   $::form->header;
141   print $::form->parse_html_template($template, \%params);
142   $::lxdebug->leave_sub;
143
144   end_request();
145 }
146
147 sub pre_startup_setup {
148   my ($self) = @_;
149
150   SL::LxOfficeConf->read;
151
152   eval {
153     package main;
154     require "bin/mozilla/common.pl";
155     require "bin/mozilla/installationcheck.pl";
156   } or die $EVAL_ERROR;
157
158   # canonial globals. if it's not here, chances are it will get refactored someday.
159   {
160     no warnings 'once';
161     $::lxdebug     = LXDebug->new;
162     $::auth        = SL::Auth->new;
163     $::form        = undef;
164     $::request     = undef;
165     %::myconfig    = User->get_default_myconfig;
166   }
167
168   $SIG{__WARN__} = sub {
169     $::lxdebug->warn(@_);
170   };
171
172   $SIG{__DIE__} = sub { Carp::confess( @_ ) } if $::lx_office_conf{debug}->{backtrace_on_die};
173
174   $self->_cache_file_modification_times;
175 }
176
177 sub pre_startup_checks {
178   ::verify_installation();
179 }
180
181 sub pre_startup {
182   my ($self) = @_;
183   $self->pre_startup_setup;
184   $self->pre_startup_checks;
185 }
186
187 sub require_main_code {
188   $::lxdebug->enter_sub;
189   my ($script, $suffix) = @_;
190
191   eval {
192     package main;
193     require "bin/mozilla/$script$suffix";
194   } or die $EVAL_ERROR;
195
196   if (-f "bin/mozilla/custom_$script$suffix") {
197     eval {
198       package main;
199       require "bin/mozilla/custom_$script$suffix";
200     };
201     $::form->error($EVAL_ERROR) if ($EVAL_ERROR);
202   }
203   if ($::form->{login} && -f "bin/mozilla/$::form->{login}_$script") {
204     eval {
205       package main;
206       require "bin/mozilla/$::form->{login}_$script";
207     };
208     $::form->error($EVAL_ERROR) if ($EVAL_ERROR);
209   }
210   $::lxdebug->leave_sub;
211 }
212
213 sub _require_controller {
214   my $controller =  shift;
215   $controller    =~ s|[^A-Za-z0-9_]||g;
216   $controller    =  "SL/Controller/${controller}";
217
218   eval {
219     package main;
220     require "${controller}.pm";
221   } or die $EVAL_ERROR;
222 }
223
224 sub _run_controller {
225   "SL::Controller::$_[0]"->new->_run_action($_[1]);
226 }
227
228 sub handle_all_requests {
229   my ($self) = @_;
230
231   my $request = FCGI::Request();
232   while ($request->Accept() >= 0) {
233     $self->handle_request($request);
234
235     $self->restart_after_request(1) if $self->_interface_is_fcgi && SL::System::Process::memory_usage_is_too_high();
236     $request->LastCall              if $self->restart_after_request;
237   }
238
239   exec $0 if $self->restart_after_request;
240 }
241
242 sub handle_request {
243   my $self         = shift;
244   $self->{request} = shift;
245
246   $::lxdebug->enter_sub;
247   $::lxdebug->begin_request;
248
249   my ($script, $path, $suffix, $script_name, $action, $routing_type);
250
251   my $session_result = $self->pre_request_initialization;
252
253   $::form->read_cgi_input;
254
255   my %routing;
256   eval { %routing = $self->_route_request($ENV{SCRIPT_NAME}); 1; } or return;
257   ($routing_type, $script_name, $action) = @routing{qw(type controller action)};
258   $::lxdebug->log_request($routing_type, $script_name, $action);
259
260   $::request->type(lc($routing{request_type} || 'html'));
261
262   if ($routing_type eq 'old') {
263     $::form->{action}  =  lc $::form->{action};
264     $::form->{action}  =~ s/( |-|,|\#)/_/g;
265
266    ($script, $path, $suffix) = fileparse($script_name, ".pl");
267     require_main_code($script, $suffix) unless $script eq 'admin';
268
269     $::form->{script} = $script . $suffix;
270
271   } else {
272     _require_controller($script_name);
273     $::form->{script} = "controller.pl";
274   }
275
276   eval {
277     pre_request_checks(script => $script, action => $action, routing_type => $routing_type, script_name => $script_name);
278
279     if (   SL::System::InstallationLock->is_locked
280         && !is_admin_request(script => $script, script_name => $script_name, routing_type => $routing_type)) {
281       $::form->error($::locale->text('System currently down for maintenance!'));
282     }
283
284     # For compatibility with a lot of database upgrade scripts etc:
285     # Re-write request to old 'login.pl?action=login' to new
286     # 'LoginScreen' controller. Make sure to load its code!
287     if (($script eq 'login') && ($action eq 'login')) {
288       ($routing_type, $script, $script_name, $action) = qw(controller controller LoginScreen login);
289       _require_controller('LoginScreen');
290     }
291
292     if (   (($script eq 'login') && !$action)
293         || ($script eq 'admin')
294         || (SL::Auth::SESSION_EXPIRED() == $session_result)) {
295       $self->handle_login_error(routing_type => $routing_type,
296                                 script       => $script,
297                                 controller   => $script_name,
298                                 action       => $action,
299                                 error        => 'session');
300     }
301
302     my %auth_result = $self->{auth_handler}->handle(
303       routing_type => $routing_type,
304       script       => $script,
305       controller   => $script_name,
306       action       => $action,
307     );
308
309     $self->end_request unless $auth_result{auth_ok};
310
311     delete @{ $::form }{ grep { m/^\{AUTH\}/ } keys %{ $::form } } unless $auth_result{keep_auth_vars};
312
313     if ($action) {
314       $::form->set_standard_title;
315       if ($routing_type eq 'old') {
316         ::call_sub('::' . $::locale->findsub($action));
317       } else {
318         _run_controller($script_name, $action);
319       }
320     } else {
321       $::form->error($::locale->text('action= not defined!'));
322     }
323
324     1;
325   } or do {
326     if (substr($EVAL_ERROR, 0, length(END_OF_REQUEST())) ne END_OF_REQUEST()) {
327       my $error = $EVAL_ERROR;
328       print STDERR $error;
329
330       if ($::request->is_ajax) {
331         eval { render_error_ajax($error) };
332       } else {
333         $::form->{label_error} = $::request->{cgi}->pre($error);
334         chdir SL::System::Process::exe_dir;
335         eval { show_error('generic/error') };
336       }
337     }
338   };
339
340   $::form->footer;
341
342   if ($self->_interface_is_fcgi) {
343     # fcgi? send send reponse on its way before cleanup.
344     $self->{request}->Flush;
345     $self->{request}->Finish;
346   }
347
348   $::lxdebug->end_request(routing_type => $routing_type, script_name => $script_name, action => $action);
349
350   # cleanup
351   $::auth->save_session;
352   $::auth->expire_sessions;
353   $::auth->reset;
354
355   $::locale   = undef;
356   $::form     = undef;
357   %::myconfig = ();
358   $::request  = undef;
359
360   SL::DBConnect::Cache->reset_all;
361
362   $self->_watch_for_changed_files;
363
364   $::lxdebug->leave_sub;
365 }
366
367 sub reply_with_json_error {
368   my ($self, %params) = @_;
369
370   my %errors = (
371     session  => { code => '401 Unauthorized',          text => 'session expired' },
372     password => { code => '401 Unauthorized',          text => 'incorrect username or password' },
373     action   => { code => '400 Bad request',           text => 'incorrect or missing action' },
374     access   => { code => '403 Forbidden',             text => 'no permissions for accessing this function' },
375     _default => { code => '500 Internal server error', text => 'general server-side error' },
376   );
377
378   my $error = $errors{$params{error}} // $errors{_default};
379   my $reply = SL::JSON::to_json({ status => 'failed', error => $error->{text} });
380
381   print $::request->cgi->header(
382     -type    => 'application/json',
383     -charset => 'utf-8',
384     -status  => $error->{code},
385   );
386
387   print $reply;
388
389   $self->end_request;
390 }
391
392 sub handle_login_error {
393   my ($self, %params) = @_;
394
395   return $self->reply_with_json_error(error => $params{error}) if $::request->type eq 'json';
396
397   my $action          = ($params{script} // '') =~ m/^admin/i ? 'Admin/login' : 'LoginScreen/user_login';
398   $action            .= '&error=' . $params{error} if $params{error};
399
400   my $redirect_url = "controller.pl?action=${action}";
401
402   if (   $action =~ m/LoginScreen\/user_login/
403       && $params{action}
404       && 'get' eq lc($ENV{REQUEST_METHOD})
405   ) {
406
407     require SL::Controller::Base;
408     my $controller = SL::Controller::Base->new;
409
410     delete $params{error};
411     delete $params{routing_type};
412     delete @{ $::form }{ grep { m/^\{AUTH\}/ } keys %{ $::form } };
413
414     my $callback   = $controller->url_for(%params, %{$::form});
415     $redirect_url .= '&callback=' . uri_encode($callback);
416   }
417
418   print $::request->cgi->redirect($redirect_url);
419   $self->end_request;
420 }
421
422 sub unrequire_bin_mozilla {
423   my $self = shift;
424   return unless $self->_interface_is_fcgi;
425
426   for (keys %INC) {
427     next unless m#^bin/mozilla/#;
428     next if /\bcommon.pl$/;
429     next if /\binstallationcheck.pl$/;
430     delete $INC{$_};
431   }
432 }
433
434 sub _interface_is_fcgi {
435   my $self = shift;
436   return $self->{interface} =~ m/^(?:fastcgi|fcgid|fcgi)$/;
437 }
438
439 sub _route_request {
440   my ($self, $script_name) = @_;
441
442   return $script_name =~ m/dispatcher\.pl$/ ? (type => 'old',        $self->_route_dispatcher_request)
443        : $script_name =~ m/controller\.pl/  ? (type => 'controller', $self->_route_controller_request)
444        :                                      (type => 'old',        controller => $script_name, action => $::form->{action});
445 }
446
447 sub _route_dispatcher_request {
448   my ($self)  = @_;
449   my $name_re = qr{[a-z]\w*};
450   my ($script_name, $action);
451
452   eval {
453     die "Unroutable request -- invalid module name.\n" if !$::form->{M} || ($::form->{M} !~ m/^${name_re}$/);
454     $script_name = $::form->{M} . '.pl';
455
456     if ($::form->{A}) {
457       $action = $::form->{A};
458
459     } else {
460       $action = first { m/^A_${name_re}$/ } keys %{ $::form };
461       die "Unroutable request -- invalid action name.\n" if !$action;
462
463       delete $::form->{$action};
464       $action = substr $action, 2;
465     }
466
467     delete @{$::form}{qw(M A)};
468
469     1;
470   } or do {
471     $::form->{label_error} = $::request->{cgi}->pre($EVAL_ERROR);
472     show_error('generic/error');
473   };
474
475   return (controller => $script_name, action => $action);
476 }
477
478 sub _route_controller_request {
479   my ($self) = @_;
480   my ($controller, $action, $request_type);
481
482   eval {
483     # Redirect simple requests to controller.pl without any GET/POST
484     # param to the login page.
485     $self->handle_login_error(error => 'action') if !$::form->{action};
486
487     # Show an error if the »action« parameter doesn't match the
488     # pattern »Controller/action«.
489     $::form->{action}      =~ m|^ ( [A-Z] [A-Za-z0-9_]* ) / ( [a-z] [a-z0-9_]* ) ( \. [a-zA-Z]+ )? $|x || die "Unroutable request -- invalid controller/action.\n";
490     ($controller, $action) =  ($1, $2);
491     delete $::form->{action};
492
493     $request_type = $3 ? lc(substr($3, 1)) : 'html';
494
495     1;
496   } or do {
497     $::form->{label_error} = $::request->{cgi}->pre($EVAL_ERROR);
498     show_error('generic/error');
499   };
500
501   return (controller => $controller, action => $action, request_type => $request_type);
502 }
503
504 sub _cache_file_modification_times {
505   my ($self) = @_;
506
507   return unless $self->_interface_is_fcgi && $::lx_office_conf{debug}->{restart_fcgi_process_on_changes};
508
509   require File::Find;
510   require POSIX;
511
512   my $wanted = sub {
513     return unless $File::Find::name =~ m/\.(?:pm|f?pl|html|conf|conf\.default)$/;
514     $fcgi_file_cache{ $File::Find::name } = (stat $File::Find::name)[9];
515   };
516
517   my $cwd = POSIX::getcwd();
518   File::Find::find($wanted, map { "${cwd}/${_}" } qw(config bin SL templates/webpages));
519   map { my $name = "${cwd}/${_}"; $fcgi_file_cache{$name} = (stat $name)[9] } qw(admin.pl dispatcher.fpl);
520 }
521
522 sub _watch_for_changed_files {
523   my ($self) = @_;
524
525   return unless $self->_interface_is_fcgi && $::lx_office_conf{debug}->{restart_fcgi_process_on_changes};
526
527   my $ok = all { (stat($_))[9] == $fcgi_file_cache{$_} } keys %fcgi_file_cache;
528   return if $ok;
529   $::lxdebug->message(LXDebug::DEBUG1(), "Program modifications detected. Restarting.");
530   $self->restart_after_request(1);
531 }
532
533 sub get_standard_filehandles {
534   my $self = shift;
535
536   return $self->{interface} =~ m/f(?:ast)cgi/i ? $self->{request}->GetHandles() : (\*STDIN, \*STDOUT, \*STDERR);
537 }
538
539 sub _check_for_old_config_files {
540   my @old_files = grep { -f "config/${_}" } qw(authentication.pl console.conf lx-erp.conf lx-erp-local.conf);
541   return unless @old_files;
542
543   $::form->{title} = $::locale->text('Old configuration files');
544   $::form->header;
545   print $::form->parse_html_template('login_screen/old_configuration_files', { FILES => \@old_files });
546
547   end_request();
548 }
549
550 sub end_request {
551   die SL::Dispatcher->END_OF_REQUEST;
552 }
553
554 1;