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