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