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 if $path =~ m|opac/course|;
162 return $self->load_mylist_add if $path =~ m|opac/mylist/add|;
163 return $self->load_mylist_delete if $path =~ m|opac/mylist/delete|;
164 return $self->load_mylist_move if $path =~ m|opac/mylist/move|;
165 return $self->load_mylist_print if $path =~ m|opac/mylist/doprint|;
166 return $self->load_mylist if $path =~ m|opac/mylist| && $path !~ m|opac/mylist/email| && $path !~ m|opac/mylist/doemail|;
167 return $self->load_cache_clear if $path =~ m|opac/cache/clear|;
168 return $self->load_temp_warn_post if $path =~ m|opac/temp_warn/post|;
169 return $self->load_temp_warn if $path =~ m|opac/temp_warn|;
171 # ----------------------------------------------------------------
172 # Everything below here requires SSL
173 # ----------------------------------------------------------------
174 return $self->redirect_ssl unless $self->cgi->https;
175 return $self->load_password_reset if $path =~ m|opac/password_reset|;
176 return $self->load_logout if $path =~ m|opac/logout|;
177 return $self->load_patron_reg if $path =~ m|opac/register|;
179 $self->load_simple("myopac") if $path =~ m:opac/myopac:; # A default page for myopac parts
181 if($path =~ m|opac/login|) {
182 return $self->load_login unless $self->editor->requestor; # already logged in?
184 # This will be less confusing to users than to be shown a login form
185 # when they're already logged in.
186 return $self->generic_redirect(
188 "%s://%s%s/myopac/main",
190 $self->ctx->{hostname}, $self->ctx->{opac_root}
195 if ($path =~ m|opac/sms_cn| and !$self->editor->requestor) {
196 my $skip_sms_auth = $self->ctx->{get_org_setting}->($org_unit, 'sms.disable_authentication_requirement.callnumbers');
197 return $self->load_sms_cn if $skip_sms_auth;
200 if (!$self->editor->requestor && $path =~ m|opac/record/email|) {
201 if ($self->ctx->{get_org_setting}->($org_unit, 'opac.email_record.allow_without_login')) {
202 my $cache = OpenSRF::Utils::Cache->new('global');
204 if ($path !~ m|preview|) { # the real thing!
205 $logger->info("not preview");
206 my $cap_key = $self->ctx->{cap}->{key} = $self->cgi->param('capkey');
207 $logger->info("got cap_key $cap_key");
209 my $cap_answer = $self->ctx->{cap_answer} = $self->cgi->param('capanswer');
210 my $real_answer = $self->ctx->{real_answer} = $cache->get_cache(md5_hex($cap_key));
211 $logger->info("got answers $cap_answer $real_answer");
212 return $self->load_email_record(1) if ( $cap_answer eq $real_answer );
217 $$captcha{key} = time() . $$ . rand();
218 $$captcha{left} = int(rand(10));
219 $$captcha{right} = int(rand(10));
220 $cache->put_cache(md5_hex($$captcha{key}), $$captcha{left} + $$captcha{right});
221 $self->ctx->{captcha} = $captcha;
222 return $self->load_print_or_email_preview('email', 1) if $path =~ m|opac/record/email_preview|;
226 # ----------------------------------------------------------------
227 # Everything below here requires authentication
228 # ----------------------------------------------------------------
229 return $self->redirect_auth unless $self->editor->requestor;
231 # Don't cache anything requiring auth for security reasons
232 $self->apache->headers_out->add("cache-control" => "no-store, no-cache, must-revalidate");
233 $self->apache->headers_out->add("expires" => "-1");
235 if ($path =~ m|opac/mylist/email|) {
236 (undef, $self->ctx->{mylist}) = $self->fetch_mylist;
238 $self->load_simple("mylist/email") if $path =~ m|opac/mylist/email|;
239 return $self->load_print_or_email_preview('email') if $path =~ m|opac/mylist/doemail_preview|;
240 return $self->load_mylist_email if $path =~ m|opac/mylist/doemail|;
241 return $self->load_print_or_email_preview('email') if $path =~ m|opac/record/email_preview|;
242 return $self->load_email_record if $path =~ m|opac/record/email|;
244 return $self->load_place_hold if $path =~ m|opac/place_hold|;
245 return $self->load_myopac_holds if $path =~ m|opac/myopac/holds|;
246 return $self->load_myopac_circs if $path =~ m|opac/myopac/circs|;
247 return $self->load_myopac_messages if $path =~ m|opac/myopac/messages|;
248 return $self->load_myopac_payment_form if $path =~ m|opac/myopac/main_payment_form|;
249 return $self->load_myopac_payments if $path =~ m|opac/myopac/main_payments|;
250 return $self->load_myopac_pay_init if $path =~ m|opac/myopac/main_pay_init|;
251 return $self->load_myopac_pay if $path =~ m|opac/myopac/main_pay|;
252 return $self->load_myopac_main if $path =~ m|opac/myopac/charges|;
253 return $self->load_myopac_main if $path =~ m|opac/myopac/main|;
254 return $self->load_myopac_receipt_email if $path =~ m|opac/myopac/receipt_email|;
255 return $self->load_myopac_receipt_print if $path =~ m|opac/myopac/receipt_print|;
256 return $self->load_myopac_update_email if $path =~ m|opac/myopac/update_email|;
257 return $self->load_myopac_update_password if $path =~ m|opac/myopac/update_password|;
258 return $self->load_myopac_update_username if $path =~ m|opac/myopac/update_username|;
259 return $self->load_myopac_bookbags if $path =~ m|opac/myopac/lists|;
260 return $self->load_myopac_bookbag_print if $path =~ m|opac/myopac/list/print|;
261 return $self->load_myopac_bookbag_update if $path =~ m|opac/myopac/list/update|;
262 return $self->load_myopac_circ_history_export if $path =~ m|opac/myopac/circ_history/export|;
263 return $self->load_myopac_circ_history if $path =~ m|opac/myopac/circ_history|;
264 return $self->load_myopac_hold_history if $path =~ m|opac/myopac/hold_history|;
265 return $self->load_myopac_prefs_notify_changed_holds if $path =~ m|opac/myopac/prefs_notify_changed_holds|;
266 return $self->load_myopac_prefs_notify if $path =~ m|opac/myopac/prefs_notify|;
267 return $self->load_myopac_prefs_settings if $path =~ m|opac/myopac/prefs_settings|;
268 return $self->load_myopac_prefs_my_lists if $path =~ m|opac/myopac/prefs_my_lists|;
269 return $self->load_myopac_prefs if $path =~ m|opac/myopac/prefs|;
270 return $self->load_myopac_reservations if $path =~ m|opac/myopac/reservations|;
271 return $self->load_sms_cn if $path =~ m|opac/sms_cn|;
273 return Apache2::Const::OK;
277 # -----------------------------------------------------------------------------
278 # Redirect to SSL equivalent of a given page
279 # -----------------------------------------------------------------------------
282 my $new_page = sprintf('%s://%s%s', ($self->ctx->{is_staff} ? 'oils' : 'https'), $self->ctx->{hostname}, $self->apache->unparsed_uri);
283 return $self->generic_redirect($new_page);
286 # -----------------------------------------------------------------------------
287 # If an authnticated resource is requested w/o auth, redirect to the login page,
288 # then return to the originally requrested resource upon successful login.
289 # -----------------------------------------------------------------------------
292 my $login_page = sprintf('%s://%s%s/login',($self->ctx->{is_staff} ? 'oils' : 'https'), $self->ctx->{hostname}, $self->ctx->{opac_root});
293 my $redirect_to = uri_escape_utf8($self->apache->unparsed_uri);
294 return $self->generic_redirect("$login_page?redirect_to=$redirect_to");
297 # -----------------------------------------------------------------------------
298 # Fall-through for loading a basic page
299 # -----------------------------------------------------------------------------
301 my ($self, $page) = @_;
302 $self->ctx->{page} = $page;
303 $self->ctx->{search_ou} = $self->_get_search_lib();
305 return Apache2::Const::OK;
308 # -----------------------------------------------------------------------------
309 # Tests to see if the user is authenticated and sets some common context values
310 # -----------------------------------------------------------------------------
314 my $e = $self->editor;
315 my $ctx = $self->ctx;
317 # redirect non-https to https if we think we are already logged in
318 if ($self->cgi->cookie(COOKIE_LOGGEDIN)) {
319 return $self->redirect_ssl unless $self->cgi->https;
322 # XXX Cache this? Makes testing difficult as apache needs a restart.
323 my $default_sort = $e->retrieve_config_global_flag('opac.default_sort');
324 $ctx->{default_sort} =
325 ($default_sort && $U->is_true($default_sort->enabled)) ? $default_sort->value : '';
327 $ctx->{client_tz} = $self->cgi->cookie(COOKIE_TZ) || $ENV{TZ};
328 $ctx->{referer} = $self->cgi->referer;
329 $ctx->{path_info} = $self->cgi->path_info;
330 $ctx->{full_path} = $ctx->{base_path} . $self->cgi->path_info;
331 $ctx->{unparsed_uri} = $self->apache->unparsed_uri;
332 $ctx->{opac_root} = $ctx->{base_path} . "/opac"; # absolute base url
334 $ctx->{original_tz} = $ENV{TZ};
335 $ENV{TZ} = $ctx->{client_tz};
338 ($self->apache->headers_in->get('OILS-Wrapper') || '') =~ /true/;
342 $ctx->{is_staff} = 1;
343 $ctx->{proto} = 'oils';
344 $ctx->{hostname} = 'remote';
347 $ctx->{physical_loc} = $self->get_physical_loc;
349 # capture some commonly accessed pages
350 $ctx->{home_page} = $ctx->{proto} . '://' . $ctx->{hostname} . $self->ctx->{opac_root} . "/home";
351 $ctx->{logout_page} = ($ctx->{proto} eq 'http' ? 'https' : $ctx->{proto} ) . '://' . $ctx->{hostname} . $self->ctx->{opac_root} . "/logout";
353 if($e->authtoken($self->cgi->cookie(COOKIE_SES))) {
357 $ctx->{authtoken} = $e->authtoken;
358 $ctx->{authtime} = $e->authtime;
359 $ctx->{user} = $e->requestor;
360 my $card = $self->editor->retrieve_actor_card($ctx->{user}->card);
361 $ctx->{active_card} = (ref $card) ? $card->barcode : undef;
362 $ctx->{place_unfillable} = 1 if $e->requestor->wsid && $e->allowed('PLACE_UNFILLABLE_HOLD', $e->requestor->ws_ou);
364 # The browser client does not set an OILS-Wrapper header (above).
365 # The presence of a workstation and no header indicates staff mode.
366 # FIXME: this approach leaves un-wrapped TPAC's within the same
367 # browser (and hence same ses cookie) in an unnatural is_staff
368 # state. Consider alternatives for determining is_staff /
369 # is_browser_staff when $xul_wrapper is false.
370 if (!$xul_wrapper and $e->requestor->wsid) {
371 $ctx->{is_staff} = 1;
372 $ctx->{is_browser_staff} = 1;
375 $self->update_dashboard_stats();
379 # if we encounter a stale authtoken, call load_logout
380 # to clean up the cookie, then redirect the user to the
381 # originally requested page
382 return $self->load_logout($self->apache->unparsed_uri);
386 # List of <meta> and <link> elements to populate
387 $ctx->{metalinks} = [];
389 $self->extract_copy_location_group_info;
390 $ctx->{search_ou} = $self->_get_search_lib();
391 $self->staff_saved_searches_set_expansion_state if $ctx->{is_staff};
392 $self->load_eg_cache_hash;
393 $self->load_copy_location_groups;
394 $self->staff_saved_searches_set_expansion_state if $ctx->{is_staff};
395 $self->load_search_filter_groups($ctx->{search_ou});
396 $self->load_org_util_funcs;
397 $self->load_perm_funcs;
399 # FIXME - move carousel helpers to a separate file
400 $ctx->{get_visible_carousels} = sub {
401 my $org_unit = $self->ctx->{physical_loc} || $self->cgi->param('loc') || $self->ctx->{aou_tree}->()->id;
402 return $U->simplereq(
404 'open-ils.actor.carousel.retrieve_by_org',
408 $ctx->{get_carousel} = sub {
411 my $carousel = $e->retrieve_container_carousel($id);
414 name => $carousel->name
417 select => { bre => ['id'], mfde => [{ column => 'value', alias => 'title' }] },
431 '+cc' => { id => $id },
432 '+bre' => { deleted => 'f' },
433 '+mfde' => { name => 'title' }
436 my $r = $e->json_query($q);
441 $ctx->{fetch_display_fields} = sub {
445 return $ctx->{_hl_data}{''.$$id[0]}
446 if ($ctx->{_hl_data}{''.$$id[0]});
449 $self->timelog("HL data not cached, fetching from server.");
451 my $rows = $U->simplereq(
453 'open-ils.search.fetch.metabib.display_field.highlight',
454 $ctx->{query_struct}{additional_data}{highlight_map},
458 $ctx->{_hl_data}{''.$$id[0]} = $rows if (@$id == 1);
463 return Apache2::Const::OK;
466 sub update_dashboard_stats {
469 my $e = $self->editor;
470 my $ctx = $self->ctx;
472 $ctx->{user_stats} = $U->simplereq(
474 'open-ils.actor.user.opac.vital_stats',
475 $e->authtoken, $e->requestor->id);
478 sub staff_saved_searches_set_expansion_state {
481 my $param = $self->cgi->param('sss_expand');
484 if (defined $param) {
485 $value = ($param ? 1 : 0);
486 $self->apache->headers_out->add(
487 "Set-Cookie" => $self->cgi->cookie(
488 -name => COOKIE_SSS_EXPAND,
489 -path => $self->ctx->{base_path},
490 -secure => 1, # not strictly necessary, but this feature is staff-only, so may as well
496 $value = $self->cgi->cookie(COOKIE_SSS_EXPAND);
499 $self->ctx->{saved_searches_expanded} = $value;
502 # physical_loc (i.e. "original location") passed in as a URL
503 # param will replace any existing physical_loc stored as a cookie.
504 # If specified via ENV that rules over all and we don't set cookies.
505 sub get_physical_loc {
508 return $ENV{physical_loc} if($ENV{physical_loc});
510 if(my $physical_loc = $self->cgi->param('physical_loc')) {
511 $self->apache->headers_out->add(
512 "Set-Cookie" => $self->cgi->cookie(
513 -name => COOKIE_PHYSICAL_LOC,
514 -path => $self->ctx->{base_path},
515 -value => $physical_loc,
519 return $physical_loc;
522 return $self->cgi->cookie(COOKIE_PHYSICAL_LOC);
525 # -----------------------------------------------------------------------------
526 # Log in and redirect to the redirect_to URL (or home)
527 # -----------------------------------------------------------------------------
530 my $cgi = $self->cgi;
531 my $ctx = $self->ctx;
533 $self->timelog("Load login begins");
535 $ctx->{page} = 'login';
537 my $username = $cgi->param('username') || '';
538 $username =~ s/\s//g; # Remove blanks
539 my $password = $cgi->param('password');
540 my $org_unit = $ctx->{physical_loc} || $ctx->{aou_tree}->()->id;
541 my $persist = $cgi->param('persist');
542 my $client_tz = $cgi->param('client_tz');
544 # initial log form only
545 return Apache2::Const::OK unless $username and $password;
547 my $auth_proxy_enabled = 0; # default false
548 try { # if the service is not running, just let this fail silently
549 $auth_proxy_enabled = $U->simplereq(
550 'open-ils.auth_proxy',
551 'open-ils.auth_proxy.enabled');
552 } catch Error with {};
554 $self->timelog("Checked for auth proxy: $auth_proxy_enabled; org = $org_unit; username = $username");
557 type => ($persist) ? 'persist' : 'opac',
562 my $bc_regex = $ctx->{get_org_setting}->($org_unit, 'opac.barcode_regex');
564 # To avoid surprises, default to "Barcodes start with digits"
565 $bc_regex = '^\d' unless $bc_regex;
567 if ($bc_regex and ($username =~ /$bc_regex/)) {
568 $args->{barcode} = $username;
570 $args->{username} = $username;
574 if (!$auth_proxy_enabled) {
575 my $seed = $U->simplereq(
577 'open-ils.auth.authenticate.init', $username);
578 $args->{password} = md5_hex($seed . md5_hex($password));
579 $response = $U->simplereq(
580 'open-ils.auth', 'open-ils.auth.authenticate.complete', $args);
582 $args->{password} = $password;
583 $response = $U->simplereq(
584 'open-ils.auth_proxy',
585 'open-ils.auth_proxy.login', $args);
587 $self->timelog("Checked password");
589 if($U->event_code($response)) {
590 # login failed, report the reason to the template
591 $ctx->{login_failed_event} = $response;
592 return Apache2::Const::OK;
595 # login succeeded, redirect as necessary
597 my $acct = $self->apache->unparsed_uri;
598 $acct =~ s|/login|/myopac/main|;
600 # both login-related cookies should expire at the same time
601 my $login_cookie_expires = ($persist) ? CORE::time + $response->{payload}->{authtime} : undef;
604 # contains the actual auth token and should be sent only over https
609 -value => $response->{payload}->{authtoken},
610 -expires => $login_cookie_expires
612 # contains only a hint that we are logged in, and is used to
613 # trigger a redirect to https
615 -name => COOKIE_LOGGEDIN,
619 -expires => $login_cookie_expires
624 # contains the client's tz, as passed by the client
625 # trigger a redirect to https
626 push @$cookie_list, $cgi->cookie(
630 -value => $client_tz,
631 -expires => $login_cookie_expires
635 return $self->generic_redirect(
636 $cgi->param('redirect_to') || $acct,
641 # -----------------------------------------------------------------------------
642 # Log out and redirect to the home page
643 # -----------------------------------------------------------------------------
646 my $redirect_to = shift || $self->cgi->param('redirect_to');
648 # If the user was adding anyting to an anonymous cache
649 # while logged in, go ahead and clear it out.
650 $self->clear_anon_cache;
652 try { # a missing auth token will cause an ugly explosion
655 'open-ils.auth.session.delete',
656 $self->cgi->cookie(COOKIE_SES)
658 } catch Error with {};
660 return $self->generic_redirect(
661 $redirect_to || $self->ctx->{home_page},
663 # clear value of and expire both of these login-related cookies
671 -name => COOKIE_LOGGEDIN,