1 package OpenILS::WWW::EGCatLoader;
2 use strict; use warnings;
3 use Apache2::Const -compile => qw(OK DECLINED FORBIDDEN HTTP_GONE HTTP_INTERNAL_SERVER_ERROR REDIRECT HTTP_BAD_REQUEST HTTP_NOT_FOUND);
4 use OpenSRF::Utils::Logger qw/$logger/;
5 use OpenILS::Utils::CStoreEditor qw/:funcs/;
6 use OpenILS::Utils::Fieldmapper;
7 use OpenILS::Application::AppUtils;
10 my $U = 'OpenILS::Application::AppUtils';
12 our $ac_types = ['toc', 'anotes', 'excerpt', 'summary', 'reviews'];
20 $ctx->{page} = 'record';
22 $self->timelog("load_record() began");
24 my $rec_id = $ctx->{page_args}->[0];
26 return Apache2::Const::HTTP_BAD_REQUEST
27 unless $rec_id and $rec_id =~ /^\d+$/;
29 $self->added_content_stage1($rec_id);
30 $self->timelog("past added content stage 1");
32 my $org = $self->_get_search_lib();
33 my $org_name = $ctx->{get_aou}->($org)->shortname;
34 my $pref_ou = $self->_get_pref_lib();
35 my $depth = $self->cgi->param('depth');
36 $depth = $ctx->{get_aou}->($org)->ou_type->depth
37 unless defined $depth; # can be 0
39 my $copy_depth = $self->cgi->param('copy_depth');
40 $copy_depth = $depth unless defined $copy_depth; # can be 0
41 $self->ctx->{copy_depth} = $copy_depth;
43 my $copy_limit = int($self->cgi->param('copy_limit') || 10);
44 my $copy_offset = int($self->cgi->param('copy_offset') || 0);
46 $self->get_staff_search_settings;
47 if ($ctx->{staff_saved_search_size}) {
48 $ctx->{saved_searches} = ($self->staff_load_searches)[1];
50 $self->timelog("past staff saved searches");
52 $self->fetch_related_search_info($rec_id) unless $kwargs{no_search};
53 $self->timelog("past related search info");
55 # Check for user and load lists and prefs
56 if ($self->ctx->{user}) {
57 $self->_load_lists_and_settings;
58 $self->timelog("load user lists and settings");
61 # run copy retrieval in parallel to bib retrieval
63 my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
64 my $copy_rec = $cstore->request(
65 'open-ils.cstore.json_query.atomic',
66 $self->mk_copy_query($rec_id, $org, $copy_depth, $copy_limit, $copy_offset, $pref_ou)
69 if ($self->cgi->param('badges')) {
70 my $badges = $self->cgi->param('badges');
71 $badges = $badges ? [split(',', $badges)] : [];
72 $badges = [grep { /^\d+$/ } @$badges];
74 $self->ctx->{badge_scores} = $cstore->request(
75 'open-ils.cstore.direct.rating.record_badge_score.search.atomic',
76 { record => $rec_id, badge => $badges },
77 { flesh => 1, flesh_fields => { rrbs => ['badge'] } }
81 $self->ctx->{badge_scores} = [];
84 # find foreign copy data
85 my $peer_rec = $U->simplereq(
87 'open-ils.search.peer_bibs', $rec_id );
89 $ctx->{foreign_copies} = $peer_rec;
91 my (undef, @rec_data) = $self->get_records_and_facets([$rec_id], undef, {
92 flesh => '{holdings_xml,bmp,mra,acp,acnp,acns}',
98 $self->timelog("past get_records_and_facets()");
99 $ctx->{bre_id} = $rec_data[0]->{id};
100 $ctx->{marc_xml} = $rec_data[0]->{marc_xml};
102 $ctx->{copies} = $copy_rec->gather(1);
104 # Add public copy notes to each copy - and while we're in there, grab peer bib records
106 my %cached_bibs = ();
107 foreach my $copy (@{$ctx->{copies}}) {
108 $copy->{notes} = $U->simplereq(
110 'open-ils.circ.copy_note.retrieve.all',
111 {itemid => $copy->{id}, pub => 1 }
113 $self->timelog("past copy note retrieval call");
114 my $meth = 'open-ils.circ.copy_tags.retrieve';
115 $meth .= ".staff" if $ctx->{is_staff};
116 $copy->{tags} = $U->simplereq(
120 ($ctx->{is_staff} ? (authtoken => $ctx->{authtoken}) : ()),
121 copy_id => $copy->{id},
123 depth => $copy_depth,
126 $self->timelog("past copy tag retrieval call");
127 $copy->{peer_bibs} = $U->simplereq(
129 'open-ils.search.multi_home.bib_ids.by_barcode',
132 $self->timelog("past peer bib id retrieval");
134 foreach my $bib (@{$copy->{peer_bibs}}) {
135 next if $bib eq $ctx->{bre_id};
136 next if $cached_bibs{$bib};
137 my (undef, @peer_data) = $self->get_records_and_facets(
144 $cached_bibs{$bib} = 1;
145 #$copy->{peer_bib_marc} = $peer_data[0]->{marc_xml};
146 push @peer_marc, $peer_data[0]->{marc_xml};
147 $self->timelog("fetched peer bib record $bib");
149 $copy->{peer_bib_marc} = \@peer_marc;
152 $self->timelog("past store copy retrieval call");
153 $ctx->{copy_limit} = $copy_limit;
154 $ctx->{copy_offset} = $copy_offset;
156 $ctx->{have_holdings_to_show} = 0;
157 $ctx->{have_mfhd_to_show} = 0;
159 $self->get_hold_copy_summary($rec_id, $org);
161 $self->timelog("past get_hold_copy_summary()");
162 $self->ctx->{bib_is_dead} = OpenILS::Application::AppUtils->is_true(
163 OpenILS::Utils::CStoreEditor->new->json_query({
164 select => { bre => [ 'deleted' ] },
166 where => { 'id' => $rec_id }
172 # Shortcut and help the machines with a 410 Gone status code
173 if ($self->ctx->{bib_is_dead}) {
174 return Apache2::Const::HTTP_GONE;
177 # Shortcut and help the machines with a 404 Not Found status code
178 if (!$ctx->{bre_id}) {
179 return Apache2::Const::HTTP_NOT_FOUND;
182 $ctx->{mfhd_summaries} =
183 $self->get_mfhd_summaries($rec_id, $org, $copy_depth);
186 $ctx->{get_org_setting}->
187 ($org, "opac.fully_compressed_serial_holdings")
189 # We're loading this data here? Are we therefore assuming that we
190 # *are* going to display something in the "issues" expandy?
191 $self->load_serial_holding_summaries($rec_id, $org, $copy_depth);
193 if ($ctx->{mfhd_summaries} && scalar(@{$ctx->{mfhd_summaries}})
195 $ctx->{have_mfhd_to_show} = 1;
199 $self->timelog("past serials holding stuff");
203 $ctx->{marchtml} = $self->mk_marc_html($rec_id);
210 $self->prepare_browse_call_numbers();
214 my @expand = $self->cgi->param('expand');
215 if (grep {$_ eq 'all'} @expand) {
216 $ctx->{expand_all} = 1;
217 $expandies{$_}->() for keys %expandies;
220 for my $exp (@expand) {
221 $ctx->{"expand_$exp"} = 1;
222 $expandies{$exp}->() if exists $expandies{$exp};
226 $self->timelog("past expandies");
228 $self->added_content_stage2($rec_id);
230 $self->timelog("past added content stage 2");
232 # Gather up metarecord info for display
233 # Let's start by getting the metarecord ID
234 my $mmr_id = OpenILS::Utils::CStoreEditor->new->json_query({
235 select => { mmrsm => [ 'metarecord' ] },
237 where => { 'source' => $rec_id }
238 })->[0]->{metarecord};
239 # If this record is apart of a meta group, I want to know more
241 my (undef, @metarecord_data) = $self->get_records_and_facets([$mmr_id], undef, {
242 flesh => '{holdings_xml,mra}',
248 my ($rec) = grep { $_->{mmr_id} == $mmr_id } @metarecord_data;
249 $ctx->{mmr_id} = $mmr_id;
250 $ctx->{mmr_data} = $rec;
252 return Apache2::Const::OK;
255 # collect IDs and info on the search that lead to this details page
256 # If no search query, etc is present, we leave ctx.search_result_index == -1
257 sub fetch_related_search_info {
260 my $ctx = $self->ctx;
261 $ctx->{search_result_index} = -1;
263 $self->load_rresults(internal => 1);
265 my @search_ids = @{$ctx->{ids}};
266 return unless @search_ids;
268 for my $idx (0..$#search_ids) {
269 if ($search_ids[$idx] == $rec_id) {
270 $ctx->{prev_search_record} = $search_ids[$idx - 1] if $idx > 0;
271 $ctx->{next_search_record} = $search_ids[$idx + 1];
272 $ctx->{search_result_index} = $idx;
277 $ctx->{first_search_record} = $search_ids[0];
278 $ctx->{last_search_record} = $search_ids[-1];
287 my $copy_limit = shift;
288 my $copy_offset = shift;
291 my $query = $U->basic_opac_copy_query(
292 $rec_id, undef, undef, $copy_limit, $copy_offset, $self->ctx->{is_staff}
295 if($org != $self->ctx->{aou_tree}->()->id) {
296 # no need to add the org join filter if we're not actually filtering
297 $query->{from}->{acp}->[1] = { aou => {
305 transform => 'actor.org_unit_descendants',
306 result_field => 'id',
310 where => {id => $org}
317 # Unsure if we want these in the shared function, leaving here for now
318 unshift(@{$query->{order_by}},
319 { class => "aou", field => 'id',
320 transform => 'evergreen.rank_ou', params => [$org, $pref_ou]
323 push(@{$query->{order_by}},
324 { class => "acp", field => 'id',
325 transform => 'evergreen.rank_cp'
333 my($self, $rec_id) = @_;
335 # could be optimized considerably by performing the xslt on the already fetched record
336 return $U->simplereq(
338 'open-ils.search.biblio.record.html', $rec_id, 1);
341 sub load_serial_holding_summaries {
342 my ($self, $rec_id, $org, $depth) = @_;
344 my $limit = $self->cgi->param("slimit") || 10;
345 my $offset = $self->cgi->param("soffset") || 0;
347 my $serial = create OpenSRF::AppSession("open-ils.serial");
349 # First, get the tree of /summaries/ of holdings.
350 my $tree = $serial->request(
351 "open-ils.serial.holding_summary_tree.by_bib",
352 $rec_id, $org, $depth, $limit, $offset
355 return if $self->apache_log_if_event(
356 $tree, "getting holding summary tree for record $rec_id"
359 # Next, if requested, get a list of individual holdings under a
360 # particular summary.
362 my $summary_id = int($self->cgi->param("sid") || 0);
363 my $summary_type = $self->cgi->param("stype");
365 if ($summary_id and $summary_type) {
366 my $expand_path = [ $self->cgi->param("sepath") ],
367 my $expand_limit = $self->cgi->param("selimit");
368 my $expand_offsets = [ $self->cgi->param("seoffset") ];
369 my $auto_expand_first = 0;
371 if (not @$expand_offsets) {
372 $expand_offsets = undef;
373 $auto_expand_first = 1;
376 $holdings = $serial->request(
377 "open-ils.serial.holdings.grouped_by_summary",
378 $summary_type, $summary_id,
379 $expand_path, $expand_limit, $expand_offsets,
381 1 + ($self->ctx->{is_staff} ? 1 : 0)
384 if ($holdings and ref $holdings eq "ARRAY") {
385 $self->place_holdings_with_summary(
386 $tree, $holdings, $summary_id, $summary_type
387 ) or $self->apache->log->warn(
388 "could not place holdings within summary tree"
391 $self->apache_log_if_event(
392 $holdings, "getting holdings grouped by summary $summary_id"
399 # The presence of any keys in the tree hash other than 'more' means that we
400 # must have /something/ we could show.
401 $self->ctx->{have_holdings_to_show} = grep { $_ ne 'more' } (keys %$tree);
403 $self->ctx->{holding_summary_tree} = $tree;
406 # This helper to load_serial_holding_summaries() recursively searches in
407 # $tree for a holding summary matching $sid and $stype, and places $holdings
408 # within the node for that summary. IOW, this is about showing expanded
409 # holdings under their "parent" summary.
410 sub place_holdings_with_summary {
411 my ($self, $tree, $holdings, $sid, $stype) = @_;
413 foreach my $sum (@{$tree->{holding_summaries}}) {
414 if ($sum->{id} == $sid and $sum->{summary_type} eq $stype) {
415 $sum->{holdings} = $holdings;
420 foreach my $child (@{$tree->{children}}) {
421 return 1 if $self->place_holdings_with_summary(
422 $child, $holdings, $sid, $stype
429 sub get_mfhd_summaries {
430 my ($self, $rec_id, $org, $depth) = @_;
432 my $serial = create OpenSRF::AppSession("open-ils.search");
433 my $result = $serial->request(
434 "open-ils.search.serial.record.bib.retrieve",
435 $rec_id, $org, $depth
442 sub any_call_number_label {
445 if ($self->ctx->{copies} and @{$self->ctx->{copies}}) {
446 return $self->ctx->{copies}->[0]->{call_number_label};
452 sub prepare_browse_call_numbers {
455 my $cn = ($self->cgi->param("cn") || $self->any_call_number_label) or
458 my $org_unit = $self->ctx->{get_aou}->($self->_get_search_lib()) ||
459 $self->ctx->{aou_tree}->();
461 my $supercat = create OpenSRF::AppSession("open-ils.supercat");
462 my $results = $supercat->request(
463 "open-ils.supercat.call_number.browse",
464 $cn, $org_unit->shortname, 9, $self->cgi->param("cnoffset")
469 $self->ctx->{browsed_call_numbers} = [
472 (new XML::LibXML)->parse_string($_->record->marc)
477 $self->ctx->{browsing_ou} = $org_unit;
480 sub get_hold_copy_summary {
481 my ($self, $rec_id, $org) = @_;
482 my $ctx = $self->ctx;
484 my $search = OpenSRF::AppSession->create('open-ils.search');
485 my $copy_count_meth = 'open-ils.search.biblio.record.copy_count';
486 # We want to include OPAC-invisible copies in a staff context
487 if ($ctx->{is_staff}) {
488 $copy_count_meth .= '.staff';
490 my $req1 = $search->request($copy_count_meth, $org, $rec_id);
492 # if org unit hiding applies, limit the hold count to holds
493 # whose pickup library is within our depth-scoped tree
495 while ($org and $ctx->{org_within_hiding_scope}->($org)) {
496 $count_args->{pickup_lib_descendant} = $org;
497 $org = $ctx->{get_aou}->($org)->parent_ou;
500 $self->ctx->{record_hold_count} = $U->simplereq(
501 'open-ils.circ', 'open-ils.circ.bre.holds.count',
502 $rec_id, $count_args);
504 $self->ctx->{copy_summary} = $req1->recv->content;
509 sub load_print_record {
512 my $rec_id = $self->ctx->{page_args}->[0]
513 or return Apache2::Const::HTTP_BAD_REQUEST;
515 $self->{ctx}->{bre_id} = $rec_id;
516 $self->{ctx}->{printable_record} = $U->simplereq(
518 'open-ils.search.biblio.record.print', $rec_id);
520 return Apache2::Const::OK;
523 sub load_email_record {
526 my $rec_id = $self->ctx->{page_args}->[0]
527 or return Apache2::Const::HTTP_BAD_REQUEST;
529 $self->{ctx}->{bre_id} = $rec_id;
532 'open-ils.search.biblio.record.email',
533 $self->ctx->{authtoken}, $rec_id);
535 return Apache2::Const::OK;
538 # for each type, fire off the reqeust to see if content is available
539 # ctx.added_content.$type.status:
543 sub added_content_stage1 {
546 my $ctx = $self->ctx;
547 my $sel_type = $self->cgi->param('ac') || '';
549 # Connect to this machine's IP address, using the same
550 # Host with which our caller used to connect to us.
551 # This avoids us having to route out of the cluster
552 # and back in to reach the top-level virtualhost.
553 my $ac_addr = $ENV{SERVER_ADDR};
554 # Internal connections are HTTP-only (no HTTPS) and assume the
555 # connection port is '80' unless otherwise specified in the Apache
556 # configuration (e.g. for proxy setups)
557 my $ac_port = $self->apache->dir_config('OILSWebInternalHTTPPort') || 80;
558 my $ac_host = $self->apache->hostname;
561 $logger->info("tpac: added content connecting to $ac_addr:$ac_port / $ac_host");
563 $ctx->{added_content} = {};
564 for my $type (@$ac_types) {
566 $ctx->{added_content}->{$type} = {content => ''};
567 $ctx->{added_content}->{$type}->{status} = 3;
569 $logger->debug("tpac: starting added content request for $rec_id => $type");
571 # Net::HTTP::NB is non-blocking /after/ the initial connect()
572 # Passing Timeout=>1 ensures we wait no longer than 1 second to
573 # connect to the local Evergreen instance (i.e. ourself).
574 # Connecting to oneself should either be very fast (normal)
575 # or very slow (routing problems).
577 my $req = Net::HTTP::NB->new(
578 Host => $ac_addr, Timeout => 1, PeerPort => $ac_port);
580 $logger->warn("Unable to connect to $ac_addr:$ac_port / $ac_host".
581 " for added content lookup for $rec_id: $@");
586 $req->host($self->apache->hostname);
588 my $http_type = ($type eq $sel_type) ? 'GET' : 'HEAD';
589 $req->write_request($http_type => "/opac/extras/ac/$type/html/r/" . $rec_id);
590 $ctx->{added_content}->{$type}->{request} = $req;
594 # check each outstanding request. If it's ready, read the HTTP
595 # status and use it to determine if content is available. Otherwise,
596 # leave the status as unknown.
597 sub added_content_stage2 {
599 my $ctx = $self->ctx;
600 my $sel_type = $self->cgi->param('ac') || '';
602 for my $type (keys %{$ctx->{added_content}}) {
603 my $content = $ctx->{added_content}->{$type};
605 if ($content->{status} == 3) {
606 $logger->debug("tpac: finishing added content request for $type");
608 my $req = $content->{request};
609 my $sel = IO::Select->new($req);
611 # if we are requesting a specific type of content, give the
612 # backend code a little extra time to retrieve the content.
613 my $wait = $type eq $sel_type ? 3 : 0; # TODO: config?
615 if ($sel->can_read($wait)) {
616 my ($code) = $req->read_response_headers;
617 $content->{status} = $code eq '200' ? 1 : 2;
618 $logger->debug("tpac: added content request for $type returned $code");
620 if ($code eq '200' and $type eq $sel_type) {
623 my $n = $req->read_entity_body($buf, 1024);
625 $content->{content} .= $buf;
630 # To avoid a lot of hanging connections.
631 if ($content->{request}) {
632 $content->{request}->shutdown(2);
633 $content->{request}->close();