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