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