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