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