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