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