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