]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/WWW/EGCatLoader/Search.pm
Merge remote branch 'working/user/berick/marc-stream-importer-read-repair'
[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 # when fetching "all" search results for staff client 
14 # start/end paging, fetch this many IDs at most
15 my $all_recs_limit = 10000;
16
17
18 sub _prepare_biblio_search_basics {
19     my ($cgi) = @_;
20
21     return $cgi->param('query') unless $cgi->param('qtype');
22
23     my %parts;
24     my @part_names = qw/qtype contains query bool/;
25     $parts{$_} = [ $cgi->param($_) ] for (@part_names);
26
27     my $full_query = '';
28     for (my $i = 0; $i < scalar @{$parts{'qtype'}}; $i++) {
29         my ($qtype, $contains, $query, $bool) = map { $parts{$_}->[$i] } @part_names;
30
31         next unless $query =~ /\S/;
32
33         # This stuff probably will need refined or rethought to better handle
34         # the weird things Real Users will surely type in.
35         $contains = "" unless defined $contains; # silence warning
36         if ($contains eq 'nocontains') {
37             $query =~ s/"//g;
38             $query = ('"' . $query . '"') if index $query, ' ';
39             $query = '-' . $query;
40         } elsif ($contains eq 'phrase') {
41             $query =~ s/"//g;
42             $query = ('"' . $query . '"') if index $query, ' ';
43         } elsif ($contains eq 'exact') {
44             $query =~ s/[\^\$]//g;
45             $query = '^' . $query . '$';
46         }
47         $query = "$qtype:$query" unless $qtype eq 'keyword' and $i == 0;
48
49         $bool = ($bool and $bool eq 'or') ? '||' : '&&';
50         $full_query = $full_query ? "($full_query $bool $query)" : $query;
51     }
52
53     return $full_query;
54 }
55
56 sub _prepare_biblio_search {
57     my ($cgi, $ctx) = @_;
58
59     my $query = _prepare_biblio_search_basics($cgi) || '';
60
61     foreach ($cgi->param('modifier')) {
62         # The unless bit is to avoid stacking modifiers.
63         $query = ('#' . $_ . ' ' . $query) unless $query =~ qr/\#\Q$_/;
64     }
65
66     # filters
67     foreach (grep /^fi:/, $cgi->param) {
68         /:(-?\w+)$/ or next;
69         my $term = join(",", $cgi->param($_));
70         $query .= " $1($term)" if length $term;
71     }
72
73     # sort is treated specially, even though it's actually a filter
74     if ($cgi->param('sort')) {
75         $query =~ s/sort\([^\)]*\)//g;  # override existing sort(). no stacking.
76         my ($axis, $desc) = split /\./, $cgi->param('sort');
77         $query .= " sort($axis)";
78         if ($desc and not $query =~ /\#descending/) {
79             $query .= '#descending';
80         } elsif (not $desc) {
81             $query =~ s/\#descending//;
82         }
83     }
84
85     if ($cgi->param('pubdate') && $cgi->param('date1')) {
86         if ($cgi->param('pubdate') eq 'between') {
87             $query .= ' between(' . $cgi->param('date1');
88             $query .= ',' .  $cgi->param('date2') if $cgi->param('date2');
89             $query .= ')';
90         } elsif ($cgi->param('pubdate') eq 'is') {
91             $query .= ' between(' . $cgi->param('date1') .
92                 ',' .  $cgi->param('date1') . ')';  # sic, date1 twice
93         } else {
94             $query .= ' ' . $cgi->param('pubdate') .
95                 '(' . $cgi->param('date1') . ')';
96         }
97     }
98
99     my $site;
100     my $org = $cgi->param('loc');
101     if (defined($org) and $org ne '' and ($org ne $ctx->{aou_tree}->()->id) and not $query =~ /site\(\S+\)/) {
102         $site = $ctx->{get_aou}->($org)->shortname;
103         $query .= " site($site)";
104     }
105
106     if(!$site) {
107         ($site) = ($query =~ /site\(([^\)]+)\)/);
108         $site ||= $ctx->{aou_tree}->()->shortname;
109     }
110
111
112     my $depth;
113     if (defined($cgi->param('depth')) and not $query =~ /depth\(\d+\)/) {
114         $depth = defined $cgi->param('depth') ?
115             $cgi->param('depth') : $ctx->{get_aou}->($site)->ou_type->depth;
116         $query .= " depth($depth)";
117     }
118
119     return ($query, $site, $depth);
120 }
121
122 sub _get_search_limit {
123     my $self = shift;
124
125     # param takes precedence
126     my $limit = $self->cgi->param('limit');
127     return $limit if $limit;
128
129     if($self->editor->requestor) {
130         # See if the user has a hit count preference
131         my $lset = $self->editor->search_actor_user_setting({
132             usr => $self->editor->requestor->id, 
133             name => 'opac.hits_per_page'
134         })->[0];
135         return OpenSRF::Utils::JSON->JSON2perl($lset->value) if $lset;
136     }
137
138     return 10; # default
139 }
140
141 # context additions: 
142 #   page_size
143 #   hit_count
144 #   records : list of bre's and copy-count objects
145 sub load_rresults {
146     my $self = shift;
147     my %args = @_;
148     my $internal = $args{internal};
149     my $cgi = $self->cgi;
150     my $ctx = $self->ctx;
151     my $e = $self->editor;
152
153     $ctx->{page} = 'rresult' unless $internal;
154     $ctx->{ids} = [];
155     $ctx->{records} = [];
156     $ctx->{search_facets} = {};
157     $ctx->{hit_count} = 0;
158
159     # Special alternative searches here.  This could all stand to be cleaner.
160     if ($cgi->param("_special")) {
161         return $self->marc_expert_search(%args) if scalar($cgi->param("tag"));
162         return $self->item_barcode_shortcut if (
163             $cgi->param("qtype") and ($cgi->param("qtype") eq "item_barcode")
164         );
165         return $self->call_number_browse_standalone if (
166             $cgi->param("qtype") and ($cgi->param("qtype") eq "cnbrowse")
167         );
168     }
169
170     my $page = $cgi->param('page') || 0;
171     my @facets = $cgi->param('facet');
172     my $limit = $self->_get_search_limit;
173     my $loc = $cgi->param('loc') || $ctx->{aou_tree}->()->id;
174     my $offset = $page * $limit;
175     my $metarecord = $cgi->param('metarecord');
176     my $results; 
177
178     $ctx->{page_size} = $limit;
179     $ctx->{search_page} = $page;
180
181     # fetch the first hit from the next page
182     if ($internal) {
183         $limit = $all_recs_limit;
184         $offset = 0;
185     }
186
187     my ($query, $site, $depth) = _prepare_biblio_search($cgi, $ctx);
188
189     $self->get_staff_search_settings;
190
191     if ($ctx->{staff_saved_search_size}) {
192         my ($key, $list) = $self->staff_save_search($query);
193         if ($key) {
194             $self->apache->headers_out->add(
195                 "Set-Cookie" => $self->cgi->cookie(
196                     -name => (ref $self)->COOKIE_ANON_CACHE,
197                     -path => "/",
198                     -value => ($key || ''),
199                     -expires => ($key ? undef : "-1h")
200                 )
201             );
202             $ctx->{saved_searches} = $list;
203         }
204     }
205
206     if ($metarecord and !$internal) {
207
208         # TODO: other limits, like SVF/format, etc.
209         $results = $U->simplereq(
210             'open-ils.search', 
211             'open-ils.search.biblio.metarecord_to_records',
212             $metarecord, {org => $loc, depth => $depth}
213         );
214
215         # force the metarecord result blob to match the format of regular search results
216         $results->{ids} = [map { [$_] } @{$results->{ids}}]; 
217
218     } else {
219
220         if (!$query) {
221             return Apache2::Const::OK if $internal;
222             return $self->generic_redirect;
223         }
224
225         # Limit and offset will stay here. Everything else should be part of
226         # the query string, not special args.
227         my $args = {'limit' => $limit, 'offset' => $offset};
228
229         # Stuff these into the TT context so that templates can use them in redrawing forms
230         $ctx->{processed_search_query} = $query;
231
232         $query .= " $_" for @facets;
233
234         $logger->activity("EGWeb: [search] $query");
235
236         try {
237
238             my $method = 'open-ils.search.biblio.multiclass.query';
239             $method .= '.staff' if $ctx->{is_staff};
240             $results = $U->simplereq('open-ils.search', $method, $args, $query, 1);
241
242         } catch Error with {
243             my $err = shift;
244             $logger->error("multiclass search error: $err");
245             $results = {count => 0, ids => []};
246         };
247     }
248
249     my $rec_ids = [map { $_->[0] } @{$results->{ids}}];
250
251     $ctx->{ids} = $rec_ids;
252     $ctx->{hit_count} = $results->{count};
253     $ctx->{parsed_query} = $results->{parsed_query};
254
255     return Apache2::Const::OK if @$rec_ids == 0 or $internal;
256
257     my ($facets, @data) = $self->get_records_and_facets(
258         $rec_ids, $results->{facet_key}, 
259         {
260             flesh => '{holdings_xml,mra,acp}',
261             site => $site,
262             depth => $depth
263         }
264     );
265
266     if ($page == 0) {
267         my $stat = $self->check_1hit_redirect($rec_ids);
268         return $stat if $stat;
269     }
270
271     # shove recs into context in search results order
272     for my $rec_id (@$rec_ids) {
273         push(
274             @{$ctx->{records}},
275             grep { $_->{id} == $rec_id } @data
276         );
277     }
278
279     $ctx->{search_facets} = $facets;
280
281     return Apache2::Const::OK;
282 }
283
284 # If the calling search results in 1 record and the client
285 # is configured to do so, redirect the search results to 
286 # the record details page.
287 sub check_1hit_redirect {
288     my ($self, $rec_ids) = @_;
289     my $ctx = $self->ctx;
290
291     return undef unless $rec_ids and @$rec_ids == 1;
292
293     my ($sname, $org);
294
295     if ($ctx->{is_staff}) {
296         $sname = 'opac.staff.jump_to_details_on_single_hit';
297         $org = $ctx->{user}->ws_ou;
298
299     } else {
300         $sname = 'opac.patron.jump_to_details_on_single_hit';
301         $org = ($ctx->{user}) ? 
302             $ctx->{user}->home_ou : 
303             $ctx->{orig_loc} || 
304             $self->ctx->{aou_tree}->()->id;
305     }
306
307     return undef unless 
308         $self->ctx->{get_org_setting}->($org, $sname);
309
310     my $base_url = sprintf(
311         '%s://%s%s/record/%s',
312         $ctx->{proto}, 
313         $self->apache->hostname,
314         $self->ctx->{opac_root},
315         $$rec_ids[0],
316     );
317     
318     # If we get here from the same record detail page to which we
319     # now wish to redirect, do not perform the redirect.  This
320     # approach seems to work well, with the rare exception of 
321     # performing a new serach directly from the detail page that 
322     # happens to result in the same single hit.  In this case, the 
323     # user will be left on the search results page.  This could be 
324     # overcome w/ additional CGI, etc., but I'm not sure it's necessary.
325     if (my $referer = $ctx->{referer}) {
326         $referer =~ s/([^?]*).*/$1/g;
327         return undef if $base_url eq $referer;
328     }
329
330     return $self->generic_redirect($base_url . '?' . $self->cgi->query_string);
331 }
332
333 # Searching by barcode is a special search that does /not/ respect any other
334 # of the usual search parameters, not even the ones for sorting and paging!
335 sub item_barcode_shortcut {
336     my ($self) = @_;
337
338     my $method = "open-ils.search.multi_home.bib_ids.by_barcode";
339     if (my $search = create OpenSRF::AppSession("open-ils.search")) {
340         my $rec_ids = $search->request(
341             $method, $self->cgi->param("query")
342         )->gather(1);
343         $search->kill_me;
344
345         if (ref $rec_ids ne 'ARRAY') {
346
347             if($U->event_equals($rec_ids, 'ASSET_COPY_NOT_FOUND')) {
348                 $rec_ids = [];
349
350             } else {
351                 if (defined $U->event_code($rec_ids)) {
352                     $self->apache->log->warn(
353                         "$method returned event: " . $U->event_code($rec_ids)
354                     );
355                 } else {
356                     $self->apache->log->warn(
357                         "$method returned something unexpected: $rec_ids"
358                     );
359                 }
360                 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
361             }
362         }
363
364         my ($facets, @data) = $self->get_records_and_facets(
365             $rec_ids, undef, {flesh => "{holdings_xml,mra}"}
366         );
367
368         $self->ctx->{records} = [@data];
369         $self->ctx->{search_facets} = {};
370         $self->ctx->{hit_count} = scalar @data;
371         $self->ctx->{page_size} = $self->ctx->{hit_count};
372
373         return Apache2::Const::OK;
374     } {
375         $self->apache->log->warn("couldn't connect to open-ils.search");
376         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
377     }
378 }
379
380 # like item_barcode_search, this can't take all the usual search params, but
381 # this one will at least do site, limit and page
382 sub marc_expert_search {
383     my ($self, %args) = @_;
384
385     my @tags = $self->cgi->param("tag");
386     my @subfields = $self->cgi->param("subfield");
387     my @terms = $self->cgi->param("term");
388
389     my $query = [];
390     for (my $i = 0; $i < scalar @tags; $i++) {
391         next if ($tags[$i] eq "" || $terms[$i] eq "");
392         $subfields[$i] = '_' unless $subfields[$i];
393         push @$query, {
394             "term" => $terms[$i],
395             "restrict" => [{"tag" => $tags[$i], "subfield" => $subfields[$i]}]
396         };
397     }
398
399     $logger->info("query for expert search: " . Dumper($query));
400
401     # loc, limit and offset
402     my $page = $self->cgi->param("page") || 0;
403     my $limit = $self->_get_search_limit;
404     my $org_unit = $self->cgi->param("loc") || $self->ctx->{aou_tree}->()->id;
405     my $offset = $page * $limit;
406
407     $self->ctx->{records} = [];
408     $self->ctx->{search_facets} = {};
409     $self->ctx->{page_size} = $limit;
410     $self->ctx->{hit_count} = 0;
411     $self->ctx->{ids} = [];
412     $self->ctx->{search_page} = $page;
413         
414     # nothing to do
415     return Apache2::Const::OK if @$query == 0;
416
417     if ($args{internal}) {
418         $limit = $all_recs_limit;
419         $offset = 0;
420     }
421
422     my $timeout = 120;
423     my $ses = OpenSRF::AppSession->create('open-ils.search');
424     my $req = $ses->request(
425         'open-ils.search.biblio.marc',
426         {searches => $query, org_unit => $org_unit}, 
427         $limit, $offset, $timeout);
428
429     my $resp = $req->recv($timeout);
430     my $results = $resp ? $resp->content : undef;
431     $ses->kill_me;
432
433     if (defined $U->event_code($results)) {
434         $self->apache->log->warn(
435             "open-ils.search.biblio.marc returned event: " .
436             $U->event_code($results)
437         );
438         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
439     }
440
441     $self->ctx->{ids} = [ grep { $_ } @{$results->{ids}} ];
442     $self->ctx->{hit_count} = $results->{count};
443
444     return Apache2::Const::OK if @{$self->ctx->{ids}} == 0 or $args{internal};
445
446     if ($page == 0) {
447         my $stat = $self->check_1hit_redirect($self->ctx->{ids});
448         return $stat if $stat;
449     }
450
451     my ($facets, @data) = $self->get_records_and_facets(
452         $self->ctx->{ids}, undef, {flesh => "{holdings_xml,mra}"}
453     );
454
455     $self->ctx->{records} = [@data];
456
457     return Apache2::Const::OK;
458 }
459
460 sub call_number_browse_standalone {
461     my ($self) = @_;
462
463     if (my $cnfrag = $self->cgi->param("query")) {
464         my $url = sprintf(
465             'http%s://%s%s/cnbrowse?cn=%s',
466             $self->cgi->https ? "s" : "",
467             $self->apache->hostname,
468             $self->ctx->{opac_root},
469             $cnfrag # XXX some kind of escaping needed here?
470         );
471         return $self->generic_redirect($url);
472     } else {
473         return $self->generic_redirect; # return to search page
474     }
475 }
476
477 sub load_cnbrowse {
478     my ($self) = @_;
479
480     $self->prepare_browse_call_numbers();
481
482     return Apache2::Const::OK;
483 }
484
485 sub get_staff_search_settings {
486     my ($self) = @_;
487
488     unless ($self->ctx->{is_staff}) {
489         $self->ctx->{staff_saved_search_size} = 0;
490         return;
491     }
492
493     my $sss_size = $self->ctx->{get_org_setting}->(
494         $self->ctx->{orig_loc} || $self->ctx->{aou_tree}->()->id,
495         "opac.staff_saved_search.size",
496     );
497
498     # Sic: 0 is 0 (off), but undefined is 10.
499     $sss_size = 10 unless defined $sss_size;
500
501     $self->ctx->{staff_saved_search_size} = $sss_size;
502 }
503
504 sub staff_load_searches {
505     my ($self) = @_;
506
507     my $cache_key = $self->cgi->cookie((ref $self)->COOKIE_ANON_CACHE);
508
509     my $list = [];
510     if ($cache_key) {
511         $list = $U->simplereq(
512             "open-ils.actor",
513             "open-ils.actor.anon_cache.get_value",
514             $cache_key, (ref $self)->ANON_CACHE_STAFF_SEARCH
515         );
516
517         unless ($list) {
518             undef $cache_key;
519             $list = [];
520         }
521     }
522
523     return ($cache_key, $list);
524 }
525
526 sub staff_save_search {
527     my ($self, $query) = @_;
528
529     my $sss_size = $self->ctx->{staff_saved_search_size}; 
530     return unless $sss_size > 0;
531
532     my ($cache_key, $list) = $self->staff_load_searches;
533     my %already = ( map { $_ => 1 } @$list );
534
535     unshift @$list, $query unless $already{$query};
536
537     splice @$list, $sss_size;
538
539     $cache_key = $U->simplereq(
540         "open-ils.actor",
541         "open-ils.actor.anon_cache.set_value",
542         $cache_key, (ref $self)->ANON_CACHE_STAFF_SEARCH, $list
543     );
544
545     return ($cache_key, $list);
546 }
547
548 1;