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