3 # Copyright 2008 Garry Collum and the Koha Development team
4 # Copyright 2010 BibLibre
5 # Copyright 2011 KohaAloha, NZ
7 # This file is part of Koha.
9 # Koha is free software; you can redistribute it and/or modify it
10 # under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
14 # Koha is distributed in the hope that it will be useful, but
15 # WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
19 # You should have received a copy of the GNU General Public License
20 # along with Koha; if not, see <http://www.gnu.org/licenses>.
22 # Script to perform searching
23 # Mostly copied from search.pl, see POD there
26 ## STEP 1. Load things that are used in both search page and
27 # results page and decide which template to load, operations
31 use List::MoreUtils q/any/;
33 use Data::Dumper; # TODO remove
35 use Koha::ElasticSearch::Search;
36 use Koha::SearchEngine::QueryBuilder;
37 use Koha::SearchEngine::Zebra::Search;
39 my $searchengine = C4::Context->preference("SearchEngine");
40 my ($builder, $searcher);
41 #$searchengine = 'Zebra'; # XXX
42 $builder = Koha::SearchEngine::QueryBuilder->new();
43 for ( $searchengine ) {
46 require 'opac/search.pl';
50 $searcher=Koha::SearchEngine::Zebra::Search->new();
52 when (/^Elasticsearch$/) {
53 # TODO refactor Koha::ES::Search into Koha::SE::ES::Search
54 $searcher=Koha::ElasticSearch::Search->new({index => 'biblios'});
59 use C4::Auth qw(:DEFAULT get_session);
60 use C4::Languages qw(getLanguages);
62 use C4::Search::History;
63 use C4::Biblio; # GetBiblioData
65 use C4::Tags qw(get_tags);
66 use C4::Branch; # GetBranches
69 use C4::External::OverDrive;
71 use Koha::LibraryCategories;
73 use POSIX qw(ceil floor strftime);
75 use JSON qw/decode_json encode_json/;
78 my $DisplayMultiPlaceHold = C4::Context->preference("DisplayMultiPlaceHold");
79 # create a new CGI object
80 # FIXME: no_undef_params needs to be tested
81 use CGI qw('-no_undef_params' -utf8);
84 my $branch_group_limit = $cgi->param("branch_group_limit");
85 if ( $branch_group_limit ) {
86 if ( $branch_group_limit =~ /^multibranchlimit-/ ) {
87 # For search groups we are going to convert this branch_group_limit CGI
88 # parameter into a multibranchlimit CGI parameter for the purposes of
89 # actually performing the query
91 -name => 'multibranchlimit',
92 -values => substr($branch_group_limit, 17)
97 -values => [ $branch_group_limit ]
103 if (C4::Context->preference('BakerTaylorEnabled')) {
104 require C4::External::BakerTaylor;
105 import C4::External::BakerTaylor qw(&image_url &link_url);
109 my ($template,$borrowernumber,$cookie);
110 # decide which template to use
112 my $template_type = 'basic';
113 my @params = $cgi->param("limit");
114 my @searchCategories = $cgi->param('searchcat');
116 my $format = $cgi->param("format") || '';
117 my $build_grouped_results = C4::Context->preference('OPACGroupResults');
118 if ($format =~ /(rss|atom|opensearchdescription)/) {
119 $template_name = 'opac-opensearch.tt';
121 elsif (@params && $build_grouped_results) {
122 $template_name = 'opac-results-grouped.tt';
124 elsif ((@params>=1) || ($cgi->param("q")) || ($cgi->param('multibranchlimit')) || ($cgi->param('limit-yr')) ) {
125 $template_name = 'opac-results.tt';
128 $template_name = 'opac-advsearch.tt';
129 $template_type = 'advsearch';
132 ($template, $borrowernumber, $cookie) = get_template_and_user({
133 template_name => $template_name,
136 authnotrequired => ( C4::Context->preference("OpacPublic") ? 1 : 0 ),
140 my $lang = C4::Languages::getlanguage($cgi);
142 if ($template_name eq 'opac-results.tt') {
143 $template->param('COinSinOPACResults' => C4::Context->preference('COinSinOPACResults'));
146 # get biblionumbers stored in the cart
149 if($cgi->cookie("bib_list")){
150 my $cart_list = $cgi->cookie("bib_list");
151 @cart_list = split(/\//, $cart_list);
154 if ($format eq 'rss2' or $format eq 'opensearchdescription' or $format eq 'atom') {
155 $template->param($format => 1);
156 $template->param(timestamp => strftime("%Y-%m-%dT%H:%M:%S-00:00", gmtime)) if ($format eq 'atom');
157 # FIXME - the timestamp is a hack - the biblio update timestamp should be used for each
158 # entry, but not sure if that's worth an extra database query for each bib
160 if (C4::Context->preference("marcflavour") eq "UNIMARC" ) {
161 $template->param('UNIMARC' => 1);
163 elsif (C4::Context->preference("marcflavour") eq "MARC21" ) {
164 $template->param('usmarc' => 1);
167 $template->param( 'OPACNoResultsFound' => C4::Context->preference('OPACNoResultsFound') );
170 OpacStarRatings => C4::Context->preference("OpacStarRatings") );
172 if (C4::Context->preference('BakerTaylorEnabled')) {
174 BakerTaylorEnabled => 1,
175 BakerTaylorImageURL => &image_url(),
176 BakerTaylorLinkURL => &link_url(),
177 BakerTaylorBookstoreURL => C4::Context->preference('BakerTaylorBookstoreURL'),
181 if (C4::Context->preference('TagsEnabled')) {
182 $template->param(TagsEnabled => 1);
183 foreach (qw(TagsShowOnList TagsInputOnList)) {
184 C4::Context->preference($_) and $template->param($_ => 1);
189 # Deprecated, but preserved because it's interesting :-)
190 # The same thing can be accomplished with mod_rewrite in
194 #my $uri = $cgi->url(-base => 1);
195 #my $relative_url = $cgi->url(-relative=>1);
196 #$uri.="/".$relative_url."?";
198 #my @cgi_params_list = $cgi->param();
199 #my $url_params = $cgi->Vars;
201 #for my $each_param_set (@cgi_params_list) {
202 # $uri.= join "", map "\&$each_param_set=".$_, split("\0",$url_params->{$each_param_set}) if $url_params->{$each_param_set};
204 #warn "New URI:$uri";
205 # Only re-write a URI if there are params or if it already hasn't been re-written
206 #unless (($cgi->param('r')) || (!$cgi->param()) ) {
207 # print $cgi->redirect( -uri=>$uri."&r=1",
208 # -cookie => $cookie);
214 if ($cgi->param("returntosearch")) {
215 $template->param('ReturnToSearch' => 1);
217 if ($cgi->cookie("search_path_code")) {
218 my $pathcode = $cgi->cookie("search_path_code");
219 if ($pathcode eq '"ads"') {
220 $template->param('ReturnPath' => '/cgi-bin/koha/opac-search.pl?returntosearch=1');
222 elsif ($pathcode eq '"exs"') {
223 $template->param('ReturnPath' => '/cgi-bin/koha/opac-search.pl?expanded_options=1&returntosearch=1');
226 warn "ReturnPath switch error";
230 my $branches = GetBranches(); # used later in *getRecords, probably should be internalized by those functions after caching in C4::Branch is established
231 my $library_categories = Koha::LibraryCategories->search( { categorytype => 'searchdomain' }, { order_by => [ 'categorytype', 'categorycode' ] } );
232 $template->param( searchdomainloop => $library_categories );
234 # load the language limits (for search)
235 my $languages_limit_loop = getLanguages($lang, 1);
236 $template->param(search_languages_loop => $languages_limit_loop,);
238 # load the Type stuff
239 my $itemtypes = GetItemTypesCategorized;
240 # add translated_description to itemtypes
241 foreach my $itemtype ( keys %{$itemtypes} ) {
242 # Itemtypes search categories don't have (yet) translated descriptions, they are auth values
243 my $translated_description = getitemtypeinfo( $itemtype, 'opac' )->{translated_description};
244 $itemtypes->{$itemtype}->{translated_description} =
245 ( $translated_description ) ? $translated_description : $itemtypes->{$itemtype}->{description};
247 # Load the Type stuff without search categories for facets
248 my $itemtypes_nocategory = GetItemTypes;
249 # the index parameter is different for item-level itemtypes
250 my $itype_or_itemtype = (C4::Context->preference("item-level_itypes"))?'itype':'itemtype';
251 my @advancedsearchesloop;
253 my $advanced_search_types = C4::Context->preference("AdvancedSearchTypes") || "itemtypes";
254 my @advanced_search_types = split(/\|/, $advanced_search_types);
256 my $hidingrules = {};
257 my $yaml = C4::Context->preference('OpacHiddenItems');
258 if ( $yaml =~ /\S/ ) {
259 $yaml = "$yaml\n\n"; # YAML expects trailing newline. Surplus does not hurt.
261 $hidingrules = YAML::Load($yaml);
264 warn "Unable to parse OpacHiddenItems syspref : $@";
268 foreach my $advanced_srch_type (@advanced_search_types) {
269 $advanced_srch_type =~ s/^\s*//;
270 $advanced_srch_type =~ s/\s*$//;
271 if ($advanced_srch_type eq 'itemtypes') {
272 # itemtype is a special case, since it's not defined in authorized values
274 foreach my $thisitemtype ( sort {$itemtypes->{$a}->{translated_description} cmp $itemtypes->{$b}->{translated_description} } keys %$itemtypes ) {
275 next if $hidingrules->{itype} && any { $_ eq $thisitemtype } @{$hidingrules->{itype}};
276 next if $hidingrules->{itemtype} && any { $_ eq $thisitemtype } @{$hidingrules->{itemtype}};
277 my %row =( number=>$cnt++,
278 ccl => "$itype_or_itemtype,phr",
279 code => $thisitemtype,
280 description => $itemtypes->{$thisitemtype}->{translated_description},
281 imageurl=> getitemtypeimagelocation( 'opac', $itemtypes->{$thisitemtype}->{'imageurl'} ),
282 cat => $itemtypes->{$thisitemtype}->{'iscat'},
283 hideinopac => $itemtypes->{$thisitemtype}->{'hideinopac'},
284 searchcategory => $itemtypes->{$thisitemtype}->{'searchcategory'},
286 if ( !$itemtypes->{$thisitemtype}->{'hideinopac'} ) {
287 push @itypesloop, \%row;
290 my %search_code = ( advanced_search_type => $advanced_srch_type,
291 code_loop => \@itypesloop );
292 push @advancedsearchesloop, \%search_code;
294 # covers all the other cases: non-itemtype authorized values
295 my $advsearchtypes = GetAuthorisedValues($advanced_srch_type, 'opac');
297 for my $thisitemtype (@$advsearchtypes) {
298 my $hiding_key = lc $thisitemtype->{category};
299 $hiding_key = "location" if $hiding_key eq 'loc';
300 next if $hidingrules->{$hiding_key} && any { $_ eq $thisitemtype->{authorised_value} } @{$hidingrules->{$hiding_key}};
303 ccl => $advanced_srch_type,
304 code => $thisitemtype->{authorised_value},
305 description => $thisitemtype->{'lib_opac'} || $thisitemtype->{'lib'},
306 searchcategory => $itemtypes->{$thisitemtype}->{'searchcategory'},
307 imageurl => getitemtypeimagelocation( 'opac', $thisitemtype->{'imageurl'} ),
309 push @authvalueloop, \%row;
311 my %search_code = ( advanced_search_type => $advanced_srch_type,
312 code_loop => \@authvalueloop );
313 push @advancedsearchesloop, \%search_code;
316 $template->param(advancedsearchesloop => \@advancedsearchesloop);
318 # The following should only be loaded if we're bringing up the advanced search template
319 if ( $template_type && $template_type eq 'advsearch' ) {
320 # load the servers (used for searching -- to do federated searching, etc.)
321 my $primary_servers_loop;# = displayPrimaryServers();
322 $template->param(outer_servers_loop => $primary_servers_loop,);
324 my $secondary_servers_loop;
325 $template->param(outer_sup_servers_loop => $secondary_servers_loop,);
327 # set the default sorting
328 if ( C4::Context->preference('OPACdefaultSortField')
329 && C4::Context->preference('OPACdefaultSortOrder') ) {
330 my $default_sort_by =
331 C4::Context->preference('OPACdefaultSortField') . '_'
332 . C4::Context->preference('OPACdefaultSortOrder');
333 $template->param( sort_by => $default_sort_by );
336 # determine what to display next to the search boxes (ie, boolean option
337 # shouldn't appear on the first one, scan indexes should, adding a new
338 # box should only appear on the last, etc.
339 my @search_boxes_array;
340 my $search_boxes_count = 3; # begin whith 3 boxes
341 $template->param( search_boxes_count => $search_boxes_count );
343 if ($cgi->cookie("num_paragraph")){
344 $search_boxes_count = $cgi->cookie("num_paragraph");
347 for (my $i=1;$i<=$search_boxes_count;$i++) {
348 # if it's the first one, don't display boolean option, but show scan indexes
350 push @search_boxes_array,
356 # if it's the last one, show the 'add field' box
357 elsif ($i==$search_boxes_count) {
358 push @search_boxes_array,
365 push @search_boxes_array,
373 my @advsearch_limits = split /,/, C4::Context->preference('OpacAdvSearchOptions');
374 my @advsearch_more_limits = split /,/,
375 C4::Context->preference('OpacAdvSearchMoreOptions');
377 uc( C4::Context->preference("marcflavour") ) => 1, # we already did this for UNIMARC
379 search_boxes_loop => \@search_boxes_array,
380 OpacAdvSearchOptions => \@advsearch_limits,
381 OpacAdvSearchMoreOptions => \@advsearch_more_limits,
384 # use the global setting by default
385 if ( C4::Context->preference("expandedSearchOption") == 1 ) {
386 $template->param( expanded_options => C4::Context->preference("expandedSearchOption") );
388 # but let the user override it
389 if (defined $cgi->param('expanded_options')) {
390 if ( ($cgi->param('expanded_options') == 0) || ($cgi->param('expanded_options') == 1 ) ) {
391 $template->param( expanded_options => $cgi->param('expanded_options'));
395 if (C4::Context->preference('OPACNumbersPreferPhrase')) {
396 $template->param('numbersphr' => 1);
399 output_html_with_http_headers $cgi, $cookie, $template->output;
403 ### OK, if we're this far, we're performing an actual search
405 # Fetch the paramater list as a hash in scalar context:
406 # * returns paramater list as tied hash ref
407 # * we can edit the values by changing the key
408 # * multivalued CGI paramaters are returned as a packaged string separated by "\0" (null)
409 my $params = $cgi->Vars;
411 if ( $params->{tag} ) {
412 $tag = $params->{tag};
413 $template->param( tag => $tag );
416 # String with params with the search criteria for the paging in opac-detail
417 # param value is URI encoded and params separator is HTML encode (&)
418 my $pasarParams = '';
420 for (keys %$params) {
421 my @pasarParam = $cgi->param($_);
422 for my $paramValue(@pasarParam) {
423 $pasarParams .= '&' if ($j > 0);
424 $pasarParams .= $_ . '=' . uri_escape_utf8($paramValue);
429 # Params that can have more than one value
430 # sort by is used to sort the query
431 # in theory can have more than one but generally there's just one
434 if ( C4::Context->preference('OPACdefaultSortField')
435 && C4::Context->preference('OPACdefaultSortOrder') ) {
437 C4::Context->preference('OPACdefaultSortField') . '_'
438 . C4::Context->preference('OPACdefaultSortOrder');
441 my @allowed_sortby = qw /acqdate_asc acqdate_dsc author_az author_za call_number_asc call_number_dsc popularity_asc popularity_dsc pubdate_asc pubdate_dsc relevance title_az title_za/;
442 @sort_by = $cgi->param('sort_by');
443 $sort_by[0] = $default_sort_by if !$sort_by[0] && defined($default_sort_by);
444 foreach my $sort (@sort_by) {
445 if ( grep { /^$sort$/ } @allowed_sortby ) {
446 $template->param($sort => 1);
449 $template->param('sort_by' => $sort_by[0]);
451 # Use the servers defined, or just search our local catalog(default)
452 my @servers = $cgi->param('server');
454 #FIXME: this should be handled using Context.pm
455 @servers = ("biblioserver");
456 # @servers = C4::Context->config("biblioserver");
459 # operators include boolean and proximity operators and are used
460 # to evaluate multiple operands
461 my @operators = $cgi->param('op');
462 @operators = map { uri_unescape($_) } @operators;
464 # indexes are query qualifiers, like 'title', 'author', etc. They
465 # can be single or multiple parameters separated by comma: kw,right-Truncation
466 my @indexes = $cgi->param('idx');
467 @indexes = map { uri_unescape($_) } @indexes;
469 # if a simple index (only one) display the index used in the top search box
470 if ($indexes[0] && !$indexes[1]) {
471 $template->param("ms_".$indexes[0] => 1);
473 # an operand can be a single term, a phrase, or a complete ccl query
474 my @operands = $cgi->param('q');
475 @operands = map { uri_unescape($_) } @operands;
477 $template->{VARS}->{querystring} = join(' ', @operands);
479 # if a simple search, display the value in the search box
480 if ($operands[0] && !$operands[1]) {
481 my $ms_query = $operands[0];
482 $ms_query =~ s/ #\S+//;
483 $template->param(ms_value => $ms_query);
486 # limits are use to limit to results to a pre-defined category such as branch or language
487 my @limits = $cgi->param('limit');
488 @limits = map { uri_unescape($_) } @limits;
489 my @nolimits = $cgi->param('nolimit');
490 @nolimits = map { uri_unescape($_) } @nolimits;
491 my %is_nolimit = map { $_ => 1 } @nolimits;
492 @limits = grep { not $is_nolimit{$_} } @limits;
494 if (@searchCategories > 0) {
496 foreach my $typecategory (@searchCategories) {
497 push (@tabcat, GetItemTypesByCategory($typecategory));
500 foreach my $itemtypeInCategory (@tabcat) {
501 push (@limits, "mc-$itype_or_itemtype,phr:".$itemtypeInCategory);
505 @limits = map { uri_unescape($_) } @limits;
507 if($params->{'multibranchlimit'}) {
508 my $library_category = Koha::LibraryCategories->find( $params->{multibranchlimit} );
509 my @libraries = $library_category->libraries;
510 my $multibranch = '('.join( " or ", map { 'branch: ' . $_->id } @libraries ) .')';
511 push @limits, $multibranch if ($multibranch ne '()');
515 foreach my $limit(@limits) {
516 if ($limit =~/available/) {
520 $template->param(available => $available);
522 # append year limits if they exist
523 if ($params->{'limit-yr'}) {
524 if ($params->{'limit-yr'} =~ /\d{4}-\d{4}/) {
525 my ($yr1,$yr2) = split(/-/, $params->{'limit-yr'});
526 push @limits, "yr,st-numeric,ge=$yr1 and yr,st-numeric,le=$yr2";
528 elsif ($params->{'limit-yr'} =~ /\d{4}/) {
529 push @limits, "yr,st-numeric=$params->{'limit-yr'}";
532 #FIXME: Should return a error to the user, incorect date format specified
536 # Params that can only have one value
537 my $scan = $params->{'scan'};
538 my $count = C4::Context->preference('OPACnumSearchResults') || 20;
539 my $countRSS = C4::Context->preference('numSearchRSSResults') || 50;
540 my $results_per_page = $params->{'count'} || $count;
541 my $offset = $params->{'offset'} || 0;
542 my $page = $cgi->param('page') || 1;
543 $offset = ($page-1)*$results_per_page if $page>1;
545 my $expanded_facet = $params->{'expand'};
547 # Define some global variables
548 my ($error,$query,$simple_query,$query_cgi,$query_desc,$limit,$limit_cgi,$limit_desc,$query_type);
552 ## I. BUILD THE QUERY
553 ( $error,$query,$simple_query,$query_cgi,$query_desc,$limit,$limit_cgi,$limit_desc,$query_type) = $builder->build_query_compat(\@operators,\@operands,\@indexes,\@limits,\@sort_by, 0, $lang);
555 sub _input_cgi_parse {
557 my $query_cgi = shift or return @elements;
558 for my $this_cgi ( split('&',$query_cgi) ) {
559 next unless $this_cgi;
560 $this_cgi =~ /(.*?)=(.*)/;
561 push @elements, { input_name => $1, input_value => Encode::decode_utf8( uri_unescape($2) ) };
566 ## parse the query_cgi string and put it into a form suitable for <input>s
567 my @query_inputs = _input_cgi_parse($query_cgi);
568 $template->param ( QUERY_INPUTS => \@query_inputs );
570 ## parse the limit_cgi string and put it into a form suitable for <input>s
571 my @limit_inputs = $limit_cgi ? _input_cgi_parse($limit_cgi) : ();
573 # add OPAC 'hidelostitems'
574 #if (C4::Context->preference('hidelostitems') == 1) {
575 # # either lost ge 0 or no value in the lost register
576 # $query ="($query) and ( (lost,st-numeric <= 0) or ( allrecords,AlwaysMatches='' not lost,AlwaysMatches='') )";
579 # add OPAC suppression - requires at least one item indexed with Suppress
580 if (C4::Context->preference('OpacSuppression')) {
581 # OPAC suppression by IP address
582 if (C4::Context->preference('OpacSuppressionByIPRange')) {
583 my $IPAddress = $ENV{'REMOTE_ADDR'};
584 my $IPRange = C4::Context->preference('OpacSuppressionByIPRange');
585 if ($IPAddress !~ /^$IPRange/) {
586 if ( $query_type eq 'pqf' ) {
587 $query = '@not '.$query.' @attr 14=1 @attr 1=9011 1';
589 $query = "($query) not Suppress=1";
594 if ( $query_type eq 'pqf' ) {
595 #$query = "($query) && -(suppress:1)"; #QP syntax
596 $query = '@not '.$query.' @attr 14=1 @attr 1=9011 1'; #PQF syntax
598 $query = "($query) not Suppress=1";
603 $template->param ( LIMIT_INPUTS => \@limit_inputs );
604 $template->param ( OPACResultsSidebar => C4::Context->preference('OPACResultsSidebar'));
606 ## II. DO THE SEARCH AND GET THE RESULTS
607 my $total = 0; # the total results for the whole set
608 my $facets; # this object stores the faceted results that display on the left-hand of the results page
614 $query_cgi = "tag=" .$tag . "&" . $query_cgi;
615 my $taglist = get_tags({term=>$tag, approved=>1});
616 $results_hashref->{biblioserver}->{hits} = scalar (@$taglist);
617 my @biblist = (map {GetBiblioData($_->{biblionumber})} @$taglist);
618 my @marclist = (map { (C4::Context->config('zebra_bib_index_mode') eq 'dom')? $_->{marcxml}: $_->{marc}; } @biblist);
619 $DEBUG and printf STDERR "taglist (%s biblionumber)\nmarclist (%s records)\n", scalar(@$taglist), scalar(@marclist);
620 $results_hashref->{biblioserver}->{RECORDS} = \@marclist;
621 # FIXME: tag search and standard search should work together, not exclusively
622 # FIXME: No facets for tags search.
623 } elsif ($build_grouped_results) {
625 ($error, $results_hashref, $facets) = C4::Search::pazGetRecords($query,$simple_query,\@sort_by,\@servers,$results_per_page,$offset,$expanded_facet,$branches,$query_type,$scan);
628 $pasarParams .= '&query=' . uri_escape_utf8($query);
629 $pasarParams .= '&count=' . uri_escape_utf8($results_per_page);
630 $pasarParams .= '&simple_query=' . uri_escape_utf8($simple_query);
631 $pasarParams .= '&query_type=' . uri_escape_utf8($query_type) if ($query_type);
633 ($error, $results_hashref, $facets) = $searcher->search_compat($query,$simple_query,\@sort_by,\@servers,$results_per_page,$offset,$expanded_facet,$branches,$itemtypes,$query_type,$scan,1);
637 # This sorts the facets into alphabetical order
638 if ($facets && @$facets) {
639 foreach my $f (@$facets) {
640 $f->{facets} = [ sort { uc($a->{facet_label_value}) cmp uc($b->{facet_label_value}) } @{ $f->{facets} } ];
642 @$facets = sort {$a->{expand} cmp $b->{expand}} @$facets;
645 # use Data::Dumper; print STDERR "-" x 25, "\n", Dumper($results_hashref);
647 $template->param(query_error => $error.$@);
648 output_html_with_http_headers $cgi, $cookie, $template->output;
652 # At this point, each server has given us a result set
653 # now we build that set for template display
654 my @sup_results_array;
655 for (my $i=0;$i<@servers;$i++) {
656 my $server = $servers[$i];
657 if ($server && $server =~/biblioserver/) { # this is the local bibliographic server
658 $hits = $results_hashref->{$server}->{"hits"};
659 my $page = $cgi->param('page') || 0;
661 if ($build_grouped_results) {
662 foreach my $group (@{ $results_hashref->{$server}->{"GROUPS"} }) {
663 # because pazGetRecords handles retieving only the records
664 # we want as specified by $offset and $results_per_page,
665 # we need to set the offset parameter of searchResults to 0
666 my @group_results = searchResults( 'opac', $query_desc, $group->{'group_count'},$results_per_page, 0, $scan,
667 $group->{"RECORDS"});
668 push @newresults, { group_label => $group->{'group_label'}, GROUP_RESULTS => \@group_results };
671 @newresults = searchResults('opac', $query_desc, $hits, $results_per_page, $offset, $scan,
672 $results_hashref->{$server}->{"RECORDS"});
674 $hits = 0 unless @newresults;
676 foreach my $res (@newresults) {
678 # must define a value for size if not present in DB
679 # in order to avoid problems generated by the default size value in TT
680 if ( not exists $res->{'size'} ) { $res->{'size'} = "" }
681 # while we're checking each line, see if item is in the cart
682 if ( grep {$_ eq $res->{'biblionumber'}} @cart_list) {
683 $res->{'incart'} = 1;
686 if (C4::Context->preference('COinSinOPACResults')) {
687 my $record = GetMarcBiblio($res->{'biblionumber'});
688 $res->{coins} = GetCOinSBiblio($record);
690 if ( C4::Context->preference( "Babeltheque" ) and $res->{normalized_isbn} ) {
691 if( my $isbn = Business::ISBN->new( $res->{normalized_isbn} ) ) {
692 $isbn = $isbn->as_isbn13->as_string;
694 my $social_datas = C4::SocialData::get_data( $isbn );
695 if ( $social_datas ) {
696 for my $key ( keys %$social_datas ) {
697 $res->{$key} = $$social_datas{$key};
698 if ( $key eq 'score_avg' ){
699 $res->{score_int} = sprintf("%.0f", $$social_datas{score_avg} );
706 if (C4::Context->preference('TagsEnabled') and
707 C4::Context->preference('TagsShowOnList')) {
708 if ( my $bibnum = $res->{biblionumber} ) {
709 $res->{itemsissued} = CountItemsIssued( $bibnum );
710 $res->{'TagLoop'} = get_tags({
711 biblionumber => $bibnum,
714 limit => C4::Context->preference('TagsShowOnList')
719 if ( C4::Context->preference('OpacStarRatings') eq 'all' ) {
720 my $rating = GetRating( $res->{'biblionumber'}, $borrowernumber );
721 $res->{'rating_value'} = $rating->{'rating_value'};
722 $res->{'rating_total'} = $rating->{'rating_total'};
723 $res->{'rating_avg'} = $rating->{'rating_avg'};
724 $res->{'rating_avg_int'} = $rating->{'rating_avg_int'};
728 if ($results_hashref->{$server}->{"hits"}){
729 $total = $total + $hits;
732 # Opac search history
733 if (C4::Context->preference('EnableOpacSearchHistory')) {
735 my $path_info = $cgi->url(-path_info=>1);
736 my $query_cgi_history = $cgi->url(-query=>1);
737 $query_cgi_history =~ s/^$path_info\?//;
738 $query_cgi_history =~ s/;/&/g;
739 my $query_desc_history = join ", ", grep { defined $_ } $query_desc, $limit_desc;
741 unless ( $borrowernumber ) {
742 my $new_searches = C4::Search::History::add_to_session({
744 query_desc => $query_desc_history,
745 query_cgi => $query_cgi_history,
750 # To the session (the user is logged in)
751 C4::Search::History::add({
752 userid => $borrowernumber,
753 sessionid => $cgi->cookie("CGISESSID"),
754 query_desc => $query_desc_history,
755 query_cgi => $query_cgi_history,
761 $template->param( EnableOpacSearchHistory => 1 );
764 ## If there's just one result, redirect to the detail page
765 if ($total == 1 && $format ne 'rss2'
766 && $format ne 'opensearchdescription' && $format ne 'atom') {
767 my $biblionumber=$newresults[0]->{biblionumber};
768 if (C4::Context->preference('BiblioDefaultView') eq 'isbd') {
769 print $cgi->redirect("/cgi-bin/koha/opac-ISBDdetail.pl?biblionumber=$biblionumber");
770 } elsif (C4::Context->preference('BiblioDefaultView') eq 'marc') {
771 print $cgi->redirect("/cgi-bin/koha/opac-MARCdetail.pl?biblionumber=$biblionumber");
773 print $cgi->redirect("/cgi-bin/koha/opac-detail.pl?biblionumber=$biblionumber");
778 if ( !$build_grouped_results ) {
779 # We build the encrypted list of first OPACnumSearchResults biblios to pass with the search criteria for paging on opac-detail
780 $pasarParams .= '&listBiblios=';
782 foreach (@newresults) {
783 my $bibnum = ($_->{biblionumber})?$_->{biblionumber}:0;
784 $pasarParams .= uri_escape_utf8($bibnum) . ',';
786 last if ($j == $results_per_page);
788 chop $pasarParams if ($pasarParams =~ /,$/);
789 $pasarParams .= '&total=' . uri_escape_utf8( int($total) ) if ($pasarParams !~ /total=(?:[0-9]+)?/);
791 my $session = get_session($cgi->cookie("CGISESSID"));
792 $session->param('busc' => $pasarParams);
796 $template->param(total => $hits);
797 my $limit_cgi_not_availablity = $limit_cgi;
798 $limit_cgi_not_availablity =~ s/&limit=available//g if defined $limit_cgi_not_availablity;
799 $template->param(limit_cgi_not_availablity => $limit_cgi_not_availablity);
800 $template->param(limit_cgi => $limit_cgi);
801 $template->param(countrss => $countRSS );
802 $template->param(query_cgi => $query_cgi);
803 $template->param(query_desc => $query_desc);
804 $template->param(limit_desc => $limit_desc);
805 $template->param(offset => $offset);
806 $template->param(DisplayMultiPlaceHold => $DisplayMultiPlaceHold);
807 if ($query_desc || $limit_desc) {
808 $template->param(searchdesc => 1);
810 $template->param(results_per_page => $results_per_page);
811 my $hide = C4::Context->preference('OpacHiddenItems');
812 $hide = ($hide =~ m/\S/) if $hide; # Just in case it has some spaces/new lines
814 if (C4::Context->userenv){
815 $branch = C4::Context->userenv->{branch};
817 if ( C4::Context->preference('HighlightOwnItemsOnOPAC') ) {
819 ( ( C4::Context->preference('HighlightOwnItemsOnOPACWhich') eq 'PatronBranch' ) && $branch )
821 C4::Context->preference('HighlightOwnItemsOnOPACWhich') eq 'OpacURLBranch'
824 if ( C4::Context->preference('HighlightOwnItemsOnOPACWhich') eq 'PatronBranch' ) {
825 $branchname = $branches->{$branch}->{'branchname'};
827 elsif ( C4::Context->preference('HighlightOwnItemsOnOPACWhich') eq 'OpacURLBranch' ) {
828 $branchname = $branches->{ $ENV{'BRANCHCODE'} }->{'branchname'};
831 foreach my $res ( @newresults ) {
834 my @old_loop = @{$res->{'available_items_loop'}};
835 foreach my $item ( @old_loop ) {
836 if ( $item->{'branchname'} eq $branchname ) {
837 $item->{'this_branch'} = 1;
838 push( @top_loop, $item );
840 push( @new_loop, $item );
843 my @complete_loop = ( @top_loop, @new_loop );
844 $res->{'available_items_loop'} = \@complete_loop;
850 SEARCH_RESULTS => \@newresults,
851 OPACItemsResultsDisplay => (C4::Context->preference("OPACItemsResultsDisplay")),
852 suppress_result_number => $hide,
854 if (C4::Context->preference("OPACLocalCoverImages")){
855 $template->param(OPACLocalCoverImages => 1);
856 $template->param(OPACLocalCoverImagesPriority => C4::Context->preference("OPACLocalCoverImagesPriority"));
858 ## Build the page numbers on the bottom of the page
860 # total number of pages there will be
861 my $pages = ceil($hits / $results_per_page);
862 # default page number
863 my $current_page_number = 1;
865 $current_page_number = ( $offset / $results_per_page + 1 );
867 my $previous_page_offset;
868 if ( $offset >= $results_per_page ) {
869 $previous_page_offset = $offset - $results_per_page;
871 my $next_page_offset = $offset + $results_per_page;
872 # If we're within the first 10 pages, keep it simple
873 #warn "current page:".$current_page_number;
874 if ($current_page_number < 10) {
875 # just show the first 10 pages
876 # Loop through the pages
877 my $pages_to_show = 10;
878 $pages_to_show = $pages if $pages<10;
879 for ($i=1; $i<=$pages_to_show;$i++) {
880 # the offset for this page
881 my $this_offset = (($i*$results_per_page)-$results_per_page);
882 # the page number for this page
883 my $this_page_number = $i;
884 # put it in the array
886 { offset => $this_offset,
887 pg => $this_page_number,
888 highlight => $this_page_number == $current_page_number,
889 sort_by => join ' ', @sort_by
895 # now, show twenty pages, with the current one smack in the middle
897 for ($i=$current_page_number; $i<=($current_page_number + 20 );$i++) {
898 my $this_offset = ((($i-9)*$results_per_page)-$results_per_page);
899 my $this_page_number = $i-9;
900 if ( $this_page_number <= $pages ) {
902 { offset => $this_offset,
903 pg => $this_page_number,
904 highlight => $this_page_number == $current_page_number,
905 sort_by => join ' ', @sort_by
911 $template->param( PAGE_NUMBERS => \@page_numbers,
912 previous_page_offset => $previous_page_offset) unless $pages < 2;
913 $template->param(next_page_offset => $next_page_offset) unless $pages eq $current_page_number;
917 my $nohits = C4::Context->preference('OPACNoResultsFound');
918 if ($nohits and $nohits=~/{QUERY_KW}/){
919 # extracting keywords in case of relaunching search
920 (my $query_kw=$query_desc)=~s/ and|or / /g;
921 my @query_kw=($query_kw=~ /([-\w]+\b)(?:[^,:]|$)/g);
922 $query_kw=join('+',@query_kw);
923 $nohits=~s/{QUERY_KW}/$query_kw/g;
924 $template->param('OPACNoResultsFound' =>$nohits);
928 query_desc => $query_desc,
929 limit_desc => $limit_desc,
930 query_cgi => $query_cgi,
931 limit_cgi => $limit_cgi
934 } # end of the if local
935 # asynchronously search the authority server
936 elsif ($server && $server =~/authorityserver/) { # this is the local authority server
937 my @inner_sup_results_array;
938 for my $sup_record ( @{$results_hashref->{$server}->{"RECORDS"}} ) {
939 my $marc_record_object = MARC::Record->new_from_usmarc($sup_record);
940 my $title_field = $marc_record_object->field(100);
941 push @inner_sup_results_array, {
942 'title' => $title_field->subfield('a'),
943 'link' => "&idx=an&q=".$marc_record_object->field('001')->as_string(),
946 my $servername = $server;
947 push @sup_results_array, { servername => $servername,
948 inner_sup_results_loop => \@inner_sup_results_array} if @inner_sup_results_array;
950 # FIXME: can add support for other targets as needed here
951 $template->param( outer_sup_results_loop => \@sup_results_array);
952 } #/end of the for loop
953 #$template->param(FEDERATED_RESULTS => \@results_array);
955 for my $facet ( @$facets ) {
956 for my $entry ( @{ $facet->{facets} } ) {
957 my $index = $entry->{type_link_value};
958 my $value = $entry->{facet_link_value};
959 $entry->{active} = grep { $_->{input_value} eq qq{$index:$value} } @limit_inputs;
965 #classlist => $classlist,
968 facets_loop => $facets,
969 displayFacetCount=> C4::Context->preference('displayFacetCount')||0,
971 search_error => $error,
974 if ($query_desc || $limit_desc) {
975 $template->param(searchdesc => 1);
978 # VI. BUILD THE TEMPLATE
979 my $some_private_shelves = Koha::Virtualshelves->get_some_shelves(
981 borrowernumber => $borrowernumber,
986 my $some_public_shelves = Koha::Virtualshelves->get_some_shelves(
988 borrowernumber => $borrowernumber,
995 add_to_some_private_shelves => $some_private_shelves,
996 add_to_some_public_shelves => $some_public_shelves,
999 my $content_type = ($format eq 'rss' or $format eq 'atom') ? $format : 'html';
1001 # If GoogleIndicTransliteration system preference is On Set parameter to load Google's javascript in OPAC search screens
1002 if (C4::Context->preference('GoogleIndicTransliteration')) {
1003 $template->param('GoogleIndicTransliteration' => 1);
1006 $template->{VARS}->{DidYouMean} =
1007 ( defined C4::Context->preference('OPACdidyoumean')
1008 && C4::Context->preference('OPACdidyoumean') =~ m/enable/ );
1009 $template->{VARS}->{IDreamBooksReviews} = C4::Context->preference('IDreamBooksReviews');
1010 $template->{VARS}->{IDreamBooksReadometer} = C4::Context->preference('IDreamBooksReadometer');
1011 $template->{VARS}->{IDreamBooksResults} = C4::Context->preference('IDreamBooksResults');
1013 if ($offset == 0 && IsOverDriveEnabled()) {
1014 $template->param(OverDriveEnabled => 1);
1015 $template->param(OverDriveLibraryID => C4::Context->preference('OverDriveLibraryID'));
1018 $template->param( borrowernumber => $borrowernumber);
1019 output_with_http_headers $cgi, $cookie, $template->output, $content_type;