]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/WWW/EGCatLoader/Search.pm
Staff saved searches when browsing catalog in staff client
[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     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     $self->get_staff_search_settings;
171
172     if ($ctx->{staff_saved_search_size}) {
173         my ($key, $list) = $self->staff_save_search($query);
174         if ($key) {
175             $self->apache->headers_out->add(
176                 "Set-Cookie" => $self->cgi->cookie(
177                     -name => (ref $self)->COOKIE_ANON_CACHE,
178                     -path => "/",
179                     -value => ($key || ''),
180                     -expires => ($key ? undef : "-1h")
181                 )
182             );
183             $ctx->{saved_searches} = $list;
184         }
185     }
186
187     if ($metarecord) {
188
189         # TODO: other limits, like SVF/format, etc.
190         $results = $U->simplereq(
191             'open-ils.search', 
192             'open-ils.search.biblio.metarecord_to_records',
193             $metarecord, {org => $loc, depth => $depth}
194         );
195
196         # force the metarecord result blob to match the format of regular search results
197         $results->{ids} = [map { [$_] } @{$results->{ids}}]; 
198
199     } else {
200
201         return $self->generic_redirect unless $query;
202
203         # Limit and offset will stay here. Everything else should be part of
204         # the query string, not special args.
205         my $args = {'limit' => $limit, 'offset' => $offset};
206
207         # Stuff these into the TT context so that templates can use them in redrawing forms
208         $ctx->{processed_search_query} = $query;
209
210         $query = "$query $facet" if $facet; # TODO
211
212         $logger->activity("EGWeb: [search] $query");
213
214         try {
215
216             my $method = 'open-ils.search.biblio.multiclass.query';
217             $method .= '.staff' if $ctx->{is_staff};
218             $results = $U->simplereq('open-ils.search', $method, $args, $query, 1);
219
220         } catch Error with {
221             my $err = shift;
222             $logger->error("multiclass search error: $err");
223             $results = {count => 0, ids => []};
224         };
225     }
226
227     my $rec_ids = [map { $_->[0] } @{$results->{ids}}];
228
229     $ctx->{records} = [];
230     $ctx->{search_facets} = {};
231     $ctx->{page_size} = $limit;
232     $ctx->{hit_count} = $results->{count};
233     $ctx->{parsed_query} = $results->{parsed_query};
234
235     return Apache2::Const::OK if @$rec_ids == 0;
236
237     my ($facets, @data) = $self->get_records_and_facets(
238         $rec_ids, $results->{facet_key}, 
239         {
240             flesh => '{holdings_xml,mra,acp}',
241             site => $site,
242             depth => $depth
243         }
244     );
245
246     # shove recs into context in search results order
247     for my $rec_id (@$rec_ids) {
248         push(
249             @{$ctx->{records}},
250             grep { $_->{id} == $rec_id } @data
251         );
252     }
253
254     $ctx->{search_facets} = $facets;
255
256     return Apache2::Const::OK;
257 }
258
259 # Searching by barcode is a special search that does /not/ respect any other
260 # of the usual search parameters, not even the ones for sorting and paging!
261 sub item_barcode_shortcut {
262     my ($self) = @_;
263
264     my $method = "open-ils.search.multi_home.bib_ids.by_barcode";
265     if (my $search = create OpenSRF::AppSession("open-ils.search")) {
266         my $rec_ids = $search->request(
267             $method, $self->cgi->param("query")
268         )->gather(1);
269         $search->kill_me;
270
271         if (ref $rec_ids ne 'ARRAY') {
272
273             if($U->event_equals($rec_ids, 'ASSET_COPY_NOT_FOUND')) {
274                 $rec_ids = [];
275
276             } else {
277                 if (defined $U->event_code($rec_ids)) {
278                     $self->apache->log->warn(
279                         "$method returned event: " . $U->event_code($rec_ids)
280                     );
281                 } else {
282                     $self->apache->log->warn(
283                         "$method returned something unexpected: $rec_ids"
284                     );
285                 }
286                 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
287             }
288         }
289
290         my ($facets, @data) = $self->get_records_and_facets(
291             $rec_ids, undef, {flesh => "{holdings_xml,mra}"}
292         );
293
294         $self->ctx->{records} = [@data];
295         $self->ctx->{search_facets} = {};
296         $self->ctx->{hit_count} = scalar @data;
297         $self->ctx->{page_size} = $self->ctx->{hit_count};
298
299         return Apache2::Const::OK;
300     } {
301         $self->apache->log->warn("couldn't connect to open-ils.search");
302         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
303     }
304 }
305
306 # like item_barcode_search, this can't take all the usual search params, but
307 # this one will at least do site, limit and page
308 sub marc_expert_search {
309     my ($self) = @_;
310
311     my @tags = $self->cgi->param("tag");
312     my @subfields = $self->cgi->param("subfield");
313     my @terms = $self->cgi->param("term");
314
315     my $query = [];
316     for (my $i = 0; $i < scalar @tags; $i++) {
317         next if ($tags[$i] eq "" || $terms[$i] eq "");
318         $subfields[$i] = '_' unless $subfields[$i];
319         push @$query, {
320             "term" => $terms[$i],
321             "restrict" => [{"tag" => $tags[$i], "subfield" => $subfields[$i]}]
322         };
323     }
324
325     $logger->info("query for expert search: " . Dumper($query));
326
327     # loc, limit and offset
328     my $page = $self->cgi->param("page") || 0;
329     my $limit = $self->_get_search_limit;
330     my $org_unit = $self->cgi->param("loc") || $self->ctx->{aou_tree}->()->id;
331     my $offset = $page * $limit;
332
333     $self->ctx->{records} = [];
334     $self->ctx->{search_facets} = {};
335     $self->ctx->{page_size} = $limit;
336     $self->ctx->{hit_count} = 0;
337         
338     # nothing to do
339     return Apache2::Const::OK if @$query == 0;
340
341     my $results = $U->simplereq(
342         'open-ils.search', 
343         'open-ils.search.biblio.marc',
344         {searches => $query, org_unit => $org_unit}, $limit, $offset);
345
346     if (defined $U->event_code($results)) {
347         $self->apache->log->warn(
348             "open-ils.search.biblio.marc returned event: " .
349             $U->event_code($results)
350         );
351         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
352     }
353
354     my ($facets, @data) = $self->get_records_and_facets(
355         # filter out nulls that will turn up here
356         [ grep { $_ } @{$results->{ids}} ],
357         undef, {flesh => "{holdings_xml,mra}"}
358     );
359
360     $self->ctx->{records} = [@data];
361     $self->ctx->{page_size} = $limit;
362     $self->ctx->{hit_count} = $results->{count};
363
364     return Apache2::Const::OK;
365 }
366
367 sub call_number_browse_standalone {
368     my ($self) = @_;
369
370     if (my $cnfrag = $self->cgi->param("query")) {
371         my $url = sprintf(
372             'http%s://%s%s/cnbrowse?cn=%s',
373             $self->cgi->https ? "s" : "",
374             $self->apache->hostname,
375             $self->ctx->{opac_root},
376             $cnfrag # XXX some kind of escaping needed here?
377         );
378         return $self->generic_redirect($url);
379     } else {
380         return $self->generic_redirect; # return to search page
381     }
382 }
383
384 sub load_cnbrowse {
385     my ($self) = @_;
386
387     $self->prepare_browse_call_numbers();
388
389     return Apache2::Const::OK;
390 }
391
392 sub get_staff_search_settings {
393     my ($self) = @_;
394
395     unless ($self->ctx->{is_staff}) {
396         $self->ctx->{staff_saved_search_size} = 0;
397         return;
398     }
399
400     my $sss_size = $self->ctx->{get_org_setting}->(
401         $self->ctx->{orig_loc} || $self->ctx->{aou_tree}->()->id,
402         "opac.staff_saved_search.size",
403     );
404
405     # Sic: 0 is 0 (off), but undefined is 10.
406     $sss_size = 10 unless defined $sss_size;
407
408     $self->ctx->{staff_saved_search_size} = $sss_size;
409 }
410
411 sub staff_load_searches {
412     my ($self) = @_;
413
414     my $cache_key = $self->cgi->cookie((ref $self)->COOKIE_ANON_CACHE);
415
416     my $list = [];
417     if ($cache_key) {
418         $list = $U->simplereq(
419             "open-ils.actor",
420             "open-ils.actor.anon_cache.get_value",
421             $cache_key, (ref $self)->ANON_CACHE_STAFF_SEARCH
422         );
423
424         unless ($list) {
425             undef $cache_key;
426             $list = [];
427         }
428     }
429
430     return ($cache_key, $list);
431 }
432
433 sub staff_save_search {
434     my ($self, $query) = @_;
435
436     my $sss_size = $self->ctx->{staff_saved_search_size}; 
437     return unless $sss_size > 0;
438
439     my ($cache_key, $list) = $self->staff_load_searches;
440     my %already = ( map { $_ => 1 } @$list );
441
442     unshift @$list, $query unless $already{$query};
443
444     splice @$list, $sss_size;
445
446     $cache_key = $U->simplereq(
447         "open-ils.actor",
448         "open-ils.actor.anon_cache.set_value",
449         $cache_key, (ref $self)->ANON_CACHE_STAFF_SEARCH, $list
450     );
451
452     return ($cache_key, $list);
453 }
454
455 1;