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