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