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