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