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::Container;
28 use OpenILS::WWW::EGCatLoader::SMS;
29 use OpenILS::WWW::EGCatLoader::Register;
31 my $U = 'OpenILS::Application::AppUtils';
33 use constant COOKIE_SES => 'ses';
34 use constant COOKIE_LOGGEDIN => 'eg_loggedin';
35 use constant COOKIE_TZ => 'client_tz';
36 use constant COOKIE_PHYSICAL_LOC => 'eg_physical_loc';
37 use constant COOKIE_SSS_EXPAND => 'eg_sss_expand';
39 use constant COOKIE_ANON_CACHE => 'anoncache';
40 use constant COOKIE_CART_CACHE => 'cartcache';
41 use constant CART_CACHE_MYLIST => 'mylist';
42 use constant ANON_CACHE_STAFF_SEARCH => 'staffsearch';
44 use constant DEBUG_TIMING => 0;
47 my($class, $apache, $ctx) = @_;
49 my $self = bless({}, ref($class) || $class);
51 $self->apache($apache);
54 $self->timelog("New page");
56 # Add a timelog helper to the context
57 $self->ctx->{timelog} = sub { return $self->timelog(@_) };
59 OpenILS::Utils::CStoreEditor->init; # just in case
60 $self->editor(new_editor());
67 $ENV{TZ} = $self->ctx->{original_tz}
68 if ($self->ctx && exists $self->ctx->{original_tz});
71 # current Apache2::RequestRec;
73 my($self, $apache) = @_;
74 $self->{apache} = $apache if $apache;
75 return $self->{apache};
78 # runtime / template context
81 $self->{ctx} = $ctx if $ctx;
87 my($self, $editor) = @_;
88 $self->{editor} = $editor if $editor;
89 return $self->{editor};
95 $self->{cgi} = $cgi if $cgi;
100 my($self, $description) = @_;
102 return unless DEBUG_TIMING;
103 return unless $description;
104 $self->ctx->{timing} ||= [];
106 my $timer = [Time::HiRes::gettimeofday()];
107 $self->ctx->{time_begin} ||= $timer;
109 push @{$self->ctx->{timing}}, [
110 Time::HiRes::tv_interval($self->ctx->{time_begin}, $timer), $description
114 # -----------------------------------------------------------------------------
115 # Perform initial setup, load common data, then load page data
116 # -----------------------------------------------------------------------------
120 $self->init_ro_object_cache;
121 $self->timelog("Initial load");
123 my $stat = $self->load_common;
124 return $stat unless $stat == Apache2::Const::OK;
126 my $path = $self->apache->path_info;
128 if ($path =~ m|opac/?$|) {
129 # nowhere specified, just go home
130 return $self->generic_redirect($self->ctx->{home_page});
133 (undef, $self->ctx->{mylist}) = $self->fetch_mylist unless
134 $path =~ /opac\/my(opac\/lists|list)/ ||
135 $path =~ m!opac/api/mylist!;
137 my $org_unit = $self->ctx->{physical_loc} || $self->cgi->param('context_org') || $self->_get_search_lib;
138 $self->ctx->{selected_print_email_loc} = $org_unit;
140 return $self->load_api_mylist_retrieve if $path =~ m|opac/api/mylist/retrieve|;
141 return $self->load_api_mylist_add if $path =~ m|opac/api/mylist/add|;
142 return $self->load_api_mylist_delete if $path =~ m|opac/api/mylist/delete|;
143 return $self->load_api_mylist_clear if $path =~ m|opac/api/mylist/clear|;
145 return $self->load_simple("home") if $path =~ m|opac/home|;
146 return $self->load_simple("css") if $path =~ m|opac/css|;
147 return $self->load_simple("advanced") if
148 $path =~ m:opac/(advanced|numeric|expert):;
150 return $self->load_library if $path =~ m|opac/library|;
151 return $self->load_rresults if $path =~ m|opac/results|;
152 return $self->load_print_or_email_preview('print') if $path =~ m|opac/record/print_preview|;
153 return $self->load_print_record if $path =~ m|opac/record/print|;
154 return $self->load_record if $path =~ m|opac/record/\d|;
155 return $self->load_cnbrowse if $path =~ m|opac/cnbrowse|;
156 return $self->load_browse if $path =~ m|opac/browse|;
158 return $self->load_mylist_add if $path =~ m|opac/mylist/add|;
159 return $self->load_mylist_delete if $path =~ m|opac/mylist/delete|;
160 return $self->load_mylist_move if $path =~ m|opac/mylist/move|;
161 return $self->load_mylist_print if $path =~ m|opac/mylist/doprint|;
162 return $self->load_mylist if $path =~ m|opac/mylist| && $path !~ m|opac/mylist/email| && $path !~ m|opac/mylist/doemail|;
163 return $self->load_cache_clear if $path =~ m|opac/cache/clear|;
164 return $self->load_temp_warn_post if $path =~ m|opac/temp_warn/post|;
165 return $self->load_temp_warn if $path =~ m|opac/temp_warn|;
167 # ----------------------------------------------------------------
168 # Everything below here requires SSL
169 # ----------------------------------------------------------------
170 return $self->redirect_ssl unless $self->cgi->https;
171 return $self->load_password_reset if $path =~ m|opac/password_reset|;
172 return $self->load_logout if $path =~ m|opac/logout|;
173 return $self->load_patron_reg if $path =~ m|opac/register|;
175 $self->load_simple("myopac") if $path =~ m:opac/myopac:; # A default page for myopac parts
177 if($path =~ m|opac/login|) {
178 return $self->load_login unless $self->editor->requestor; # already logged in?
180 # This will be less confusing to users than to be shown a login form
181 # when they're already logged in.
182 return $self->generic_redirect(
184 "%s://%s%s/myopac/main",
186 $self->ctx->{hostname}, $self->ctx->{opac_root}
191 if ($path =~ m|opac/sms_cn| and !$self->editor->requestor) {
192 my $skip_sms_auth = $self->ctx->{get_org_setting}->($org_unit, 'sms.disable_authentication_requirement.callnumbers');
193 return $self->load_sms_cn if $skip_sms_auth;
196 if (!$self->editor->requestor && $path =~ m|opac/record/email|) {
197 if ($self->ctx->{get_org_setting}->($org_unit, 'opac.email_record.allow_without_login')) {
198 my $cache = OpenSRF::Utils::Cache->new('global');
200 if ($path !~ m|preview|) { # the real thing!
201 $logger->info("not preview");
202 my $cap_key = $self->ctx->{cap}->{key} = $self->cgi->param('capkey');
203 $logger->info("got cap_key $cap_key");
205 my $cap_answer = $self->ctx->{cap_answer} = $self->cgi->param('capanswer');
206 my $real_answer = $self->ctx->{real_answer} = $cache->get_cache(md5_hex($cap_key));
207 $logger->info("got answers $cap_answer $real_answer");
208 return $self->load_email_record(1) if ( $cap_answer eq $real_answer );
213 $$captcha{key} = time() . $$ . rand();
214 $$captcha{left} = int(rand(10));
215 $$captcha{right} = int(rand(10));
216 $cache->put_cache(md5_hex($$captcha{key}), $$captcha{left} + $$captcha{right});
217 $self->ctx->{captcha} = $captcha;
218 return $self->load_print_or_email_preview('email', 1) if $path =~ m|opac/record/email_preview|;
222 # ----------------------------------------------------------------
223 # Everything below here requires authentication
224 # ----------------------------------------------------------------
225 return $self->redirect_auth unless $self->editor->requestor;
227 # Don't cache anything requiring auth for security reasons
228 $self->apache->headers_out->add("cache-control" => "no-store, no-cache, must-revalidate");
229 $self->apache->headers_out->add("expires" => "-1");
231 if ($path =~ m|opac/mylist/email|) {
232 (undef, $self->ctx->{mylist}) = $self->fetch_mylist;
234 $self->load_simple("mylist/email") if $path =~ m|opac/mylist/email|;
235 return $self->load_print_or_email_preview('email') if $path =~ m|opac/mylist/doemail_preview|;
236 return $self->load_mylist_email if $path =~ m|opac/mylist/doemail|;
237 return $self->load_print_or_email_preview('email') if $path =~ m|opac/record/email_preview|;
238 return $self->load_email_record if $path =~ m|opac/record/email|;
240 return $self->load_place_hold if $path =~ m|opac/place_hold|;
241 return $self->load_myopac_holds if $path =~ m|opac/myopac/holds|;
242 return $self->load_myopac_circs if $path =~ m|opac/myopac/circs|;
243 return $self->load_myopac_messages if $path =~ m|opac/myopac/messages|;
244 return $self->load_myopac_payment_form if $path =~ m|opac/myopac/main_payment_form|;
245 return $self->load_myopac_payments if $path =~ m|opac/myopac/main_payments|;
246 return $self->load_myopac_pay_init if $path =~ m|opac/myopac/main_pay_init|;
247 return $self->load_myopac_pay if $path =~ m|opac/myopac/main_pay|;
248 return $self->load_myopac_main if $path =~ m|opac/myopac/charges|;
249 return $self->load_myopac_main if $path =~ m|opac/myopac/main|;
250 return $self->load_myopac_receipt_email if $path =~ m|opac/myopac/receipt_email|;
251 return $self->load_myopac_receipt_print if $path =~ m|opac/myopac/receipt_print|;
252 return $self->load_myopac_update_email if $path =~ m|opac/myopac/update_email|;
253 return $self->load_myopac_update_password if $path =~ m|opac/myopac/update_password|;
254 return $self->load_myopac_update_username if $path =~ m|opac/myopac/update_username|;
255 return $self->load_myopac_bookbags if $path =~ m|opac/myopac/lists|;
256 return $self->load_myopac_bookbag_print if $path =~ m|opac/myopac/list/print|;
257 return $self->load_myopac_bookbag_update if $path =~ m|opac/myopac/list/update|;
258 return $self->load_myopac_circ_history_export if $path =~ m|opac/myopac/circ_history/export|;
259 return $self->load_myopac_circ_history if $path =~ m|opac/myopac/circ_history|;
260 return $self->load_myopac_hold_history if $path =~ m|opac/myopac/hold_history|;
261 return $self->load_myopac_prefs_notify_changed_holds if $path =~ m|opac/myopac/prefs_notify_changed_holds|;
262 return $self->load_myopac_prefs_notify if $path =~ m|opac/myopac/prefs_notify|;
263 return $self->load_myopac_prefs_settings if $path =~ m|opac/myopac/prefs_settings|;
264 return $self->load_myopac_prefs_my_lists if $path =~ m|opac/myopac/prefs_my_lists|;
265 return $self->load_myopac_prefs if $path =~ m|opac/myopac/prefs|;
266 return $self->load_myopac_reservations if $path =~ m|opac/myopac/reservations|;
267 return $self->load_sms_cn if $path =~ m|opac/sms_cn|;
269 return Apache2::Const::OK;
273 # -----------------------------------------------------------------------------
274 # Redirect to SSL equivalent of a given page
275 # -----------------------------------------------------------------------------
278 my $new_page = sprintf('%s://%s%s', ($self->ctx->{is_staff} ? 'oils' : 'https'), $self->ctx->{hostname}, $self->apache->unparsed_uri);
279 return $self->generic_redirect($new_page);
282 # -----------------------------------------------------------------------------
283 # If an authnticated resource is requested w/o auth, redirect to the login page,
284 # then return to the originally requrested resource upon successful login.
285 # -----------------------------------------------------------------------------
288 my $login_page = sprintf('%s://%s%s/login',($self->ctx->{is_staff} ? 'oils' : 'https'), $self->ctx->{hostname}, $self->ctx->{opac_root});
289 my $redirect_to = uri_escape_utf8($self->apache->unparsed_uri);
290 return $self->generic_redirect("$login_page?redirect_to=$redirect_to");
293 # -----------------------------------------------------------------------------
294 # Fall-through for loading a basic page
295 # -----------------------------------------------------------------------------
297 my ($self, $page) = @_;
298 $self->ctx->{page} = $page;
299 $self->ctx->{search_ou} = $self->_get_search_lib();
301 return Apache2::Const::OK;
304 # -----------------------------------------------------------------------------
305 # Tests to see if the user is authenticated and sets some common context values
306 # -----------------------------------------------------------------------------
310 my $e = $self->editor;
311 my $ctx = $self->ctx;
313 # redirect non-https to https if we think we are already logged in
314 if ($self->cgi->cookie(COOKIE_LOGGEDIN)) {
315 return $self->redirect_ssl unless $self->cgi->https;
318 # XXX Cache this? Makes testing difficult as apache needs a restart.
319 my $default_sort = $e->retrieve_config_global_flag('opac.default_sort');
320 $ctx->{default_sort} =
321 ($default_sort && $U->is_true($default_sort->enabled)) ? $default_sort->value : '';
323 $ctx->{client_tz} = $self->cgi->cookie(COOKIE_TZ) || $ENV{TZ};
324 $ctx->{referer} = $self->cgi->referer;
325 $ctx->{path_info} = $self->cgi->path_info;
326 $ctx->{full_path} = $ctx->{base_path} . $self->cgi->path_info;
327 $ctx->{unparsed_uri} = $self->apache->unparsed_uri;
328 $ctx->{opac_root} = $ctx->{base_path} . "/opac"; # absolute base url
330 $ctx->{original_tz} = $ENV{TZ};
331 $ENV{TZ} = $ctx->{client_tz};
334 ($self->apache->headers_in->get('OILS-Wrapper') || '') =~ /true/;
338 $ctx->{is_staff} = 1;
339 $ctx->{proto} = 'oils';
340 $ctx->{hostname} = 'remote';
343 $ctx->{physical_loc} = $self->get_physical_loc;
345 # capture some commonly accessed pages
346 $ctx->{home_page} = $ctx->{proto} . '://' . $ctx->{hostname} . $self->ctx->{opac_root} . "/home";
347 $ctx->{logout_page} = ($ctx->{proto} eq 'http' ? 'https' : $ctx->{proto} ) . '://' . $ctx->{hostname} . $self->ctx->{opac_root} . "/logout";
349 if($e->authtoken($self->cgi->cookie(COOKIE_SES))) {
353 $ctx->{authtoken} = $e->authtoken;
354 $ctx->{authtime} = $e->authtime;
355 $ctx->{user} = $e->requestor;
356 my $card = $self->editor->retrieve_actor_card($ctx->{user}->card);
357 $ctx->{active_card} = (ref $card) ? $card->barcode : undef;
358 $ctx->{place_unfillable} = 1 if $e->requestor->wsid && $e->allowed('PLACE_UNFILLABLE_HOLD', $e->requestor->ws_ou);
360 # The browser client does not set an OILS-Wrapper header (above).
361 # The presence of a workstation and no header indicates staff mode.
362 # FIXME: this approach leaves un-wrapped TPAC's within the same
363 # browser (and hence same ses cookie) in an unnatural is_staff
364 # state. Consider alternatives for determining is_staff /
365 # is_browser_staff when $xul_wrapper is false.
366 if (!$xul_wrapper and $e->requestor->wsid) {
367 $ctx->{is_staff} = 1;
368 $ctx->{is_browser_staff} = 1;
371 $self->update_dashboard_stats();
375 # if we encounter a stale authtoken, call load_logout
376 # to clean up the cookie, then redirect the user to the
377 # originally requested page
378 return $self->load_logout($self->apache->unparsed_uri);
382 # List of <meta> and <link> elements to populate
383 $ctx->{metalinks} = [];
385 $self->extract_copy_location_group_info;
386 $ctx->{search_ou} = $self->_get_search_lib();
387 $self->staff_saved_searches_set_expansion_state if $ctx->{is_staff};
388 $self->load_eg_cache_hash;
389 $self->load_copy_location_groups;
390 $self->staff_saved_searches_set_expansion_state if $ctx->{is_staff};
391 $self->load_search_filter_groups($ctx->{search_ou});
392 $self->load_org_util_funcs;
393 $self->load_perm_funcs;
395 # FIXME - move carousel helpers to a separate file
396 $ctx->{get_visible_carousels} = sub {
397 my $org_unit = $self->ctx->{physical_loc} || $self->cgi->param('loc') || $self->ctx->{aou_tree}->()->id;
398 return $U->simplereq(
400 'open-ils.actor.carousel.retrieve_by_org',
404 $ctx->{get_carousel} = sub {
407 my $carousel = $e->retrieve_container_carousel($id);
410 name => $carousel->name
413 select => { bre => ['id'], mfde => [{ column => 'value', alias => 'title' }] },
427 '+cc' => { id => $id },
428 '+bre' => { deleted => 'f' },
429 '+mfde' => { name => 'title' }
432 my $r = $e->json_query($q);
437 $ctx->{fetch_display_fields} = sub {
441 return $ctx->{_hl_data}{''.$$id[0]}
442 if ($ctx->{_hl_data}{''.$$id[0]});
445 $self->timelog("HL data not cached, fetching from server.");
447 my $rows = $U->simplereq(
449 'open-ils.search.fetch.metabib.display_field.highlight',
450 $ctx->{query_struct}{additional_data}{highlight_map},
454 $ctx->{_hl_data}{''.$$id[0]} = $rows if (@$id == 1);
459 return Apache2::Const::OK;
462 sub update_dashboard_stats {
465 my $e = $self->editor;
466 my $ctx = $self->ctx;
468 $ctx->{user_stats} = $U->simplereq(
470 'open-ils.actor.user.opac.vital_stats',
471 $e->authtoken, $e->requestor->id);
474 sub staff_saved_searches_set_expansion_state {
477 my $param = $self->cgi->param('sss_expand');
480 if (defined $param) {
481 $value = ($param ? 1 : 0);
482 $self->apache->headers_out->add(
483 "Set-Cookie" => $self->cgi->cookie(
484 -name => COOKIE_SSS_EXPAND,
485 -path => $self->ctx->{base_path},
486 -secure => 1, # not strictly necessary, but this feature is staff-only, so may as well
492 $value = $self->cgi->cookie(COOKIE_SSS_EXPAND);
495 $self->ctx->{saved_searches_expanded} = $value;
498 # physical_loc (i.e. "original location") passed in as a URL
499 # param will replace any existing physical_loc stored as a cookie.
500 # If specified via ENV that rules over all and we don't set cookies.
501 sub get_physical_loc {
504 return $ENV{physical_loc} if($ENV{physical_loc});
506 if(my $physical_loc = $self->cgi->param('physical_loc')) {
507 $self->apache->headers_out->add(
508 "Set-Cookie" => $self->cgi->cookie(
509 -name => COOKIE_PHYSICAL_LOC,
510 -path => $self->ctx->{base_path},
511 -value => $physical_loc,
515 return $physical_loc;
518 return $self->cgi->cookie(COOKIE_PHYSICAL_LOC);
521 # -----------------------------------------------------------------------------
522 # Log in and redirect to the redirect_to URL (or home)
523 # -----------------------------------------------------------------------------
526 my $cgi = $self->cgi;
527 my $ctx = $self->ctx;
529 $self->timelog("Load login begins");
531 $ctx->{page} = 'login';
533 my $username = $cgi->param('username') || '';
534 $username =~ s/\s//g; # Remove blanks
535 my $password = $cgi->param('password');
536 my $org_unit = $ctx->{physical_loc} || $ctx->{aou_tree}->()->id;
537 my $persist = $cgi->param('persist');
538 my $client_tz = $cgi->param('client_tz');
540 # initial log form only
541 return Apache2::Const::OK unless $username and $password;
543 my $auth_proxy_enabled = 0; # default false
544 try { # if the service is not running, just let this fail silently
545 $auth_proxy_enabled = $U->simplereq(
546 'open-ils.auth_proxy',
547 'open-ils.auth_proxy.enabled');
548 } catch Error with {};
550 $self->timelog("Checked for auth proxy: $auth_proxy_enabled; org = $org_unit; username = $username");
553 type => ($persist) ? 'persist' : 'opac',
558 my $bc_regex = $ctx->{get_org_setting}->($org_unit, 'opac.barcode_regex');
560 # To avoid surprises, default to "Barcodes start with digits"
561 $bc_regex = '^\d' unless $bc_regex;
563 if ($bc_regex and ($username =~ /$bc_regex/)) {
564 $args->{barcode} = $username;
566 $args->{username} = $username;
570 if (!$auth_proxy_enabled) {
571 my $seed = $U->simplereq(
573 'open-ils.auth.authenticate.init', $username);
574 $args->{password} = md5_hex($seed . md5_hex($password));
575 $response = $U->simplereq(
576 'open-ils.auth', 'open-ils.auth.authenticate.complete', $args);
578 $args->{password} = $password;
579 $response = $U->simplereq(
580 'open-ils.auth_proxy',
581 'open-ils.auth_proxy.login', $args);
583 $self->timelog("Checked password");
585 if($U->event_code($response)) {
586 # login failed, report the reason to the template
587 $ctx->{login_failed_event} = $response;
588 return Apache2::Const::OK;
591 # login succeeded, redirect as necessary
593 my $acct = $self->apache->unparsed_uri;
594 $acct =~ s|/login|/myopac/main|;
596 # both login-related cookies should expire at the same time
597 my $login_cookie_expires = ($persist) ? CORE::time + $response->{payload}->{authtime} : undef;
600 # contains the actual auth token and should be sent only over https
605 -value => $response->{payload}->{authtoken},
606 -expires => $login_cookie_expires
608 # contains only a hint that we are logged in, and is used to
609 # trigger a redirect to https
611 -name => COOKIE_LOGGEDIN,
615 -expires => $login_cookie_expires
620 # contains the client's tz, as passed by the client
621 # trigger a redirect to https
622 push @$cookie_list, $cgi->cookie(
626 -value => $client_tz,
627 -expires => $login_cookie_expires
631 return $self->generic_redirect(
632 $cgi->param('redirect_to') || $acct,
637 # -----------------------------------------------------------------------------
638 # Log out and redirect to the home page
639 # -----------------------------------------------------------------------------
642 my $redirect_to = shift || $self->cgi->param('redirect_to');
644 # If the user was adding anyting to an anonymous cache
645 # while logged in, go ahead and clear it out.
646 $self->clear_anon_cache;
648 try { # a missing auth token will cause an ugly explosion
651 'open-ils.auth.session.delete',
652 $self->cgi->cookie(COOKIE_SES)
654 } catch Error with {};
656 return $self->generic_redirect(
657 $redirect_to || $self->ctx->{home_page},
659 # clear value of and expire both of these login-related cookies
667 -name => COOKIE_LOGGEDIN,