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