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