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