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;
10 $Data::Dumper::Indent = 0;
11 my $U = 'OpenILS::Application::AppUtils';
13 sub _prepare_biblio_search_basics {
16 return $cgi->param('query') unless $cgi->param('qtype');
19 my @part_names = qw/qtype contains query bool/;
20 $parts{$_} = [ $cgi->param($_) ] for (@part_names);
23 for (my $i = 0; $i < scalar @{$parts{'qtype'}}; $i++) {
24 my ($qtype, $contains, $query, $bool) = map { $parts{$_}->[$i] } @part_names;
26 next unless $query =~ /\S/;
28 # Hack for journal title
34 # This stuff probably will need refined or rethought to better handle
35 # the weird things Real Users will surely type in.
36 $contains = "" unless defined $contains; # silence warning
37 if ($contains eq 'nocontains') {
39 $query = ('"' . $query . '"') if index $query, ' ';
40 $query = '-' . $query;
41 } elsif ($contains eq 'phrase') {
43 $query = ('"' . $query . '"') if index $query, ' ';
44 } elsif ($contains eq 'exact') {
45 $query =~ s/[\^\$]//g;
46 $query = '^' . $query . '$';
48 $query = "$qtype:$query" unless $qtype eq 'keyword' and $i == 0;
50 $bool = ($bool and $bool eq 'or') ? '||' : '&&';
51 $full_query = $full_query ? "($full_query $bool $query)" : $query;
57 sub _prepare_biblio_search {
60 my $query = _prepare_biblio_search_basics($cgi) || '';
62 $query .= ' ' . $ctx->{global_search_filter} if $ctx->{global_search_filter};
64 foreach ($cgi->param('modifier')) {
65 # The unless bit is to avoid stacking modifiers.
66 $query = ('#' . $_ . ' ' . $query) unless $query =~ qr/\#\Q$_/;
70 foreach (grep /^fi:/, $cgi->param) {
72 my $term = join(",", $cgi->param($_));
73 $query .= " $1($term)" if length $term;
76 # filter group entries. Entries from like filters are grouped into a single
77 # filter_group_entry() filter (ORed). Each collection is ANDed together.
78 # fg:foo_group=foo_entry_id
79 foreach (grep /^fg:/, $cgi->param) {
81 my $term = join(",", $cgi->param($_));
82 $query .= " filter_group_entry($term)" if length $term;
85 if ($cgi->param("bookbag")) {
86 $query .= " container(bre,bookbag," . int($cgi->param("bookbag")) . ")";
89 # Journal title hackery complete
90 if ($cgi->param("qtype") && $cgi->param("qtype") eq "jtitle") {
91 $query .= " bib_level(s)";
94 if ($cgi->param('pubdate') && $cgi->param('date1')) {
95 if ($cgi->param('pubdate') eq 'between') {
96 $query .= ' between(' . $cgi->param('date1');
97 $query .= ',' . $cgi->param('date2') if $cgi->param('date2');
99 } elsif ($cgi->param('pubdate') eq 'is') {
100 $query .= ' between(' . $cgi->param('date1') .
101 ',' . $cgi->param('date1') . ')'; # sic, date1 twice
103 $query .= ' ' . $cgi->param('pubdate') .
104 '(' . $cgi->param('date1') . ')';
108 # ---------------------------------------------------------------------
109 # Nothing below here constitutes a query by itself. If the query value
110 # is still empty up to this point, there is no query. abandon ship.
111 return () unless $query;
113 # sort is treated specially, even though it's actually a filter
114 if ($cgi->param('sort')) {
115 $query =~ s/sort\([^\)]*\)//g; # override existing sort(). no stacking.
116 my ($axis, $desc) = split /\./, $cgi->param('sort');
117 $query .= " sort($axis)";
118 if ($desc and not $query =~ /\#descending/) {
119 $query .= '#descending';
120 } elsif (not $desc) {
121 $query =~ s/\#descending//;
125 my (@naive_query_re, $site);
127 my $org = $ctx->{search_ou};
128 if (defined($org) and $org ne '' and ($org ne $ctx->{aou_tree}->()->id) and not $query =~ /site\(\S+\)/) {
129 my $thing = " site(" . $ctx->{get_aou}->($org)->shortname . ")";
132 push @naive_query_re, $thing;
135 my $pref_ou = $ctx->{pref_ou};
136 if (defined($pref_ou) and $pref_ou ne '' and $pref_ou != $org and ($pref_ou ne $ctx->{aou_tree}->()->id)) {
137 my $plib = $ctx->{get_aou}->($pref_ou)->shortname;
138 $query .= " pref_ou($plib)";
141 if (my $grp = $ctx->{copy_location_group}) {
142 $query .= " location_groups($grp)";
146 ($site) = ($query =~ /site\(([^\)]+)\)/);
147 $site ||= $ctx->{aou_tree}->()->shortname;
151 if ($query =~ /depth\(\d+\)/) {
153 # depth is encoded in the search query
154 ($depth) = ($query =~ /depth\((\d+)\)/);
158 if (defined $cgi->param('depth')) {
159 $depth = $cgi->param('depth');
161 # no depth specified. match the depth to the search org
162 my ($org) = grep { $_->shortname eq $site } @{$ctx->{aou_list}->()};
163 $depth = $org->ou_type->depth;
165 my $thing = " depth($depth)";
168 push @naive_query_re, $thing;
171 # This gives templates a way to take site() and depth() back out of
172 # query strings when they shouldn't be there (because they're controllable
173 # with other widgets).
174 $ctx->{naive_query_scrub} = sub {
176 $query =~ s/\Q$_\E// foreach (@naive_query_re);
180 $logger->info("tpac: site=$site, depth=$depth, query=$query");
182 return ($query, $site, $depth);
185 sub _get_search_limit {
188 # param takes precedence
189 my $limit = $self->cgi->param('limit');
190 return $limit if $limit;
192 if($self->editor->requestor) {
193 $self->timelog("Checking for opac.hits_per_page preference");
194 # See if the user has a hit count preference
195 my $lset = $self->editor->search_actor_user_setting({
196 usr => $self->editor->requestor->id,
197 name => 'opac.hits_per_page'
199 $self->timelog("Got opac.hits_per_page preference");
200 return OpenSRF::Utils::JSON->JSON2perl($lset->value) if $lset;
206 sub tag_circed_items {
208 my $e = $self->editor;
210 $self->timelog("Tag circed items?");
211 return 0 unless $e->requestor;
212 $self->timelog("Checking for opac.search.tag_circulated_items");
213 return 0 unless $self->ctx->{get_org_setting}->(
214 $e->requestor->home_ou,
215 'opac.search.tag_circulated_items');
217 # user has to be opted-in to circ history in some capacity
218 $self->timelog("Checking for history.circ.retention_*");
219 my $sets = $e->search_actor_user_setting({
220 usr => $e->requestor->id,
222 'history.circ.retention_age',
223 'history.circ.retention_start'
227 $self->timelog("Return from checking for history.circ.retention_*");
229 return 0 unless @$sets;
234 # This only loads the bookbag itself (in support of a record results page)
235 # if a "bookbag" CGI parameter is specified and if the bookbag is public
236 # or owned by the logged-in user (if any). Bookbag notes are fetched
237 # later if applicable.
238 sub load_rresults_bookbag {
241 my $bookbag_id = int($self->cgi->param("bookbag") || 0);
242 return if $bookbag_id < 1;
244 my %authz = $self->ctx->{"user"} ?
245 ("-or" => {"pub" => "t", "owner" => $self->ctx->{"user"}->id}) :
248 $self->timelog("Load results bookbag");
249 my $bbag = $self->editor->search_container_biblio_record_entry_bucket(
250 {"id" => $bookbag_id, "btype" => "bookbag", %authz}
252 $self->timelog("Got results bookbag");
255 $self->apache->log->warn(
256 "error from cstore retrieving bookbag $bookbag_id!"
258 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
260 $self->ctx->{"bookbag"} = shift @$bbag;
266 # assumes context has a bookbag we're already authorized to look at, and
267 # a list of rec_ids, reasonably sized (from paged search).
268 sub load_rresults_bookbag_item_notes {
269 my ($self, $rec_ids) = @_;
271 $self->timelog("Load results bookbag item notes");
272 my $items_with_notes =
273 $self->editor->search_container_biblio_record_entry_bucket_item([
274 {"target_biblio_record_entry" => $rec_ids,
275 "bucket" => $self->ctx->{"bookbag"}->id},
276 {"flesh" => 1, "flesh_fields" => {"cbrebi" => ["notes"]},
277 "order_by" => {"cbrebi" => ["id"]}}
279 $self->timelog("Got results bookbag item notes");
281 if (!$items_with_notes) {
282 $self->apache->log->warn("error from cstore retrieving cbrebi objects");
283 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
286 $self->ctx->{"bookbag_items_by_bre_id"} = +{
287 map { $_->target_biblio_record_entry => $_ } @$items_with_notes
296 # records : list of bre's and copy-count objects
300 my $internal = $args{internal};
301 my $cgi = $self->cgi;
302 my $ctx = $self->ctx;
303 my $e = $self->editor;
305 # find the last record in the set, then redirect
306 my $find_last = $cgi->param('find_last');
308 $self->timelog("Loading results");
309 # load bookbag metadata, if requested.
310 if (my $bbag_err = $self->load_rresults_bookbag) {
314 $ctx->{page} = 'rresult' unless $internal;
316 $ctx->{records} = [];
317 $ctx->{search_facets} = {};
318 $ctx->{hit_count} = 0;
320 # Special alternative searches here. This could all stand to be cleaner.
321 if ($cgi->param("_special")) {
322 $self->timelog("Calling MARC expert search");
323 return $self->marc_expert_search(%args) if scalar($cgi->param("tag"));
324 $self->timelog("Calling item barcode search");
325 return $self->item_barcode_shortcut if (
326 $cgi->param("qtype") and ($cgi->param("qtype") eq "item_barcode")
328 $self->timelog("Calling call number browse");
329 return $self->call_number_browse_standalone if (
330 $cgi->param("qtype") and ($cgi->param("qtype") eq "cnbrowse")
334 $self->timelog("Getting search parameters");
335 my $page = $cgi->param('page') || 0;
336 my @facets = $cgi->param('facet');
337 my $limit = $self->_get_search_limit;
338 $ctx->{search_ou} = $self->_get_search_lib();
339 $ctx->{pref_ou} = $self->_get_pref_lib() || $ctx->{search_ou};
340 my $offset = $page * $limit;
341 my $metarecord = $cgi->param('metarecord');
343 my $tag_circs = $self->tag_circed_items;
344 $self->timelog("Got search parameters");
346 $ctx->{page_size} = $limit;
347 $ctx->{search_page} = $page;
349 # fetch this page plus the first hit from the next page
351 $limit = $offset + $limit + 1;
355 my ($query, $site, $depth) = _prepare_biblio_search($cgi, $ctx);
357 $self->get_staff_search_settings;
359 if (!$find_last and $ctx->{staff_saved_search_size}) {
360 my ($key, $list) = $self->staff_save_search($query);
362 $self->apache->headers_out->add(
363 "Set-Cookie" => $self->cgi->cookie(
364 -name => (ref $self)->COOKIE_ANON_CACHE,
366 -value => ($key || ''),
367 -expires => ($key ? undef : "-1h")
370 $ctx->{saved_searches} = $list;
374 if ($metarecord and !$internal) {
376 # TODO: other limits, like SVF/format, etc.
377 $self->timelog("Getting metarecords to records");
378 $results = $U->simplereq(
380 'open-ils.search.biblio.metarecord_to_records',
381 $metarecord, {org => $ctx->{search_ou}, depth => $depth}
383 $self->timelog("Got metarecords to records");
385 # force the metarecord result blob to match the format of regular search results
386 $results->{ids} = [map { [$_] } @{$results->{ids}}];
391 return Apache2::Const::OK if $internal;
392 return $self->generic_redirect;
395 # Limit and offset will stay here. Everything else should be part of
396 # the query string, not special args.
397 my $args = {'limit' => $limit, 'offset' => $offset};
400 $args->{tag_circulated_records} = 1;
401 $args->{authtoken} = $self->editor->authtoken;
404 # Stuff these into the TT context so that templates can use them in redrawing forms
405 $ctx->{processed_search_query} = $query;
407 $query .= " $_" for @facets;
409 $logger->activity("EGWeb: [search] $query");
413 my $method = 'open-ils.search.biblio.multiclass.query';
414 $method .= '.staff' if $ctx->{is_staff};
416 $self->timelog("Firing off the multiclass query");
417 $results = $U->simplereq('open-ils.search', $method, $args, $query, 1);
418 $self->timelog("Returned from the multiclass query");
422 $logger->error("multiclass search error: $err");
423 $results = {count => 0, ids => []};
427 my $rec_ids = [map { $_->[0] } @{$results->{ids}}];
429 $ctx->{ids} = $rec_ids;
430 $ctx->{hit_count} = $results->{count};
431 $ctx->{parsed_query} = $results->{parsed_query};
434 # redirect to the record detail page for the last record in the results
435 my $rec_id = pop @$rec_ids;
436 $cgi->delete('find_last');
437 my $url = $cgi->url(-full => 1, -path => 1, -query => 1);
438 $url =~ s|/results|/record/$rec_id|;
439 return $self->generic_redirect($url);
442 return Apache2::Const::OK if @$rec_ids == 0 or $internal;
444 $self->load_rresults_bookbag_item_notes($rec_ids) if $ctx->{bookbag};
446 $self->timelog("Calling get_records_and_facets()");
447 my ($facets, @data) = $self->get_records_and_facets(
448 $rec_ids, $results->{facet_key},
450 flesh => '{holdings_xml,mra,acp,acnp,acns,bmp}',
453 pref_lib => $ctx->{pref_ou},
456 $self->timelog("Returned from get_records_and_facets()");
459 my $stat = $self->check_1hit_redirect($rec_ids);
460 return $stat if $stat;
463 # load temporary_list settings for user and ou:
464 $self->_load_lists_and_settings if ($ctx->{user});
466 # shove recs into context in search results order
467 for my $rec_id (@$rec_ids) {
470 grep { $_->{id} == $rec_id } @data
475 for my $rec (@{$ctx->{records}}) {
476 my ($res_rec) = grep { $_->[0] == $rec->{id} } @{$results->{ids}};
477 # index 1 in the per-record result array is a boolean which
478 # indicates whether the record in question is in the users
479 # accessible circ history list
480 $rec->{user_circulated} = 1 if $res_rec->[1];
484 $ctx->{search_facets} = $facets;
486 return Apache2::Const::OK;
489 # If the calling search results in 1 record and the client
490 # is configured to do so, redirect the search results to
491 # the record details page.
492 sub check_1hit_redirect {
493 my ($self, $rec_ids) = @_;
494 my $ctx = $self->ctx;
496 return undef unless $rec_ids and @$rec_ids == 1;
500 $self->timelog("Checking whether to jump to details on a single hit");
501 if ($ctx->{is_staff}) {
502 $sname = 'opac.staff.jump_to_details_on_single_hit';
503 $org = $ctx->{user}->ws_ou;
506 $sname = 'opac.patron.jump_to_details_on_single_hit';
507 $org = $self->_get_search_lib();
510 $self->timelog("Return from checking whether to jump to details on a single hit");
513 $self->ctx->{get_org_setting}->($org, $sname);
515 my $base_url = sprintf(
516 '%s://%s%s/record/%s',
518 $self->ctx->{hostname},
519 $self->ctx->{opac_root},
523 # If we get here from the same record detail page to which we
524 # now wish to redirect, do not perform the redirect. This
525 # approach seems to work well, with the rare exception of
526 # performing a new search directly from the detail page that
527 # happens to result in the same single hit. In this case, the
528 # user will be left on the search results page. This could be
529 # overcome w/ additional CGI, etc., but I'm not sure it's necessary.
530 if (my $referer = $ctx->{referer}) {
531 $referer =~ s/([^?]*).*/$1/g;
532 return undef if $base_url eq $referer;
535 return $self->generic_redirect($base_url . '?' . $self->cgi->query_string);
538 # Searching by barcode is a special search that does /not/ respect any other
539 # of the usual search parameters, not even the ones for sorting and paging!
540 sub item_barcode_shortcut {
543 $self->timelog("Searching for item_barcode");
544 my $method = "open-ils.search.multi_home.bib_ids.by_barcode";
545 if (my $search = create OpenSRF::AppSession("open-ils.search")) {
546 my $rec_ids = $search->request(
547 $method, $self->cgi->param("query")
550 $self->timelog("Finished searching for item_barcode");
552 if (ref $rec_ids ne 'ARRAY') {
554 if($U->event_equals($rec_ids, 'ASSET_COPY_NOT_FOUND')) {
558 if (defined $U->event_code($rec_ids)) {
559 $self->apache->log->warn(
560 "$method returned event: " . $U->event_code($rec_ids)
563 $self->apache->log->warn(
564 "$method returned something unexpected: $rec_ids"
567 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
571 $self->timelog("Calling get_records_and_facets() for item_barcode");
572 my ($facets, @data) = $self->get_records_and_facets(
573 $rec_ids, undef, {flesh => "{holdings_xml,mra,acnp,acns,bmp}"}
575 $self->timelog("Returned from calling get_records_and_facets() for item_barcode");
577 $self->ctx->{records} = [@data];
578 $self->ctx->{search_facets} = {};
579 $self->ctx->{hit_count} = scalar @data;
580 $self->ctx->{page_size} = $self->ctx->{hit_count};
581 # load temporary_list settings for user and ou:
582 $self->_load_lists_and_settings if ($self->ctx->{user});
584 return Apache2::Const::OK;
586 $self->apache->log->warn("couldn't connect to open-ils.search");
587 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
591 # like item_barcode_search, this can't take all the usual search params, but
592 # this one will at least do site, limit and page
593 sub marc_expert_search {
594 my ($self, %args) = @_;
596 my @tags = $self->cgi->param("tag");
597 my @subfields = $self->cgi->param("subfield");
598 my @terms = $self->cgi->param("term");
601 for (my $i = 0; $i < scalar @tags; $i++) {
602 next if ($tags[$i] eq "" || $terms[$i] eq "");
603 $subfields[$i] = '_' unless $subfields[$i];
605 "term" => $terms[$i],
606 "restrict" => [{"tag" => $tags[$i], "subfield" => $subfields[$i]}]
610 $logger->info("query for expert search: " . Dumper($query));
612 $self->timelog("Getting search parameters");
613 # loc, limit and offset
614 my $page = $self->cgi->param("page") || 0;
615 my $limit = $self->_get_search_limit;
616 $self->ctx->{search_ou} = $self->_get_search_lib();
617 $self->ctx->{pref_ou} = $self->_get_pref_lib();
618 my $offset = $page * $limit;
619 $self->timelog("Got search parameters");
621 $self->ctx->{records} = [];
622 $self->ctx->{search_facets} = {};
623 $self->ctx->{page_size} = $limit;
624 $self->ctx->{hit_count} = 0;
625 $self->ctx->{ids} = [];
626 $self->ctx->{search_page} = $page;
629 return Apache2::Const::OK if @$query == 0;
631 if ($args{internal}) {
632 $limit = $offset + $limit + 1;
636 $self->timelog("Searching for MARC expert");
637 my $method = 'open-ils.search.biblio.marc';
638 $method .= '.staff' if $self->ctx->{is_staff};
640 my $ses = OpenSRF::AppSession->create('open-ils.search');
641 my $req = $ses->request(
643 {searches => $query, org_unit => $self->ctx->{search_ou}},
644 $limit, $offset, $timeout);
646 my $resp = $req->recv($timeout);
647 my $results = $resp ? $resp->content : undef;
649 $self->timelog("Got our MARC expert results");
651 if (defined $U->event_code($results)) {
652 $self->apache->log->warn(
653 "open-ils.search.biblio.marc returned event: " .
654 $U->event_code($results)
656 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
659 $self->ctx->{ids} = [ grep { $_ } @{$results->{ids}} ];
660 $self->ctx->{hit_count} = $results->{count};
662 return Apache2::Const::OK if @{$self->ctx->{ids}} == 0 or $args{internal};
665 my $stat = $self->check_1hit_redirect($self->ctx->{ids});
666 return $stat if $stat;
669 $self->timelog("Calling get_records_and_facets() for MARC expert");
670 my ($facets, @data) = $self->get_records_and_facets(
671 $self->ctx->{ids}, undef, {
672 flesh => "{holdings_xml,mra,acnp,acns}",
673 pref_lib => $self->ctx->{pref_ou},
676 $self->timelog("Returned from calling get_records_and_facets() for MARC expert");
678 # load temporary_list settings for user and ou:
679 $self->_load_lists_and_settings if ($self->ctx->{user});
681 $self->ctx->{records} = [@data];
683 return Apache2::Const::OK;
686 sub call_number_browse_standalone {
689 if (my $cnfrag = $self->cgi->param("query")) {
691 '%s://%s%s/cnbrowse?cn=%s',
693 $self->ctx->{hostname},
694 $self->ctx->{opac_root},
695 $cnfrag # XXX some kind of escaping needed here?
697 $url .= '&locg=' . $self->_get_search_lib() if ($self->_get_search_lib());
698 return $self->generic_redirect($url);
700 return $self->generic_redirect; # return to search page
707 $self->prepare_browse_call_numbers();
709 return Apache2::Const::OK;
712 sub get_staff_search_settings {
715 unless ($self->ctx->{is_staff}) {
716 $self->ctx->{staff_saved_search_size} = 0;
720 $self->timelog("Getting staff search size");
721 my $sss_size = $self->ctx->{get_org_setting}->(
722 $self->ctx->{physical_loc} || $self->ctx->{aou_tree}->()->id,
723 "opac.staff_saved_search.size",
725 $self->timelog("Got staff search size");
727 # Sic: 0 is 0 (off), but undefined is 10.
728 $sss_size = 10 unless defined $sss_size;
730 $self->ctx->{staff_saved_search_size} = $sss_size;
733 sub staff_load_searches {
736 my $cache_key = $self->cgi->cookie((ref $self)->COOKIE_ANON_CACHE);
740 $self->timelog("Getting anon_cache value");
741 $list = $U->simplereq(
743 "open-ils.actor.anon_cache.get_value",
744 $cache_key, (ref $self)->ANON_CACHE_STAFF_SEARCH
746 $self->timelog("Got anon_cache value");
754 return ($cache_key, $list);
757 sub staff_save_search {
758 my ($self, $query) = @_;
760 my $sss_size = $self->ctx->{staff_saved_search_size};
761 return unless $sss_size > 0;
763 my ($cache_key, $list) = $self->staff_load_searches;
764 my %already = ( map { $_ => 1 } @$list );
766 unshift @$list, $query unless $already{$query};
768 splice @$list, $sss_size if scalar @$list > $sss_size;
770 $self->timelog("Setting anon_cache value");
771 $cache_key = $U->simplereq(
773 "open-ils.actor.anon_cache.set_value",
774 $cache_key, (ref $self)->ANON_CACHE_STAFF_SEARCH, $list
776 $self->timelog("Set anon_cache value");
778 return ($cache_key, $list);