1 package OpenILS::WWW::EGCatLoader;
2 use strict; use warnings;
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 OpenILS::Utils::DateTime 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 OpenSRF::Utils::Cache;
16 use DateTime::Format::ISO8601;
17 use CGI qw(:all -utf8);
20 # EGCatLoader sub-modules
21 use OpenILS::WWW::EGCatLoader::Util;
22 use OpenILS::WWW::EGCatLoader::Account;
23 use OpenILS::WWW::EGCatLoader::Browse;
24 use OpenILS::WWW::EGCatLoader::Library;
25 use OpenILS::WWW::EGCatLoader::Search;
26 use OpenILS::WWW::EGCatLoader::Record;
27 use OpenILS::WWW::EGCatLoader::Course;
28 use OpenILS::WWW::EGCatLoader::Container;
29 use OpenILS::WWW::EGCatLoader::SMS;
30 use OpenILS::WWW::EGCatLoader::Register;
32 my $U = 'OpenILS::Application::AppUtils';
34 use constant COOKIE_SES => 'ses';
35 use constant COOKIE_LOGGEDIN => 'eg_loggedin';
36 use constant COOKIE_TZ => 'client_tz';
37 use constant COOKIE_PHYSICAL_LOC => 'eg_physical_loc';
38 use constant COOKIE_SSS_EXPAND => 'eg_sss_expand';
40 use constant COOKIE_ANON_CACHE => 'anoncache';
41 use constant COOKIE_CART_CACHE => 'cartcache';
42 use constant CART_CACHE_MYLIST => 'mylist';
43 use constant ANON_CACHE_STAFF_SEARCH => 'staffsearch';
45 use constant DEBUG_TIMING => 0;
48 my($class, $apache, $ctx) = @_;
50 my $self = bless({}, ref($class) || $class);
52 $self->apache($apache);
55 $self->timelog("New page");
57 # Add a timelog helper to the context
58 $self->ctx->{timelog} = sub { return $self->timelog(@_) };
60 OpenILS::Utils::CStoreEditor->init; # just in case
61 $self->editor(new_editor());
68 $ENV{TZ} = $self->ctx->{original_tz}
69 if ($self->ctx && exists $self->ctx->{original_tz});
72 # current Apache2::RequestRec;
74 my($self, $apache) = @_;
75 $self->{apache} = $apache if $apache;
76 return $self->{apache};
79 # runtime / template context
82 $self->{ctx} = $ctx if $ctx;
88 my($self, $editor) = @_;
89 $self->{editor} = $editor if $editor;
90 return $self->{editor};
96 $self->{cgi} = $cgi if $cgi;
101 my($self, $description) = @_;
103 return unless DEBUG_TIMING;
104 return unless $description;
105 $self->ctx->{timing} ||= [];
107 my $timer = [Time::HiRes::gettimeofday()];
108 $self->ctx->{time_begin} ||= $timer;
110 push @{$self->ctx->{timing}}, [
111 Time::HiRes::tv_interval($self->ctx->{time_begin}, $timer), $description
115 # -----------------------------------------------------------------------------
116 # Perform initial setup, load common data, then load page data
117 # -----------------------------------------------------------------------------
121 $self->init_ro_object_cache;
122 $self->timelog("Initial load");
124 my $stat = $self->load_common;
125 return $stat unless $stat == Apache2::Const::OK;
127 my $path = $self->apache->path_info;
129 if ($path =~ m|opac/?$|) {
130 # nowhere specified, just go home
131 return $self->generic_redirect($self->ctx->{home_page});
134 (undef, $self->ctx->{mylist}) = $self->fetch_mylist unless
135 $path =~ /opac\/my(opac\/lists|list)/ ||
136 $path =~ m!opac/api/mylist!;
138 my $org_unit = $self->ctx->{physical_loc} || $self->cgi->param('context_org') || $self->_get_search_lib;
139 $self->ctx->{selected_print_email_loc} = $org_unit;
141 return $self->load_api_mylist_retrieve if $path =~ m|opac/api/mylist/retrieve|;
142 return $self->load_api_mylist_add if $path =~ m|opac/api/mylist/add|;
143 return $self->load_api_mylist_delete if $path =~ m|opac/api/mylist/delete|;
144 return $self->load_api_mylist_clear if $path =~ m|opac/api/mylist/clear|;
146 return $self->load_simple("home") if $path =~ m|opac/home|;
147 return $self->load_simple("css") if $path =~ m|opac/css|;
148 return $self->load_cresults if $path =~ m|opac/course/results|;
149 return $self->load_simple("course_search") if $path =~ m|opac/course_search|;
150 return $self->load_simple("advanced") if
151 $path =~ m:opac/(advanced|numeric|expert):;
153 return $self->load_library if $path =~ m|opac/library|;
154 return $self->load_rresults if $path =~ m|opac/results|;
155 return $self->load_print_or_email_preview('print') if $path =~ m|opac/record/print_preview|;
156 return $self->load_print_record if $path =~ m|opac/record/print|;
157 return $self->load_record if $path =~ m|opac/record/\d|;
158 return $self->load_cnbrowse if $path =~ m|opac/cnbrowse|;
159 return $self->load_browse if $path =~ m|opac/browse|;
160 return $self->load_course_browse if $path =~ m|opac/course_browse|;
161 return $self->load_course if $path =~ m|opac/course|;
163 return $self->load_mylist_add if $path =~ m|opac/mylist/add|;
164 return $self->load_mylist_delete if $path =~ m|opac/mylist/delete|;
165 return $self->load_mylist_move if $path =~ m|opac/mylist/move|;
166 return $self->load_mylist_print if $path =~ m|opac/mylist/doprint|;
167 return $self->load_mylist if $path =~ m|opac/mylist| && $path !~ m|opac/mylist/email| && $path !~ m|opac/mylist/doemail|;
168 return $self->load_cache_clear if $path =~ m|opac/cache/clear|;
169 return $self->load_temp_warn_post if $path =~ m|opac/temp_warn/post|;
170 return $self->load_temp_warn if $path =~ m|opac/temp_warn|;
172 # ----------------------------------------------------------------
173 # Everything below here requires SSL
174 # ----------------------------------------------------------------
175 return $self->redirect_ssl unless $self->cgi->https;
176 return $self->load_password_reset if $path =~ m|opac/password_reset|;
177 return $self->load_logout if $path =~ m|opac/logout|;
178 return $self->load_patron_reg if $path =~ m|opac/register|;
180 $self->load_simple("myopac") if $path =~ m:opac/myopac:; # A default page for myopac parts
182 if($path =~ m|opac/login|) {
183 return $self->load_login unless $self->editor->requestor; # already logged in?
185 # This will be less confusing to users than to be shown a login form
186 # when they're already logged in.
187 return $self->generic_redirect(
189 "%s://%s%s/myopac/main",
191 $self->ctx->{hostname}, $self->ctx->{opac_root}
196 if ($path =~ m|opac/sms_cn| and !$self->editor->requestor) {
197 my $skip_sms_auth = $self->ctx->{get_org_setting}->($org_unit, 'sms.disable_authentication_requirement.callnumbers');
198 return $self->load_sms_cn if $skip_sms_auth;
201 if (!$self->editor->requestor && $path =~ m|opac/record/email|) {
202 if ($self->ctx->{get_org_setting}->($org_unit, 'opac.email_record.allow_without_login')) {
203 my $cache = OpenSRF::Utils::Cache->new('global');
205 if ($path !~ m|preview|) { # the real thing!
206 $logger->info("not preview");
207 my $cap_key = $self->ctx->{cap}->{key} = $self->cgi->param('capkey');
208 $logger->info("got cap_key $cap_key");
210 my $cap_answer = $self->ctx->{cap_answer} = $self->cgi->param('capanswer');
211 my $real_answer = $self->ctx->{real_answer} = $cache->get_cache(md5_hex($cap_key));
212 $logger->info("got answers $cap_answer $real_answer");
213 return $self->load_email_record(1) if ( $cap_answer eq $real_answer );
218 $$captcha{key} = time() . $$ . rand();
219 $$captcha{left} = int(rand(10));
220 $$captcha{right} = int(rand(10));
221 $cache->put_cache(md5_hex($$captcha{key}), $$captcha{left} + $$captcha{right});
222 $self->ctx->{captcha} = $captcha;
223 return $self->load_print_or_email_preview('email', 1) if $path =~ m|opac/record/email_preview|;
227 # ----------------------------------------------------------------
228 # Everything below here requires authentication
229 # ----------------------------------------------------------------
230 return $self->redirect_auth unless $self->editor->requestor;
232 # Don't cache anything requiring auth for security reasons
233 $self->apache->headers_out->add("cache-control" => "no-store, no-cache, must-revalidate");
234 $self->apache->headers_out->add("expires" => "-1");
236 if ($path =~ m|opac/mylist/email|) {
237 (undef, $self->ctx->{mylist}) = $self->fetch_mylist;
239 $self->load_simple("mylist/email") if $path =~ m|opac/mylist/email|;
240 return $self->load_print_or_email_preview('email') if $path =~ m|opac/mylist/doemail_preview|;
241 return $self->load_mylist_email if $path =~ m|opac/mylist/doemail|;
242 return $self->load_print_or_email_preview('email') if $path =~ m|opac/record/email_preview|;
243 return $self->load_email_record if $path =~ m|opac/record/email|;
244 return $self->load_sms_cn if $path =~ m|opac/sms_cn|;
246 return $self->load_place_hold if $path =~ m|opac/place_hold|;
248 # centralize check for curbside tab display
249 $self->load_current_curbside_libs;
251 return $self->load_myopac_holds if $path =~ m|opac/myopac/holds|;
252 return $self->load_myopac_circs if $path =~ m|opac/myopac/circs|;
253 return $self->load_myopac_messages if $path =~ m|opac/myopac/messages|;
254 return $self->load_myopac_payment_form if $path =~ m|opac/myopac/main_payment_form|;
255 return $self->load_myopac_payments if $path =~ m|opac/myopac/main_payments|;
256 return $self->load_myopac_pay_init if $path =~ m|opac/myopac/main_pay_init|;
257 return $self->load_myopac_pay if $path =~ m|opac/myopac/main_pay|;
258 return $self->load_myopac_main if $path =~ m|opac/myopac/charges|;
259 return $self->load_myopac_main if $path =~ m|opac/myopac/main|;
260 return $self->load_myopac_receipt_email if $path =~ m|opac/myopac/receipt_email|;
261 return $self->load_myopac_receipt_print if $path =~ m|opac/myopac/receipt_print|;
262 return $self->load_myopac_update_email if $path =~ m|opac/myopac/update_email|;
263 return $self->load_myopac_update_password if $path =~ m|opac/myopac/update_password|;
264 return $self->load_myopac_update_username if $path =~ m|opac/myopac/update_username|;
265 return $self->load_myopac_bookbags if $path =~ m|opac/myopac/lists|;
266 return $self->load_myopac_bookbag_print if $path =~ m|opac/myopac/list/print|;
267 return $self->load_myopac_bookbag_update if $path =~ m|opac/myopac/list/update|;
268 return $self->load_myopac_circ_history_export if $path =~ m|opac/myopac/circ_history/export|;
269 return $self->load_myopac_circ_history if $path =~ m|opac/myopac/circ_history|;
270 return $self->load_myopac_hold_history if $path =~ m|opac/myopac/hold_history|;
271 return $self->load_myopac_prefs_notify_changed_holds if $path =~ m|opac/myopac/prefs_notify_changed_holds|;
272 return $self->load_myopac_prefs_notify if $path =~ m|opac/myopac/prefs_notify|;
273 return $self->load_myopac_prefs_settings if $path =~ m|opac/myopac/prefs_settings|;
274 return $self->load_myopac_prefs_my_lists if $path =~ m|opac/myopac/prefs_my_lists|;
275 return $self->load_myopac_prefs if $path =~ m|opac/myopac/prefs|;
276 return $self->load_myopac_reservations if $path =~ m|opac/myopac/reservations|;
278 return Apache2::Const::OK;
282 # -----------------------------------------------------------------------------
283 # Redirect to SSL equivalent of a given page
284 # -----------------------------------------------------------------------------
287 my $new_page = sprintf('%s://%s%s', ($self->ctx->{is_staff} ? 'oils' : 'https'), $self->ctx->{hostname}, $self->apache->unparsed_uri);
288 return $self->generic_redirect($new_page);
291 # -----------------------------------------------------------------------------
292 # If an authnticated resource is requested w/o auth, redirect to the login page,
293 # then return to the originally requrested resource upon successful login.
294 # -----------------------------------------------------------------------------
297 my $login_page = sprintf('%s://%s%s/login',($self->ctx->{is_staff} ? 'oils' : 'https'), $self->ctx->{hostname}, $self->ctx->{opac_root});
298 my $redirect_to = uri_escape_utf8($self->apache->unparsed_uri);
299 return $self->generic_redirect("$login_page?redirect_to=$redirect_to");
302 # -----------------------------------------------------------------------------
303 # Fall-through for loading a basic page
304 # -----------------------------------------------------------------------------
306 my ($self, $page) = @_;
307 $self->ctx->{page} = $page;
308 $self->ctx->{search_ou} = $self->_get_search_lib();
310 return Apache2::Const::OK;
313 # -----------------------------------------------------------------------------
314 # Tests to see if the user is authenticated and sets some common context values
315 # -----------------------------------------------------------------------------
319 my $e = $self->editor;
320 my $ctx = $self->ctx;
322 # redirect non-https to https if we think we are already logged in
323 if ($self->cgi->cookie(COOKIE_LOGGEDIN)) {
324 return $self->redirect_ssl unless $self->cgi->https;
327 # XXX Cache this? Makes testing difficult as apache needs a restart.
328 my $default_sort = $e->retrieve_config_global_flag('opac.default_sort');
329 $ctx->{default_sort} =
330 ($default_sort && $U->is_true($default_sort->enabled)) ? $default_sort->value : '';
332 $ctx->{client_tz} = $self->cgi->cookie(COOKIE_TZ) || $ENV{TZ};
333 $ctx->{referer} = $self->cgi->referer;
334 $ctx->{path_info} = $self->cgi->path_info;
335 $ctx->{full_path} = $ctx->{base_path} . $self->cgi->path_info;
336 $ctx->{unparsed_uri} = $self->apache->unparsed_uri;
337 $ctx->{opac_root} = $ctx->{base_path} . "/opac"; # absolute base url
339 $ctx->{original_tz} = $ENV{TZ};
340 $ENV{TZ} = $ctx->{client_tz};
343 ($self->apache->headers_in->get('OILS-Wrapper') || '') =~ /true/;
347 $ctx->{is_staff} = 1;
348 $ctx->{proto} = 'oils';
349 $ctx->{hostname} = 'remote';
352 $ctx->{carousel_loc} = $self->get_carousel_loc;
353 $ctx->{physical_loc} = $self->get_physical_loc;
355 # capture some commonly accessed pages
356 $ctx->{home_page} = $ctx->{proto} . '://' . $ctx->{hostname} . $self->ctx->{opac_root} . "/home";
357 $ctx->{logout_page} = ($ctx->{proto} eq 'http' ? 'https' : $ctx->{proto} ) . '://' . $ctx->{hostname} . $self->ctx->{opac_root} . "/logout";
359 if($e->authtoken($self->cgi->cookie(COOKIE_SES))) {
363 $ctx->{authtoken} = $e->authtoken;
364 $ctx->{authtime} = $e->authtime;
365 $ctx->{user} = $e->requestor;
366 my $card = $self->editor->retrieve_actor_card($ctx->{user}->card);
367 $ctx->{active_card} = (ref $card) ? $card->barcode : undef;
368 $ctx->{place_unfillable} = 1 if $e->requestor->wsid && $e->allowed('PLACE_UNFILLABLE_HOLD', $e->requestor->ws_ou);
370 # The browser client does not set an OILS-Wrapper header (above).
371 # The presence of a workstation and no header indicates staff mode.
372 # FIXME: this approach leaves un-wrapped TPAC's within the same
373 # browser (and hence same ses cookie) in an unnatural is_staff
374 # state. Consider alternatives for determining is_staff /
375 # is_browser_staff when $xul_wrapper is false.
376 if (!$xul_wrapper and $e->requestor->wsid) {
377 $ctx->{is_staff} = 1;
378 $ctx->{is_browser_staff} = 1;
381 $self->update_dashboard_stats();
385 # if we encounter a stale authtoken, call load_logout
386 # to clean up the cookie, then redirect the user to the
387 # originally requested page
388 return $self->load_logout($self->apache->unparsed_uri);
392 # List of <meta> and <link> elements to populate
393 $ctx->{metalinks} = [];
395 $self->extract_copy_location_group_info;
396 $ctx->{search_ou} = $self->_get_search_lib();
397 $self->staff_saved_searches_set_expansion_state if $ctx->{is_staff};
398 $self->load_eg_cache_hash;
399 $self->load_copy_location_groups;
400 $self->staff_saved_searches_set_expansion_state if $ctx->{is_staff};
401 $self->load_search_filter_groups($ctx->{search_ou});
402 $self->load_org_util_funcs;
403 $self->load_perm_funcs;
405 # FIXME - move carousel helpers to a separate file
406 $ctx->{get_visible_carousels} = sub {
407 my $org_unit = $self->ctx->{carousel_loc} || $self->ctx->{physical_loc} || $self->cgi->param('loc') || $self->ctx->{aou_tree}->()->id;
408 return $U->simplereq(
410 'open-ils.actor.carousel.retrieve_by_org',
414 $ctx->{get_carousel} = sub {
417 my $carousel = $e->retrieve_container_carousel($id);
420 name => $carousel->name
423 select => { bre => ['id'], mfde => [{ column => 'value', alias => 'title' }] },
437 '+cc' => { id => $id },
438 '+bre' => { deleted => 'f' },
439 '+mfde' => { name => 'title' }
442 my $r = $e->json_query($q);
447 $ctx->{fetch_display_fields} = sub {
451 return $ctx->{_hl_data}{''.$$id[0]}
452 if ($ctx->{_hl_data}{''.$$id[0]});
455 $self->timelog("HL data not cached, fetching from server.");
457 my $rows = $U->simplereq(
459 'open-ils.search.fetch.metabib.display_field.highlight',
460 $ctx->{query_struct}{additional_data}{highlight_map},
464 $ctx->{_hl_data}{''.$$id[0]} = $rows if (@$id == 1);
469 $ctx->{course_ou} = int($self->cgi->param('locg')) || $self->ctx->{physical_loc} || $self->ctx->{aou_tree}->()->id;
470 $ctx->{use_courses} = $ctx->{get_org_setting}->($ctx->{course_ou}, 'circ.course_materials_opt_in') ? 1 : 0;
472 return Apache2::Const::OK;
475 sub update_dashboard_stats {
478 my $e = $self->editor;
479 my $ctx = $self->ctx;
481 $ctx->{user_stats} = $U->simplereq(
483 'open-ils.actor.user.opac.vital_stats',
484 $e->authtoken, $e->requestor->id);
487 sub staff_saved_searches_set_expansion_state {
490 my $param = $self->cgi->param('sss_expand');
493 if (defined $param) {
494 $value = ($param ? 1 : 0);
495 $self->apache->headers_out->add(
496 "Set-Cookie" => $self->cgi->cookie(
497 -name => COOKIE_SSS_EXPAND,
498 -path => $self->ctx->{base_path},
499 -secure => 1, # not strictly necessary, but this feature is staff-only, so may as well
505 $value = $self->cgi->cookie(COOKIE_SSS_EXPAND);
508 $self->ctx->{saved_searches_expanded} = $value;
511 # physical_loc (i.e. "original location") passed in as a URL
512 # param will replace any existing physical_loc stored as a cookie.
513 # If specified via ENV that rules over all and we don't set cookies.
514 sub get_physical_loc {
517 return $ENV{physical_loc} if($ENV{physical_loc});
519 if(my $physical_loc = $self->cgi->param('physical_loc')) {
520 $self->apache->headers_out->add(
521 "Set-Cookie" => $self->cgi->cookie(
522 -name => COOKIE_PHYSICAL_LOC,
523 -path => $self->ctx->{base_path},
524 -value => $physical_loc,
528 return $physical_loc;
531 return $self->cgi->cookie(COOKIE_PHYSICAL_LOC);
534 sub get_carousel_loc {
536 return $self->cgi->param('carousel_loc') || $ENV{carousel_loc};
539 # -----------------------------------------------------------------------------
540 # Log in and redirect to the redirect_to URL (or home)
541 # -----------------------------------------------------------------------------
544 my $cgi = $self->cgi;
545 my $ctx = $self->ctx;
547 $self->timelog("Load login begins");
549 $ctx->{page} = 'login';
551 my $username = $cgi->param('username') || '';
552 $username =~ s/\s//g; # Remove blanks
553 my $password = $cgi->param('password');
554 my $org_unit = $ctx->{physical_loc} || $ctx->{aou_tree}->()->id;
555 my $persist = $cgi->param('persist');
556 my $client_tz = $cgi->param('client_tz');
558 # initial log form only
559 return Apache2::Const::OK unless $username and $password;
561 my $auth_proxy_enabled = 0; # default false
562 try { # if the service is not running, just let this fail silently
563 $auth_proxy_enabled = $U->simplereq(
564 'open-ils.auth_proxy',
565 'open-ils.auth_proxy.enabled');
566 } catch Error with {};
568 $self->timelog("Checked for auth proxy: $auth_proxy_enabled; org = $org_unit; username = $username");
571 type => ($persist) ? 'persist' : 'opac',
576 my $bc_regex = $ctx->{get_org_setting}->($org_unit, 'opac.barcode_regex');
578 # To avoid surprises, default to "Barcodes start with digits"
579 $bc_regex = '^\d' unless $bc_regex;
581 if ($bc_regex and ($username =~ /$bc_regex/)) {
582 $args->{barcode} = $username;
584 $args->{username} = $username;
588 if (!$auth_proxy_enabled) {
589 my $seed = $U->simplereq(
591 'open-ils.auth.authenticate.init', $username);
592 $args->{password} = md5_hex($seed . md5_hex($password));
593 $response = $U->simplereq(
594 'open-ils.auth', 'open-ils.auth.authenticate.complete', $args);
596 $args->{password} = $password;
597 $response = $U->simplereq(
598 'open-ils.auth_proxy',
599 'open-ils.auth_proxy.login', $args);
601 $self->timelog("Checked password");
603 if($U->event_code($response)) {
604 # login failed, report the reason to the template
605 $ctx->{login_failed_event} = $response;
606 return Apache2::Const::OK;
609 # login succeeded, redirect as necessary
611 my $acct = $self->apache->unparsed_uri;
612 $acct =~ s|/login|/myopac/main|;
614 # both login-related cookies should expire at the same time
615 my $login_cookie_expires = ($persist) ? CORE::time + $response->{payload}->{authtime} : undef;
618 # contains the actual auth token and should be sent only over https
623 -value => $response->{payload}->{authtoken},
624 -expires => $login_cookie_expires
626 # contains only a hint that we are logged in, and is used to
627 # trigger a redirect to https
629 -name => COOKIE_LOGGEDIN,
633 -expires => $login_cookie_expires
638 # contains the client's tz, as passed by the client
639 # trigger a redirect to https
640 push @$cookie_list, $cgi->cookie(
644 -value => $client_tz,
645 -expires => $login_cookie_expires
649 return $self->generic_redirect(
650 $cgi->param('redirect_to') || $acct,
655 # -----------------------------------------------------------------------------
656 # Log out and redirect to the home page
657 # -----------------------------------------------------------------------------
660 my $redirect_to = shift || $self->cgi->param('redirect_to');
662 # If the user was adding anyting to an anonymous cache
663 # while logged in, go ahead and clear it out.
664 $self->clear_anon_cache;
666 try { # a missing auth token will cause an ugly explosion
669 'open-ils.auth.session.delete',
670 $self->cgi->cookie(COOKIE_SES)
672 } catch Error with {};
674 return $self->generic_redirect(
675 $redirect_to || $self->ctx->{home_page},
677 # clear value of and expire both of these login-related cookies
685 -name => COOKIE_LOGGEDIN,