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