1 package OpenILS::WWW::EGCatLoader;
2 use strict; use warnings;
3 use Apache2::Const -compile => qw(OK DECLINED FORBIDDEN HTTP_INTERNAL_SERVER_ERROR REDIRECT HTTP_BAD_REQUEST);
5 use Time::HiRes qw/time sleep/;
6 use OpenSRF::Utils::Cache;
7 use OpenSRF::Utils::Logger qw/$logger/;
8 use OpenILS::Utils::CStoreEditor qw/:funcs/;
9 use OpenILS::Utils::Fieldmapper;
10 use OpenILS::Application::AppUtils;
11 use OpenSRF::MultiSession;
13 my $U = 'OpenILS::Application::AppUtils';
15 my $ro_object_subs; # cached subs
16 our %cache = ( # cached data
18 list => {en_us => {}},
19 search => {en_us => {}},
20 org_settings => {en_us => {}},
21 search_filter_groups => {en_us => {}},
22 aou_tree => {en_us => undef},
24 eg_cache_hash => undef,
25 authority_fields => {en_us => {}}
28 sub init_ro_object_cache {
30 my $e = $self->editor;
33 # reset org unit setting cache on each page load to avoid the
34 # requirement of reloading apache with each org-setting change
35 $cache{org_settings} = {};
38 # subs have been built. insert into the context then move along.
39 $ctx->{$_} = $ro_object_subs->{$_} for keys %$ro_object_subs;
43 # make all "field_safe" classes accesible by default in the template context
45 ($Fieldmapper::fieldmap->{$_}->{field_safe} || '') =~ /true/i
46 } keys %{ $Fieldmapper::fieldmap };
48 for my $class (@classes) {
50 my $hint = $Fieldmapper::fieldmap->{$class}->{hint};
51 next if $hint eq 'aou'; # handled separately
53 my $ident_field = $Fieldmapper::fieldmap->{$class}->{identity};
54 (my $eclass = $class) =~ s/Fieldmapper:://o;
57 my $list_key = "${hint}_list";
58 my $get_key = "get_$hint";
59 my $search_key = "search_$hint";
61 # Retrieve the full set of objects with class $hint
62 $ro_object_subs->{$list_key} = sub {
63 my $method = "retrieve_all_$eclass";
64 $cache{list}{$ctx->{locale}}{$hint} = $e->$method() unless $cache{list}{$ctx->{locale}}{$hint};
65 return $cache{list}{$ctx->{locale}}{$hint};
68 # locate object of class $hint with Ident field $id
69 $cache{map}{$hint} = {};
70 $ro_object_subs->{$get_key} = sub {
72 return $cache{map}{$ctx->{locale}}{$hint}{$id} if $cache{map}{$ctx->{locale}}{$hint}{$id};
73 ($cache{map}{$ctx->{locale}}{$hint}{$id}) = grep { $_->$ident_field eq $id } @{$ro_object_subs->{$list_key}->()};
74 return $cache{map}{$ctx->{locale}}{$hint}{$id};
77 # search for objects of class $hint where field=value
78 $cache{search}{$hint} = {};
79 $ro_object_subs->{$search_key} = sub {
80 my ($field, $val, $filterfield, $filterval) = @_;
81 my $method = "search_$eclass";
84 $val = [sort(@$val)] if ref $val eq 'ARRAY';
85 $cacheval = OpenSRF::Utils::JSON->perl2JSON($val);
86 #$self->apache->log->info("cacheval : $cacheval");
88 my $search_obj = {$field => $val};
90 $search_obj->{$filterfield} = $filterval;
91 $cacheval .= ':' . $filterfield . ':' . $filterval;
93 #$cache{search}{$ctx->{locale}}{$hint}{$field} = {} unless $cache{search}{$ctx->{locale}}{$hint}{$field};
94 $cache{search}{$ctx->{locale}}{$hint}{$field}{$cacheval} = $e->$method($search_obj)
95 unless $cache{search}{$ctx->{locale}}{$hint}{$field}{$cacheval};
96 return $cache{search}{$ctx->{locale}}{$hint}{$field}{$cacheval};
100 $ro_object_subs->{aou_tree} = sub {
102 # fetch the org unit tree
103 unless($cache{aou_tree}{$ctx->{locale}}) {
104 my $tree = $e->search_actor_org_unit([
105 { parent_ou => undef},
107 flesh_fields => {aou => ['children']},
108 order_by => {aou => 'name'}
112 # flesh the org unit type for each org unit
113 # and simultaneously set the id => aou map cache
116 my $ro_object_subs = shift;
118 $node->ou_type( $ro_object_subs->{get_aout}->($node->ou_type) );
119 $cache{map}{$ctx->{locale}}{aou}{$node->id} = $node;
120 flesh_aout($_, $ro_object_subs, $ctx) foreach @{$node->children};
122 flesh_aout($tree, $ro_object_subs, $ctx);
124 $cache{aou_tree}{$ctx->{locale}} = $tree;
127 return $cache{aou_tree}{$ctx->{locale}};
130 # Add a special handler for the tree-shaped org unit cache
131 $ro_object_subs->{get_aou} = sub {
133 return undef unless defined $org_id;
134 $ro_object_subs->{aou_tree}->(); # force the org tree to load
135 return $cache{map}{$ctx->{locale}}{aou}{$org_id};
138 # Returns a flat list of aou objects. often easier to manage than a tree.
139 $ro_object_subs->{aou_list} = sub {
140 $ro_object_subs->{aou_tree}->(); # force the org tree to load
141 return [ values %{$cache{map}{$ctx->{locale}}{aou}} ];
144 # returns the org unit object by shortname
145 $ro_object_subs->{get_aou_by_shortname} = sub {
146 my $sn = shift or return undef;
147 my $list = $ro_object_subs->{aou_list}->();
148 return (grep {$_->shortname eq $sn} @$list)[0];
151 $ro_object_subs->{aouct_tree} = sub {
153 # fetch the org unit tree
154 unless(exists $cache{aouct_tree}{$ctx->{locale}}) {
155 $cache{aouct_tree}{$ctx->{locale}} = undef;
157 my $tree_id = $e->search_actor_org_unit_custom_tree(
158 {purpose => 'opac', active => 't'},
163 my $node_tree = $e->search_actor_org_unit_custom_tree_node([
164 {parent_node => undef, tree => $tree_id},
166 flesh_fields => {aouctn => ['children', 'org_unit']},
167 order_by => {aouctn => 'sibling_order'}
171 # tree-ify the org units. note that since the orgs are fleshed
172 # upon retrieval, this org tree will not clobber ctx->{aou_tree}.
173 my @nodes = ($node_tree);
174 while (my $node = shift(@nodes)) {
175 my $aou = $node->org_unit;
177 for my $cnode (@{$node->children}) {
178 my $child_org = $cnode->org_unit;
179 $child_org->parent_ou($aou->id);
180 $child_org->ou_type( $ro_object_subs->{get_aout}->($child_org->ou_type) );
181 push(@{$aou->children}, $child_org);
182 push(@nodes, $cnode);
186 $cache{aouct_tree}{$ctx->{locale}} =
187 $node_tree->org_unit if $node_tree;
191 return $cache{aouct_tree}{$ctx->{locale}};
194 # turns an ISO date into something TT can understand
195 $ro_object_subs->{parse_datetime} = sub {
198 # Probably an accidental entry like '0212' instead of '2012',
199 # but 1) the leading 0 may get stripped in cstore and
200 # 2) DateTime::Format::ISO8601 returns an error as years
201 # must be 2 or 4 digits
202 if ($date =~ m/^\d{3}-/) {
203 $logger->warn("Invalid date had a 3-digit year: $date");
205 } elsif ($date =~ m/^\d{1}-/) {
206 $logger->warn("Invalid date had a 1-digit year: $date");
207 $date = '000' . $date;
210 my $cleansed_date = cleanse_ISO8601($date);
212 $date = DateTime::Format::ISO8601->new->parse_datetime($cleansed_date);
214 "%0.2d:%0.2d:%0.2d %0.2d-%0.2d-%0.4d",
224 # retrieve and cache org unit setting values
225 $ro_object_subs->{get_org_setting} = sub {
226 my($org_id, $setting) = @_;
228 $cache{org_settings}{$ctx->{locale}}{$org_id}{$setting} =
229 $U->ou_ancestor_setting_value($org_id, $setting)
230 unless exists $cache{org_settings}{$ctx->{locale}}{$org_id}{$setting};
232 return $cache{org_settings}{$ctx->{locale}}{$org_id}{$setting};
235 # retrieve and cache acsaf values
236 $ro_object_subs->{get_authority_fields} = sub {
237 my ($control_set) = @_;
239 if (not exists $cache{authority_fields}{$ctx->{locale}}{$control_set}) {
240 my $acs = $e->search_authority_control_set_authority_field(
241 {control_set => $control_set}
243 $cache{authority_fields}{$ctx->{locale}}{$control_set} =
244 +{ map { $_->id => $_ } @$acs };
247 return $cache{authority_fields}{$ctx->{locale}}{$control_set};
250 $ctx->{$_} = $ro_object_subs->{$_} for keys %$ro_object_subs;
253 sub generic_redirect {
256 my $cookie = shift; # can be an array of cgi.cookie's
258 $self->apache->print(
259 $self->cgi->redirect(
261 $self->cgi->param('redirect_to') ||
262 $self->ctx->{referer} ||
263 $self->ctx->{home_page},
268 return Apache2::Const::REDIRECT;
272 sub get_records_and_facets {
273 my ($self, $rec_ids, $facet_key, $unapi_args) = @_;
276 $unapi_args->{site} ||= $self->ctx->{aou_tree}->()->shortname;
277 $unapi_args->{depth} ||= $self->ctx->{aou_tree}->()->ou_type->depth;
278 $unapi_args->{flesh_depth} ||= 5;
280 my $is_meta = delete $unapi_args->{metarecord};
281 my $unapi_type = $is_meta ? 'unapi.mmr' : 'unapi.bre';
283 $unapi_cache ||= OpenSRF::Utils::Cache->new('global');
284 my $unapi_cache_key_suffix = join(
288 $unapi_args->{depth},
289 $unapi_args->{flesh_depth},
290 ($unapi_args->{pref_lib} || '')
294 my $outer_self = $self;
295 $self->timelog("get_records_and_facets(): about to call multisession");
296 my $ses = OpenSRF::MultiSession->new(
297 app => 'open-ils.cstore',
298 cap => 10, # XXX config
299 success_handler => sub {
300 my($self, $req) = @_;
301 my $data = $req->{response}->[0]->content;
303 $outer_self->timelog("get_records_and_facets(): got response content");
305 # Protect against requests for non-existent records
306 return unless $data->{$unapi_type};
308 my $xml = XML::LibXML->new->parse_string($data->{$unapi_type})->documentElement;
310 $outer_self->timelog("get_records_and_facets(): parsed xml");
311 # Protect against legacy invalid MARCXML that might not have a 901c
314 my $bre_id_nodes = $xml->find('*[@tag="901"]/*[@code="c"]');
316 $bre_id = $bre_id_nodes->[0]->textContent;
318 $logger->warn("Missing 901 subfield 'c' in " . $xml->toString());
322 # extract metarecord ID from mmr.unapi tag
323 for my $node ($xml->getElementsByTagName('abbr')) {
324 my $title = $node->getAttribute('title');
325 ($mmr_id = $title) =~
326 s/tag:open-ils.org:U2\@mmr\/(\d+)\/.*/$1/g;
331 my $rec_id = $mmr_id ? $mmr_id : $bre_id;
332 $tmp_data{$rec_id} = {
340 # Let other backends grab our data now that we're done.
341 my $key = 'TPAC_unapi_cache_'.$rec_id.'_'.$unapi_cache_key_suffix;
342 my $cache_data = $unapi_cache->get_cache($key);
343 if ($$cache_data{running}) {
344 $unapi_cache->put_cache($key, {
348 marc_xml => $data->{$unapi_type}
353 $outer_self->timelog("get_records_and_facets(): end of success handler");
357 $self->timelog("get_records_and_facets(): about to call ".
358 "$unapi_type via json_query (rec_ids has " . scalar(@$rec_ids));
360 my @loop_recs = @$rec_ids;
363 while (my $bid = shift @loop_recs) {
365 sleep(0.1) if $rec_timeout{$bid};
367 my $unapi_cache_key = 'TPAC_unapi_cache_'.$bid.'_'.$unapi_cache_key_suffix;
368 my $unapi_data = $unapi_cache->get_cache($unapi_cache_key) || {};
370 if ($unapi_data->{running}) { #cache entry from ongoing, concurrent retrieval
371 if (!$rec_timeout{$bid}) {
372 $rec_timeout{$bid} = time() + 10;
375 if ( time() > $rec_timeout{$bid} ) { # we've waited too long. just do it
377 delete $rec_timeout{$bid};
378 } else { # we'll pause next time around to let this one try again
379 push(@loop_recs, $bid);
384 if ($unapi_data->{marc_xml}) { # we got data from the cache
385 $unapi_data->{marc_xml} = XML::LibXML->new->parse_string($unapi_data->{marc_xml})->documentElement;
386 $tmp_data{$unapi_data->{id}} = $unapi_data;
387 } else { # we're the first or we timed out. success_handler will populate the real value
388 $unapi_cache->put_cache($unapi_cache_key, { running => $$ }, 10);
390 my $sdepth = $unapi_args->{flesh_depth};
391 my $slimit = "acn=>$sdepth,acp=>$sdepth";
392 $slimit .= ",bre=>$sdepth" if $is_meta;
393 my $flesh = $unapi_args->{flesh} || '';
395 # tag the record with the MR id
396 $flesh =~ s/}$/,mmr.unapi}/g if $is_meta;
399 'open-ils.cstore.json_query',
401 $unapi_type, $bid, 'marcxml','record', $flesh,
403 $unapi_args->{depth},
405 undef, undef, $unapi_args->{pref_lib}
412 $self->timelog("get_records_and_facets():almost ready to fetch facets");
413 # collect the facet data
414 my $search = OpenSRF::AppSession->create('open-ils.search');
415 my $facet_req = $search->request(
416 'open-ils.search.facet_cache.retrieve', $facet_key
419 # gather up the unapi recs
420 $ses->session_wait(1);
421 $self->timelog("get_records_and_facets():past session wait");
425 my $tmp_facets = $facet_req->gather(1);
426 $self->timelog("get_records_and_facets(): gathered facet data");
427 for my $cmf_id (keys %$tmp_facets) {
429 # sort highest to lowest match count
431 my $entries = $tmp_facets->{$cmf_id};
432 for my $ent (keys %$entries) {
433 push(@entries, {value => $ent, count => $$entries{$ent}});
436 # Sort facet entries by 1) count descending, 2) text ascending
438 $b->{count} <=> $a->{count} ||
439 $a->{value} cmp $b->{value}
442 $facets->{$cmf_id} = {
443 cmf => $self->ctx->{get_cmf}->($cmf_id),
447 $self->timelog("get_records_and_facets(): gathered/sorted facet data");
454 return ($facets, map { $tmp_data{$_} } @$rec_ids);
457 sub _resolve_org_id_or_shortname {
458 my ($self, $str) = @_;
461 # Match on shortname case insensitively, but only if there's exactly
462 # one match. We wouldn't want the system to arbitrarily interpret
463 # 'foo' as either the org unit with shortname 'FOO' or 'Foo' and fail
464 # to make it clear to the user which one was chosen and why.
465 my $res = $self->editor->search_actor_org_unit({
468 transform => 'evergreen.lowercase',
473 return $res->[0]->id if $res and @$res == 1;
476 # Note that we don't validate IDs; we only try a shortname lookup and then
477 # assume anything else must be an ID.
478 return int($str); # Wrapping in int() prevents 500 on unmatched string.
481 sub _get_search_lib {
483 my $ctx = $self->ctx;
485 # avoid duplicate lookups
486 return $ctx->{search_ou} if $ctx->{search_ou};
488 my $loc = $ctx->{copy_location_group_org};
491 # loc param takes precedence
492 # XXX ^-- over what exactly? We could use clarification here. To me it looks
493 # like locg takes precedence over loc which in turn takes precedence over
494 # request headers which take precedence over pref_lib (which can be
495 # specified a lot of different ways and eventually falls back to
496 # physical_loc) and it all finally defaults to top of the org tree.
497 # To say nothing of all the code that doesn't look to this function at all
498 # but rather accesses some subset of these inputs directly.
500 $loc = $self->cgi->param('loc');
503 if ($self->apache->headers_in->get('OILS-Search-Lib')) {
504 return $self->apache->headers_in->get('OILS-Search-Lib');
507 my $pref_lib = $self->_get_pref_lib();
508 return $pref_lib if $pref_lib;
510 return $ctx->{aou_tree}->()->id;
515 my $ctx = $self->ctx;
517 # plib param takes precedence
518 my $plib = $self->cgi->param('plib');
519 return $plib if $plib;
521 if ($self->apache->headers_in->get('OILS-Pref-Lib')) {
522 return $self->apache->headers_in->get('OILS-Pref-Lib');
526 # See if the user has a search library preference
527 my $lset = $self->editor->search_actor_user_setting({
528 usr => $ctx->{user}->id,
529 name => 'opac.default_search_location'
531 return OpenSRF::Utils::JSON->JSON2perl($lset->value) if $lset;
533 # Otherwise return the user's home library
534 my $ou = $ctx->{user}->home_ou;
535 return ref($ou) ? $ou->id : $ou;
538 if ($ctx->{physical_loc}) {
539 return $ctx->{physical_loc};
544 # This is defensively coded since we don't do much manual reading from the
545 # file system in this module.
546 sub load_eg_cache_hash {
549 # just a context helper
550 $self->ctx->{eg_cache_hash} = sub { return $cache{eg_cache_hash}; };
552 # Need to actually load the value? If already done, move on.
553 return if defined $cache{eg_cache_hash};
555 # In this way even if we fail, we won't slow things down by ever trying
556 # again within this Apache process' lifetime.
557 $cache{eg_cache_hash} = 0;
559 my $path = File::Spec->catfile(
560 $self->apache->document_root, "eg_cache_hash"
563 if (not open FH, "<$path") {
564 $self->apache->log->warn("error opening $path : $!");
568 my $rv = read FH, $buf, 64; # defensive
571 if (not defined $rv) { # error
572 $self->apache->log->warn("error reading $path : $!");
573 } elsif ($rv > 0) { # no error, something read
575 $cache{eg_cache_hash} = $buf;
580 # Extracts the copy location org unit and group from the
581 # "logc" param, which takes the form org_id:grp_id.
582 sub extract_copy_location_group_info {
584 my $ctx = $self->ctx;
585 if (my $clump = $self->cgi->param('locg')) {
586 my ($org, $grp) = split(/:/, $clump);
587 $ctx->{copy_location_group_org} =
588 $self->_resolve_org_id_or_shortname($org);
589 $ctx->{copy_location_group} = $grp if $grp;
593 sub load_copy_location_groups {
595 my $ctx = $self->ctx;
597 # User can access to the search location groups at the current
598 # search lib, the physical location lib, and the patron's home ou.
599 my @ctx_orgs = $ctx->{search_ou};
600 push(@ctx_orgs, $ctx->{physical_loc}) if $ctx->{physical_loc};
601 push(@ctx_orgs, $ctx->{user}->home_ou) if $ctx->{user};
603 my $grps = $self->editor->search_asset_copy_location_group([
610 transform => 'actor.org_unit_full_path',
611 result_field => 'id',
614 where => {id => \@ctx_orgs}
618 {order_by => {acplg => 'pos'}}
622 push(@{$buckets{$_->owner}}, $_) for @$grps;
623 $ctx->{copy_location_groups} = \%buckets;
626 sub set_file_download_headers {
628 my $filename = shift;
629 my $ctype = shift || "text/plain; encoding=utf8";
631 $self->apache->content_type($ctype);
633 $self->apache->headers_out->add(
634 "Content-Disposition",
635 "attachment;filename=$filename"
638 return Apache2::Const::OK;
641 sub apache_log_if_event {
642 my ($self, $event, $prefix_text, $success_ok, $level) = @_;
644 $prefix_text ||= "Evergreen returned event";
649 $prefix_text .= ": ";
651 my $code = $U->event_code($event);
652 if (defined $code and ($code or not $success_ok)) {
653 $self->apache->log->$level(
655 ($event->{textcode} || "") . " ($code)" .
656 ($event->{note} ? (": " . $event->{note}) : "")
664 sub load_search_filter_groups {
667 my $org_list = $U->get_org_ancestors($ctx_org, 1);
670 for my $org_id (@$org_list) {
673 if (! ($grps = $cache{search_filter_groups}{$org_id}) ) {
674 $grps = $self->editor->search_actor_search_filter_group([
681 order_by => {asfge => 'pos'}
684 $cache{search_filter_groups}{$org_id} = $grps;
687 # for the current context, if a descendant org has a group
688 # with a matching code replace the group from the parent.
689 $seen{$_->code} = $_ for @$grps;
692 return $self->ctx->{search_filter_groups} = \%seen;
696 sub check_for_temp_list_warning {
698 my $ctx = $self->ctx;
699 my $cgi = $self->cgi;
701 my $lib = $self->_get_search_lib;
702 my $warn = ($ctx->{get_org_setting}->($lib || 1, 'opac.patron.temporary_list_warn')) ? 1 : 0;
704 if ($warn && $ctx->{user}) {
705 $self->_load_user_with_prefs;
706 my $map = $ctx->{user_setting_map};
707 $warn = 0 if ($$map{'opac.temporary_list_no_warn'});
710 # Check for a cookie disabling the warning.
711 $warn = 0 if ($warn && $cgi->cookie('no_temp_list_warn'));
716 sub load_org_util_funcs {
718 my $ctx = $self->ctx;
720 # evaluates to true if test_ou is within the same depth-
721 # scoped tree as ctx_ou. both ou's are org unit objects.
722 $ctx->{org_within_scope} = sub {
723 my ($ctx_ou, $test_ou, $depth) = @_;
725 return 1 if $ctx_ou->id == $test_ou->id;
729 # find the top-most ctx-org ancestor at the provided depth
730 while ($depth < $ctx_ou->ou_type->depth
731 and $ctx_ou->id != $test_ou->id) {
732 $ctx_ou = $ctx->{get_aou}->($ctx_ou->parent_ou);
735 # the preceeding loop may have landed on our org
736 return 1 if $ctx_ou->id == $test_ou->id;
740 return 1 if defined $depth; # $depth == 0;
743 for my $child (@{$ctx_ou->children}) {
744 return 1 if $ctx->{org_within_scope}->($child, $test_ou);
750 # Returns true if the provided org unit is within the same
751 # org unit hiding depth-scoped tree as the physical location.
752 # Org unit hiding is based on the immutable physical_loc
753 # and is not meant to change as search/pref/etc libs change
754 $ctx->{org_within_hiding_scope} = sub {
756 my $ploc = $ctx->{physical_loc} or return 1;
758 my $depth = $ctx->{get_org_setting}->(
759 $ploc, 'opac.org_unit_hiding.depth');
761 return 1 unless $depth; # 0 or undef
763 return $ctx->{org_within_scope}->(
764 $ctx->{get_aou}->($ploc),
765 $ctx->{get_aou}->($org_id), $depth);
769 # Evaluates to true if the context org (defaults to get_library)
770 # is not within the hiding scope. Also evaluates to true if the
771 # user's pref_ou is set and it's out of hiding scope.
772 # Always evaluates to true when ctx.is_staff
773 $ctx->{org_hiding_disabled} = sub {
774 my $ctx_org = shift || $ctx->{search_ou};
776 return 1 if $ctx->{is_staff};
778 # beware locg values formatted as org:loc
779 $ctx_org =~ s/:.*//g;
781 return 1 if !$ctx->{org_within_hiding_scope}->($ctx_org);
783 return 1 if $ctx->{pref_ou} and $ctx->{pref_ou} != $ctx_org
784 and !$ctx->{org_within_hiding_scope}->($ctx->{pref_ou});
791 # returns the list of org unit IDs for which the
792 # selected org unit setting returned a true value
793 sub setting_is_true_for_orgs {
794 my ($self, $setting) = @_;
795 my $ctx = $self->ctx;
801 push (@valid_orgs, $org->id) if
802 $ctx->{get_org_setting}->($org->id, $setting);
803 $test_org->($_) for @{$org->children};
806 $test_org->($ctx->{aou_tree}->());