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