]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/WWW/EGCatLoader/Search.pm
TPac: Avoid long-running, unintended empty searches
[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     if ($cgi->param("bookbag")) {
74         $query .= " container(bre,bookbag," . int($cgi->param("bookbag")) . ")";
75     }
76
77     if ($cgi->param('pubdate') && $cgi->param('date1')) {
78         if ($cgi->param('pubdate') eq 'between') {
79             $query .= ' between(' . $cgi->param('date1');
80             $query .= ',' .  $cgi->param('date2') if $cgi->param('date2');
81             $query .= ')';
82         } elsif ($cgi->param('pubdate') eq 'is') {
83             $query .= ' between(' . $cgi->param('date1') .
84                 ',' .  $cgi->param('date1') . ')';  # sic, date1 twice
85         } else {
86             $query .= ' ' . $cgi->param('pubdate') .
87                 '(' . $cgi->param('date1') . ')';
88         }
89     }
90
91     # ---------------------------------------------------------------------
92     # Nothing below here constitutes a query by itself.  If the query value 
93     # is still empty up to this point, there is no query.  abandon ship.
94     return () unless $query;
95
96     # sort is treated specially, even though it's actually a filter
97     if ($cgi->param('sort')) {
98         $query =~ s/sort\([^\)]*\)//g;  # override existing sort(). no stacking.
99         my ($axis, $desc) = split /\./, $cgi->param('sort');
100         $query .= " sort($axis)";
101         if ($desc and not $query =~ /\#descending/) {
102             $query .= '#descending';
103         } elsif (not $desc) {
104             $query =~ s/\#descending//;
105         }
106     }
107
108     my $site;
109     my $org = $ctx->{search_ou};
110     if (defined($org) and $org ne '' and ($org ne $ctx->{aou_tree}->()->id) and not $query =~ /site\(\S+\)/) {
111         $site = $ctx->{get_aou}->($org)->shortname;
112         $query .= " site($site)";
113     }
114
115     if(!$site) {
116         ($site) = ($query =~ /site\(([^\)]+)\)/);
117         $site ||= $ctx->{aou_tree}->()->shortname;
118     }
119
120     my $depth;
121     if ($query =~ /depth\(\d+\)/) {
122
123         # depth is encoded in the search query
124         ($depth) = ($query =~ /depth\((\d+)\)/);
125
126     } else {
127
128         if (defined $cgi->param('depth')) {
129             $depth = $cgi->param('depth');
130         } else {
131             # no depth specified.  match the depth to the search org
132             my ($org) = grep { $_->shortname eq $site } @{$ctx->{aou_list}->()};
133             $depth = $org->ou_type->depth;
134         }
135         $query .= " depth($depth)";
136     }
137
138     $logger->info("tpac: site=$site, depth=$depth, query=$query");
139
140     return ($query, $site, $depth);
141 }
142
143 sub _get_search_limit {
144     my $self = shift;
145
146     # param takes precedence
147     my $limit = $self->cgi->param('limit');
148     return $limit if $limit;
149
150     if($self->editor->requestor) {
151         # See if the user has a hit count preference
152         my $lset = $self->editor->search_actor_user_setting({
153             usr => $self->editor->requestor->id, 
154             name => 'opac.hits_per_page'
155         })->[0];
156         return OpenSRF::Utils::JSON->JSON2perl($lset->value) if $lset;
157     }
158
159     return 10; # default
160 }
161
162 sub tag_circed_items {
163     my $self = shift;
164     my $e = $self->editor;
165
166     return 0 unless $e->requestor;
167     return 0 unless $self->ctx->{get_org_setting}->(
168         $e->requestor->home_ou, 
169         'opac.search.tag_circulated_items');
170
171     # user has to be opted-in to circ history in some capacity
172     my $sets = $e->search_actor_user_setting({
173         usr => $e->requestor->id, 
174         name => [
175             'history.circ.retention_age', 
176             'history.circ.retention_start'
177         ]
178     });
179
180     return 0 unless @$sets;
181     return 1;
182
183 }
184
185 # This only loads the bookbag itself (in support of a record results page)
186 # if a "bookbag" CGI parameter is specified and if the bookbag is public
187 # or owned by the logged-in user (if any).  Bookbag notes are fetched
188 # later if applicable.
189 sub load_rresults_bookbag {
190     my ($self) = @_;
191
192     my $bookbag_id = int($self->cgi->param("bookbag") || 0);
193     return if $bookbag_id < 1;
194
195     my %authz = $self->ctx->{"user"} ?
196         ("-or" => {"pub" => "t", "owner" => $self->ctx->{"user"}->id}) :
197         ("pub" => "t");
198
199     my $bbag = $self->editor->search_container_biblio_record_entry_bucket(
200         {"id" => $bookbag_id, "btype" => "bookbag", %authz}
201     );
202
203     if (!$bbag) {
204         $self->apache->log->warn(
205             "error from cstore retrieving bookbag $bookbag_id!"
206         );
207         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
208     } elsif (@$bbag) {
209         $self->ctx->{"bookbag"} = shift @$bbag;
210     }
211
212     return;
213 }
214
215 # assumes context has a bookbag we're already authorized to look at, and
216 # a list of rec_ids, reasonably sized (from paged search).
217 sub load_rresults_bookbag_item_notes {
218     my ($self, $rec_ids) = @_;
219
220     my $items_with_notes =
221         $self->editor->search_container_biblio_record_entry_bucket_item([
222             {"target_biblio_record_entry" => $rec_ids,
223                 "bucket" => $self->ctx->{"bookbag"}->id},
224             {"flesh" => 1, "flesh_fields" => {"cbrebi" => ["notes"]},
225                 "order_by" => {"cbrebi" => ["id"]}}
226         ]);
227
228     if (!$items_with_notes) {
229         $self->apache->log->warn("error from cstore retrieving cbrebi objects");
230         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
231     }
232
233     $self->ctx->{"bookbag_items_by_bre_id"} = +{
234         map { $_->target_biblio_record_entry => $_ } @$items_with_notes
235     };
236
237     return;
238 }
239
240 # context additions: 
241 #   page_size
242 #   hit_count
243 #   records : list of bre's and copy-count objects
244 sub load_rresults {
245     my $self = shift;
246     my %args = @_;
247     my $internal = $args{internal};
248     my $cgi = $self->cgi;
249     my $ctx = $self->ctx;
250     my $e = $self->editor;
251
252     # load bookbag metadata, if requested.
253     if (my $bbag_err = $self->load_rresults_bookbag) {
254         return $bbag_err;
255     }
256
257     $ctx->{page} = 'rresult' unless $internal;
258     $ctx->{ids} = [];
259     $ctx->{records} = [];
260     $ctx->{search_facets} = {};
261     $ctx->{hit_count} = 0;
262
263     # Special alternative searches here.  This could all stand to be cleaner.
264     if ($cgi->param("_special")) {
265         return $self->marc_expert_search(%args) if scalar($cgi->param("tag"));
266         return $self->item_barcode_shortcut if (
267             $cgi->param("qtype") and ($cgi->param("qtype") eq "item_barcode")
268         );
269         return $self->call_number_browse_standalone if (
270             $cgi->param("qtype") and ($cgi->param("qtype") eq "cnbrowse")
271         );
272     }
273
274     my $page = $cgi->param('page') || 0;
275     my @facets = $cgi->param('facet');
276     my $limit = $self->_get_search_limit;
277     $ctx->{search_ou} = $self->_get_search_lib();
278     my $offset = $page * $limit;
279     my $metarecord = $cgi->param('metarecord');
280     my $results; 
281     my $tag_circs = $self->tag_circed_items;
282
283     $ctx->{page_size} = $limit;
284     $ctx->{search_page} = $page;
285
286     # fetch the first hit from the next page
287     if ($internal) {
288         $limit = $all_recs_limit;
289         $offset = 0;
290     }
291
292     my ($query, $site, $depth) = _prepare_biblio_search($cgi, $ctx);
293
294     $self->get_staff_search_settings;
295
296     if ($ctx->{staff_saved_search_size}) {
297         my ($key, $list) = $self->staff_save_search($query);
298         if ($key) {
299             $self->apache->headers_out->add(
300                 "Set-Cookie" => $self->cgi->cookie(
301                     -name => (ref $self)->COOKIE_ANON_CACHE,
302                     -path => "/",
303                     -value => ($key || ''),
304                     -expires => ($key ? undef : "-1h")
305                 )
306             );
307             $ctx->{saved_searches} = $list;
308         }
309     }
310
311     if ($metarecord and !$internal) {
312
313         # TODO: other limits, like SVF/format, etc.
314         $results = $U->simplereq(
315             'open-ils.search', 
316             'open-ils.search.biblio.metarecord_to_records',
317             $metarecord, {org => $ctx->{search_ou}, depth => $depth}
318         );
319
320         # force the metarecord result blob to match the format of regular search results
321         $results->{ids} = [map { [$_] } @{$results->{ids}}]; 
322
323     } else {
324
325         if (!$query) {
326             return Apache2::Const::OK if $internal;
327             return $self->generic_redirect;
328         }
329
330         # Limit and offset will stay here. Everything else should be part of
331         # the query string, not special args.
332         my $args = {'limit' => $limit, 'offset' => $offset};
333
334         if ($tag_circs) {
335             $args->{tag_circulated_records} = 1;
336             $args->{authtoken} = $self->editor->authtoken;
337         }
338
339         # Stuff these into the TT context so that templates can use them in redrawing forms
340         $ctx->{processed_search_query} = $query;
341
342         $query .= " $_" for @facets;
343
344         $logger->activity("EGWeb: [search] $query");
345
346         try {
347
348             my $method = 'open-ils.search.biblio.multiclass.query';
349             $method .= '.staff' if $ctx->{is_staff};
350             $results = $U->simplereq('open-ils.search', $method, $args, $query, 1);
351
352         } catch Error with {
353             my $err = shift;
354             $logger->error("multiclass search error: $err");
355             $results = {count => 0, ids => []};
356         };
357     }
358
359     my $rec_ids = [map { $_->[0] } @{$results->{ids}}];
360
361     $ctx->{ids} = $rec_ids;
362     $ctx->{hit_count} = $results->{count};
363     $ctx->{parsed_query} = $results->{parsed_query};
364
365     return Apache2::Const::OK if @$rec_ids == 0 or $internal;
366
367     $self->load_rresults_bookbag_item_notes($rec_ids) if $ctx->{bookbag};
368
369     my ($facets, @data) = $self->get_records_and_facets(
370         $rec_ids, $results->{facet_key}, 
371         {
372             flesh => '{holdings_xml,mra,acp,acnp,acns,bmp}',
373             site => $site,
374             depth => $depth
375         }
376     );
377
378     if ($page == 0) {
379         my $stat = $self->check_1hit_redirect($rec_ids);
380         return $stat if $stat;
381     }
382
383     # shove recs into context in search results order
384     for my $rec_id (@$rec_ids) {
385         push(
386             @{$ctx->{records}},
387             grep { $_->{id} == $rec_id } @data
388         );
389     }
390
391     if ($tag_circs) {
392         for my $rec (@{$ctx->{records}}) {
393             my ($res_rec) = grep { $_->[0] == $rec->{id} } @{$results->{ids}};
394             # index 1 in the per-record result array is a boolean which
395             # indicates whether the record in question is in the users
396             # accessible circ history list
397             $rec->{user_circulated} = 1 if $res_rec->[1];
398         }
399     }
400
401     $ctx->{search_facets} = $facets;
402
403     return Apache2::Const::OK;
404 }
405
406 # If the calling search results in 1 record and the client
407 # is configured to do so, redirect the search results to 
408 # the record details page.
409 sub check_1hit_redirect {
410     my ($self, $rec_ids) = @_;
411     my $ctx = $self->ctx;
412
413     return undef unless $rec_ids and @$rec_ids == 1;
414
415     my ($sname, $org);
416
417     if ($ctx->{is_staff}) {
418         $sname = 'opac.staff.jump_to_details_on_single_hit';
419         $org = $ctx->{user}->ws_ou;
420
421     } else {
422         $sname = 'opac.patron.jump_to_details_on_single_hit';
423         $org = $self->_get_search_lib();
424     }
425
426     return undef unless 
427         $self->ctx->{get_org_setting}->($org, $sname);
428
429     my $base_url = sprintf(
430         '%s://%s%s/record/%s',
431         $ctx->{proto}, 
432         $self->apache->hostname,
433         $self->ctx->{opac_root},
434         $$rec_ids[0],
435     );
436     
437     # If we get here from the same record detail page to which we
438     # now wish to redirect, do not perform the redirect.  This
439     # approach seems to work well, with the rare exception of 
440     # performing a new serach directly from the detail page that 
441     # happens to result in the same single hit.  In this case, the 
442     # user will be left on the search results page.  This could be 
443     # overcome w/ additional CGI, etc., but I'm not sure it's necessary.
444     if (my $referer = $ctx->{referer}) {
445         $referer =~ s/([^?]*).*/$1/g;
446         return undef if $base_url eq $referer;
447     }
448
449     return $self->generic_redirect($base_url . '?' . $self->cgi->query_string);
450 }
451
452 # Searching by barcode is a special search that does /not/ respect any other
453 # of the usual search parameters, not even the ones for sorting and paging!
454 sub item_barcode_shortcut {
455     my ($self) = @_;
456
457     my $method = "open-ils.search.multi_home.bib_ids.by_barcode";
458     if (my $search = create OpenSRF::AppSession("open-ils.search")) {
459         my $rec_ids = $search->request(
460             $method, $self->cgi->param("query")
461         )->gather(1);
462         $search->kill_me;
463
464         if (ref $rec_ids ne 'ARRAY') {
465
466             if($U->event_equals($rec_ids, 'ASSET_COPY_NOT_FOUND')) {
467                 $rec_ids = [];
468
469             } else {
470                 if (defined $U->event_code($rec_ids)) {
471                     $self->apache->log->warn(
472                         "$method returned event: " . $U->event_code($rec_ids)
473                     );
474                 } else {
475                     $self->apache->log->warn(
476                         "$method returned something unexpected: $rec_ids"
477                     );
478                 }
479                 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
480             }
481         }
482
483         my ($facets, @data) = $self->get_records_and_facets(
484             $rec_ids, undef, {flesh => "{holdings_xml,mra,acnp,acns,bmp}"}
485         );
486
487         $self->ctx->{records} = [@data];
488         $self->ctx->{search_facets} = {};
489         $self->ctx->{hit_count} = scalar @data;
490         $self->ctx->{page_size} = $self->ctx->{hit_count};
491
492         return Apache2::Const::OK;
493     } {
494         $self->apache->log->warn("couldn't connect to open-ils.search");
495         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
496     }
497 }
498
499 # like item_barcode_search, this can't take all the usual search params, but
500 # this one will at least do site, limit and page
501 sub marc_expert_search {
502     my ($self, %args) = @_;
503
504     my @tags = $self->cgi->param("tag");
505     my @subfields = $self->cgi->param("subfield");
506     my @terms = $self->cgi->param("term");
507
508     my $query = [];
509     for (my $i = 0; $i < scalar @tags; $i++) {
510         next if ($tags[$i] eq "" || $terms[$i] eq "");
511         $subfields[$i] = '_' unless $subfields[$i];
512         push @$query, {
513             "term" => $terms[$i],
514             "restrict" => [{"tag" => $tags[$i], "subfield" => $subfields[$i]}]
515         };
516     }
517
518     $logger->info("query for expert search: " . Dumper($query));
519
520     # loc, limit and offset
521     my $page = $self->cgi->param("page") || 0;
522     my $limit = $self->_get_search_limit;
523     $self->ctx->{search_ou} = $self->_get_search_lib();
524     my $offset = $page * $limit;
525
526     $self->ctx->{records} = [];
527     $self->ctx->{search_facets} = {};
528     $self->ctx->{page_size} = $limit;
529     $self->ctx->{hit_count} = 0;
530     $self->ctx->{ids} = [];
531     $self->ctx->{search_page} = $page;
532         
533     # nothing to do
534     return Apache2::Const::OK if @$query == 0;
535
536     if ($args{internal}) {
537         $limit = $all_recs_limit;
538         $offset = 0;
539     }
540
541     my $timeout = 120;
542     my $ses = OpenSRF::AppSession->create('open-ils.search');
543     my $req = $ses->request(
544         'open-ils.search.biblio.marc',
545         {searches => $query, org_unit => $self->ctx->{search_ou}}, 
546         $limit, $offset, $timeout);
547
548     my $resp = $req->recv($timeout);
549     my $results = $resp ? $resp->content : undef;
550     $ses->kill_me;
551
552     if (defined $U->event_code($results)) {
553         $self->apache->log->warn(
554             "open-ils.search.biblio.marc returned event: " .
555             $U->event_code($results)
556         );
557         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
558     }
559
560     $self->ctx->{ids} = [ grep { $_ } @{$results->{ids}} ];
561     $self->ctx->{hit_count} = $results->{count};
562
563     return Apache2::Const::OK if @{$self->ctx->{ids}} == 0 or $args{internal};
564
565     if ($page == 0) {
566         my $stat = $self->check_1hit_redirect($self->ctx->{ids});
567         return $stat if $stat;
568     }
569
570     my ($facets, @data) = $self->get_records_and_facets(
571         $self->ctx->{ids}, undef, {flesh => "{holdings_xml,mra,acnp,acns}"}
572     );
573
574     $self->ctx->{records} = [@data];
575
576     return Apache2::Const::OK;
577 }
578
579 sub call_number_browse_standalone {
580     my ($self) = @_;
581
582     if (my $cnfrag = $self->cgi->param("query")) {
583         my $url = sprintf(
584             'http%s://%s%s/cnbrowse?cn=%s',
585             $self->cgi->https ? "s" : "",
586             $self->apache->hostname,
587             $self->ctx->{opac_root},
588             $cnfrag # XXX some kind of escaping needed here?
589         );
590         return $self->generic_redirect($url);
591     } else {
592         return $self->generic_redirect; # return to search page
593     }
594 }
595
596 sub load_cnbrowse {
597     my ($self) = @_;
598
599     $self->prepare_browse_call_numbers();
600
601     return Apache2::Const::OK;
602 }
603
604 sub get_staff_search_settings {
605     my ($self) = @_;
606
607     unless ($self->ctx->{is_staff}) {
608         $self->ctx->{staff_saved_search_size} = 0;
609         return;
610     }
611
612     my $sss_size = $self->ctx->{get_org_setting}->(
613         $self->ctx->{physical_loc} || $self->ctx->{aou_tree}->()->id,
614         "opac.staff_saved_search.size",
615     );
616
617     # Sic: 0 is 0 (off), but undefined is 10.
618     $sss_size = 10 unless defined $sss_size;
619
620     $self->ctx->{staff_saved_search_size} = $sss_size;
621 }
622
623 sub staff_load_searches {
624     my ($self) = @_;
625
626     my $cache_key = $self->cgi->cookie((ref $self)->COOKIE_ANON_CACHE);
627
628     my $list = [];
629     if ($cache_key) {
630         $list = $U->simplereq(
631             "open-ils.actor",
632             "open-ils.actor.anon_cache.get_value",
633             $cache_key, (ref $self)->ANON_CACHE_STAFF_SEARCH
634         );
635
636         unless ($list) {
637             undef $cache_key;
638             $list = [];
639         }
640     }
641
642     return ($cache_key, $list);
643 }
644
645 sub staff_save_search {
646     my ($self, $query) = @_;
647
648     my $sss_size = $self->ctx->{staff_saved_search_size}; 
649     return unless $sss_size > 0;
650
651     my ($cache_key, $list) = $self->staff_load_searches;
652     my %already = ( map { $_ => 1 } @$list );
653
654     unshift @$list, $query unless $already{$query};
655
656     splice @$list, $sss_size;
657
658     $cache_key = $U->simplereq(
659         "open-ils.actor",
660         "open-ils.actor.anon_cache.set_value",
661         $cache_key, (ref $self)->ANON_CACHE_STAFF_SEARCH, $list
662     );
663
664     return ($cache_key, $list);
665 }
666
667 1;