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