]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/WWW/EGCatLoader/Util.pm
tpac : search_HINT cache fixes
[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 OpenSRF::Utils::Logger qw/$logger/;
6 use OpenILS::Utils::CStoreEditor qw/:funcs/;
7 use OpenILS::Utils::Fieldmapper;
8 use OpenILS::Application::AppUtils;
9 use OpenSRF::MultiSession;
10 my $U = 'OpenILS::Application::AppUtils';
11
12 my $ro_object_subs; # cached subs
13 our %cache = ( # cached data
14     map => {aou => {}}, # others added dynamically as needed
15     list => {},
16     search => {},
17     org_settings => {},
18     eg_cache_hash => undef
19 );
20
21 sub init_ro_object_cache {
22     my $self = shift;
23     my $e = $self->editor;
24     my $ctx = $self->ctx;
25
26     # reset org unit setting cache on each page load to avoid the 
27     # requirement of reloading apache with each org-setting change
28     $cache{org_settings} = {};
29
30     if($ro_object_subs) {
31         # subs have been built.  insert into the context then move along.
32         $ctx->{$_} = $ro_object_subs->{$_} for keys %$ro_object_subs;
33         return;
34     }
35
36     # make all "field_safe" classes accesible by default in the template context
37     my @classes = grep {
38         ($Fieldmapper::fieldmap->{$_}->{field_safe} || '') =~ /true/i
39     } keys %{ $Fieldmapper::fieldmap };
40
41     for my $class (@classes) {
42
43         my $hint = $Fieldmapper::fieldmap->{$class}->{hint};
44         next if $hint eq 'aou'; # handled separately
45
46         my $ident_field =  $Fieldmapper::fieldmap->{$class}->{identity};
47         (my $eclass = $class) =~ s/Fieldmapper:://o;
48         $eclass =~ s/::/_/g;
49
50         my $list_key = "${hint}_list";
51         my $get_key = "get_$hint";
52         my $search_key = "search_$hint";
53
54         # Retrieve the full set of objects with class $hint
55         $ro_object_subs->{$list_key} = sub {
56             my $method = "retrieve_all_$eclass";
57             $cache{list}{$hint} = $e->$method() unless $cache{list}{$hint};
58             return $cache{list}{$hint};
59         };
60     
61         # locate object of class $hint with Ident field $id
62         $cache{map}{$hint} = {};
63         $ro_object_subs->{$get_key} = sub {
64             my $id = shift;
65             return $cache{map}{$hint}{$id} if $cache{map}{$hint}{$id}; 
66             ($cache{map}{$hint}{$id}) = grep { $_->$ident_field eq $id } @{$ro_object_subs->{$list_key}->()};
67             return $cache{map}{$hint}{$id};
68         };
69
70         # search for objects of class $hint where field=value
71         $cache{search}{$hint} = {};
72         $ro_object_subs->{$search_key} = sub {
73             my ($field, $val, $filterfield, $filterval) = @_;
74             my $method = "search_$eclass";
75             my $cacheval = $val;
76             if (ref $val) {
77                 $val = [sort(@$val)] if ref $val eq 'ARRAY';
78                 $cacheval = OpenSRF::Utils::JSON->perl2JSON($val); 
79                 #$self->apache->log->info("cacheval : $cacheval");
80             }
81             my $search_obj = {$field => $val};
82             if($filterfield) {
83                 $search_obj->{$filterfield} = $filterval;
84                 $cacheval .= ':' . $filterfield . ':' . $filterval;
85             }
86             $cache{search}{$hint}{$field} = {} unless $cache{search}{$hint}{$field};
87             $cache{search}{$hint}{$field}{$cacheval} = $e->$method($search_obj) 
88                 unless $cache{search}{$hint}{$field}{$cacheval};
89             return $cache{search}{$hint}{$field}{$cacheval};
90         };
91     }
92
93     $ro_object_subs->{aou_tree} = sub {
94
95         # fetch the org unit tree
96         unless($cache{aou_tree}) {
97             my $tree = $e->search_actor_org_unit([
98                             {   parent_ou => undef},
99                             {   flesh            => -1,
100                                     flesh_fields    => {aou =>  ['children']},
101                                     order_by        => {aou => 'name'}
102                             }
103                     ])->[0];
104
105             # flesh the org unit type for each org unit
106             # and simultaneously set the id => aou map cache
107             sub flesh_aout {
108                 my $node = shift;
109                 my $ro_object_subs = shift;
110                 $node->ou_type( $ro_object_subs->{get_aout}->($node->ou_type) );
111                 $cache{map}{aou}{$node->id} = $node;
112                 flesh_aout($_, $ro_object_subs) foreach @{$node->children};
113             };
114             flesh_aout($tree, $ro_object_subs);
115
116             $cache{aou_tree} = $tree;
117         }
118
119         return $cache{aou_tree};
120     };
121
122     # Add a special handler for the tree-shaped org unit cache
123     $ro_object_subs->{get_aou} = sub {
124         my $org_id = shift;
125         return undef unless defined $org_id;
126         $ro_object_subs->{aou_tree}->(); # force the org tree to load
127         return $cache{map}{aou}{$org_id};
128     };
129
130     # Returns a flat list of aou objects.  often easier to manage than a tree.
131     $ro_object_subs->{aou_list} = sub {
132         $ro_object_subs->{aou_tree}->(); # force the org tree to load
133         return [ values %{$cache{map}{aou}} ];
134     };
135
136     $ro_object_subs->{aouct_tree} = sub {
137
138         # fetch the org unit tree
139         unless(exists $cache{aouct_tree}) {
140             $cache{aouct_tree} = undef;
141
142             my $tree_id = $e->search_actor_org_unit_custom_tree(
143                 {purpose => 'opac', active => 't'},
144                 {idlist => 1}
145             )->[0];
146
147             if ($tree_id) {
148                 my $node_tree = $e->search_actor_org_unit_custom_tree_node([
149                 {parent_node => undef, tree => $tree_id},
150                 {   flesh        => -1,
151                     flesh_fields => {aouctn => ['children', 'org_unit']},
152                     order_by     => {aouctn => 'sibling_order'}
153                 }
154                 ])->[0];
155
156                 # tree-ify the org units.  note that since the orgs are fleshed
157                 # upon retrieval, this org tree will not clobber ctx->{aou_tree}.
158                 my @nodes = ($node_tree);
159                 while (my $node = shift(@nodes)) {
160                     my $aou = $node->org_unit;
161                     $aou->children([]);
162                     for my $cnode (@{$node->children}) {
163                         my $child_org = $cnode->org_unit;
164                         $child_org->parent_ou($aou->id);
165                         $child_org->ou_type( $ro_object_subs->{get_aout}->($child_org->ou_type) );
166                         push(@{$aou->children}, $child_org);
167                         push(@nodes, $cnode);
168                     }
169                 }
170
171                 $cache{aouct_tree} = $node_tree->org_unit;
172             }
173         }
174
175         return $cache{aouct_tree};
176     };
177
178     # turns an ISO date into something TT can understand
179     $ro_object_subs->{parse_datetime} = sub {
180         my $date = shift;
181         $date = DateTime::Format::ISO8601->new->parse_datetime(cleanse_ISO8601($date));
182         return sprintf(
183             "%0.2d:%0.2d:%0.2d %0.2d-%0.2d-%0.4d",
184             $date->hour,
185             $date->minute,
186             $date->second,
187             $date->day,
188             $date->month,
189             $date->year
190         );
191     };
192
193     # retrieve and cache org unit setting values
194     $ro_object_subs->{get_org_setting} = sub {
195         my($org_id, $setting) = @_;
196
197         $cache{org_settings}{$org_id} = {} 
198             unless $cache{org_settings}{$org_id};
199
200         $cache{org_settings}{$org_id}{$setting} = 
201             $U->ou_ancestor_setting_value($org_id, $setting)
202                 unless exists $cache{org_settings}{$org_id}{$setting};
203
204         return $cache{org_settings}{$org_id}{$setting};
205     };
206
207     $ctx->{$_} = $ro_object_subs->{$_} for keys %$ro_object_subs;
208 }
209
210 sub generic_redirect {
211     my $self = shift;
212     my $url = shift;
213     my $cookie = shift; # can be an array of cgi.cookie's
214
215     $self->apache->print(
216         $self->cgi->redirect(
217             -url => $url || 
218                 $self->cgi->param('redirect_to') || 
219                 $self->ctx->{referer} || 
220                 $self->ctx->{home_page},
221             -cookie => $cookie
222         )
223     );
224
225     return Apache2::Const::REDIRECT;
226 }
227
228 sub get_records_and_facets {
229     my ($self, $rec_ids, $facet_key, $unapi_args) = @_;
230
231     $unapi_args ||= {};
232     $unapi_args->{site} ||= $self->ctx->{aou_tree}->()->shortname;
233     $unapi_args->{depth} ||= $self->ctx->{aou_tree}->()->ou_type->depth;
234     $unapi_args->{flesh_depth} ||= 5;
235
236     my @data;
237     my $outer_self = $self;
238     $self->timelog("get_records_and_facets(): about to call multisession");
239     my $ses = OpenSRF::MultiSession->new(
240         app => 'open-ils.cstore',
241         cap => 10, # XXX config
242         success_handler => sub {
243             my($self, $req) = @_;
244             my $data = $req->{response}->[0]->content;
245
246             $outer_self->timelog("get_records_and_facets(): got response content");
247
248             # Protect against requests for non-existent records
249             return unless $data->{'unapi.bre'};
250
251             my $xml = XML::LibXML->new->parse_string($data->{'unapi.bre'})->documentElement;
252
253             $outer_self->timelog("get_records_and_facets(): parsed xml");
254             # Protect against legacy invalid MARCXML that might not have a 901c
255             my $bre_id;
256             my $bre_id_nodes =  $xml->find('*[@tag="901"]/*[@code="c"]');
257             if ($bre_id_nodes) {
258                 $bre_id =  $bre_id_nodes->[0]->textContent;
259             } else {
260                 $logger->warn("Missing 901 subfield 'c' in " . $xml->toString());
261             }
262             push(@data, {id => $bre_id, marc_xml => $xml});
263             $outer_self->timelog("get_records_and_facets(): end of success handler");
264         }
265     );
266
267     $self->timelog("get_records_and_facets(): about to call unapi.bre via json_query (rec_ids has " . scalar(@$rec_ids));
268
269     $ses->request(
270         'open-ils.cstore.json_query',
271          {from => [
272             'unapi.bre', $_, 'marcxml','record', 
273             $unapi_args->{flesh}, 
274             $unapi_args->{site}, 
275             $unapi_args->{depth}, 
276             'acn=>' . $unapi_args->{flesh_depth} . ',acp=>' . $unapi_args->{flesh_depth}, 
277             undef, undef, $unapi_args->{pref_lib}
278         ]}
279     ) for @$rec_ids;
280
281
282     $self->timelog("get_records_and_facets():almost ready to fetch facets");
283     # collect the facet data
284     my $search = OpenSRF::AppSession->create('open-ils.search');
285     my $facet_req = $search->request(
286         'open-ils.search.facet_cache.retrieve', $facet_key, 10
287     ) if $facet_key;
288
289     # gather up the unapi recs
290     $ses->session_wait(1);
291     $self->timelog("get_records_and_facets():past session wait");
292
293     my $facets = {};
294     if ($facet_key) {
295         my $tmp_facets = $facet_req->gather(1);
296         $self->timelog("get_records_and_facets(): gathered facet data");
297         for my $cmf_id (keys %$tmp_facets) {
298
299             # sort highest to lowest match count
300             my @entries;
301             my $entries = $tmp_facets->{$cmf_id};
302             for my $ent (keys %$entries) {
303                 push(@entries, {value => $ent, count => $$entries{$ent}});
304             };
305             @entries = sort { $b->{count} <=> $a->{count} } @entries;
306             $facets->{$cmf_id} = {
307                 cmf => $self->ctx->{get_cmf}->($cmf_id),
308                 data => \@entries
309             }
310         }
311         $self->timelog("get_records_and_facets(): gathered/sorted facet data");
312     } else {
313         $facets = undef;
314     }
315
316     $search->kill_me;
317
318     return ($facets, @data);
319 }
320
321 # TODO: blend this code w/ ^-- get_records_and_facets
322 sub fetch_marc_xml_by_id {
323     my ($self, $id_list) = @_;
324     $id_list = [$id_list] unless ref($id_list);
325
326     {
327         no warnings qw/numeric/;
328         $id_list = [map { int $_ } @$id_list];
329         $id_list = [grep { $_ > 0} @$id_list];
330     };
331
332     return {} if scalar(@$id_list) < 1;
333
334     # I'm just sure there needs to be some more efficient way to get all of
335     # this.
336     my $results = $self->editor->json_query({
337         "select" => {"bre" => ["id", "marc"]},
338         "from" => {"bre" => {}},
339         "where" => {"id" => $id_list}
340     }, {substream => 1}) or return $self->editor->die_event;
341
342     my $marc_xml = {};
343     for my $r (@$results) {
344         $marc_xml->{$r->{"id"}} =
345             (new XML::LibXML)->parse_string($r->{"marc"});
346     }
347
348     return $marc_xml;
349 }
350
351 sub _get_search_lib {
352     my $self = shift;
353     my $ctx = $self->ctx;
354
355     # avoid duplicate lookups
356     return $ctx->{search_ou} if $ctx->{search_ou};
357
358     my $loc = $ctx->{copy_location_group_org};
359     return $loc if $loc;
360
361     # loc param takes precedence
362     $loc = $self->cgi->param('loc');
363     return $loc if $loc;
364
365     my $pref_lib = $self->_get_pref_lib();
366     return $pref_lib if $pref_lib;
367
368     return $ctx->{aou_tree}->()->id;
369 }
370
371 sub _get_pref_lib {
372     my $self = shift;
373     my $ctx = $self->ctx;
374
375     # plib param takes precedence
376     my $plib = $self->cgi->param('plib');
377     return $plib if $plib;
378
379     if ($ctx->{user}) {
380         # See if the user has a search library preference
381         my $lset = $self->editor->search_actor_user_setting({
382             usr => $ctx->{user}->id, 
383             name => 'opac.default_search_location'
384         })->[0];
385         return OpenSRF::Utils::JSON->JSON2perl($lset->value) if $lset;
386
387         # Otherwise return the user's home library
388         return $ctx->{user}->home_ou;
389     }
390
391     if ($self->cgi->param('physical_loc')) {
392         return $self->cgi->param('physical_loc');
393     }
394
395 }
396
397 # This is defensively coded since we don't do much manual reading from the
398 # file system in this module.
399 sub load_eg_cache_hash {
400     my ($self) = @_;
401
402     # just a context helper
403     $self->ctx->{eg_cache_hash} = sub { return $cache{eg_cache_hash}; };
404
405     # Need to actually load the value? If already done, move on.
406     return if defined $cache{eg_cache_hash};
407
408     # In this way even if we fail, we won't slow things down by ever trying
409     # again within this Apache process' lifetime.
410     $cache{eg_cache_hash} = 0;
411
412     my $path = File::Spec->catfile(
413         $self->apache->document_root, "eg_cache_hash"
414     );
415
416     if (not open FH, "<$path") {
417         $self->apache->log->warn("error opening $path : $!");
418         return;
419     } else {
420         my $buf;
421         my $rv = read FH, $buf, 64;  # defensive
422         close FH;
423
424         if (not defined $rv) {  # error
425             $self->apache->log->warn("error reading $path : $!");
426         } elsif ($rv > 0) {     # no error, something read
427             chomp $buf;
428             $cache{eg_cache_hash} = $buf;
429         }
430     }
431 }
432
433 # Extracts the copy location org unit and group from the 
434 # "logc" param, which takes the form org_id:grp_id.
435 sub extract_copy_location_group_info {
436     my $self = shift;
437     my $ctx = $self->ctx;
438     if (my $clump = $self->cgi->param('locg')) {
439         my ($org, $grp) = split(/:/, $clump);
440         $ctx->{copy_location_group_org} = $org;
441         $ctx->{copy_location_group} = $grp if $grp;
442     }
443 }
444
445 sub load_copy_location_groups {
446     my $self = shift;
447     my $ctx = $self->ctx;
448
449     # User can access to the search location groups at the current 
450     # search lib, the physical location lib, and the patron's home ou.
451     my @ctx_orgs = $ctx->{search_ou};
452     push(@ctx_orgs, $ctx->{physical_loc}) if $ctx->{physical_loc};
453     push(@ctx_orgs, $ctx->{user}->home_ou) if $ctx->{user};
454
455     my $grps = $self->editor->search_asset_copy_location_group([
456         {
457             opac_visible => 't',
458             owner => {
459                 in => {
460                     select => {aou => [{
461                         column => 'id', 
462                         transform => 'actor.org_unit_full_path',
463                         result_field => 'id',
464                     }]},
465                     from => 'aou',
466                     where => {id => \@ctx_orgs}
467                 }
468             }
469         },
470         {order_by => {acplg => 'pos'}}
471     ]);
472
473     my %buckets;
474     push(@{$buckets{$_->owner}}, $_) for @$grps;
475     $ctx->{copy_location_groups} = \%buckets;
476 }
477
478 sub set_file_download_headers {
479     my $self = shift;
480     my $filename = shift;
481     my $ctype = shift || "text/plain; encoding=utf8";
482
483     $self->apache->content_type($ctype);
484
485     $self->apache->headers_out->add(
486         "Content-Disposition",
487         "attachment;filename=$filename"
488     );
489
490     return Apache2::Const::OK;
491 }
492
493 sub apache_log_if_event {
494     my ($self, $event, $prefix_text, $success_ok, $level) = @_;
495
496     $prefix_text ||= "Evergreen returned event";
497     $success_ok ||= 0;
498     $level ||= "warn";
499
500     chomp $prefix_text;
501     $prefix_text .= ": ";
502
503     my $code = $U->event_code($event);
504     if (defined $code and ($code or not $success_ok)) {
505         $self->apache->log->$level(
506             $prefix_text .
507             ($event->{textcode} || "") . " ($code)" .
508             ($event->{note} ? (": " . $event->{note}) : "")
509         );
510         return 1;
511     }
512
513     return;
514 }
515
516 1;