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};
66 foreach (grep /^fi:/, $cgi->param) {
68 my $term = join(",", $cgi->param($_));
69 $query .= " $1($term)" if length $term;
72 # filter group entries. Entries from like filters are grouped into a single
73 # filter_group_entry() filter (ORed). Each collection is ANDed together.
74 # fg:foo_group=foo_entry_id
75 foreach (grep /^fg:/, $cgi->param) {
77 my $term = join(",", $cgi->param($_));
78 $query .= " filter_group_entry($term)" if length $term;
81 if ($cgi->param("bookbag")) {
82 $query .= " container(bre,bookbag," . int($cgi->param("bookbag")) . ")";
85 # Journal title hackery complete
86 if ($cgi->param("qtype") && $cgi->param("qtype") eq "jtitle") {
87 $query .= " bib_level(s)";
90 if ($cgi->param('pubdate') && $cgi->param('date1')) {
91 if ($cgi->param('pubdate') eq 'between') {
92 $query .= ' between(' . $cgi->param('date1');
93 $query .= ',' . $cgi->param('date2') if $cgi->param('date2');
95 } elsif ($cgi->param('pubdate') eq 'is') {
96 $query .= ' between(' . $cgi->param('date1') .
97 ',' . $cgi->param('date1') . ')'; # sic, date1 twice
99 $query .= ' ' . $cgi->param('pubdate') .
100 '(' . $cgi->param('date1') . ')';
104 # ---------------------------------------------------------------------
105 # Nothing below here constitutes a query by itself. If the query value
106 # is still empty up to this point, there is no query. abandon ship.
107 return () unless $query;
109 # sort is treated specially, even though it's actually a filter
110 if ($cgi->param('sort')) {
111 $query =~ s/sort\([^\)]*\)//g; # override existing sort(). no stacking.
112 my ($axis, $desc) = split /\./, $cgi->param('sort');
113 $query .= " sort($axis)";
114 if ($desc and not $query =~ /\#descending/) {
115 $query .= '#descending';
116 } elsif (not $desc) {
117 $query =~ s/\#descending//;
121 my (@naive_query_re, $site);
123 my $org = $ctx->{search_ou};
124 if (defined($org) and $org ne '' and ($org ne $ctx->{aou_tree}->()->id) and not $query =~ /site\(\S+\)/) {
125 my $thing = " site(" . $ctx->{get_aou}->($org)->shortname . ")";
128 push @naive_query_re, $thing;
131 my $pref_ou = $ctx->{pref_ou};
132 if (defined($pref_ou) and $pref_ou ne '' and $pref_ou != $org and ($pref_ou ne $ctx->{aou_tree}->()->id)) {
133 my $plib = $ctx->{get_aou}->($pref_ou)->shortname;
134 $query .= " pref_ou($plib)";
137 if (my $grp = $ctx->{copy_location_group}) {
138 $query .= " location_groups($grp)";
142 ($site) = ($query =~ /site\(([^\)]+)\)/);
143 $site ||= $ctx->{aou_tree}->()->shortname;
147 if ($query =~ /depth\(\d+\)/) {
149 # depth is encoded in the search query
150 ($depth) = ($query =~ /depth\((\d+)\)/);
154 if (defined $cgi->param('depth')) {
155 $depth = $cgi->param('depth');
157 # no depth specified. match the depth to the search org
158 my ($org) = grep { $_->shortname eq $site } @{$ctx->{aou_list}->()};
159 $depth = $org->ou_type->depth;
161 my $thing = " depth($depth)";
164 push @naive_query_re, $thing;
167 foreach ($cgi->param('modifier')) {
168 # The unless bit is to avoid stacking modifiers.
169 $query .= " #$_" unless $query =~ qr/\#\Q$_/;
172 # This gives templates a way to take site() and depth() back out of
173 # query strings when they shouldn't be there (because they're controllable
174 # with other widgets).
175 $ctx->{naive_query_scrub} = sub {
177 $query =~ s/\Q$_\E// foreach (@naive_query_re);
181 $logger->info("tpac: site=$site, depth=$depth, query=$query");
183 return ($query, $site, $depth);
186 sub _get_search_limit {
189 # param takes precedence
190 my $limit = $self->cgi->param('limit');
191 return $limit if $limit;
193 if($self->editor->requestor) {
194 $self->timelog("Checking for opac.hits_per_page preference");
195 # See if the user has a hit count preference
196 my $lset = $self->editor->search_actor_user_setting({
197 usr => $self->editor->requestor->id,
198 name => 'opac.hits_per_page'
200 $self->timelog("Got opac.hits_per_page preference");
201 return OpenSRF::Utils::JSON->JSON2perl($lset->value) if $lset;
207 sub tag_circed_items {
209 my $e = $self->editor;
211 $self->timelog("Tag circed items?");
212 return 0 unless $e->requestor;
213 $self->timelog("Checking for opac.search.tag_circulated_items");
214 return 0 unless $self->ctx->{get_org_setting}->(
215 $e->requestor->home_ou,
216 'opac.search.tag_circulated_items');
218 # user has to be opted-in to circ history in some capacity
219 $self->timelog("Checking for history.circ.retention_*");
220 my $sets = $e->search_actor_user_setting({
221 usr => $e->requestor->id,
223 'history.circ.retention_age',
224 'history.circ.retention_start'
228 $self->timelog("Return from checking for history.circ.retention_*");
230 return 0 unless @$sets;
235 # This only loads the bookbag itself (in support of a record results page)
236 # if a "bookbag" CGI parameter is specified and if the bookbag is public
237 # or owned by the logged-in user (if any). Bookbag notes are fetched
238 # later if applicable.
239 sub load_rresults_bookbag {
242 my $bookbag_id = int($self->cgi->param("bookbag") || 0);
243 return if $bookbag_id < 1;
245 my %authz = $self->ctx->{"user"} ?
246 ("-or" => {"pub" => "t", "owner" => $self->ctx->{"user"}->id}) :
249 $self->timelog("Load results bookbag");
250 my $bbag = $self->editor->search_container_biblio_record_entry_bucket(
251 {"id" => $bookbag_id, "btype" => "bookbag", %authz}
253 $self->timelog("Got results bookbag");
256 $self->apache->log->warn(
257 "error from cstore retrieving bookbag $bookbag_id!"
259 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
261 $self->ctx->{"bookbag"} = shift @$bbag;
267 # assumes context has a bookbag we're already authorized to look at, and
268 # a list of rec_ids, reasonably sized (from paged search).
269 sub load_rresults_bookbag_item_notes {
270 my ($self, $rec_ids) = @_;
272 $self->timelog("Load results bookbag item notes");
273 my $items_with_notes =
274 $self->editor->search_container_biblio_record_entry_bucket_item([
275 {"target_biblio_record_entry" => $rec_ids,
276 "bucket" => $self->ctx->{"bookbag"}->id},
277 {"flesh" => 1, "flesh_fields" => {"cbrebi" => ["notes"]},
278 "order_by" => {"cbrebi" => ["id"]}}
280 $self->timelog("Got results bookbag item notes");
282 if (!$items_with_notes) {
283 $self->apache->log->warn("error from cstore retrieving cbrebi objects");
284 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
287 $self->ctx->{"bookbag_items_by_bre_id"} = +{
288 map { $_->target_biblio_record_entry => $_ } @$items_with_notes
297 # records : list of bre's and copy-count objects
301 my $internal = $args{internal};
302 my $cgi = $self->cgi;
303 my $ctx = $self->ctx;
304 my $e = $self->editor;
306 # find the last record in the set, then redirect
307 my $find_last = $cgi->param('find_last');
309 $self->timelog("Loading results");
310 # load bookbag metadata, if requested.
311 if (my $bbag_err = $self->load_rresults_bookbag) {
315 $ctx->{page} = 'rresult' unless $internal;
317 $ctx->{records} = [];
318 $ctx->{search_facets} = {};
319 $ctx->{hit_count} = 0;
321 # Special alternative searches here. This could all stand to be cleaner.
322 if ($cgi->param("_special")) {
323 $self->timelog("Calling MARC expert search");
324 return $self->marc_expert_search(%args) if scalar($cgi->param("tag"));
325 $self->timelog("Calling item barcode search");
326 return $self->item_barcode_shortcut if (
327 $cgi->param("qtype") and ($cgi->param("qtype") eq "item_barcode") and not $internal
329 $self->timelog("Calling call number browse");
330 return $self->call_number_browse_standalone if (
331 $cgi->param("qtype") and ($cgi->param("qtype") eq "cnbrowse")
335 $self->timelog("Getting search parameters");
336 my $page = $cgi->param('page') || 0;
337 my @facets = $cgi->param('facet');
338 my $limit = $self->_get_search_limit;
339 $ctx->{search_ou} = $self->_get_search_lib();
340 $ctx->{pref_ou} = $self->_get_pref_lib() || $ctx->{search_ou};
341 my $offset = $page * $limit;
342 my $metarecord = $cgi->param('metarecord');
344 my $tag_circs = $self->tag_circed_items;
345 $self->timelog("Got search parameters");
347 $ctx->{page_size} = $limit;
348 $ctx->{search_page} = $page;
350 # fetch this page plus the first hit from the next page
352 $limit = $offset + $limit + 1;
356 my ($query, $site, $depth) = _prepare_biblio_search($cgi, $ctx);
358 $self->get_staff_search_settings;
360 if (!$find_last and $ctx->{staff_saved_search_size}) {
361 my ($key, $list) = $self->staff_save_search($query);
363 $self->apache->headers_out->add(
364 "Set-Cookie" => $self->cgi->cookie(
365 -name => (ref $self)->COOKIE_ANON_CACHE,
367 -value => ($key || ''),
368 -expires => ($key ? undef : "-1h")
371 $ctx->{saved_searches} = $list;
375 if ($metarecord and !$internal) {
377 # TODO: other limits, like SVF/format, etc.
378 $self->timelog("Getting metarecords to records");
379 $results = $U->simplereq(
381 'open-ils.search.biblio.metarecord_to_records',
382 $metarecord, {org => $ctx->{search_ou}, depth => $depth}
384 $self->timelog("Got metarecords to records");
386 # force the metarecord result blob to match the format of regular search results
387 $results->{ids} = [map { [$_] } @{$results->{ids}}];
392 return Apache2::Const::OK if $internal;
393 return $self->generic_redirect;
396 # Limit and offset will stay here. Everything else should be part of
397 # the query string, not special args.
398 my $args = {'limit' => $limit, 'offset' => $offset};
401 $args->{tag_circulated_records} = 1;
402 $args->{authtoken} = $self->editor->authtoken;
405 # Stuff these into the TT context so that templates can use them in redrawing forms
406 $ctx->{processed_search_query} = $query;
408 $query .= " $_" for @facets;
410 $logger->activity("EGWeb: [search] $query");
414 my $method = 'open-ils.search.biblio.multiclass.query';
415 $method .= '.staff' if $ctx->{is_staff};
417 my $ses = OpenSRF::AppSession->create('open-ils.search');
418 $ses->session_locale($OpenILS::Utils::CStoreEditor::default_locale); # set in EGWeb
420 $self->timelog("Firing off the multiclass query");
421 my $req = $ses->request($method, $args, $query, 1);
422 $results = $req->gather(1);
423 $self->timelog("Returned from the multiclass query");
427 $logger->error("multiclass search error: $err");
428 $results = {count => 0, ids => []};
432 my $rec_ids = [map { $_->[0] } @{$results->{ids}}];
434 $ctx->{ids} = $rec_ids;
435 $ctx->{hit_count} = $results->{count};
436 $ctx->{parsed_query} = $results->{parsed_query};
439 # redirect to the record detail page for the last record in the results
440 my $rec_id = pop @$rec_ids;
441 $cgi->delete('find_last');
442 my $url = $cgi->url(-full => 1, -path => 1, -query => 1);
443 $url =~ s|/results|/record/$rec_id|;
444 return $self->generic_redirect($url);
447 return Apache2::Const::OK if @$rec_ids == 0 or $internal;
449 $self->load_rresults_bookbag_item_notes($rec_ids) if $ctx->{bookbag};
451 $self->timelog("Calling get_records_and_facets()");
452 my ($facets, @data) = $self->get_records_and_facets(
453 $rec_ids, $results->{facet_key},
455 flesh => '{holdings_xml,mra,acp,acnp,acns,bmp}',
458 pref_lib => $ctx->{pref_ou},
461 $self->timelog("Returned from get_records_and_facets()");
464 my $stat = $self->check_1hit_redirect($rec_ids);
465 return $stat if $stat;
468 # load temporary_list settings for user and ou:
469 $self->_load_lists_and_settings if ($ctx->{user});
471 # shove recs into context in search results order
472 for my $rec_id (@$rec_ids) {
475 grep { $_->{id} == $rec_id } @data
480 for my $rec (@{$ctx->{records}}) {
481 my ($res_rec) = grep { $_->[0] == $rec->{id} } @{$results->{ids}};
482 # index 1 in the per-record result array is a boolean which
483 # indicates whether the record in question is in the users
484 # accessible circ history list
485 $rec->{user_circulated} = 1 if $res_rec->[1];
489 $ctx->{search_facets} = $facets;
491 return Apache2::Const::OK;
494 # If the calling search results in 1 record and the client
495 # is configured to do so, redirect the search results to
496 # the record details page.
497 sub check_1hit_redirect {
498 my ($self, $rec_ids) = @_;
499 my $ctx = $self->ctx;
501 return undef unless $rec_ids and @$rec_ids == 1;
505 $self->timelog("Checking whether to jump to details on a single hit");
506 if ($ctx->{is_staff}) {
507 $sname = 'opac.staff.jump_to_details_on_single_hit';
508 $org = $ctx->{user}->ws_ou;
511 $sname = 'opac.patron.jump_to_details_on_single_hit';
512 $org = $self->_get_search_lib();
515 $self->timelog("Return from checking whether to jump to details on a single hit");
518 $self->ctx->{get_org_setting}->($org, $sname);
520 my $base_url = sprintf(
521 '%s://%s%s/record/%s',
523 $self->ctx->{hostname},
524 $self->ctx->{opac_root},
528 # If we get here from the same record detail page to which we
529 # now wish to redirect, do not perform the redirect. This
530 # approach seems to work well, with the rare exception of
531 # performing a new search directly from the detail page that
532 # happens to result in the same single hit. In this case, the
533 # user will be left on the search results page. This could be
534 # overcome w/ additional CGI, etc., but I'm not sure it's necessary.
535 if (my $referer = $ctx->{referer}) {
536 $referer =~ s/([^?]*).*/$1/g;
537 return undef if $base_url eq $referer;
540 return $self->generic_redirect($base_url . '?' . $self->cgi->query_string);
543 # Searching by barcode is a special search that does /not/ respect any other
544 # of the usual search parameters, not even the ones for sorting and paging!
545 sub item_barcode_shortcut {
548 $self->timelog("Searching for item_barcode");
549 my $method = "open-ils.search.multi_home.bib_ids.by_barcode";
550 if (my $search = create OpenSRF::AppSession("open-ils.search")) {
551 my $rec_ids = $search->request(
552 $method, $self->cgi->param("query")
555 $self->timelog("Finished searching for item_barcode");
557 if (ref $rec_ids ne 'ARRAY') {
559 if($U->event_equals($rec_ids, 'ASSET_COPY_NOT_FOUND')) {
563 if (defined $U->event_code($rec_ids)) {
564 $self->apache->log->warn(
565 "$method returned event: " . $U->event_code($rec_ids)
568 $self->apache->log->warn(
569 "$method returned something unexpected: $rec_ids"
572 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
576 $self->timelog("Calling get_records_and_facets() for item_barcode");
577 my ($facets, @data) = $self->get_records_and_facets(
578 $rec_ids, undef, {flesh => "{holdings_xml,mra,acnp,acns,bmp}"}
580 $self->timelog("Returned from calling get_records_and_facets() for item_barcode");
582 my $stat = $self->check_1hit_redirect($rec_ids);
583 return $stat if $stat;
585 $self->ctx->{records} = [@data];
586 $self->ctx->{search_facets} = {};
587 $self->ctx->{hit_count} = scalar @data;
588 $self->ctx->{page_size} = $self->ctx->{hit_count};
589 # load temporary_list settings for user and ou:
590 $self->_load_lists_and_settings if ($self->ctx->{user});
592 return Apache2::Const::OK;
594 $self->apache->log->warn("couldn't connect to open-ils.search");
595 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
599 # like item_barcode_search, this can't take all the usual search params, but
600 # this one will at least do site, limit and page
601 sub marc_expert_search {
602 my ($self, %args) = @_;
604 my @tags = $self->cgi->param("tag");
605 my @subfields = $self->cgi->param("subfield");
606 my @terms = $self->cgi->param("term");
609 for (my $i = 0; $i < scalar @tags; $i++) {
610 next if ($tags[$i] eq "" || $terms[$i] eq "");
611 $subfields[$i] = '_' unless $subfields[$i];
613 "term" => $terms[$i],
614 "restrict" => [{"tag" => $tags[$i], "subfield" => $subfields[$i]}]
618 $logger->info("query for expert search: " . Dumper($query));
620 $self->timelog("Getting search parameters");
621 # loc, limit and offset
622 my $page = $self->cgi->param("page") || 0;
623 my $limit = $self->_get_search_limit;
624 $self->ctx->{search_ou} = $self->_get_search_lib();
625 $self->ctx->{pref_ou} = $self->_get_pref_lib();
626 my $offset = $page * $limit;
627 $self->timelog("Got search parameters");
629 $self->ctx->{records} = [];
630 $self->ctx->{search_facets} = {};
631 $self->ctx->{page_size} = $limit;
632 $self->ctx->{hit_count} = 0;
633 $self->ctx->{ids} = [];
634 $self->ctx->{search_page} = $page;
637 return Apache2::Const::OK if @$query == 0;
639 if ($args{internal}) {
640 $limit = $offset + $limit + 1;
644 $self->timelog("Searching for MARC expert");
645 my $method = 'open-ils.search.biblio.marc';
646 $method .= '.staff' if $self->ctx->{is_staff};
648 my $ses = OpenSRF::AppSession->create('open-ils.search');
649 my $req = $ses->request(
651 {searches => $query, org_unit => $self->ctx->{search_ou}},
652 $limit, $offset, $timeout);
654 my $resp = $req->recv($timeout);
655 my $results = $resp ? $resp->content : undef;
657 $self->timelog("Got our MARC expert results");
659 if (defined $U->event_code($results)) {
660 $self->apache->log->warn(
661 "open-ils.search.biblio.marc returned event: " .
662 $U->event_code($results)
664 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
667 $self->ctx->{ids} = [ grep { $_ } @{$results->{ids}} ];
668 $self->ctx->{hit_count} = $results->{count};
670 return Apache2::Const::OK if @{$self->ctx->{ids}} == 0 or $args{internal};
673 my $stat = $self->check_1hit_redirect($self->ctx->{ids});
674 return $stat if $stat;
677 $self->timelog("Calling get_records_and_facets() for MARC expert");
678 my ($facets, @data) = $self->get_records_and_facets(
679 $self->ctx->{ids}, undef, {
680 flesh => "{holdings_xml,mra,acnp,acns}",
681 pref_lib => $self->ctx->{pref_ou},
684 $self->timelog("Returned from calling get_records_and_facets() for MARC expert");
686 # load temporary_list settings for user and ou:
687 $self->_load_lists_and_settings if ($self->ctx->{user});
689 $self->ctx->{records} = [@data];
691 return Apache2::Const::OK;
694 sub call_number_browse_standalone {
697 if (my $cnfrag = $self->cgi->param("query")) {
699 '%s://%s%s/cnbrowse?cn=%s',
701 $self->ctx->{hostname},
702 $self->ctx->{opac_root},
703 $cnfrag # XXX some kind of escaping needed here?
705 $url .= '&locg=' . $self->_get_search_lib() if ($self->_get_search_lib());
706 return $self->generic_redirect($url);
708 return $self->generic_redirect; # return to search page
715 $self->prepare_browse_call_numbers();
717 return Apache2::Const::OK;
720 sub get_staff_search_settings {
723 unless ($self->ctx->{is_staff}) {
724 $self->ctx->{staff_saved_search_size} = 0;
728 $self->timelog("Getting staff search size");
729 my $sss_size = $self->ctx->{get_org_setting}->(
730 $self->ctx->{physical_loc} || $self->ctx->{aou_tree}->()->id,
731 "opac.staff_saved_search.size",
733 $self->timelog("Got staff search size");
735 # Sic: 0 is 0 (off), but undefined is 10.
736 $sss_size = 10 unless defined $sss_size;
738 $self->ctx->{staff_saved_search_size} = $sss_size;
741 sub staff_load_searches {
744 my $cache_key = $self->cgi->cookie((ref $self)->COOKIE_ANON_CACHE);
748 $self->timelog("Getting anon_cache value");
749 $list = $U->simplereq(
751 "open-ils.actor.anon_cache.get_value",
752 $cache_key, (ref $self)->ANON_CACHE_STAFF_SEARCH
754 $self->timelog("Got anon_cache value");
762 return ($cache_key, $list);
765 sub staff_save_search {
766 my ($self, $query) = @_;
768 my $sss_size = $self->ctx->{staff_saved_search_size};
769 return unless $sss_size > 0;
771 my ($cache_key, $list) = $self->staff_load_searches;
772 my %already = ( map { $_ => 1 } @$list );
774 unshift @$list, $query unless $already{$query};
776 splice @$list, $sss_size if scalar @$list > $sss_size;
778 $self->timelog("Setting anon_cache value");
779 $cache_key = $U->simplereq(
781 "open-ils.actor.anon_cache.set_value",
782 $cache_key, (ref $self)->ANON_CACHE_STAFF_SEARCH, $list
784 $self->timelog("Set anon_cache value");
786 return ($cache_key, $list);