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);
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;
13 my $U = 'OpenILS::Application::AppUtils';
15 my $ro_object_subs; # cached subs
16 our %cache = ( # cached data
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},
24 eg_cache_hash => undef,
25 authority_fields => {en_us => {}}
32 # create a stub object with just enough in place
33 # to call init_ro_object_cache()
34 my $stub = bless({}, ref($class) || $class);
38 foreach my $locale (sort keys %locales) {
39 OpenSRF::AppSession->default_locale($locales{$locale});
40 $ctx->{locale} = $locale;
41 $stub->init_ro_object_cache();
43 # pre-cache various sets of objects
44 # known to be time-consuming to retrieve
46 $ro_object_subs->{$locale}->{aou_tree}();
47 $ro_object_subs->{$locale}->{aouct_tree}();
48 $ro_object_subs->{$locale}->{ccvm_list}();
49 $ro_object_subs->{$locale}->{crad_list}();
50 $ro_object_subs->{$locale}->{get_authority_fields}(1);
54 sub init_ro_object_cache {
57 my $memcache ||= OpenSRF::Utils::Cache->new('global');
59 # reset org unit setting cache on each page load to avoid the
60 # requirement of reloading apache with each org-setting change
61 $cache{org_settings} = {};
63 if($ro_object_subs->{$ctx->{locale}}) {
64 # subs have been built. insert into the context then move along.
65 $ctx->{$_} = $ro_object_subs->{$ctx->{locale}}->{$_} for keys %{ $ro_object_subs->{$ctx->{locale}} };
70 my $locale = $ctx->{locale};
72 # make all "field_safe" classes accesible by default in the template context
74 ($Fieldmapper::fieldmap->{$_}->{field_safe} || '') =~ /true/i
75 } keys %{ $Fieldmapper::fieldmap };
77 for my $class (@classes) {
79 my $hint = $Fieldmapper::fieldmap->{$class}->{hint};
80 next if $hint eq 'aou'; # handled separately
82 my $ident_field = $Fieldmapper::fieldmap->{$class}->{identity};
83 (my $eclass = $class) =~ s/Fieldmapper:://o;
86 my $list_key = "${hint}_list";
87 my $get_key = "get_$hint";
88 my $search_key = "search_$hint";
90 my $memcache_key = join('.', 'EGWeb',$locale,$hint) . '.';
92 # Retrieve the full set of objects with class $hint
93 $locale_subs->{$list_key} = sub {
94 my $from_memcache = 0;
95 my $list = $memcache->get_cache($memcache_key.'list');
97 $cache{list}{$locale}{$hint} = $list;
100 my $method = "retrieve_all_$eclass";
101 my $e = new_editor();
102 $cache{list}{$locale}{$hint} = $e->$method() unless $cache{list}{$locale}{$hint};
104 $memcache->put_cache($memcache_key.'list',$cache{list}{$locale}{$hint}) unless $from_memcache;
105 return $cache{list}{$locale}{$hint};
108 # locate object of class $hint with Ident field $id
109 $cache{map}{$hint} = {};
110 $locale_subs->{$get_key} = sub {
112 return $cache{map}{$locale}{$hint}{$id} if $cache{map}{$locale}{$hint}{$id};
113 ($cache{map}{$locale}{$hint}{$id}) = grep { $_->$ident_field eq $id } @{$locale_subs->{$list_key}->()};
114 return $cache{map}{$locale}{$hint}{$id};
117 # search for objects of class $hint where field=value
118 $cache{search}{$hint} = {};
119 $locale_subs->{$search_key} = sub {
120 my ($field, $val, $filterfield, $filterval) = @_;
121 my $method = "search_$eclass";
123 my $scalar_cacheval = 1;
126 $scalar_cacheval = 0;
127 $val = [sort(@$val)] if ref $val eq 'ARRAY';
128 $cacheval = OpenSRF::Utils::JSON->perl2JSON($val);
129 #$self->apache->log->info("cacheval : $cacheval");
132 my $search_obj = {$field => $val};
134 $search_obj->{$filterfield} = $filterval;
135 $cacheval .= ':' . $filterfield . ':' . $filterval;
138 and $cache{list}{$locale}{$hint}
139 and !$cache{search}{$locale}{$hint}{$field}{$cacheval}
141 return $cache{search}{$locale}{$hint}{$field}{$cacheval} =
142 [ grep { $_->$field() eq $val } @{$cache{list}{$locale}{$hint}} ];
145 my $e = new_editor();
146 $cache{search}{$locale}{$hint}{$field}{$cacheval} = $e->$method($search_obj)
147 unless $cache{search}{$locale}{$hint}{$field}{$cacheval};
149 return $cache{search}{$locale}{$hint}{$field}{$cacheval};
153 $locale_subs->{aou_tree} = sub {
155 # fetch the org unit tree
156 unless($cache{aou_tree}{$locale}) {
157 my $e = new_editor();
158 my $tree = $e->search_actor_org_unit([
159 { parent_ou => undef},
161 flesh_fields => {aou => ['children']},
162 order_by => {aou => 'name'}
166 # flesh the org unit type for each org unit
167 # and simultaneously set the id => aou map cache
170 my $locale_subs = shift;
172 $node->ou_type( $locale_subs->{get_aout}->($node->ou_type) );
173 $cache{map}{$locale}{aou}{$node->id} = $node;
174 flesh_aout($_, $locale_subs, $locale) foreach @{$node->children};
176 flesh_aout($tree, $locale_subs, $locale);
178 $cache{aou_tree}{$locale} = $tree;
181 return $cache{aou_tree}{$locale};
184 # Add a special handler for the tree-shaped org unit cache
185 $locale_subs->{get_aou} = sub {
187 return undef unless defined $org_id;
188 $locale_subs->{aou_tree}->(); # force the org tree to load
189 return $cache{map}{$locale}{aou}{$org_id};
192 # Returns a flat list of aou objects. often easier to manage than a tree.
193 $locale_subs->{aou_list} = sub {
194 $locale_subs->{aou_tree}->(); # force the org tree to load
195 return [ values %{$cache{map}{$locale}{aou}} ];
198 # returns the org unit object by shortname
199 $locale_subs->{get_aou_by_shortname} = sub {
200 my $sn = shift or return undef;
201 my $list = $locale_subs->{aou_list}->();
202 return (grep {$_->shortname eq $sn} @$list)[0];
205 $locale_subs->{aouct_tree} = sub {
207 # fetch the org unit tree
208 unless(exists $cache{aouct_tree}{$locale}) {
209 $cache{aouct_tree}{$locale} = undef;
211 my $e = new_editor();
212 my $tree_id = $e->search_actor_org_unit_custom_tree(
213 {purpose => 'opac', active => 't'},
218 my $node_tree = $e->search_actor_org_unit_custom_tree_node([
219 {parent_node => undef, tree => $tree_id},
221 flesh_fields => {aouctn => ['children', 'org_unit']},
222 order_by => {aouctn => 'sibling_order'}
226 # tree-ify the org units. note that since the orgs are fleshed
227 # upon retrieval, this org tree will not clobber ctx->{aou_tree}.
228 my @nodes = ($node_tree);
229 while (my $node = shift(@nodes)) {
230 my $aou = $node->org_unit;
232 for my $cnode (@{$node->children}) {
233 my $child_org = $cnode->org_unit;
234 $child_org->parent_ou($aou->id);
235 $child_org->ou_type( $locale_subs->{get_aout}->($child_org->ou_type) );
236 push(@{$aou->children}, $child_org);
237 push(@nodes, $cnode);
241 $cache{aouct_tree}{$locale} =
242 $node_tree->org_unit if $node_tree;
247 return $cache{aouct_tree}{$locale};
250 # turns an ISO date into something TT can understand
251 $locale_subs->{parse_datetime} = sub {
253 my $context_org = shift; # optional, for setting timezone via YAOUS
255 # Calling parse_datetime() with empty $date will lead to Internal Server Error
256 return '' if (!defined($date) or $date eq '');
258 # Probably an accidental entry like '0212' instead of '2012',
259 # but 1) the leading 0 may get stripped in cstore and
260 # 2) DateTime::Format::ISO8601 returns an error as years
261 # must be 2 or 4 digits
262 if ($date =~ m/^\d{3}-/) {
263 $logger->warn("Invalid date had a 3-digit year: $date");
265 } elsif ($date =~ m/^\d{1}-/) {
266 $logger->warn("Invalid date had a 1-digit year: $date");
267 $date = '000' . $date;
270 my $cleansed_date = clean_ISO8601($date);
272 $date = DateTime::Format::ISO8601->new->parse_datetime($cleansed_date);
274 $context_org = $context_org->id if ref($context_org);
275 my $tz = $locale_subs->{get_org_setting}->($context_org,'lib.timezone');
278 $date->set_time_zone($tz);
280 $logger->warn("Invalid timezone: $tz");
285 "%0.2d:%0.2d:%0.2d %0.2d-%0.2d-%0.4d",
295 # retrieve and cache org unit setting values
296 $locale_subs->{get_org_setting} = sub {
297 my($org_id, $setting) = @_;
299 $cache{org_settings}{$locale}{$org_id}{$setting} =
300 $U->ou_ancestor_setting_value($org_id, $setting)
301 unless exists $cache{org_settings}{$locale}{$org_id}{$setting};
303 return $cache{org_settings}{$locale}{$org_id}{$setting};
306 # retrieve and cache acsaf values
307 $locale_subs->{get_authority_fields} = sub {
308 my ($control_set) = @_;
310 if (not exists $cache{authority_fields}{$locale}{$control_set}) {
311 my $e = new_editor();
312 if (my $acs = $e->search_authority_control_set_authority_field(
313 {control_set => $control_set}
316 $cache{authority_fields}{$locale}{$control_set} =
317 +{ map { $_->id => $_ } @$acs };
325 return $cache{authority_fields}{$locale}{$control_set};
328 $ctx->{$_} = $locale_subs->{$_} for keys %$locale_subs;
329 $ro_object_subs->{$locale} = $locale_subs;
332 sub generic_redirect {
335 my $cookie = shift; # can be an array of cgi.cookie's
337 $self->apache->print(
338 $self->cgi->redirect(
340 $self->cgi->param('redirect_to') ||
341 $self->ctx->{referer} ||
342 $self->ctx->{home_page},
347 return Apache2::Const::REDIRECT;
351 sub get_records_and_facets {
352 my ($self, $rec_ids, $facet_key, $unapi_args) = @_;
354 # collect the facet data
355 my $search = OpenSRF::AppSession->create('open-ils.search');
358 $facet_req = $search->request(
359 'open-ils.search.facet_cache.retrieve', $facet_key
364 $unapi_args->{site} ||= $self->ctx->{aou_tree}->()->shortname;
365 $unapi_args->{depth} ||= $self->ctx->{aou_tree}->()->ou_type->depth;
366 $unapi_args->{flesh_depth} ||= 5;
368 my $is_meta = delete $unapi_args->{metarecord};
369 #my $unapi_type = $is_meta ? 'unapi.mmr' : 'unapi.bre';
370 my $unapi_type = $is_meta ? 'unapi.metabib_virtual_record_feed' : 'unapi.biblio_record_entry_feed';
372 $unapi_cache ||= OpenSRF::Utils::Cache->new('global');
373 my $unapi_cache_key_suffix = join(
377 $unapi_args->{depth},
378 $unapi_args->{flesh_depth},
379 ($unapi_args->{pref_lib} || '')
384 my $outer_self = $self;
386 my $sdepth = $unapi_args->{flesh_depth};
387 my $slimit = "acn=>$sdepth,acp=>$sdepth";
388 $slimit .= ",bre=>$sdepth" if $is_meta;
389 my $flesh = $unapi_args->{flesh} || '';
391 # tag the record with the MR id
392 $flesh =~ s/}$/,mmr.unapi}/g if $is_meta;
394 my $ses = OpenSRF::AppSession->create('open-ils.cstore');
395 my $hl_ses = OpenSRF::AppSession->create('open-ils.search');
398 for my $bid (@$rec_ids) {
399 my $unapi_cache_key = 'TPAC_unapi_cache_'.$bid.'_'.$unapi_cache_key_suffix;
400 my $unapi_data = $unapi_cache->get_cache($unapi_cache_key);
402 if (!$unapi_data || $unapi_data->{running}) { #cache entry not done yet, get our own copy
403 push(@loop_recs, $bid);
405 $unapi_data->{marc_xml} = XML::LibXML->new->parse_string($unapi_data->{marc_xml})->documentElement;
406 $tmp_data{$unapi_data->{id}} = $unapi_data;
407 $unapi_cache->put_cache($unapi_cache_key, { running => $$ }, 5);
411 my $hl_req = $hl_ses->request(
412 'open-ils.search.fetch.metabib.display_field.highlight.atomic',
413 $self->ctx->{query_struct}{additional_data}{highlight_map},
418 my $unapi_req = $ses->request(
419 'open-ils.cstore.json_query',
421 $unapi_type, '{'.join(',',@loop_recs).'}', 'marcxml', $flesh,
423 $unapi_args->{depth},
425 undef, undef, undef, undef, undef, undef, undef, undef,
426 $unapi_args->{pref_lib}
430 my $data = $unapi_req->gather(1);
432 $outer_self->timelog("get_records_and_facets(): got feed content");
434 # Protect against requests for non-existent records
435 return unless ($data->{$unapi_type});
437 my $doc = XML::LibXML->new->parse_string($data->{$unapi_type})->documentElement;
439 $outer_self->timelog("get_records_and_facets(): parsed xml");
440 for my $xml ($doc->getElementsByTagName('record')) {
441 $xml = XML::LibXML->new->parse_string($xml->toString)->documentElement;
443 # Protect against legacy invalid MARCXML that might not have a 901c
446 my $bre_id_nodes = $xml->find('*[@tag="901"]/*[@code="c"]');
448 $bre_id = $bre_id_nodes->[0]->textContent;
450 $logger->warn("Missing 901 subfield 'c' in " . $xml->toString());
454 # extract metarecord ID from mmr.unapi tag
455 for my $node ($xml->getElementsByTagName('abbr')) {
456 my $title = $node->getAttribute('title');
457 ($mmr_id = $title) =~
458 s/tag:open-ils.org:U2\@mmr\/(\d+)\/.*/$1/g;
463 my $rec_id = $mmr_id ? $mmr_id : $bre_id;
464 $tmp_data{$rec_id} = {
472 # Let other backends grab our data now that we're done.
473 my $key = 'TPAC_unapi_cache_'.$rec_id.'_'.$unapi_cache_key_suffix;
474 my $cache_data = $unapi_cache->get_cache($key);
475 if (!$cache_data || $$cache_data{running} == $$) {
476 $unapi_cache->put_cache($key, {
480 marc_xml => $xml->toString
488 my $hl_data = $hl_req->gather(1); # list of arrayref of hashrefs
489 $self->ctx->{_hl_data} = { map { ''.$$_[0]{source} => $_ } @$hl_data };
490 $outer_self->timelog("get_records_and_facets(): got highlighting content (". keys(%{$self->ctx->{_hl_data}}).")");
495 $self->timelog("get_records_and_facets():almost ready to fetch facets");
497 my $tmp_facets = $facet_req->gather(1);
498 $self->timelog("get_records_and_facets(): gathered facet data");
499 for my $cmf_id (keys %$tmp_facets) {
501 # sort highest to lowest match count
503 my $entries = $tmp_facets->{$cmf_id};
504 for my $ent (keys %$entries) {
505 push(@entries, {value => $ent, count => $$entries{$ent}});
508 # Sort facet entries by 1) count descending, 2) text ascending
510 $b->{count} <=> $a->{count} ||
511 $a->{value} cmp $b->{value}
514 $facets->{$cmf_id} = {
515 cmf => $self->ctx->{get_cmf}->($cmf_id),
519 $self->timelog("get_records_and_facets(): gathered/sorted facet data");
526 return ($facets, map { $tmp_data{$_} } @$rec_ids);
529 sub _resolve_org_id_or_shortname {
530 my ($self, $str) = @_;
533 # Match on shortname case insensitively, but only if there's exactly
534 # one match. We wouldn't want the system to arbitrarily interpret
535 # 'foo' as either the org unit with shortname 'FOO' or 'Foo' and fail
536 # to make it clear to the user which one was chosen and why.
537 my $res = $self->editor->search_actor_org_unit({
540 transform => 'evergreen.lowercase',
545 return $res->[0]->id if $res and @$res == 1;
548 # Note that we don't validate IDs; we only try a shortname lookup and then
549 # assume anything else must be an ID.
550 return int($str); # Wrapping in int() prevents 500 on unmatched string.
553 sub _get_search_lib {
555 my $ctx = $self->ctx;
557 # avoid duplicate lookups
558 return $ctx->{search_ou} if $ctx->{search_ou};
560 my $loc = $ctx->{copy_location_group_org};
563 # loc param takes precedence
564 # XXX ^-- over what exactly? We could use clarification here. To me it looks
565 # like locg takes precedence over loc which in turn takes precedence over
566 # request headers which take precedence over pref_lib (which can be
567 # specified a lot of different ways and eventually falls back to
568 # physical_loc) and it all finally defaults to top of the org tree.
569 # To say nothing of all the code that doesn't look to this function at all
570 # but rather accesses some subset of these inputs directly.
572 $loc = $self->cgi->param('loc');
575 if ($self->apache->headers_in->get('OILS-Search-Lib')) {
576 return $self->apache->headers_in->get('OILS-Search-Lib');
578 if ($self->cgi->cookie('eg_search_lib')) {
579 return $self->cgi->cookie('eg_search_lib');
582 my $pref_lib = $self->_get_pref_lib();
583 return $pref_lib if $pref_lib;
585 return $ctx->{aou_tree}->()->id;
590 my $ctx = $self->ctx;
592 # plib param takes precedence
593 my $plib = $self->cgi->param('plib');
594 return $plib if $plib;
596 if ($self->apache->headers_in->get('OILS-Pref-Lib')) {
597 return $self->apache->headers_in->get('OILS-Pref-Lib');
599 if ($self->cgi->cookie('eg_pref_lib')) {
600 return $self->cgi->cookie('eg_pref_lib');
604 # See if the user has a search library preference
605 my $lset = $self->editor->search_actor_user_setting({
606 usr => $ctx->{user}->id,
607 name => 'opac.default_search_location'
609 return OpenSRF::Utils::JSON->JSON2perl($lset->value) if $lset;
611 # Otherwise return the user's home library
612 my $ou = $ctx->{user}->home_ou;
613 return ref($ou) ? $ou->id : $ou;
616 if ($ctx->{physical_loc}) {
617 return $ctx->{physical_loc};
622 # This is defensively coded since we don't do much manual reading from the
623 # file system in this module.
624 sub load_eg_cache_hash {
627 # just a context helper
628 $self->ctx->{eg_cache_hash} = sub { return $cache{eg_cache_hash}; };
630 # Need to actually load the value? If already done, move on.
631 return if defined $cache{eg_cache_hash};
633 # In this way even if we fail, we won't slow things down by ever trying
634 # again within this Apache process' lifetime.
635 $cache{eg_cache_hash} = 0;
637 my $path = File::Spec->catfile(
638 $self->apache->document_root, "eg_cache_hash"
641 if (not open FH, "<$path") {
642 $self->apache->log->warn("error opening $path : $!");
646 my $rv = read FH, $buf, 64; # defensive
649 if (not defined $rv) { # error
650 $self->apache->log->warn("error reading $path : $!");
651 } elsif ($rv > 0) { # no error, something read
653 $cache{eg_cache_hash} = $buf;
658 # Extracts the copy location org unit and group from the
659 # "logc" param, which takes the form org_id:grp_id.
660 sub extract_copy_location_group_info {
662 my $ctx = $self->ctx;
663 if (my $clump = $self->cgi->param('locg')) {
664 my ($org, $grp) = split(/:/, $clump);
665 $ctx->{copy_location_group_org} =
666 $self->_resolve_org_id_or_shortname($org);
667 $ctx->{copy_location_group} = $grp if $grp;
671 sub load_copy_location_groups {
673 my $ctx = $self->ctx;
675 # User can access to the search location groups at the current
676 # search lib, the physical location lib, and the patron's home ou.
677 my @ctx_orgs = $ctx->{search_ou};
678 push(@ctx_orgs, $ctx->{physical_loc}) if $ctx->{physical_loc};
679 push(@ctx_orgs, $ctx->{user}->home_ou) if $ctx->{user};
681 my $grps = $self->editor->search_asset_copy_location_group([
688 transform => 'actor.org_unit_full_path',
689 result_field => 'id',
692 where => {id => \@ctx_orgs}
696 {order_by => {acplg => 'pos'}}
700 push(@{$buckets{$_->owner}}, $_) for @$grps;
701 $ctx->{copy_location_groups} = \%buckets;
704 sub set_file_download_headers {
706 my $filename = shift;
707 my $ctype = shift || "text/plain; encoding=utf8";
709 $self->apache->content_type($ctype);
711 $self->apache->headers_out->add(
712 "Content-Disposition",
713 "attachment;filename=$filename"
716 return Apache2::Const::OK;
719 sub apache_log_if_event {
720 my ($self, $event, $prefix_text, $success_ok, $level) = @_;
722 $prefix_text ||= "Evergreen returned event";
727 $prefix_text .= ": ";
729 my $code = $U->event_code($event);
730 if (defined $code and ($code or not $success_ok)) {
731 $self->apache->log->$level(
733 ($event->{textcode} || "") . " ($code)" .
734 ($event->{note} ? (": " . $event->{note}) : "")
742 sub load_search_filter_groups {
745 my $org_list = $U->get_org_ancestors($ctx_org, 1);
748 for my $org_id (@$org_list) {
751 if (! ($grps = $cache{search_filter_groups}{$org_id}) ) {
752 $grps = $self->editor->search_actor_search_filter_group([
759 order_by => {asfge => 'pos'}
762 $cache{search_filter_groups}{$org_id} = $grps;
765 # for the current context, if a descendant org has a group
766 # with a matching code replace the group from the parent.
767 $seen{$_->code} = $_ for @$grps;
770 return $self->ctx->{search_filter_groups} = \%seen;
774 sub check_for_temp_list_warning {
776 my $ctx = $self->ctx;
777 my $cgi = $self->cgi;
779 my $lib = $self->_get_search_lib;
780 my $warn = ($ctx->{get_org_setting}->($lib || 1, 'opac.patron.temporary_list_warn')) ? 1 : 0;
782 if ($warn && $ctx->{user}) {
783 $self->_load_user_with_prefs;
784 my $map = $ctx->{user_setting_map};
785 $warn = 0 if ($$map{'opac.temporary_list_no_warn'});
788 # Check for a cookie disabling the warning.
789 $warn = 0 if ($warn && $cgi->cookie('no_temp_list_warn'));
794 sub load_org_util_funcs {
796 my $ctx = $self->ctx;
798 # evaluates to true if test_ou is within the same depth-
799 # scoped tree as ctx_ou. both ou's are org unit objects.
800 $ctx->{org_within_scope} = sub {
801 my ($ctx_ou, $test_ou, $depth) = @_;
803 return 1 if $ctx_ou->id == $test_ou->id;
807 # find the top-most ctx-org ancestor at the provided depth
808 while ($depth < $ctx_ou->ou_type->depth
809 and $ctx_ou->id != $test_ou->id) {
810 $ctx_ou = $ctx->{get_aou}->($ctx_ou->parent_ou);
813 # the preceeding loop may have landed on our org
814 return 1 if $ctx_ou->id == $test_ou->id;
818 return 1 if defined $depth; # $depth == 0;
821 for my $child (@{$ctx_ou->children}) {
822 return 1 if $ctx->{org_within_scope}->($child, $test_ou);
828 # Returns true if the provided org unit is within the same
829 # org unit hiding depth-scoped tree as the physical location.
830 # Org unit hiding is based on the immutable physical_loc
831 # and is not meant to change as search/pref/etc libs change
832 $ctx->{org_within_hiding_scope} = sub {
834 my $ploc = $ctx->{physical_loc} or return 1;
836 my $depth = $ctx->{get_org_setting}->(
837 $ploc, 'opac.org_unit_hiding.depth');
839 return 1 unless $depth; # 0 or undef
841 return $ctx->{org_within_scope}->(
842 $ctx->{get_aou}->($ploc),
843 $ctx->{get_aou}->($org_id), $depth);
847 # Evaluates to true if the context org (defaults to get_library)
848 # is not within the hiding scope. Also evaluates to true if the
849 # user's pref_ou is set and it's out of hiding scope.
850 # Always evaluates to true when ctx.is_staff
851 $ctx->{org_hiding_disabled} = sub {
852 my $ctx_org = shift || $ctx->{search_ou};
854 return 1 if $ctx->{is_staff};
856 # beware locg values formatted as org:loc
857 $ctx_org =~ s/:.*//g;
859 return 1 if !$ctx->{org_within_hiding_scope}->($ctx_org);
861 return 1 if $ctx->{pref_ou} and $ctx->{pref_ou} != $ctx_org
862 and !$ctx->{org_within_hiding_scope}->($ctx->{pref_ou});
869 # returns the list of org unit IDs for which the
870 # selected org unit setting returned a true value
871 sub setting_is_true_for_orgs {
872 my ($self, $setting) = @_;
873 my $ctx = $self->ctx;
879 push (@valid_orgs, $org->id) if
880 $ctx->{get_org_setting}->($org->id, $setting);
881 $test_org->($_) for @{$org->children};
884 $test_org->($ctx->{aou_tree}->());
888 # Builds and links a perm checking function, testing permissions against
889 # the currently logged in user.
890 # ctx->{has_perm}->(perm_code, org_id) => 1/undef
891 # For security, perm checks are cached per page, not per process.
892 sub load_perm_funcs {
895 $self->ctx->{has_perm} = sub {
896 my ($perm_code, $org_id) = @_;
897 return 0 unless $self->editor->requestor;
899 if ($perm_cache{$org_id}) {
900 return $perm_cache{$org_id}{$perm_code}
901 if exists $perm_cache{$org_id}{$perm_code};
903 $perm_cache{$org_id} = {};
905 return $perm_cache{$org_id}{$perm_code} =
906 $self->editor->allowed($perm_code, $org_id);