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
21 sub init_ro_object_cache {
23 my $e = $self->editor;
26 # reset org unit setting cache on each page load to avoid the
27 # requirement of reloading apache with each org-setting change
28 $cache{org_settings} = {};
31 # subs have been built. insert into the context then move along.
32 $ctx->{$_} = $ro_object_subs->{$_} for keys %$ro_object_subs;
36 # make all "field_safe" classes accesible by default in the template context
38 ($Fieldmapper::fieldmap->{$_}->{field_safe} || '') =~ /true/i
39 } keys %{ $Fieldmapper::fieldmap };
41 for my $class (@classes) {
43 my $hint = $Fieldmapper::fieldmap->{$class}->{hint};
44 next if $hint eq 'aou'; # handled separately
46 my $ident_field = $Fieldmapper::fieldmap->{$class}->{identity};
47 (my $eclass = $class) =~ s/Fieldmapper:://o;
50 my $list_key = "${hint}_list";
51 my $get_key = "get_$hint";
52 my $search_key = "search_$hint";
54 # Retrieve the full set of objects with class $hint
55 $ro_object_subs->{$list_key} = sub {
56 my $method = "retrieve_all_$eclass";
57 $cache{list}{$hint} = $e->$method() unless $cache{list}{$hint};
58 return $cache{list}{$hint};
61 # locate object of class $hint with Ident field $id
62 $cache{map}{$hint} = {};
63 $ro_object_subs->{$get_key} = sub {
65 return $cache{map}{$hint}{$id} if $cache{map}{$hint}{$id};
66 ($cache{map}{$hint}{$id}) = grep { $_->$ident_field eq $id } @{$ro_object_subs->{$list_key}->()};
67 return $cache{map}{$hint}{$id};
70 # search for objects of class $hint where field=value
71 $cache{search}{$hint} = {};
72 $ro_object_subs->{$search_key} = sub {
73 my ($field, $val, $filterfield, $filterval) = @_;
74 my $method = "search_$eclass";
77 $val = [sort(@$val)] if ref $val eq 'ARRAY';
78 $cacheval = OpenSRF::Utils::JSON->perl2JSON($val);
79 #$self->apache->log->info("cacheval : $cacheval");
81 my $search_obj = {$field => $val};
83 $search_obj->{$filterfield} = $filterval;
84 $cacheval .= ':' . $filterfield . ':' . $filterval;
86 $cache{search}{$hint}{$field} = {} unless $cache{search}{$hint}{$field};
87 $cache{search}{$hint}{$field}{$cacheval} = $e->$method($search_obj)
88 unless $cache{search}{$hint}{$field}{$cacheval};
89 return $cache{search}{$hint}{$field}{$cacheval};
93 $ro_object_subs->{aou_tree} = sub {
95 # fetch the org unit tree
96 unless($cache{aou_tree}) {
97 my $tree = $e->search_actor_org_unit([
98 { parent_ou => undef},
100 flesh_fields => {aou => ['children']},
101 order_by => {aou => 'name'}
105 # flesh the org unit type for each org unit
106 # and simultaneously set the id => aou map cache
109 my $ro_object_subs = shift;
110 $node->ou_type( $ro_object_subs->{get_aout}->($node->ou_type) );
111 $cache{map}{aou}{$node->id} = $node;
112 flesh_aout($_, $ro_object_subs) foreach @{$node->children};
114 flesh_aout($tree, $ro_object_subs);
116 $cache{aou_tree} = $tree;
119 return $cache{aou_tree};
122 # Add a special handler for the tree-shaped org unit cache
123 $ro_object_subs->{get_aou} = sub {
125 return undef unless defined $org_id;
126 $ro_object_subs->{aou_tree}->(); # force the org tree to load
127 return $cache{map}{aou}{$org_id};
130 # Returns a flat list of aou objects. often easier to manage than a tree.
131 $ro_object_subs->{aou_list} = sub {
132 $ro_object_subs->{aou_tree}->(); # force the org tree to load
133 return [ values %{$cache{map}{aou}} ];
136 $ro_object_subs->{aouct_tree} = sub {
138 # fetch the org unit tree
139 unless(exists $cache{aouct_tree}) {
140 $cache{aouct_tree} = undef;
142 my $tree_id = $e->search_actor_org_unit_custom_tree(
143 {purpose => 'opac', active => 't'},
148 my $node_tree = $e->search_actor_org_unit_custom_tree_node([
149 {parent_node => undef, tree => $tree_id},
151 flesh_fields => {aouctn => ['children', 'org_unit']},
152 order_by => {aouctn => 'sibling_order'}
156 # tree-ify the org units. note that since the orgs are fleshed
157 # upon retrieval, this org tree will not clobber ctx->{aou_tree}.
158 my @nodes = ($node_tree);
159 while (my $node = shift(@nodes)) {
160 my $aou = $node->org_unit;
162 for my $cnode (@{$node->children}) {
163 my $child_org = $cnode->org_unit;
164 $child_org->parent_ou($aou->id);
165 $child_org->ou_type( $ro_object_subs->{get_aout}->($child_org->ou_type) );
166 push(@{$aou->children}, $child_org);
167 push(@nodes, $cnode);
171 $cache{aouct_tree} = $node_tree->org_unit;
175 return $cache{aouct_tree};
178 # turns an ISO date into something TT can understand
179 $ro_object_subs->{parse_datetime} = sub {
181 $date = DateTime::Format::ISO8601->new->parse_datetime(cleanse_ISO8601($date));
183 "%0.2d:%0.2d:%0.2d %0.2d-%0.2d-%0.4d",
193 # retrieve and cache org unit setting values
194 $ro_object_subs->{get_org_setting} = sub {
195 my($org_id, $setting) = @_;
197 $cache{org_settings}{$org_id} = {}
198 unless $cache{org_settings}{$org_id};
200 $cache{org_settings}{$org_id}{$setting} =
201 $U->ou_ancestor_setting_value($org_id, $setting)
202 unless exists $cache{org_settings}{$org_id}{$setting};
204 return $cache{org_settings}{$org_id}{$setting};
207 $ctx->{$_} = $ro_object_subs->{$_} for keys %$ro_object_subs;
210 sub generic_redirect {
213 my $cookie = shift; # can be an array of cgi.cookie's
215 $self->apache->print(
216 $self->cgi->redirect(
218 $self->cgi->param('redirect_to') ||
219 $self->ctx->{referer} ||
220 $self->ctx->{home_page},
225 return Apache2::Const::REDIRECT;
228 sub get_records_and_facets {
229 my ($self, $rec_ids, $facet_key, $unapi_args) = @_;
232 $unapi_args->{site} ||= $self->ctx->{aou_tree}->()->shortname;
233 $unapi_args->{depth} ||= $self->ctx->{aou_tree}->()->ou_type->depth;
234 $unapi_args->{flesh_depth} ||= 5;
237 my $outer_self = $self;
238 $self->timelog("get_records_and_facets(): about to call multisession");
239 my $ses = OpenSRF::MultiSession->new(
240 app => 'open-ils.cstore',
241 cap => 10, # XXX config
242 success_handler => sub {
243 my($self, $req) = @_;
244 my $data = $req->{response}->[0]->content;
246 $outer_self->timelog("get_records_and_facets(): got response content");
248 # Protect against requests for non-existent records
249 return unless $data->{'unapi.bre'};
251 my $xml = XML::LibXML->new->parse_string($data->{'unapi.bre'})->documentElement;
253 $outer_self->timelog("get_records_and_facets(): parsed xml");
254 # Protect against legacy invalid MARCXML that might not have a 901c
256 my $bre_id_nodes = $xml->find('*[@tag="901"]/*[@code="c"]');
258 $bre_id = $bre_id_nodes->[0]->textContent;
260 $logger->warn("Missing 901 subfield 'c' in " . $xml->toString());
262 push(@data, {id => $bre_id, marc_xml => $xml});
263 $outer_self->timelog("get_records_and_facets(): end of success handler");
267 $self->timelog("get_records_and_facets(): about to call unapi.bre via json_query (rec_ids has " . scalar(@$rec_ids));
270 'open-ils.cstore.json_query',
272 'unapi.bre', $_, 'marcxml','record',
273 $unapi_args->{flesh},
275 $unapi_args->{depth},
276 'acn=>' . $unapi_args->{flesh_depth} . ',acp=>' . $unapi_args->{flesh_depth},
277 undef, undef, $unapi_args->{pref_lib}
282 $self->timelog("get_records_and_facets():almost ready to fetch facets");
283 # collect the facet data
284 my $search = OpenSRF::AppSession->create('open-ils.search');
285 my $facet_req = $search->request(
286 'open-ils.search.facet_cache.retrieve', $facet_key, 10
289 # gather up the unapi recs
290 $ses->session_wait(1);
291 $self->timelog("get_records_and_facets():past session wait");
295 my $tmp_facets = $facet_req->gather(1);
296 $self->timelog("get_records_and_facets(): gathered facet data");
297 for my $cmf_id (keys %$tmp_facets) {
299 # sort highest to lowest match count
301 my $entries = $tmp_facets->{$cmf_id};
302 for my $ent (keys %$entries) {
303 push(@entries, {value => $ent, count => $$entries{$ent}});
305 @entries = sort { $b->{count} <=> $a->{count} } @entries;
306 $facets->{$cmf_id} = {
307 cmf => $self->ctx->{get_cmf}->($cmf_id),
311 $self->timelog("get_records_and_facets(): gathered/sorted facet data");
318 return ($facets, @data);
321 # TODO: blend this code w/ ^-- get_records_and_facets
322 sub fetch_marc_xml_by_id {
323 my ($self, $id_list) = @_;
324 $id_list = [$id_list] unless ref($id_list);
327 no warnings qw/numeric/;
328 $id_list = [map { int $_ } @$id_list];
329 $id_list = [grep { $_ > 0} @$id_list];
332 return {} if scalar(@$id_list) < 1;
334 # I'm just sure there needs to be some more efficient way to get all of
336 my $results = $self->editor->json_query({
337 "select" => {"bre" => ["id", "marc"]},
338 "from" => {"bre" => {}},
339 "where" => {"id" => $id_list}
340 }, {substream => 1}) or return $self->editor->die_event;
343 for my $r (@$results) {
344 $marc_xml->{$r->{"id"}} =
345 (new XML::LibXML)->parse_string($r->{"marc"});
351 sub _get_search_lib {
353 my $ctx = $self->ctx;
355 # avoid duplicate lookups
356 return $ctx->{search_ou} if $ctx->{search_ou};
358 my $loc = $ctx->{copy_location_group_org};
361 # loc param takes precedence
362 $loc = $self->cgi->param('loc');
365 my $pref_lib = $self->_get_pref_lib();
366 return $pref_lib if $pref_lib;
368 return $ctx->{aou_tree}->()->id;
373 my $ctx = $self->ctx;
375 # plib param takes precedence
376 my $plib = $self->cgi->param('plib');
377 return $plib if $plib;
380 # See if the user has a search library preference
381 my $lset = $self->editor->search_actor_user_setting({
382 usr => $ctx->{user}->id,
383 name => 'opac.default_search_location'
385 return OpenSRF::Utils::JSON->JSON2perl($lset->value) if $lset;
387 # Otherwise return the user's home library
388 return $ctx->{user}->home_ou;
391 if ($self->cgi->param('physical_loc')) {
392 return $self->cgi->param('physical_loc');
397 # This is defensively coded since we don't do much manual reading from the
398 # file system in this module.
399 sub load_eg_cache_hash {
402 # just a context helper
403 $self->ctx->{eg_cache_hash} = sub { return $cache{eg_cache_hash}; };
405 # Need to actually load the value? If already done, move on.
406 return if defined $cache{eg_cache_hash};
408 # In this way even if we fail, we won't slow things down by ever trying
409 # again within this Apache process' lifetime.
410 $cache{eg_cache_hash} = 0;
412 my $path = File::Spec->catfile(
413 $self->apache->document_root, "eg_cache_hash"
416 if (not open FH, "<$path") {
417 $self->apache->log->warn("error opening $path : $!");
421 my $rv = read FH, $buf, 64; # defensive
424 if (not defined $rv) { # error
425 $self->apache->log->warn("error reading $path : $!");
426 } elsif ($rv > 0) { # no error, something read
428 $cache{eg_cache_hash} = $buf;
433 # Extracts the copy location org unit and group from the
434 # "logc" param, which takes the form org_id:grp_id.
435 sub extract_copy_location_group_info {
437 my $ctx = $self->ctx;
438 if (my $clump = $self->cgi->param('locg')) {
439 my ($org, $grp) = split(/:/, $clump);
440 $ctx->{copy_location_group_org} = $org;
441 $ctx->{copy_location_group} = $grp if $grp;
445 sub load_copy_location_groups {
447 my $ctx = $self->ctx;
449 # User can access to the search location groups at the current
450 # search lib, the physical location lib, and the patron's home ou.
451 my @ctx_orgs = $ctx->{search_ou};
452 push(@ctx_orgs, $ctx->{physical_loc}) if $ctx->{physical_loc};
453 push(@ctx_orgs, $ctx->{user}->home_ou) if $ctx->{user};
455 my $grps = $self->editor->search_asset_copy_location_group([
462 transform => 'actor.org_unit_full_path',
463 result_field => 'id',
466 where => {id => \@ctx_orgs}
470 {order_by => {acplg => 'pos'}}
474 push(@{$buckets{$_->owner}}, $_) for @$grps;
475 $ctx->{copy_location_groups} = \%buckets;
478 sub set_file_download_headers {
480 my $filename = shift;
481 my $ctype = shift || "text/plain; encoding=utf8";
483 $self->apache->content_type($ctype);
485 $self->apache->headers_out->add(
486 "Content-Disposition",
487 "attachment;filename=$filename"
490 return Apache2::Const::OK;
493 sub apache_log_if_event {
494 my ($self, $event, $prefix_text, $success_ok, $level) = @_;
496 $prefix_text ||= "Evergreen returned event";
501 $prefix_text .= ": ";
503 my $code = $U->event_code($event);
504 if (defined $code and ($code or not $success_ok)) {
505 $self->apache->log->$level(
507 ($event->{textcode} || "") . " ($code)" .
508 ($event->{note} ? (": " . $event->{note}) : "")