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