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);
10 use OpenSRF::Utils::Cache;
11 use OpenSRF::Utils::Logger qw/$logger/;
12 use OpenILS::Utils::CStoreEditor qw/:funcs/;
13 use OpenILS::Utils::Fieldmapper;
14 use OpenILS::Application::AppUtils;
15 use OpenSRF::MultiSession;
17 my $defang = HTML::Defang->new;
18 my $U = 'OpenILS::Application::AppUtils';
20 my $ro_object_subs; # cached subs
21 our %cache = ( # cached data
23 list => {en_us => {}},
24 search => {en_us => {}},
25 org_settings => {en_us => {}},
26 search_filter_groups => {en_us => {}},
27 aou_tree => {en_us => undef},
29 eg_cache_hash => undef,
30 authority_fields => {en_us => {}}
37 # create a stub object with just enough in place
38 # to call init_ro_object_cache()
39 my $stub = bless({}, ref($class) || $class);
43 foreach my $locale (sort keys %locales) {
44 OpenSRF::AppSession->default_locale($locales{$locale});
45 $ctx->{locale} = $locale;
46 $stub->init_ro_object_cache();
48 # pre-cache various sets of objects
49 # known to be time-consuming to retrieve
51 $ro_object_subs->{$locale}->{aou_tree}();
52 $ro_object_subs->{$locale}->{aouct_tree}();
53 $ro_object_subs->{$locale}->{ccvm_list}();
54 $ro_object_subs->{$locale}->{crad_list}();
55 $ro_object_subs->{$locale}->{get_authority_fields}(1);
59 sub init_ro_object_cache {
62 my $memcache ||= OpenSRF::Utils::Cache->new('global');
64 # reset org unit setting cache on each page load to avoid the
65 # requirement of reloading apache with each org-setting change
66 $cache{org_settings} = {};
68 if($ro_object_subs->{$ctx->{locale}}) {
69 # subs have been built. insert into the context then move along.
70 $ctx->{$_} = $ro_object_subs->{$ctx->{locale}}->{$_} for keys %{ $ro_object_subs->{$ctx->{locale}} };
75 my $locale = $ctx->{locale};
77 # Create special-purpose subs
79 # aou is special because it's tree-ish
80 $locale_subs->{aou_tree} = sub {
82 # fetch the org unit tree
83 unless($cache{aou_tree}{$locale}) {
85 my $tree = $e->search_actor_org_unit([
86 { parent_ou => undef},
88 flesh_fields => {aou => ['children']},
89 order_by => {aou => 'name'}
93 # flesh the org unit type for each org unit
94 # and simultaneously set the id => aou map cache
97 my $locale_subs = shift;
99 $node->ou_type( $locale_subs->{get_aout}->($node->ou_type) );
100 $cache{map}{$locale}{aou}{$node->id} = $node;
101 flesh_aout($_, $locale_subs, $locale) foreach @{$node->children};
103 flesh_aout($tree, $locale_subs, $locale);
105 $cache{aou_tree}{$locale} = $tree;
108 return $cache{aou_tree}{$locale};
111 # Add a special handler for the tree-shaped org unit cache
112 $locale_subs->{get_aou} = sub {
114 return undef unless defined $org_id;
115 $locale_subs->{aou_tree}->(); # force the org tree to load
116 return $cache{map}{$locale}{aou}{$org_id};
119 # Returns a flat list of aout objects, sorted by depth and opac_label.
120 $locale_subs->{sorted_aout_list} = sub {
121 return [ sort { $a->depth() <=> $b->depth() || $a->opac_label() cmp $b->opac_label() } @{$locale_subs->{aout_list}->()} ];
124 # Returns a flat list of aou objects. often easier to manage than a tree.
125 $locale_subs->{aou_list} = sub {
126 $locale_subs->{aou_tree}->(); # force the org tree to load
127 return [ values %{$cache{map}{$locale}{aou}} ];
130 # returns the org unit object by shortname
131 $locale_subs->{get_aou_by_shortname} = sub {
132 my $sn = shift or return undef;
133 my $list = $locale_subs->{aou_list}->();
134 return (grep {$_->shortname eq $sn} @$list)[0];
137 # Defang an HTML string
138 $locale_subs->{defang_string} = sub {
140 return $defang->defang($html);
143 # Turns one string into two for long text strings
144 $locale_subs->{split_for_accordion} = sub {
146 my $trunc_length = shift;
148 return unless defined $html && defined $trunc_length;
150 my $html_string = "";
151 my $trunc_str = "<span class='truncEllipse'>...</span><span class='truncated' style='display:none'>";
152 my $current_length = 0;
156 my $html_tree = HTML::TreeBuilder->new;
157 $html_tree->parse($html);
160 # Navigate #html_tree to determine length of contained strings
161 my @nodes = $html_tree->guts();
162 foreach my $node(@nodes) {
163 my $nref = ref $node;
164 if ($nref eq "HTML::Element") {
165 $current_length += length $node->as_text();
166 my $escaped_html = $defang->defang($node->as_HTML());
167 push(@html_strings, $escaped_html);
169 # Node is whitespace - handling this like regular simple text
170 # doesn't like to play nice, so handling separately
173 if ($current_length >= $trunc_length and not $truncated) {
174 push(@html_strings, " $trunc_str");
177 push(@html_strings, $defang->defang($node));
179 # Node is simple text
181 my $new_length += length $node;
182 if ($new_length >= $trunc_length and not $truncated) {
185 my $calc_length = abs($trunc_length - $current_length);
186 if ((substr $node, $calc_length, 1) =~ /\s/) {
187 $nshort = substr $node, 0, $calc_length;
188 $nrest = substr $node, $calc_length;
190 my $nloc = rindex $node, ' ', $calc_length;
191 $nshort = substr $node, 0, $nloc;
192 $nrest = substr $node, $nloc;
194 $nshort = $defang->defang($nshort);
195 $nrest = $defang->defang($nrest);
196 push(@html_strings, "$nshort $trunc_str $nrest");
199 push(@html_strings, $defang->defang($node));
201 $current_length += length $node;
206 push(@html_strings, "</span>");
209 if (@html_strings > 1) {
210 $html_string = join '', @html_strings;
212 $html_string = $html_strings[0];
215 return ($html_string, $truncated);
218 $locale_subs->{aouct_tree} = sub {
220 # fetch the org unit tree
221 unless(exists $cache{aouct_tree}{$locale}) {
222 $cache{aouct_tree}{$locale} = undef;
224 my $e = new_editor();
225 my $tree_id = $e->search_actor_org_unit_custom_tree(
226 {purpose => 'opac', active => 't'},
231 my $node_tree = $e->search_actor_org_unit_custom_tree_node([
232 {parent_node => undef, tree => $tree_id},
234 flesh_fields => {aouctn => ['children', 'org_unit']},
235 order_by => {aouctn => 'sibling_order'}
239 # tree-ify the org units. note that since the orgs are fleshed
240 # upon retrieval, this org tree will not clobber ctx->{aou_tree}.
241 my @nodes = ($node_tree);
242 while (my $node = shift(@nodes)) {
243 my $aou = $node->org_unit;
245 for my $cnode (@{$node->children}) {
246 my $child_org = $cnode->org_unit;
247 $child_org->parent_ou($aou->id);
248 $child_org->ou_type( $locale_subs->{get_aout}->($child_org->ou_type) );
249 push(@{$aou->children}, $child_org);
250 push(@nodes, $cnode);
254 $cache{aouct_tree}{$locale} =
255 $node_tree->org_unit if $node_tree;
260 return $cache{aouct_tree}{$locale};
263 # turns an ISO date into something TT can understand
264 $locale_subs->{parse_datetime} = sub {
266 my $context_org = shift; # optional, for setting timezone via YAOUS
268 # Calling parse_datetime() with empty $date will lead to Internal Server Error
269 return '' if (!defined($date) or $date eq '');
271 # Probably an accidental entry like '0212' instead of '2012',
272 # but 1) the leading 0 may get stripped in cstore and
273 # 2) DateTime::Format::ISO8601 returns an error as years
274 # must be 2 or 4 digits
275 if ($date =~ m/^\d{3}-/) {
276 $logger->warn("Invalid date had a 3-digit year: $date");
278 } elsif ($date =~ m/^\d{1}-/) {
279 $logger->warn("Invalid date had a 1-digit year: $date");
280 $date = '000' . $date;
283 my $cleansed_date = clean_ISO8601($date);
285 $date = DateTime::Format::ISO8601->new->parse_datetime($cleansed_date);
287 $context_org = $context_org->id if ref($context_org);
288 my $tz = $locale_subs->{get_org_setting}->($context_org,'lib.timezone');
291 $date->set_time_zone($tz);
293 $logger->warn("Invalid timezone: $tz");
298 "%0.2d:%0.2d:%0.2d %0.2d-%0.2d-%0.4d",
308 # retrieve and cache org unit setting values
309 $locale_subs->{get_org_setting} = sub {
310 my($org_id, $setting) = @_;
312 $cache{org_settings}{$locale}{$org_id}{$setting} =
313 $U->ou_ancestor_setting_value($org_id, $setting)
314 unless exists $cache{org_settings}{$locale}{$org_id}{$setting};
316 return $cache{org_settings}{$locale}{$org_id}{$setting};
319 # retrieve and cache acsaf values
320 $locale_subs->{get_authority_fields} = sub {
321 my ($control_set) = @_;
323 if (not exists $cache{authority_fields}{$locale}{$control_set}) {
324 my $e = new_editor();
325 if (my $acs = $e->search_authority_control_set_authority_field(
326 {control_set => $control_set}
329 $cache{authority_fields}{$locale}{$control_set} =
330 +{ map { $_->id => $_ } @$acs };
338 return $cache{authority_fields}{$locale}{$control_set};
341 # make all "field_safe" classes accesible by default in the template context
343 ($Fieldmapper::fieldmap->{$_}->{field_safe} || '') =~ /true/i
344 } keys %{ $Fieldmapper::fieldmap };
346 for my $class (@classes) {
348 my $hint = $Fieldmapper::fieldmap->{$class}->{hint};
349 next if $hint eq 'aou'; # handled separately
351 my $ident_field = $Fieldmapper::fieldmap->{$class}->{identity};
352 (my $eclass = $class) =~ s/Fieldmapper:://o;
355 my $list_key = "${hint}_list";
356 my $get_key = "get_$hint";
357 my $search_key = "search_$hint";
359 my $memcache_key = join('.', 'EGWeb',$locale,$hint) . '.';
361 # Retrieve the full set of objects with class $hint
362 $locale_subs->{$list_key} ||= sub {
363 my $from_memcache = 0;
364 my $list = $memcache->get_cache($memcache_key.'list');
366 $cache{list}{$locale}{$hint} = $list;
369 my $method = "retrieve_all_$eclass";
370 my $e = new_editor();
371 $cache{list}{$locale}{$hint} = $e->$method() unless $cache{list}{$locale}{$hint};
373 $memcache->put_cache($memcache_key.'list',$cache{list}{$locale}{$hint}) unless $from_memcache;
374 return $cache{list}{$locale}{$hint};
377 # locate object of class $hint with Ident field $id
378 $cache{map}{$hint} = {};
379 $locale_subs->{$get_key} ||= sub {
381 return $cache{map}{$locale}{$hint}{$id} if $cache{map}{$locale}{$hint}{$id};
382 ($cache{map}{$locale}{$hint}{$id}) = grep { $_->$ident_field eq $id } @{$locale_subs->{$list_key}->()};
383 return $cache{map}{$locale}{$hint}{$id};
386 # search for objects of class $hint where field=value
387 $cache{search}{$hint} = {};
388 $locale_subs->{$search_key} ||= sub {
389 my ($field, $val, $filterfield, $filterval) = @_;
390 my $method = "search_$eclass";
392 my $scalar_cacheval = 1;
395 $scalar_cacheval = 0;
396 $val = [sort(@$val)] if ref $val eq 'ARRAY';
397 $cacheval = OpenSRF::Utils::JSON->perl2JSON($val);
398 #$self->apache->log->info("cacheval : $cacheval");
401 my $search_obj = {$field => $val};
403 $search_obj->{$filterfield} = $filterval;
404 $cacheval .= ':' . $filterfield . ':' . $filterval;
407 and $cache{list}{$locale}{$hint}
408 and !$cache{search}{$locale}{$hint}{$field}{$cacheval}
410 return $cache{search}{$locale}{$hint}{$field}{$cacheval} =
411 [ grep { $_->$field() eq $val } @{$cache{list}{$locale}{$hint}} ];
414 my $e = new_editor();
415 $cache{search}{$locale}{$hint}{$field}{$cacheval} = $e->$method($search_obj)
416 unless $cache{search}{$locale}{$hint}{$field}{$cacheval};
418 return $cache{search}{$locale}{$hint}{$field}{$cacheval};
422 $ctx->{$_} = $locale_subs->{$_} for keys %$locale_subs;
423 $ro_object_subs->{$locale} = $locale_subs;
426 sub generic_redirect {
429 my $cookie = shift; # can be an array of cgi.cookie's
431 $self->apache->print(
432 $self->cgi->redirect(
434 $self->cgi->param('redirect_to') ||
435 $self->ctx->{referer} ||
436 $self->ctx->{home_page},
441 return Apache2::Const::REDIRECT;
445 sub get_records_and_facets {
446 my ($self, $rec_ids, $facet_key, $unapi_args) = @_;
448 # collect the facet data
449 my $search = OpenSRF::AppSession->create('open-ils.search');
452 $facet_req = $search->request(
453 'open-ils.search.facet_cache.retrieve', $facet_key
458 $unapi_args->{site} ||= $self->ctx->{aou_tree}->()->shortname;
459 $unapi_args->{depth} ||= $self->ctx->{aou_tree}->()->ou_type->depth;
460 $unapi_args->{flesh_depth} ||= 5;
462 my $is_meta = delete $unapi_args->{metarecord};
463 #my $unapi_type = $is_meta ? 'unapi.mmr' : 'unapi.bre';
464 my $unapi_type = $is_meta ? 'unapi.metabib_virtual_record_feed' : 'unapi.biblio_record_entry_feed';
466 $unapi_cache ||= OpenSRF::Utils::Cache->new('global');
467 my $unapi_cache_key_suffix = join(
471 $unapi_args->{depth},
472 $unapi_args->{flesh_depth},
473 ($unapi_args->{pref_lib} || '')
478 my $outer_self = $self;
480 my $sdepth = $unapi_args->{flesh_depth};
481 my $slimit = "acn=>$sdepth,acp=>$sdepth";
482 $slimit .= ",bre=>$sdepth" if $is_meta;
483 my $flesh = $unapi_args->{flesh} || '';
485 # tag the record with the MR id
486 $flesh =~ s/}$/,mmr.unapi}/g if $is_meta;
488 my $ses = OpenSRF::AppSession->create('open-ils.cstore');
489 my $hl_ses = OpenSRF::AppSession->create('open-ils.search');
492 for my $bid (@$rec_ids) {
493 my $unapi_cache_key = 'TPAC_unapi_cache_'.$bid.'_'.$unapi_cache_key_suffix;
494 my $unapi_data = $unapi_cache->get_cache($unapi_cache_key);
496 if (!$unapi_data || $unapi_data->{running}) { #cache entry not done yet, get our own copy
497 push(@loop_recs, $bid);
499 $unapi_data->{marc_xml} = XML::LibXML->new->parse_string($unapi_data->{marc_xml})->documentElement;
500 $tmp_data{$unapi_data->{id}} = $unapi_data;
501 $unapi_cache->put_cache($unapi_cache_key, { running => $$ }, 5);
505 my $hl_req = $hl_ses->request(
506 'open-ils.search.fetch.metabib.display_field.highlight.atomic',
507 $self->ctx->{query_struct}{additional_data}{highlight_map},
512 my $unapi_req = $ses->request(
513 'open-ils.cstore.json_query',
515 $unapi_type, '{'.join(',',@loop_recs).'}', 'marcxml', $flesh,
517 $unapi_args->{depth},
519 undef, undef, undef, undef, undef, undef, undef, undef,
520 $unapi_args->{pref_lib}
524 my $data = $unapi_req->gather(1);
526 $outer_self->timelog("get_records_and_facets(): got feed content");
528 # Protect against requests for non-existent records
529 return unless ($data->{$unapi_type});
531 my $doc = XML::LibXML->new->parse_string($data->{$unapi_type})->documentElement;
533 $outer_self->timelog("get_records_and_facets(): parsed xml");
534 for my $xml ($doc->getElementsByTagName('record')) {
535 $xml = XML::LibXML->new->parse_string($xml->toString)->documentElement;
537 # Protect against legacy invalid MARCXML that might not have a 901c
540 my $bre_id_nodes = $xml->find('*[@tag="901"]/*[@code="c"]');
542 $bre_id = $bre_id_nodes->[0]->textContent;
544 $logger->warn("Missing 901 subfield 'c' in " . $xml->toString());
548 # extract metarecord ID from mmr.unapi tag
549 for my $node ($xml->getElementsByTagName('abbr')) {
550 my $title = $node->getAttribute('title');
551 ($mmr_id = $title) =~
552 s/tag:open-ils.org:U2\@mmr\/(\d+)\/.*/$1/g;
557 my $rec_id = $mmr_id ? $mmr_id : $bre_id;
558 $tmp_data{$rec_id} = {
566 # Let other backends grab our data now that we're done.
567 my $key = 'TPAC_unapi_cache_'.$rec_id.'_'.$unapi_cache_key_suffix;
568 my $cache_data = $unapi_cache->get_cache($key);
569 if (!$cache_data || $$cache_data{running} == $$) {
570 $unapi_cache->put_cache($key, {
574 marc_xml => $xml->toString
582 my $hl_data = $hl_req->gather(1); # list of arrayref of hashrefs
583 $self->ctx->{_hl_data} = { map { ''.$$_[0]{source} => $_ } @$hl_data };
584 $outer_self->timelog("get_records_and_facets(): got highlighting content (". keys(%{$self->ctx->{_hl_data}}).")");
589 $self->timelog("get_records_and_facets():almost ready to fetch facets");
591 my $tmp_facets = $facet_req->gather(1);
592 $self->timelog("get_records_and_facets(): gathered facet data");
593 for my $cmf_id (keys %$tmp_facets) {
595 # sort highest to lowest match count
597 my $entries = $tmp_facets->{$cmf_id};
598 for my $ent (keys %$entries) {
599 push(@entries, {value => $ent, count => $$entries{$ent}});
602 # Sort facet entries by 1) count descending, 2) text ascending
604 $b->{count} <=> $a->{count} ||
605 $a->{value} cmp $b->{value}
608 $facets->{$cmf_id} = {
609 cmf => $self->ctx->{get_cmf}->($cmf_id),
613 $self->timelog("get_records_and_facets(): gathered/sorted facet data");
620 return ($facets, map { $tmp_data{$_} } @$rec_ids);
623 sub _resolve_org_id_or_shortname {
624 my ($self, $str) = @_;
627 # Match on shortname case insensitively, but only if there's exactly
628 # one match. We wouldn't want the system to arbitrarily interpret
629 # 'foo' as either the org unit with shortname 'FOO' or 'Foo' and fail
630 # to make it clear to the user which one was chosen and why.
631 my $res = $self->editor->search_actor_org_unit({
634 transform => 'evergreen.lowercase',
639 return $res->[0]->id if $res and @$res == 1;
642 # Note that we don't validate IDs; we only try a shortname lookup and then
643 # assume anything else must be an ID.
644 return int($str); # Wrapping in int() prevents 500 on unmatched string.
647 sub _get_search_lib {
649 my $ctx = $self->ctx;
651 # avoid duplicate lookups
652 return $ctx->{search_ou} if $ctx->{search_ou};
654 my $loc = $ctx->{copy_location_group_org};
657 # loc param takes precedence
658 # XXX ^-- over what exactly? We could use clarification here. To me it looks
659 # like locg takes precedence over loc which in turn takes precedence over
660 # request headers which take precedence over pref_lib (which can be
661 # specified a lot of different ways and eventually falls back to
662 # physical_loc) and it all finally defaults to top of the org tree.
663 # To say nothing of all the code that doesn't look to this function at all
664 # but rather accesses some subset of these inputs directly.
666 $loc = $self->cgi->param('loc');
669 if ($self->apache->headers_in->get('OILS-Search-Lib')) {
670 return $self->apache->headers_in->get('OILS-Search-Lib');
672 if ($self->cgi->cookie('eg_search_lib')) {
673 return $self->cgi->cookie('eg_search_lib');
676 my $pref_lib = $self->_get_pref_lib();
677 return $pref_lib if $pref_lib;
679 return $ctx->{aou_tree}->()->id;
684 my $ctx = $self->ctx;
686 # plib param takes precedence
687 my $plib = $self->cgi->param('plib');
688 return $plib if $plib;
690 if ($self->apache->headers_in->get('OILS-Pref-Lib')) {
691 return $self->apache->headers_in->get('OILS-Pref-Lib');
693 if ($self->cgi->cookie('eg_pref_lib')) {
694 return $self->cgi->cookie('eg_pref_lib');
698 # See if the user has a search library preference
699 my $lset = $self->editor->search_actor_user_setting({
700 usr => $ctx->{user}->id,
701 name => 'opac.default_search_location'
703 return OpenSRF::Utils::JSON->JSON2perl($lset->value) if $lset;
705 # Otherwise return the user's home library
706 my $ou = $ctx->{user}->home_ou;
707 return ref($ou) ? $ou->id : $ou;
710 if ($ctx->{physical_loc}) {
711 return $ctx->{physical_loc};
716 # This is defensively coded since we don't do much manual reading from the
717 # file system in this module.
718 sub load_eg_cache_hash {
721 # just a context helper
722 $self->ctx->{eg_cache_hash} = sub { return $cache{eg_cache_hash}; };
724 # Need to actually load the value? If already done, move on.
725 return if defined $cache{eg_cache_hash};
727 # In this way even if we fail, we won't slow things down by ever trying
728 # again within this Apache process' lifetime.
729 $cache{eg_cache_hash} = 0;
731 my $path = File::Spec->catfile(
732 $self->apache->document_root, "eg_cache_hash"
735 if (not open FH, "<$path") {
736 $self->apache->log->warn("error opening $path : $!");
740 my $rv = read FH, $buf, 64; # defensive
743 if (not defined $rv) { # error
744 $self->apache->log->warn("error reading $path : $!");
745 } elsif ($rv > 0) { # no error, something read
747 $cache{eg_cache_hash} = $buf;
752 # Extracts the copy location org unit and group from the
753 # "logc" param, which takes the form org_id:grp, where
754 # grp can either be a location group id or can match the
755 # pattern "lasso(lasso_name_or_id)".
756 sub extract_copy_location_group_info {
758 my $ctx = $self->ctx;
759 if (my $clump = $self->cgi->param('locg')) {
760 my ($org, $grp) = split(/:/, $clump);
761 if ($grp =~ /^lasso\(([^)]+)\)/) {
762 $ctx->{search_lasso} = $1;
763 $ctx->{search_scope} = $grp;
764 $self->search_lasso_orgs;
766 $ctx->{copy_location_group} = $grp;
767 $ctx->{search_scope} = "location_groups($grp)";
769 $ctx->{copy_location_group_org} =
770 $self->_resolve_org_id_or_shortname($org);
774 sub load_copy_location_groups {
776 my $ctx = $self->ctx;
778 # User can access to the search location groups at the current
779 # search lib, the physical location lib, and the patron's home ou.
780 my @ctx_orgs = $ctx->{search_ou};
781 push(@ctx_orgs, $ctx->{physical_loc}) if $ctx->{physical_loc};
782 push(@ctx_orgs, $ctx->{user}->home_ou) if $ctx->{user};
784 my $grps = $self->editor->search_asset_copy_location_group([
791 transform => 'actor.org_unit_full_path',
792 result_field => 'id',
795 where => {id => \@ctx_orgs}
799 {order_by => {acplg => ['pos','name']}}
803 push(@{$buckets{$_->owner}}, $_) for @$grps;
804 $ctx->{copy_location_groups} = \%buckets;
807 sub load_hold_subscriptions {
809 my $ctx = $self->ctx;
811 return unless $ctx->{authtoken};
813 my $e = new_editor(authtoken => $ctx->{authtoken});
814 $e->personality('open-ils.pcrud'); # use pcrud mode to filter appropriately
816 $ctx->{hold_subscriptions} =
817 $e->search_container_user_bucket([
818 { btype => 'hold_subscription' },
819 { order_by => {cub => 'name'} }
824 sub load_my_hold_subscriptions {
826 my $ctx = $self->ctx;
828 return unless $ctx->{authtoken};
830 my $sub_entries = $self->editor->search_container_user_bucket_item(
831 { target_user => $ctx->{user}->id }
834 my $sub_ids = [ uniq map { $_->bucket } @$sub_entries ];
835 $ctx->{my_hold_subscriptions} = scalar(@$sub_ids) ?
836 $self->editor->search_container_user_bucket(
837 {btype => 'hold_subscription', id => $sub_ids, pub => 't'}
841 sub search_lasso_orgs {
843 my $ctx = $self->ctx;
844 return $ctx->{search_lasso_orgs} if defined $ctx->{search_lasso_orgs};
845 return undef unless $ctx->{search_lasso};
847 # User can access global lassos and those at the current search lib
848 my $lasso_maps = $self->editor->search_actor_org_lasso_map(
849 { lasso => $ctx->{search_lasso} }
851 $ctx->{search_lasso_orgs} = [ map { $_->org_unit } @$lasso_maps];
856 my $ctx = $self->ctx;
858 # User can access global lassos and those at the current search lib
859 my $direct_lassos = $self->editor->search_actor_org_lasso_map(
860 { org_unit => $ctx->{search_ou} }
862 $direct_lassos = [ map { $_->lasso } @$direct_lassos];
864 my $lassos = $self->editor->search_actor_org_lasso(
865 { '-or' => { global => 't', @$direct_lassos ? (id => { in => $direct_lassos}) : () } }
868 $ctx->{lassos} = [ sort { $a->name cmp $b->name } @$lassos ];
869 $self->apache->log->info("Fetched ".scalar(@$lassos)." lassos");
872 sub set_file_download_headers {
874 my $filename = shift;
875 my $ctype = shift || "text/plain; encoding=utf8";
877 $self->apache->content_type($ctype);
879 $self->apache->headers_out->add(
880 "Content-Disposition",
881 "attachment;filename=$filename"
884 return Apache2::Const::OK;
887 sub apache_log_if_event {
888 my ($self, $event, $prefix_text, $success_ok, $level) = @_;
890 $prefix_text ||= "Evergreen returned event";
895 $prefix_text .= ": ";
897 my $code = $U->event_code($event);
898 if (defined $code and ($code or not $success_ok)) {
899 $self->apache->log->$level(
901 ($event->{textcode} || "") . " ($code)" .
902 ($event->{note} ? (": " . $event->{note}) : "")
910 sub load_search_filter_groups {
913 my $org_list = $U->get_org_ancestors($ctx_org, 1);
916 for my $org_id (@$org_list) {
919 if (! ($grps = $cache{search_filter_groups}{$org_id}) ) {
920 $grps = $self->editor->search_actor_search_filter_group([
927 order_by => {asfge => 'pos'}
930 $cache{search_filter_groups}{$org_id} = $grps;
933 # for the current context, if a descendant org has a group
934 # with a matching code replace the group from the parent.
935 $seen{$_->code} = $_ for @$grps;
938 return $self->ctx->{search_filter_groups} = \%seen;
942 sub check_for_temp_list_warning {
944 my $ctx = $self->ctx;
945 my $cgi = $self->cgi;
947 my $lib = $self->_get_search_lib;
948 my $warn = ($ctx->{get_org_setting}->($lib || 1, 'opac.patron.temporary_list_warn')) ? 1 : 0;
950 if ($warn && $ctx->{user}) {
951 $self->_load_user_with_prefs;
952 my $map = $ctx->{user_setting_map};
953 $warn = 0 if ($$map{'opac.temporary_list_no_warn'});
956 # Check for a cookie disabling the warning.
957 $warn = 0 if ($warn && $cgi->cookie('no_temp_list_warn'));
962 sub load_org_util_funcs {
964 my $ctx = $self->ctx;
966 # evaluates to true if test_ou is within the same depth-
967 # scoped tree as ctx_ou. both ou's are org unit objects.
968 $ctx->{org_within_scope} = sub {
969 my ($ctx_ou, $test_ou, $depth) = @_;
971 return 1 if $ctx_ou->id == $test_ou->id;
975 # find the top-most ctx-org ancestor at the provided depth
976 while ($depth < $ctx_ou->ou_type->depth
977 and $ctx_ou->id != $test_ou->id) {
978 $ctx_ou = $ctx->{get_aou}->($ctx_ou->parent_ou);
981 # the preceeding loop may have landed on our org
982 return 1 if $ctx_ou->id == $test_ou->id;
986 return 1 if defined $depth; # $depth == 0;
989 for my $child (@{$ctx_ou->children}) {
990 return 1 if $ctx->{org_within_scope}->($child, $test_ou);
996 # Returns true if the provided org unit is within the same
997 # org unit hiding depth-scoped tree as the physical location.
998 # Org unit hiding is based on the immutable physical_loc
999 # and is not meant to change as search/pref/etc libs change
1000 $ctx->{org_within_hiding_scope} = sub {
1002 my $ploc = $ctx->{physical_loc} or return 1;
1004 my $depth = $ctx->{get_org_setting}->(
1005 $ploc, 'opac.org_unit_hiding.depth');
1007 return 1 unless $depth; # 0 or undef
1009 return $ctx->{org_within_scope}->(
1010 $ctx->{get_aou}->($ploc),
1011 $ctx->{get_aou}->($org_id), $depth);
1015 # Evaluates to true if the context org (defaults to get_library)
1016 # is not within the hiding scope. Also evaluates to true if the
1017 # user's pref_ou is set and it's out of hiding scope.
1018 # Always evaluates to true when ctx.is_staff
1019 $ctx->{org_hiding_disabled} = sub {
1020 my $ctx_org = shift || $ctx->{search_ou};
1022 return 1 if $ctx->{is_staff};
1024 # beware locg values formatted as org:loc
1025 $ctx_org =~ s/:.*//g;
1027 return 1 if !$ctx->{org_within_hiding_scope}->($ctx_org);
1029 return 1 if $ctx->{pref_ou} and $ctx->{pref_ou} != $ctx_org
1030 and !$ctx->{org_within_hiding_scope}->($ctx->{pref_ou});
1037 # returns the list of org unit IDs for which the
1038 # selected org unit setting returned a true value
1039 sub setting_is_true_for_orgs {
1040 my ($self, $setting) = @_;
1041 my $ctx = $self->ctx;
1047 push (@valid_orgs, $org->id) if
1048 $ctx->{get_org_setting}->($org->id, $setting);
1049 $test_org->($_) for @{$org->children};
1052 $test_org->($ctx->{aou_tree}->());
1053 return \@valid_orgs;
1056 # Builds and links a perm checking function, testing permissions against
1057 # the currently logged in user.
1058 # ctx->{has_perm}->(perm_code, org_id) => 1/undef
1059 # For security, perm checks are cached per page, not per process.
1060 sub load_perm_funcs {
1063 $self->ctx->{has_perm} = sub {
1064 my ($perm_code, $org_id) = @_;
1065 return 0 unless $self->editor->requestor;
1067 if ($perm_cache{$org_id}) {
1068 return $perm_cache{$org_id}{$perm_code}
1069 if exists $perm_cache{$org_id}{$perm_code};
1071 $perm_cache{$org_id} = {};
1073 return $perm_cache{$org_id}{$perm_code} =
1074 $self->editor->allowed($perm_code, $org_id);