]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/WWW/EGCatLoader/Search.pm
LP2045292 Color contrast for AngularJS patron bills
[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 OpenSRF::Utils::Cache;
6 use OpenILS::Utils::CStoreEditor qw/:funcs/;
7 use OpenILS::Utils::Fieldmapper;
8 use OpenILS::Application::AppUtils;
9 use OpenSRF::Utils::JSON;
10 use Data::Dumper;
11 $Data::Dumper::Indent = 0;
12 my $U = 'OpenILS::Application::AppUtils';
13
14 my @_qtype_list;
15
16 sub _prepare_biblio_search_basics {
17     my ($cgi) = @_;
18
19     return scalar($cgi->param('query')) unless scalar($cgi->param('qtype'));
20
21     # fetch, once per mod_perl backend, the list of valid classes and aliases
22     unless (@_qtype_list) {
23         my $editor = new_editor();
24         my $classes = $editor->retrieve_all_config_metabib_class();
25         my $aliases = $editor->retrieve_all_config_metabib_search_alias();
26
27         push @_qtype_list, map { $_->name } @$classes;
28         push @_qtype_list, map { $_->alias } @$aliases;
29     }
30
31     my %parts;
32     my @part_names = qw/qtype contains query bool/;
33     $parts{$_} = [ $cgi->param($_) ] for (@part_names);
34
35     my $full_query = '';
36     my @bookplate_queries = ();
37     for (my $i = 0; $i < scalar @{$parts{'qtype'}}; $i++) {
38         my ($qtype, $contains, $query, $bool) = map { $parts{$_}->[$i] } @part_names;
39
40         next unless $query =~ /\S/;
41
42         # Hack for bookplates; "bookplate" is not a real search
43         # class, so grabbing them out of the advanced search query
44         # params to convert to a copy_tag(*,...) filter later
45         if ($qtype eq 'bookplate') {
46             $query =~ s/[)(]/ /g; # don't break on 'foo(bar)baz'
47             push @bookplate_queries, $query;
48             next;
49         }
50  
51         # Hack for journal title
52         my $jtitle = 0;
53         if ($qtype eq 'jtitle') {
54             $qtype = 'title';
55             $jtitle = 1;
56         }
57
58         # This restricts qtype to classes, aliases, and field lists (approximately)
59         next unless grep { $qtype =~ /^$_(?:\|\w+)*$/ } @_qtype_list;
60
61         # This stuff probably will need refined or rethought to better handle
62         # the weird things Real Users will surely type in.
63         $contains = "" unless defined $contains; # silence warning
64         if ($contains eq 'nocontains') {
65             $query =~ s/"//g;
66             $query = ('"' . $query . '"') if index $query, ' ';
67             $query = '-' . $query;
68         } elsif ($contains eq 'phrase') {
69             $query =~ s/"//g;
70             $query = ('"' . $query . '"') if index $query, ' ';
71         } elsif ($contains eq 'exact') {
72             $query =~ s/[\^\$]//g;
73             $query = '^' . $query . '$';
74         } elsif ($contains eq 'starts') {
75             $query =~ s/"//g;
76             $query =~ s/[\^\$]//g;
77             $query = '^' . $query;
78             $query = ('"' . $query . '"') if index $query, ' ';
79         }
80
81         # Journal title hackery complete
82         if ($jtitle) {
83             $query = "bib_level(s) $query";
84         }
85
86         $query = "$qtype:$query" unless ($query =~ /^$qtype:/ or ($qtype eq 'keyword' and $i == 0));
87
88         $bool = ($bool and $bool eq 'or') ? '||' : '&&';
89         $full_query = $full_query ? "($full_query $bool $query)" : $query;
90     }
91
92     return $full_query, \@bookplate_queries;
93 }
94
95 sub _prepare_biblio_search {
96     my ($cgi, $ctx) = @_;
97
98     # XXX This will still contain the jtitle hack...
99     my ($user_query, $bookplate_queries) = _prepare_biblio_search_basics($cgi);
100     $user_query //= '';
101     $bookplate_queries //= [];
102     my $query = $user_query;
103     if (@$bookplate_queries) {
104         $query .= " " . join(" ", map { "copy_tag(*,$_)" } @$bookplate_queries);
105         # hack to handle the case where a bookplate comes from the
106         # simple search box
107         $user_query = $bookplate_queries->[0] if $user_query eq '';
108     }
109
110     $query .= ' ' . $ctx->{global_search_filter} if $ctx->{global_search_filter};
111
112     foreach ($cgi->multi_param('modifier')) {
113         # The unless bit is to avoid stacking modifiers.
114         $query = ('#' . $_ . ' ' . $query) unless 
115             $query =~ qr/\#\Q$_/ or $_ eq 'metabib';
116     }
117
118     # filters
119     foreach (grep /^fi:/, $cgi->multi_param) {
120         /:(-?\w+)$/ or next;
121         my $term = join(",", $cgi->multi_param($_));
122         $query .= " $1($term)" if length $term;
123     }
124
125     # filter group entries.  Entries from like filters are grouped into a single 
126     # filter_group_entry() filter (ORed).  Each collection is ANDed together.
127     # fg:foo_group=foo_entry_id
128     foreach (grep /^fg:/, $cgi->multi_param) {
129         /:(-?\w+)$/ or next;
130         my $term = join(",", $cgi->multi_param($_));
131         $query = "filter_group_entry($term) $query" if length $term;
132     }
133
134     if ($cgi->param("bookbag")) {
135         $query = "container(bre,bookbag," . int($cgi->param("bookbag")) . ") $query";
136     }
137
138     if ($cgi->param('pubdate') && $cgi->param('date1')) {
139         if ($cgi->param('pubdate') eq 'between') {
140             my $btw = 'between(' . $cgi->param('date1');
141             $btw .= ',' .  $cgi->param('date2') if $cgi->param('date2');
142             $btw .= ')';
143             $query = "$btw $query";
144         } elsif ($cgi->param('pubdate') eq 'is') {
145             $query = 'date1(' . $cgi->param('date1') . ") $query";
146         } else {
147             $query = $cgi->param('pubdate') .
148                 '(' . $cgi->param('date1') . ") $query";
149         }
150     }
151
152     # ---------------------------------------------------------------------
153     # Nothing below here constitutes a query by itself.  If the query value 
154     # is still empty up to this point, there is no query.  abandon ship.
155     return () unless $query;
156
157     # The search_scope param comes from a mixed-use dropdown containing depth,
158     # lasso, and location_groups filters.
159     $query .= ' ' . $cgi->param('search_scope') if defined $cgi->param('search_scope');
160
161     # The search_lasso context param comes from the locg dropdown, like the copy location.
162     $query .= ' lasso(' . $ctx->{search_lasso} .')' if $ctx->{search_lasso};
163
164     # sort is treated specially, even though it's actually a filter
165     if (defined($cgi->param('sort'))) {
166         $query =~ s/sort\([^\)]*\)//g;  # override existing sort(). no stacking.
167         my ($axis, $desc) = split /\./, $cgi->param('sort');
168         $query = "sort($axis) $query" if $axis;
169         if ($desc and not $query =~ /\#descending/) {
170             $query = "#descending $query";
171         } elsif (not $desc) {
172             $query =~ s/\#descending//;
173         }
174         # tidy up
175         $query =~ s/^\s+//;
176         $query =~ s/\s+$//;
177     }
178
179     my (@naive_query_re, $site);
180
181     my $org = $ctx->{search_ou};
182     if (defined($org) and $org ne '' and ($org ne $ctx->{aou_tree}->()->id) and not $query =~ /site\(\S+\)/) {
183         my $thing = " site(" . $ctx->{get_aou}->($org)->shortname . ")";
184
185         $query .= $thing;
186         push @naive_query_re, $thing;
187     }
188
189     my $pref_ou = $ctx->{pref_ou};
190     if (defined($pref_ou) and $pref_ou ne '' and $pref_ou != $org and ($pref_ou ne $ctx->{aou_tree}->()->id) and not $query =~ / pref_ou\(\S+\)/) {
191         my $plib = $ctx->{get_aou}->($pref_ou)->shortname;
192         $query = "pref_ou($plib) $query";
193     }
194
195     if (my $grp = $ctx->{copy_location_group}) {
196         $query = "location_groups($grp) $query";
197     }
198
199     if(!$site) {
200         ($site) = ($query =~ /site\(([^\)]+)\)/);
201         $site ||= $ctx->{aou_tree}->()->shortname;
202     }
203
204     # Course on_reserves filter, handles specially since the UI includes
205     # an option to negate the filter, and it relies on the org unit
206     # calculations
207     if ($cgi->param('course_filter')) {
208         my $course_lib = $org || 'all';
209         if ($cgi->param('course_filter') eq 'true') {
210             $query = "on_reserve($course_lib) $query";
211         } elsif ($cgi->param('course_filter') eq 'negated') {
212             $query = "-on_reserve($course_lib) $query";
213         }
214     }
215
216     my $depth;
217     if ($query =~ /depth\(\d+\)/) {
218
219         # depth is encoded in the search query
220         ($depth) = ($query =~ /depth\((\d+)\)/);
221
222     } else {
223
224         if (defined $cgi->param('depth')) {
225             $depth = $cgi->param('depth');
226         } else {
227             # no depth specified.  match the depth to the search org
228             my ($org) = grep { $_->shortname eq $site } @{$ctx->{aou_list}->()};
229             $depth = $org->ou_type->depth;
230         }
231         my $thing = " depth($depth)";
232
233         $query .= $thing;
234         push @naive_query_re, $thing;
235     }
236
237     # This gives templates a way to take site() and depth() back out of
238     # query strings when they shouldn't be there (because they're controllable
239     # with other widgets).
240     $ctx->{naive_query_scrub} = sub {
241         my ($query) = @_;
242         $query =~ s/\Q$_\E// foreach (@naive_query_re);
243         return $query;
244     };
245
246     $logger->info("tpac: site=$site, depth=$depth, user_query=$user_query, query=$query");
247
248     return ($user_query, $query, $site, $depth);
249 }
250
251 sub _get_search_limit {
252     my $self = shift;
253
254     # param takes precedence
255     my $limit = $self->cgi->param('limit');
256     return $limit if $limit;
257
258     if($self->editor->requestor) {
259         $self->timelog("Checking for opac.hits_per_page preference");
260         # See if the user has a hit count preference
261         my $lset = $self->editor->search_actor_user_setting({
262             usr => $self->editor->requestor->id, 
263             name => 'opac.hits_per_page'
264         })->[0];
265         $self->timelog("Got opac.hits_per_page preference");
266         return OpenSRF::Utils::JSON->JSON2perl($lset->value) if $lset;
267     }
268
269     return 10; # default
270 }
271
272 sub tag_circed_items {
273     my $self = shift;
274     my $e = $self->editor;
275
276     $self->timelog("Tag circed items?");
277     return 0 unless $e->requestor;
278     $self->timelog("Checking for opac.search.tag_circulated_items");
279     return 0 unless $self->ctx->{get_org_setting}->(
280         $e->requestor->home_ou, 
281         'opac.search.tag_circulated_items');
282
283     # user has to be opted-in to circ history in some capacity
284     $self->timelog("Checking for history.circ.retention_*");
285     my $sets = $e->search_actor_user_setting({
286         usr => $e->requestor->id, 
287         name => [
288             'history.circ.retention_age', 
289             'history.circ.retention_start'
290         ]
291     });
292
293     $self->timelog("Return from checking for history.circ.retention_*");
294
295     return 0 unless @$sets;
296     return 1;
297
298 }
299
300 # This only loads the bookbag itself (in support of a record results page)
301 # if a "bookbag" CGI parameter is specified and if the bookbag is public
302 # or owned by the logged-in user (if any).  Bookbag notes are fetched
303 # later if applicable.
304 sub load_rresults_bookbag {
305     my ($self) = @_;
306
307     my $bookbag_id = int($self->cgi->param("bookbag") || 0);
308     return if $bookbag_id < 1;
309
310     my %authz = $self->ctx->{"user"} ?
311         ("-or" => {"pub" => "t", "owner" => $self->ctx->{"user"}->id}) :
312         ("pub" => "t");
313
314     $self->timelog("Load results bookbag");
315     my $bbag = $self->editor->search_container_biblio_record_entry_bucket(
316         {"id" => $bookbag_id, "btype" => "bookbag", %authz}
317     );
318     $self->timelog("Got results bookbag");
319
320     if (!$bbag) {
321         $self->apache->log->warn(
322             "error from cstore retrieving bookbag $bookbag_id!"
323         );
324         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
325     } elsif (@$bbag) {
326         $self->ctx->{"bookbag"} = shift @$bbag;
327     }
328
329     return;
330 }
331
332 # assumes context has a bookbag we're already authorized to look at, and
333 # a list of rec_ids, reasonably sized (from paged search).
334 sub load_rresults_bookbag_item_notes {
335     my ($self, $rec_ids) = @_;
336
337     $self->timelog("Load results bookbag item notes");
338     my $items_with_notes =
339         $self->editor->search_container_biblio_record_entry_bucket_item([
340             {"target_biblio_record_entry" => $rec_ids,
341                 "bucket" => $self->ctx->{"bookbag"}->id},
342             {"flesh" => 1, "flesh_fields" => {"cbrebi" => ["notes"]},
343                 "order_by" => {"cbrebi" => ["id"]}}
344         ]);
345     $self->timelog("Got results bookbag item notes");
346
347     if (!$items_with_notes) {
348         $self->apache->log->warn("error from cstore retrieving cbrebi objects");
349         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
350     }
351
352     $self->ctx->{"bookbag_items_by_bre_id"} = +{
353         map { $_->target_biblio_record_entry => $_ } @$items_with_notes
354     };
355
356     return;
357 }
358
359 # $filter -- CCVM filter expression (see also composite attr def)
360 sub recs_from_metarecord {
361     my ($self, $mr_id, $org, $depth, $filter) = @_;
362     $self->timelog("Getting metarecords to records");
363
364     # in the context of searching, we include all records which
365     # have an opac-visible copy.
366     my $bre_ids = $U->simplereq(
367         'open-ils.circ',
368         'open-ils.circ.holds.metarecord.filtered_records',
369         $mr_id, $filter, $org, $depth, 1);
370
371     $self->timelog("Got metarecords to records");
372     return $bre_ids;
373 }
374
375
376
377 # context additions: 
378 #   page_size
379 #   hit_count
380 #   records : list of bre's and copy-count objects
381 my $max_concurrent_search;
382 sub load_rresults {
383     my $self = shift;
384     my %args = @_;
385     my $internal = $args{internal};
386     my $cgi = $self->cgi;
387     my $ctx = $self->ctx;
388     my $e = $self->editor;
389
390     my $mc = OpenSRF::Utils::Cache->new('global');
391     my $client_ip = $self->apache->headers_in->get('X-Forwarded-For') ||
392         $self->apache->useragent_ip;
393     ($client_ip) = split(/,\s*/, $client_ip);
394     $logger->activity("Client IP: $client_ip");
395
396
397     # 1. param->metarecord : view constituent bib records for a metarecord
398     # 2. param->modifier=metabib : perform a metarecord search
399     my $metarecord = $ctx->{metarecord} = $cgi->param('metarecord');
400     my @mods = $cgi->multi_param('modifier');
401     my $is_meta = (@mods and grep {$_ eq 'metabib'} @mods and !$metarecord);
402     my $id_key = $is_meta ? 'mmr_id' : 'bre_id';
403
404     # find the last record in the set, then redirect
405     my $find_last = $cgi->param('find_last');
406
407     $self->timelog("Loading results");
408     # load bookbag metadata, if requested.
409     if (my $bbag_err = $self->load_rresults_bookbag) {
410         return $bbag_err;
411     }
412
413     $ctx->{page} = 'rresult' unless $internal;
414     $ctx->{ids} = [];
415     $ctx->{records} = [];
416     $ctx->{search_facets} = {};
417     $ctx->{hit_count} = 0;
418     $ctx->{is_meta} = $is_meta;
419
420     # Special alternative searches here.  This could all stand to be cleaner.
421     if ($cgi->param("_special")) {
422         $self->timelog("Calling MARC expert search");
423         return $self->marc_expert_search(%args) if (scalar($cgi->param("tag")) and
424             (!defined $cgi->param("query") or $cgi->param("query") =~ /^\s*$/));
425         $self->timelog("Calling item barcode search");
426         return $self->item_barcode_shortcut if (
427             $cgi->param("qtype") and ($cgi->param("qtype") eq "item_barcode") and not $internal
428         );
429         $self->timelog("Calling call number browse");
430         return $self->call_number_browse_standalone if (
431             $cgi->param("qtype") and ($cgi->param("qtype") eq "cnbrowse")
432         );
433     }
434
435     $self->timelog("Getting search parameters");
436     my $page = $cgi->param('page') || 0;
437     my @facets = $cgi->multi_param('facet');
438     my $limit = $self->_get_search_limit;
439     $ctx->{search_ou} = $self->_get_search_lib();
440     $ctx->{pref_ou} = $self->_get_pref_lib() || $ctx->{search_ou};
441     my $offset = $page * $limit;
442     my $results; 
443     my $tag_circs = $self->tag_circed_items;
444     $self->timelog("Got search parameters");
445
446     $ctx->{page_size} = $limit;
447     $ctx->{search_page} = $page;
448
449     # fetch this page plus the first hit from the next page
450     if ($internal) {
451         $limit = $offset + $limit + 1;
452         $offset = 0;
453     }
454
455     my ($user_query, $query, $site, $depth) = _prepare_biblio_search($cgi, $ctx);
456
457     $self->get_staff_search_settings;
458
459     if (!$find_last and $ctx->{staff_saved_search_size}) {
460         my ($key, $list) = $self->staff_save_search($query);
461         if ($key) {
462             $self->apache->headers_out->add(
463                 "Set-Cookie" => $self->cgi->cookie(
464                     -name => (ref $self)->COOKIE_ANON_CACHE,
465                     -path => "/",
466                     -value => ($key || ''),
467                     -expires => ($key ? undef : "-1h")
468                 )
469             );
470             $ctx->{saved_searches} = $list;
471         }
472     }
473     # Limit and offset will stay here. Everything else should be part of
474     # the query string, not special args.
475     my $args = {'limit' => $limit, 'offset' => $offset};
476
477     return Apache2::Const::OK unless $query;
478
479     if ($tag_circs) {
480         $args->{tag_circulated_records} = 1;
481         $args->{authtoken} = $self->editor->authtoken;
482     }
483     $args->{from_metarecord} = $metarecord if $metarecord;
484
485     # Stuff these into the TT context so that templates can use them in redrawing forms
486     $ctx->{user_query} = $user_query;
487     $ctx->{processed_search_query} = $query;
488
489     $query = "$_ $query" for @facets;
490
491     my $ltag = $is_meta ? '[mmr search]' : '[bre search]';
492     $logger->activity("EGWeb: $ltag $query");
493
494     # Fetch the global flag, defaults to "never too many".
495     unless (defined $max_concurrent_search) {
496         my $mcs = $e->retrieve_config_global_flag('opac.max_concurrent_search.ip');
497         $max_concurrent_search = ($mcs and $mcs->enabled eq 't') ? $mcs->value : 0;
498     }
499
500     if ($max_concurrent_search > 0) {
501         # Right up front, we will limit concurrent searches coming from the same client IP, if configured to do so.
502         $mc->get_cache('EGWEB-MAX-SEARCH-IP:'.$client_ip) || $mc->{memcache}->add('EGWEB-MAX-SEARCH-IP:'.$client_ip, 0);
503         my $concurrent_searches = $mc->{memcache}->incr('EGWEB-MAX-SEARCH-IP:'.$client_ip);
504         $logger->activity("Concurrent searches from client IP $client_ip: $concurrent_searches");
505
506         if ($concurrent_searches > $max_concurrent_search) {
507             $self->apache->log->warn("Too many concurrent searches from IP $client_ip");
508             $mc->{memcache}->decr('EGWEB-MAX-SEARCH-IP:'.$client_ip);
509             return 429; # Apache2::Const does not have a symbol for 429 too many requests
510         }
511     }
512
513     my $method = 'open-ils.search.biblio.multiclass.query';
514     try {
515         $method .= '.staff' if $ctx->{is_staff};
516         $method =~ s/biblio/metabib/ if $is_meta;
517
518         my $ses = OpenSRF::AppSession->create('open-ils.search');
519
520         $self->timelog("Firing off the multiclass query");
521         my $req = $ses->request($method, $args, $query, 1, $ctx->{physical_loc});
522         $results = $req->gather(1);
523         $self->timelog("Returned from the multiclass query");
524
525     } catch Error with {
526         my $err = shift;
527         $logger->error("multiclass search error: $err");
528         $results = {count => 0, ids => []};
529     };
530
531     $mc->{memcache}->decr('EGWEB-MAX-SEARCH-IP:'.$client_ip) if ($max_concurrent_search);
532
533     # INFO: an OpenILS::Event only means "go away" for now.
534     if (defined $U->event_code($results)) {
535         $logger->activity("$method returned event: " . $U->event_code($results));
536         $self->apache->log->warn( "$method returned event: " . $U->event_code($results));
537         return 429; # Apache2::Const does not have a symbol for 429 too many requests
538     }
539
540     my $rec_ids = [map { $_->[0] } @{$results->{ids}}];
541
542     $ctx->{ids} = $rec_ids;
543     $ctx->{hit_count} = $results->{count};
544     $ctx->{superpage} = $results->{superpage};
545     $ctx->{superpage_size} = $results->{superpage_size};
546     $ctx->{pagable_limit} = $results->{core_limit};
547     $ctx->{query_struct} = $results->{global_summary}{query_struct};
548     $logger->debug('query struct: '. Dumper($ctx->{query_struct}));
549     $ctx->{canonicalized_query} = $results->{global_summary}{canonicalized_query};
550     $ctx->{search_summary} = $results->{global_summary};
551
552     if ($find_last) {
553         # redirect to the record detail page for the last record in the results
554         my $rec_id = pop @$rec_ids;
555         $cgi->delete('find_last');
556         my $url = $cgi->url(-full => 1, -path => 1, -query => 1);
557         # TODO: metarecord => /rresults?metarecord=$mmr_id
558         $url =~ s|/results|/record/$rec_id|;
559         return $self->generic_redirect($url);
560     }
561
562     return Apache2::Const::OK if @$rec_ids == 0 or $internal;
563
564     $self->load_rresults_bookbag_item_notes($rec_ids) if $ctx->{bookbag};
565
566     my $fetch_recs = $rec_ids;
567
568     $self->timelog("Calling get_records_and_facets()");
569     my ($facets, @data) = $self->get_records_and_facets(
570         $fetch_recs, $results->{facet_key}, 
571         {
572             flesh => '{holdings_xml,mra,acp,acnp,acns,bmp,cbs}',
573             site => $site,
574             metarecord => $is_meta,
575             depth => $depth,
576             pref_lib => $ctx->{pref_ou},
577         }
578     );
579     $self->timelog("Returned from get_records_and_facets()");
580
581     if ($page == 0 and @$rec_ids == 1) {
582         my $stat = 0;
583         if ($is_meta) {
584             # if the MR has a single constituent record, it will
585             # be in array position 4 of the result blob.
586             # otherwise, we don't want to redirect anyway.
587             my $bre_id = $results->{ids}->[0]->[4];
588             $stat = $self->check_1hit_redirect([$bre_id]) if $bre_id;
589         } else {
590             my $stat = $self->check_1hit_redirect($rec_ids);
591         }
592         return $stat if $stat;
593     }
594
595     # load temporary_list settings for user and ou:
596     $self->_load_lists_and_settings if ($ctx->{user});
597
598     my %mr_contents;
599     # shove recs into context in search results order
600     for my $rec_id (@$rec_ids) {
601         my ($rec) = grep { $_->{$id_key} == $rec_id } @data;
602         push(@{$ctx->{records}}, $rec);
603
604         if ($is_meta) {
605             try {
606                 my $method = 'open-ils.search.biblio.multiclass.query';
607                 $method .= '.staff' if $ctx->{is_staff};
608                 my $ses = OpenSRF::AppSession->create('open-ils.search');
609                 $self->timelog("Firing off the multiclass query: ". $rec_id);
610                 $args->{from_metarecord} = $rec_id;
611                 # offset of main search does not apply to the MR
612                 # constituents query
613                 my $save_offset = $args->{offset};
614                 $args->{offset} = 0;
615                 $mr_contents{$rec_id} = $ses->request($method, $args, $query, 1, $ctx->{physical_loc});
616                 $args->{offset} = $save_offset;
617             } catch Error with {
618                 my $err = shift;
619                 $logger->error("multiclass search error: $err");
620             };
621         }
622     }
623
624     # above we fire all searches in parallel, now we collect the results
625     if ($is_meta) {
626         for my $rec_id (@$rec_ids) {
627             my ($rec) = grep { $_->{$id_key} == $rec_id } @data;
628             my $meta_results;
629             if ($mr_contents{$rec_id}) {
630                 $meta_results = $mr_contents{$rec_id}->gather(1);
631                 $self->timelog("Returned from the multiclass query: ". $rec_id);
632             } else {
633                 $meta_results = {count => 0, ids => []};
634             }
635             my $meta_rec_ids = [map { $_->[0] } @{$meta_results->{ids}}];
636             $rec->{mr_constituent_count} = $meta_results->{count};
637             $rec->{mr_constituent_ids} = $meta_rec_ids;
638         }
639     }
640
641     my $course_module_opt_in = 0;
642     if ($ctx->{get_org_setting}->($self->_get_search_lib, "circ.course_materials_opt_in")) {
643         $course_module_opt_in = 1;
644     }
645
646     for my $rec (@{$ctx->{records}}) {
647         my ($res_rec) = grep { $_->[0] == $rec->{$id_key} } @{$results->{ids}};
648         $rec->{badges} = [split(',', $res_rec->[1])] if $res_rec->[1];
649         $rec->{popularity} = $res_rec->[2];
650         if ($course_module_opt_in) {
651             $rec->{course_materials} = $U->simplereq(
652                 'open-ils.courses',
653                 'open-ils.courses.course_materials.retrieve.atomic',
654                 {record => $rec->{id}}
655             );
656             my %course_ids;
657             for my $material (@{$rec->{course_materials}}) {
658                 $course_ids{$material->course} = 1;
659             }
660
661             $rec->{courses} = $U->simplereq(
662                 'open-ils.courses',
663                 'open-ils.courses.courses.retrieve',
664                 keys %course_ids
665             );
666         }
667         if ($tag_circs) {
668             # index 3 (5 for MR) in the per-record result array is a boolean which
669             # indicates whether the record in question is in the users
670             # accessible circ history list
671             my $index = $is_meta ? 5 : 3;
672             $rec->{user_circulated} = 1 if $res_rec->[$index];
673         }
674     }
675     
676
677     $ctx->{search_facets} = $facets;
678
679     return Apache2::Const::OK;
680 }
681
682 # If the calling search results in 1 record and the client
683 # is configured to do so, redirect the search results to 
684 # the record details page.
685 sub check_1hit_redirect {
686     my ($self, $rec_ids) = @_;
687     my $ctx = $self->ctx;
688
689     return undef unless $rec_ids and @$rec_ids == 1;
690
691     my ($sname, $org);
692
693     $self->timelog("Checking whether to jump to details on a single hit");
694     if ($ctx->{is_staff}) {
695         $sname = 'opac.staff.jump_to_details_on_single_hit';
696         $org = $ctx->{user}->ws_ou;
697
698     } else {
699         $sname = 'opac.patron.jump_to_details_on_single_hit';
700         $org = $self->_get_search_lib();
701     }
702
703     $self->timelog("Return from checking whether to jump to details on a single hit");
704
705     return undef unless 
706         $self->ctx->{get_org_setting}->($org, $sname);
707
708     my $base_url = sprintf(
709         '%s://%s%s/record/%s',
710         $self->ctx->{proto},
711         $self->ctx->{hostname},
712         $self->ctx->{opac_root},
713         $$rec_ids[0],
714     );
715     
716     # If we get here from the same record detail page to which we
717     # now wish to redirect, do not perform the redirect.  This
718     # approach seems to work well, with the rare exception of 
719     # performing a new search directly from the detail page that 
720     # happens to result in the same single hit.  In this case, the 
721     # user will be left on the search results page.  This could be 
722     # overcome w/ additional CGI, etc., but I'm not sure it's necessary.
723     if (my $referer = $ctx->{referer}) {
724         $referer =~ s/([^?]*).*/$1/g;
725         return undef if $base_url eq $referer;
726     }
727
728     return $self->generic_redirect($base_url . '?' . $self->cgi->query_string);
729 }
730
731 # Searching by barcode is a special search that does /not/ respect any other
732 # of the usual search parameters, not even the ones for sorting and paging!
733 sub item_barcode_shortcut {
734     my ($self) = @_;
735
736     $self->timelog("Searching for item_barcode");
737     my $method = "open-ils.search.multi_home.bib_ids.by_barcode";
738     if (my $search = create OpenSRF::AppSession("open-ils.search")) {
739         my $rec_ids = $search->request(
740             $method, $self->cgi->param("query")
741         )->gather(1);
742         $search->kill_me;
743         $self->timelog("Finished searching for item_barcode");
744
745         if (ref $rec_ids ne 'ARRAY') {
746
747             if($U->event_equals($rec_ids, 'ASSET_COPY_NOT_FOUND')) {
748                 $rec_ids = [];
749
750             } else {
751                 if (defined $U->event_code($rec_ids)) {
752                     $self->apache->log->warn(
753                         "$method returned event: " . $U->event_code($rec_ids)
754                     );
755                 } else {
756                     $self->apache->log->warn(
757                         "$method returned something unexpected: $rec_ids"
758                     );
759                 }
760                 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
761             }
762         }
763
764         $self->timelog("Calling get_records_and_facets() for item_barcode");
765         my ($facets, @data) = $self->get_records_and_facets(
766             $rec_ids, undef, {flesh => "{holdings_xml,mra,acnp,acns,bmp,cbs}"}
767         );
768         $self->timelog("Returned from calling get_records_and_facets() for item_barcode");
769
770         my $stat = $self->check_1hit_redirect($rec_ids);
771         return $stat if $stat;
772
773         $self->ctx->{records} = [@data];
774         $self->ctx->{search_facets} = {};
775         $self->ctx->{hit_count} = scalar @data;
776         $self->ctx->{page_size} = $self->ctx->{hit_count};
777         # load temporary_list settings for user and ou:
778         $self->_load_lists_and_settings if ($self->ctx->{user});
779
780         return Apache2::Const::OK;
781     } {
782         $self->apache->log->warn("couldn't connect to open-ils.search");
783         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
784     }
785 }
786
787 # like item_barcode_search, this can't take all the usual search params, but
788 # this one will at least do site, limit and page
789 sub marc_expert_search {
790     my ($self, %args) = @_;
791
792     my @tags = $self->cgi->multi_param("tag");
793     my @subfields = $self->cgi->multi_param("subfield");
794     my @terms = $self->cgi->multi_param("term");
795
796     my $query = [];
797     for (my $i = 0; $i < scalar @tags; $i++) {
798         next if ($tags[$i] eq "" || $terms[$i] eq "");
799         $subfields[$i] = '_' unless $subfields[$i];
800         push @$query, {
801             "term" => $terms[$i],
802             "restrict" => [{"tag" => $tags[$i], "subfield" => $subfields[$i]}]
803         };
804     }
805
806     $logger->info("query for expert search: " . Dumper($query));
807
808     $self->timelog("Getting search parameters");
809     # loc, limit and offset
810     my $page = $self->cgi->param("page") || 0;
811     my $limit = $self->_get_search_limit;
812     $self->ctx->{search_ou} = $self->_get_search_lib();
813     $self->ctx->{pref_ou} = $self->_get_pref_lib();
814     my $offset = $page * $limit;
815     $self->timelog("Got search parameters");
816
817     $self->ctx->{records} = [];
818     $self->ctx->{search_facets} = {};
819     $self->ctx->{page_size} = $limit;
820     $self->ctx->{hit_count} = 0;
821     $self->ctx->{ids} = [];
822     $self->ctx->{search_page} = $page;
823         
824     # nothing to do
825     return Apache2::Const::OK if @$query == 0;
826
827     if ($args{internal}) {
828         $limit = $offset + $limit + 1;
829         $offset = 0;
830     }
831
832     $self->timelog("Searching for MARC expert");
833     my $method = 'open-ils.search.biblio.marc';
834     $method .= '.staff' if $self->ctx->{is_staff};
835     my $timeout = 120;
836     my $ses = OpenSRF::AppSession->create('open-ils.search');
837
838     #when a sort variable is passed in we need to add its value to the arguments
839     my $arghash = {searches => $query, org_unit => $self->ctx->{search_ou}};
840     if (defined $self->cgi->param("sort")) {
841         my ($sort, $sort_dir) = split /\./, $self->cgi->param('sort');
842         $arghash = {%$arghash, sort => "$sort"};
843         if (!defined $sort_dir) {
844             $arghash = {%$arghash, sort_dir => "ASC"};
845         }
846     }
847
848     #add the offset and limit to the argash, so we can go past 100 results
849     #if offset and limit are not in the args then they default to 0 and 100
850     #respectively in biblio_multi_search_full_rec, which limits the results to 100
851     #records
852     $arghash = {%$arghash, offset => $offset, limit => $limit}; 
853
854     my $req = $ses->request(
855         $method,
856         $arghash,
857         $timeout);
858
859     my $resp = $req->recv($timeout);
860     my $results = $resp ? $resp->content : undef;
861     $ses->kill_me;
862     $self->timelog("Got our MARC expert results");
863
864     if (defined $U->event_code($results)) {
865         $self->apache->log->warn(
866             "open-ils.search.biblio.marc returned event: " .
867             $U->event_code($results)
868         );
869         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
870     }
871
872     $self->ctx->{ids} = [ grep { $_ } @{$results->{ids}} ];
873     $self->ctx->{hit_count} = $results->{count};
874
875     return Apache2::Const::OK if @{$self->ctx->{ids}} == 0 or $args{internal};
876
877     if ($page == 0) {
878         my $stat = $self->check_1hit_redirect($self->ctx->{ids});
879         return $stat if $stat;
880     }
881
882     $self->timelog("Calling get_records_and_facets() for MARC expert");
883     my ($facets, @data) = $self->get_records_and_facets(
884         $self->ctx->{ids}, undef, {
885             flesh => "{holdings_xml,mra,acnp,acns,cbs}",
886             pref_lib => $self->ctx->{pref_ou},
887         }
888     );
889     $self->timelog("Returned from calling get_records_and_facets() for MARC expert");
890
891     # load temporary_list settings for user and ou:
892     $self->_load_lists_and_settings if ($self->ctx->{user});
893
894     $self->ctx->{records} = [@data];
895
896     return Apache2::Const::OK;
897 }
898
899 sub call_number_browse_standalone {
900     my ($self) = @_;
901
902     if (my $cnfrag = $self->cgi->param("query")) {
903         my $url = sprintf(
904             '%s://%s%s/cnbrowse?cn=%s',
905             $self->ctx->{proto},
906             $self->ctx->{hostname},
907             $self->ctx->{opac_root},
908             $cnfrag # XXX some kind of escaping needed here?
909         );
910         $url .= '&locg=' . $self->_get_search_lib() if ($self->_get_search_lib());
911         return $self->generic_redirect($url);
912     } else {
913         return $self->generic_redirect; # return to search page
914     }
915 }
916
917 sub load_cnbrowse {
918     my ($self) = @_;
919
920     $self->prepare_browse_call_numbers();
921
922     return Apache2::Const::OK;
923 }
924
925 sub get_staff_search_settings {
926     my ($self) = @_;
927
928     unless ($self->ctx->{is_staff}) {
929         $self->ctx->{staff_saved_search_size} = 0;
930         return;
931     }
932
933     $self->timelog("Getting staff search size");
934     my $sss_size = $self->ctx->{get_org_setting}->(
935         $self->ctx->{physical_loc} || $self->ctx->{aou_tree}->()->id,
936         "opac.staff_saved_search.size",
937     );
938     $self->timelog("Got staff search size");
939
940     # Sic: 0 is 0 (off), but undefined is 10.
941     $sss_size = 10 unless defined $sss_size;
942
943     $self->ctx->{staff_saved_search_size} = $sss_size;
944 }
945
946 sub staff_load_searches {
947     my ($self) = @_;
948
949     my $cache_key = $self->cgi->cookie((ref $self)->COOKIE_ANON_CACHE);
950
951     my $list = [];
952     if ($cache_key) {
953         $self->timelog("Getting anon_cache value");
954         $list = $U->simplereq(
955             "open-ils.actor",
956             "open-ils.actor.anon_cache.get_value",
957             $cache_key, (ref $self)->ANON_CACHE_STAFF_SEARCH
958         );
959         $self->timelog("Got anon_cache value");
960
961         unless ($list) {
962             undef $cache_key;
963             $list = [];
964         }
965     }
966
967     return ($cache_key, $list);
968 }
969
970 sub staff_save_search {
971     my ($self, $query) = @_;
972
973     my $sss_size = $self->ctx->{staff_saved_search_size}; 
974     return unless $sss_size > 0;
975
976     my ($cache_key, $list) = $self->staff_load_searches;
977     my %already = ( map { $_ => 1 } @$list );
978
979     unshift @$list, $query unless $already{$query};
980
981     splice @$list, $sss_size if scalar @$list > $sss_size;
982
983     $self->timelog("Setting anon_cache value");
984     $cache_key = $U->simplereq(
985         "open-ils.actor",
986         "open-ils.actor.anon_cache.set_value",
987         $cache_key, (ref $self)->ANON_CACHE_STAFF_SEARCH, $list
988     );
989     $self->timelog("Set anon_cache value");
990
991     return ($cache_key, $list);
992 }
993
994 1;