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::SearchEngine::Elasticsearch::QueryBuilder;
36 use Koha::ElasticSearch::Search;
37 use Koha::SearchEngine::Zebra::QueryBuilder;
38 use Koha::SearchEngine::Zebra::Search;
40 my $searchengine = C4::Context->preference("SearchEngine");
41 my ($builder, $searcher);
42 #$searchengine = 'Zebra'; # XXX
43 for ( $searchengine ) {
46 require 'opac/search.pl';
50 $builder=Koha::SearchEngine::Zebra::QueryBuilder->new();
51 $searcher=Koha::SearchEngine::Zebra::Search->new();
53 when (/^Elasticsearch$/) {
54 # Should use the base QueryBuilder, but I don't have it wired up
56 $builder=Koha::SearchEngine::Elasticsearch::QueryBuilder->new();
57 # $builder=Koha::SearchEngine::Zebra::QueryBuilder->new();
58 $searcher=Koha::ElasticSearch::Search->new({index => 'biblios'});
63 use C4::Auth qw(:DEFAULT get_session);
64 use C4::Languages qw(getLanguages);
66 use C4::Search::History;
67 use C4::Biblio; # GetBiblioData
69 use C4::Tags qw(get_tags);
70 use C4::Branch; # GetBranches
73 use C4::External::OverDrive;
75 use Koha::LibraryCategories;
77 use POSIX qw(ceil floor strftime);
79 use JSON qw/decode_json encode_json/;
82 my $DisplayMultiPlaceHold = C4::Context->preference("DisplayMultiPlaceHold");
83 # create a new CGI object
84 # FIXME: no_undef_params needs to be tested
85 use CGI qw('-no_undef_params' -utf8);
88 my $branch_group_limit = $cgi->param("branch_group_limit");
89 if ( $branch_group_limit ) {
90 if ( $branch_group_limit =~ /^multibranchlimit-/ ) {
91 # For search groups we are going to convert this branch_group_limit CGI
92 # parameter into a multibranchlimit CGI parameter for the purposes of
93 # actually performing the query
95 -name => 'multibranchlimit',
96 -values => substr($branch_group_limit, 17)
101 -values => [ $branch_group_limit ]
107 if (C4::Context->preference('BakerTaylorEnabled')) {
108 require C4::External::BakerTaylor;
109 import C4::External::BakerTaylor qw(&image_url &link_url);
113 my ($template,$borrowernumber,$cookie);
114 # decide which template to use
116 my $template_type = 'basic';
117 my @params = $cgi->param("limit");
118 my @searchCategories = $cgi->param('searchcat');
120 my $format = $cgi->param("format") || '';
121 my $build_grouped_results = C4::Context->preference('OPACGroupResults');
122 if ($format =~ /(rss|atom|opensearchdescription)/) {
123 $template_name = 'opac-opensearch.tt';
125 elsif (@params && $build_grouped_results) {
126 $template_name = 'opac-results-grouped.tt';
128 elsif ((@params>=1) || ($cgi->param("q")) || ($cgi->param('multibranchlimit')) || ($cgi->param('limit-yr')) ) {
129 $template_name = 'opac-results.tt';
132 $template_name = 'opac-advsearch.tt';
133 $template_type = 'advsearch';
136 ($template, $borrowernumber, $cookie) = get_template_and_user({
137 template_name => $template_name,
140 authnotrequired => ( C4::Context->preference("OpacPublic") ? 1 : 0 ),
144 my $lang = C4::Languages::getlanguage($cgi);
146 if ($template_name eq 'opac-results.tt') {
147 $template->param('COinSinOPACResults' => C4::Context->preference('COinSinOPACResults'));
150 # get biblionumbers stored in the cart
153 if($cgi->cookie("bib_list")){
154 my $cart_list = $cgi->cookie("bib_list");
155 @cart_list = split(/\//, $cart_list);
158 if ($format eq 'rss2' or $format eq 'opensearchdescription' or $format eq 'atom') {
159 $template->param($format => 1);
160 $template->param(timestamp => strftime("%Y-%m-%dT%H:%M:%S-00:00", gmtime)) if ($format eq 'atom');
161 # FIXME - the timestamp is a hack - the biblio update timestamp should be used for each
162 # entry, but not sure if that's worth an extra database query for each bib
164 if (C4::Context->preference("marcflavour") eq "UNIMARC" ) {
165 $template->param('UNIMARC' => 1);
167 elsif (C4::Context->preference("marcflavour") eq "MARC21" ) {
168 $template->param('usmarc' => 1);
171 $template->param( 'OPACNoResultsFound' => C4::Context->preference('OPACNoResultsFound') );
174 OpacStarRatings => C4::Context->preference("OpacStarRatings") );
176 if (C4::Context->preference('BakerTaylorEnabled')) {
178 BakerTaylorEnabled => 1,
179 BakerTaylorImageURL => &image_url(),
180 BakerTaylorLinkURL => &link_url(),
181 BakerTaylorBookstoreURL => C4::Context->preference('BakerTaylorBookstoreURL'),
185 if (C4::Context->preference('TagsEnabled')) {
186 $template->param(TagsEnabled => 1);
187 foreach (qw(TagsShowOnList TagsInputOnList)) {
188 C4::Context->preference($_) and $template->param($_ => 1);
193 # Deprecated, but preserved because it's interesting :-)
194 # The same thing can be accomplished with mod_rewrite in
198 #my $uri = $cgi->url(-base => 1);
199 #my $relative_url = $cgi->url(-relative=>1);
200 #$uri.="/".$relative_url."?";
202 #my @cgi_params_list = $cgi->param();
203 #my $url_params = $cgi->Vars;
205 #for my $each_param_set (@cgi_params_list) {
206 # $uri.= join "", map "\&$each_param_set=".$_, split("\0",$url_params->{$each_param_set}) if $url_params->{$each_param_set};
208 #warn "New URI:$uri";
209 # Only re-write a URI if there are params or if it already hasn't been re-written
210 #unless (($cgi->param('r')) || (!$cgi->param()) ) {
211 # print $cgi->redirect( -uri=>$uri."&r=1",
212 # -cookie => $cookie);
218 if ($cgi->param("returntosearch")) {
219 $template->param('ReturnToSearch' => 1);
221 if ($cgi->cookie("search_path_code")) {
222 my $pathcode = $cgi->cookie("search_path_code");
223 if ($pathcode eq '"ads"') {
224 $template->param('ReturnPath' => '/cgi-bin/koha/opac-search.pl?returntosearch=1');
226 elsif ($pathcode eq '"exs"') {
227 $template->param('ReturnPath' => '/cgi-bin/koha/opac-search.pl?expanded_options=1&returntosearch=1');
230 warn "ReturnPath switch error";
234 my $branches = GetBranches(); # used later in *getRecords, probably should be internalized by those functions after caching in C4::Branch is established
235 my $library_categories = Koha::LibraryCategories->search( { categorytype => 'searchdomain' }, { order_by => [ 'categorytype', 'categorycode' ] } );
236 $template->param( searchdomainloop => $library_categories );
238 # load the language limits (for search)
239 my $languages_limit_loop = getLanguages($lang, 1);
240 $template->param(search_languages_loop => $languages_limit_loop,);
242 # load the Type stuff
243 my $itemtypes = GetItemTypesCategorized;
244 # add translated_description to itemtypes
245 foreach my $itemtype ( keys %{$itemtypes} ) {
246 # Itemtypes search categories don't have (yet) translated descriptions, they are auth values
247 my $translated_description = getitemtypeinfo( $itemtype, 'opac' )->{translated_description};
248 $itemtypes->{$itemtype}->{translated_description} =
249 ( $translated_description ) ? $translated_description : $itemtypes->{$itemtype}->{description};
251 # Load the Type stuff without search categories for facets
252 my $itemtypes_nocategory = GetItemTypes;
253 # the index parameter is different for item-level itemtypes
254 my $itype_or_itemtype = (C4::Context->preference("item-level_itypes"))?'itype':'itemtype';
255 my @advancedsearchesloop;
257 my $advanced_search_types = C4::Context->preference("AdvancedSearchTypes") || "itemtypes";
258 my @advanced_search_types = split(/\|/, $advanced_search_types);
260 my $hidingrules = {};
261 my $yaml = C4::Context->preference('OpacHiddenItems');
262 if ( $yaml =~ /\S/ ) {
263 $yaml = "$yaml\n\n"; # YAML expects trailing newline. Surplus does not hurt.
265 $hidingrules = YAML::Load($yaml);
268 warn "Unable to parse OpacHiddenItems syspref : $@";
272 foreach my $advanced_srch_type (@advanced_search_types) {
273 $advanced_srch_type =~ s/^\s*//;
274 $advanced_srch_type =~ s/\s*$//;
275 if ($advanced_srch_type eq 'itemtypes') {
276 # itemtype is a special case, since it's not defined in authorized values
278 foreach my $thisitemtype ( sort {$itemtypes->{$a}->{translated_description} cmp $itemtypes->{$b}->{translated_description} } keys %$itemtypes ) {
279 next if $hidingrules->{itype} && any { $_ eq $thisitemtype } @{$hidingrules->{itype}};
280 next if $hidingrules->{itemtype} && any { $_ eq $thisitemtype } @{$hidingrules->{itemtype}};
281 my %row =( number=>$cnt++,
282 ccl => "$itype_or_itemtype,phr",
283 code => $thisitemtype,
284 description => $itemtypes->{$thisitemtype}->{translated_description},
285 imageurl=> getitemtypeimagelocation( 'opac', $itemtypes->{$thisitemtype}->{'imageurl'} ),
286 cat => $itemtypes->{$thisitemtype}->{'iscat'},
287 hideinopac => $itemtypes->{$thisitemtype}->{'hideinopac'},
288 searchcategory => $itemtypes->{$thisitemtype}->{'searchcategory'},
290 if ( !$itemtypes->{$thisitemtype}->{'hideinopac'} ) {
291 push @itypesloop, \%row;
294 my %search_code = ( advanced_search_type => $advanced_srch_type,
295 code_loop => \@itypesloop );
296 push @advancedsearchesloop, \%search_code;
298 # covers all the other cases: non-itemtype authorized values
299 my $advsearchtypes = GetAuthorisedValues($advanced_srch_type, 'opac');
301 for my $thisitemtype (@$advsearchtypes) {
302 my $hiding_key = lc $thisitemtype->{category};
303 $hiding_key = "location" if $hiding_key eq 'loc';
304 next if $hidingrules->{$hiding_key} && any { $_ eq $thisitemtype->{authorised_value} } @{$hidingrules->{$hiding_key}};
307 ccl => $advanced_srch_type,
308 code => $thisitemtype->{authorised_value},
309 description => $thisitemtype->{'lib_opac'} || $thisitemtype->{'lib'},
310 searchcategory => $itemtypes->{$thisitemtype}->{'searchcategory'},
311 imageurl => getitemtypeimagelocation( 'opac', $thisitemtype->{'imageurl'} ),
313 push @authvalueloop, \%row;
315 my %search_code = ( advanced_search_type => $advanced_srch_type,
316 code_loop => \@authvalueloop );
317 push @advancedsearchesloop, \%search_code;
320 $template->param(advancedsearchesloop => \@advancedsearchesloop);
322 # The following should only be loaded if we're bringing up the advanced search template
323 if ( $template_type && $template_type eq 'advsearch' ) {
324 # load the servers (used for searching -- to do federated searching, etc.)
325 my $primary_servers_loop;# = displayPrimaryServers();
326 $template->param(outer_servers_loop => $primary_servers_loop,);
328 my $secondary_servers_loop;
329 $template->param(outer_sup_servers_loop => $secondary_servers_loop,);
331 # set the default sorting
332 if ( C4::Context->preference('OPACdefaultSortField')
333 && C4::Context->preference('OPACdefaultSortOrder') ) {
334 my $default_sort_by =
335 C4::Context->preference('OPACdefaultSortField') . '_'
336 . C4::Context->preference('OPACdefaultSortOrder');
337 $template->param( sort_by => $default_sort_by );
340 # determine what to display next to the search boxes (ie, boolean option
341 # shouldn't appear on the first one, scan indexes should, adding a new
342 # box should only appear on the last, etc.
343 my @search_boxes_array;
344 my $search_boxes_count = 3; # begin whith 3 boxes
345 $template->param( search_boxes_count => $search_boxes_count );
347 if ($cgi->cookie("num_paragraph")){
348 $search_boxes_count = $cgi->cookie("num_paragraph");
351 for (my $i=1;$i<=$search_boxes_count;$i++) {
352 # if it's the first one, don't display boolean option, but show scan indexes
354 push @search_boxes_array,
360 # if it's the last one, show the 'add field' box
361 elsif ($i==$search_boxes_count) {
362 push @search_boxes_array,
369 push @search_boxes_array,
377 my @advsearch_limits = split /,/, C4::Context->preference('OpacAdvSearchOptions');
378 my @advsearch_more_limits = split /,/,
379 C4::Context->preference('OpacAdvSearchMoreOptions');
381 uc( C4::Context->preference("marcflavour") ) => 1, # we already did this for UNIMARC
383 search_boxes_loop => \@search_boxes_array,
384 OpacAdvSearchOptions => \@advsearch_limits,
385 OpacAdvSearchMoreOptions => \@advsearch_more_limits,
388 # use the global setting by default
389 if ( C4::Context->preference("expandedSearchOption") == 1 ) {
390 $template->param( expanded_options => C4::Context->preference("expandedSearchOption") );
392 # but let the user override it
393 if (defined $cgi->param('expanded_options')) {
394 if ( ($cgi->param('expanded_options') == 0) || ($cgi->param('expanded_options') == 1 ) ) {
395 $template->param( expanded_options => $cgi->param('expanded_options'));
399 if (C4::Context->preference('OPACNumbersPreferPhrase')) {
400 $template->param('numbersphr' => 1);
403 output_html_with_http_headers $cgi, $cookie, $template->output;
407 ### OK, if we're this far, we're performing an actual search
409 # Fetch the paramater list as a hash in scalar context:
410 # * returns paramater list as tied hash ref
411 # * we can edit the values by changing the key
412 # * multivalued CGI paramaters are returned as a packaged string separated by "\0" (null)
413 my $params = $cgi->Vars;
415 if ( $params->{tag} ) {
416 $tag = $params->{tag};
417 $template->param( tag => $tag );
420 # String with params with the search criteria for the paging in opac-detail
421 # param value is URI encoded and params separator is HTML encode (&)
422 my $pasarParams = '';
424 for (keys %$params) {
425 my @pasarParam = $cgi->param($_);
426 for my $paramValue(@pasarParam) {
427 $pasarParams .= '&' if ($j > 0);
428 $pasarParams .= $_ . '=' . uri_escape_utf8($paramValue);
433 # Params that can have more than one value
434 # sort by is used to sort the query
435 # in theory can have more than one but generally there's just one
438 if ( C4::Context->preference('OPACdefaultSortField')
439 && C4::Context->preference('OPACdefaultSortOrder') ) {
441 C4::Context->preference('OPACdefaultSortField') . '_'
442 . C4::Context->preference('OPACdefaultSortOrder');
445 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/;
446 @sort_by = $cgi->param('sort_by');
447 $sort_by[0] = $default_sort_by if !$sort_by[0] && defined($default_sort_by);
448 foreach my $sort (@sort_by) {
449 if ( grep { /^$sort$/ } @allowed_sortby ) {
450 $template->param($sort => 1);
453 $template->param('sort_by' => $sort_by[0]);
455 # Use the servers defined, or just search our local catalog(default)
456 my @servers = $cgi->param('server');
458 #FIXME: this should be handled using Context.pm
459 @servers = ("biblioserver");
460 # @servers = C4::Context->config("biblioserver");
463 # operators include boolean and proximity operators and are used
464 # to evaluate multiple operands
465 my @operators = $cgi->param('op');
466 @operators = map { uri_unescape($_) } @operators;
468 # indexes are query qualifiers, like 'title', 'author', etc. They
469 # can be single or multiple parameters separated by comma: kw,right-Truncation
470 my @indexes = $cgi->param('idx');
471 @indexes = map { uri_unescape($_) } @indexes;
473 # if a simple index (only one) display the index used in the top search box
474 if ($indexes[0] && !$indexes[1]) {
475 $template->param("ms_".$indexes[0] => 1);
477 # an operand can be a single term, a phrase, or a complete ccl query
478 my @operands = $cgi->param('q');
479 @operands = map { uri_unescape($_) } @operands;
481 $template->{VARS}->{querystring} = join(' ', @operands);
483 # if a simple search, display the value in the search box
484 if ($operands[0] && !$operands[1]) {
485 my $ms_query = $operands[0];
486 $ms_query =~ s/ #\S+//;
487 $template->param(ms_value => $ms_query);
490 # limits are use to limit to results to a pre-defined category such as branch or language
491 my @limits = $cgi->param('limit');
492 @limits = map { uri_unescape($_) } @limits;
493 my @nolimits = $cgi->param('nolimit');
494 @nolimits = map { uri_unescape($_) } @nolimits;
495 my %is_nolimit = map { $_ => 1 } @nolimits;
496 @limits = grep { not $is_nolimit{$_} } @limits;
498 if (@searchCategories > 0) {
500 foreach my $typecategory (@searchCategories) {
501 push (@tabcat, GetItemTypesByCategory($typecategory));
504 foreach my $itemtypeInCategory (@tabcat) {
505 push (@limits, "mc-$itype_or_itemtype,phr:".$itemtypeInCategory);
509 @limits = map { uri_unescape($_) } @limits;
511 if($params->{'multibranchlimit'}) {
512 my $library_category = Koha::LibraryCategories->find( $params->{multibranchlimit} );
513 my @libraries = $library_category->libraries;
514 my $multibranch = '('.join( " or ", map { 'branch: ' . $_->id } @libraries ) .')';
515 push @limits, $multibranch if ($multibranch ne '()');
519 foreach my $limit(@limits) {
520 if ($limit =~/available/) {
524 $template->param(available => $available);
526 # append year limits if they exist
527 if ($params->{'limit-yr'}) {
528 if ($params->{'limit-yr'} =~ /\d{4}-\d{4}/) {
529 my ($yr1,$yr2) = split(/-/, $params->{'limit-yr'});
530 push @limits, "yr,st-numeric,ge=$yr1 and yr,st-numeric,le=$yr2";
532 elsif ($params->{'limit-yr'} =~ /\d{4}/) {
533 push @limits, "yr,st-numeric=$params->{'limit-yr'}";
536 #FIXME: Should return a error to the user, incorect date format specified
540 # Params that can only have one value
541 my $scan = $params->{'scan'};
542 my $count = C4::Context->preference('OPACnumSearchResults') || 20;
543 my $countRSS = C4::Context->preference('numSearchRSSResults') || 50;
544 my $results_per_page = $params->{'count'} || $count;
545 my $offset = $params->{'offset'} || 0;
546 my $page = $cgi->param('page') || 1;
547 $offset = ($page-1)*$results_per_page if $page>1;
549 my $expanded_facet = $params->{'expand'};
551 # Define some global variables
552 my ($error,$query,$simple_query,$query_cgi,$query_desc,$limit,$limit_cgi,$limit_desc,$query_type);
556 ## I. BUILD THE QUERY
557 ( $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);
559 sub _input_cgi_parse {
561 my $query_cgi = shift or return @elements;
562 for my $this_cgi ( split('&',$query_cgi) ) {
563 next unless $this_cgi;
564 $this_cgi =~ /(.*?)=(.*)/;
565 push @elements, { input_name => $1, input_value => Encode::decode_utf8( uri_unescape($2) ) };
570 ## parse the query_cgi string and put it into a form suitable for <input>s
571 my @query_inputs = _input_cgi_parse($query_cgi);
572 $template->param ( QUERY_INPUTS => \@query_inputs );
574 ## parse the limit_cgi string and put it into a form suitable for <input>s
575 my @limit_inputs = $limit_cgi ? _input_cgi_parse($limit_cgi) : ();
577 # add OPAC 'hidelostitems'
578 #if (C4::Context->preference('hidelostitems') == 1) {
579 # # either lost ge 0 or no value in the lost register
580 # $query ="($query) and ( (lost,st-numeric <= 0) or ( allrecords,AlwaysMatches='' not lost,AlwaysMatches='') )";
583 # add OPAC suppression - requires at least one item indexed with Suppress
584 if (C4::Context->preference('OpacSuppression')) {
585 # OPAC suppression by IP address
586 if (C4::Context->preference('OpacSuppressionByIPRange')) {
587 my $IPAddress = $ENV{'REMOTE_ADDR'};
588 my $IPRange = C4::Context->preference('OpacSuppressionByIPRange');
589 if ($IPAddress !~ /^$IPRange/) {
590 if ( $query_type eq 'pqf' ) {
591 $query = '@not '.$query.' @attr 14=1 @attr 1=9011 1';
593 $query = "($query) not Suppress=1";
598 if ( $query_type eq 'pqf' ) {
599 #$query = "($query) && -(suppress:1)"; #QP syntax
600 $query = '@not '.$query.' @attr 14=1 @attr 1=9011 1'; #PQF syntax
602 $query = "($query) not Suppress=1";
607 $template->param ( LIMIT_INPUTS => \@limit_inputs );
608 $template->param ( OPACResultsSidebar => C4::Context->preference('OPACResultsSidebar'));
610 ## II. DO THE SEARCH AND GET THE RESULTS
611 my $total = 0; # the total results for the whole set
612 my $facets; # this object stores the faceted results that display on the left-hand of the results page
618 $query_cgi = "tag=" .$tag . "&" . $query_cgi;
619 my $taglist = get_tags({term=>$tag, approved=>1});
620 $results_hashref->{biblioserver}->{hits} = scalar (@$taglist);
621 my @biblist = (map {GetBiblioData($_->{biblionumber})} @$taglist);
622 my @marclist = (map { (C4::Context->config('zebra_bib_index_mode') eq 'dom')? $_->{marcxml}: $_->{marc}; } @biblist);
623 $DEBUG and printf STDERR "taglist (%s biblionumber)\nmarclist (%s records)\n", scalar(@$taglist), scalar(@marclist);
624 $results_hashref->{biblioserver}->{RECORDS} = \@marclist;
625 # FIXME: tag search and standard search should work together, not exclusively
626 # FIXME: No facets for tags search.
627 } elsif ($build_grouped_results) {
629 ($error, $results_hashref, $facets) = C4::Search::pazGetRecords($query,$simple_query,\@sort_by,\@servers,$results_per_page,$offset,$expanded_facet,$branches,$query_type,$scan);
632 $pasarParams .= '&query=' . uri_escape_utf8($query);
633 $pasarParams .= '&count=' . uri_escape_utf8($results_per_page);
634 $pasarParams .= '&simple_query=' . uri_escape_utf8($simple_query);
635 $pasarParams .= '&query_type=' . uri_escape_utf8($query_type) if ($query_type);
637 ($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);
641 # This sorts the facets into alphabetical order
642 if ($facets && @$facets) {
643 foreach my $f (@$facets) {
644 $f->{facets} = [ sort { uc($a->{facet_label_value}) cmp uc($b->{facet_label_value}) } @{ $f->{facets} } ];
646 @$facets = sort {$a->{expand} cmp $b->{expand}} @$facets;
649 # use Data::Dumper; print STDERR "-" x 25, "\n", Dumper($results_hashref);
651 $template->param(query_error => $error.$@);
652 output_html_with_http_headers $cgi, $cookie, $template->output;
656 # At this point, each server has given us a result set
657 # now we build that set for template display
658 my @sup_results_array;
659 for (my $i=0;$i<@servers;$i++) {
660 my $server = $servers[$i];
661 if ($server && $server =~/biblioserver/) { # this is the local bibliographic server
662 $hits = $results_hashref->{$server}->{"hits"};
663 my $page = $cgi->param('page') || 0;
665 if ($build_grouped_results) {
666 foreach my $group (@{ $results_hashref->{$server}->{"GROUPS"} }) {
667 # because pazGetRecords handles retieving only the records
668 # we want as specified by $offset and $results_per_page,
669 # we need to set the offset parameter of searchResults to 0
670 my @group_results = searchResults( 'opac', $query_desc, $group->{'group_count'},$results_per_page, 0, $scan,
671 $group->{"RECORDS"});
672 push @newresults, { group_label => $group->{'group_label'}, GROUP_RESULTS => \@group_results };
675 @newresults = searchResults('opac', $query_desc, $hits, $results_per_page, $offset, $scan,
676 $results_hashref->{$server}->{"RECORDS"});
678 $hits = 0 unless @newresults;
680 foreach my $res (@newresults) {
682 # must define a value for size if not present in DB
683 # in order to avoid problems generated by the default size value in TT
684 if ( not exists $res->{'size'} ) { $res->{'size'} = "" }
685 # while we're checking each line, see if item is in the cart
686 if ( grep {$_ eq $res->{'biblionumber'}} @cart_list) {
687 $res->{'incart'} = 1;
690 if (C4::Context->preference('COinSinOPACResults')) {
691 my $record = GetMarcBiblio($res->{'biblionumber'});
692 $res->{coins} = GetCOinSBiblio($record);
694 if ( C4::Context->preference( "Babeltheque" ) and $res->{normalized_isbn} ) {
695 if( my $isbn = Business::ISBN->new( $res->{normalized_isbn} ) ) {
696 $isbn = $isbn->as_isbn13->as_string;
698 my $social_datas = C4::SocialData::get_data( $isbn );
699 if ( $social_datas ) {
700 for my $key ( keys %$social_datas ) {
701 $res->{$key} = $$social_datas{$key};
702 if ( $key eq 'score_avg' ){
703 $res->{score_int} = sprintf("%.0f", $$social_datas{score_avg} );
710 if (C4::Context->preference('TagsEnabled') and
711 C4::Context->preference('TagsShowOnList')) {
712 if ( my $bibnum = $res->{biblionumber} ) {
713 $res->{itemsissued} = CountItemsIssued( $bibnum );
714 $res->{'TagLoop'} = get_tags({
715 biblionumber => $bibnum,
718 limit => C4::Context->preference('TagsShowOnList')
723 if ( C4::Context->preference('OpacStarRatings') eq 'all' ) {
724 my $rating = GetRating( $res->{'biblionumber'}, $borrowernumber );
725 $res->{'rating_value'} = $rating->{'rating_value'};
726 $res->{'rating_total'} = $rating->{'rating_total'};
727 $res->{'rating_avg'} = $rating->{'rating_avg'};
728 $res->{'rating_avg_int'} = $rating->{'rating_avg_int'};
732 if ($results_hashref->{$server}->{"hits"}){
733 $total = $total + $hits;
736 # Opac search history
737 if (C4::Context->preference('EnableOpacSearchHistory')) {
739 my $path_info = $cgi->url(-path_info=>1);
740 my $query_cgi_history = $cgi->url(-query=>1);
741 $query_cgi_history =~ s/^$path_info\?//;
742 $query_cgi_history =~ s/;/&/g;
743 my $query_desc_history = join ", ", grep { defined $_ } $query_desc, $limit_desc;
745 unless ( $borrowernumber ) {
746 my $new_searches = C4::Search::History::add_to_session({
748 query_desc => $query_desc_history,
749 query_cgi => $query_cgi_history,
754 # To the session (the user is logged in)
755 C4::Search::History::add({
756 userid => $borrowernumber,
757 sessionid => $cgi->cookie("CGISESSID"),
758 query_desc => $query_desc_history,
759 query_cgi => $query_cgi_history,
765 $template->param( EnableOpacSearchHistory => 1 );
768 ## If there's just one result, redirect to the detail page
769 if ($total == 1 && $format ne 'rss2'
770 && $format ne 'opensearchdescription' && $format ne 'atom') {
771 my $biblionumber=$newresults[0]->{biblionumber};
772 if (C4::Context->preference('BiblioDefaultView') eq 'isbd') {
773 print $cgi->redirect("/cgi-bin/koha/opac-ISBDdetail.pl?biblionumber=$biblionumber");
774 } elsif (C4::Context->preference('BiblioDefaultView') eq 'marc') {
775 print $cgi->redirect("/cgi-bin/koha/opac-MARCdetail.pl?biblionumber=$biblionumber");
777 print $cgi->redirect("/cgi-bin/koha/opac-detail.pl?biblionumber=$biblionumber");
782 if ( !$build_grouped_results ) {
783 # We build the encrypted list of first OPACnumSearchResults biblios to pass with the search criteria for paging on opac-detail
784 $pasarParams .= '&listBiblios=';
786 foreach (@newresults) {
787 my $bibnum = ($_->{biblionumber})?$_->{biblionumber}:0;
788 $pasarParams .= uri_escape_utf8($bibnum) . ',';
790 last if ($j == $results_per_page);
792 chop $pasarParams if ($pasarParams =~ /,$/);
793 $pasarParams .= '&total=' . uri_escape_utf8( int($total) ) if ($pasarParams !~ /total=(?:[0-9]+)?/);
795 my $session = get_session($cgi->cookie("CGISESSID"));
796 $session->param('busc' => $pasarParams);
800 $template->param(total => $hits);
801 my $limit_cgi_not_availablity = $limit_cgi;
802 $limit_cgi_not_availablity =~ s/&limit=available//g if defined $limit_cgi_not_availablity;
803 $template->param(limit_cgi_not_availablity => $limit_cgi_not_availablity);
804 $template->param(limit_cgi => $limit_cgi);
805 $template->param(countrss => $countRSS );
806 $template->param(query_cgi => $query_cgi);
807 $template->param(query_desc => $query_desc);
808 $template->param(limit_desc => $limit_desc);
809 $template->param(offset => $offset);
810 $template->param(DisplayMultiPlaceHold => $DisplayMultiPlaceHold);
811 if ($query_desc || $limit_desc) {
812 $template->param(searchdesc => 1);
814 $template->param(results_per_page => $results_per_page);
815 my $hide = C4::Context->preference('OpacHiddenItems');
816 $hide = ($hide =~ m/\S/) if $hide; # Just in case it has some spaces/new lines
818 if (C4::Context->userenv){
819 $branch = C4::Context->userenv->{branch};
821 if ( C4::Context->preference('HighlightOwnItemsOnOPAC') ) {
823 ( ( C4::Context->preference('HighlightOwnItemsOnOPACWhich') eq 'PatronBranch' ) && $branch )
825 C4::Context->preference('HighlightOwnItemsOnOPACWhich') eq 'OpacURLBranch'
828 if ( C4::Context->preference('HighlightOwnItemsOnOPACWhich') eq 'PatronBranch' ) {
829 $branchname = $branches->{$branch}->{'branchname'};
831 elsif ( C4::Context->preference('HighlightOwnItemsOnOPACWhich') eq 'OpacURLBranch' ) {
832 $branchname = $branches->{ $ENV{'BRANCHCODE'} }->{'branchname'};
835 foreach my $res ( @newresults ) {
838 my @old_loop = @{$res->{'available_items_loop'}};
839 foreach my $item ( @old_loop ) {
840 if ( $item->{'branchname'} eq $branchname ) {
841 $item->{'this_branch'} = 1;
842 push( @top_loop, $item );
844 push( @new_loop, $item );
847 my @complete_loop = ( @top_loop, @new_loop );
848 $res->{'available_items_loop'} = \@complete_loop;
854 SEARCH_RESULTS => \@newresults,
855 OPACItemsResultsDisplay => (C4::Context->preference("OPACItemsResultsDisplay")),
856 suppress_result_number => $hide,
858 if (C4::Context->preference("OPACLocalCoverImages")){
859 $template->param(OPACLocalCoverImages => 1);
860 $template->param(OPACLocalCoverImagesPriority => C4::Context->preference("OPACLocalCoverImagesPriority"));
862 ## Build the page numbers on the bottom of the page
864 # total number of pages there will be
865 my $pages = ceil($hits / $results_per_page);
866 # default page number
867 my $current_page_number = 1;
869 $current_page_number = ( $offset / $results_per_page + 1 );
871 my $previous_page_offset;
872 if ( $offset >= $results_per_page ) {
873 $previous_page_offset = $offset - $results_per_page;
875 my $next_page_offset = $offset + $results_per_page;
876 # If we're within the first 10 pages, keep it simple
877 #warn "current page:".$current_page_number;
878 if ($current_page_number < 10) {
879 # just show the first 10 pages
880 # Loop through the pages
881 my $pages_to_show = 10;
882 $pages_to_show = $pages if $pages<10;
883 for ($i=1; $i<=$pages_to_show;$i++) {
884 # the offset for this page
885 my $this_offset = (($i*$results_per_page)-$results_per_page);
886 # the page number for this page
887 my $this_page_number = $i;
888 # put it in the array
890 { offset => $this_offset,
891 pg => $this_page_number,
892 highlight => $this_page_number == $current_page_number,
893 sort_by => join ' ', @sort_by
899 # now, show twenty pages, with the current one smack in the middle
901 for ($i=$current_page_number; $i<=($current_page_number + 20 );$i++) {
902 my $this_offset = ((($i-9)*$results_per_page)-$results_per_page);
903 my $this_page_number = $i-9;
904 if ( $this_page_number <= $pages ) {
906 { offset => $this_offset,
907 pg => $this_page_number,
908 highlight => $this_page_number == $current_page_number,
909 sort_by => join ' ', @sort_by
915 $template->param( PAGE_NUMBERS => \@page_numbers,
916 previous_page_offset => $previous_page_offset) unless $pages < 2;
917 $template->param(next_page_offset => $next_page_offset) unless $pages eq $current_page_number;
921 my $nohits = C4::Context->preference('OPACNoResultsFound');
922 if ($nohits and $nohits=~/{QUERY_KW}/){
923 # extracting keywords in case of relaunching search
924 (my $query_kw=$query_desc)=~s/ and|or / /g;
925 my @query_kw=($query_kw=~ /([-\w]+\b)(?:[^,:]|$)/g);
926 $query_kw=join('+',@query_kw);
927 $nohits=~s/{QUERY_KW}/$query_kw/g;
928 $template->param('OPACNoResultsFound' =>$nohits);
932 query_desc => $query_desc,
933 limit_desc => $limit_desc,
934 query_cgi => $query_cgi,
935 limit_cgi => $limit_cgi
938 } # end of the if local
939 # asynchronously search the authority server
940 elsif ($server && $server =~/authorityserver/) { # this is the local authority server
941 my @inner_sup_results_array;
942 for my $sup_record ( @{$results_hashref->{$server}->{"RECORDS"}} ) {
943 my $marc_record_object = MARC::Record->new_from_usmarc($sup_record);
944 my $title_field = $marc_record_object->field(100);
945 push @inner_sup_results_array, {
946 'title' => $title_field->subfield('a'),
947 'link' => "&idx=an&q=".$marc_record_object->field('001')->as_string(),
950 my $servername = $server;
951 push @sup_results_array, { servername => $servername,
952 inner_sup_results_loop => \@inner_sup_results_array} if @inner_sup_results_array;
954 # FIXME: can add support for other targets as needed here
955 $template->param( outer_sup_results_loop => \@sup_results_array);
956 } #/end of the for loop
957 #$template->param(FEDERATED_RESULTS => \@results_array);
959 for my $facet ( @$facets ) {
960 for my $entry ( @{ $facet->{facets} } ) {
961 my $index = $entry->{type_link_value};
962 my $value = $entry->{facet_link_value};
963 $entry->{active} = grep { $_->{input_value} eq qq{$index:$value} } @limit_inputs;
969 #classlist => $classlist,
972 facets_loop => $facets,
973 displayFacetCount=> C4::Context->preference('displayFacetCount')||0,
975 search_error => $error,
978 if ($query_desc || $limit_desc) {
979 $template->param(searchdesc => 1);
982 # VI. BUILD THE TEMPLATE
983 my $some_private_shelves = Koha::Virtualshelves->get_some_shelves(
985 borrowernumber => $borrowernumber,
990 my $some_public_shelves = Koha::Virtualshelves->get_some_shelves(
992 borrowernumber => $borrowernumber,
999 add_to_some_private_shelves => $some_private_shelves,
1000 add_to_some_public_shelves => $some_public_shelves,
1003 my $content_type = ($format eq 'rss' or $format eq 'atom') ? $format : 'html';
1005 # If GoogleIndicTransliteration system preference is On Set parameter to load Google's javascript in OPAC search screens
1006 if (C4::Context->preference('GoogleIndicTransliteration')) {
1007 $template->param('GoogleIndicTransliteration' => 1);
1010 $template->{VARS}->{DidYouMean} =
1011 ( defined C4::Context->preference('OPACdidyoumean')
1012 && C4::Context->preference('OPACdidyoumean') =~ m/enable/ );
1013 $template->{VARS}->{IDreamBooksReviews} = C4::Context->preference('IDreamBooksReviews');
1014 $template->{VARS}->{IDreamBooksReadometer} = C4::Context->preference('IDreamBooksReadometer');
1015 $template->{VARS}->{IDreamBooksResults} = C4::Context->preference('IDreamBooksResults');
1017 if ($offset == 0 && IsOverDriveEnabled()) {
1018 $template->param(OverDriveEnabled => 1);
1019 $template->param(OverDriveLibraryID => C4::Context->preference('OverDriveLibraryID'));
1022 $template->param( borrowernumber => $borrowernumber);
1023 output_with_http_headers $cgi, $cookie, $template->output, $content_type;