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