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