]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/WWW/EGCatLoader/Record.pm
114de0cb6998b60ad6c1eae8ff088a44f7564725
[working/Evergreen.git] / Open-ILS / src / perlmods / lib / OpenILS / WWW / EGCatLoader / Record.pm
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;
8 use Net::HTTP::NB;
9 use IO::Select;
10 my $U = 'OpenILS::Application::AppUtils';
11
12 our $ac_types = ['toc',  'anotes', 'excerpt', 'summary', 'reviews'];
13
14 # context additions: 
15 #   record : bre object
16 sub load_record {
17     my $self = shift;
18     my %kwargs = @_;
19     my $ctx = $self->ctx;
20     $ctx->{page} = 'record';  
21
22     $self->timelog("load_record() began");
23
24     my $rec_id = $ctx->{page_args}->[0];
25
26     return Apache2::Const::HTTP_BAD_REQUEST 
27         unless $rec_id and $rec_id =~ /^\d+$/;
28
29     $self->added_content_stage1($rec_id);
30     $self->timelog("past added content stage 1");
31
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
38
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;
42
43     my $copy_limit = int($self->cgi->param('copy_limit') || 10);
44     my $copy_offset = int($self->cgi->param('copy_offset') || 0);
45
46     $self->get_staff_search_settings;
47     if ($ctx->{staff_saved_search_size}) {
48         $ctx->{saved_searches} = ($self->staff_load_searches)[1];
49     }
50     $self->timelog("past staff saved searches");
51
52     $self->fetch_related_search_info($rec_id) unless $kwargs{no_search};
53     $self->timelog("past related search info");
54
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");
59     }
60
61     # run copy retrieval in parallel to bib retrieval
62     # XXX unapi
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)
67     );
68
69     if ($self->cgi->param('badges')) {
70         my $badges = $self->cgi->param('badges');
71         $badges = $badges ? [split(',', $badges)] : [];
72         $badges = [grep { /^\d+$/ } @$badges];
73         if (@$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'] } }
78             )->gather(1);
79         }
80     } else {
81         $self->ctx->{badge_scores} = [];
82     }
83
84     # find foreign copy data
85     my $peer_rec = $U->simplereq(
86         'open-ils.search',
87         'open-ils.search.peer_bibs', $rec_id );
88
89     $ctx->{foreign_copies} = $peer_rec;
90
91     my (undef, @rec_data) = $self->get_records_and_facets([$rec_id], undef, {
92         flesh => '{holdings_xml,bmp,mra,acp,acnp,acns}',
93         site => $org_name,
94         depth => $depth,
95         pref_lib => $pref_ou
96     });
97
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};
101
102     $ctx->{copies} = $copy_rec->gather(1);
103
104     # Add public copy notes to each copy - and while we're in there, grab peer bib records
105     my %cached_bibs = ();
106     foreach my $copy (@{$ctx->{copies}}) {
107         $copy->{notes} = $U->simplereq(
108             'open-ils.circ',
109             'open-ils.circ.copy_note.retrieve.all',
110             {itemid => $copy->{id}, pub => 1 }
111         );
112         $self->timelog("past copy note retrieval call");
113         $copy->{peer_bibs} = $U->simplereq(
114             'open-ils.search',
115             'open-ils.search.multi_home.bib_ids.by_barcode',
116             $copy->{barcode}
117         );
118         $self->timelog("past peer bib id retrieval");
119         my @peer_marc;
120         foreach my $bib (@{$copy->{peer_bibs}}) {
121             next if $bib eq $ctx->{bre_id};
122             next if $cached_bibs{$bib};
123             my (undef, @peer_data) = $self->get_records_and_facets(
124                 [$bib], undef, {
125                     flesh => '{}',
126                     site => $org_name,
127                     depth => $depth,
128                     pref_lib => $pref_ou
129             });
130             $cached_bibs{$bib} = 1;
131             #$copy->{peer_bib_marc} = $peer_data[0]->{marc_xml};
132             push @peer_marc, $peer_data[0]->{marc_xml};
133             $self->timelog("fetched peer bib record $bib");
134         }
135         $copy->{peer_bib_marc} = \@peer_marc;
136     }
137
138     $self->timelog("past store copy retrieval call");
139     $ctx->{copy_limit} = $copy_limit;
140     $ctx->{copy_offset} = $copy_offset;
141
142     $ctx->{have_holdings_to_show} = 0;
143     $ctx->{have_mfhd_to_show} = 0;
144
145     $self->get_hold_copy_summary($rec_id, $org);
146
147     $self->timelog("past get_hold_copy_summary()");
148     $self->ctx->{bib_is_dead} = OpenILS::Application::AppUtils->is_true(
149         OpenILS::Utils::CStoreEditor->new->json_query({
150             select => { bre => [ 'deleted' ] },
151             from => 'bre',
152             where => { 'id' => $rec_id }
153         })->[0]->{deleted}
154     );
155
156     $cstore->kill_me;
157
158     # Shortcut and help the machines with a 410 Gone status code
159     if ($self->ctx->{bib_is_dead}) {
160         return Apache2::Const::HTTP_GONE;
161     }
162
163     # Shortcut and help the machines with a 404 Not Found status code
164     if (!$ctx->{bre_id}) {
165         return Apache2::Const::HTTP_NOT_FOUND;
166     }
167
168     $ctx->{mfhd_summaries} =
169         $self->get_mfhd_summaries($rec_id, $org, $copy_depth);
170
171     if (
172         $ctx->{get_org_setting}->
173             ($org, "opac.fully_compressed_serial_holdings")
174     ) {
175         # We're loading this data here? Are we therefore assuming that we
176         # *are* going to display something in the "issues" expandy?
177         $self->load_serial_holding_summaries($rec_id, $org, $copy_depth);
178     } else {
179         if ($ctx->{mfhd_summaries} && scalar(@{$ctx->{mfhd_summaries}})
180         ) {
181             $ctx->{have_mfhd_to_show} = 1;
182         };
183     }
184
185     $self->timelog("past serials holding stuff");
186
187     my %expandies = (
188         marchtml => sub {
189             $ctx->{marchtml} = $self->mk_marc_html($rec_id);
190         },
191         issues => sub {
192             return;
193             # XXX this needed?
194         },
195         cnbrowse => sub {
196             $self->prepare_browse_call_numbers();
197         }
198     );
199
200     my @expand = $self->cgi->param('expand');
201     if (grep {$_ eq 'all'} @expand) {
202         $ctx->{expand_all} = 1;
203         $expandies{$_}->() for keys %expandies;
204
205     } else {
206         for my $exp (@expand) {
207             $ctx->{"expand_$exp"} = 1;
208             $expandies{$exp}->() if exists $expandies{$exp};
209         }
210     }
211
212     $self->timelog("past expandies");
213
214     $self->added_content_stage2($rec_id);
215
216     $self->timelog("past added content stage 2");
217
218     # Gather up metarecord info for display
219     # Let's start by getting the metarecord ID
220     my $mmr_id = OpenILS::Utils::CStoreEditor->new->json_query({
221         select   => { mmrsm => [ 'metarecord' ] },
222         from     => 'mmrsm',
223         where    => { 'source' => $rec_id }
224     })->[0]->{metarecord};
225     # If this record is apart of a meta group, I want to know more
226     if ( $mmr_id ) {
227         my (undef, @metarecord_data) = $self->get_records_and_facets([$mmr_id], undef, {
228             flesh => '{holdings_xml,mra}',
229             metarecord => 1,
230             site => $org_name,
231             depth => $depth,
232             pref_lib => $pref_ou
233         });
234         my ($rec) = grep { $_->{mmr_id} == $mmr_id } @metarecord_data;
235         $ctx->{mmr_id} = $mmr_id;
236         $ctx->{mmr_data} = $rec;
237     }
238     return Apache2::Const::OK;
239 }
240
241 # collect IDs and info on the search that lead to this details page
242 # If no search query, etc is present, we leave ctx.search_result_index == -1
243 sub fetch_related_search_info {
244     my $self = shift;
245     my $rec_id = shift;
246     my $ctx = $self->ctx;
247     $ctx->{search_result_index} = -1;
248
249     $self->load_rresults(internal => 1);
250
251     my @search_ids = @{$ctx->{ids}};
252     return unless @search_ids;
253
254     for my $idx (0..$#search_ids) {
255         if ($search_ids[$idx] == $rec_id) {
256             $ctx->{prev_search_record} = $search_ids[$idx - 1] if $idx > 0;
257             $ctx->{next_search_record} = $search_ids[$idx + 1];
258             $ctx->{search_result_index} = $idx;
259             last;
260         }
261     }
262
263     $ctx->{first_search_record} = $search_ids[0];
264     $ctx->{last_search_record} = $search_ids[-1];
265 }
266
267
268 sub mk_copy_query {
269     my $self = shift;
270     my $rec_id = shift;
271     my $org = shift;
272     my $depth = shift;
273     my $copy_limit = shift;
274     my $copy_offset = shift;
275     my $pref_ou = shift;
276
277     my $query = $U->basic_opac_copy_query(
278         $rec_id, undef, undef, $copy_limit, $copy_offset, $self->ctx->{is_staff}
279     );
280
281     if($org != $self->ctx->{aou_tree}->()->id) { 
282         # no need to add the org join filter if we're not actually filtering
283         $query->{from}->{acp}->{aou} = {
284             fkey => 'circ_lib',
285             field => 'id',
286             filter => {
287                 id => {
288                     in => {
289                         select => {aou => [{
290                             column => 'id', 
291                             transform => 'actor.org_unit_descendants',
292                             result_field => 'id', 
293                             params => [$depth]
294                         }]},
295                         from => 'aou',
296                         where => {id => $org}
297                     }
298                 }
299             }
300         };
301     };
302
303     # Unsure if we want these in the shared function, leaving here for now
304     unshift(@{$query->{order_by}},
305         { class => "aou", field => 'id',
306           transform => 'evergreen.rank_ou', params => [$org, $pref_ou]
307         }
308     );
309     push(@{$query->{order_by}},
310         { class => "acp", field => 'id',
311           transform => 'evergreen.rank_cp'
312         }
313     );
314
315     return $query;
316 }
317
318 sub mk_marc_html {
319     my($self, $rec_id) = @_;
320
321     # could be optimized considerably by performing the xslt on the already fetched record
322     return $U->simplereq(
323         'open-ils.search', 
324         'open-ils.search.biblio.record.html', $rec_id, 1);
325 }
326
327 sub load_serial_holding_summaries {
328     my ($self, $rec_id, $org, $depth) = @_;
329
330     my $limit = $self->cgi->param("slimit") || 10;
331     my $offset = $self->cgi->param("soffset") || 0;
332
333     my $serial = create OpenSRF::AppSession("open-ils.serial");
334
335     # First, get the tree of /summaries/ of holdings.
336     my $tree = $serial->request(
337         "open-ils.serial.holding_summary_tree.by_bib",
338         $rec_id, $org, $depth, $limit, $offset
339     )->gather(1);
340
341     return if $self->apache_log_if_event(
342         $tree, "getting holding summary tree for record $rec_id"
343     );
344
345     # Next, if requested, get a list of individual holdings under a
346     # particular summary.
347     my $holdings;
348     my $summary_id = int($self->cgi->param("sid") || 0);
349     my $summary_type = $self->cgi->param("stype");
350
351     if ($summary_id and $summary_type) {
352         my $expand_path = [ $self->cgi->param("sepath") ],
353         my $expand_limit = $self->cgi->param("selimit");
354         my $expand_offsets = [ $self->cgi->param("seoffset") ];
355         my $auto_expand_first = 0;
356
357         if (not @$expand_offsets) {
358             $expand_offsets = undef;
359             $auto_expand_first = 1;
360         }
361
362         $holdings = $serial->request(
363             "open-ils.serial.holdings.grouped_by_summary",
364             $summary_type, $summary_id,
365             $expand_path, $expand_limit, $expand_offsets,
366             $auto_expand_first,
367             1 + ($self->ctx->{is_staff} ? 1 : 0)
368         )->gather(1);
369
370         if ($holdings and ref $holdings eq "ARRAY") {
371             $self->place_holdings_with_summary(
372                     $tree, $holdings, $summary_id, $summary_type
373             ) or $self->apache->log->warn(
374                 "could not place holdings within summary tree"
375             );
376         } else {
377             $self->apache_log_if_event(
378                 $holdings, "getting holdings grouped by summary $summary_id"
379             );
380         }
381     }
382
383     $serial->kill_me;
384
385     # The presence of any keys in the tree hash other than 'more' means that we
386     # must have /something/ we could show.
387     $self->ctx->{have_holdings_to_show} = grep { $_ ne 'more' } (keys %$tree);
388
389     $self->ctx->{holding_summary_tree} = $tree;
390 }
391
392 # This helper to load_serial_holding_summaries() recursively searches in
393 # $tree for a holding summary matching $sid and $stype, and places $holdings
394 # within the node for that summary. IOW, this is about showing expanded
395 # holdings under their "parent" summary.
396 sub place_holdings_with_summary {
397     my ($self, $tree, $holdings, $sid, $stype) = @_;
398
399     foreach my $sum (@{$tree->{holding_summaries}}) {
400         if ($sum->{id} == $sid and $sum->{summary_type} eq $stype) {
401             $sum->{holdings} = $holdings;
402             return 1;
403         }
404     }
405
406     foreach my $child (@{$tree->{children}}) {
407         return 1 if $self->place_holdings_with_summary(
408             $child, $holdings, $sid, $stype
409         );
410     }
411
412     return;
413 }
414
415 sub get_mfhd_summaries {
416     my ($self, $rec_id, $org, $depth) = @_;
417
418     my $serial = create OpenSRF::AppSession("open-ils.search");
419     my $result = $serial->request(
420         "open-ils.search.serial.record.bib.retrieve",
421         $rec_id, $org, $depth
422     )->gather(1);
423
424     $serial->kill_me;
425     return $result;
426 }
427
428 sub any_call_number_label {
429     my ($self) = @_;
430
431     if ($self->ctx->{copies} and @{$self->ctx->{copies}}) {
432         return $self->ctx->{copies}->[0]->{call_number_label};
433     } else {
434         return;
435     }
436 }
437
438 sub prepare_browse_call_numbers {
439     my ($self) = @_;
440
441     my $cn = ($self->cgi->param("cn") || $self->any_call_number_label) or
442         return [];
443
444     my $org_unit = $self->ctx->{get_aou}->($self->_get_search_lib()) ||
445         $self->ctx->{aou_tree}->();
446
447     my $supercat = create OpenSRF::AppSession("open-ils.supercat");
448     my $results = $supercat->request(
449         "open-ils.supercat.call_number.browse", 
450         $cn, $org_unit->shortname, 9, $self->cgi->param("cnoffset")
451     )->gather(1) || [];
452
453     $supercat->kill_me;
454
455     $self->ctx->{browsed_call_numbers} = [
456         map {
457             $_->record->marc(
458                 (new XML::LibXML)->parse_string($_->record->marc)
459             );
460             $_;
461         } @$results
462     ];
463     $self->ctx->{browsing_ou} = $org_unit;
464 }
465
466 sub get_hold_copy_summary {
467     my ($self, $rec_id, $org) = @_;
468     my $ctx = $self->ctx;
469     
470     my $search = OpenSRF::AppSession->create('open-ils.search');
471     my $copy_count_meth = 'open-ils.search.biblio.record.copy_count';
472     # We want to include OPAC-invisible copies in a staff context
473     if ($ctx->{is_staff}) {
474         $copy_count_meth .= '.staff';
475     }
476     my $req1 = $search->request($copy_count_meth, $org, $rec_id); 
477
478     # if org unit hiding applies, limit the hold count to holds
479     # whose pickup library is within our depth-scoped tree
480     my $count_args = {};
481     while ($org and $ctx->{org_within_hiding_scope}->($org)) {
482         $count_args->{pickup_lib_descendant} = $org;
483         $org = $ctx->{get_aou}->($org)->parent_ou;
484     }
485
486     $self->ctx->{record_hold_count} = $U->simplereq(
487         'open-ils.circ', 'open-ils.circ.bre.holds.count', 
488         $rec_id, $count_args);
489
490     $self->ctx->{copy_summary} = $req1->recv->content;
491
492     $search->kill_me;
493 }
494
495 sub load_print_record {
496     my $self = shift;
497
498     my $rec_id = $self->ctx->{page_args}->[0] 
499         or return Apache2::Const::HTTP_BAD_REQUEST;
500
501     $self->{ctx}->{bre_id} = $rec_id;
502     $self->{ctx}->{printable_record} = $U->simplereq(
503         'open-ils.search',
504         'open-ils.search.biblio.record.print', $rec_id);
505
506     return Apache2::Const::OK;
507 }
508
509 sub load_email_record {
510     my $self = shift;
511
512     my $rec_id = $self->ctx->{page_args}->[0] 
513         or return Apache2::Const::HTTP_BAD_REQUEST;
514
515     $self->{ctx}->{bre_id} = $rec_id;
516     $U->simplereq(
517         'open-ils.search',
518         'open-ils.search.biblio.record.email', 
519         $self->ctx->{authtoken}, $rec_id);
520
521     return Apache2::Const::OK;
522 }
523
524 # for each type, fire off the reqeust to see if content is available
525 # ctx.added_content.$type.status:
526 #   1 == available
527 #   2 == not available
528 #   3 == unknown
529 sub added_content_stage1 {
530     my $self = shift;
531     my $rec_id = shift;
532     my $ctx = $self->ctx;
533     my $sel_type = $self->cgi->param('ac') || '';
534
535     # Connect to this machine's IP address, using the same 
536     # Host with which our caller used to connect to us.
537     # This avoids us having to route out of the cluster 
538     # and back in to reach the top-level virtualhost.
539     my $ac_addr = $ENV{SERVER_ADDR};
540     # Internal connections are HTTP-only (no HTTPS) and assume the
541     # connection port is '80' unless otherwise specified in the Apache
542     # configuration (e.g. for proxy setups)
543     my $ac_port = $self->apache->dir_config('OILSWebInternalHTTPPort') || 80;
544     my $ac_host = $self->apache->hostname;
545     my $ac_failed = 0;
546
547     $logger->info("tpac: added content connecting to $ac_addr:$ac_port / $ac_host");
548
549     $ctx->{added_content} = {};
550     for my $type (@$ac_types) {
551         last if $ac_failed;
552         $ctx->{added_content}->{$type} = {content => ''};
553         $ctx->{added_content}->{$type}->{status} = 3;
554
555         $logger->debug("tpac: starting added content request for $rec_id => $type");
556
557         # Net::HTTP::NB is non-blocking /after/ the initial connect()
558         # Passing Timeout=>1 ensures we wait no longer than 1 second to 
559         # connect to the local Evergreen instance (i.e. ourself).  
560         # Connecting to oneself should either be very fast (normal) 
561         # or very slow (routing problems).
562
563         my $req = Net::HTTP::NB->new(
564             Host => $ac_addr, Timeout => 1, PeerPort => $ac_port);
565         if (!$req) {
566             $logger->warn("Unable to connect to $ac_addr:$ac_port / $ac_host".
567                 " for added content lookup for $rec_id: $@");
568             $ac_failed = 1;
569             next;
570         }
571
572         $req->host($self->apache->hostname);
573
574         my $http_type = ($type eq $sel_type) ? 'GET' : 'HEAD';
575         $req->write_request($http_type => "/opac/extras/ac/$type/html/r/" . $rec_id);
576         $ctx->{added_content}->{$type}->{request} = $req;
577     }
578 }
579
580 # check each outstanding request.  If it's ready, read the HTTP 
581 # status and use it to determine if content is available.  Otherwise,
582 # leave the status as unknown.
583 sub added_content_stage2 {
584     my $self = shift;
585     my $ctx = $self->ctx;
586     my $sel_type = $self->cgi->param('ac') || '';
587
588     for my $type (keys %{$ctx->{added_content}}) {
589         my $content = $ctx->{added_content}->{$type};
590
591         if ($content->{status} == 3) {
592             $logger->debug("tpac: finishing added content request for $type");
593
594             my $req = $content->{request};
595             my $sel = IO::Select->new($req);
596
597             # if we are requesting a specific type of content, give the 
598             # backend code a little extra time to retrieve the content.
599             my $wait = $type eq $sel_type ? 3 : 0; # TODO: config?
600
601             if ($sel->can_read($wait)) {
602                 my ($code) = $req->read_response_headers;
603                 $content->{status} = $code eq '200' ? 1 : 2;
604                 $logger->debug("tpac: added content request for $type returned $code");
605
606                 if ($code eq '200' and $type eq $sel_type) {
607                     while (1) {
608                         my $buf;
609                         my $n = $req->read_entity_body($buf, 1024);
610                         last unless $n;
611                         $content->{content} .= $buf;
612                     }
613                 }
614             }
615         }
616         # To avoid a lot of hanging connections.
617         if ($content->{request}) {
618             $content->{request}->shutdown(2);
619             $content->{request}->close();
620         } 
621     }
622 }
623
624 1;