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