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 OpenSRF::Utils::Cache;
6 use OpenILS::Utils::CStoreEditor qw/:funcs/;
7 use OpenILS::Utils::Fieldmapper;
8 use OpenILS::Application::AppUtils;
9 use OpenSRF::Utils::JSON;
11 $Data::Dumper::Indent = 0;
12 my $U = 'OpenILS::Application::AppUtils';
16 sub _prepare_biblio_search_basics {
19 return scalar($cgi->param('query')) unless scalar($cgi->param('qtype'));
21 # fetch, once per mod_perl backend, the list of valid classes and aliases
22 unless (@_qtype_list) {
23 my $editor = new_editor();
24 my $classes = $editor->retrieve_all_config_metabib_class();
25 my $aliases = $editor->retrieve_all_config_metabib_search_alias();
27 push @_qtype_list, map { $_->name } @$classes;
28 push @_qtype_list, map { $_->alias } @$aliases;
32 my @part_names = qw/qtype contains query bool/;
33 $parts{$_} = [ $cgi->param($_) ] for (@part_names);
36 my @bookplate_queries = ();
37 for (my $i = 0; $i < scalar @{$parts{'qtype'}}; $i++) {
38 my ($qtype, $contains, $query, $bool) = map { $parts{$_}->[$i] } @part_names;
40 next unless $query =~ /\S/;
42 # Hack for bookplates; "bookplate" is not a real search
43 # class, so grabbing them out of the advanced search query
44 # params to convert to a copy_tag(*,...) filter later
45 if ($qtype eq 'bookplate') {
46 $query =~ s/[)(]/ /g; # don't break on 'foo(bar)baz'
47 push @bookplate_queries, $query;
51 # Hack for journal title
53 if ($qtype eq 'jtitle') {
58 # This restricts qtype to classes, aliases, and field lists (approximately)
59 next unless grep { $qtype =~ /^$_(?:\|\w+)*$/ } @_qtype_list;
61 # This stuff probably will need refined or rethought to better handle
62 # the weird things Real Users will surely type in.
63 $contains = "" unless defined $contains; # silence warning
64 if ($contains eq 'nocontains') {
66 $query = ('"' . $query . '"') if index $query, ' ';
67 $query = '-' . $query;
68 } elsif ($contains eq 'phrase') {
70 $query = ('"' . $query . '"') if index $query, ' ';
71 } elsif ($contains eq 'exact') {
72 $query =~ s/[\^\$]//g;
73 $query = '^' . $query . '$';
74 } elsif ($contains eq 'starts') {
76 $query =~ s/[\^\$]//g;
77 $query = '^' . $query;
78 $query = ('"' . $query . '"') if index $query, ' ';
81 # Journal title hackery complete
83 $query = "bib_level(s) $query";
86 $query = "$qtype:$query" unless ($query =~ /^$qtype:/ or ($qtype eq 'keyword' and $i == 0));
88 $bool = ($bool and $bool eq 'or') ? '||' : '&&';
89 $full_query = $full_query ? "($full_query $bool $query)" : $query;
92 return $full_query, \@bookplate_queries;
95 sub _prepare_biblio_search {
98 # XXX This will still contain the jtitle hack...
99 my ($user_query, $bookplate_queries) = _prepare_biblio_search_basics($cgi);
101 $bookplate_queries //= [];
102 my $query = $user_query;
103 if (@$bookplate_queries) {
104 $query .= " " . join(" ", map { "copy_tag(*,$_)" } @$bookplate_queries);
105 # hack to handle the case where a bookplate comes from the
107 $user_query = $bookplate_queries->[0] if $user_query eq '';
110 $query .= ' ' . $ctx->{global_search_filter} if $ctx->{global_search_filter};
112 foreach ($cgi->multi_param('modifier')) {
113 # The unless bit is to avoid stacking modifiers.
114 $query = ('#' . $_ . ' ' . $query) unless
115 $query =~ qr/\#\Q$_/ or $_ eq 'metabib';
119 foreach (grep /^fi:/, $cgi->multi_param) {
121 my $term = join(",", $cgi->multi_param($_));
122 $query .= " $1($term)" if length $term;
125 # filter group entries. Entries from like filters are grouped into a single
126 # filter_group_entry() filter (ORed). Each collection is ANDed together.
127 # fg:foo_group=foo_entry_id
128 foreach (grep /^fg:/, $cgi->multi_param) {
130 my $term = join(",", $cgi->multi_param($_));
131 $query = "filter_group_entry($term) $query" if length $term;
134 if ($cgi->param("bookbag")) {
135 $query = "container(bre,bookbag," . int($cgi->param("bookbag")) . ") $query";
138 if ($cgi->param('pubdate') && $cgi->param('date1')) {
139 if ($cgi->param('pubdate') eq 'between') {
140 my $btw = 'between(' . $cgi->param('date1');
141 $btw .= ',' . $cgi->param('date2') if $cgi->param('date2');
143 $query = "$btw $query";
144 } elsif ($cgi->param('pubdate') eq 'is') {
145 $query = 'date1(' . $cgi->param('date1') . ") $query";
147 $query = $cgi->param('pubdate') .
148 '(' . $cgi->param('date1') . ") $query";
152 # ---------------------------------------------------------------------
153 # Nothing below here constitutes a query by itself. If the query value
154 # is still empty up to this point, there is no query. abandon ship.
155 return () unless $query;
157 # The search_scope param comes from a mixed-use dropdown containing depth,
158 # lasso, and location_groups filters.
159 $query .= ' ' . $cgi->param('search_scope') if defined $cgi->param('search_scope');
161 # The search_lasso context param comes from the locg dropdown, like the copy location.
162 $query .= ' lasso(' . $ctx->{search_lasso} .')' if $ctx->{search_lasso};
164 # sort is treated specially, even though it's actually a filter
165 if (defined($cgi->param('sort'))) {
166 $query =~ s/sort\([^\)]*\)//g; # override existing sort(). no stacking.
167 my ($axis, $desc) = split /\./, $cgi->param('sort');
168 $query = "sort($axis) $query" if $axis;
169 if ($desc and not $query =~ /\#descending/) {
170 $query = "#descending $query";
171 } elsif (not $desc) {
172 $query =~ s/\#descending//;
179 my (@naive_query_re, $site);
181 my $org = $ctx->{search_ou};
182 if (defined($org) and $org ne '' and ($org ne $ctx->{aou_tree}->()->id) and not $query =~ /site\(\S+\)/) {
183 my $thing = " site(" . $ctx->{get_aou}->($org)->shortname . ")";
186 push @naive_query_re, $thing;
189 my $pref_ou = $ctx->{pref_ou};
190 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+\)/) {
191 my $plib = $ctx->{get_aou}->($pref_ou)->shortname;
192 $query = "pref_ou($plib) $query";
195 if (my $grp = $ctx->{copy_location_group}) {
196 $query = "location_groups($grp) $query";
200 ($site) = ($query =~ /site\(([^\)]+)\)/);
201 $site ||= $ctx->{aou_tree}->()->shortname;
205 if ($query =~ /depth\(\d+\)/) {
207 # depth is encoded in the search query
208 ($depth) = ($query =~ /depth\((\d+)\)/);
212 if (defined $cgi->param('depth')) {
213 $depth = $cgi->param('depth');
215 # no depth specified. match the depth to the search org
216 my ($org) = grep { $_->shortname eq $site } @{$ctx->{aou_list}->()};
217 $depth = $org->ou_type->depth;
219 my $thing = " depth($depth)";
222 push @naive_query_re, $thing;
225 # This gives templates a way to take site() and depth() back out of
226 # query strings when they shouldn't be there (because they're controllable
227 # with other widgets).
228 $ctx->{naive_query_scrub} = sub {
230 $query =~ s/\Q$_\E// foreach (@naive_query_re);
234 $logger->info("tpac: site=$site, depth=$depth, user_query=$user_query, query=$query");
236 return ($user_query, $query, $site, $depth);
239 sub _get_search_limit {
242 # param takes precedence
243 my $limit = $self->cgi->param('limit');
244 return $limit if $limit;
246 if($self->editor->requestor) {
247 $self->timelog("Checking for opac.hits_per_page preference");
248 # See if the user has a hit count preference
249 my $lset = $self->editor->search_actor_user_setting({
250 usr => $self->editor->requestor->id,
251 name => 'opac.hits_per_page'
253 $self->timelog("Got opac.hits_per_page preference");
254 return OpenSRF::Utils::JSON->JSON2perl($lset->value) if $lset;
260 sub tag_circed_items {
262 my $e = $self->editor;
264 $self->timelog("Tag circed items?");
265 return 0 unless $e->requestor;
266 $self->timelog("Checking for opac.search.tag_circulated_items");
267 return 0 unless $self->ctx->{get_org_setting}->(
268 $e->requestor->home_ou,
269 'opac.search.tag_circulated_items');
271 # user has to be opted-in to circ history in some capacity
272 $self->timelog("Checking for history.circ.retention_*");
273 my $sets = $e->search_actor_user_setting({
274 usr => $e->requestor->id,
276 'history.circ.retention_age',
277 'history.circ.retention_start'
281 $self->timelog("Return from checking for history.circ.retention_*");
283 return 0 unless @$sets;
288 # This only loads the bookbag itself (in support of a record results page)
289 # if a "bookbag" CGI parameter is specified and if the bookbag is public
290 # or owned by the logged-in user (if any). Bookbag notes are fetched
291 # later if applicable.
292 sub load_rresults_bookbag {
295 my $bookbag_id = int($self->cgi->param("bookbag") || 0);
296 return if $bookbag_id < 1;
298 my %authz = $self->ctx->{"user"} ?
299 ("-or" => {"pub" => "t", "owner" => $self->ctx->{"user"}->id}) :
302 $self->timelog("Load results bookbag");
303 my $bbag = $self->editor->search_container_biblio_record_entry_bucket(
304 {"id" => $bookbag_id, "btype" => "bookbag", %authz}
306 $self->timelog("Got results bookbag");
309 $self->apache->log->warn(
310 "error from cstore retrieving bookbag $bookbag_id!"
312 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
314 $self->ctx->{"bookbag"} = shift @$bbag;
320 # assumes context has a bookbag we're already authorized to look at, and
321 # a list of rec_ids, reasonably sized (from paged search).
322 sub load_rresults_bookbag_item_notes {
323 my ($self, $rec_ids) = @_;
325 $self->timelog("Load results bookbag item notes");
326 my $items_with_notes =
327 $self->editor->search_container_biblio_record_entry_bucket_item([
328 {"target_biblio_record_entry" => $rec_ids,
329 "bucket" => $self->ctx->{"bookbag"}->id},
330 {"flesh" => 1, "flesh_fields" => {"cbrebi" => ["notes"]},
331 "order_by" => {"cbrebi" => ["id"]}}
333 $self->timelog("Got results bookbag item notes");
335 if (!$items_with_notes) {
336 $self->apache->log->warn("error from cstore retrieving cbrebi objects");
337 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
340 $self->ctx->{"bookbag_items_by_bre_id"} = +{
341 map { $_->target_biblio_record_entry => $_ } @$items_with_notes
347 # $filter -- CCVM filter expression (see also composite attr def)
348 sub recs_from_metarecord {
349 my ($self, $mr_id, $org, $depth, $filter) = @_;
350 $self->timelog("Getting metarecords to records");
352 # in the context of searching, we include all records which
353 # have an opac-visible copy.
354 my $bre_ids = $U->simplereq(
356 'open-ils.circ.holds.metarecord.filtered_records',
357 $mr_id, $filter, $org, $depth, 1);
359 $self->timelog("Got metarecords to records");
368 # records : list of bre's and copy-count objects
369 my $max_concurrent_search;
373 my $internal = $args{internal};
374 my $cgi = $self->cgi;
375 my $ctx = $self->ctx;
376 my $e = $self->editor;
378 my $mc = OpenSRF::Utils::Cache->new('global');
379 my $client_ip = $self->apache->headers_in->get('X-Forwarded-For') ||
380 $self->apache->useragent_ip;
381 ($client_ip) = split(/,\s*/, $client_ip);
382 $logger->activity("Client IP: $client_ip");
385 # 1. param->metarecord : view constituent bib records for a metarecord
386 # 2. param->modifier=metabib : perform a metarecord search
387 my $metarecord = $ctx->{metarecord} = $cgi->param('metarecord');
388 my @mods = $cgi->multi_param('modifier');
389 my $is_meta = (@mods and grep {$_ eq 'metabib'} @mods and !$metarecord);
390 my $id_key = $is_meta ? 'mmr_id' : 'bre_id';
392 # find the last record in the set, then redirect
393 my $find_last = $cgi->param('find_last');
395 $self->timelog("Loading results");
396 # load bookbag metadata, if requested.
397 if (my $bbag_err = $self->load_rresults_bookbag) {
401 $ctx->{page} = 'rresult' unless $internal;
403 $ctx->{records} = [];
404 $ctx->{search_facets} = {};
405 $ctx->{hit_count} = 0;
406 $ctx->{is_meta} = $is_meta;
408 # Special alternative searches here. This could all stand to be cleaner.
409 if ($cgi->param("_special")) {
410 $self->timelog("Calling MARC expert search");
411 return $self->marc_expert_search(%args) if (scalar($cgi->param("tag")) and
412 (!defined $cgi->param("query") or $cgi->param("query") =~ /^\s*$/));
413 $self->timelog("Calling item barcode search");
414 return $self->item_barcode_shortcut if (
415 $cgi->param("qtype") and ($cgi->param("qtype") eq "item_barcode") and not $internal
417 $self->timelog("Calling call number browse");
418 return $self->call_number_browse_standalone if (
419 $cgi->param("qtype") and ($cgi->param("qtype") eq "cnbrowse")
423 $self->timelog("Getting search parameters");
424 my $page = $cgi->param('page') || 0;
425 my @facets = $cgi->multi_param('facet');
426 my $limit = $self->_get_search_limit;
427 $ctx->{search_ou} = $self->_get_search_lib();
428 $ctx->{pref_ou} = $self->_get_pref_lib() || $ctx->{search_ou};
429 my $offset = $page * $limit;
431 my $tag_circs = $self->tag_circed_items;
432 $self->timelog("Got search parameters");
434 $ctx->{page_size} = $limit;
435 $ctx->{search_page} = $page;
437 # fetch this page plus the first hit from the next page
439 $limit = $offset + $limit + 1;
443 my ($user_query, $query, $site, $depth) = _prepare_biblio_search($cgi, $ctx);
445 $self->get_staff_search_settings;
447 if (!$find_last and $ctx->{staff_saved_search_size}) {
448 my ($key, $list) = $self->staff_save_search($query);
450 $self->apache->headers_out->add(
451 "Set-Cookie" => $self->cgi->cookie(
452 -name => (ref $self)->COOKIE_ANON_CACHE,
454 -value => ($key || ''),
455 -expires => ($key ? undef : "-1h")
458 $ctx->{saved_searches} = $list;
461 # Limit and offset will stay here. Everything else should be part of
462 # the query string, not special args.
463 my $args = {'limit' => $limit, 'offset' => $offset};
465 return Apache2::Const::OK unless $query;
468 $args->{tag_circulated_records} = 1;
469 $args->{authtoken} = $self->editor->authtoken;
471 $args->{from_metarecord} = $metarecord if $metarecord;
473 # Stuff these into the TT context so that templates can use them in redrawing forms
474 $ctx->{user_query} = $user_query;
475 $ctx->{processed_search_query} = $query;
477 $query = "$_ $query" for @facets;
479 my $ltag = $is_meta ? '[mmr search]' : '[bre search]';
480 $logger->activity("EGWeb: $ltag $query");
482 # Fetch the global flag, defaults to "never too many".
483 unless (defined $max_concurrent_search) {
484 my $mcs = $e->retrieve_config_global_flag('opac.max_concurrent_search.ip');
485 $max_concurrent_search = ($mcs and $mcs->enabled eq 't') ? $mcs->value : 0;
488 if ($max_concurrent_search > 0) {
489 # Right up front, we will limit concurrent searches coming from the same client IP, if configured to do so.
490 $mc->get_cache('EGWEB-MAX-SEARCH-IP:'.$client_ip) || $mc->{memcache}->add('EGWEB-MAX-SEARCH-IP:'.$client_ip, 0);
491 my $concurrent_searches = $mc->{memcache}->incr('EGWEB-MAX-SEARCH-IP:'.$client_ip);
492 $logger->activity("Concurrent searches from client IP $client_ip: $concurrent_searches");
494 if ($concurrent_searches > $max_concurrent_search) {
495 $self->apache->log->warn("Too many concurrent searches from IP $client_ip");
496 $mc->{memcache}->decr('EGWEB-MAX-SEARCH-IP:'.$client_ip);
497 return 429; # Apache2::Const does not have a symbol for 429 too many requests
501 my $method = 'open-ils.search.biblio.multiclass.query';
503 $method .= '.staff' if $ctx->{is_staff};
504 $method =~ s/biblio/metabib/ if $is_meta;
506 my $ses = OpenSRF::AppSession->create('open-ils.search');
508 $self->timelog("Firing off the multiclass query");
509 my $req = $ses->request($method, $args, $query, 1, $ctx->{physical_loc});
510 $results = $req->gather(1);
511 $self->timelog("Returned from the multiclass query");
515 $logger->error("multiclass search error: $err");
516 $results = {count => 0, ids => []};
519 $mc->{memcache}->decr('EGWEB-MAX-SEARCH-IP:'.$client_ip) if ($max_concurrent_search);
521 # INFO: an OpenILS::Event only means "go away" for now.
522 if (defined $U->event_code($results)) {
523 $logger->activity("$method returned event: " . $U->event_code($results));
524 $self->apache->log->warn( "$method returned event: " . $U->event_code($results));
525 return 429; # Apache2::Const does not have a symbol for 429 too many requests
528 my $rec_ids = [map { $_->[0] } @{$results->{ids}}];
530 $ctx->{ids} = $rec_ids;
531 $ctx->{hit_count} = $results->{count};
532 $ctx->{superpage} = $results->{superpage};
533 $ctx->{superpage_size} = $results->{superpage_size};
534 $ctx->{pagable_limit} = $results->{core_limit};
535 $ctx->{query_struct} = $results->{global_summary}{query_struct};
536 $logger->debug('query struct: '. Dumper($ctx->{query_struct}));
537 $ctx->{canonicalized_query} = $results->{global_summary}{canonicalized_query};
538 $ctx->{search_summary} = $results->{global_summary};
541 # redirect to the record detail page for the last record in the results
542 my $rec_id = pop @$rec_ids;
543 $cgi->delete('find_last');
544 my $url = $cgi->url(-full => 1, -path => 1, -query => 1);
545 # TODO: metarecord => /rresults?metarecord=$mmr_id
546 $url =~ s|/results|/record/$rec_id|;
547 return $self->generic_redirect($url);
550 return Apache2::Const::OK if @$rec_ids == 0 or $internal;
552 $self->load_rresults_bookbag_item_notes($rec_ids) if $ctx->{bookbag};
554 my $fetch_recs = $rec_ids;
556 $self->timelog("Calling get_records_and_facets()");
557 my ($facets, @data) = $self->get_records_and_facets(
558 $fetch_recs, $results->{facet_key},
560 flesh => '{holdings_xml,mra,acp,acnp,acns,bmp,cbs}',
562 metarecord => $is_meta,
564 pref_lib => $ctx->{pref_ou},
567 $self->timelog("Returned from get_records_and_facets()");
569 if ($page == 0 and @$rec_ids == 1) {
572 # if the MR has a single constituent record, it will
573 # be in array position 4 of the result blob.
574 # otherwise, we don't want to redirect anyway.
575 my $bre_id = $results->{ids}->[0]->[4];
576 $stat = $self->check_1hit_redirect([$bre_id]) if $bre_id;
578 my $stat = $self->check_1hit_redirect($rec_ids);
580 return $stat if $stat;
583 # load temporary_list settings for user and ou:
584 $self->_load_lists_and_settings if ($ctx->{user});
587 # shove recs into context in search results order
588 for my $rec_id (@$rec_ids) {
589 my ($rec) = grep { $_->{$id_key} == $rec_id } @data;
590 push(@{$ctx->{records}}, $rec);
594 my $method = 'open-ils.search.biblio.multiclass.query';
595 $method .= '.staff' if $ctx->{is_staff};
596 my $ses = OpenSRF::AppSession->create('open-ils.search');
597 $self->timelog("Firing off the multiclass query: ". $rec_id);
598 $args->{from_metarecord} = $rec_id;
599 # offset of main search does not apply to the MR
601 my $save_offset = $args->{offset};
603 $mr_contents{$rec_id} = $ses->request($method, $args, $query, 1, $ctx->{physical_loc});
604 $args->{offset} = $save_offset;
607 $logger->error("multiclass search error: $err");
612 # above we fire all searches in parallel, now we collect the results
614 for my $rec_id (@$rec_ids) {
615 my ($rec) = grep { $_->{$id_key} == $rec_id } @data;
617 if ($mr_contents{$rec_id}) {
618 $meta_results = $mr_contents{$rec_id}->gather(1);
619 $self->timelog("Returned from the multiclass query: ". $rec_id);
621 $meta_results = {count => 0, ids => []};
623 my $meta_rec_ids = [map { $_->[0] } @{$meta_results->{ids}}];
624 $rec->{mr_constituent_count} = $meta_results->{count};
625 $rec->{mr_constituent_ids} = $meta_rec_ids;
629 my $course_module_opt_in = 0;
630 if ($ctx->{get_org_setting}->($self->_get_search_lib, "circ.course_materials_opt_in")) {
631 $course_module_opt_in = 1;
634 for my $rec (@{$ctx->{records}}) {
635 my ($res_rec) = grep { $_->[0] == $rec->{$id_key} } @{$results->{ids}};
636 $rec->{badges} = [split(',', $res_rec->[1])] if $res_rec->[1];
637 $rec->{popularity} = $res_rec->[2];
638 if ($course_module_opt_in) {
639 $rec->{course_materials} = $U->simplereq(
641 'open-ils.courses.course_materials.retrieve.atomic',
642 {record => $rec->{id}}
645 for my $material (@{$rec->{course_materials}}) {
646 $course_ids{$material->course} = 1;
649 $rec->{courses} = $U->simplereq(
651 'open-ils.courses.courses.retrieve',
656 # index 3 (5 for MR) in the per-record result array is a boolean which
657 # indicates whether the record in question is in the users
658 # accessible circ history list
659 my $index = $is_meta ? 5 : 3;
660 $rec->{user_circulated} = 1 if $res_rec->[$index];
665 $ctx->{search_facets} = $facets;
667 return Apache2::Const::OK;
670 # If the calling search results in 1 record and the client
671 # is configured to do so, redirect the search results to
672 # the record details page.
673 sub check_1hit_redirect {
674 my ($self, $rec_ids) = @_;
675 my $ctx = $self->ctx;
677 return undef unless $rec_ids and @$rec_ids == 1;
681 $self->timelog("Checking whether to jump to details on a single hit");
682 if ($ctx->{is_staff}) {
683 $sname = 'opac.staff.jump_to_details_on_single_hit';
684 $org = $ctx->{user}->ws_ou;
687 $sname = 'opac.patron.jump_to_details_on_single_hit';
688 $org = $self->_get_search_lib();
691 $self->timelog("Return from checking whether to jump to details on a single hit");
694 $self->ctx->{get_org_setting}->($org, $sname);
696 my $base_url = sprintf(
697 '%s://%s%s/record/%s',
699 $self->ctx->{hostname},
700 $self->ctx->{opac_root},
704 # If we get here from the same record detail page to which we
705 # now wish to redirect, do not perform the redirect. This
706 # approach seems to work well, with the rare exception of
707 # performing a new search directly from the detail page that
708 # happens to result in the same single hit. In this case, the
709 # user will be left on the search results page. This could be
710 # overcome w/ additional CGI, etc., but I'm not sure it's necessary.
711 if (my $referer = $ctx->{referer}) {
712 $referer =~ s/([^?]*).*/$1/g;
713 return undef if $base_url eq $referer;
716 return $self->generic_redirect($base_url . '?' . $self->cgi->query_string);
719 # Searching by barcode is a special search that does /not/ respect any other
720 # of the usual search parameters, not even the ones for sorting and paging!
721 sub item_barcode_shortcut {
724 $self->timelog("Searching for item_barcode");
725 my $method = "open-ils.search.multi_home.bib_ids.by_barcode";
726 if (my $search = create OpenSRF::AppSession("open-ils.search")) {
727 my $rec_ids = $search->request(
728 $method, $self->cgi->param("query")
731 $self->timelog("Finished searching for item_barcode");
733 if (ref $rec_ids ne 'ARRAY') {
735 if($U->event_equals($rec_ids, 'ASSET_COPY_NOT_FOUND')) {
739 if (defined $U->event_code($rec_ids)) {
740 $self->apache->log->warn(
741 "$method returned event: " . $U->event_code($rec_ids)
744 $self->apache->log->warn(
745 "$method returned something unexpected: $rec_ids"
748 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
752 $self->timelog("Calling get_records_and_facets() for item_barcode");
753 my ($facets, @data) = $self->get_records_and_facets(
754 $rec_ids, undef, {flesh => "{holdings_xml,mra,acnp,acns,bmp,cbs}"}
756 $self->timelog("Returned from calling get_records_and_facets() for item_barcode");
758 my $stat = $self->check_1hit_redirect($rec_ids);
759 return $stat if $stat;
761 $self->ctx->{records} = [@data];
762 $self->ctx->{search_facets} = {};
763 $self->ctx->{hit_count} = scalar @data;
764 $self->ctx->{page_size} = $self->ctx->{hit_count};
765 # load temporary_list settings for user and ou:
766 $self->_load_lists_and_settings if ($self->ctx->{user});
768 return Apache2::Const::OK;
770 $self->apache->log->warn("couldn't connect to open-ils.search");
771 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
775 # like item_barcode_search, this can't take all the usual search params, but
776 # this one will at least do site, limit and page
777 sub marc_expert_search {
778 my ($self, %args) = @_;
780 my @tags = $self->cgi->multi_param("tag");
781 my @subfields = $self->cgi->multi_param("subfield");
782 my @terms = $self->cgi->multi_param("term");
785 for (my $i = 0; $i < scalar @tags; $i++) {
786 next if ($tags[$i] eq "" || $terms[$i] eq "");
787 $subfields[$i] = '_' unless $subfields[$i];
789 "term" => $terms[$i],
790 "restrict" => [{"tag" => $tags[$i], "subfield" => $subfields[$i]}]
794 $logger->info("query for expert search: " . Dumper($query));
796 $self->timelog("Getting search parameters");
797 # loc, limit and offset
798 my $page = $self->cgi->param("page") || 0;
799 my $limit = $self->_get_search_limit;
800 $self->ctx->{search_ou} = $self->_get_search_lib();
801 $self->ctx->{pref_ou} = $self->_get_pref_lib();
802 my $offset = $page * $limit;
803 $self->timelog("Got search parameters");
805 $self->ctx->{records} = [];
806 $self->ctx->{search_facets} = {};
807 $self->ctx->{page_size} = $limit;
808 $self->ctx->{hit_count} = 0;
809 $self->ctx->{ids} = [];
810 $self->ctx->{search_page} = $page;
813 return Apache2::Const::OK if @$query == 0;
815 if ($args{internal}) {
816 $limit = $offset + $limit + 1;
820 $self->timelog("Searching for MARC expert");
821 my $method = 'open-ils.search.biblio.marc';
822 $method .= '.staff' if $self->ctx->{is_staff};
824 my $ses = OpenSRF::AppSession->create('open-ils.search');
826 #when a sort variable is passed in we need to add its value to the arguments
827 my $arghash = {searches => $query, org_unit => $self->ctx->{search_ou}};
828 if (defined $self->cgi->param("sort")) {
829 my ($sort, $sort_dir) = split /\./, $self->cgi->param('sort');
830 $arghash = {%$arghash, sort => "$sort"};
831 if (!defined $sort_dir) {
832 $arghash = {%$arghash, sort_dir => "ASC"};
836 #add the offset and limit to the argash, so we can go past 100 results
837 #if offset and limit are not in the args then they default to 0 and 100
838 #respectively in biblio_multi_search_full_rec, which limits the results to 100
840 $arghash = {%$arghash, offset => $offset, limit => $limit};
842 my $req = $ses->request(
847 my $resp = $req->recv($timeout);
848 my $results = $resp ? $resp->content : undef;
850 $self->timelog("Got our MARC expert results");
852 if (defined $U->event_code($results)) {
853 $self->apache->log->warn(
854 "open-ils.search.biblio.marc returned event: " .
855 $U->event_code($results)
857 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
860 $self->ctx->{ids} = [ grep { $_ } @{$results->{ids}} ];
861 $self->ctx->{hit_count} = $results->{count};
863 return Apache2::Const::OK if @{$self->ctx->{ids}} == 0 or $args{internal};
866 my $stat = $self->check_1hit_redirect($self->ctx->{ids});
867 return $stat if $stat;
870 $self->timelog("Calling get_records_and_facets() for MARC expert");
871 my ($facets, @data) = $self->get_records_and_facets(
872 $self->ctx->{ids}, undef, {
873 flesh => "{holdings_xml,mra,acnp,acns,cbs}",
874 pref_lib => $self->ctx->{pref_ou},
877 $self->timelog("Returned from calling get_records_and_facets() for MARC expert");
879 # load temporary_list settings for user and ou:
880 $self->_load_lists_and_settings if ($self->ctx->{user});
882 $self->ctx->{records} = [@data];
884 return Apache2::Const::OK;
887 sub call_number_browse_standalone {
890 if (my $cnfrag = $self->cgi->param("query")) {
892 '%s://%s%s/cnbrowse?cn=%s',
894 $self->ctx->{hostname},
895 $self->ctx->{opac_root},
896 $cnfrag # XXX some kind of escaping needed here?
898 $url .= '&locg=' . $self->_get_search_lib() if ($self->_get_search_lib());
899 return $self->generic_redirect($url);
901 return $self->generic_redirect; # return to search page
908 $self->prepare_browse_call_numbers();
910 return Apache2::Const::OK;
913 sub get_staff_search_settings {
916 unless ($self->ctx->{is_staff}) {
917 $self->ctx->{staff_saved_search_size} = 0;
921 $self->timelog("Getting staff search size");
922 my $sss_size = $self->ctx->{get_org_setting}->(
923 $self->ctx->{physical_loc} || $self->ctx->{aou_tree}->()->id,
924 "opac.staff_saved_search.size",
926 $self->timelog("Got staff search size");
928 # Sic: 0 is 0 (off), but undefined is 10.
929 $sss_size = 10 unless defined $sss_size;
931 $self->ctx->{staff_saved_search_size} = $sss_size;
934 sub staff_load_searches {
937 my $cache_key = $self->cgi->cookie((ref $self)->COOKIE_ANON_CACHE);
941 $self->timelog("Getting anon_cache value");
942 $list = $U->simplereq(
944 "open-ils.actor.anon_cache.get_value",
945 $cache_key, (ref $self)->ANON_CACHE_STAFF_SEARCH
947 $self->timelog("Got anon_cache value");
955 return ($cache_key, $list);
958 sub staff_save_search {
959 my ($self, $query) = @_;
961 my $sss_size = $self->ctx->{staff_saved_search_size};
962 return unless $sss_size > 0;
964 my ($cache_key, $list) = $self->staff_load_searches;
965 my %already = ( map { $_ => 1 } @$list );
967 unshift @$list, $query unless $already{$query};
969 splice @$list, $sss_size if scalar @$list > $sss_size;
971 $self->timelog("Setting anon_cache value");
972 $cache_key = $U->simplereq(
974 "open-ils.actor.anon_cache.set_value",
975 $cache_key, (ref $self)->ANON_CACHE_STAFF_SEARCH, $list
977 $self->timelog("Set anon_cache value");
979 return ($cache_key, $list);