]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/WWW/EGCatLoader/Record.pm
LP#1527731: Allow specified join order
[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     # and copy tags
106     my %cached_bibs = ();
107     foreach my $copy (@{$ctx->{copies}}) {
108         $copy->{notes} = $U->simplereq(
109             'open-ils.circ',
110             'open-ils.circ.copy_note.retrieve.all',
111             {itemid => $copy->{id}, pub => 1 }
112         );
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(
117             'open-ils.circ',
118             $meth,
119             {
120                 ($ctx->{is_staff} ? (authtoken => $ctx->{authtoken}) : ()),
121                 copy_id  => $copy->{id},
122                 scope    => $org,
123                 depth    => $copy_depth,
124             }
125         );
126         $self->timelog("past copy tag retrieval call");
127         $copy->{peer_bibs} = $U->simplereq(
128             'open-ils.search',
129             'open-ils.search.multi_home.bib_ids.by_barcode',
130             $copy->{barcode}
131         );
132         $self->timelog("past peer bib id retrieval");
133         my @peer_marc;
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(
138                 [$bib], undef, {
139                     flesh => '{}',
140                     site => $org_name,
141                     depth => $depth,
142                     pref_lib => $pref_ou
143             });
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");
148         }
149         $copy->{peer_bib_marc} = \@peer_marc;
150     }
151
152     $self->timelog("past store copy retrieval call");
153     $ctx->{copy_limit} = $copy_limit;
154     $ctx->{copy_offset} = $copy_offset;
155
156     $ctx->{have_holdings_to_show} = 0;
157     $ctx->{have_mfhd_to_show} = 0;
158
159     $self->get_hold_copy_summary($rec_id, $org);
160
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' ] },
165             from => 'bre',
166             where => { 'id' => $rec_id }
167         })->[0]->{deleted}
168     );
169
170     $cstore->kill_me;
171
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;
175     }
176
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;
180     }
181
182     $ctx->{mfhd_summaries} =
183         $self->get_mfhd_summaries($rec_id, $org, $copy_depth);
184
185     if (
186         $ctx->{get_org_setting}->
187             ($org, "opac.fully_compressed_serial_holdings")
188     ) {
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);
192     } else {
193         if ($ctx->{mfhd_summaries} && scalar(@{$ctx->{mfhd_summaries}})
194         ) {
195             $ctx->{have_mfhd_to_show} = 1;
196         };
197     }
198
199     $self->timelog("past serials holding stuff");
200
201     my %expandies = (
202         marchtml => sub {
203             $ctx->{marchtml} = $self->mk_marc_html($rec_id);
204         },
205         issues => sub {
206             return;
207             # XXX this needed?
208         },
209         cnbrowse => sub {
210             $self->prepare_browse_call_numbers();
211         }
212     );
213
214     my @expand = $self->cgi->param('expand');
215     if (grep {$_ eq 'all'} @expand) {
216         $ctx->{expand_all} = 1;
217         $expandies{$_}->() for keys %expandies;
218
219     } else {
220         for my $exp (@expand) {
221             $ctx->{"expand_$exp"} = 1;
222             $expandies{$exp}->() if exists $expandies{$exp};
223         }
224     }
225
226     $self->timelog("past expandies");
227
228     $self->added_content_stage2($rec_id);
229
230     $self->timelog("past added content stage 2");
231
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' ] },
236         from     => 'mmrsm',
237         where    => { 'source' => $rec_id }
238     })->[0]->{metarecord};
239     # If this record is apart of a meta group, I want to know more
240     if ( $mmr_id ) {
241         my (undef, @metarecord_data) = $self->get_records_and_facets([$mmr_id], undef, {
242             flesh => '{holdings_xml,mra}',
243             metarecord => 1,
244             site => $org_name,
245             depth => $depth,
246             pref_lib => $pref_ou
247         });
248         my ($rec) = grep { $_->{mmr_id} == $mmr_id } @metarecord_data;
249         $ctx->{mmr_id} = $mmr_id;
250         $ctx->{mmr_data} = $rec;
251     }
252     return Apache2::Const::OK;
253 }
254
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 {
258     my $self = shift;
259     my $rec_id = shift;
260     my $ctx = $self->ctx;
261     $ctx->{search_result_index} = -1;
262
263     $self->load_rresults(internal => 1);
264
265     my @search_ids = @{$ctx->{ids}};
266     return unless @search_ids;
267
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;
273             last;
274         }
275     }
276
277     $ctx->{first_search_record} = $search_ids[0];
278     $ctx->{last_search_record} = $search_ids[-1];
279 }
280
281
282 sub mk_copy_query {
283     my $self = shift;
284     my $rec_id = shift;
285     my $org = shift;
286     my $depth = shift;
287     my $copy_limit = shift;
288     my $copy_offset = shift;
289     my $pref_ou = shift;
290
291     my $query = $U->basic_opac_copy_query(
292         $rec_id, undef, undef, $copy_limit, $copy_offset, $self->ctx->{is_staff}
293     );
294
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 => {
298             fkey => 'circ_lib',
299             field => 'id',
300             filter => {
301                 id => {
302                     in => {
303                         select => {aou => [{
304                             column => 'id', 
305                             transform => 'actor.org_unit_descendants',
306                             result_field => 'id', 
307                             params => [$depth]
308                         }]},
309                         from => 'aou',
310                         where => {id => $org}
311                     }
312                 }
313             }
314         }};
315     };
316
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]
321         }
322     );
323     push(@{$query->{order_by}},
324         { class => "acp", field => 'id',
325           transform => 'evergreen.rank_cp'
326         }
327     );
328
329     return $query;
330 }
331
332 sub mk_marc_html {
333     my($self, $rec_id) = @_;
334
335     # could be optimized considerably by performing the xslt on the already fetched record
336     return $U->simplereq(
337         'open-ils.search', 
338         'open-ils.search.biblio.record.html', $rec_id, 1);
339 }
340
341 sub load_serial_holding_summaries {
342     my ($self, $rec_id, $org, $depth) = @_;
343
344     my $limit = $self->cgi->param("slimit") || 10;
345     my $offset = $self->cgi->param("soffset") || 0;
346
347     my $serial = create OpenSRF::AppSession("open-ils.serial");
348
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
353     )->gather(1);
354
355     return if $self->apache_log_if_event(
356         $tree, "getting holding summary tree for record $rec_id"
357     );
358
359     # Next, if requested, get a list of individual holdings under a
360     # particular summary.
361     my $holdings;
362     my $summary_id = int($self->cgi->param("sid") || 0);
363     my $summary_type = $self->cgi->param("stype");
364
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;
370
371         if (not @$expand_offsets) {
372             $expand_offsets = undef;
373             $auto_expand_first = 1;
374         }
375
376         $holdings = $serial->request(
377             "open-ils.serial.holdings.grouped_by_summary",
378             $summary_type, $summary_id,
379             $expand_path, $expand_limit, $expand_offsets,
380             $auto_expand_first,
381             1 + ($self->ctx->{is_staff} ? 1 : 0)
382         )->gather(1);
383
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"
389             );
390         } else {
391             $self->apache_log_if_event(
392                 $holdings, "getting holdings grouped by summary $summary_id"
393             );
394         }
395     }
396
397     $serial->kill_me;
398
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);
402
403     $self->ctx->{holding_summary_tree} = $tree;
404 }
405
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) = @_;
412
413     foreach my $sum (@{$tree->{holding_summaries}}) {
414         if ($sum->{id} == $sid and $sum->{summary_type} eq $stype) {
415             $sum->{holdings} = $holdings;
416             return 1;
417         }
418     }
419
420     foreach my $child (@{$tree->{children}}) {
421         return 1 if $self->place_holdings_with_summary(
422             $child, $holdings, $sid, $stype
423         );
424     }
425
426     return;
427 }
428
429 sub get_mfhd_summaries {
430     my ($self, $rec_id, $org, $depth) = @_;
431
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
436     )->gather(1);
437
438     $serial->kill_me;
439     return $result;
440 }
441
442 sub any_call_number_label {
443     my ($self) = @_;
444
445     if ($self->ctx->{copies} and @{$self->ctx->{copies}}) {
446         return $self->ctx->{copies}->[0]->{call_number_label};
447     } else {
448         return;
449     }
450 }
451
452 sub prepare_browse_call_numbers {
453     my ($self) = @_;
454
455     my $cn = ($self->cgi->param("cn") || $self->any_call_number_label) or
456         return [];
457
458     my $org_unit = $self->ctx->{get_aou}->($self->_get_search_lib()) ||
459         $self->ctx->{aou_tree}->();
460
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")
465     )->gather(1) || [];
466
467     $supercat->kill_me;
468
469     $self->ctx->{browsed_call_numbers} = [
470         map {
471             $_->record->marc(
472                 (new XML::LibXML)->parse_string($_->record->marc)
473             );
474             $_;
475         } @$results
476     ];
477     $self->ctx->{browsing_ou} = $org_unit;
478 }
479
480 sub get_hold_copy_summary {
481     my ($self, $rec_id, $org) = @_;
482     my $ctx = $self->ctx;
483     
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';
489     }
490     my $req1 = $search->request($copy_count_meth, $org, $rec_id); 
491
492     # if org unit hiding applies, limit the hold count to holds
493     # whose pickup library is within our depth-scoped tree
494     my $count_args = {};
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;
498     }
499
500     $self->ctx->{record_hold_count} = $U->simplereq(
501         'open-ils.circ', 'open-ils.circ.bre.holds.count', 
502         $rec_id, $count_args);
503
504     $self->ctx->{copy_summary} = $req1->recv->content;
505
506     $search->kill_me;
507 }
508
509 sub load_print_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     $self->{ctx}->{printable_record} = $U->simplereq(
517         'open-ils.search',
518         'open-ils.search.biblio.record.print', $rec_id);
519
520     return Apache2::Const::OK;
521 }
522
523 sub load_email_record {
524     my $self = shift;
525
526     my $rec_id = $self->ctx->{page_args}->[0] 
527         or return Apache2::Const::HTTP_BAD_REQUEST;
528
529     $self->{ctx}->{bre_id} = $rec_id;
530     $U->simplereq(
531         'open-ils.search',
532         'open-ils.search.biblio.record.email', 
533         $self->ctx->{authtoken}, $rec_id);
534
535     return Apache2::Const::OK;
536 }
537
538 # for each type, fire off the reqeust to see if content is available
539 # ctx.added_content.$type.status:
540 #   1 == available
541 #   2 == not available
542 #   3 == unknown
543 sub added_content_stage1 {
544     my $self = shift;
545     my $rec_id = shift;
546     my $ctx = $self->ctx;
547     my $sel_type = $self->cgi->param('ac') || '';
548
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;
559     my $ac_failed = 0;
560
561     $logger->info("tpac: added content connecting to $ac_addr:$ac_port / $ac_host");
562
563     $ctx->{added_content} = {};
564     for my $type (@$ac_types) {
565         last if $ac_failed;
566         $ctx->{added_content}->{$type} = {content => ''};
567         $ctx->{added_content}->{$type}->{status} = 3;
568
569         $logger->debug("tpac: starting added content request for $rec_id => $type");
570
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).
576
577         my $req = Net::HTTP::NB->new(
578             Host => $ac_addr, Timeout => 1, PeerPort => $ac_port);
579         if (!$req) {
580             $logger->warn("Unable to connect to $ac_addr:$ac_port / $ac_host".
581                 " for added content lookup for $rec_id: $@");
582             $ac_failed = 1;
583             next;
584         }
585
586         $req->host($self->apache->hostname);
587
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;
591     }
592 }
593
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 {
598     my $self = shift;
599     my $ctx = $self->ctx;
600     my $sel_type = $self->cgi->param('ac') || '';
601
602     for my $type (keys %{$ctx->{added_content}}) {
603         my $content = $ctx->{added_content}->{$type};
604
605         if ($content->{status} == 3) {
606             $logger->debug("tpac: finishing added content request for $type");
607
608             my $req = $content->{request};
609             my $sel = IO::Select->new($req);
610
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?
614
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");
619
620                 if ($code eq '200' and $type eq $sel_type) {
621                     while (1) {
622                         my $buf;
623                         my $n = $req->read_entity_body($buf, 1024);
624                         last unless $n;
625                         $content->{content} .= $buf;
626                     }
627                 }
628             }
629         }
630         # To avoid a lot of hanging connections.
631         if ($content->{request}) {
632             $content->{request}->shutdown(2);
633             $content->{request}->close();
634         } 
635     }
636 }
637
638 1;