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