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