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