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