]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/WWW/EGCatLoader/Util.pm
LP#1902965: HTML filter on OPAC search results and record display, with accordion
[Evergreen.git] / Open-ILS / src / perlmods / lib / OpenILS / WWW / EGCatLoader / Util.pm
1 package OpenILS::WWW::EGCatLoader;
2 use strict; use warnings;
3 use Apache2::Const -compile => qw(OK DECLINED FORBIDDEN HTTP_INTERNAL_SERVER_ERROR REDIRECT HTTP_BAD_REQUEST);
4 use File::Spec;
5 use Time::HiRes qw/time sleep/;
6 use List::MoreUtils qw(uniq);
7 use HTML::TreeBuilder;
8 use HTML::Element;
9 use HTML::Defang;
10 use OpenSRF::Utils::Cache;
11 use OpenSRF::Utils::Logger qw/$logger/;
12 use OpenILS::Utils::CStoreEditor qw/:funcs/;
13 use OpenILS::Utils::Fieldmapper;
14 use OpenILS::Application::AppUtils;
15 use OpenSRF::MultiSession;
16
17 my $defang = HTML::Defang->new;
18 my $U = 'OpenILS::Application::AppUtils';
19
20 my $ro_object_subs; # cached subs
21 our %cache = ( # cached data
22     map => {en_us => {}},
23     list => {en_us => {}},
24     search => {en_us => {}},
25     org_settings => {en_us => {}},
26     search_filter_groups => {en_us => {}},
27     aou_tree => {en_us => undef},
28     aouct_tree => {},
29     eg_cache_hash => undef,
30     authority_fields => {en_us => {}}
31 );
32
33 sub child_init {
34     my $class = shift;
35     my %locales = @_;
36
37     # create a stub object with just enough in place
38     # to call init_ro_object_cache()
39     my $stub = bless({}, ref($class) || $class);
40     my $ctx = {};
41     $stub->ctx($ctx);
42
43     foreach my $locale (sort keys %locales) {
44         OpenSRF::AppSession->default_locale($locales{$locale});
45         $ctx->{locale} = $locale;
46         $stub->init_ro_object_cache();
47
48         # pre-cache various sets of objects
49         # known to be time-consuming to retrieve
50         # the first go around
51         $ro_object_subs->{$locale}->{aou_tree}();
52         $ro_object_subs->{$locale}->{aouct_tree}();
53         $ro_object_subs->{$locale}->{ccvm_list}();
54         $ro_object_subs->{$locale}->{crad_list}();
55         $ro_object_subs->{$locale}->{get_authority_fields}(1);
56     }
57 }
58
59 sub init_ro_object_cache {
60     my $self = shift;
61     my $ctx = $self->ctx;
62     my $memcache ||= OpenSRF::Utils::Cache->new('global');
63
64     # reset org unit setting cache on each page load to avoid the
65     # requirement of reloading apache with each org-setting change
66     $cache{org_settings} = {};
67
68     if($ro_object_subs->{$ctx->{locale}}) {
69         # subs have been built.  insert into the context then move along.
70         $ctx->{$_} = $ro_object_subs->{$ctx->{locale}}->{$_} for keys %{ $ro_object_subs->{$ctx->{locale}} };
71         return;
72     }
73
74     my $locale_subs = {};
75     my $locale = $ctx->{locale};
76
77     # Create special-purpose subs
78
79     # aou is special because it's tree-ish
80     $locale_subs->{aou_tree} = sub {
81
82         # fetch the org unit tree
83         unless($cache{aou_tree}{$locale}) {
84             my $e = new_editor();
85             my $tree = $e->search_actor_org_unit([
86                 {   parent_ou => undef},
87                 {   flesh            => -1,
88                     flesh_fields    => {aou =>  ['children']},
89                     order_by        => {aou => 'name'}
90                 }
91             ])->[0];
92
93             # flesh the org unit type for each org unit
94             # and simultaneously set the id => aou map cache
95             sub flesh_aout {
96                 my $node = shift;
97                 my $locale_subs = shift;
98                 my $locale = shift;
99                 $node->ou_type( $locale_subs->{get_aout}->($node->ou_type) );
100                 $cache{map}{$locale}{aou}{$node->id} = $node;
101                 flesh_aout($_, $locale_subs, $locale) foreach @{$node->children};
102             };
103             flesh_aout($tree, $locale_subs, $locale);
104             undef $e;
105             $cache{aou_tree}{$locale} = $tree;
106         }
107
108         return $cache{aou_tree}{$locale};
109     };
110
111     # Add a special handler for the tree-shaped org unit cache
112     $locale_subs->{get_aou} = sub {
113         my $org_id = shift;
114         return undef unless defined $org_id;
115         $locale_subs->{aou_tree}->(); # force the org tree to load
116         return $cache{map}{$locale}{aou}{$org_id};
117     };
118
119     # Returns a flat list of aout objects, sorted by depth and opac_label.
120     $locale_subs->{sorted_aout_list} = sub {
121         return [ sort { $a->depth() <=> $b->depth() || $a->opac_label() cmp $b->opac_label() } @{$locale_subs->{aout_list}->()} ];
122     };
123
124     # Returns a flat list of aou objects.  often easier to manage than a tree.
125     $locale_subs->{aou_list} = sub {
126         $locale_subs->{aou_tree}->(); # force the org tree to load
127         return [ values %{$cache{map}{$locale}{aou}} ];
128     };
129
130     # returns the org unit object by shortname
131     $locale_subs->{get_aou_by_shortname} = sub {
132         my $sn = shift or return undef;
133         my $list = $locale_subs->{aou_list}->();
134         return (grep {$_->shortname eq $sn} @$list)[0];
135     };
136
137     # Turns one string into two for long text strings
138     $locale_subs->{split_for_accordion} = sub {
139         my $html = shift;
140         my $trunc_length = shift;
141
142         return unless defined $html && defined $trunc_length;
143         
144         my $html_string = "";
145         my $trunc_str = "<span class='truncEllipse'>...</span><span class='truncated' style='display:none'>";
146         my $current_length = 0;
147         my $truncated;
148         my @html_strings;
149
150         my $html_tree = HTML::TreeBuilder->new;
151         $html_tree->parse($html);
152         $html_tree->eof();
153
154         # Navigate #html_tree to determine length of contained strings
155         my @nodes = $html_tree->guts();
156         foreach my $node(@nodes) {
157             my $nref = ref $node;
158             if ($nref eq "HTML::Element") {
159                 $current_length += length $node->as_text();
160                 my $escaped_html = $defang->defang($node->as_HTML());
161                 push(@html_strings, $escaped_html);
162             } else {
163                 # Node is whitespace - handling this like regular simple text
164                 # doesn't like to play nice, so handling separately
165                 if ($node eq ' ') { 
166                     $current_length++;
167                     if ($current_length >= $trunc_length and not $truncated) {
168                         push(@html_strings, " $trunc_str");
169                         $truncated = 1;
170                     } else {
171                         push(@html_strings, $defang->defang($node));
172                     }
173                 # Node is simple text
174                 } else {
175                     my $new_length += length $node;
176                     if ($new_length >= $trunc_length and not $truncated) {
177                         my $nshort;
178                         my $nrest;
179                         my $calc_length = abs($trunc_length - $current_length);
180                         if ((substr $node, $calc_length, 1) =~ /\s/) {
181                             $nshort = substr $node, 0, $calc_length;
182                             $nrest = substr $node, $calc_length;
183                         } else {
184                             my $nloc = rindex $node, ' ', $calc_length;
185                             $nshort = substr $node, 0, $nloc;
186                             $nrest = substr $node, $nloc;
187                         }
188                         $nshort = $defang->defang($nshort);
189                         $nrest = $defang->defang($nrest);
190                         push(@html_strings, "$nshort $trunc_str $nrest");
191                         $truncated = 1;
192                     } else {
193                         push(@html_strings, $defang->defang($node));
194                     }
195                     $current_length += length $node;
196                 }
197             }
198         }
199         if ($truncated) {
200             push(@html_strings, "</span>");
201         }
202  
203         if (@html_strings > 1) {
204             $html_string = join '', @html_strings;
205         } else {
206             $html_string = $html_strings[0];
207         }
208
209         return ($html_string, $truncated);
210     };
211
212     $locale_subs->{aouct_tree} = sub {
213
214         # fetch the org unit tree
215         unless(exists $cache{aouct_tree}{$locale}) {
216             $cache{aouct_tree}{$locale} = undef;
217
218             my $e = new_editor();
219             my $tree_id = $e->search_actor_org_unit_custom_tree(
220                 {purpose => 'opac', active => 't'},
221                 {idlist => 1}
222             )->[0];
223
224             if ($tree_id) {
225                 my $node_tree = $e->search_actor_org_unit_custom_tree_node([
226                 {parent_node => undef, tree => $tree_id},
227                 {   flesh        => -1,
228                     flesh_fields => {aouctn => ['children', 'org_unit']},
229                     order_by     => {aouctn => 'sibling_order'}
230                 }
231                 ])->[0];
232
233                 # tree-ify the org units.  note that since the orgs are fleshed
234                 # upon retrieval, this org tree will not clobber ctx->{aou_tree}.
235                 my @nodes = ($node_tree);
236                 while (my $node = shift(@nodes)) {
237                     my $aou = $node->org_unit;
238                     $aou->children([]);
239                     for my $cnode (@{$node->children}) {
240                         my $child_org = $cnode->org_unit;
241                         $child_org->parent_ou($aou->id);
242                         $child_org->ou_type( $locale_subs->{get_aout}->($child_org->ou_type) );
243                         push(@{$aou->children}, $child_org);
244                         push(@nodes, $cnode);
245                     }
246                 }
247
248                 $cache{aouct_tree}{$locale} = 
249                     $node_tree->org_unit if $node_tree;
250             }
251             undef $e;
252         }
253
254         return $cache{aouct_tree}{$locale};
255     };
256
257     # turns an ISO date into something TT can understand
258     $locale_subs->{parse_datetime} = sub {
259         my $date = shift;
260         my $context_org = shift; # optional, for setting timezone via YAOUS
261
262         # Calling parse_datetime() with empty $date will lead to Internal Server Error
263         return '' if (!defined($date) or $date eq '');
264
265         # Probably an accidental entry like '0212' instead of '2012',
266         # but 1) the leading 0 may get stripped in cstore and
267         # 2) DateTime::Format::ISO8601 returns an error as years
268         # must be 2 or 4 digits
269         if ($date =~ m/^\d{3}-/) {
270             $logger->warn("Invalid date had a 3-digit year: $date");
271             $date = '0' . $date;
272         } elsif ($date =~ m/^\d{1}-/) {
273             $logger->warn("Invalid date had a 1-digit year: $date");
274             $date = '000' . $date;
275         }
276
277         my $cleansed_date = clean_ISO8601($date);
278
279         $date = DateTime::Format::ISO8601->new->parse_datetime($cleansed_date);
280         if ($context_org) {
281             $context_org = $context_org->id if ref($context_org);
282             my $tz = $locale_subs->{get_org_setting}->($context_org,'lib.timezone');
283             if ($tz) {
284                 try {
285                     $date->set_time_zone($tz);
286                 } catch Error with {
287                     $logger->warn("Invalid timezone: $tz");
288                 };
289             }
290         }
291         return sprintf(
292             "%0.2d:%0.2d:%0.2d %0.2d-%0.2d-%0.4d",
293             $date->hour,
294             $date->minute,
295             $date->second,
296             $date->day,
297             $date->month,
298             $date->year
299         );
300     };
301
302     # retrieve and cache org unit setting values
303     $locale_subs->{get_org_setting} = sub {
304         my($org_id, $setting) = @_;
305
306         $cache{org_settings}{$locale}{$org_id}{$setting} =
307             $U->ou_ancestor_setting_value($org_id, $setting)
308                 unless exists $cache{org_settings}{$locale}{$org_id}{$setting};
309
310         return $cache{org_settings}{$locale}{$org_id}{$setting};
311     };
312
313     # retrieve and cache acsaf values
314     $locale_subs->{get_authority_fields} = sub {
315         my ($control_set) = @_;
316
317         if (not exists $cache{authority_fields}{$locale}{$control_set}) {
318             my $e = new_editor();
319             if (my $acs = $e->search_authority_control_set_authority_field(
320                                     {control_set => $control_set}
321                                 )
322             ) {
323                 $cache{authority_fields}{$locale}{$control_set} =
324                  +{ map { $_->id => $_ } @$acs };
325                 undef $e;
326             } else {
327                 undef $e;
328                 return;
329             }
330         }
331
332         return $cache{authority_fields}{$locale}{$control_set};
333     };
334
335     # make all "field_safe" classes accesible by default in the template context
336     my @classes = grep {
337         ($Fieldmapper::fieldmap->{$_}->{field_safe} || '') =~ /true/i
338     } keys %{ $Fieldmapper::fieldmap };
339
340     for my $class (@classes) {
341
342         my $hint = $Fieldmapper::fieldmap->{$class}->{hint};
343         next if $hint eq 'aou'; # handled separately
344
345         my $ident_field =  $Fieldmapper::fieldmap->{$class}->{identity};
346         (my $eclass = $class) =~ s/Fieldmapper:://o;
347         $eclass =~ s/::/_/g;
348
349         my $list_key = "${hint}_list";
350         my $get_key = "get_$hint";
351         my $search_key = "search_$hint";
352
353         my $memcache_key = join('.', 'EGWeb',$locale,$hint) . '.';
354
355         # Retrieve the full set of objects with class $hint
356         $locale_subs->{$list_key} ||= sub {
357             my $from_memcache = 0;
358             my $list = $memcache->get_cache($memcache_key.'list');
359             if ($list) {
360                 $cache{list}{$locale}{$hint} = $list;
361                 $from_memcache = 1;
362             }
363             my $method = "retrieve_all_$eclass";
364             my $e = new_editor();
365             $cache{list}{$locale}{$hint} = $e->$method() unless $cache{list}{$locale}{$hint};
366             undef $e;
367             $memcache->put_cache($memcache_key.'list',$cache{list}{$locale}{$hint}) unless $from_memcache;
368             return $cache{list}{$locale}{$hint};
369         };
370
371         # locate object of class $hint with Ident field $id
372         $cache{map}{$hint} = {};
373         $locale_subs->{$get_key} ||= sub {
374             my $id = shift;
375             return $cache{map}{$locale}{$hint}{$id} if $cache{map}{$locale}{$hint}{$id};
376             ($cache{map}{$locale}{$hint}{$id}) = grep { $_->$ident_field eq $id } @{$locale_subs->{$list_key}->()};
377             return $cache{map}{$locale}{$hint}{$id};
378         };
379
380         # search for objects of class $hint where field=value
381         $cache{search}{$hint} = {};
382         $locale_subs->{$search_key} ||= sub {
383             my ($field, $val, $filterfield, $filterval) = @_;
384             my $method = "search_$eclass";
385             my $cacheval = $val;
386             my $scalar_cacheval = 1;
387
388             if (ref $val) {
389                 $scalar_cacheval = 0;
390                 $val = [sort(@$val)] if ref $val eq 'ARRAY';
391                 $cacheval = OpenSRF::Utils::JSON->perl2JSON($val);
392                 #$self->apache->log->info("cacheval : $cacheval");
393             }
394
395             my $search_obj = {$field => $val};
396             if($filterfield) {
397                 $search_obj->{$filterfield} = $filterval;
398                 $cacheval .= ':' . $filterfield . ':' . $filterval;
399             } elsif (
400                 $scalar_cacheval
401                 and $cache{list}{$locale}{$hint}
402                 and !$cache{search}{$locale}{$hint}{$field}{$cacheval}
403             ) {
404                 return $cache{search}{$locale}{$hint}{$field}{$cacheval} =
405                     [ grep { $_->$field() eq $val } @{$cache{list}{$locale}{$hint}} ];
406             }
407
408             my $e = new_editor();
409             $cache{search}{$locale}{$hint}{$field}{$cacheval} = $e->$method($search_obj)
410                 unless $cache{search}{$locale}{$hint}{$field}{$cacheval};
411             undef $e;
412             return $cache{search}{$locale}{$hint}{$field}{$cacheval};
413         };
414     }
415
416     $ctx->{$_} = $locale_subs->{$_} for keys %$locale_subs;
417     $ro_object_subs->{$locale} = $locale_subs;
418 }
419
420 sub generic_redirect {
421     my $self = shift;
422     my $url = shift;
423     my $cookie = shift; # can be an array of cgi.cookie's
424
425     $self->apache->print(
426         $self->cgi->redirect(
427             -url => $url || 
428                 $self->cgi->param('redirect_to') || 
429                 $self->ctx->{referer} || 
430                 $self->ctx->{home_page},
431             -cookie => $cookie
432         )
433     );
434
435     return Apache2::Const::REDIRECT;
436 }
437
438 my $unapi_cache;
439 sub get_records_and_facets {
440     my ($self, $rec_ids, $facet_key, $unapi_args) = @_;
441
442     # collect the facet data
443     my $search = OpenSRF::AppSession->create('open-ils.search');
444     my $facet_req;
445     if ($facet_key) {
446         $facet_req = $search->request(
447             'open-ils.search.facet_cache.retrieve', $facet_key
448         );
449     }
450
451     $unapi_args ||= {};
452     $unapi_args->{site} ||= $self->ctx->{aou_tree}->()->shortname;
453     $unapi_args->{depth} ||= $self->ctx->{aou_tree}->()->ou_type->depth;
454     $unapi_args->{flesh_depth} ||= 5;
455
456     my $is_meta = delete $unapi_args->{metarecord};
457     #my $unapi_type = $is_meta ? 'unapi.mmr' : 'unapi.bre';
458     my $unapi_type = $is_meta ? 'unapi.metabib_virtual_record_feed' : 'unapi.biblio_record_entry_feed';
459
460     $unapi_cache ||= OpenSRF::Utils::Cache->new('global');
461     my $unapi_cache_key_suffix = join(
462         '_',
463         $is_meta || 0,
464         $unapi_args->{site},
465         $unapi_args->{depth},
466         $unapi_args->{flesh_depth},
467         ($unapi_args->{pref_lib} || '')
468     );
469
470     my %tmp_data;
471     my %hl_tmp_data;
472     my $outer_self = $self;
473
474     my $sdepth = $unapi_args->{flesh_depth};
475     my $slimit = "acn=>$sdepth,acp=>$sdepth";
476     $slimit .= ",bre=>$sdepth" if $is_meta;
477     my $flesh = $unapi_args->{flesh} || '';
478
479     # tag the record with the MR id
480     $flesh =~ s/}$/,mmr.unapi}/g if $is_meta;
481
482     my $ses = OpenSRF::AppSession->create('open-ils.cstore');
483     my $hl_ses = OpenSRF::AppSession->create('open-ils.search');
484
485     my @loop_recs;
486     for my $bid (@$rec_ids) {
487         my $unapi_cache_key = 'TPAC_unapi_cache_'.$bid.'_'.$unapi_cache_key_suffix;
488         my $unapi_data = $unapi_cache->get_cache($unapi_cache_key);
489
490         if (!$unapi_data || $unapi_data->{running}) { #cache entry not done yet, get our own copy
491             push(@loop_recs, $bid);
492         } else {
493             $unapi_data->{marc_xml} = XML::LibXML->new->parse_string($unapi_data->{marc_xml})->documentElement;
494             $tmp_data{$unapi_data->{id}} = $unapi_data;
495             $unapi_cache->put_cache($unapi_cache_key, { running => $$ }, 5);
496         }
497     }
498
499     my $hl_req = $hl_ses->request(
500         'open-ils.search.fetch.metabib.display_field.highlight.atomic',
501         $self->ctx->{query_struct}{additional_data}{highlight_map},
502         @$rec_ids
503     ) if (!$is_meta);
504
505     if (@loop_recs) {
506         my $unapi_req = $ses->request(
507             'open-ils.cstore.json_query',
508              {from => [
509                 $unapi_type, '{'.join(',',@loop_recs).'}', 'marcxml', $flesh,
510                 $unapi_args->{site}, 
511                 $unapi_args->{depth}, 
512                 $slimit,
513                 undef, undef, undef, undef, undef, undef, undef, undef,
514                 $unapi_args->{pref_lib}
515             ]}
516         );
517     
518         my $data = $unapi_req->gather(1);
519     
520         $outer_self->timelog("get_records_and_facets(): got feed content");
521     
522         # Protect against requests for non-existent records
523         return unless ($data->{$unapi_type});
524     
525         my $doc = XML::LibXML->new->parse_string($data->{$unapi_type})->documentElement;
526     
527         $outer_self->timelog("get_records_and_facets(): parsed xml");
528         for my $xml ($doc->getElementsByTagName('record')) {
529             $xml = XML::LibXML->new->parse_string($xml->toString)->documentElement;
530     
531             # Protect against legacy invalid MARCXML that might not have a 901c
532             my $bre_id;
533             my $mmr_id;
534             my $bre_id_nodes =  $xml->find('*[@tag="901"]/*[@code="c"]');
535             if ($bre_id_nodes) {
536                 $bre_id =  $bre_id_nodes->[0]->textContent;
537             } else {
538                 $logger->warn("Missing 901 subfield 'c' in " . $xml->toString());
539             }
540         
541             if ($is_meta) {
542                 # extract metarecord ID from mmr.unapi tag
543                 for my $node ($xml->getElementsByTagName('abbr')) {
544                     my $title = $node->getAttribute('title');
545                     ($mmr_id = $title) =~ 
546                         s/tag:open-ils.org:U2\@mmr\/(\d+)\/.*/$1/g;
547                     last if $mmr_id;
548                 }
549             }
550         
551             my $rec_id = $mmr_id ? $mmr_id : $bre_id;
552             $tmp_data{$rec_id} = {
553                 id => $rec_id, 
554                 bre_id => $bre_id, 
555                 mmr_id => $mmr_id,
556                 marc_xml => $xml
557             };
558         
559             if ($rec_id) {
560                 # Let other backends grab our data now that we're done.
561                 my $key = 'TPAC_unapi_cache_'.$rec_id.'_'.$unapi_cache_key_suffix;
562                 my $cache_data = $unapi_cache->get_cache($key);
563                 if (!$cache_data || $$cache_data{running} == $$) {
564                     $unapi_cache->put_cache($key, {
565                         bre_id => $bre_id,
566                         mmr_id => $mmr_id,
567                         id => $rec_id, 
568                         marc_xml => $xml->toString
569                     }, 10);
570                 }
571             }
572         }
573     }
574
575     if (!$is_meta) {
576         my $hl_data = $hl_req->gather(1); # list of arrayref of hashrefs
577         $self->ctx->{_hl_data} = { map { ''.$$_[0]{source} => $_ } @$hl_data };
578         $outer_self->timelog("get_records_and_facets(): got highlighting content (". keys(%{$self->ctx->{_hl_data}}).")");
579     }
580
581     my $facets = {};
582     if ($facet_req) {
583         $self->timelog("get_records_and_facets():almost ready to fetch facets");
584
585         my $tmp_facets = $facet_req->gather(1);
586         $self->timelog("get_records_and_facets(): gathered facet data");
587         for my $cmf_id (keys %$tmp_facets) {
588
589             # sort highest to lowest match count
590             my @entries;
591             my $entries = $tmp_facets->{$cmf_id};
592             for my $ent (keys %$entries) {
593                 push(@entries, {value => $ent, count => $$entries{$ent}});
594             };
595
596             # Sort facet entries by 1) count descending, 2) text ascending
597             @entries = sort {
598                 $b->{count} <=> $a->{count} ||
599                 $a->{value} cmp $b->{value}
600             } @entries;
601
602             $facets->{$cmf_id} = {
603                 cmf => $self->ctx->{get_cmf}->($cmf_id),
604                 data => \@entries
605             }
606         }
607         $self->timelog("get_records_and_facets(): gathered/sorted facet data");
608     } else {
609         $facets = undef;
610     }
611     $search->kill_me;
612
613
614     return ($facets, map { $tmp_data{$_} } @$rec_ids);
615 }
616
617 sub _resolve_org_id_or_shortname {
618     my ($self, $str) = @_;
619
620     if (length $str) {
621         # Match on shortname case insensitively, but only if there's exactly
622         # one match.  We wouldn't want the system to arbitrarily interpret
623         # 'foo' as either the org unit with shortname 'FOO' or 'Foo' and fail
624         # to make it clear to the user which one was chosen and why.
625         my $res = $self->editor->search_actor_org_unit({
626             shortname => {
627                 '=' => {
628                     transform => 'evergreen.lowercase',
629                     value => lc($str)
630                 }
631             }
632         });
633         return $res->[0]->id if $res and @$res == 1;
634     }
635
636     # Note that we don't validate IDs; we only try a shortname lookup and then
637     # assume anything else must be an ID.
638     return int($str); # Wrapping in int() prevents 500 on unmatched string.
639 }
640
641 sub _get_search_lib {
642     my $self = shift;
643     my $ctx = $self->ctx;
644
645     # avoid duplicate lookups
646     return $ctx->{search_ou} if $ctx->{search_ou};
647
648     my $loc = $ctx->{copy_location_group_org};
649     return $loc if $loc;
650
651     # loc param takes precedence
652     # XXX ^-- over what exactly? We could use clarification here. To me it looks
653     # like locg takes precedence over loc which in turn takes precedence over
654     # request headers which take precedence over pref_lib (which can be
655     # specified a lot of different ways and eventually falls back to
656     # physical_loc) and it all finally defaults to top of the org tree.
657     # To say nothing of all the code that doesn't look to this function at all
658     # but rather accesses some subset of these inputs directly.
659
660     $loc = $self->cgi->param('loc');
661     return $loc if $loc;
662
663     if ($self->apache->headers_in->get('OILS-Search-Lib')) {
664         return $self->apache->headers_in->get('OILS-Search-Lib');
665     }
666     if ($self->cgi->cookie('eg_search_lib')) {
667         return $self->cgi->cookie('eg_search_lib');
668     }
669
670     my $pref_lib = $self->_get_pref_lib();
671     return $pref_lib if $pref_lib;
672
673     return $ctx->{aou_tree}->()->id;
674 }
675
676 sub _get_pref_lib {
677     my $self = shift;
678     my $ctx = $self->ctx;
679
680     # plib param takes precedence
681     my $plib = $self->cgi->param('plib');
682     return $plib if $plib;
683
684     if ($self->apache->headers_in->get('OILS-Pref-Lib')) {
685         return $self->apache->headers_in->get('OILS-Pref-Lib');
686     }
687     if ($self->cgi->cookie('eg_pref_lib')) {
688         return $self->cgi->cookie('eg_pref_lib');
689     }
690
691     if ($ctx->{user}) {
692         # See if the user has a search library preference
693         my $lset = $self->editor->search_actor_user_setting({
694             usr => $ctx->{user}->id, 
695             name => 'opac.default_search_location'
696         })->[0];
697         return OpenSRF::Utils::JSON->JSON2perl($lset->value) if $lset;
698
699         # Otherwise return the user's home library
700         my $ou = $ctx->{user}->home_ou;
701         return ref($ou) ? $ou->id : $ou;
702     }
703
704     if ($ctx->{physical_loc}) {
705         return $ctx->{physical_loc};
706     }
707
708 }
709
710 # This is defensively coded since we don't do much manual reading from the
711 # file system in this module.
712 sub load_eg_cache_hash {
713     my ($self) = @_;
714
715     # just a context helper
716     $self->ctx->{eg_cache_hash} = sub { return $cache{eg_cache_hash}; };
717
718     # Need to actually load the value? If already done, move on.
719     return if defined $cache{eg_cache_hash};
720
721     # In this way even if we fail, we won't slow things down by ever trying
722     # again within this Apache process' lifetime.
723     $cache{eg_cache_hash} = 0;
724
725     my $path = File::Spec->catfile(
726         $self->apache->document_root, "eg_cache_hash"
727     );
728
729     if (not open FH, "<$path") {
730         $self->apache->log->warn("error opening $path : $!");
731         return;
732     } else {
733         my $buf;
734         my $rv = read FH, $buf, 64;  # defensive
735         close FH;
736
737         if (not defined $rv) {  # error
738             $self->apache->log->warn("error reading $path : $!");
739         } elsif ($rv > 0) {     # no error, something read
740             chomp $buf;
741             $cache{eg_cache_hash} = $buf;
742         }
743     }
744 }
745
746 # Extracts the copy location org unit and group from the 
747 # "logc" param, which takes the form org_id:grp, where
748 # grp can either be a location group id or can match the
749 # pattern "lasso(lasso_name_or_id)".
750 sub extract_copy_location_group_info {
751     my $self = shift;
752     my $ctx = $self->ctx;
753     if (my $clump = $self->cgi->param('locg')) {
754         my ($org, $grp) = split(/:/, $clump);
755         if ($grp =~ /^lasso\(([^)]+)\)/) {
756             $ctx->{search_lasso} = $1;
757             $ctx->{search_scope} = $grp;
758             $self->search_lasso_orgs;
759         } elsif ($grp) {
760             $ctx->{copy_location_group} = $grp;
761             $ctx->{search_scope} = "location_groups($grp)";
762         }
763         $ctx->{copy_location_group_org} =
764             $self->_resolve_org_id_or_shortname($org);
765     }
766 }
767
768 sub load_copy_location_groups {
769     my $self = shift;
770     my $ctx = $self->ctx;
771
772     # User can access to the search location groups at the current 
773     # search lib, the physical location lib, and the patron's home ou.
774     my @ctx_orgs = $ctx->{search_ou};
775     push(@ctx_orgs, $ctx->{physical_loc}) if $ctx->{physical_loc};
776     push(@ctx_orgs, $ctx->{user}->home_ou) if $ctx->{user};
777
778     my $grps = $self->editor->search_asset_copy_location_group([
779         {
780             opac_visible => 't',
781             owner => {
782                 in => {
783                     select => {aou => [{
784                         column => 'id', 
785                         transform => 'actor.org_unit_full_path',
786                         result_field => 'id',
787                     }]},
788                     from => 'aou',
789                     where => {id => \@ctx_orgs}
790                 }
791             }
792         },
793         {order_by => {acplg => ['pos','name']}}
794     ]);
795
796     my %buckets;
797     push(@{$buckets{$_->owner}}, $_) for @$grps;
798     $ctx->{copy_location_groups} = \%buckets;
799 }
800
801 sub load_hold_subscriptions {
802     my $self = shift;
803     my $ctx = $self->ctx;
804
805     return unless $ctx->{authtoken};
806
807     my $e = new_editor(authtoken => $ctx->{authtoken});
808     $e->personality('open-ils.pcrud'); # use pcrud mode to filter appropriately
809
810     $ctx->{hold_subscriptions} =
811         $e->search_container_user_bucket([
812             { btype => 'hold_subscription' },
813             { order_by => {cub => 'name'} }
814         ]);
815
816 }
817
818 sub load_my_hold_subscriptions {
819     my $self = shift;
820     my $ctx = $self->ctx;
821
822     return unless $ctx->{authtoken};
823
824     my $sub_entries = $self->editor->search_container_user_bucket_item(
825         { target_user => $ctx->{user}->id }
826     );
827
828     my $sub_ids = [ uniq map { $_->bucket } @$sub_entries ];
829     $ctx->{my_hold_subscriptions} = scalar(@$sub_ids) ?
830         $self->editor->search_container_user_bucket(
831             {btype => 'hold_subscription', id => $sub_ids, pub => 't'}
832         ) : [];
833 }
834
835 sub search_lasso_orgs {
836     my $self = shift;
837     my $ctx = $self->ctx;
838     return $ctx->{search_lasso_orgs} if defined $ctx->{search_lasso_orgs};
839     return undef unless $ctx->{search_lasso};
840
841     # User can access global lassos and those at the current search lib
842     my $lasso_maps = $self->editor->search_actor_org_lasso_map(
843         { lasso => $ctx->{search_lasso} }
844     );
845     $ctx->{search_lasso_orgs} = [ map { $_->org_unit } @$lasso_maps];
846 }
847
848 sub load_lassos {
849     my $self = shift;
850     my $ctx = $self->ctx;
851
852     # User can access global lassos and those at the current search lib
853     my $direct_lassos = $self->editor->search_actor_org_lasso_map(
854         { org_unit => $ctx->{search_ou} }
855     );
856     $direct_lassos = [ map { $_->lasso } @$direct_lassos];
857
858     my $lassos = $self->editor->search_actor_org_lasso(
859         { '-or' => { global => 't', @$direct_lassos ? (id => { in => $direct_lassos}) : () } }
860     );
861
862     $ctx->{lassos} = [ sort { $a->name cmp $b->name } @$lassos ];
863     $self->apache->log->info("Fetched ".scalar(@$lassos)." lassos");
864 }
865
866 sub set_file_download_headers {
867     my $self = shift;
868     my $filename = shift;
869     my $ctype = shift || "text/plain; encoding=utf8";
870
871     $self->apache->content_type($ctype);
872
873     $self->apache->headers_out->add(
874         "Content-Disposition",
875         "attachment;filename=$filename"
876     );
877
878     return Apache2::Const::OK;
879 }
880
881 sub apache_log_if_event {
882     my ($self, $event, $prefix_text, $success_ok, $level) = @_;
883
884     $prefix_text ||= "Evergreen returned event";
885     $success_ok ||= 0;
886     $level ||= "warn";
887
888     chomp $prefix_text;
889     $prefix_text .= ": ";
890
891     my $code = $U->event_code($event);
892     if (defined $code and ($code or not $success_ok)) {
893         $self->apache->log->$level(
894             $prefix_text .
895             ($event->{textcode} || "") . " ($code)" .
896             ($event->{note} ? (": " . $event->{note}) : "")
897         );
898         return 1;
899     }
900
901     return;
902 }
903
904 sub load_search_filter_groups {
905     my $self = shift;
906     my $ctx_org = shift;
907     my $org_list = $U->get_org_ancestors($ctx_org, 1);
908
909     my %seen;
910     for my $org_id (@$org_list) {
911
912         my $grps;
913         if (! ($grps = $cache{search_filter_groups}{$org_id}) ) {
914             $grps = $self->editor->search_actor_search_filter_group([
915                 {owner => $org_id},
916                 {   flesh => 2, 
917                     flesh_fields => {
918                         asfg => ['entries'],
919                         asfge => ['query']
920                     },
921                     order_by => {asfge => 'pos'}
922                 }
923             ]);
924             $cache{search_filter_groups}{$org_id} = $grps;
925         }
926
927         # for the current context, if a descendant org has a group 
928         # with a matching code replace the group from the parent.
929         $seen{$_->code} = $_ for @$grps;
930     }
931
932     return $self->ctx->{search_filter_groups} = \%seen;
933 }
934
935
936 sub check_for_temp_list_warning {
937     my $self = shift;
938     my $ctx = $self->ctx;
939     my $cgi = $self->cgi;
940
941     my $lib = $self->_get_search_lib;
942     my $warn = ($ctx->{get_org_setting}->($lib || 1, 'opac.patron.temporary_list_warn')) ? 1 : 0;
943
944     if ($warn && $ctx->{user}) {
945         $self->_load_user_with_prefs;
946         my $map = $ctx->{user_setting_map};
947         $warn = 0 if ($$map{'opac.temporary_list_no_warn'});
948     }
949
950     # Check for a cookie disabling the warning.
951     $warn = 0 if ($warn && $cgi->cookie('no_temp_list_warn'));
952
953     return $warn;
954 }
955
956 sub load_org_util_funcs {
957     my $self = shift;
958     my $ctx = $self->ctx;
959
960     # evaluates to true if test_ou is within the same depth-
961     # scoped tree as ctx_ou. both ou's are org unit objects.
962     $ctx->{org_within_scope} = sub {
963         my ($ctx_ou, $test_ou, $depth) = @_;
964
965         return 1 if $ctx_ou->id == $test_ou->id;
966
967         if ($depth) {
968
969             # find the top-most ctx-org ancestor at the provided depth
970             while ($depth < $ctx_ou->ou_type->depth 
971                     and $ctx_ou->id != $test_ou->id) {
972                 $ctx_ou = $ctx->{get_aou}->($ctx_ou->parent_ou);
973             }
974
975             # the preceeding loop may have landed on our org
976             return 1 if $ctx_ou->id == $test_ou->id;
977
978         } else {
979
980             return 1 if defined $depth; # $depth == 0;
981         }
982
983         for my $child (@{$ctx_ou->children}) {
984             return 1 if $ctx->{org_within_scope}->($child, $test_ou);
985         }
986
987         return 0;
988     };
989
990     # Returns true if the provided org unit is within the same 
991     # org unit hiding depth-scoped tree as the physical location.
992     # Org unit hiding is based on the immutable physical_loc
993     # and is not meant to change as search/pref/etc libs change
994     $ctx->{org_within_hiding_scope} = sub {
995         my $org_id = shift;
996         my $ploc = $ctx->{physical_loc} or return 1;
997
998         my $depth = $ctx->{get_org_setting}->(
999             $ploc, 'opac.org_unit_hiding.depth');
1000
1001         return 1 unless $depth; # 0 or undef
1002
1003         return $ctx->{org_within_scope}->( 
1004             $ctx->{get_aou}->($ploc), 
1005             $ctx->{get_aou}->($org_id), $depth);
1006  
1007     };
1008
1009     # Evaluates to true if the context org (defaults to get_library) 
1010     # is not within the hiding scope.  Also evaluates to true if the 
1011     # user's pref_ou is set and it's out of hiding scope.
1012     # Always evaluates to true when ctx.is_staff
1013     $ctx->{org_hiding_disabled} = sub {
1014         my $ctx_org = shift || $ctx->{search_ou};
1015
1016         return 1 if $ctx->{is_staff};
1017
1018         # beware locg values formatted as org:loc
1019         $ctx_org =~ s/:.*//g;
1020
1021         return 1 if !$ctx->{org_within_hiding_scope}->($ctx_org);
1022
1023         return 1 if $ctx->{pref_ou} and $ctx->{pref_ou} != $ctx_org 
1024             and !$ctx->{org_within_hiding_scope}->($ctx->{pref_ou});
1025
1026         return 0;
1027     };
1028
1029 }
1030
1031 # returns the list of org unit IDs for which the 
1032 # selected org unit setting returned a true value
1033 sub setting_is_true_for_orgs {
1034     my ($self, $setting) = @_;
1035     my $ctx = $self->ctx;
1036     my @valid_orgs;
1037
1038     my $test_org;
1039     $test_org = sub {
1040         my $org = shift;
1041         push (@valid_orgs, $org->id) if
1042             $ctx->{get_org_setting}->($org->id, $setting);
1043         $test_org->($_) for @{$org->children};
1044     };
1045
1046     $test_org->($ctx->{aou_tree}->());
1047     return \@valid_orgs;
1048 }
1049
1050 # Builds and links a perm checking function, testing permissions against
1051 # the currently logged in user.  
1052 # ctx->{has_perm}->(perm_code, org_id) => 1/undef
1053 # For security, perm checks are cached per page, not per process.
1054 sub load_perm_funcs {
1055     my $self = shift;
1056     my %perm_cache;
1057     $self->ctx->{has_perm} = sub {
1058         my ($perm_code, $org_id) = @_;
1059         return 0 unless $self->editor->requestor;
1060
1061         if ($perm_cache{$org_id}) {
1062             return $perm_cache{$org_id}{$perm_code} 
1063                 if exists $perm_cache{$org_id}{$perm_code};
1064         } else {
1065             $perm_cache{$org_id} = {};
1066         }
1067         return $perm_cache{$org_id}{$perm_code} =
1068             $self->editor->allowed($perm_code, $org_id);
1069     }
1070 }
1071     
1072
1073
1074 1;