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