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 OpenSRF::Utils::Logger qw/$logger/;
6 use OpenILS::Utils::CStoreEditor qw/:funcs/;
7 use OpenILS::Utils::Fieldmapper;
8 use OpenILS::Application::AppUtils;
9 use OpenSRF::MultiSession;
10 my $U = 'OpenILS::Application::AppUtils';
12 my $ro_object_subs; # cached subs
13 our %cache = ( # cached data
14 map => {aou => {}}, # others added dynamically as needed
18 eg_cache_hash => undef,
19 search_filter_groups => {}
22 sub init_ro_object_cache {
24 my $e = $self->editor;
27 # reset org unit setting cache on each page load to avoid the
28 # requirement of reloading apache with each org-setting change
29 $cache{org_settings} = {};
32 # subs have been built. insert into the context then move along.
33 $ctx->{$_} = $ro_object_subs->{$_} for keys %$ro_object_subs;
37 # make all "field_safe" classes accesible by default in the template context
39 ($Fieldmapper::fieldmap->{$_}->{field_safe} || '') =~ /true/i
40 } keys %{ $Fieldmapper::fieldmap };
42 for my $class (@classes) {
44 my $hint = $Fieldmapper::fieldmap->{$class}->{hint};
45 next if $hint eq 'aou'; # handled separately
47 my $ident_field = $Fieldmapper::fieldmap->{$class}->{identity};
48 (my $eclass = $class) =~ s/Fieldmapper:://o;
51 my $list_key = "${hint}_list";
52 my $get_key = "get_$hint";
53 my $search_key = "search_$hint";
55 # Retrieve the full set of objects with class $hint
56 $ro_object_subs->{$list_key} = sub {
57 my $method = "retrieve_all_$eclass";
58 $cache{list}{$hint} = $e->$method() unless $cache{list}{$hint};
59 return $cache{list}{$hint};
62 # locate object of class $hint with Ident field $id
63 $cache{map}{$hint} = {};
64 $ro_object_subs->{$get_key} = sub {
66 return $cache{map}{$hint}{$id} if $cache{map}{$hint}{$id};
67 ($cache{map}{$hint}{$id}) = grep { $_->$ident_field eq $id } @{$ro_object_subs->{$list_key}->()};
68 return $cache{map}{$hint}{$id};
71 # search for objects of class $hint where field=value
72 $cache{search}{$hint} = {};
73 $ro_object_subs->{$search_key} = sub {
74 my ($field, $val, $filterfield, $filterval) = @_;
75 my $method = "search_$eclass";
78 $val = [sort(@$val)] if ref $val eq 'ARRAY';
79 $cacheval = OpenSRF::Utils::JSON->perl2JSON($val);
80 #$self->apache->log->info("cacheval : $cacheval");
82 my $search_obj = {$field => $val};
84 $search_obj->{$filterfield} = $filterval;
85 $cacheval .= ':' . $filterfield . ':' . $filterval;
87 $cache{search}{$hint}{$field} = {} unless $cache{search}{$hint}{$field};
88 $cache{search}{$hint}{$field}{$cacheval} = $e->$method($search_obj)
89 unless $cache{search}{$hint}{$field}{$cacheval};
90 return $cache{search}{$hint}{$field}{$cacheval};
94 $ro_object_subs->{aou_tree} = sub {
96 # fetch the org unit tree
97 unless($cache{aou_tree}) {
98 my $tree = $e->search_actor_org_unit([
99 { parent_ou => undef},
101 flesh_fields => {aou => ['children']},
102 order_by => {aou => 'name'}
106 # flesh the org unit type for each org unit
107 # and simultaneously set the id => aou map cache
110 my $ro_object_subs = shift;
111 $node->ou_type( $ro_object_subs->{get_aout}->($node->ou_type) );
112 $cache{map}{aou}{$node->id} = $node;
113 flesh_aout($_, $ro_object_subs) foreach @{$node->children};
115 flesh_aout($tree, $ro_object_subs);
117 $cache{aou_tree} = $tree;
120 return $cache{aou_tree};
123 # Add a special handler for the tree-shaped org unit cache
124 $ro_object_subs->{get_aou} = sub {
126 return undef unless defined $org_id;
127 $ro_object_subs->{aou_tree}->(); # force the org tree to load
128 return $cache{map}{aou}{$org_id};
131 # Returns a flat list of aou objects. often easier to manage than a tree.
132 $ro_object_subs->{aou_list} = sub {
133 $ro_object_subs->{aou_tree}->(); # force the org tree to load
134 return [ values %{$cache{map}{aou}} ];
137 $ro_object_subs->{aouct_tree} = sub {
139 # fetch the org unit tree
140 unless(exists $cache{aouct_tree}) {
141 $cache{aouct_tree} = undef;
143 my $tree_id = $e->search_actor_org_unit_custom_tree(
144 {purpose => 'opac', active => 't'},
149 my $node_tree = $e->search_actor_org_unit_custom_tree_node([
150 {parent_node => undef, tree => $tree_id},
152 flesh_fields => {aouctn => ['children', 'org_unit']},
153 order_by => {aouctn => 'sibling_order'}
157 # tree-ify the org units. note that since the orgs are fleshed
158 # upon retrieval, this org tree will not clobber ctx->{aou_tree}.
159 my @nodes = ($node_tree);
160 while (my $node = shift(@nodes)) {
161 my $aou = $node->org_unit;
163 for my $cnode (@{$node->children}) {
164 my $child_org = $cnode->org_unit;
165 $child_org->parent_ou($aou->id);
166 $child_org->ou_type( $ro_object_subs->{get_aout}->($child_org->ou_type) );
167 push(@{$aou->children}, $child_org);
168 push(@nodes, $cnode);
172 $cache{aouct_tree} = $node_tree->org_unit;
176 return $cache{aouct_tree};
179 # turns an ISO date into something TT can understand
180 $ro_object_subs->{parse_datetime} = sub {
182 $date = DateTime::Format::ISO8601->new->parse_datetime(cleanse_ISO8601($date));
184 "%0.2d:%0.2d:%0.2d %0.2d-%0.2d-%0.4d",
194 # retrieve and cache org unit setting values
195 $ro_object_subs->{get_org_setting} = sub {
196 my($org_id, $setting) = @_;
198 $cache{org_settings}{$org_id} = {}
199 unless $cache{org_settings}{$org_id};
201 $cache{org_settings}{$org_id}{$setting} =
202 $U->ou_ancestor_setting_value($org_id, $setting)
203 unless exists $cache{org_settings}{$org_id}{$setting};
205 return $cache{org_settings}{$org_id}{$setting};
208 $ctx->{$_} = $ro_object_subs->{$_} for keys %$ro_object_subs;
211 sub generic_redirect {
214 my $cookie = shift; # can be an array of cgi.cookie's
216 $self->apache->print(
217 $self->cgi->redirect(
219 $self->cgi->param('redirect_to') ||
220 $self->ctx->{referer} ||
221 $self->ctx->{home_page},
226 return Apache2::Const::REDIRECT;
229 sub get_records_and_facets {
230 my ($self, $rec_ids, $facet_key, $unapi_args) = @_;
233 $unapi_args->{site} ||= $self->ctx->{aou_tree}->()->shortname;
234 $unapi_args->{depth} ||= $self->ctx->{aou_tree}->()->ou_type->depth;
235 $unapi_args->{flesh_depth} ||= 5;
238 my $outer_self = $self;
239 $self->timelog("get_records_and_facets(): about to call multisession");
240 my $ses = OpenSRF::MultiSession->new(
241 app => 'open-ils.cstore',
242 cap => 10, # XXX config
243 success_handler => sub {
244 my($self, $req) = @_;
245 my $data = $req->{response}->[0]->content;
247 $outer_self->timelog("get_records_and_facets(): got response content");
249 # Protect against requests for non-existent records
250 return unless $data->{'unapi.bre'};
252 my $xml = XML::LibXML->new->parse_string($data->{'unapi.bre'})->documentElement;
254 $outer_self->timelog("get_records_and_facets(): parsed xml");
255 # Protect against legacy invalid MARCXML that might not have a 901c
257 my $bre_id_nodes = $xml->find('*[@tag="901"]/*[@code="c"]');
259 $bre_id = $bre_id_nodes->[0]->textContent;
261 $logger->warn("Missing 901 subfield 'c' in " . $xml->toString());
263 push(@data, {id => $bre_id, marc_xml => $xml});
264 $outer_self->timelog("get_records_and_facets(): end of success handler");
268 $self->timelog("get_records_and_facets(): about to call unapi.bre via json_query (rec_ids has " . scalar(@$rec_ids));
271 'open-ils.cstore.json_query',
273 'unapi.bre', $_, 'marcxml','record',
274 $unapi_args->{flesh},
276 $unapi_args->{depth},
277 'acn=>' . $unapi_args->{flesh_depth} . ',acp=>' . $unapi_args->{flesh_depth},
278 undef, undef, $unapi_args->{pref_lib}
283 $self->timelog("get_records_and_facets():almost ready to fetch facets");
284 # collect the facet data
285 my $search = OpenSRF::AppSession->create('open-ils.search');
286 my $facet_req = $search->request(
287 'open-ils.search.facet_cache.retrieve', $facet_key, 10
290 # gather up the unapi recs
291 $ses->session_wait(1);
292 $self->timelog("get_records_and_facets():past session wait");
296 my $tmp_facets = $facet_req->gather(1);
297 $self->timelog("get_records_and_facets(): gathered facet data");
298 for my $cmf_id (keys %$tmp_facets) {
300 # sort highest to lowest match count
302 my $entries = $tmp_facets->{$cmf_id};
303 for my $ent (keys %$entries) {
304 push(@entries, {value => $ent, count => $$entries{$ent}});
306 @entries = sort { $b->{count} <=> $a->{count} } @entries;
307 $facets->{$cmf_id} = {
308 cmf => $self->ctx->{get_cmf}->($cmf_id),
312 $self->timelog("get_records_and_facets(): gathered/sorted facet data");
319 return ($facets, @data);
322 # TODO: blend this code w/ ^-- get_records_and_facets
323 sub fetch_marc_xml_by_id {
324 my ($self, $id_list) = @_;
325 $id_list = [$id_list] unless ref($id_list);
328 no warnings qw/numeric/;
329 $id_list = [map { int $_ } @$id_list];
330 $id_list = [grep { $_ > 0} @$id_list];
333 return {} if scalar(@$id_list) < 1;
335 # I'm just sure there needs to be some more efficient way to get all of
337 my $results = $self->editor->json_query({
338 "select" => {"bre" => ["id", "marc"]},
339 "from" => {"bre" => {}},
340 "where" => {"id" => $id_list}
341 }, {substream => 1}) or return $self->editor->die_event;
344 for my $r (@$results) {
345 $marc_xml->{$r->{"id"}} =
346 (new XML::LibXML)->parse_string($r->{"marc"});
352 sub _get_search_lib {
354 my $ctx = $self->ctx;
356 # avoid duplicate lookups
357 return $ctx->{search_ou} if $ctx->{search_ou};
359 my $loc = $ctx->{copy_location_group_org};
362 # loc param takes precedence
363 $loc = $self->cgi->param('loc');
366 my $pref_lib = $self->_get_pref_lib();
367 return $pref_lib if $pref_lib;
369 return $ctx->{aou_tree}->()->id;
374 my $ctx = $self->ctx;
376 # plib param takes precedence
377 my $plib = $self->cgi->param('plib');
378 return $plib if $plib;
381 # See if the user has a search library preference
382 my $lset = $self->editor->search_actor_user_setting({
383 usr => $ctx->{user}->id,
384 name => 'opac.default_search_location'
386 return OpenSRF::Utils::JSON->JSON2perl($lset->value) if $lset;
388 # Otherwise return the user's home library
389 return $ctx->{user}->home_ou;
392 if ($ctx->{physical_loc}) {
393 return $ctx->{physical_loc};
398 # This is defensively coded since we don't do much manual reading from the
399 # file system in this module.
400 sub load_eg_cache_hash {
403 # just a context helper
404 $self->ctx->{eg_cache_hash} = sub { return $cache{eg_cache_hash}; };
406 # Need to actually load the value? If already done, move on.
407 return if defined $cache{eg_cache_hash};
409 # In this way even if we fail, we won't slow things down by ever trying
410 # again within this Apache process' lifetime.
411 $cache{eg_cache_hash} = 0;
413 my $path = File::Spec->catfile(
414 $self->apache->document_root, "eg_cache_hash"
417 if (not open FH, "<$path") {
418 $self->apache->log->warn("error opening $path : $!");
422 my $rv = read FH, $buf, 64; # defensive
425 if (not defined $rv) { # error
426 $self->apache->log->warn("error reading $path : $!");
427 } elsif ($rv > 0) { # no error, something read
429 $cache{eg_cache_hash} = $buf;
434 # Extracts the copy location org unit and group from the
435 # "logc" param, which takes the form org_id:grp_id.
436 sub extract_copy_location_group_info {
438 my $ctx = $self->ctx;
439 if (my $clump = $self->cgi->param('locg')) {
440 my ($org, $grp) = split(/:/, $clump);
441 $ctx->{copy_location_group_org} = $org;
442 $ctx->{copy_location_group} = $grp if $grp;
446 sub load_copy_location_groups {
448 my $ctx = $self->ctx;
450 # User can access to the search location groups at the current
451 # search lib, the physical location lib, and the patron's home ou.
452 my @ctx_orgs = $ctx->{search_ou};
453 push(@ctx_orgs, $ctx->{physical_loc}) if $ctx->{physical_loc};
454 push(@ctx_orgs, $ctx->{user}->home_ou) if $ctx->{user};
456 my $grps = $self->editor->search_asset_copy_location_group([
463 transform => 'actor.org_unit_full_path',
464 result_field => 'id',
467 where => {id => \@ctx_orgs}
471 {order_by => {acplg => 'pos'}}
475 push(@{$buckets{$_->owner}}, $_) for @$grps;
476 $ctx->{copy_location_groups} = \%buckets;
479 sub set_file_download_headers {
481 my $filename = shift;
482 my $ctype = shift || "text/plain; encoding=utf8";
484 $self->apache->content_type($ctype);
486 $self->apache->headers_out->add(
487 "Content-Disposition",
488 "attachment;filename=$filename"
491 return Apache2::Const::OK;
494 sub apache_log_if_event {
495 my ($self, $event, $prefix_text, $success_ok, $level) = @_;
497 $prefix_text ||= "Evergreen returned event";
502 $prefix_text .= ": ";
504 my $code = $U->event_code($event);
505 if (defined $code and ($code or not $success_ok)) {
506 $self->apache->log->$level(
508 ($event->{textcode} || "") . " ($code)" .
509 ($event->{note} ? (": " . $event->{note}) : "")
517 sub load_search_filter_groups {
520 my $org_list = $U->get_org_ancestors($ctx_org, 1);
523 for my $org_id (@$org_list) {
526 if (! ($grps = $cache{search_filter_groups}{$org_id}) ) {
527 $grps = $self->editor->search_actor_search_filter_group([
536 $cache{search_filter_groups}{$org_id} = $grps;
539 # for the current context, if a descendant org has a group
540 # with a matching code replace the group from the parent.
541 $seen{$_->code} = $_ for @$grps;
544 return $self->ctx->{search_filter_groups} = \%seen;
548 sub check_for_temp_list_warning {
550 my $ctx = $self->ctx;
551 my $cgi = $self->cgi;
553 my $lib = $self->_get_search_lib;
554 my $warn = ($ctx->{get_org_setting}->($lib || 1, 'opac.patron.temporary_list_warn')) ? 1 : 0;
556 if ($warn && $ctx->{user}) {
557 $self->_load_user_with_prefs;
558 my $map = $ctx->{user_setting_map};
559 $warn = 0 if ($$map{'opac.temporary_list_no_warn'});
562 # Check for a cookie disabling the warning.
563 $warn = 0 if ($warn && $cgi->cookie('no_temp_list_warn'));