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