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