]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/WWW/EGCatLoader/Search.pm
Clean up OpenSRF::AppSession objects after use
[working/Evergreen.git] / Open-ILS / src / perlmods / lib / OpenILS / WWW / EGCatLoader / Search.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 OpenSRF::Utils::Logger qw/$logger/;
5 use OpenILS::Utils::CStoreEditor qw/:funcs/;
6 use OpenILS::Utils::Fieldmapper;
7 use OpenILS::Application::AppUtils;
8 use OpenSRF::Utils::JSON;
9 use Data::Dumper;
10 $Data::Dumper::Indent = 0;
11 my $U = 'OpenILS::Application::AppUtils';
12
13
14 sub _prepare_biblio_search_basics {
15     my ($cgi) = @_;
16
17     return $cgi->param('query') unless $cgi->param('qtype');
18
19     my %parts;
20     my @part_names = qw/qtype contains query/;
21     $parts{$_} = [ $cgi->param($_) ] for (@part_names);
22
23     my @chunks = ();
24     for (my $i = 0; $i < scalar @{$parts{'qtype'}}; $i++) {
25         my ($qtype, $contains, $query) = map { $parts{$_}->[$i] } @part_names;
26
27         next unless $query =~ /\S/;
28         push(@chunks, $qtype . ':') unless $qtype eq 'keyword' and $i == 0;
29
30         # This stuff probably will need refined or rethought to better handle
31         # the weird things Real Users will surely type in.
32         $contains = "" unless defined $contains; # silence warning
33         if ($contains eq 'nocontains') {
34             $query =~ s/"//g;
35             $query = ('"' . $query . '"') if index $query, ' ';
36             $query = '-' . $query;
37         } elsif ($contains eq 'phrase') {
38             $query =~ s/"//g;
39             $query = ('"' . $query . '"') if index $query, ' ';
40         } elsif ($contains eq 'exact') {
41             $query =~ s/[\^\$]//g;
42             $query = '^' . $query . '$';
43         }
44         push @chunks, $query;
45     }
46
47     return join(' ', @chunks);
48 }
49
50 sub _prepare_biblio_search {
51     my ($cgi, $ctx) = @_;
52
53     my $query = _prepare_biblio_search_basics($cgi) || '';
54
55     $query = ('#' . $_ . ' ' . $query) foreach ($cgi->param('modifier'));
56
57     # filters
58     foreach (grep /^fi:/, $cgi->param) {
59         /:(-?\w+)$/ or next;
60         my $term = join(",", $cgi->param($_));
61         $query .= " $1($term)" if length $term;
62     }
63
64     if ($cgi->param('sort')) {
65         my ($axis, $desc) = split /\./, $cgi->param('sort');
66         $query .= " sort($axis)";
67         $query .= '#descending' if $desc;
68     }
69
70     if ($cgi->param('pubdate') && $cgi->param('date1')) {
71         if ($cgi->param('pubdate') eq 'between') {
72             $query .= ' between(' . $cgi->param('date1');
73             $query .= ',' .  $cgi->param('date2') if $cgi->param('date2');
74             $query .= ')';
75         } elsif ($cgi->param('pubdate') eq 'is') {
76             $query .= ' between(' . $cgi->param('date1') .
77                 ',' .  $cgi->param('date1') . ')';  # sic, date1 twice
78         } else {
79             $query .= ' ' . $cgi->param('pubdate') .
80                 '(' . $cgi->param('date1') . ')';
81         }
82     }
83
84     my $site;
85     my $org = $cgi->param('loc');
86     if (defined($org) and $org ne '' and ($org ne $ctx->{aou_tree}->()->id) and not $query =~ /site\(\S+\)/) {
87         $site = $ctx->{get_aou}->($org)->shortname;
88         $query .= " site($site)";
89     }
90
91     if(!$site) {
92         ($site) = ($query =~ /site\(([^\)]+)\)/);
93         $site ||= $ctx->{aou_tree}->()->shortname;
94     }
95
96
97     my $depth;
98     if (defined($cgi->param('depth')) and not $query =~ /depth\(\d+\)/) {
99         $depth = defined $cgi->param('depth') ?
100             $cgi->param('depth') : $ctx->{get_aou}->($site)->ou_type->depth;
101         $query .= " depth($depth)";
102     }
103
104     return ($query, $site, $depth);
105 }
106
107 sub _get_search_limit {
108     my $self = shift;
109
110     # param takes precedence
111     my $limit = $self->cgi->param('limit');
112     return $limit if $limit;
113
114     if($self->editor->requestor) {
115         # See if the user has a hit count preference
116         my $lset = $self->editor->search_actor_user_setting({
117             usr => $self->editor->requestor->id, 
118             name => 'opac.hits_per_page'
119         })->[0];
120         return OpenSRF::Utils::JSON->JSON2perl($lset->value) if $lset;
121     }
122
123     return 10; # default
124 }
125
126 # context additions: 
127 #   page_size
128 #   hit_count
129 #   records : list of bre's and copy-count objects
130 sub load_rresults {
131     my $self = shift;
132     my $cgi = $self->cgi;
133     my $ctx = $self->ctx;
134     my $e = $self->editor;
135
136     $ctx->{page} = 'rresult';
137
138     # Special alternative searches here.  This could all stand to be cleaner.
139     if ($cgi->param("_special")) {
140         return $self->marc_expert_search if scalar($cgi->param("tag"));
141         return $self->item_barcode_shortcut if (
142             $cgi->param("qtype") and ($cgi->param("qtype") eq "item_barcode")
143         );
144         return $self->call_number_browse_standalone if (
145             $cgi->param("qtype") and ($cgi->param("qtype") eq "cnbrowse")
146         );
147     }
148
149     my $page = $cgi->param('page') || 0;
150     my $facet = $cgi->param('facet');
151     my $limit = $self->_get_search_limit;
152     my $loc = $cgi->param('loc') || $ctx->{aou_tree}->()->id;
153     my $offset = $page * $limit;
154     my $metarecord = $cgi->param('metarecord');
155     my $results; 
156
157     my ($query, $site, $depth) = _prepare_biblio_search($cgi, $ctx);
158
159     if ($metarecord) {
160
161         # TODO: other limits, like SVF/format, etc.
162         $results = $U->simplereq(
163             'open-ils.search', 
164             'open-ils.search.biblio.metarecord_to_records',
165             $metarecord, {org => $loc, depth => $depth}
166         );
167
168         # force the metarecord result blob to match the format of regular search results
169         $results->{ids} = [map { [$_] } @{$results->{ids}}]; 
170
171     } else {
172
173         return $self->generic_redirect unless $query;
174
175         # Limit and offset will stay here. Everything else should be part of
176         # the query string, not special args.
177         my $args = {'limit' => $limit, 'offset' => $offset};
178
179         # Stuff these into the TT context so that templates can use them in redrawing forms
180         $ctx->{processed_search_query} = $query;
181
182         $query = "$query $facet" if $facet; # TODO
183
184         $logger->activity("EGWeb: [search] $query");
185
186         try {
187
188             my $method = 'open-ils.search.biblio.multiclass.query';
189             $method .= '.staff' if $ctx->{is_staff};
190             $results = $U->simplereq('open-ils.search', $method, $args, $query, 1);
191
192         } catch Error with {
193             my $err = shift;
194             $logger->error("multiclass search error: $err");
195             $results = {count => 0, ids => []};
196         };
197     }
198
199     my $rec_ids = [map { $_->[0] } @{$results->{ids}}];
200
201     $ctx->{records} = [];
202     $ctx->{search_facets} = {};
203     $ctx->{page_size} = $limit;
204     $ctx->{hit_count} = $results->{count};
205
206     return Apache2::Const::OK if @$rec_ids == 0;
207
208     my ($facets, @data) = $self->get_records_and_facets(
209         $rec_ids, $results->{facet_key}, 
210         {
211             flesh => '{holdings_xml,mra}',
212             site => $site,
213             depth => $depth
214         }
215     );
216
217     # shove recs into context in search results order
218     for my $rec_id (@$rec_ids) {
219         push(
220             @{$ctx->{records}},
221             grep { $_->{id} == $rec_id } @data
222         );
223     }
224
225     $ctx->{search_facets} = $facets;
226
227     return Apache2::Const::OK;
228 }
229
230 # Searching by barcode is a special search that does /not/ respect any other
231 # of the usual search parameters, not even the ones for sorting and paging!
232 sub item_barcode_shortcut {
233     my ($self) = @_;
234
235     my $method = "open-ils.search.multi_home.bib_ids.by_barcode";
236     if (my $search = create OpenSRF::AppSession("open-ils.search")) {
237         my $rec_ids = $search->request(
238             $method, $self->cgi->param("query")
239         )->gather(1);
240         $search->kill_me;
241
242         if (ref $rec_ids ne 'ARRAY') {
243
244             if($U->event_equals($rec_ids, 'ASSET_COPY_NOT_FOUND')) {
245                 $rec_ids = [];
246
247             } else {
248                 if (defined $U->event_code($rec_ids)) {
249                     $self->apache->log->warn(
250                         "$method returned event: " . $U->event_code($rec_ids)
251                     );
252                 } else {
253                     $self->apache->log->warn(
254                         "$method returned something unexpected: $rec_ids"
255                     );
256                 }
257                 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
258             }
259         }
260
261         my ($facets, @data) = $self->get_records_and_facets(
262             $rec_ids, undef, {flesh => "{holdings_xml,mra}"}
263         );
264
265         $self->ctx->{records} = [@data];
266         $self->ctx->{search_facets} = {};
267         $self->ctx->{hit_count} = scalar @data;
268         $self->ctx->{page_size} = $self->ctx->{hit_count};
269
270         return Apache2::Const::OK;
271     } {
272         $self->apache->log->warn("couldn't connect to open-ils.search");
273         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
274     }
275 }
276
277 # like item_barcode_search, this can't take all the usual search params, but
278 # this one will at least do site, limit and page
279 sub marc_expert_search {
280     my ($self) = @_;
281
282     my @tags = $self->cgi->param("tag");
283     my @subfields = $self->cgi->param("subfield");
284     my @terms = $self->cgi->param("term");
285
286     my $query = [];
287     for (my $i = 0; $i < scalar @tags; $i++) {
288         next if ($tags[$i] eq "" || $subfields[$i] eq "" || $terms[$i] eq "");
289         push @$query, {
290             "term" => $terms[$i],
291             "restrict" => [{"tag" => $tags[$i], "subfield" => $subfields[$i]}]
292         };
293     }
294
295     $logger->info("query for expert search: " . Dumper($query));
296     # loc, limit and offset
297     my $page = $self->cgi->param("page") || 0;
298     my $limit = $self->_get_search_limit;
299     my $org_unit = $self->cgi->param("loc") || $self->ctx->{aou_tree}->()->id;
300     my $offset = $page * $limit;
301
302     if (my $search = create OpenSRF::AppSession("open-ils.search")) {
303         my $results = $search->request(
304             "open-ils.search.biblio.marc", {
305                 "searches" => $query, "org_unit" => $org_unit
306             }, $limit, $offset
307         )->gather(1);
308         $search->kill_me;
309
310         if (defined $U->event_code($results)) {
311             $self->apache->log->warn(
312                 "open-ils.search.biblio.marc returned event: " .
313                 $U->event_code($results)
314             );
315             return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
316         }
317
318         my ($facets, @data) = $self->get_records_and_facets(
319             # filter out nulls that will turn up here
320             [ grep { $_ } @{$results->{ids}} ],
321             undef, {flesh => "{holdings_xml,mra}"}
322         );
323
324         $self->ctx->{records} = [@data];
325         $self->ctx->{search_facets} = {};
326
327         $self->ctx->{page_size} = $limit;
328         $self->ctx->{hit_count} = $results->{count};
329
330         return Apache2::Const::OK;
331     } else {
332         $self->apache->log->warn("couldn't connect to open-ils.search");
333         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
334     }
335 }
336
337 sub call_number_browse_standalone {
338     my ($self) = @_;
339
340     if (my $cnfrag = $self->cgi->param("query")) {
341         my $url = sprintf(
342             'http%s://%s%s/cnbrowse?cn=%s',
343             $self->cgi->https ? "s" : "",
344             $self->apache->hostname,
345             $self->ctx->{opac_root},
346             $cnfrag # XXX some kind of escaping needed here?
347         );
348         return $self->generic_redirect($url);
349     } else {
350         return $self->generic_redirect; # return to search page
351     }
352 }
353
354 sub load_cnbrowse {
355     my ($self) = @_;
356
357     $self->prepare_browse_call_numbers();
358
359     return Apache2::Const::OK;
360 }
361
362 1;