]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/WWW/EGCatLoader.pm
LP#1485374: Adjust TZ scope in mod_perl
[working/Evergreen.git] / Open-ILS / src / perlmods / lib / OpenILS / WWW / EGCatLoader.pm
1 package OpenILS::WWW::EGCatLoader;
2 use strict; use warnings;
3 use XML::LibXML;
4 use URI::Escape;
5 use Digest::MD5 qw(md5_hex);
6 use Apache2::Const -compile => qw(OK DECLINED FORBIDDEN HTTP_INTERNAL_SERVER_ERROR REDIRECT HTTP_BAD_REQUEST);
7 use OpenSRF::AppSession;
8 use OpenSRF::EX qw/:try/;
9 use OpenSRF::Utils qw/:datetime/;
10 use OpenSRF::Utils::JSON;
11 use OpenSRF::Utils::Logger qw/$logger/;
12 use OpenILS::Application::AppUtils;
13 use OpenILS::Utils::CStoreEditor qw/:funcs/;
14 use OpenILS::Utils::Fieldmapper;
15 use DateTime::Format::ISO8601;
16 use CGI qw(:all -utf8);
17 use Time::HiRes;
18
19 # EGCatLoader sub-modules 
20 use OpenILS::WWW::EGCatLoader::Util;
21 use OpenILS::WWW::EGCatLoader::Account;
22 use OpenILS::WWW::EGCatLoader::Browse;
23 use OpenILS::WWW::EGCatLoader::Library;
24 use OpenILS::WWW::EGCatLoader::Search;
25 use OpenILS::WWW::EGCatLoader::Record;
26 use OpenILS::WWW::EGCatLoader::Container;
27 use OpenILS::WWW::EGCatLoader::SMS;
28 use OpenILS::WWW::EGCatLoader::Register;
29
30 my $U = 'OpenILS::Application::AppUtils';
31
32 use constant COOKIE_SES => 'ses';
33 use constant COOKIE_LOGGEDIN => 'eg_loggedin';
34 use constant COOKIE_TZ => 'client_tz';
35 use constant COOKIE_PHYSICAL_LOC => 'eg_physical_loc';
36 use constant COOKIE_SSS_EXPAND => 'eg_sss_expand';
37
38 use constant COOKIE_ANON_CACHE => 'anoncache';
39 use constant ANON_CACHE_MYLIST => 'mylist';
40 use constant ANON_CACHE_STAFF_SEARCH => 'staffsearch';
41
42 use constant DEBUG_TIMING => 0;
43
44 sub new {
45     my($class, $apache, $ctx) = @_;
46
47     my $self = bless({}, ref($class) || $class);
48
49     $self->apache($apache);
50     $self->ctx($ctx);
51     $self->cgi(new CGI);
52     $self->timelog("New page");
53
54     OpenILS::Utils::CStoreEditor->init; # just in case
55     $self->editor(new_editor());
56
57     return $self;
58 }
59
60 sub DESTROY {
61     my $self = shift;
62     $ENV{TZ} = $self->ctx->{original_tz}
63         if ($self->ctx && exists $self->ctx->{original_tz});
64 }
65
66 # current Apache2::RequestRec;
67 sub apache {
68     my($self, $apache) = @_;
69     $self->{apache} = $apache if $apache;
70     return $self->{apache};
71 }
72
73 # runtime / template context
74 sub ctx {
75     my($self, $ctx) = @_;
76     $self->{ctx} = $ctx if $ctx;
77     return $self->{ctx};
78 }
79
80 # cstore editor
81 sub editor {
82     my($self, $editor) = @_;
83     $self->{editor} = $editor if $editor;
84     return $self->{editor};
85 }
86
87 # CGI handle
88 sub cgi {
89     my($self, $cgi) = @_;
90     $self->{cgi} = $cgi if $cgi;
91     return $self->{cgi};
92 }
93
94 sub timelog {
95     my($self, $description) = @_;
96
97     return unless DEBUG_TIMING;
98     return unless $description;
99     $self->ctx->{timing} ||= [];
100     
101     my $timer = [Time::HiRes::gettimeofday()];
102     $self->ctx->{time_begin} ||= $timer;
103
104     push @{$self->ctx->{timing}}, [
105         Time::HiRes::tv_interval($self->ctx->{time_begin}, $timer), $description
106     ];
107 }
108
109 # -----------------------------------------------------------------------------
110 # Perform initial setup, load common data, then load page data
111 # -----------------------------------------------------------------------------
112 sub load {
113     my $self = shift;
114
115     $self->init_ro_object_cache;
116     $self->timelog("Initial load");
117
118     my $stat = $self->load_common;
119     return $stat unless $stat == Apache2::Const::OK;
120
121     my $path = $self->apache->path_info;
122
123     if ($path =~ m|opac/?$|) {
124         # nowhere specified, just go home
125         return $self->generic_redirect($self->ctx->{home_page});
126     }
127
128     (undef, $self->ctx->{mylist}) = $self->fetch_mylist unless
129         $path =~ /opac\/my(opac\/lists|list)/;
130
131     return $self->load_simple("home") if $path =~ m|opac/home|;
132     return $self->load_simple("css") if $path =~ m|opac/css|;
133     return $self->load_simple("advanced") if
134         $path =~ m:opac/(advanced|numeric|expert):;
135
136     return $self->load_library if $path =~ m|opac/library|;
137     return $self->load_rresults if $path =~ m|opac/results|;
138     return $self->load_print_record if $path =~ m|opac/record/print|;
139     return $self->load_record if $path =~ m|opac/record/\d|;
140     return $self->load_cnbrowse if $path =~ m|opac/cnbrowse|;
141     return $self->load_browse if $path =~ m|opac/browse|;
142
143     return $self->load_mylist_add if $path =~ m|opac/mylist/add|;
144     return $self->load_mylist_delete if $path =~ m|opac/mylist/delete|;
145     return $self->load_mylist_move if $path =~ m|opac/mylist/move|;
146     return $self->load_mylist if $path =~ m|opac/mylist|;
147     return $self->load_cache_clear if $path =~ m|opac/cache/clear|;
148     return $self->load_temp_warn_post if $path =~ m|opac/temp_warn/post|;
149     return $self->load_temp_warn if $path =~ m|opac/temp_warn|;
150
151     # ----------------------------------------------------------------
152     #  Everything below here requires SSL
153     # ----------------------------------------------------------------
154     return $self->redirect_ssl unless $self->cgi->https;
155     return $self->load_password_reset if $path =~ m|opac/password_reset|;
156     return $self->load_logout if $path =~ m|opac/logout|;
157     return $self->load_patron_reg if $path =~ m|opac/register|;
158
159     if($path =~ m|opac/login|) {
160         return $self->load_login unless $self->editor->requestor; # already logged in?
161
162         # This will be less confusing to users than to be shown a login form
163         # when they're already logged in.
164         return $self->generic_redirect(
165             sprintf(
166                 "%s://%s%s/myopac/main",
167                 $self->ctx->{proto},
168                 $self->ctx->{hostname}, $self->ctx->{opac_root}
169             )
170         );
171     }
172
173     if ($path =~ m|opac/sms_cn| and !$self->editor->requestor) {
174         my $org_unit = $self->ctx->{physical_loc} || $self->cgi->param('loc') || $self->ctx->{aou_tree}->()->id;
175         my $skip_sms_auth = $self->ctx->{get_org_setting}->($org_unit, 'sms.disable_authentication_requirement.callnumbers');
176         return $self->load_sms_cn if $skip_sms_auth;
177     }
178
179     # ----------------------------------------------------------------
180     #  Everything below here requires authentication
181     # ----------------------------------------------------------------
182     return $self->redirect_auth unless $self->editor->requestor;
183
184     # Don't cache anything requiring auth for security reasons
185     $self->apache->headers_out->add("cache-control" => "no-store, no-cache, must-revalidate");
186     $self->apache->headers_out->add("expires" => "-1");
187
188     return $self->load_email_record if $path =~ m|opac/record/email|;
189
190     return $self->load_place_hold if $path =~ m|opac/place_hold|;
191     return $self->load_myopac_holds if $path =~ m|opac/myopac/holds|;
192     return $self->load_myopac_circs if $path =~ m|opac/myopac/circs|;
193     return $self->load_myopac_messages if $path =~ m|opac/myopac/messages|;
194     return $self->load_myopac_payment_form if $path =~ m|opac/myopac/main_payment_form|;
195     return $self->load_myopac_payments if $path =~ m|opac/myopac/main_payments|;
196     return $self->load_myopac_pay_init if $path =~ m|opac/myopac/main_pay_init|;
197     return $self->load_myopac_pay if $path =~ m|opac/myopac/main_pay|;
198     return $self->load_myopac_main if $path =~ m|opac/myopac/main|;
199     return $self->load_myopac_receipt_email if $path =~ m|opac/myopac/receipt_email|;
200     return $self->load_myopac_receipt_print if $path =~ m|opac/myopac/receipt_print|;
201     return $self->load_myopac_update_email if $path =~ m|opac/myopac/update_email|;
202     return $self->load_myopac_update_password if $path =~ m|opac/myopac/update_password|;
203     return $self->load_myopac_update_username if $path =~ m|opac/myopac/update_username|;
204     return $self->load_myopac_bookbags if $path =~ m|opac/myopac/lists|;
205     return $self->load_myopac_bookbag_print if $path =~ m|opac/myopac/list/print|;
206     return $self->load_myopac_bookbag_update if $path =~ m|opac/myopac/list/update|;
207     return $self->load_myopac_circ_history_export if $path =~ m|opac/myopac/circ_history/export|;
208     return $self->load_myopac_circ_history if $path =~ m|opac/myopac/circ_history|;
209     return $self->load_myopac_hold_history if $path =~ m|opac/myopac/hold_history|;
210     return $self->load_myopac_prefs_notify if $path =~ m|opac/myopac/prefs_notify|;
211     return $self->load_myopac_prefs_settings if $path =~ m|opac/myopac/prefs_settings|;
212     return $self->load_myopac_prefs_my_lists if $path =~ m|opac/myopac/prefs_my_lists|;
213     return $self->load_myopac_prefs if $path =~ m|opac/myopac/prefs|;
214     return $self->load_sms_cn if $path =~ m|opac/sms_cn|;
215
216     return Apache2::Const::OK;
217 }
218
219
220 # -----------------------------------------------------------------------------
221 # Redirect to SSL equivalent of a given page
222 # -----------------------------------------------------------------------------
223 sub redirect_ssl {
224     my $self = shift;
225     my $new_page = sprintf('%s://%s%s', ($self->ctx->{is_staff} ? 'oils' : 'https'), $self->ctx->{hostname}, $self->apache->unparsed_uri);
226     return $self->generic_redirect($new_page);
227 }
228
229 # -----------------------------------------------------------------------------
230 # If an authnticated resource is requested w/o auth, redirect to the login page,
231 # then return to the originally requrested resource upon successful login.
232 # -----------------------------------------------------------------------------
233 sub redirect_auth {
234     my $self = shift;
235     my $login_page = sprintf('%s://%s%s/login',($self->ctx->{is_staff} ? 'oils' : 'https'), $self->ctx->{hostname}, $self->ctx->{opac_root});
236     my $redirect_to = uri_escape_utf8($self->apache->unparsed_uri);
237     return $self->generic_redirect("$login_page?redirect_to=$redirect_to");
238 }
239
240 # -----------------------------------------------------------------------------
241 # Fall-through for loading a basic page
242 # -----------------------------------------------------------------------------
243 sub load_simple {
244     my ($self, $page) = @_;
245     $self->ctx->{page} = $page;
246     $self->ctx->{search_ou} = $self->_get_search_lib();
247
248     return Apache2::Const::OK;
249 }
250
251 # -----------------------------------------------------------------------------
252 # Tests to see if the user is authenticated and sets some common context values
253 # -----------------------------------------------------------------------------
254 sub load_common {
255     my $self = shift;
256
257     my $e = $self->editor;
258     my $ctx = $self->ctx;
259
260     # redirect non-https to https if we think we are already logged in
261     if ($self->cgi->cookie(COOKIE_LOGGEDIN)) {
262         return $self->redirect_ssl unless $self->cgi->https;
263     }
264
265     # XXX Cache this? Makes testing difficult as apache needs a restart.
266     my $default_sort = $e->retrieve_config_global_flag('opac.default_sort');
267     $ctx->{default_sort} =
268         ($default_sort && $U->is_true($default_sort->enabled)) ? $default_sort->value : '';
269
270     $ctx->{client_tz} = $self->cgi->cookie(COOKIE_TZ) || $ENV{TZ};
271     $ctx->{referer} = $self->cgi->referer;
272     $ctx->{path_info} = $self->cgi->path_info;
273     $ctx->{full_path} = $ctx->{base_path} . $self->cgi->path_info;
274     $ctx->{unparsed_uri} = $self->apache->unparsed_uri;
275     $ctx->{opac_root} = $ctx->{base_path} . "/opac"; # absolute base url
276
277     $ctx->{original_tz} = $ENV{TZ};
278     $ENV{TZ} = $ctx->{client_tz};
279
280     my $xul_wrapper = 
281         ($self->apache->headers_in->get('OILS-Wrapper') || '') =~ /true/;
282
283     if ($xul_wrapper) {
284         # XUL client
285         $ctx->{is_staff} = 1;
286         $ctx->{proto} = 'oils';
287         $ctx->{hostname} = 'remote';
288     }
289
290     $ctx->{physical_loc} = $self->get_physical_loc;
291
292     # capture some commonly accessed pages
293     $ctx->{home_page} = $ctx->{proto} . '://' . $ctx->{hostname} . $self->ctx->{opac_root} . "/home";
294     $ctx->{logout_page} = ($ctx->{proto} eq 'http' ? 'https' : $ctx->{proto} ) . '://' . $ctx->{hostname} . $self->ctx->{opac_root} . "/logout";
295
296     if($e->authtoken($self->cgi->cookie(COOKIE_SES))) {
297
298         if($e->checkauth) {
299
300             $ctx->{authtoken} = $e->authtoken;
301             $ctx->{authtime} = $e->authtime;
302             $ctx->{user} = $e->requestor;
303             $ctx->{place_unfillable} = 1 if $e->requestor->wsid && $e->allowed('PLACE_UNFILLABLE_HOLD', $e->requestor->ws_ou);
304
305             # The browser client does not set an OILS-Wrapper header (above).
306             # The presence of a workstation and no header indicates staff mode.
307             # FIXME: this approach leaves un-wrapped TPAC's within the same
308             # browser (and hence same ses cookie) in an unnatural is_staff
309             # state.  Consider alternatives for determining is_staff / 
310             # is_browser_staff when $xul_wrapper is false.
311             if (!$xul_wrapper and $e->requestor->wsid) {
312                 $ctx->{is_staff} = 1;
313                 $ctx->{is_browser_staff} = 1;
314             }
315
316             $self->update_dashboard_stats();
317
318         } else {
319
320             # if we encounter a stale authtoken, call load_logout 
321             # to clean up the cookie, then redirect the user to the
322             # originally requested page
323             return $self->load_logout($self->apache->unparsed_uri);
324         }
325     }
326
327     # List of <meta> and <link> elements to populate
328     $ctx->{metalinks} = [];
329
330     $self->extract_copy_location_group_info;
331     $ctx->{search_ou} = $self->_get_search_lib();
332     $self->staff_saved_searches_set_expansion_state if $ctx->{is_staff};
333     $self->load_eg_cache_hash;
334     $self->load_copy_location_groups;
335     $self->staff_saved_searches_set_expansion_state if $ctx->{is_staff};
336     $self->load_search_filter_groups($ctx->{search_ou});
337     $self->load_org_util_funcs;
338     $self->load_perm_funcs;
339
340     return Apache2::Const::OK;
341 }
342
343 sub update_dashboard_stats {
344     my $self = shift;
345
346     my $e = $self->editor;
347     my $ctx = $self->ctx;
348
349     $ctx->{user_stats} = $U->simplereq(
350         'open-ils.actor', 
351         'open-ils.actor.user.opac.vital_stats', 
352         $e->authtoken, $e->requestor->id);
353 }
354
355 sub staff_saved_searches_set_expansion_state {
356     my $self = shift;
357
358     my $param = $self->cgi->param('sss_expand');
359     my $value;
360     
361     if (defined $param) {
362         $value = ($param ? 1 : 0);
363         $self->apache->headers_out->add(
364             "Set-Cookie" => $self->cgi->cookie(
365                 -name => COOKIE_SSS_EXPAND,
366                 -path => $self->ctx->{base_path},
367                 -secure => 1,   # not strictly necessary, but this feature is staff-only, so may as well
368                 -value => $value,
369                 -expires => undef
370             )
371         );
372     } else {
373         $value = $self->cgi->cookie(COOKIE_SSS_EXPAND);
374     }
375
376     $self->ctx->{saved_searches_expanded} = $value;
377 }
378
379 # physical_loc (i.e. "original location") passed in as a URL 
380 # param will replace any existing physical_loc stored as a cookie.
381 # If specified via ENV that rules over all and we don't set cookies.
382 sub get_physical_loc {
383     my $self = shift;
384
385     return $ENV{physical_loc} if($ENV{physical_loc});
386
387     if(my $physical_loc = $self->cgi->param('physical_loc')) {
388         $self->apache->headers_out->add(
389             "Set-Cookie" => $self->cgi->cookie(
390                 -name => COOKIE_PHYSICAL_LOC,
391                 -path => $self->ctx->{base_path},
392                 -value => $physical_loc,
393                 -expires => undef
394             )
395         );
396         return $physical_loc;
397     }
398
399     return $self->cgi->cookie(COOKIE_PHYSICAL_LOC);
400 }
401
402 # -----------------------------------------------------------------------------
403 # Log in and redirect to the redirect_to URL (or home)
404 # -----------------------------------------------------------------------------
405 sub load_login {
406     my $self = shift;
407     my $cgi = $self->cgi;
408     my $ctx = $self->ctx;
409
410     $self->timelog("Load login begins");
411
412     $ctx->{page} = 'login';
413
414     my $username = $cgi->param('username') || '';
415     $username =~ s/\s//g;  # Remove blanks
416     my $password = $cgi->param('password');
417     my $org_unit = $ctx->{physical_loc} || $ctx->{aou_tree}->()->id;
418     my $persist = $cgi->param('persist');
419     my $client_tz = $cgi->param('client_tz');
420
421     # initial log form only
422     return Apache2::Const::OK unless $username and $password;
423
424     my $auth_proxy_enabled = 0; # default false
425     try { # if the service is not running, just let this fail silently
426         $auth_proxy_enabled = $U->simplereq(
427             'open-ils.auth_proxy',
428             'open-ils.auth_proxy.enabled');
429     } catch Error with {};
430
431     $self->timelog("Checked for auth proxy: $auth_proxy_enabled; org = $org_unit; username = $username");
432
433     my $args = {
434         type => ($persist) ? 'persist' : 'opac',
435         org => $org_unit,
436         agent => 'opac'
437     };
438
439     my $bc_regex = $ctx->{get_org_setting}->($org_unit, 'opac.barcode_regex');
440
441     # To avoid surprises, default to "Barcodes start with digits"
442     $bc_regex = '^\d' unless $bc_regex;
443
444     if ($bc_regex and ($username =~ /$bc_regex/)) {
445         $args->{barcode} = $username;
446     } else {
447         $args->{username} = $username;
448     }
449
450     my $response;
451     if (!$auth_proxy_enabled) {
452         my $seed = $U->simplereq(
453             'open-ils.auth',
454             'open-ils.auth.authenticate.init', $username);
455         $args->{password} = md5_hex($seed . md5_hex($password));
456         $response = $U->simplereq(
457             'open-ils.auth', 'open-ils.auth.authenticate.complete', $args);
458     } else {
459         $args->{password} = $password;
460         $response = $U->simplereq(
461             'open-ils.auth_proxy',
462             'open-ils.auth_proxy.login', $args);
463     }
464     $self->timelog("Checked password");
465
466     if($U->event_code($response)) { 
467         # login failed, report the reason to the template
468         $ctx->{login_failed_event} = $response;
469         return Apache2::Const::OK;
470     }
471
472     # login succeeded, redirect as necessary
473
474     my $acct = $self->apache->unparsed_uri;
475     $acct =~ s|/login|/myopac/main|;
476
477     # both login-related cookies should expire at the same time
478     my $login_cookie_expires = ($persist) ? CORE::time + $response->{payload}->{authtime} : undef;
479
480     my $cookie_list = [
481         # contains the actual auth token and should be sent only over https
482         $cgi->cookie(
483             -name => COOKIE_SES,
484             -path => '/',
485             -secure => 1,
486             -value => $response->{payload}->{authtoken},
487             -expires => $login_cookie_expires
488         ),
489         # contains only a hint that we are logged in, and is used to
490         # trigger a redirect to https
491         $cgi->cookie(
492             -name => COOKIE_LOGGEDIN,
493             -path => '/',
494             -secure => 0,
495             -value => '1',
496             -expires => $login_cookie_expires
497         )
498     ];
499
500     if ($client_tz) {
501         # contains the client's tz, as passed by the client
502         # trigger a redirect to https
503         push @$cookie_list, $cgi->cookie(
504             -name => COOKIE_TZ,
505             -path => '/',
506             -secure => 0,
507             -value => $client_tz,
508             -expires => $login_cookie_expires
509         );
510     }
511
512     return $self->generic_redirect(
513         $cgi->param('redirect_to') || $acct,
514         $cookie_list
515     );
516 }
517
518 # -----------------------------------------------------------------------------
519 # Log out and redirect to the home page
520 # -----------------------------------------------------------------------------
521 sub load_logout {
522     my $self = shift;
523     my $redirect_to = shift || $self->cgi->param('redirect_to');
524
525     # If the user was adding anyting to an anonymous cache 
526     # while logged in, go ahead and clear it out.
527     $self->clear_anon_cache;
528
529     try { # a missing auth token will cause an ugly explosion
530         $U->simplereq(
531             'open-ils.auth',
532             'open-ils.auth.session.delete',
533             $self->cgi->cookie(COOKIE_SES)
534         );
535     } catch Error with {};
536
537     return $self->generic_redirect(
538         $redirect_to || $self->ctx->{home_page},
539         [
540             # clear value of and expire both of these login-related cookies
541             $self->cgi->cookie(
542                 -name => COOKIE_SES,
543                 -path => '/',
544                 -value => '',
545                 -expires => '-1h'
546             ),
547             $self->cgi->cookie(
548                 -name => COOKIE_LOGGEDIN,
549                 -path => '/',
550                 -value => '',
551                 -expires => '-1h'
552             )
553         ]
554     );
555 }
556
557 1;
558