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 List::MoreUtils qw(uniq);
7 use OpenSRF::Utils::Cache;
8 use OpenSRF::Utils::Logger qw/$logger/;
9 use OpenILS::Utils::CStoreEditor qw/:funcs/;
10 use OpenILS::Utils::Fieldmapper;
11 use OpenILS::Application::AppUtils;
12 use OpenSRF::MultiSession;
14 my $U = 'OpenILS::Application::AppUtils';
16 my $ro_object_subs; # cached subs
17 our %cache = ( # cached data
19 list => {en_us => {}},
20 search => {en_us => {}},
21 org_settings => {en_us => {}},
22 search_filter_groups => {en_us => {}},
23 aou_tree => {en_us => undef},
25 eg_cache_hash => undef,
26 authority_fields => {en_us => {}}
33 # create a stub object with just enough in place
34 # to call init_ro_object_cache()
35 my $stub = bless({}, ref($class) || $class);
39 foreach my $locale (sort keys %locales) {
40 OpenSRF::AppSession->default_locale($locales{$locale});
41 $ctx->{locale} = $locale;
42 $stub->init_ro_object_cache();
44 # pre-cache various sets of objects
45 # known to be time-consuming to retrieve
47 $ro_object_subs->{$locale}->{aou_tree}();
48 $ro_object_subs->{$locale}->{aouct_tree}();
49 $ro_object_subs->{$locale}->{ccvm_list}();
50 $ro_object_subs->{$locale}->{crad_list}();
51 $ro_object_subs->{$locale}->{get_authority_fields}(1);
55 sub init_ro_object_cache {
58 my $memcache ||= OpenSRF::Utils::Cache->new('global');
60 # reset org unit setting cache on each page load to avoid the
61 # requirement of reloading apache with each org-setting change
62 $cache{org_settings} = {};
64 if($ro_object_subs->{$ctx->{locale}}) {
65 # subs have been built. insert into the context then move along.
66 $ctx->{$_} = $ro_object_subs->{$ctx->{locale}}->{$_} for keys %{ $ro_object_subs->{$ctx->{locale}} };
71 my $locale = $ctx->{locale};
73 # Create special-purpose subs
75 # aou is special because it's tree-ish
76 $locale_subs->{aou_tree} = sub {
78 # fetch the org unit tree
79 unless($cache{aou_tree}{$locale}) {
81 my $tree = $e->search_actor_org_unit([
82 { parent_ou => undef},
84 flesh_fields => {aou => ['children']},
85 order_by => {aou => 'name'}
89 # flesh the org unit type for each org unit
90 # and simultaneously set the id => aou map cache
93 my $locale_subs = shift;
95 $node->ou_type( $locale_subs->{get_aout}->($node->ou_type) );
96 $cache{map}{$locale}{aou}{$node->id} = $node;
97 flesh_aout($_, $locale_subs, $locale) foreach @{$node->children};
99 flesh_aout($tree, $locale_subs, $locale);
101 $cache{aou_tree}{$locale} = $tree;
104 return $cache{aou_tree}{$locale};
107 # Add a special handler for the tree-shaped org unit cache
108 $locale_subs->{get_aou} = sub {
110 return undef unless defined $org_id;
111 $locale_subs->{aou_tree}->(); # force the org tree to load
112 return $cache{map}{$locale}{aou}{$org_id};
115 # Returns a flat list of aout objects, sorted by depth and opac_label.
116 $locale_subs->{sorted_aout_list} = sub {
117 return [ sort { $a->depth() <=> $b->depth() || $a->opac_label() cmp $b->opac_label() } @{$locale_subs->{aout_list}->()} ];
120 # Returns a flat list of aou objects. often easier to manage than a tree.
121 $locale_subs->{aou_list} = sub {
122 $locale_subs->{aou_tree}->(); # force the org tree to load
123 return [ values %{$cache{map}{$locale}{aou}} ];
126 # returns the org unit object by shortname
127 $locale_subs->{get_aou_by_shortname} = sub {
128 my $sn = shift or return undef;
129 my $list = $locale_subs->{aou_list}->();
130 return (grep {$_->shortname eq $sn} @$list)[0];
133 $locale_subs->{aouct_tree} = sub {
135 # fetch the org unit tree
136 unless(exists $cache{aouct_tree}{$locale}) {
137 $cache{aouct_tree}{$locale} = undef;
139 my $e = new_editor();
140 my $tree_id = $e->search_actor_org_unit_custom_tree(
141 {purpose => 'opac', active => 't'},
146 my $node_tree = $e->search_actor_org_unit_custom_tree_node([
147 {parent_node => undef, tree => $tree_id},
149 flesh_fields => {aouctn => ['children', 'org_unit']},
150 order_by => {aouctn => 'sibling_order'}
154 # tree-ify the org units. note that since the orgs are fleshed
155 # upon retrieval, this org tree will not clobber ctx->{aou_tree}.
156 my @nodes = ($node_tree);
157 while (my $node = shift(@nodes)) {
158 my $aou = $node->org_unit;
160 for my $cnode (@{$node->children}) {
161 my $child_org = $cnode->org_unit;
162 $child_org->parent_ou($aou->id);
163 $child_org->ou_type( $locale_subs->{get_aout}->($child_org->ou_type) );
164 push(@{$aou->children}, $child_org);
165 push(@nodes, $cnode);
169 $cache{aouct_tree}{$locale} =
170 $node_tree->org_unit if $node_tree;
175 return $cache{aouct_tree}{$locale};
178 # turns an ISO date into something TT can understand
179 $locale_subs->{parse_datetime} = sub {
181 my $context_org = shift; # optional, for setting timezone via YAOUS
183 # Calling parse_datetime() with empty $date will lead to Internal Server Error
184 return '' if (!defined($date) or $date eq '');
186 # Probably an accidental entry like '0212' instead of '2012',
187 # but 1) the leading 0 may get stripped in cstore and
188 # 2) DateTime::Format::ISO8601 returns an error as years
189 # must be 2 or 4 digits
190 if ($date =~ m/^\d{3}-/) {
191 $logger->warn("Invalid date had a 3-digit year: $date");
193 } elsif ($date =~ m/^\d{1}-/) {
194 $logger->warn("Invalid date had a 1-digit year: $date");
195 $date = '000' . $date;
198 my $cleansed_date = clean_ISO8601($date);
200 $date = DateTime::Format::ISO8601->new->parse_datetime($cleansed_date);
202 $context_org = $context_org->id if ref($context_org);
203 my $tz = $locale_subs->{get_org_setting}->($context_org,'lib.timezone');
206 $date->set_time_zone($tz);
208 $logger->warn("Invalid timezone: $tz");
213 "%0.2d:%0.2d:%0.2d %0.2d-%0.2d-%0.4d",
223 # retrieve and cache org unit setting values
224 $locale_subs->{get_org_setting} = sub {
225 my($org_id, $setting) = @_;
227 $cache{org_settings}{$locale}{$org_id}{$setting} =
228 $U->ou_ancestor_setting_value($org_id, $setting)
229 unless exists $cache{org_settings}{$locale}{$org_id}{$setting};
231 return $cache{org_settings}{$locale}{$org_id}{$setting};
234 # retrieve and cache acsaf values
235 $locale_subs->{get_authority_fields} = sub {
236 my ($control_set) = @_;
238 if (not exists $cache{authority_fields}{$locale}{$control_set}) {
239 my $e = new_editor();
240 if (my $acs = $e->search_authority_control_set_authority_field(
241 {control_set => $control_set}
244 $cache{authority_fields}{$locale}{$control_set} =
245 +{ map { $_->id => $_ } @$acs };
253 return $cache{authority_fields}{$locale}{$control_set};
256 # make all "field_safe" classes accesible by default in the template context
258 ($Fieldmapper::fieldmap->{$_}->{field_safe} || '') =~ /true/i
259 } keys %{ $Fieldmapper::fieldmap };
261 for my $class (@classes) {
263 my $hint = $Fieldmapper::fieldmap->{$class}->{hint};
264 next if $hint eq 'aou'; # handled separately
266 my $ident_field = $Fieldmapper::fieldmap->{$class}->{identity};
267 (my $eclass = $class) =~ s/Fieldmapper:://o;
270 my $list_key = "${hint}_list";
271 my $get_key = "get_$hint";
272 my $search_key = "search_$hint";
274 my $memcache_key = join('.', 'EGWeb',$locale,$hint) . '.';
276 # Retrieve the full set of objects with class $hint
277 $locale_subs->{$list_key} ||= sub {
278 my $from_memcache = 0;
279 my $list = $memcache->get_cache($memcache_key.'list');
281 $cache{list}{$locale}{$hint} = $list;
284 my $method = "retrieve_all_$eclass";
285 my $e = new_editor();
286 $cache{list}{$locale}{$hint} = $e->$method() unless $cache{list}{$locale}{$hint};
288 $memcache->put_cache($memcache_key.'list',$cache{list}{$locale}{$hint}) unless $from_memcache;
289 return $cache{list}{$locale}{$hint};
292 # locate object of class $hint with Ident field $id
293 $cache{map}{$hint} = {};
294 $locale_subs->{$get_key} ||= sub {
296 return $cache{map}{$locale}{$hint}{$id} if $cache{map}{$locale}{$hint}{$id};
297 ($cache{map}{$locale}{$hint}{$id}) = grep { $_->$ident_field eq $id } @{$locale_subs->{$list_key}->()};
298 return $cache{map}{$locale}{$hint}{$id};
301 # search for objects of class $hint where field=value
302 $cache{search}{$hint} = {};
303 $locale_subs->{$search_key} ||= sub {
304 my ($field, $val, $filterfield, $filterval) = @_;
305 my $method = "search_$eclass";
307 my $scalar_cacheval = 1;
310 $scalar_cacheval = 0;
311 $val = [sort(@$val)] if ref $val eq 'ARRAY';
312 $cacheval = OpenSRF::Utils::JSON->perl2JSON($val);
313 #$self->apache->log->info("cacheval : $cacheval");
316 my $search_obj = {$field => $val};
318 $search_obj->{$filterfield} = $filterval;
319 $cacheval .= ':' . $filterfield . ':' . $filterval;
322 and $cache{list}{$locale}{$hint}
323 and !$cache{search}{$locale}{$hint}{$field}{$cacheval}
325 return $cache{search}{$locale}{$hint}{$field}{$cacheval} =
326 [ grep { $_->$field() eq $val } @{$cache{list}{$locale}{$hint}} ];
329 my $e = new_editor();
330 $cache{search}{$locale}{$hint}{$field}{$cacheval} = $e->$method($search_obj)
331 unless $cache{search}{$locale}{$hint}{$field}{$cacheval};
333 return $cache{search}{$locale}{$hint}{$field}{$cacheval};
337 $ctx->{$_} = $locale_subs->{$_} for keys %$locale_subs;
338 $ro_object_subs->{$locale} = $locale_subs;
341 sub generic_redirect {
344 my $cookie = shift; # can be an array of cgi.cookie's
346 $self->apache->print(
347 $self->cgi->redirect(
349 $self->cgi->param('redirect_to') ||
350 $self->ctx->{referer} ||
351 $self->ctx->{home_page},
356 return Apache2::Const::REDIRECT;
360 sub get_records_and_facets {
361 my ($self, $rec_ids, $facet_key, $unapi_args) = @_;
363 # collect the facet data
364 my $search = OpenSRF::AppSession->create('open-ils.search');
367 $facet_req = $search->request(
368 'open-ils.search.facet_cache.retrieve', $facet_key
373 $unapi_args->{site} ||= $self->ctx->{aou_tree}->()->shortname;
374 $unapi_args->{depth} ||= $self->ctx->{aou_tree}->()->ou_type->depth;
375 $unapi_args->{flesh_depth} ||= 5;
377 my $is_meta = delete $unapi_args->{metarecord};
378 #my $unapi_type = $is_meta ? 'unapi.mmr' : 'unapi.bre';
379 my $unapi_type = $is_meta ? 'unapi.metabib_virtual_record_feed' : 'unapi.biblio_record_entry_feed';
381 $unapi_cache ||= OpenSRF::Utils::Cache->new('global');
382 my $unapi_cache_key_suffix = join(
386 $unapi_args->{depth},
387 $unapi_args->{flesh_depth},
388 ($unapi_args->{pref_lib} || '')
393 my $outer_self = $self;
395 my $sdepth = $unapi_args->{flesh_depth};
396 my $slimit = "acn=>$sdepth,acp=>$sdepth";
397 $slimit .= ",bre=>$sdepth" if $is_meta;
398 my $flesh = $unapi_args->{flesh} || '';
400 # tag the record with the MR id
401 $flesh =~ s/}$/,mmr.unapi}/g if $is_meta;
403 my $ses = OpenSRF::AppSession->create('open-ils.cstore');
404 my $hl_ses = OpenSRF::AppSession->create('open-ils.search');
407 for my $bid (@$rec_ids) {
408 my $unapi_cache_key = 'TPAC_unapi_cache_'.$bid.'_'.$unapi_cache_key_suffix;
409 my $unapi_data = $unapi_cache->get_cache($unapi_cache_key);
411 if (!$unapi_data || $unapi_data->{running}) { #cache entry not done yet, get our own copy
412 push(@loop_recs, $bid);
414 $unapi_data->{marc_xml} = XML::LibXML->new->parse_string($unapi_data->{marc_xml})->documentElement;
415 $tmp_data{$unapi_data->{id}} = $unapi_data;
416 $unapi_cache->put_cache($unapi_cache_key, { running => $$ }, 5);
420 my $hl_req = $hl_ses->request(
421 'open-ils.search.fetch.metabib.display_field.highlight.atomic',
422 $self->ctx->{query_struct}{additional_data}{highlight_map},
427 my $unapi_req = $ses->request(
428 'open-ils.cstore.json_query',
430 $unapi_type, '{'.join(',',@loop_recs).'}', 'marcxml', $flesh,
432 $unapi_args->{depth},
434 undef, undef, undef, undef, undef, undef, undef, undef,
435 $unapi_args->{pref_lib}
439 my $data = $unapi_req->gather(1);
441 $outer_self->timelog("get_records_and_facets(): got feed content");
443 # Protect against requests for non-existent records
444 return unless ($data->{$unapi_type});
446 my $doc = XML::LibXML->new->parse_string($data->{$unapi_type})->documentElement;
448 $outer_self->timelog("get_records_and_facets(): parsed xml");
449 for my $xml ($doc->getElementsByTagName('record')) {
450 $xml = XML::LibXML->new->parse_string($xml->toString)->documentElement;
452 # Protect against legacy invalid MARCXML that might not have a 901c
455 my $bre_id_nodes = $xml->find('*[@tag="901"]/*[@code="c"]');
457 $bre_id = $bre_id_nodes->[0]->textContent;
459 $logger->warn("Missing 901 subfield 'c' in " . $xml->toString());
463 # extract metarecord ID from mmr.unapi tag
464 for my $node ($xml->getElementsByTagName('abbr')) {
465 my $title = $node->getAttribute('title');
466 ($mmr_id = $title) =~
467 s/tag:open-ils.org:U2\@mmr\/(\d+)\/.*/$1/g;
472 my $rec_id = $mmr_id ? $mmr_id : $bre_id;
473 $tmp_data{$rec_id} = {
481 # Let other backends grab our data now that we're done.
482 my $key = 'TPAC_unapi_cache_'.$rec_id.'_'.$unapi_cache_key_suffix;
483 my $cache_data = $unapi_cache->get_cache($key);
484 if (!$cache_data || $$cache_data{running} == $$) {
485 $unapi_cache->put_cache($key, {
489 marc_xml => $xml->toString
497 my $hl_data = $hl_req->gather(1); # list of arrayref of hashrefs
498 $self->ctx->{_hl_data} = { map { ''.$$_[0]{source} => $_ } @$hl_data };
499 $outer_self->timelog("get_records_and_facets(): got highlighting content (". keys(%{$self->ctx->{_hl_data}}).")");
504 $self->timelog("get_records_and_facets():almost ready to fetch facets");
506 my $tmp_facets = $facet_req->gather(1);
507 $self->timelog("get_records_and_facets(): gathered facet data");
508 for my $cmf_id (keys %$tmp_facets) {
510 # sort highest to lowest match count
512 my $entries = $tmp_facets->{$cmf_id};
513 for my $ent (keys %$entries) {
514 push(@entries, {value => $ent, count => $$entries{$ent}});
517 # Sort facet entries by 1) count descending, 2) text ascending
519 $b->{count} <=> $a->{count} ||
520 $a->{value} cmp $b->{value}
523 $facets->{$cmf_id} = {
524 cmf => $self->ctx->{get_cmf}->($cmf_id),
528 $self->timelog("get_records_and_facets(): gathered/sorted facet data");
535 return ($facets, map { $tmp_data{$_} } @$rec_ids);
538 sub _resolve_org_id_or_shortname {
539 my ($self, $str) = @_;
542 # Match on shortname case insensitively, but only if there's exactly
543 # one match. We wouldn't want the system to arbitrarily interpret
544 # 'foo' as either the org unit with shortname 'FOO' or 'Foo' and fail
545 # to make it clear to the user which one was chosen and why.
546 my $res = $self->editor->search_actor_org_unit({
549 transform => 'evergreen.lowercase',
554 return $res->[0]->id if $res and @$res == 1;
557 # Note that we don't validate IDs; we only try a shortname lookup and then
558 # assume anything else must be an ID.
559 return int($str); # Wrapping in int() prevents 500 on unmatched string.
562 sub _get_search_lib {
564 my $ctx = $self->ctx;
566 # avoid duplicate lookups
567 return $ctx->{search_ou} if $ctx->{search_ou};
569 my $loc = $ctx->{copy_location_group_org};
572 # loc param takes precedence
573 # XXX ^-- over what exactly? We could use clarification here. To me it looks
574 # like locg takes precedence over loc which in turn takes precedence over
575 # request headers which take precedence over pref_lib (which can be
576 # specified a lot of different ways and eventually falls back to
577 # physical_loc) and it all finally defaults to top of the org tree.
578 # To say nothing of all the code that doesn't look to this function at all
579 # but rather accesses some subset of these inputs directly.
581 $loc = $self->cgi->param('loc');
584 if ($self->apache->headers_in->get('OILS-Search-Lib')) {
585 return $self->apache->headers_in->get('OILS-Search-Lib');
587 if ($self->cgi->cookie('eg_search_lib')) {
588 return $self->cgi->cookie('eg_search_lib');
591 my $pref_lib = $self->_get_pref_lib();
592 return $pref_lib if $pref_lib;
594 return $ctx->{aou_tree}->()->id;
599 my $ctx = $self->ctx;
601 # plib param takes precedence
602 my $plib = $self->cgi->param('plib');
603 return $plib if $plib;
605 if ($self->apache->headers_in->get('OILS-Pref-Lib')) {
606 return $self->apache->headers_in->get('OILS-Pref-Lib');
608 if ($self->cgi->cookie('eg_pref_lib')) {
609 return $self->cgi->cookie('eg_pref_lib');
613 # See if the user has a search library preference
614 my $lset = $self->editor->search_actor_user_setting({
615 usr => $ctx->{user}->id,
616 name => 'opac.default_search_location'
618 return OpenSRF::Utils::JSON->JSON2perl($lset->value) if $lset;
620 # Otherwise return the user's home library
621 my $ou = $ctx->{user}->home_ou;
622 return ref($ou) ? $ou->id : $ou;
625 if ($ctx->{physical_loc}) {
626 return $ctx->{physical_loc};
631 # This is defensively coded since we don't do much manual reading from the
632 # file system in this module.
633 sub load_eg_cache_hash {
636 # just a context helper
637 $self->ctx->{eg_cache_hash} = sub { return $cache{eg_cache_hash}; };
639 # Need to actually load the value? If already done, move on.
640 return if defined $cache{eg_cache_hash};
642 # In this way even if we fail, we won't slow things down by ever trying
643 # again within this Apache process' lifetime.
644 $cache{eg_cache_hash} = 0;
646 my $path = File::Spec->catfile(
647 $self->apache->document_root, "eg_cache_hash"
650 if (not open FH, "<$path") {
651 $self->apache->log->warn("error opening $path : $!");
655 my $rv = read FH, $buf, 64; # defensive
658 if (not defined $rv) { # error
659 $self->apache->log->warn("error reading $path : $!");
660 } elsif ($rv > 0) { # no error, something read
662 $cache{eg_cache_hash} = $buf;
667 # Extracts the copy location org unit and group from the
668 # "logc" param, which takes the form org_id:grp, where
669 # grp can either be a location group id or can match the
670 # pattern "lasso(lasso_name_or_id)".
671 sub extract_copy_location_group_info {
673 my $ctx = $self->ctx;
674 if (my $clump = $self->cgi->param('locg')) {
675 my ($org, $grp) = split(/:/, $clump);
676 if ($grp =~ /^lasso\(([^)]+)\)/) {
677 $ctx->{search_lasso} = $1;
678 $ctx->{search_scope} = $grp;
679 $self->search_lasso_orgs;
681 $ctx->{copy_location_group} = $grp;
682 $ctx->{search_scope} = "location_groups($grp)";
684 $ctx->{copy_location_group_org} =
685 $self->_resolve_org_id_or_shortname($org);
689 sub load_copy_location_groups {
691 my $ctx = $self->ctx;
693 # User can access to the search location groups at the current
694 # search lib, the physical location lib, and the patron's home ou.
695 my @ctx_orgs = $ctx->{search_ou};
696 push(@ctx_orgs, $ctx->{physical_loc}) if $ctx->{physical_loc};
697 push(@ctx_orgs, $ctx->{user}->home_ou) if $ctx->{user};
699 my $grps = $self->editor->search_asset_copy_location_group([
706 transform => 'actor.org_unit_full_path',
707 result_field => 'id',
710 where => {id => \@ctx_orgs}
714 {order_by => {acplg => ['pos','name']}}
718 push(@{$buckets{$_->owner}}, $_) for @$grps;
719 $ctx->{copy_location_groups} = \%buckets;
722 sub load_hold_subscriptions {
724 my $ctx = $self->ctx;
726 return unless $ctx->{authtoken};
728 my $e = new_editor(authtoken => $ctx->{authtoken});
729 $e->personality('open-ils.pcrud'); # use pcrud mode to filter appropriately
731 $ctx->{hold_subscriptions} =
732 $e->search_container_user_bucket([
733 { btype => 'hold_subscription' },
734 { order_by => {cub => 'name'} }
739 sub load_my_hold_subscriptions {
741 my $ctx = $self->ctx;
743 return unless $ctx->{authtoken};
745 my $sub_entries = $self->editor->search_container_user_bucket_item(
746 { target_user => $ctx->{user}->id }
749 my $sub_ids = [ uniq map { $_->bucket } @$sub_entries ];
750 $ctx->{my_hold_subscriptions} = scalar(@$sub_ids) ?
751 $self->editor->search_container_user_bucket(
752 {btype => 'hold_subscription', id => $sub_ids, pub => 't'}
756 sub search_lasso_orgs {
758 my $ctx = $self->ctx;
759 return $ctx->{search_lasso_orgs} if defined $ctx->{search_lasso_orgs};
760 return undef unless $ctx->{search_lasso};
762 # User can access global lassos and those at the current search lib
763 my $lasso_maps = $self->editor->search_actor_org_lasso_map(
764 { lasso => $ctx->{search_lasso} }
766 $ctx->{search_lasso_orgs} = [ map { $_->org_unit } @$lasso_maps];
771 my $ctx = $self->ctx;
773 # User can access global lassos and those at the current search lib
774 my $direct_lassos = $self->editor->search_actor_org_lasso_map(
775 { org_unit => $ctx->{search_ou} }
777 $direct_lassos = [ map { $_->lasso } @$direct_lassos];
779 my $lassos = $self->editor->search_actor_org_lasso(
780 { '-or' => { global => 't', @$direct_lassos ? (id => { in => $direct_lassos}) : () } }
783 $ctx->{lassos} = [ sort { $a->name cmp $b->name } @$lassos ];
784 $self->apache->log->info("Fetched ".scalar(@$lassos)." lassos");
787 sub set_file_download_headers {
789 my $filename = shift;
790 my $ctype = shift || "text/plain; encoding=utf8";
792 $self->apache->content_type($ctype);
794 $self->apache->headers_out->add(
795 "Content-Disposition",
796 "attachment;filename=$filename"
799 return Apache2::Const::OK;
802 sub apache_log_if_event {
803 my ($self, $event, $prefix_text, $success_ok, $level) = @_;
805 $prefix_text ||= "Evergreen returned event";
810 $prefix_text .= ": ";
812 my $code = $U->event_code($event);
813 if (defined $code and ($code or not $success_ok)) {
814 $self->apache->log->$level(
816 ($event->{textcode} || "") . " ($code)" .
817 ($event->{note} ? (": " . $event->{note}) : "")
825 sub load_search_filter_groups {
828 my $org_list = $U->get_org_ancestors($ctx_org, 1);
831 for my $org_id (@$org_list) {
834 if (! ($grps = $cache{search_filter_groups}{$org_id}) ) {
835 $grps = $self->editor->search_actor_search_filter_group([
842 order_by => {asfge => 'pos'}
845 $cache{search_filter_groups}{$org_id} = $grps;
848 # for the current context, if a descendant org has a group
849 # with a matching code replace the group from the parent.
850 $seen{$_->code} = $_ for @$grps;
853 return $self->ctx->{search_filter_groups} = \%seen;
857 sub check_for_temp_list_warning {
859 my $ctx = $self->ctx;
860 my $cgi = $self->cgi;
862 my $lib = $self->_get_search_lib;
863 my $warn = ($ctx->{get_org_setting}->($lib || 1, 'opac.patron.temporary_list_warn')) ? 1 : 0;
865 if ($warn && $ctx->{user}) {
866 $self->_load_user_with_prefs;
867 my $map = $ctx->{user_setting_map};
868 $warn = 0 if ($$map{'opac.temporary_list_no_warn'});
871 # Check for a cookie disabling the warning.
872 $warn = 0 if ($warn && $cgi->cookie('no_temp_list_warn'));
877 sub load_org_util_funcs {
879 my $ctx = $self->ctx;
881 # evaluates to true if test_ou is within the same depth-
882 # scoped tree as ctx_ou. both ou's are org unit objects.
883 $ctx->{org_within_scope} = sub {
884 my ($ctx_ou, $test_ou, $depth) = @_;
886 return 1 if $ctx_ou->id == $test_ou->id;
890 # find the top-most ctx-org ancestor at the provided depth
891 while ($depth < $ctx_ou->ou_type->depth
892 and $ctx_ou->id != $test_ou->id) {
893 $ctx_ou = $ctx->{get_aou}->($ctx_ou->parent_ou);
896 # the preceeding loop may have landed on our org
897 return 1 if $ctx_ou->id == $test_ou->id;
901 return 1 if defined $depth; # $depth == 0;
904 for my $child (@{$ctx_ou->children}) {
905 return 1 if $ctx->{org_within_scope}->($child, $test_ou);
911 # Returns true if the provided org unit is within the same
912 # org unit hiding depth-scoped tree as the physical location.
913 # Org unit hiding is based on the immutable physical_loc
914 # and is not meant to change as search/pref/etc libs change
915 $ctx->{org_within_hiding_scope} = sub {
917 my $ploc = $ctx->{physical_loc} or return 1;
919 my $depth = $ctx->{get_org_setting}->(
920 $ploc, 'opac.org_unit_hiding.depth');
922 return 1 unless $depth; # 0 or undef
924 return $ctx->{org_within_scope}->(
925 $ctx->{get_aou}->($ploc),
926 $ctx->{get_aou}->($org_id), $depth);
930 # Evaluates to true if the context org (defaults to get_library)
931 # is not within the hiding scope. Also evaluates to true if the
932 # user's pref_ou is set and it's out of hiding scope.
933 # Always evaluates to true when ctx.is_staff
934 $ctx->{org_hiding_disabled} = sub {
935 my $ctx_org = shift || $ctx->{search_ou};
937 return 1 if $ctx->{is_staff};
939 # beware locg values formatted as org:loc
940 $ctx_org =~ s/:.*//g;
942 return 1 if !$ctx->{org_within_hiding_scope}->($ctx_org);
944 return 1 if $ctx->{pref_ou} and $ctx->{pref_ou} != $ctx_org
945 and !$ctx->{org_within_hiding_scope}->($ctx->{pref_ou});
952 # returns the list of org unit IDs for which the
953 # selected org unit setting returned a true value
954 sub setting_is_true_for_orgs {
955 my ($self, $setting) = @_;
956 my $ctx = $self->ctx;
962 push (@valid_orgs, $org->id) if
963 $ctx->{get_org_setting}->($org->id, $setting);
964 $test_org->($_) for @{$org->children};
967 $test_org->($ctx->{aou_tree}->());
971 # Builds and links a perm checking function, testing permissions against
972 # the currently logged in user.
973 # ctx->{has_perm}->(perm_code, org_id) => 1/undef
974 # For security, perm checks are cached per page, not per process.
975 sub load_perm_funcs {
978 $self->ctx->{has_perm} = sub {
979 my ($perm_code, $org_id) = @_;
980 return 0 unless $self->editor->requestor;
982 if ($perm_cache{$org_id}) {
983 return $perm_cache{$org_id}{$perm_code}
984 if exists $perm_cache{$org_id}{$perm_code};
986 $perm_cache{$org_id} = {};
988 return $perm_cache{$org_id}{$perm_code} =
989 $self->editor->allowed($perm_code, $org_id);