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