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