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