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