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