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