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