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|;
245 return $self->load_place_hold if $path =~ m|opac/place_hold|;
246 return $self->load_myopac_holds if $path =~ m|opac/myopac/holds|;
247 return $self->load_myopac_circs if $path =~ m|opac/myopac/circs|;
248 return $self->load_myopac_messages if $path =~ m|opac/myopac/messages|;
249 return $self->load_myopac_payment_form if $path =~ m|opac/myopac/main_payment_form|;
250 return $self->load_myopac_payments if $path =~ m|opac/myopac/main_payments|;
251 return $self->load_myopac_pay_init if $path =~ m|opac/myopac/main_pay_init|;
252 return $self->load_myopac_pay if $path =~ m|opac/myopac/main_pay|;
253 return $self->load_myopac_main if $path =~ m|opac/myopac/charges|;
254 return $self->load_myopac_main if $path =~ m|opac/myopac/main|;
255 return $self->load_myopac_receipt_email if $path =~ m|opac/myopac/receipt_email|;
256 return $self->load_myopac_receipt_print if $path =~ m|opac/myopac/receipt_print|;
257 return $self->load_myopac_update_email if $path =~ m|opac/myopac/update_email|;
258 return $self->load_myopac_update_password if $path =~ m|opac/myopac/update_password|;
259 return $self->load_myopac_update_username if $path =~ m|opac/myopac/update_username|;
260 return $self->load_myopac_bookbags if $path =~ m|opac/myopac/lists|;
261 return $self->load_myopac_bookbag_print if $path =~ m|opac/myopac/list/print|;
262 return $self->load_myopac_bookbag_update if $path =~ m|opac/myopac/list/update|;
263 return $self->load_myopac_circ_history_export if $path =~ m|opac/myopac/circ_history/export|;
264 return $self->load_myopac_circ_history if $path =~ m|opac/myopac/circ_history|;
265 return $self->load_myopac_hold_history if $path =~ m|opac/myopac/hold_history|;
266 return $self->load_myopac_prefs_notify_changed_holds if $path =~ m|opac/myopac/prefs_notify_changed_holds|;
267 return $self->load_myopac_prefs_notify if $path =~ m|opac/myopac/prefs_notify|;
268 return $self->load_myopac_prefs_settings if $path =~ m|opac/myopac/prefs_settings|;
269 return $self->load_myopac_prefs_my_lists if $path =~ m|opac/myopac/prefs_my_lists|;
270 return $self->load_myopac_prefs if $path =~ m|opac/myopac/prefs|;
271 return $self->load_myopac_reservations if $path =~ m|opac/myopac/reservations|;
272 return $self->load_sms_cn if $path =~ m|opac/sms_cn|;
274 return Apache2::Const::OK;
278 # -----------------------------------------------------------------------------
279 # Redirect to SSL equivalent of a given page
280 # -----------------------------------------------------------------------------
283 my $new_page = sprintf('%s://%s%s', ($self->ctx->{is_staff} ? 'oils' : 'https'), $self->ctx->{hostname}, $self->apache->unparsed_uri);
284 return $self->generic_redirect($new_page);
287 # -----------------------------------------------------------------------------
288 # If an authnticated resource is requested w/o auth, redirect to the login page,
289 # then return to the originally requrested resource upon successful login.
290 # -----------------------------------------------------------------------------
293 my $login_page = sprintf('%s://%s%s/login',($self->ctx->{is_staff} ? 'oils' : 'https'), $self->ctx->{hostname}, $self->ctx->{opac_root});
294 my $redirect_to = uri_escape_utf8($self->apache->unparsed_uri);
295 return $self->generic_redirect("$login_page?redirect_to=$redirect_to");
298 # -----------------------------------------------------------------------------
299 # Fall-through for loading a basic page
300 # -----------------------------------------------------------------------------
302 my ($self, $page) = @_;
303 $self->ctx->{page} = $page;
304 $self->ctx->{search_ou} = $self->_get_search_lib();
306 return Apache2::Const::OK;
309 # -----------------------------------------------------------------------------
310 # Tests to see if the user is authenticated and sets some common context values
311 # -----------------------------------------------------------------------------
315 my $e = $self->editor;
316 my $ctx = $self->ctx;
318 # redirect non-https to https if we think we are already logged in
319 if ($self->cgi->cookie(COOKIE_LOGGEDIN)) {
320 return $self->redirect_ssl unless $self->cgi->https;
323 # XXX Cache this? Makes testing difficult as apache needs a restart.
324 my $default_sort = $e->retrieve_config_global_flag('opac.default_sort');
325 $ctx->{default_sort} =
326 ($default_sort && $U->is_true($default_sort->enabled)) ? $default_sort->value : '';
328 $ctx->{client_tz} = $self->cgi->cookie(COOKIE_TZ) || $ENV{TZ};
329 $ctx->{referer} = $self->cgi->referer;
330 $ctx->{path_info} = $self->cgi->path_info;
331 $ctx->{full_path} = $ctx->{base_path} . $self->cgi->path_info;
332 $ctx->{unparsed_uri} = $self->apache->unparsed_uri;
333 $ctx->{opac_root} = $ctx->{base_path} . "/opac"; # absolute base url
335 $ctx->{original_tz} = $ENV{TZ};
336 $ENV{TZ} = $ctx->{client_tz};
339 ($self->apache->headers_in->get('OILS-Wrapper') || '') =~ /true/;
343 $ctx->{is_staff} = 1;
344 $ctx->{proto} = 'oils';
345 $ctx->{hostname} = 'remote';
348 $ctx->{physical_loc} = $self->get_physical_loc;
350 # capture some commonly accessed pages
351 $ctx->{home_page} = $ctx->{proto} . '://' . $ctx->{hostname} . $self->ctx->{opac_root} . "/home";
352 $ctx->{logout_page} = ($ctx->{proto} eq 'http' ? 'https' : $ctx->{proto} ) . '://' . $ctx->{hostname} . $self->ctx->{opac_root} . "/logout";
354 if($e->authtoken($self->cgi->cookie(COOKIE_SES))) {
358 $ctx->{authtoken} = $e->authtoken;
359 $ctx->{authtime} = $e->authtime;
360 $ctx->{user} = $e->requestor;
361 my $card = $self->editor->retrieve_actor_card($ctx->{user}->card);
362 $ctx->{active_card} = (ref $card) ? $card->barcode : undef;
363 $ctx->{place_unfillable} = 1 if $e->requestor->wsid && $e->allowed('PLACE_UNFILLABLE_HOLD', $e->requestor->ws_ou);
365 # The browser client does not set an OILS-Wrapper header (above).
366 # The presence of a workstation and no header indicates staff mode.
367 # FIXME: this approach leaves un-wrapped TPAC's within the same
368 # browser (and hence same ses cookie) in an unnatural is_staff
369 # state. Consider alternatives for determining is_staff /
370 # is_browser_staff when $xul_wrapper is false.
371 if (!$xul_wrapper and $e->requestor->wsid) {
372 $ctx->{is_staff} = 1;
373 $ctx->{is_browser_staff} = 1;
376 $self->update_dashboard_stats();
380 # if we encounter a stale authtoken, call load_logout
381 # to clean up the cookie, then redirect the user to the
382 # originally requested page
383 return $self->load_logout($self->apache->unparsed_uri);
387 # List of <meta> and <link> elements to populate
388 $ctx->{metalinks} = [];
390 $self->extract_copy_location_group_info;
391 $ctx->{search_ou} = $self->_get_search_lib();
392 $self->staff_saved_searches_set_expansion_state if $ctx->{is_staff};
393 $self->load_eg_cache_hash;
394 $self->load_copy_location_groups;
395 $self->staff_saved_searches_set_expansion_state if $ctx->{is_staff};
396 $self->load_search_filter_groups($ctx->{search_ou});
397 $self->load_org_util_funcs;
398 $self->load_perm_funcs;
400 # FIXME - move carousel helpers to a separate file
401 $ctx->{get_visible_carousels} = sub {
402 my $org_unit = $self->ctx->{physical_loc} || $self->cgi->param('loc') || $self->ctx->{aou_tree}->()->id;
403 return $U->simplereq(
405 'open-ils.actor.carousel.retrieve_by_org',
409 $ctx->{get_carousel} = sub {
412 my $carousel = $e->retrieve_container_carousel($id);
415 name => $carousel->name
418 select => { bre => ['id'], mfde => [{ column => 'value', alias => 'title' }] },
432 '+cc' => { id => $id },
433 '+bre' => { deleted => 'f' },
434 '+mfde' => { name => 'title' }
437 my $r = $e->json_query($q);
442 $ctx->{fetch_display_fields} = sub {
446 return $ctx->{_hl_data}{''.$$id[0]}
447 if ($ctx->{_hl_data}{''.$$id[0]});
450 $self->timelog("HL data not cached, fetching from server.");
452 my $rows = $U->simplereq(
454 'open-ils.search.fetch.metabib.display_field.highlight',
455 $ctx->{query_struct}{additional_data}{highlight_map},
459 $ctx->{_hl_data}{''.$$id[0]} = $rows if (@$id == 1);
464 return Apache2::Const::OK;
467 sub update_dashboard_stats {
470 my $e = $self->editor;
471 my $ctx = $self->ctx;
473 $ctx->{user_stats} = $U->simplereq(
475 'open-ils.actor.user.opac.vital_stats',
476 $e->authtoken, $e->requestor->id);
479 sub staff_saved_searches_set_expansion_state {
482 my $param = $self->cgi->param('sss_expand');
485 if (defined $param) {
486 $value = ($param ? 1 : 0);
487 $self->apache->headers_out->add(
488 "Set-Cookie" => $self->cgi->cookie(
489 -name => COOKIE_SSS_EXPAND,
490 -path => $self->ctx->{base_path},
491 -secure => 1, # not strictly necessary, but this feature is staff-only, so may as well
497 $value = $self->cgi->cookie(COOKIE_SSS_EXPAND);
500 $self->ctx->{saved_searches_expanded} = $value;
503 # physical_loc (i.e. "original location") passed in as a URL
504 # param will replace any existing physical_loc stored as a cookie.
505 # If specified via ENV that rules over all and we don't set cookies.
506 sub get_physical_loc {
509 return $ENV{physical_loc} if($ENV{physical_loc});
511 if(my $physical_loc = $self->cgi->param('physical_loc')) {
512 $self->apache->headers_out->add(
513 "Set-Cookie" => $self->cgi->cookie(
514 -name => COOKIE_PHYSICAL_LOC,
515 -path => $self->ctx->{base_path},
516 -value => $physical_loc,
520 return $physical_loc;
523 return $self->cgi->cookie(COOKIE_PHYSICAL_LOC);
526 # -----------------------------------------------------------------------------
527 # Log in and redirect to the redirect_to URL (or home)
528 # -----------------------------------------------------------------------------
531 my $cgi = $self->cgi;
532 my $ctx = $self->ctx;
534 $self->timelog("Load login begins");
536 $ctx->{page} = 'login';
538 my $username = $cgi->param('username') || '';
539 $username =~ s/\s//g; # Remove blanks
540 my $password = $cgi->param('password');
541 my $org_unit = $ctx->{physical_loc} || $ctx->{aou_tree}->()->id;
542 my $persist = $cgi->param('persist');
543 my $client_tz = $cgi->param('client_tz');
545 # initial log form only
546 return Apache2::Const::OK unless $username and $password;
548 my $auth_proxy_enabled = 0; # default false
549 try { # if the service is not running, just let this fail silently
550 $auth_proxy_enabled = $U->simplereq(
551 'open-ils.auth_proxy',
552 'open-ils.auth_proxy.enabled');
553 } catch Error with {};
555 $self->timelog("Checked for auth proxy: $auth_proxy_enabled; org = $org_unit; username = $username");
558 type => ($persist) ? 'persist' : 'opac',
563 my $bc_regex = $ctx->{get_org_setting}->($org_unit, 'opac.barcode_regex');
565 # To avoid surprises, default to "Barcodes start with digits"
566 $bc_regex = '^\d' unless $bc_regex;
568 if ($bc_regex and ($username =~ /$bc_regex/)) {
569 $args->{barcode} = $username;
571 $args->{username} = $username;
575 if (!$auth_proxy_enabled) {
576 my $seed = $U->simplereq(
578 'open-ils.auth.authenticate.init', $username);
579 $args->{password} = md5_hex($seed . md5_hex($password));
580 $response = $U->simplereq(
581 'open-ils.auth', 'open-ils.auth.authenticate.complete', $args);
583 $args->{password} = $password;
584 $response = $U->simplereq(
585 'open-ils.auth_proxy',
586 'open-ils.auth_proxy.login', $args);
588 $self->timelog("Checked password");
590 if($U->event_code($response)) {
591 # login failed, report the reason to the template
592 $ctx->{login_failed_event} = $response;
593 return Apache2::Const::OK;
596 # login succeeded, redirect as necessary
598 my $acct = $self->apache->unparsed_uri;
599 $acct =~ s|/login|/myopac/main|;
601 # both login-related cookies should expire at the same time
602 my $login_cookie_expires = ($persist) ? CORE::time + $response->{payload}->{authtime} : undef;
605 # contains the actual auth token and should be sent only over https
610 -value => $response->{payload}->{authtoken},
611 -expires => $login_cookie_expires
613 # contains only a hint that we are logged in, and is used to
614 # trigger a redirect to https
616 -name => COOKIE_LOGGEDIN,
620 -expires => $login_cookie_expires
625 # contains the client's tz, as passed by the client
626 # trigger a redirect to https
627 push @$cookie_list, $cgi->cookie(
631 -value => $client_tz,
632 -expires => $login_cookie_expires
636 return $self->generic_redirect(
637 $cgi->param('redirect_to') || $acct,
642 # -----------------------------------------------------------------------------
643 # Log out and redirect to the home page
644 # -----------------------------------------------------------------------------
647 my $redirect_to = shift || $self->cgi->param('redirect_to');
649 # If the user was adding anyting to an anonymous cache
650 # while logged in, go ahead and clear it out.
651 $self->clear_anon_cache;
653 try { # a missing auth token will cause an ugly explosion
656 'open-ils.auth.session.delete',
657 $self->cgi->cookie(COOKIE_SES)
659 } catch Error with {};
661 return $self->generic_redirect(
662 $redirect_to || $self->ctx->{home_page},
664 # clear value of and expire both of these login-related cookies
672 -name => COOKIE_LOGGEDIN,