]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/WWW/EGCatLoader/Record.pm
tpac : uri escape added content key
[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_INTERNAL_SERVER_ERROR REDIRECT HTTP_BAD_REQUEST);
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 $ctx = $self->ctx;
19     $ctx->{page} = 'record';  
20
21     $self->timelog("load_record() began");
22
23     my $rec_id = $ctx->{page_args}->[0]
24         or return Apache2::Const::HTTP_BAD_REQUEST;
25
26     $self->added_content_stage1($rec_id);
27     $self->timelog("past added content stage 1");
28
29     my $org = $self->_get_search_lib();
30     my $org_name = $ctx->{get_aou}->($org)->shortname;
31     my $pref_ou = $self->_get_pref_lib();
32     my $depth = $self->cgi->param('depth');
33     $depth = $ctx->{get_aou}->($org)->ou_type->depth 
34         unless defined $depth; # can be 0
35
36     my $copy_depth = $self->cgi->param('copy_depth');
37     $copy_depth = $depth unless defined $copy_depth; # can be 0
38     $self->ctx->{copy_depth} = $copy_depth;
39
40     my $copy_limit = int($self->cgi->param('copy_limit') || 10);
41     my $copy_offset = int($self->cgi->param('copy_offset') || 0);
42
43     $self->get_staff_search_settings;
44     if ($ctx->{staff_saved_search_size}) {
45         $ctx->{saved_searches} = ($self->staff_load_searches)[1];
46     }
47     $self->timelog("past staff saved searches");
48
49     $self->fetch_related_search_info($rec_id);
50     $self->timelog("past related search info");
51
52     # run copy retrieval in parallel to bib retrieval
53     # XXX unapi
54     my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
55     my $copy_rec = $cstore->request(
56         'open-ils.cstore.json_query.atomic', 
57         $self->mk_copy_query($rec_id, $org, $copy_depth, $copy_limit, $copy_offset, $pref_ou)
58     );
59
60     my (undef, @rec_data) = $self->get_records_and_facets([$rec_id], undef, {
61         flesh => '{holdings_xml,bmp,mra,acp,acnp,acns}',
62         site => $org_name,
63         depth => $depth,
64         pref_lib => $pref_ou
65     });
66
67     $self->timelog("past get_records_and_facets()");
68     $ctx->{bre_id} = $rec_data[0]->{id};
69     $ctx->{marc_xml} = $rec_data[0]->{marc_xml};
70
71     $ctx->{copies} = $copy_rec->gather(1);
72     $self->timelog("past store copy retrieval call");
73     $ctx->{copy_limit} = $copy_limit;
74     $ctx->{copy_offset} = $copy_offset;
75
76     $ctx->{have_holdings_to_show} = 0;
77     $ctx->{have_mfhd_to_show} = 0;
78
79     $self->get_hold_copy_summary($rec_id, $org);
80
81     $self->timelog("past get_hold_copy_summary()");
82     $self->ctx->{bib_is_dead} = OpenILS::Application::AppUtils->is_true(
83         OpenILS::Utils::CStoreEditor->new->json_query({
84             select => { bre => [ 'deleted' ] },
85             from => 'bre',
86             where => { 'id' => $rec_id }
87         })->[0]->{deleted}
88     );
89
90     $cstore->kill_me;
91
92     if (
93         $ctx->{get_org_setting}->
94             ($org, "opac.fully_compressed_serial_holdings")
95     ) {
96         # We're loading this data here? Are we therefore assuming that we
97         # *are* going to display something in the "issues" expandy?
98         $self->load_serial_holding_summaries($rec_id, $org, $copy_depth);
99     } else {
100         $ctx->{mfhd_summaries} =
101             $self->get_mfhd_summaries($rec_id, $org, $copy_depth);
102
103         if ($ctx->{mfhd_summaries} && scalar(@{$ctx->{mfhd_summaries}})
104         ) {
105             $ctx->{have_mfhd_to_show} = 1;
106         };
107     }
108
109     $self->timelog("past serials holding stuff");
110
111     my %expandies = (
112         marchtml => sub {
113             $ctx->{marchtml} = $self->mk_marc_html($rec_id);
114         },
115         issues => sub {
116             return;
117             # XXX this needed?
118         },
119         cnbrowse => sub {
120             $self->prepare_browse_call_numbers();
121         }
122     );
123
124     my @expand = $self->cgi->param('expand');
125     if (grep {$_ eq 'all'} @expand) {
126         $ctx->{expand_all} = 1;
127         $expandies{$_}->() for keys %expandies;
128
129     } else {
130         for my $exp (@expand) {
131             $ctx->{"expand_$exp"} = 1;
132             $expandies{$exp}->() if exists $expandies{$exp};
133         }
134     }
135
136     $self->timelog("past expandies");
137
138     $self->added_content_stage2($rec_id);
139
140     $self->timelog("past added content stage 2");
141
142     return Apache2::Const::OK;
143 }
144
145 # collect IDs and info on the search that lead to this details page
146 # If no search query, etc is present, we leave ctx.search_result_index == -1
147 sub fetch_related_search_info {
148     my $self = shift;
149     my $rec_id = shift;
150     my $ctx = $self->ctx;
151     $ctx->{search_result_index} = -1;
152
153     $self->load_rresults(internal => 1);
154
155     my @search_ids = @{$ctx->{ids}};
156     return unless @search_ids;
157
158     for my $idx (0..$#search_ids) {
159         if ($search_ids[$idx] == $rec_id) {
160             $ctx->{prev_search_record} = $search_ids[$idx - 1] if $idx > 0;
161             $ctx->{next_search_record} = $search_ids[$idx + 1];
162             $ctx->{search_result_index} = $idx;
163             last;
164         }
165     }
166
167     $ctx->{first_search_record} = $search_ids[0];
168     $ctx->{last_search_record} = $search_ids[-1];
169 }
170
171
172 sub mk_copy_query {
173     my $self = shift;
174     my $rec_id = shift;
175     my $org = shift;
176     my $depth = shift;
177     my $copy_limit = shift;
178     my $copy_offset = shift;
179     my $pref_ou = shift;
180
181     my $query = $U->basic_opac_copy_query(
182         $rec_id, undef, undef, $copy_limit, $copy_offset, $self->ctx->{is_staff}
183     );
184
185     if($org != $self->ctx->{aou_tree}->()->id) { 
186         # no need to add the org join filter if we're not actually filtering
187         $query->{from}->{acp}->{aou} = {
188             fkey => 'circ_lib',
189             field => 'id',
190             filter => {
191                 id => {
192                     in => {
193                         select => {aou => [{
194                             column => 'id', 
195                             transform => 'actor.org_unit_descendants',
196                             result_field => 'id', 
197                             params => [$depth]
198                         }]},
199                         from => 'aou',
200                         where => {id => $org}
201                     }
202                 }
203             }
204         };
205     };
206
207     # Unsure if we want these in the shared function, leaving here for now
208     unshift(@{$query->{order_by}},
209         { class => "aou", field => 'id',
210           transform => 'evergreen.rank_ou', params => [$org, $pref_ou]
211         }
212     );
213     push(@{$query->{order_by}},
214         { class => "acp", field => 'status',
215           transform => 'evergreen.rank_cp_status'
216         }
217     );
218
219     return $query;
220 }
221
222 sub mk_marc_html {
223     my($self, $rec_id) = @_;
224
225     # could be optimized considerably by performing the xslt on the already fetched record
226     return $U->simplereq(
227         'open-ils.search', 
228         'open-ils.search.biblio.record.html', $rec_id, 1);
229 }
230
231 sub load_serial_holding_summaries {
232     my ($self, $rec_id, $org, $depth) = @_;
233
234     my $limit = $self->cgi->param("slimit") || 10;
235     my $offset = $self->cgi->param("soffset") || 0;
236
237     my $serial = create OpenSRF::AppSession("open-ils.serial");
238
239     # First, get the tree of /summaries/ of holdings.
240     my $tree = $serial->request(
241         "open-ils.serial.holding_summary_tree.by_bib",
242         $rec_id, $org, $depth, $limit, $offset
243     )->gather(1);
244
245     return if $self->apache_log_if_event(
246         $tree, "getting holding summary tree for record $rec_id"
247     );
248
249     # Next, if requested, get a list of individual holdings under a
250     # particular summary.
251     my $holdings;
252     my $summary_id = int($self->cgi->param("sid") || 0);
253     my $summary_type = $self->cgi->param("stype");
254
255     if ($summary_id and $summary_type) {
256         my $expand_path = [ $self->cgi->param("sepath") ],
257         my $expand_limit = $self->cgi->param("selimit");
258         my $expand_offsets = [ $self->cgi->param("seoffset") ];
259         my $auto_expand_first = 0;
260
261         if (not @$expand_offsets) {
262             $expand_offsets = undef;
263             $auto_expand_first = 1;
264         }
265
266         $holdings = $serial->request(
267             "open-ils.serial.holdings.grouped_by_summary",
268             $summary_type, $summary_id,
269             $expand_path, $expand_limit, $expand_offsets,
270             $auto_expand_first,
271             1 + ($self->ctx->{is_staff} ? 1 : 0)
272         )->gather(1);
273
274         if ($holdings and ref $holdings eq "ARRAY") {
275             $self->place_holdings_with_summary(
276                     $tree, $holdings, $summary_id, $summary_type
277             ) or $self->apache->log->warn(
278                 "could not place holdings within summary tree"
279             );
280         } else {
281             $self->apache_log_if_event(
282                 $holdings, "getting holdings grouped by summary $summary_id"
283             );
284         }
285     }
286
287     $serial->kill_me;
288
289     # The presence of any keys in the tree hash other than 'more' means that we
290     # must have /something/ we could show.
291     $self->ctx->{have_holdings_to_show} = grep { $_ ne 'more' } (keys %$tree);
292
293     $self->ctx->{holding_summary_tree} = $tree;
294 }
295
296 # This helper to load_serial_holding_summaries() recursively searches in
297 # $tree for a holding summary matching $sid and $stype, and places $holdings
298 # within the node for that summary. IOW, this is about showing expanded
299 # holdings under their "parent" summary.
300 sub place_holdings_with_summary {
301     my ($self, $tree, $holdings, $sid, $stype) = @_;
302
303     foreach my $sum (@{$tree->{holding_summaries}}) {
304         if ($sum->{id} == $sid and $sum->{summary_type} eq $stype) {
305             $sum->{holdings} = $holdings;
306             return 1;
307         }
308     }
309
310     foreach my $child (@{$tree->{children}}) {
311         return 1 if $self->place_holdings_with_summary(
312             $child, $holdings, $sid, $stype
313         );
314     }
315
316     return;
317 }
318
319 sub get_mfhd_summaries {
320     my ($self, $rec_id, $org, $depth) = @_;
321
322     my $serial = create OpenSRF::AppSession("open-ils.search");
323     my $result = $serial->request(
324         "open-ils.search.serial.record.bib.retrieve",
325         $rec_id, $org, $depth
326     )->gather(1);
327
328     $serial->kill_me;
329     return $result;
330 }
331
332 sub any_call_number_label {
333     my ($self) = @_;
334
335     if ($self->ctx->{copies} and @{$self->ctx->{copies}}) {
336         return $self->ctx->{copies}->[0]->{call_number_label};
337     } else {
338         return;
339     }
340 }
341
342 sub prepare_browse_call_numbers {
343     my ($self) = @_;
344
345     my $cn = ($self->cgi->param("cn") || $self->any_call_number_label) or
346         return [];
347
348     my $org_unit = $self->ctx->{get_aou}->($self->cgi->param('loc')) ||
349         $self->ctx->{aou_tree}->();
350
351     my $supercat = create OpenSRF::AppSession("open-ils.supercat");
352     my $results = $supercat->request(
353         "open-ils.supercat.call_number.browse", 
354         $cn, $org_unit->shortname, 9, $self->cgi->param("cnoffset")
355     )->gather(1) || [];
356
357     $supercat->kill_me;
358
359     $self->ctx->{browsed_call_numbers} = [
360         map {
361             $_->record->marc(
362                 (new XML::LibXML)->parse_string($_->record->marc)
363             );
364             $_;
365         } @$results
366     ];
367     $self->ctx->{browsing_ou} = $org_unit;
368 }
369
370 sub get_hold_copy_summary {
371     my ($self, $rec_id, $org) = @_;
372     
373     my $search = OpenSRF::AppSession->create('open-ils.search');
374     my $req1 = $search->request(
375         'open-ils.search.biblio.record.copy_count', $org, $rec_id); 
376
377     $self->ctx->{record_hold_count} = $U->simplereq(
378         'open-ils.circ', 'open-ils.circ.bre.holds.count', $rec_id);
379
380     $self->ctx->{copy_summary} = $req1->recv->content;
381
382     $search->kill_me;
383 }
384
385 sub load_print_record {
386     my $self = shift;
387
388     my $rec_id = $self->ctx->{page_args}->[0] 
389         or return Apache2::Const::HTTP_BAD_REQUEST;
390
391     $self->{ctx}->{bre_id} = $rec_id;
392     $self->{ctx}->{printable_record} = $U->simplereq(
393         'open-ils.search',
394         'open-ils.search.biblio.record.print', $rec_id);
395
396     return Apache2::Const::OK;
397 }
398
399 sub load_email_record {
400     my $self = shift;
401
402     my $rec_id = $self->ctx->{page_args}->[0] 
403         or return Apache2::Const::HTTP_BAD_REQUEST;
404
405     $self->{ctx}->{bre_id} = $rec_id;
406     $U->simplereq(
407         'open-ils.search',
408         'open-ils.search.biblio.record.email', 
409         $self->ctx->{authtoken}, $rec_id);
410
411     return Apache2::Const::OK;
412 }
413
414 # for each type, fire off the reqeust to see if content is available
415 # ctx.added_content.$type.status:
416 #   1 == available
417 #   2 == not available
418 #   3 == unknown
419 sub added_content_stage1 {
420     my $self = shift;
421     my $rec_id = shift;
422     my $ctx = $self->ctx;
423     my $sel_type = $self->cgi->param('ac') || '';
424     my $key = $self->get_ac_key($rec_id);
425     ($key = $key->{value}) =~ s/^\s+//g if $key;
426
427     $ctx->{added_content} = {};
428     for my $type (@$ac_types) {
429         $ctx->{added_content}->{$type} = {content => ''};
430         $ctx->{added_content}->{$type}->{status} = $key ? 3 : 2;
431
432         if ($key) {
433             $logger->debug("tpac: starting added content request for $key => $type");
434
435             my $req = Net::HTTP::NB->new(Host => $self->apache->hostname);
436
437             if (!$req) {
438                 $logger->warn("Unable to fetch added content from " . $self->apache->hostname . ": $@");
439                 next;
440             }
441
442             my $http_type = ($type eq $sel_type) ? 'GET' : 'HEAD';
443             $req->write_request($http_type => "/opac/extras/ac/$type/html/" . uri_escape($key));
444             $ctx->{added_content}->{$type}->{request} = $req;
445         }
446     }
447 }
448
449 # check each outstanding request.  If it's ready, read the HTTP 
450 # status and use it to determine if content is available.  Otherwise,
451 # leave the status as unknown.
452 sub added_content_stage2 {
453     my $self = shift;
454     my $ctx = $self->ctx;
455     my $sel_type = $self->cgi->param('ac') || '';
456
457     for my $type (keys %{$ctx->{added_content}}) {
458         my $content = $ctx->{added_content}->{$type};
459
460         if ($content->{status} == 3) {
461             $logger->debug("tpac: finishing added content request for $type");
462
463             my $req = $content->{request};
464             my $sel = IO::Select->new($req);
465
466             # if we are requesting a specific type of content, give the 
467             # backend code a little extra time to retrieve the content.
468             my $wait = $type eq $sel_type ? 3 : 0; # TODO: config?
469
470             if ($sel->can_read($wait)) {
471                 my ($code) = $req->read_response_headers;
472                 $content->{status} = $code eq '200' ? 1 : 2;
473                 $logger->debug("tpac: added content request for $type returned $code");
474
475                 if ($code eq '200' and $type eq $sel_type) {
476                     while (1) {
477                         my $buf;
478                         my $n = $req->read_entity_body($buf, 1024);
479                         last unless $n;
480                         $content->{content} .= $buf;
481                     }
482                 }
483             }
484         }
485     }
486 }
487
488 # XXX this is copied directly from AddedContent.pm in 
489 # working/user/jeff/ac_by_record_id_rebase.  When Jeff's
490 # branch is merged and Evergreen gets added content 
491 # lookup by ID, this can be removed.
492 # returns [{tag => $tag, value => $value}, {tag => $tag2, value => $value2}]
493 sub get_ac_key {
494     my $self = shift;
495     my $rec_id = shift;
496     my $key_data = $self->editor->json_query({
497         select => {mfr => ['tag', 'value']},
498         from => 'mfr',
499         where => {
500             record => $rec_id,
501             '-or' => [
502                 {
503                     '-and' => [
504                         {tag => '020'},
505                         {subfield => 'a'}
506                     ]
507                 }, {
508                     '-and' => [
509                         {tag => '024'},
510                         {subfield => 'a'},
511                         {ind1 => 1}
512                     ]
513                 }
514             ]
515         }
516     });
517
518     return (
519         grep {$_->{tag} eq '020'} @$key_data,
520         grep {$_->{tag} eq '024'} @$key_data
521     )[0];
522 }
523
524 1;