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