]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/WWW/EGCatLoader/Search.pm
LP#1361782: Add DoS protection
[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     my $depth;
205     if ($query =~ /depth\(\d+\)/) {
206
207         # depth is encoded in the search query
208         ($depth) = ($query =~ /depth\((\d+)\)/);
209
210     } else {
211
212         if (defined $cgi->param('depth')) {
213             $depth = $cgi->param('depth');
214         } else {
215             # no depth specified.  match the depth to the search org
216             my ($org) = grep { $_->shortname eq $site } @{$ctx->{aou_list}->()};
217             $depth = $org->ou_type->depth;
218         }
219         my $thing = " depth($depth)";
220
221         $query .= $thing;
222         push @naive_query_re, $thing;
223     }
224
225     # This gives templates a way to take site() and depth() back out of
226     # query strings when they shouldn't be there (because they're controllable
227     # with other widgets).
228     $ctx->{naive_query_scrub} = sub {
229         my ($query) = @_;
230         $query =~ s/\Q$_\E// foreach (@naive_query_re);
231         return $query;
232     };
233
234     $logger->info("tpac: site=$site, depth=$depth, user_query=$user_query, query=$query");
235
236     return ($user_query, $query, $site, $depth);
237 }
238
239 sub _get_search_limit {
240     my $self = shift;
241
242     # param takes precedence
243     my $limit = $self->cgi->param('limit');
244     return $limit if $limit;
245
246     if($self->editor->requestor) {
247         $self->timelog("Checking for opac.hits_per_page preference");
248         # See if the user has a hit count preference
249         my $lset = $self->editor->search_actor_user_setting({
250             usr => $self->editor->requestor->id, 
251             name => 'opac.hits_per_page'
252         })->[0];
253         $self->timelog("Got opac.hits_per_page preference");
254         return OpenSRF::Utils::JSON->JSON2perl($lset->value) if $lset;
255     }
256
257     return 10; # default
258 }
259
260 sub tag_circed_items {
261     my $self = shift;
262     my $e = $self->editor;
263
264     $self->timelog("Tag circed items?");
265     return 0 unless $e->requestor;
266     $self->timelog("Checking for opac.search.tag_circulated_items");
267     return 0 unless $self->ctx->{get_org_setting}->(
268         $e->requestor->home_ou, 
269         'opac.search.tag_circulated_items');
270
271     # user has to be opted-in to circ history in some capacity
272     $self->timelog("Checking for history.circ.retention_*");
273     my $sets = $e->search_actor_user_setting({
274         usr => $e->requestor->id, 
275         name => [
276             'history.circ.retention_age', 
277             'history.circ.retention_start'
278         ]
279     });
280
281     $self->timelog("Return from checking for history.circ.retention_*");
282
283     return 0 unless @$sets;
284     return 1;
285
286 }
287
288 # This only loads the bookbag itself (in support of a record results page)
289 # if a "bookbag" CGI parameter is specified and if the bookbag is public
290 # or owned by the logged-in user (if any).  Bookbag notes are fetched
291 # later if applicable.
292 sub load_rresults_bookbag {
293     my ($self) = @_;
294
295     my $bookbag_id = int($self->cgi->param("bookbag") || 0);
296     return if $bookbag_id < 1;
297
298     my %authz = $self->ctx->{"user"} ?
299         ("-or" => {"pub" => "t", "owner" => $self->ctx->{"user"}->id}) :
300         ("pub" => "t");
301
302     $self->timelog("Load results bookbag");
303     my $bbag = $self->editor->search_container_biblio_record_entry_bucket(
304         {"id" => $bookbag_id, "btype" => "bookbag", %authz}
305     );
306     $self->timelog("Got results bookbag");
307
308     if (!$bbag) {
309         $self->apache->log->warn(
310             "error from cstore retrieving bookbag $bookbag_id!"
311         );
312         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
313     } elsif (@$bbag) {
314         $self->ctx->{"bookbag"} = shift @$bbag;
315     }
316
317     return;
318 }
319
320 # assumes context has a bookbag we're already authorized to look at, and
321 # a list of rec_ids, reasonably sized (from paged search).
322 sub load_rresults_bookbag_item_notes {
323     my ($self, $rec_ids) = @_;
324
325     $self->timelog("Load results bookbag item notes");
326     my $items_with_notes =
327         $self->editor->search_container_biblio_record_entry_bucket_item([
328             {"target_biblio_record_entry" => $rec_ids,
329                 "bucket" => $self->ctx->{"bookbag"}->id},
330             {"flesh" => 1, "flesh_fields" => {"cbrebi" => ["notes"]},
331                 "order_by" => {"cbrebi" => ["id"]}}
332         ]);
333     $self->timelog("Got results bookbag item notes");
334
335     if (!$items_with_notes) {
336         $self->apache->log->warn("error from cstore retrieving cbrebi objects");
337         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
338     }
339
340     $self->ctx->{"bookbag_items_by_bre_id"} = +{
341         map { $_->target_biblio_record_entry => $_ } @$items_with_notes
342     };
343
344     return;
345 }
346
347 # $filter -- CCVM filter expression (see also composite attr def)
348 sub recs_from_metarecord {
349     my ($self, $mr_id, $org, $depth, $filter) = @_;
350     $self->timelog("Getting metarecords to records");
351
352     # in the context of searching, we include all records which
353     # have an opac-visible copy.
354     my $bre_ids = $U->simplereq(
355         'open-ils.circ',
356         'open-ils.circ.holds.metarecord.filtered_records',
357         $mr_id, $filter, $org, $depth, 1);
358
359     $self->timelog("Got metarecords to records");
360     return $bre_ids;
361 }
362
363
364
365 # context additions: 
366 #   page_size
367 #   hit_count
368 #   records : list of bre's and copy-count objects
369 my $max_concurrent_search;
370 sub load_rresults {
371     my $self = shift;
372     my %args = @_;
373     my $internal = $args{internal};
374     my $cgi = $self->cgi;
375     my $ctx = $self->ctx;
376     my $e = $self->editor;
377
378     my $mc = OpenSRF::Utils::Cache->new('global');
379     my $client_ip = $self->apache->headers_in->get('X-Forwarded-For') ||
380         $self->apache->useragent_ip;
381     ($client_ip) = split(/,\s*/, $client_ip);
382     $logger->activity("Client IP: $client_ip");
383
384
385     # 1. param->metarecord : view constituent bib records for a metarecord
386     # 2. param->modifier=metabib : perform a metarecord search
387     my $metarecord = $ctx->{metarecord} = $cgi->param('metarecord');
388     my @mods = $cgi->multi_param('modifier');
389     my $is_meta = (@mods and grep {$_ eq 'metabib'} @mods and !$metarecord);
390     my $id_key = $is_meta ? 'mmr_id' : 'bre_id';
391
392     # find the last record in the set, then redirect
393     my $find_last = $cgi->param('find_last');
394
395     $self->timelog("Loading results");
396     # load bookbag metadata, if requested.
397     if (my $bbag_err = $self->load_rresults_bookbag) {
398         return $bbag_err;
399     }
400
401     $ctx->{page} = 'rresult' unless $internal;
402     $ctx->{ids} = [];
403     $ctx->{records} = [];
404     $ctx->{search_facets} = {};
405     $ctx->{hit_count} = 0;
406     $ctx->{is_meta} = $is_meta;
407
408     # Special alternative searches here.  This could all stand to be cleaner.
409     if ($cgi->param("_special")) {
410         $self->timelog("Calling MARC expert search");
411         return $self->marc_expert_search(%args) if (scalar($cgi->param("tag")) and
412             (!defined $cgi->param("query") or $cgi->param("query") =~ /^\s*$/));
413         $self->timelog("Calling item barcode search");
414         return $self->item_barcode_shortcut if (
415             $cgi->param("qtype") and ($cgi->param("qtype") eq "item_barcode") and not $internal
416         );
417         $self->timelog("Calling call number browse");
418         return $self->call_number_browse_standalone if (
419             $cgi->param("qtype") and ($cgi->param("qtype") eq "cnbrowse")
420         );
421     }
422
423     $self->timelog("Getting search parameters");
424     my $page = $cgi->param('page') || 0;
425     my @facets = $cgi->multi_param('facet');
426     my $limit = $self->_get_search_limit;
427     $ctx->{search_ou} = $self->_get_search_lib();
428     $ctx->{pref_ou} = $self->_get_pref_lib() || $ctx->{search_ou};
429     my $offset = $page * $limit;
430     my $results; 
431     my $tag_circs = $self->tag_circed_items;
432     $self->timelog("Got search parameters");
433
434     $ctx->{page_size} = $limit;
435     $ctx->{search_page} = $page;
436
437     # fetch this page plus the first hit from the next page
438     if ($internal) {
439         $limit = $offset + $limit + 1;
440         $offset = 0;
441     }
442
443     my ($user_query, $query, $site, $depth) = _prepare_biblio_search($cgi, $ctx);
444
445     $self->get_staff_search_settings;
446
447     if (!$find_last and $ctx->{staff_saved_search_size}) {
448         my ($key, $list) = $self->staff_save_search($query);
449         if ($key) {
450             $self->apache->headers_out->add(
451                 "Set-Cookie" => $self->cgi->cookie(
452                     -name => (ref $self)->COOKIE_ANON_CACHE,
453                     -path => "/",
454                     -value => ($key || ''),
455                     -expires => ($key ? undef : "-1h")
456                 )
457             );
458             $ctx->{saved_searches} = $list;
459         }
460     }
461     # Limit and offset will stay here. Everything else should be part of
462     # the query string, not special args.
463     my $args = {'limit' => $limit, 'offset' => $offset};
464
465     return Apache2::Const::OK unless $query;
466
467     if ($tag_circs) {
468         $args->{tag_circulated_records} = 1;
469         $args->{authtoken} = $self->editor->authtoken;
470     }
471     $args->{from_metarecord} = $metarecord if $metarecord;
472
473     # Stuff these into the TT context so that templates can use them in redrawing forms
474     $ctx->{user_query} = $user_query;
475     $ctx->{processed_search_query} = $query;
476
477     $query = "$_ $query" for @facets;
478
479     my $ltag = $is_meta ? '[mmr search]' : '[bre search]';
480     $logger->activity("EGWeb: $ltag $query");
481
482     # Fetch the global flag, defaults to "never too many".
483     unless (defined $max_concurrent_search) {
484         my $mcs = $e->retrieve_config_global_flag('opac.max_concurrent_search.ip');
485         $max_concurrent_search = ($mcs and $mcs->enabled eq 't') ? $mcs->value : 0;
486     }
487
488     if ($max_concurrent_search > 0) {
489         # Right up front, we will limit concurrent searches coming from the same client IP, if configured to do so.
490         $mc->get_cache('EGWEB-MAX-SEARCH-IP:'.$client_ip) || $mc->{memcache}->add('EGWEB-MAX-SEARCH-IP:'.$client_ip, 0);
491         my $concurrent_searches = $mc->{memcache}->incr('EGWEB-MAX-SEARCH-IP:'.$client_ip);
492         $logger->activity("Concurrent searches from client IP $client_ip: $concurrent_searches");
493
494         if ($concurrent_searches > $max_concurrent_search) {
495             $self->apache->log->warn("Too many concurrent searches from IP $client_ip");
496             $mc->{memcache}->decr('EGWEB-MAX-SEARCH-IP:'.$client_ip);
497             return 429; # Apache2::Const does not have a symbol for 429 too many requests
498         }
499     }
500
501     my $method = 'open-ils.search.biblio.multiclass.query';
502     try {
503         $method .= '.staff' if $ctx->{is_staff};
504         $method =~ s/biblio/metabib/ if $is_meta;
505
506         my $ses = OpenSRF::AppSession->create('open-ils.search');
507
508         $self->timelog("Firing off the multiclass query");
509         my $req = $ses->request($method, $args, $query, 1, $ctx->{physical_loc});
510         $results = $req->gather(1);
511         $self->timelog("Returned from the multiclass query");
512
513     } catch Error with {
514         my $err = shift;
515         $logger->error("multiclass search error: $err");
516         $results = {count => 0, ids => []};
517     };
518
519     $mc->{memcache}->decr('EGWEB-MAX-SEARCH-IP:'.$client_ip) if ($max_concurrent_search);
520
521     # INFO: an OpenILS::Event only means "go away" for now.
522     if (defined $U->event_code($results)) {
523         $logger->activity("$method returned event: " . $U->event_code($results));
524         $self->apache->log->warn( "$method returned event: " . $U->event_code($results));
525         return 429; # Apache2::Const does not have a symbol for 429 too many requests
526     }
527
528     my $rec_ids = [map { $_->[0] } @{$results->{ids}}];
529
530     $ctx->{ids} = $rec_ids;
531     $ctx->{hit_count} = $results->{count};
532     $ctx->{superpage} = $results->{superpage};
533     $ctx->{superpage_size} = $results->{superpage_size};
534     $ctx->{pagable_limit} = $results->{core_limit};
535     $ctx->{query_struct} = $results->{global_summary}{query_struct};
536     $logger->debug('query struct: '. Dumper($ctx->{query_struct}));
537     $ctx->{canonicalized_query} = $results->{global_summary}{canonicalized_query};
538     $ctx->{search_summary} = $results->{global_summary};
539
540     if ($find_last) {
541         # redirect to the record detail page for the last record in the results
542         my $rec_id = pop @$rec_ids;
543         $cgi->delete('find_last');
544         my $url = $cgi->url(-full => 1, -path => 1, -query => 1);
545         # TODO: metarecord => /rresults?metarecord=$mmr_id
546         $url =~ s|/results|/record/$rec_id|;
547         return $self->generic_redirect($url);
548     }
549
550     return Apache2::Const::OK if @$rec_ids == 0 or $internal;
551
552     $self->load_rresults_bookbag_item_notes($rec_ids) if $ctx->{bookbag};
553
554     my $fetch_recs = $rec_ids;
555
556     $self->timelog("Calling get_records_and_facets()");
557     my ($facets, @data) = $self->get_records_and_facets(
558         $fetch_recs, $results->{facet_key}, 
559         {
560             flesh => '{holdings_xml,mra,acp,acnp,acns,bmp,cbs}',
561             site => $site,
562             metarecord => $is_meta,
563             depth => $depth,
564             pref_lib => $ctx->{pref_ou},
565         }
566     );
567     $self->timelog("Returned from get_records_and_facets()");
568
569     if ($page == 0 and @$rec_ids == 1) {
570         my $stat = 0;
571         if ($is_meta) {
572             # if the MR has a single constituent record, it will
573             # be in array position 4 of the result blob.
574             # otherwise, we don't want to redirect anyway.
575             my $bre_id = $results->{ids}->[0]->[4];
576             $stat = $self->check_1hit_redirect([$bre_id]) if $bre_id;
577         } else {
578             my $stat = $self->check_1hit_redirect($rec_ids);
579         }
580         return $stat if $stat;
581     }
582
583     # load temporary_list settings for user and ou:
584     $self->_load_lists_and_settings if ($ctx->{user});
585
586     my %mr_contents;
587     # shove recs into context in search results order
588     for my $rec_id (@$rec_ids) {
589         my ($rec) = grep { $_->{$id_key} == $rec_id } @data;
590         push(@{$ctx->{records}}, $rec);
591
592         if ($is_meta) {
593             try {
594                 my $method = 'open-ils.search.biblio.multiclass.query';
595                 $method .= '.staff' if $ctx->{is_staff};
596                 my $ses = OpenSRF::AppSession->create('open-ils.search');
597                 $self->timelog("Firing off the multiclass query: ". $rec_id);
598                 $args->{from_metarecord} = $rec_id;
599                 # offset of main search does not apply to the MR
600                 # constituents query
601                 my $save_offset = $args->{offset};
602                 $args->{offset} = 0;
603                 $mr_contents{$rec_id} = $ses->request($method, $args, $query, 1, $ctx->{physical_loc});
604                 $args->{offset} = $save_offset;
605             } catch Error with {
606                 my $err = shift;
607                 $logger->error("multiclass search error: $err");
608             };
609         }
610     }
611
612     # above we fire all searches in parallel, now we collect the results
613     if ($is_meta) {
614         for my $rec_id (@$rec_ids) {
615             my ($rec) = grep { $_->{$id_key} == $rec_id } @data;
616             my $meta_results;
617             if ($mr_contents{$rec_id}) {
618                 $meta_results = $mr_contents{$rec_id}->gather(1);
619                 $self->timelog("Returned from the multiclass query: ". $rec_id);
620             } else {
621                 $meta_results = {count => 0, ids => []};
622             }
623             my $meta_rec_ids = [map { $_->[0] } @{$meta_results->{ids}}];
624             $rec->{mr_constituent_count} = $meta_results->{count};
625             $rec->{mr_constituent_ids} = $meta_rec_ids;
626         }
627     }
628
629     my $course_module_opt_in = 0;
630     if ($ctx->{get_org_setting}->($self->_get_search_lib, "circ.course_materials_opt_in")) {
631         $course_module_opt_in = 1;
632     }
633
634     for my $rec (@{$ctx->{records}}) {
635         my ($res_rec) = grep { $_->[0] == $rec->{$id_key} } @{$results->{ids}};
636         $rec->{badges} = [split(',', $res_rec->[1])] if $res_rec->[1];
637         $rec->{popularity} = $res_rec->[2];
638         if ($course_module_opt_in) {
639             $rec->{course_materials} = $U->simplereq(
640                 'open-ils.courses',
641                 'open-ils.courses.course_materials.retrieve.atomic',
642                 {record => $rec->{id}}
643             );
644             my %course_ids;
645             for my $material (@{$rec->{course_materials}}) {
646                 $course_ids{$material->course} = 1;
647             }
648
649             $rec->{courses} = $U->simplereq(
650                 'open-ils.courses',
651                 'open-ils.courses.courses.retrieve',
652                 keys %course_ids
653             );
654         }
655         if ($tag_circs) {
656             # index 3 (5 for MR) in the per-record result array is a boolean which
657             # indicates whether the record in question is in the users
658             # accessible circ history list
659             my $index = $is_meta ? 5 : 3;
660             $rec->{user_circulated} = 1 if $res_rec->[$index];
661         }
662     }
663     
664
665     $ctx->{search_facets} = $facets;
666
667     return Apache2::Const::OK;
668 }
669
670 # If the calling search results in 1 record and the client
671 # is configured to do so, redirect the search results to 
672 # the record details page.
673 sub check_1hit_redirect {
674     my ($self, $rec_ids) = @_;
675     my $ctx = $self->ctx;
676
677     return undef unless $rec_ids and @$rec_ids == 1;
678
679     my ($sname, $org);
680
681     $self->timelog("Checking whether to jump to details on a single hit");
682     if ($ctx->{is_staff}) {
683         $sname = 'opac.staff.jump_to_details_on_single_hit';
684         $org = $ctx->{user}->ws_ou;
685
686     } else {
687         $sname = 'opac.patron.jump_to_details_on_single_hit';
688         $org = $self->_get_search_lib();
689     }
690
691     $self->timelog("Return from checking whether to jump to details on a single hit");
692
693     return undef unless 
694         $self->ctx->{get_org_setting}->($org, $sname);
695
696     my $base_url = sprintf(
697         '%s://%s%s/record/%s',
698         $self->ctx->{proto},
699         $self->ctx->{hostname},
700         $self->ctx->{opac_root},
701         $$rec_ids[0],
702     );
703     
704     # If we get here from the same record detail page to which we
705     # now wish to redirect, do not perform the redirect.  This
706     # approach seems to work well, with the rare exception of 
707     # performing a new search directly from the detail page that 
708     # happens to result in the same single hit.  In this case, the 
709     # user will be left on the search results page.  This could be 
710     # overcome w/ additional CGI, etc., but I'm not sure it's necessary.
711     if (my $referer = $ctx->{referer}) {
712         $referer =~ s/([^?]*).*/$1/g;
713         return undef if $base_url eq $referer;
714     }
715
716     return $self->generic_redirect($base_url . '?' . $self->cgi->query_string);
717 }
718
719 # Searching by barcode is a special search that does /not/ respect any other
720 # of the usual search parameters, not even the ones for sorting and paging!
721 sub item_barcode_shortcut {
722     my ($self) = @_;
723
724     $self->timelog("Searching for item_barcode");
725     my $method = "open-ils.search.multi_home.bib_ids.by_barcode";
726     if (my $search = create OpenSRF::AppSession("open-ils.search")) {
727         my $rec_ids = $search->request(
728             $method, $self->cgi->param("query")
729         )->gather(1);
730         $search->kill_me;
731         $self->timelog("Finished searching for item_barcode");
732
733         if (ref $rec_ids ne 'ARRAY') {
734
735             if($U->event_equals($rec_ids, 'ASSET_COPY_NOT_FOUND')) {
736                 $rec_ids = [];
737
738             } else {
739                 if (defined $U->event_code($rec_ids)) {
740                     $self->apache->log->warn(
741                         "$method returned event: " . $U->event_code($rec_ids)
742                     );
743                 } else {
744                     $self->apache->log->warn(
745                         "$method returned something unexpected: $rec_ids"
746                     );
747                 }
748                 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
749             }
750         }
751
752         $self->timelog("Calling get_records_and_facets() for item_barcode");
753         my ($facets, @data) = $self->get_records_and_facets(
754             $rec_ids, undef, {flesh => "{holdings_xml,mra,acnp,acns,bmp,cbs}"}
755         );
756         $self->timelog("Returned from calling get_records_and_facets() for item_barcode");
757
758         my $stat = $self->check_1hit_redirect($rec_ids);
759         return $stat if $stat;
760
761         $self->ctx->{records} = [@data];
762         $self->ctx->{search_facets} = {};
763         $self->ctx->{hit_count} = scalar @data;
764         $self->ctx->{page_size} = $self->ctx->{hit_count};
765         # load temporary_list settings for user and ou:
766         $self->_load_lists_and_settings if ($self->ctx->{user});
767
768         return Apache2::Const::OK;
769     } {
770         $self->apache->log->warn("couldn't connect to open-ils.search");
771         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
772     }
773 }
774
775 # like item_barcode_search, this can't take all the usual search params, but
776 # this one will at least do site, limit and page
777 sub marc_expert_search {
778     my ($self, %args) = @_;
779
780     my @tags = $self->cgi->multi_param("tag");
781     my @subfields = $self->cgi->multi_param("subfield");
782     my @terms = $self->cgi->multi_param("term");
783
784     my $query = [];
785     for (my $i = 0; $i < scalar @tags; $i++) {
786         next if ($tags[$i] eq "" || $terms[$i] eq "");
787         $subfields[$i] = '_' unless $subfields[$i];
788         push @$query, {
789             "term" => $terms[$i],
790             "restrict" => [{"tag" => $tags[$i], "subfield" => $subfields[$i]}]
791         };
792     }
793
794     $logger->info("query for expert search: " . Dumper($query));
795
796     $self->timelog("Getting search parameters");
797     # loc, limit and offset
798     my $page = $self->cgi->param("page") || 0;
799     my $limit = $self->_get_search_limit;
800     $self->ctx->{search_ou} = $self->_get_search_lib();
801     $self->ctx->{pref_ou} = $self->_get_pref_lib();
802     my $offset = $page * $limit;
803     $self->timelog("Got search parameters");
804
805     $self->ctx->{records} = [];
806     $self->ctx->{search_facets} = {};
807     $self->ctx->{page_size} = $limit;
808     $self->ctx->{hit_count} = 0;
809     $self->ctx->{ids} = [];
810     $self->ctx->{search_page} = $page;
811         
812     # nothing to do
813     return Apache2::Const::OK if @$query == 0;
814
815     if ($args{internal}) {
816         $limit = $offset + $limit + 1;
817         $offset = 0;
818     }
819
820     $self->timelog("Searching for MARC expert");
821     my $method = 'open-ils.search.biblio.marc';
822     $method .= '.staff' if $self->ctx->{is_staff};
823     my $timeout = 120;
824     my $ses = OpenSRF::AppSession->create('open-ils.search');
825
826     #when a sort variable is passed in we need to add its value to the arguments
827     my $arghash = {searches => $query, org_unit => $self->ctx->{search_ou}};
828     if (defined $self->cgi->param("sort")) {
829         my ($sort, $sort_dir) = split /\./, $self->cgi->param('sort');
830         $arghash = {%$arghash, sort => "$sort"};
831         if (!defined $sort_dir) {
832             $arghash = {%$arghash, sort_dir => "ASC"};
833         }
834     }
835
836     #add the offset and limit to the argash, so we can go past 100 results
837     #if offset and limit are not in the args then they default to 0 and 100
838     #respectively in biblio_multi_search_full_rec, which limits the results to 100
839     #records
840     $arghash = {%$arghash, offset => $offset, limit => $limit}; 
841
842     my $req = $ses->request(
843         $method,
844         $arghash,
845         $timeout);
846
847     my $resp = $req->recv($timeout);
848     my $results = $resp ? $resp->content : undef;
849     $ses->kill_me;
850     $self->timelog("Got our MARC expert results");
851
852     if (defined $U->event_code($results)) {
853         $self->apache->log->warn(
854             "open-ils.search.biblio.marc returned event: " .
855             $U->event_code($results)
856         );
857         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
858     }
859
860     $self->ctx->{ids} = [ grep { $_ } @{$results->{ids}} ];
861     $self->ctx->{hit_count} = $results->{count};
862
863     return Apache2::Const::OK if @{$self->ctx->{ids}} == 0 or $args{internal};
864
865     if ($page == 0) {
866         my $stat = $self->check_1hit_redirect($self->ctx->{ids});
867         return $stat if $stat;
868     }
869
870     $self->timelog("Calling get_records_and_facets() for MARC expert");
871     my ($facets, @data) = $self->get_records_and_facets(
872         $self->ctx->{ids}, undef, {
873             flesh => "{holdings_xml,mra,acnp,acns,cbs}",
874             pref_lib => $self->ctx->{pref_ou},
875         }
876     );
877     $self->timelog("Returned from calling get_records_and_facets() for MARC expert");
878
879     # load temporary_list settings for user and ou:
880     $self->_load_lists_and_settings if ($self->ctx->{user});
881
882     $self->ctx->{records} = [@data];
883
884     return Apache2::Const::OK;
885 }
886
887 sub call_number_browse_standalone {
888     my ($self) = @_;
889
890     if (my $cnfrag = $self->cgi->param("query")) {
891         my $url = sprintf(
892             '%s://%s%s/cnbrowse?cn=%s',
893             $self->ctx->{proto},
894             $self->ctx->{hostname},
895             $self->ctx->{opac_root},
896             $cnfrag # XXX some kind of escaping needed here?
897         );
898         $url .= '&locg=' . $self->_get_search_lib() if ($self->_get_search_lib());
899         return $self->generic_redirect($url);
900     } else {
901         return $self->generic_redirect; # return to search page
902     }
903 }
904
905 sub load_cnbrowse {
906     my ($self) = @_;
907
908     $self->prepare_browse_call_numbers();
909
910     return Apache2::Const::OK;
911 }
912
913 sub get_staff_search_settings {
914     my ($self) = @_;
915
916     unless ($self->ctx->{is_staff}) {
917         $self->ctx->{staff_saved_search_size} = 0;
918         return;
919     }
920
921     $self->timelog("Getting staff search size");
922     my $sss_size = $self->ctx->{get_org_setting}->(
923         $self->ctx->{physical_loc} || $self->ctx->{aou_tree}->()->id,
924         "opac.staff_saved_search.size",
925     );
926     $self->timelog("Got staff search size");
927
928     # Sic: 0 is 0 (off), but undefined is 10.
929     $sss_size = 10 unless defined $sss_size;
930
931     $self->ctx->{staff_saved_search_size} = $sss_size;
932 }
933
934 sub staff_load_searches {
935     my ($self) = @_;
936
937     my $cache_key = $self->cgi->cookie((ref $self)->COOKIE_ANON_CACHE);
938
939     my $list = [];
940     if ($cache_key) {
941         $self->timelog("Getting anon_cache value");
942         $list = $U->simplereq(
943             "open-ils.actor",
944             "open-ils.actor.anon_cache.get_value",
945             $cache_key, (ref $self)->ANON_CACHE_STAFF_SEARCH
946         );
947         $self->timelog("Got anon_cache value");
948
949         unless ($list) {
950             undef $cache_key;
951             $list = [];
952         }
953     }
954
955     return ($cache_key, $list);
956 }
957
958 sub staff_save_search {
959     my ($self, $query) = @_;
960
961     my $sss_size = $self->ctx->{staff_saved_search_size}; 
962     return unless $sss_size > 0;
963
964     my ($cache_key, $list) = $self->staff_load_searches;
965     my %already = ( map { $_ => 1 } @$list );
966
967     unshift @$list, $query unless $already{$query};
968
969     splice @$list, $sss_size if scalar @$list > $sss_size;
970
971     $self->timelog("Setting anon_cache value");
972     $cache_key = $U->simplereq(
973         "open-ils.actor",
974         "open-ils.actor.anon_cache.set_value",
975         $cache_key, (ref $self)->ANON_CACHE_STAFF_SEARCH, $list
976     );
977     $self->timelog("Set anon_cache value");
978
979     return ($cache_key, $list);
980 }
981
982 1;