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