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';
21 $ctx->{readonly} = $self->cgi->param('readonly');
23 $self->timelog("load_record() began");
25 my $rec_id = $ctx->{page_args}->[0];
27 return Apache2::Const::HTTP_BAD_REQUEST
28 unless $rec_id and $rec_id =~ /^\d+$/;
30 $self->added_content_stage1($rec_id);
31 $self->timelog("past added content stage 1");
33 my $org = $self->_get_search_lib();
34 my $org_name = $ctx->{get_aou}->($org)->shortname;
35 my $pref_ou = $self->_get_pref_lib();
36 my $depth = $self->cgi->param('depth');
37 $depth = $ctx->{get_aou}->($org)->ou_type->depth
38 unless defined $depth; # can be 0
40 my $copy_depth = $self->cgi->param('copy_depth');
41 $copy_depth = $depth unless defined $copy_depth; # can be 0
42 $self->ctx->{copy_depth} = $copy_depth;
44 my $copy_limit = int($self->cgi->param('copy_limit') || 10);
45 my $copy_offset = int($self->cgi->param('copy_offset') || 0);
47 $self->get_staff_search_settings;
48 if ($ctx->{staff_saved_search_size}) {
49 $ctx->{saved_searches} = ($self->staff_load_searches)[1];
51 $self->timelog("past staff saved searches");
53 $self->fetch_related_search_info($rec_id) unless $kwargs{no_search};
54 $self->timelog("past related search info");
56 # Check for user and load lists and prefs
57 if ($self->ctx->{user}) {
58 $self->_load_lists_and_settings;
59 $self->timelog("load user lists and settings");
62 # run copy retrieval in parallel to bib retrieval
64 my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
65 my $copy_rec = $cstore->request(
66 'open-ils.cstore.json_query.atomic',
67 $self->mk_copy_query($rec_id, $org, $copy_depth, $copy_limit, $copy_offset, $pref_ou)
70 if ($self->cgi->param('badges')) {
71 my $badges = $self->cgi->param('badges');
72 $badges = $badges ? [split(',', $badges)] : [];
73 $badges = [grep { /^\d+$/ } @$badges];
75 $self->ctx->{badge_scores} = $cstore->request(
76 'open-ils.cstore.direct.rating.record_badge_score.search.atomic',
77 { record => $rec_id, badge => $badges },
78 { flesh => 1, flesh_fields => { rrbs => ['badge'] } }
82 $self->ctx->{badge_scores} = [];
85 # find foreign copy data
86 my $peer_rec = $U->simplereq(
88 'open-ils.search.peer_bibs', $rec_id );
90 $ctx->{foreign_copies} = $peer_rec;
92 my (undef, @rec_data) = $self->get_records_and_facets([$rec_id], undef, {
93 flesh => '{holdings_xml,bmp,mra,acp,acnp,acns}',
99 $self->timelog("past get_records_and_facets()");
100 $ctx->{bre_id} = $rec_data[0]->{id};
101 $ctx->{marc_xml} = $rec_data[0]->{marc_xml};
103 $ctx->{copies} = $copy_rec->gather(1);
105 $ctx->{course_module_opt_in} = 0;
106 if ($ctx->{get_org_setting}->($org, "circ.course_materials_opt_in")) {
107 $ctx->{course_module_opt_in} = 1;
110 # Add public copy notes to each copy - and while we're in there, grab peer bib records
111 # and copy tags. Oh and if we're working with course materials, those too.
112 my %cached_bibs = ();
113 foreach my $copy (@{$ctx->{copies}}) {
114 $copy->{notes} = $U->simplereq(
116 'open-ils.circ.copy_note.retrieve.all',
117 {itemid => $copy->{id}, pub => 1 }
119 if ($ctx->{course_module_opt_in}) {
120 $copy->{course_materials} = $U->simplereq(
122 'open-ils.courses.course_materials.retrieve.atomic',
123 {item => $copy->{id}}
126 for my $material (@{$copy->{course_materials}}) {
127 $course_ids{$material->course} = 1;
130 $copy->{courses} = $U->simplereq(
132 'open-ils.courses.courses.retrieve',
136 $self->timelog("past copy note retrieval call");
137 my $meth = 'open-ils.circ.copy_tags.retrieve';
138 $meth .= ".staff" if $ctx->{is_staff};
139 $copy->{tags} = $U->simplereq(
143 ($ctx->{is_staff} ? (authtoken => $ctx->{authtoken}) : ()),
144 copy_id => $copy->{id},
146 depth => $copy_depth,
149 $self->timelog("past copy tag retrieval call");
150 $copy->{peer_bibs} = $U->simplereq(
152 'open-ils.search.multi_home.bib_ids.by_barcode',
155 $self->timelog("past peer bib id retrieval");
157 foreach my $bib (@{$copy->{peer_bibs}}) {
158 next if $bib eq $ctx->{bre_id};
159 next if $cached_bibs{$bib};
160 my (undef, @peer_data) = $self->get_records_and_facets(
167 $cached_bibs{$bib} = 1;
168 #$copy->{peer_bib_marc} = $peer_data[0]->{marc_xml};
169 push @peer_marc, $peer_data[0]->{marc_xml};
170 $self->timelog("fetched peer bib record $bib");
172 $copy->{peer_bib_marc} = \@peer_marc;
175 $self->timelog("past store copy retrieval call");
176 $ctx->{copy_limit} = $copy_limit;
177 $ctx->{copy_offset} = $copy_offset;
179 $ctx->{have_holdings_to_show} = 0;
180 $ctx->{have_mfhd_to_show} = 0;
182 $self->get_hold_copy_summary($rec_id, $org);
184 $self->timelog("past get_hold_copy_summary()");
185 $self->ctx->{bib_is_dead} = OpenILS::Application::AppUtils->is_true(
186 OpenILS::Utils::CStoreEditor->new->json_query({
187 select => { bre => [ 'deleted' ] },
189 where => { 'id' => $rec_id }
195 # Shortcut and help the machines with a 410 Gone status code
196 if ($self->ctx->{bib_is_dead}) {
197 return Apache2::Const::HTTP_GONE;
200 # Shortcut and help the machines with a 404 Not Found status code
201 if (!$ctx->{bre_id}) {
202 return Apache2::Const::HTTP_NOT_FOUND;
205 $ctx->{mfhd_summaries} =
206 $self->get_mfhd_summaries($rec_id, $org, $copy_depth);
209 $ctx->{get_org_setting}->
210 ($org, "opac.fully_compressed_serial_holdings")
212 # We're loading this data here? Are we therefore assuming that we
213 # *are* going to display something in the "issues" expandy?
214 $self->load_serial_holding_summaries($rec_id, $org, $copy_depth);
216 if ($ctx->{mfhd_summaries} && scalar(@{$ctx->{mfhd_summaries}})
218 $ctx->{have_mfhd_to_show} = 1;
222 $self->timelog("past serials holding stuff");
226 $ctx->{marchtml} = $self->mk_marc_html($rec_id);
233 $self->prepare_browse_call_numbers();
237 my @expand = $self->cgi->param('expand');
238 if (grep {$_ eq 'all'} @expand) {
239 $ctx->{expand_all} = 1;
240 $expandies{$_}->() for keys %expandies;
243 for my $exp (@expand) {
244 $ctx->{"expand_$exp"} = 1;
245 $expandies{$exp}->() if exists $expandies{$exp};
249 $self->timelog("past expandies");
251 $self->added_content_stage2($rec_id);
253 $self->timelog("past added content stage 2");
255 # Gather up metarecord info for display
256 # Let's start by getting the metarecord ID
257 my $mmr_id = OpenILS::Utils::CStoreEditor->new->json_query({
258 select => { mmrsm => [ 'metarecord' ] },
260 where => { 'source' => $rec_id }
261 })->[0]->{metarecord};
262 # If this record is apart of a meta group, I want to know more
264 my (undef, @metarecord_data) = $self->get_records_and_facets([$mmr_id], undef, {
265 flesh => '{holdings_xml,mra}',
271 my ($rec) = grep { $_->{mmr_id} == $mmr_id } @metarecord_data;
272 $ctx->{mmr_id} = $mmr_id;
273 $ctx->{mmr_data} = $rec;
275 return Apache2::Const::OK;
278 # collect IDs and info on the search that lead to this details page
279 # If no search query, etc is present, we leave ctx.search_result_index == -1
280 sub fetch_related_search_info {
283 my $ctx = $self->ctx;
284 $ctx->{search_result_index} = -1;
286 $self->load_rresults(internal => 1);
288 my @search_ids = @{$ctx->{ids}};
289 return unless @search_ids;
291 for my $idx (0..$#search_ids) {
292 if ($search_ids[$idx] == $rec_id) {
293 $ctx->{prev_search_record} = $search_ids[$idx - 1] if $idx > 0;
294 $ctx->{next_search_record} = $search_ids[$idx + 1];
295 $ctx->{search_result_index} = $idx;
300 $ctx->{first_search_record} = $search_ids[0];
301 $ctx->{last_search_record} = $search_ids[-1];
310 my $copy_limit = shift;
311 my $copy_offset = shift;
314 my $query = $U->basic_opac_copy_query(
315 $rec_id, undef, undef, $copy_limit, $copy_offset, $self->ctx->{is_staff}
318 my $lasso_orgs = $self->search_lasso_orgs;
320 if($lasso_orgs || $org != $self->ctx->{aou_tree}->()->id) {
321 # no need to add the org join filter if we're not actually filtering
323 my $filter_orgs = $lasso_orgs || $org;
324 $query->{from}->{acp}->[1] = { aou => {
332 transform => 'actor.org_unit_descendants',
333 result_field => 'id',
337 where => {id => $filter_orgs}
344 # Unsure if we want these in the shared function, leaving here for now
345 unshift(@{$query->{order_by}},
346 { class => "aou", field => 'id',
347 transform => 'evergreen.rank_ou', params => [$org, $pref_ou]
350 push(@{$query->{order_by}},
351 { class => "acp", field => 'id',
352 transform => 'evergreen.rank_cp'
360 my($self, $rec_id) = @_;
362 # could be optimized considerably by performing the xslt on the already fetched record
363 return $U->simplereq(
365 'open-ils.search.biblio.record.html', $rec_id, 1);
368 sub load_serial_holding_summaries {
369 my ($self, $rec_id, $org, $depth) = @_;
371 my $limit = $self->cgi->param("slimit") || 10;
372 my $offset = $self->cgi->param("soffset") || 0;
374 my $serial = create OpenSRF::AppSession("open-ils.serial");
376 # First, get the tree of /summaries/ of holdings.
377 my $tree = $serial->request(
378 "open-ils.serial.holding_summary_tree.by_bib",
379 $rec_id, $org, $depth, $limit, $offset
382 return if $self->apache_log_if_event(
383 $tree, "getting holding summary tree for record $rec_id"
386 # Next, if requested, get a list of individual holdings under a
387 # particular summary.
389 my $summary_id = int($self->cgi->param("sid") || 0);
390 my $summary_type = $self->cgi->param("stype");
392 if ($summary_id and $summary_type) {
393 my $expand_path = [ $self->cgi->param("sepath") ],
394 my $expand_limit = $self->cgi->param("selimit");
395 my $expand_offsets = [ $self->cgi->param("seoffset") ];
396 my $auto_expand_first = 0;
398 if (not @$expand_offsets) {
399 $expand_offsets = undef;
400 $auto_expand_first = 1;
403 $holdings = $serial->request(
404 "open-ils.serial.holdings.grouped_by_summary",
405 $summary_type, $summary_id,
406 $expand_path, $expand_limit, $expand_offsets,
408 1 + ($self->ctx->{is_staff} ? 1 : 0)
411 if ($holdings and ref $holdings eq "ARRAY") {
412 $self->place_holdings_with_summary(
413 $tree, $holdings, $summary_id, $summary_type
414 ) or $self->apache->log->warn(
415 "could not place holdings within summary tree"
418 $self->apache_log_if_event(
419 $holdings, "getting holdings grouped by summary $summary_id"
426 # The presence of any keys in the tree hash other than 'more' means that we
427 # must have /something/ we could show.
428 $self->ctx->{have_holdings_to_show} = grep { $_ ne 'more' } (keys %$tree);
430 $self->ctx->{holding_summary_tree} = $tree;
433 # This helper to load_serial_holding_summaries() recursively searches in
434 # $tree for a holding summary matching $sid and $stype, and places $holdings
435 # within the node for that summary. IOW, this is about showing expanded
436 # holdings under their "parent" summary.
437 sub place_holdings_with_summary {
438 my ($self, $tree, $holdings, $sid, $stype) = @_;
440 foreach my $sum (@{$tree->{holding_summaries}}) {
441 if ($sum->{id} == $sid and $sum->{summary_type} eq $stype) {
442 $sum->{holdings} = $holdings;
447 foreach my $child (@{$tree->{children}}) {
448 return 1 if $self->place_holdings_with_summary(
449 $child, $holdings, $sid, $stype
456 sub get_mfhd_summaries {
457 my ($self, $rec_id, $org, $depth) = @_;
459 my $serial = create OpenSRF::AppSession("open-ils.search");
460 my $result = $serial->request(
461 "open-ils.search.serial.record.bib.retrieve",
462 $rec_id, $org, $depth
469 sub any_call_number_label {
472 if ($self->ctx->{copies} and @{$self->ctx->{copies}}) {
473 return $self->ctx->{copies}->[0]->{call_number_label};
479 sub prepare_browse_call_numbers {
482 my $cn = ($self->cgi->param("cn") || $self->any_call_number_label) or
485 my $org_unit = $self->ctx->{get_aou}->($self->_get_search_lib()) ||
486 $self->ctx->{aou_tree}->();
488 my $supercat = create OpenSRF::AppSession("open-ils.supercat");
489 my $results = $supercat->request(
490 "open-ils.supercat.call_number.browse",
491 $cn, $org_unit->shortname, 9, $self->cgi->param("cnoffset")
496 $self->ctx->{browsed_call_numbers} = [
499 (new XML::LibXML)->parse_string($_->record->marc)
504 $self->ctx->{browsing_ou} = $org_unit;
507 sub get_hold_copy_summary {
508 my ($self, $rec_id, $org) = @_;
509 my $ctx = $self->ctx;
511 my $search = OpenSRF::AppSession->create('open-ils.search');
512 my $copy_count_meth = 'open-ils.search.biblio.record.copy_count';
513 # We want to include OPAC-invisible copies in a staff context
514 if ($ctx->{is_staff}) {
515 $copy_count_meth .= '.staff';
517 my $req1 = $search->request($copy_count_meth, $org, $rec_id);
519 # if org unit hiding applies, limit the hold count to holds
520 # whose pickup library is within our depth-scoped tree
522 while ($org and $ctx->{org_within_hiding_scope}->($org)) {
523 $count_args->{pickup_lib_descendant} = $org;
524 $org = $ctx->{get_aou}->($org)->parent_ou;
527 $self->ctx->{record_hold_count} = $U->simplereq(
528 'open-ils.circ', 'open-ils.circ.bre.holds.count',
529 $rec_id, $count_args);
531 $self->ctx->{copy_summary} = $req1->recv->content;
536 sub load_print_or_email_preview {
539 my $captcha_pass = shift;
541 my $ctx = $self->ctx;
542 my $e = new_editor(xact => 1);
543 my $old_event = $self->cgi->param('old_event');
545 $old_event = $e->retrieve_action_trigger_event([
547 {flesh => 1, flesh_fields => { atev => ['template_output'] }}
549 $e->delete_action_trigger_event($old_event) if ($old_event);
550 $e->delete_action_trigger_event_output($old_event->template_output) if ($old_event && $old_event->template_output);
554 my $rec_or_list_id = $ctx->{page_args}->[0]
555 or return Apache2::Const::HTTP_BAD_REQUEST;
557 $ctx->{bre_id} = $rec_or_list_id;
559 my $is_list = $ctx->{is_list} = $self->cgi->param('is_list');
563 $list = $U->simplereq(
565 'open-ils.actor.anon_cache.get_value',
566 $rec_or_list_id, (ref $self)->CART_CACHE_MYLIST);
573 no warnings qw/numeric/;
574 $list = [map { int $_ } @$list];
575 $list = [grep { $_ > 0} @$list];
578 $list = $rec_or_list_id;
579 $ctx->{bre_id} = $rec_or_list_id;
582 $ctx->{sortable} = (ref($list) && @$list > 1);
584 my $group = $type eq 'print' ? 1 : 2;
586 $ctx->{formats} = $self->editor->search_action_trigger_event_def_group_member([{grp => $group},{order_by => { atevdefgm => 'name'}}]);
587 $ctx->{format} = $self->cgi->param('format') || $ctx->{formats}[0]->id;
588 if ($type eq 'email') {
589 $ctx->{email} = $self->cgi->param('email') || ($ctx->{user} ? $ctx->{user}->email : '');
590 $ctx->{subject} = $self->cgi->param('subject');
593 my $context_org = $self->cgi->param('context_org');
595 $context_org = $self->ctx->{get_aou}->($context_org);
599 $context_org = $self->ctx->{get_aou}->($self->_get_search_lib()) ||
600 $self->ctx->{aou_tree}->();
603 $ctx->{context_org} = $context_org->id;
605 my ($incoming_sort,$sort_dir) = $self->_get_bookbag_sort_params('sort');
606 $sort_dir = $self->cgi->param('sort_dir') if $self->cgi->param('sort_dir');
607 if (!$incoming_sort) {
608 ($incoming_sort,$sort_dir) = $self->_get_bookbag_sort_params('anonsort');
610 if (!$incoming_sort) {
611 $incoming_sort = 'author';
614 $incoming_sort =~ s/sort.*$//;
616 $incoming_sort = 'author'
617 unless (grep {$_ eq $incoming_sort} qw/title author pubdate/);
619 $ctx->{sort} = $incoming_sort;
620 $ctx->{sort_dir} = $sort_dir;
622 my $method = "open-ils.search.biblio.record.$type.preview";
634 unshift(@args, $ctx->{authtoken}) if ($type eq 'email');
636 $ctx->{preview_record} = $U->simplereq(
637 'open-ils.search', $method, @args);
639 $ctx->{'redirect_to'} = $self->cgi->param('redirect_to') || $self->cgi->referer;
641 return Apache2::Const::OK;
644 sub load_print_record {
647 my $event_id = $self->ctx->{page_args}->[0]
648 or return Apache2::Const::HTTP_BAD_REQUEST;
650 my $event = $self->editor->retrieve_action_trigger_event([
652 {flesh => 1, flesh_fields => { atev => ['template_output'] }}
655 return Apache2::Const::HTTP_BAD_REQUEST
656 unless ($event and $event->template_output and $event->template_output->data);
658 $self->ctx->{bre_id} = $self->cgi->param('bre_id');
659 $self->ctx->{is_list} = $self->cgi->param('is_list');
660 $self->ctx->{print_data} = $event->template_output->data;
662 if ($self->cgi->param('clear_cart')) {
663 $self->clear_anon_cache;
665 $self->ctx->{'redirect_to'} = $self->cgi->param('redirect_to');
667 return Apache2::Const::OK;
670 sub load_email_record {
672 my $captcha_pass = shift;
674 my $event_id = $self->ctx->{page_args}->[0]
675 or return Apache2::Const::HTTP_BAD_REQUEST;
677 my $e = new_editor(xact => 1, authtoken => $self->ctx->{authtoken});
678 return Apache2::Const::HTTP_BAD_REQUEST
679 unless $captcha_pass || $e->checkauth;
681 my $event = $e->retrieve_action_trigger_event([
683 {flesh => 1, flesh_fields => { atev => ['template_output'] }}
686 return Apache2::Const::HTTP_BAD_REQUEST
687 unless ($event and $event->template_output and $event->template_output->data);
689 $self->ctx->{email} = $self->cgi->param('email');
690 $self->ctx->{subject} = $self->cgi->param('subject');
691 $self->ctx->{bre_id} = $self->cgi->param('bre_id');
692 $self->ctx->{is_list} = $self->cgi->param('is_list');
693 $self->ctx->{print_data} = $event->template_output->data;
697 'open-ils.search.biblio.record.email.send_output',
698 $self->ctx->{authtoken}, $event_id,
699 $self->ctx->{cap}->{key}, $self->ctx->{cap_answer});
701 # Move the output to async so it can't be used in a resend attack
702 $event->async_output($event->template_output->id);
703 $event->clear_template_output;
704 $e->update_action_trigger_event($event);
707 if ($self->cgi->param('clear_cart')) {
708 $self->clear_anon_cache;
710 $self->ctx->{'redirect_to'} = $self->cgi->param('redirect_to');
712 return Apache2::Const::OK;
715 # for each type, fire off the reqeust to see if content is available
716 # ctx.added_content.$type.status:
720 sub added_content_stage1 {
723 my $ctx = $self->ctx;
724 my $sel_type = $self->cgi->param('ac') || '';
726 # Connect to this machine's IP address, using the same
727 # Host with which our caller used to connect to us.
728 # This avoids us having to route out of the cluster
729 # and back in to reach the top-level virtualhost.
730 my $ac_addr = $ENV{SERVER_ADDR};
731 # Internal connections are HTTP-only (no HTTPS) and assume the
732 # connection port is '80' unless otherwise specified in the Apache
733 # configuration (e.g. for proxy setups)
734 my $ac_port = $self->apache->dir_config('OILSWebInternalHTTPPort') || 80;
735 my $ac_host = $self->apache->hostname;
738 $logger->info("tpac: added content connecting to $ac_addr:$ac_port / $ac_host");
740 $ctx->{added_content} = {};
741 for my $type (@$ac_types) {
743 $ctx->{added_content}->{$type} = {content => ''};
744 $ctx->{added_content}->{$type}->{status} = 3;
746 $logger->debug("tpac: starting added content request for $rec_id => $type");
748 # Net::HTTP::NB is non-blocking /after/ the initial connect()
749 # Passing Timeout=>1 ensures we wait no longer than 1 second to
750 # connect to the local Evergreen instance (i.e. ourself).
751 # Connecting to oneself should either be very fast (normal)
752 # or very slow (routing problems).
754 my $req = Net::HTTP::NB->new(
755 Host => $ac_addr, Timeout => 1, PeerPort => $ac_port);
757 $logger->warn("Unable to connect to $ac_addr:$ac_port / $ac_host".
758 " for added content lookup for $rec_id: $@");
763 $req->host($self->apache->hostname);
765 my $http_type = ($type eq $sel_type) ? 'GET' : 'HEAD';
766 $req->write_request($http_type => "/opac/extras/ac/$type/html/r/" . $rec_id);
767 $ctx->{added_content}->{$type}->{request} = $req;
771 # check each outstanding request. If it's ready, read the HTTP
772 # status and use it to determine if content is available. Otherwise,
773 # leave the status as unknown.
774 sub added_content_stage2 {
776 my $ctx = $self->ctx;
777 my $sel_type = $self->cgi->param('ac') || '';
779 for my $type (keys %{$ctx->{added_content}}) {
780 my $content = $ctx->{added_content}->{$type};
782 if ($content->{status} == 3) {
783 $logger->debug("tpac: finishing added content request for $type");
785 my $req = $content->{request};
786 my $sel = IO::Select->new($req);
788 # if we are requesting a specific type of content, give the
789 # backend code a little extra time to retrieve the content.
790 my $wait = $type eq $sel_type ? 3 : 0; # TODO: config?
792 if ($sel->can_read($wait)) {
793 my ($code) = $req->read_response_headers;
794 $content->{status} = $code eq '200' ? 1 : 2;
795 $logger->debug("tpac: added content request for $type returned $code");
797 if ($code eq '200' and $type eq $sel_type) {
800 my $n = $req->read_entity_body($buf, 1024);
802 $content->{content} .= $buf;
807 # To avoid a lot of hanging connections.
808 if ($content->{request}) {
809 $content->{request}->shutdown(2);
810 $content->{request}->close();