]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/WWW/EGCatLoader/Search.pm
LP#1284864 correct TPAC metarecord list pagination
[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         if ($qtype eq 'jtitle') {
30             $qtype = 'title';
31         }
32
33         # This stuff probably will need refined or rethought to better handle
34         # the weird things Real Users will surely type in.
35         $contains = "" unless defined $contains; # silence warning
36         if ($contains eq 'nocontains') {
37             $query =~ s/"//g;
38             $query = ('"' . $query . '"') if index $query, ' ';
39             $query = '-' . $query;
40         } elsif ($contains eq 'phrase') {
41             $query =~ s/"//g;
42             $query = ('"' . $query . '"') if index $query, ' ';
43         } elsif ($contains eq 'exact') {
44             $query =~ s/[\^\$]//g;
45             $query = '^' . $query . '$';
46         } elsif ($contains eq 'starts') {
47             $query =~ s/"//g;
48             $query =~ s/[\^\$]//g;
49             $query = '^' . $query;
50             $query = ('"' . $query . '"') if index $query, ' ';
51         }
52         $query = "$qtype:$query" unless $qtype eq 'keyword' and $i == 0;
53
54         $bool = ($bool and $bool eq 'or') ? '||' : '&&';
55         $full_query = $full_query ? "($full_query $bool $query)" : $query;
56     }
57
58     return $full_query;
59 }
60
61 sub _prepare_biblio_search {
62     my ($cgi, $ctx) = @_;
63
64     my $query = _prepare_biblio_search_basics($cgi) || '';
65
66     $query .= ' ' . $ctx->{global_search_filter} if $ctx->{global_search_filter};
67
68     foreach ($cgi->param('modifier')) {
69         # The unless bit is to avoid stacking modifiers.
70         $query = ('#' . $_ . ' ' . $query) unless 
71             $query =~ qr/\#\Q$_/ or $_ eq 'metabib';
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) $query" if length $term;
88     }
89
90     if ($cgi->param("bookbag")) {
91         $query = "container(bre,bookbag," . int($cgi->param("bookbag")) . ") $query";
92     }
93
94     # Journal title hackery complete
95     if ($cgi->param("qtype") && $cgi->param("qtype") eq "jtitle") {
96         $query = "bib_level(s) $query";
97     }
98
99     if ($cgi->param('pubdate') && $cgi->param('date1')) {
100         if ($cgi->param('pubdate') eq 'between') {
101             my $btw = 'between(' . $cgi->param('date1');
102             $btw .= ',' .  $cgi->param('date2') if $cgi->param('date2');
103             $btw .= ')';
104             $query = "$btw $query";
105         } elsif ($cgi->param('pubdate') eq 'is') {
106             $query = 'between(' . $cgi->param('date1') .
107                 ',' .  $cgi->param('date1') . ") $query";  # sic, date1 twice
108         } else {
109             $query = $cgi->param('pubdate') .
110                 '(' . $cgi->param('date1') . ") $query";
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) $query";
124         if ($desc and not $query =~ /\#descending/) {
125             $query = "#descending $query";
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) and not $query =~ / pref_ou\(\S+\)/) {
143         my $plib = $ctx->{get_aou}->($pref_ou)->shortname;
144         $query = "pref_ou($plib) $query";
145     }
146
147     if (my $grp = $ctx->{copy_location_group}) {
148         $query = "location_groups($grp) $query";
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 # $filter -- CCVM filter expression (see also composite attr def)
300 sub recs_from_metarecord {
301     my ($self, $mr_id, $org, $depth, $filter) = @_;
302     $self->timelog("Getting metarecords to records");
303
304     # in the context of searching, we include all records which
305     # have an opac-visible copy.
306     my $bre_ids = $U->simplereq(
307         'open-ils.circ',
308         'open-ils.circ.holds.metarecord.filtered_records',
309         $mr_id, $filter, $org, $depth, 1);
310
311     $self->timelog("Got metarecords to records");
312     return $bre_ids;
313 }
314
315
316
317 # context additions: 
318 #   page_size
319 #   hit_count
320 #   records : list of bre's and copy-count objects
321 sub load_rresults {
322     my $self = shift;
323     my %args = @_;
324     my $internal = $args{internal};
325     my $cgi = $self->cgi;
326     my $ctx = $self->ctx;
327     my $e = $self->editor;
328
329     # 1. param->metarecord : view constituent bib records for a metarecord
330     # 2. param->modifier=metabib : perform a metarecord search
331     my $metarecord = $ctx->{metarecord} = $cgi->param('metarecord');
332     my @mods = $cgi->param('modifier');
333     my $is_meta = (@mods and grep {$_ eq 'metabib'} @mods and !$metarecord);
334     my $id_key = $is_meta ? 'mmr_id' : 'bre_id';
335
336     # find the last record in the set, then redirect
337     my $find_last = $cgi->param('find_last');
338
339     $self->timelog("Loading results");
340     # load bookbag metadata, if requested.
341     if (my $bbag_err = $self->load_rresults_bookbag) {
342         return $bbag_err;
343     }
344
345     $ctx->{page} = 'rresult' unless $internal;
346     $ctx->{ids} = [];
347     $ctx->{records} = [];
348     $ctx->{search_facets} = {};
349     $ctx->{hit_count} = 0;
350
351     # Special alternative searches here.  This could all stand to be cleaner.
352     if ($cgi->param("_special")) {
353         $self->timelog("Calling MARC expert search");
354         return $self->marc_expert_search(%args) if scalar($cgi->param("tag"));
355         $self->timelog("Calling item barcode search");
356         return $self->item_barcode_shortcut if (
357             $cgi->param("qtype") and ($cgi->param("qtype") eq "item_barcode") and not $internal
358         );
359         $self->timelog("Calling call number browse");
360         return $self->call_number_browse_standalone if (
361             $cgi->param("qtype") and ($cgi->param("qtype") eq "cnbrowse")
362         );
363     }
364
365     $self->timelog("Getting search parameters");
366     my $page = $cgi->param('page') || 0;
367     my @facets = $cgi->param('facet');
368     my $limit = $self->_get_search_limit;
369     $ctx->{search_ou} = $self->_get_search_lib();
370     $ctx->{pref_ou} = $self->_get_pref_lib() || $ctx->{search_ou};
371     my $offset = $page * $limit;
372     my $results; 
373     my $tag_circs = $self->tag_circed_items;
374     $self->timelog("Got search parameters");
375
376     $ctx->{page_size} = $limit;
377     $ctx->{search_page} = $page;
378
379     # fetch this page plus the first hit from the next page
380     if ($internal) {
381         $limit = $offset + $limit + 1;
382         $offset = 0;
383     }
384
385     my ($query, $site, $depth) = _prepare_biblio_search($cgi, $ctx);
386
387     $self->get_staff_search_settings;
388
389     if (!$find_last and $ctx->{staff_saved_search_size}) {
390         my ($key, $list) = $self->staff_save_search($query);
391         if ($key) {
392             $self->apache->headers_out->add(
393                 "Set-Cookie" => $self->cgi->cookie(
394                     -name => (ref $self)->COOKIE_ANON_CACHE,
395                     -path => "/",
396                     -value => ($key || ''),
397                     -expires => ($key ? undef : "-1h")
398                 )
399             );
400             $ctx->{saved_searches} = $list;
401         }
402     }
403
404     if ($metarecord) {
405         my $bre_ids = $self->recs_from_metarecord(
406             $metarecord, $ctx->{search_ou}, $depth);
407        
408         # force the metarecord result blob to match the format of regular search results
409         $results->{ids} = [map { [$_] } @$bre_ids];
410         $results->{count} = scalar(@{$results->{ids}});
411
412     } else {
413
414         return Apache2::Const::OK unless $query;
415
416         # Limit and offset will stay here. Everything else should be part of
417         # the query string, not special args.
418         my $args = {'limit' => $limit, 'offset' => $offset};
419
420         if ($tag_circs) {
421             $args->{tag_circulated_records} = 1;
422             $args->{authtoken} = $self->editor->authtoken;
423         }
424
425         # Stuff these into the TT context so that templates can use them in redrawing forms
426         $ctx->{processed_search_query} = $query;
427
428         $query = "$_ $query" for @facets;
429
430         my $ltag = $is_meta ? '[mmr search]' : '[bre search]';
431         $logger->activity("EGWeb: $ltag $query");
432
433         try {
434
435             my $method = 'open-ils.search.biblio.multiclass.query';
436             $method .= '.staff' if $ctx->{is_staff};
437             $method =~ s/biblio/metabib/ if $is_meta;
438
439             my $ses = OpenSRF::AppSession->create('open-ils.search');
440
441             $self->timelog("Firing off the multiclass query");
442             my $req = $ses->request($method, $args, $query, 1);
443             $results = $req->gather(1);
444             $self->timelog("Returned from the multiclass query");
445
446         } catch Error with {
447             my $err = shift;
448             $logger->error("multiclass search error: $err");
449             $results = {count => 0, ids => []};
450         };
451     }
452
453     my $rec_ids = [map { $_->[0] } @{$results->{ids}}];
454
455     $ctx->{ids} = $rec_ids;
456     $ctx->{hit_count} = $results->{count};
457     $ctx->{parsed_query} = $results->{parsed_query};
458
459     if ($find_last) {
460         # redirect to the record detail page for the last record in the results
461         my $rec_id = pop @$rec_ids;
462         $cgi->delete('find_last');
463         my $url = $cgi->url(-full => 1, -path => 1, -query => 1);
464         # TODO: metarecord => /rresults?metarecord=$mmr_id
465         $url =~ s|/results|/record/$rec_id|;
466         return $self->generic_redirect($url);
467     }
468
469     return Apache2::Const::OK if @$rec_ids == 0 or $internal;
470
471     $self->load_rresults_bookbag_item_notes($rec_ids) if $ctx->{bookbag};
472
473     my $fetch_recs = $rec_ids;
474
475     $self->timelog("Calling get_records_and_facets()");
476     my ($facets, @data) = $self->get_records_and_facets(
477         $fetch_recs, $results->{facet_key}, 
478         {
479             flesh => '{holdings_xml,mra,acp,acnp,acns,bmp}',
480             site => $site,
481             metarecord => $is_meta,
482             depth => $depth,
483             pref_lib => $ctx->{pref_ou},
484         }
485     );
486     $self->timelog("Returned from get_records_and_facets()");
487
488     if ($page == 0 and @$rec_ids == 1) {
489         my $stat = 0;
490         if ($is_meta) {
491             # if the MR has a single constituent record, it will
492             # be in array position 2 of the result blob.
493             # otherwise, we don't want to redirect anyway.
494             my $bre_id = $results->{ids}->[0]->[2];
495             $stat = $self->check_1hit_redirect([$bre_id]) if $bre_id;
496         } else {
497             my $stat = $self->check_1hit_redirect($rec_ids);
498         }
499         return $stat if $stat;
500     }
501
502     # load temporary_list settings for user and ou:
503     $self->_load_lists_and_settings if ($ctx->{user});
504
505     # shove recs into context in search results order
506     for my $rec_id (@$rec_ids) {
507         my ($rec) = grep { $_->{$id_key} == $rec_id } @data;
508         push(@{$ctx->{records}}, $rec);
509
510         if ($is_meta) {
511             # collect filtered, constituent records count for each MR
512             my $bre_ids = $self->recs_from_metarecord(
513                 $rec_id, $ctx->{search_ou}, $depth);
514             $rec->{mr_constituent_count} = scalar(@$bre_ids);
515         }
516     }
517
518     if ($tag_circs) {
519         for my $rec (@{$ctx->{records}}) {
520             my ($res_rec) = grep { $_->[0] == $rec->{$id_key} } @{$results->{ids}};
521             # index 1 in the per-record result array is a boolean which
522             # indicates whether the record in question is in the users
523             # accessible circ history list
524             my $index = $is_meta ? 3 : 1;
525             $rec->{user_circulated} = 1 if $res_rec->[$index];
526         }
527     }
528
529     $ctx->{search_facets} = $facets;
530
531     return Apache2::Const::OK;
532 }
533
534 # If the calling search results in 1 record and the client
535 # is configured to do so, redirect the search results to 
536 # the record details page.
537 sub check_1hit_redirect {
538     my ($self, $rec_ids) = @_;
539     my $ctx = $self->ctx;
540
541     return undef unless $rec_ids and @$rec_ids == 1;
542
543     my ($sname, $org);
544
545     $self->timelog("Checking whether to jump to details on a single hit");
546     if ($ctx->{is_staff}) {
547         $sname = 'opac.staff.jump_to_details_on_single_hit';
548         $org = $ctx->{user}->ws_ou;
549
550     } else {
551         $sname = 'opac.patron.jump_to_details_on_single_hit';
552         $org = $self->_get_search_lib();
553     }
554
555     $self->timelog("Return from checking whether to jump to details on a single hit");
556
557     return undef unless 
558         $self->ctx->{get_org_setting}->($org, $sname);
559
560     my $base_url = sprintf(
561         '%s://%s%s/record/%s',
562         $self->ctx->{proto},
563         $self->ctx->{hostname},
564         $self->ctx->{opac_root},
565         $$rec_ids[0],
566     );
567     
568     # If we get here from the same record detail page to which we
569     # now wish to redirect, do not perform the redirect.  This
570     # approach seems to work well, with the rare exception of 
571     # performing a new search directly from the detail page that 
572     # happens to result in the same single hit.  In this case, the 
573     # user will be left on the search results page.  This could be 
574     # overcome w/ additional CGI, etc., but I'm not sure it's necessary.
575     if (my $referer = $ctx->{referer}) {
576         $referer =~ s/([^?]*).*/$1/g;
577         return undef if $base_url eq $referer;
578     }
579
580     return $self->generic_redirect($base_url . '?' . $self->cgi->query_string);
581 }
582
583 # Searching by barcode is a special search that does /not/ respect any other
584 # of the usual search parameters, not even the ones for sorting and paging!
585 sub item_barcode_shortcut {
586     my ($self) = @_;
587
588     $self->timelog("Searching for item_barcode");
589     my $method = "open-ils.search.multi_home.bib_ids.by_barcode";
590     if (my $search = create OpenSRF::AppSession("open-ils.search")) {
591         my $rec_ids = $search->request(
592             $method, $self->cgi->param("query")
593         )->gather(1);
594         $search->kill_me;
595         $self->timelog("Finished searching for item_barcode");
596
597         if (ref $rec_ids ne 'ARRAY') {
598
599             if($U->event_equals($rec_ids, 'ASSET_COPY_NOT_FOUND')) {
600                 $rec_ids = [];
601
602             } else {
603                 if (defined $U->event_code($rec_ids)) {
604                     $self->apache->log->warn(
605                         "$method returned event: " . $U->event_code($rec_ids)
606                     );
607                 } else {
608                     $self->apache->log->warn(
609                         "$method returned something unexpected: $rec_ids"
610                     );
611                 }
612                 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
613             }
614         }
615
616         $self->timelog("Calling get_records_and_facets() for item_barcode");
617         my ($facets, @data) = $self->get_records_and_facets(
618             $rec_ids, undef, {flesh => "{holdings_xml,mra,acnp,acns,bmp}"}
619         );
620         $self->timelog("Returned from calling get_records_and_facets() for item_barcode");
621
622         my $stat = $self->check_1hit_redirect($rec_ids);
623         return $stat if $stat;
624
625         $self->ctx->{records} = [@data];
626         $self->ctx->{search_facets} = {};
627         $self->ctx->{hit_count} = scalar @data;
628         $self->ctx->{page_size} = $self->ctx->{hit_count};
629         # load temporary_list settings for user and ou:
630         $self->_load_lists_and_settings if ($self->ctx->{user});
631
632         return Apache2::Const::OK;
633     } {
634         $self->apache->log->warn("couldn't connect to open-ils.search");
635         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
636     }
637 }
638
639 # like item_barcode_search, this can't take all the usual search params, but
640 # this one will at least do site, limit and page
641 sub marc_expert_search {
642     my ($self, %args) = @_;
643
644     my @tags = $self->cgi->param("tag");
645     my @subfields = $self->cgi->param("subfield");
646     my @terms = $self->cgi->param("term");
647
648     my $query = [];
649     for (my $i = 0; $i < scalar @tags; $i++) {
650         next if ($tags[$i] eq "" || $terms[$i] eq "");
651         $subfields[$i] = '_' unless $subfields[$i];
652         push @$query, {
653             "term" => $terms[$i],
654             "restrict" => [{"tag" => $tags[$i], "subfield" => $subfields[$i]}]
655         };
656     }
657
658     $logger->info("query for expert search: " . Dumper($query));
659
660     $self->timelog("Getting search parameters");
661     # loc, limit and offset
662     my $page = $self->cgi->param("page") || 0;
663     my $limit = $self->_get_search_limit;
664     $self->ctx->{search_ou} = $self->_get_search_lib();
665     $self->ctx->{pref_ou} = $self->_get_pref_lib();
666     my $offset = $page * $limit;
667     $self->timelog("Got search parameters");
668
669     $self->ctx->{records} = [];
670     $self->ctx->{search_facets} = {};
671     $self->ctx->{page_size} = $limit;
672     $self->ctx->{hit_count} = 0;
673     $self->ctx->{ids} = [];
674     $self->ctx->{search_page} = $page;
675         
676     # nothing to do
677     return Apache2::Const::OK if @$query == 0;
678
679     if ($args{internal}) {
680         $limit = $offset + $limit + 1;
681         $offset = 0;
682     }
683
684     $self->timelog("Searching for MARC expert");
685     my $method = 'open-ils.search.biblio.marc';
686     $method .= '.staff' if $self->ctx->{is_staff};
687     my $timeout = 120;
688     my $ses = OpenSRF::AppSession->create('open-ils.search');
689     my $req = $ses->request(
690         $method,
691         {searches => $query, org_unit => $self->ctx->{search_ou}}, 
692         $limit, $offset, $timeout);
693
694     my $resp = $req->recv($timeout);
695     my $results = $resp ? $resp->content : undef;
696     $ses->kill_me;
697     $self->timelog("Got our MARC expert results");
698
699     if (defined $U->event_code($results)) {
700         $self->apache->log->warn(
701             "open-ils.search.biblio.marc returned event: " .
702             $U->event_code($results)
703         );
704         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
705     }
706
707     $self->ctx->{ids} = [ grep { $_ } @{$results->{ids}} ];
708     $self->ctx->{hit_count} = $results->{count};
709
710     return Apache2::Const::OK if @{$self->ctx->{ids}} == 0 or $args{internal};
711
712     if ($page == 0) {
713         my $stat = $self->check_1hit_redirect($self->ctx->{ids});
714         return $stat if $stat;
715     }
716
717     $self->timelog("Calling get_records_and_facets() for MARC expert");
718     my ($facets, @data) = $self->get_records_and_facets(
719         $self->ctx->{ids}, undef, {
720             flesh => "{holdings_xml,mra,acnp,acns}",
721             pref_lib => $self->ctx->{pref_ou},
722         }
723     );
724     $self->timelog("Returned from calling get_records_and_facets() for MARC expert");
725
726     # load temporary_list settings for user and ou:
727     $self->_load_lists_and_settings if ($self->ctx->{user});
728
729     $self->ctx->{records} = [@data];
730
731     return Apache2::Const::OK;
732 }
733
734 sub call_number_browse_standalone {
735     my ($self) = @_;
736
737     if (my $cnfrag = $self->cgi->param("query")) {
738         my $url = sprintf(
739             '%s://%s%s/cnbrowse?cn=%s',
740             $self->ctx->{proto},
741             $self->ctx->{hostname},
742             $self->ctx->{opac_root},
743             $cnfrag # XXX some kind of escaping needed here?
744         );
745         $url .= '&locg=' . $self->_get_search_lib() if ($self->_get_search_lib());
746         return $self->generic_redirect($url);
747     } else {
748         return $self->generic_redirect; # return to search page
749     }
750 }
751
752 sub load_cnbrowse {
753     my ($self) = @_;
754
755     $self->prepare_browse_call_numbers();
756
757     return Apache2::Const::OK;
758 }
759
760 sub get_staff_search_settings {
761     my ($self) = @_;
762
763     unless ($self->ctx->{is_staff}) {
764         $self->ctx->{staff_saved_search_size} = 0;
765         return;
766     }
767
768     $self->timelog("Getting staff search size");
769     my $sss_size = $self->ctx->{get_org_setting}->(
770         $self->ctx->{physical_loc} || $self->ctx->{aou_tree}->()->id,
771         "opac.staff_saved_search.size",
772     );
773     $self->timelog("Got staff search size");
774
775     # Sic: 0 is 0 (off), but undefined is 10.
776     $sss_size = 10 unless defined $sss_size;
777
778     $self->ctx->{staff_saved_search_size} = $sss_size;
779 }
780
781 sub staff_load_searches {
782     my ($self) = @_;
783
784     my $cache_key = $self->cgi->cookie((ref $self)->COOKIE_ANON_CACHE);
785
786     my $list = [];
787     if ($cache_key) {
788         $self->timelog("Getting anon_cache value");
789         $list = $U->simplereq(
790             "open-ils.actor",
791             "open-ils.actor.anon_cache.get_value",
792             $cache_key, (ref $self)->ANON_CACHE_STAFF_SEARCH
793         );
794         $self->timelog("Got anon_cache value");
795
796         unless ($list) {
797             undef $cache_key;
798             $list = [];
799         }
800     }
801
802     return ($cache_key, $list);
803 }
804
805 sub staff_save_search {
806     my ($self, $query) = @_;
807
808     my $sss_size = $self->ctx->{staff_saved_search_size}; 
809     return unless $sss_size > 0;
810
811     my ($cache_key, $list) = $self->staff_load_searches;
812     my %already = ( map { $_ => 1 } @$list );
813
814     unshift @$list, $query unless $already{$query};
815
816     splice @$list, $sss_size if scalar @$list > $sss_size;
817
818     $self->timelog("Setting anon_cache value");
819     $cache_key = $U->simplereq(
820         "open-ils.actor",
821         "open-ils.actor.anon_cache.set_value",
822         $cache_key, (ref $self)->ANON_CACHE_STAFF_SEARCH, $list
823     );
824     $self->timelog("Set anon_cache value");
825
826     return ($cache_key, $list);
827 }
828
829 1;