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