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