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