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