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