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