Bug 14778: Make Search.t pass - replace SHOW COLUMNS
[koha.git] / opac / opac-search.pl
blob7d21354e3b88ec07a8dd63f28db7f3c0d645479d
1 #!/usr/bin/perl
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
24 use Modern::Perl;
26 ## STEP 1. Load things that are used in both search page and
27 # results page and decide which template to load, operations
28 # to perform, etc.
29 ## load Koha modules
30 use C4::Context;
31 use List::MoreUtils q/any/;
33 use C4::Output;
34 use C4::Auth qw(:DEFAULT get_session);
35 use C4::Languages qw(getLanguages);
36 use C4::Search;
37 use C4::Search::History;
38 use C4::Biblio; # GetBiblioData
39 use C4::Koha;
40 use C4::Tags qw(get_tags);
41 use C4::Branch; # GetBranches
42 use C4::SocialData;
43 use C4::Ratings;
44 use C4::External::OverDrive;
46 use POSIX qw(ceil floor strftime);
47 use URI::Escape;
48 use JSON qw/decode_json encode_json/;
49 use Business::ISBN;
51 my $DisplayMultiPlaceHold = C4::Context->preference("DisplayMultiPlaceHold");
52 # create a new CGI object
53 # FIXME: no_undef_params needs to be tested
54 use CGI qw('-no_undef_params' -utf8);
55 my $cgi = new CGI;
57 my $branch_group_limit = $cgi->param("branch_group_limit");
58 if ( $branch_group_limit ) {
59 if ( $branch_group_limit =~ /^multibranchlimit-/ ) {
60 # For search groups we are going to convert this branch_group_limit CGI
61 # parameter into a multibranchlimit CGI parameter for the purposes of
62 # actually performing the query
63 $cgi->param(
64 -name => 'multibranchlimit',
65 -values => substr($branch_group_limit, 17)
67 } else {
68 $cgi->append(
69 -name => 'limit',
70 -values => [ $branch_group_limit ]
75 BEGIN {
76 if (C4::Context->preference('BakerTaylorEnabled')) {
77 require C4::External::BakerTaylor;
78 import C4::External::BakerTaylor qw(&image_url &link_url);
82 my ($template,$borrowernumber,$cookie);
83 # decide which template to use
84 my $template_name;
85 my $template_type = 'basic';
86 my @params = $cgi->param("limit");
87 my @searchCategories = $cgi->param('searchcat');
89 my $format = $cgi->param("format") || '';
90 my $build_grouped_results = C4::Context->preference('OPACGroupResults');
91 if ($format =~ /(rss|atom|opensearchdescription)/) {
92 $template_name = 'opac-opensearch.tt';
94 elsif (@params && $build_grouped_results) {
95 $template_name = 'opac-results-grouped.tt';
97 elsif ((@params>=1) || ($cgi->param("q")) || ($cgi->param('multibranchlimit')) || ($cgi->param('limit-yr')) ) {
98 $template_name = 'opac-results.tt';
100 else {
101 $template_name = 'opac-advsearch.tt';
102 $template_type = 'advsearch';
104 # load the template
105 ($template, $borrowernumber, $cookie) = get_template_and_user({
106 template_name => $template_name,
107 query => $cgi,
108 type => "opac",
109 authnotrequired => ( C4::Context->preference("OpacPublic") ? 1 : 0 ),
113 my $lang = C4::Languages::getlanguage($cgi);
115 if ($template_name eq 'opac-results.tt') {
116 $template->param('COinSinOPACResults' => C4::Context->preference('COinSinOPACResults'));
119 # get biblionumbers stored in the cart
120 my @cart_list;
122 if($cgi->cookie("bib_list")){
123 my $cart_list = $cgi->cookie("bib_list");
124 @cart_list = split(/\//, $cart_list);
127 if ($format eq 'rss2' or $format eq 'opensearchdescription' or $format eq 'atom') {
128 $template->param($format => 1);
129 $template->param(timestamp => strftime("%Y-%m-%dT%H:%M:%S-00:00", gmtime)) if ($format eq 'atom');
130 # FIXME - the timestamp is a hack - the biblio update timestamp should be used for each
131 # entry, but not sure if that's worth an extra database query for each bib
133 if (C4::Context->preference("marcflavour") eq "UNIMARC" ) {
134 $template->param('UNIMARC' => 1);
136 elsif (C4::Context->preference("marcflavour") eq "MARC21" ) {
137 $template->param('usmarc' => 1);
140 $template->param( 'OPACNoResultsFound' => C4::Context->preference('OPACNoResultsFound') );
142 $template->param(
143 OpacStarRatings => C4::Context->preference("OpacStarRatings") );
145 if (C4::Context->preference('BakerTaylorEnabled')) {
146 $template->param(
147 BakerTaylorEnabled => 1,
148 BakerTaylorImageURL => &image_url(),
149 BakerTaylorLinkURL => &link_url(),
150 BakerTaylorBookstoreURL => C4::Context->preference('BakerTaylorBookstoreURL'),
154 if (C4::Context->preference('TagsEnabled')) {
155 $template->param(TagsEnabled => 1);
156 foreach (qw(TagsShowOnList TagsInputOnList)) {
157 C4::Context->preference($_) and $template->param($_ => 1);
161 ## URI Re-Writing
162 # Deprecated, but preserved because it's interesting :-)
163 # The same thing can be accomplished with mod_rewrite in
164 # a more elegant way
166 #my $rewrite_flag;
167 #my $uri = $cgi->url(-base => 1);
168 #my $relative_url = $cgi->url(-relative=>1);
169 #$uri.="/".$relative_url."?";
170 #warn "URI:$uri";
171 #my @cgi_params_list = $cgi->param();
172 #my $url_params = $cgi->Vars;
174 #for my $each_param_set (@cgi_params_list) {
175 # $uri.= join "", map "\&$each_param_set=".$_, split("\0",$url_params->{$each_param_set}) if $url_params->{$each_param_set};
177 #warn "New URI:$uri";
178 # Only re-write a URI if there are params or if it already hasn't been re-written
179 #unless (($cgi->param('r')) || (!$cgi->param()) ) {
180 # print $cgi->redirect( -uri=>$uri."&r=1",
181 # -cookie => $cookie);
182 # exit;
185 # load the branches
187 if ($cgi->param("returntosearch")) {
188 $template->param('ReturnToSearch' => 1);
190 if ($cgi->cookie("search_path_code")) {
191 my $pathcode = $cgi->cookie("search_path_code");
192 if ($pathcode eq '"ads"') {
193 $template->param('ReturnPath' => '/cgi-bin/koha/opac-search.pl?returntosearch=1');
195 elsif ($pathcode eq '"exs"') {
196 $template->param('ReturnPath' => '/cgi-bin/koha/opac-search.pl?expanded_options=1&returntosearch=1');
198 else {
199 warn "ReturnPath switch error";
203 my $branches = GetBranches(); # used later in *getRecords, probably should be internalized by those functions after caching in C4::Branch is established
204 $template->param(
205 searchdomainloop => GetBranchCategories('searchdomain'),
208 # load the language limits (for search)
209 my $languages_limit_loop = getLanguages($lang, 1);
210 $template->param(search_languages_loop => $languages_limit_loop,);
212 # load the Type stuff
213 my $itemtypes = GetItemTypesCategorized;
214 # the index parameter is different for item-level itemtypes
215 my $itype_or_itemtype = (C4::Context->preference("item-level_itypes"))?'itype':'itemtype';
216 my @advancedsearchesloop;
217 my $cnt;
218 my $advanced_search_types = C4::Context->preference("AdvancedSearchTypes") || "itemtypes";
219 my @advanced_search_types = split(/\|/, $advanced_search_types);
221 my $hidingrules = {};
222 my $yaml = C4::Context->preference('OpacHiddenItems');
223 if ( $yaml =~ /\S/ ) {
224 $yaml = "$yaml\n\n"; # YAML expects trailing newline. Surplus does not hurt.
225 eval {
226 $hidingrules = YAML::Load($yaml);
228 if ($@) {
229 warn "Unable to parse OpacHiddenItems syspref : $@";
233 foreach my $advanced_srch_type (@advanced_search_types) {
234 $advanced_srch_type =~ s/^\s*//;
235 $advanced_srch_type =~ s/\s*$//;
236 if ($advanced_srch_type eq 'itemtypes') {
237 # itemtype is a special case, since it's not defined in authorized values
238 my @itypesloop;
239 foreach my $thisitemtype ( sort {$itemtypes->{$a}->{'description'} cmp $itemtypes->{$b}->{'description'} } keys %$itemtypes ) {
240 next if $hidingrules->{itype} && any { $_ eq $thisitemtype } @{$hidingrules->{itype}};
241 next if $hidingrules->{itemtype} && any { $_ eq $thisitemtype } @{$hidingrules->{itemtype}};
242 my %row =( number=>$cnt++,
243 ccl => "$itype_or_itemtype,phr",
244 code => $thisitemtype,
245 description => $itemtypes->{$thisitemtype}->{'description'},
246 imageurl=> getitemtypeimagelocation( 'opac', $itemtypes->{$thisitemtype}->{'imageurl'} ),
247 cat => $itemtypes->{$thisitemtype}->{'iscat'},
248 hideinopac => $itemtypes->{$thisitemtype}->{'hideinopac'},
249 searchcategory => $itemtypes->{$thisitemtype}->{'searchcategory'},
251 if ( !$itemtypes->{$thisitemtype}->{'hideinopac'} ) {
252 push @itypesloop, \%row;
255 my %search_code = ( advanced_search_type => $advanced_srch_type,
256 code_loop => \@itypesloop );
257 push @advancedsearchesloop, \%search_code;
258 } else {
259 # covers all the other cases: non-itemtype authorized values
260 my $advsearchtypes = GetAuthorisedValues($advanced_srch_type, '', 'opac');
261 my @authvalueloop;
262 for my $thisitemtype (@$advsearchtypes) {
263 my $hiding_key = lc $thisitemtype->{category};
264 $hiding_key = "location" if $hiding_key eq 'loc';
265 next if $hidingrules->{$hiding_key} && any { $_ eq $thisitemtype->{authorised_value} } @{$hidingrules->{$hiding_key}};
266 my %row =(
267 number=>$cnt++,
268 ccl => $advanced_srch_type,
269 code => $thisitemtype->{authorised_value},
270 description => $thisitemtype->{'lib_opac'} || $thisitemtype->{'lib'},
271 searchcategory => $itemtypes->{$thisitemtype}->{'searchcategory'},
272 imageurl => getitemtypeimagelocation( 'opac', $thisitemtype->{'imageurl'} ),
274 push @authvalueloop, \%row;
276 my %search_code = ( advanced_search_type => $advanced_srch_type,
277 code_loop => \@authvalueloop );
278 push @advancedsearchesloop, \%search_code;
281 $template->param(advancedsearchesloop => \@advancedsearchesloop);
283 # The following should only be loaded if we're bringing up the advanced search template
284 if ( $template_type && $template_type eq 'advsearch' ) {
285 # load the servers (used for searching -- to do federated searching, etc.)
286 my $primary_servers_loop;# = displayPrimaryServers();
287 $template->param(outer_servers_loop => $primary_servers_loop,);
289 my $secondary_servers_loop;
290 $template->param(outer_sup_servers_loop => $secondary_servers_loop,);
292 # set the default sorting
293 if ( C4::Context->preference('OPACdefaultSortField')
294 && C4::Context->preference('OPACdefaultSortOrder') ) {
295 my $default_sort_by =
296 C4::Context->preference('OPACdefaultSortField') . '_'
297 . C4::Context->preference('OPACdefaultSortOrder');
298 $template->param( sort_by => $default_sort_by );
301 # determine what to display next to the search boxes (ie, boolean option
302 # shouldn't appear on the first one, scan indexes should, adding a new
303 # box should only appear on the last, etc.
304 my @search_boxes_array;
305 my $search_boxes_count = 3; # begin whith 3 boxes
306 $template->param( search_boxes_count => $search_boxes_count );
308 if ($cgi->cookie("num_paragraph")){
309 $search_boxes_count = $cgi->cookie("num_paragraph");
312 for (my $i=1;$i<=$search_boxes_count;$i++) {
313 # if it's the first one, don't display boolean option, but show scan indexes
314 if ($i==1) {
315 push @search_boxes_array,
317 scan_index => 1,
321 # if it's the last one, show the 'add field' box
322 elsif ($i==$search_boxes_count) {
323 push @search_boxes_array,
325 boolean => 1,
326 add_field => 1,
329 else {
330 push @search_boxes_array,
332 boolean => 1,
338 my @advsearch_limits = split /,/, C4::Context->preference('OpacAdvSearchOptions');
339 my @advsearch_more_limits = split /,/,
340 C4::Context->preference('OpacAdvSearchMoreOptions');
341 $template->param(
342 uc( C4::Context->preference("marcflavour") ) => 1, # we already did this for UNIMARC
343 advsearch => 1,
344 search_boxes_loop => \@search_boxes_array,
345 OpacAdvSearchOptions => \@advsearch_limits,
346 OpacAdvSearchMoreOptions => \@advsearch_more_limits,
349 # use the global setting by default
350 if ( C4::Context->preference("expandedSearchOption") == 1 ) {
351 $template->param( expanded_options => C4::Context->preference("expandedSearchOption") );
353 # but let the user override it
354 if (defined $cgi->param('expanded_options')) {
355 if ( ($cgi->param('expanded_options') == 0) || ($cgi->param('expanded_options') == 1 ) ) {
356 $template->param( expanded_options => $cgi->param('expanded_options'));
360 if (C4::Context->preference('OPACNumbersPreferPhrase')) {
361 $template->param('numbersphr' => 1);
364 output_html_with_http_headers $cgi, $cookie, $template->output;
365 exit;
368 ### OK, if we're this far, we're performing an actual search
370 # Fetch the paramater list as a hash in scalar context:
371 # * returns paramater list as tied hash ref
372 # * we can edit the values by changing the key
373 # * multivalued CGI paramaters are returned as a packaged string separated by "\0" (null)
374 my $params = $cgi->Vars;
375 my $tag;
376 if ( $params->{tag} ) {
377 $tag = $params->{tag};
378 $template->param( tag => $tag );
381 # String with params with the search criteria for the paging in opac-detail
382 # param value is URI encoded and params separator is HTML encode (&amp;)
383 my $pasarParams = '';
384 my $j = 0;
385 for (keys %$params) {
386 my @pasarParam = $cgi->param($_);
387 for my $paramValue(@pasarParam) {
388 $pasarParams .= '&amp;' if ($j > 0);
389 $pasarParams .= $_ . '=' . uri_escape_utf8($paramValue);
390 $j++;
394 # Params that can have more than one value
395 # sort by is used to sort the query
396 # in theory can have more than one but generally there's just one
397 my @sort_by;
398 my $default_sort_by;
399 if ( C4::Context->preference('OPACdefaultSortField')
400 && C4::Context->preference('OPACdefaultSortOrder') ) {
401 $default_sort_by =
402 C4::Context->preference('OPACdefaultSortField') . '_'
403 . C4::Context->preference('OPACdefaultSortOrder');
406 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/;
407 @sort_by = $cgi->param('sort_by');
408 $sort_by[0] = $default_sort_by if !$sort_by[0] && defined($default_sort_by);
409 foreach my $sort (@sort_by) {
410 if ( grep { /^$sort$/ } @allowed_sortby ) {
411 $template->param($sort => 1);
414 $template->param('sort_by' => $sort_by[0]);
416 # Use the servers defined, or just search our local catalog(default)
417 my @servers = $cgi->param('server');
418 unless (@servers) {
419 #FIXME: this should be handled using Context.pm
420 @servers = ("biblioserver");
421 # @servers = C4::Context->config("biblioserver");
424 # operators include boolean and proximity operators and are used
425 # to evaluate multiple operands
426 my @operators = $cgi->param('op');
427 @operators = map { uri_unescape($_) } @operators;
429 # indexes are query qualifiers, like 'title', 'author', etc. They
430 # can be single or multiple parameters separated by comma: kw,right-Truncation
431 my @indexes = $cgi->param('idx');
432 @indexes = map { uri_unescape($_) } @indexes;
434 # if a simple index (only one) display the index used in the top search box
435 if ($indexes[0] && !$indexes[1]) {
436 $template->param("ms_".$indexes[0] => 1);
438 # an operand can be a single term, a phrase, or a complete ccl query
439 my @operands = $cgi->param('q');
440 @operands = map { uri_unescape($_) } @operands;
442 $template->{VARS}->{querystring} = join(' ', @operands);
444 # if a simple search, display the value in the search box
445 if ($operands[0] && !$operands[1]) {
446 my $ms_query = $operands[0];
447 $ms_query =~ s/ #\S+//;
448 $template->param(ms_value => $ms_query);
451 # limits are use to limit to results to a pre-defined category such as branch or language
452 my @limits = $cgi->param('limit');
453 @limits = map { uri_unescape($_) } @limits;
454 my @nolimits = $cgi->param('nolimit');
455 @nolimits = map { uri_unescape($_) } @nolimits;
456 my %is_nolimit = map { $_ => 1 } @nolimits;
457 @limits = grep { not $is_nolimit{$_} } @limits;
459 if (@searchCategories > 0) {
460 my @tabcat;
461 foreach my $typecategory (@searchCategories) {
462 push (@tabcat, GetItemTypesByCategory($typecategory));
465 foreach my $itemtypeInCategory (@tabcat) {
466 push (@limits, "mc-$itype_or_itemtype,phr:".$itemtypeInCategory);
470 @limits = map { uri_unescape($_) } @limits;
472 if($params->{'multibranchlimit'}) {
473 my $multibranch = '('.join( " or ", map { "branch: $_ " } @{ GetBranchesInCategory( $params->{'multibranchlimit'} ) } ).')';
474 push @limits, $multibranch if ($multibranch ne '()');
477 my $available;
478 foreach my $limit(@limits) {
479 if ($limit =~/available/) {
480 $available = 1;
483 $template->param(available => $available);
485 # append year limits if they exist
486 if ($params->{'limit-yr'}) {
487 if ($params->{'limit-yr'} =~ /\d{4}-\d{4}/) {
488 my ($yr1,$yr2) = split(/-/, $params->{'limit-yr'});
489 push @limits, "yr,st-numeric,ge=$yr1 and yr,st-numeric,le=$yr2";
491 elsif ($params->{'limit-yr'} =~ /\d{4}/) {
492 push @limits, "yr,st-numeric=$params->{'limit-yr'}";
494 else {
495 #FIXME: Should return a error to the user, incorect date format specified
499 # Params that can only have one value
500 my $scan = $params->{'scan'};
501 my $count = C4::Context->preference('OPACnumSearchResults') || 20;
502 my $countRSS = C4::Context->preference('numSearchRSSResults') || 50;
503 my $results_per_page = $params->{'count'} || $count;
504 my $offset = $params->{'offset'} || 0;
505 my $page = $cgi->param('page') || 1;
506 $offset = ($page-1)*$results_per_page if $page>1;
507 my $hits;
508 my $expanded_facet = $params->{'expand'};
510 # Define some global variables
511 my ($error,$query,$simple_query,$query_cgi,$query_desc,$limit,$limit_cgi,$limit_desc,$stopwords_removed,$query_type);
513 my @results;
515 ## I. BUILD THE QUERY
516 ( $error,$query,$simple_query,$query_cgi,$query_desc,$limit,$limit_cgi,$limit_desc,$stopwords_removed,$query_type) = buildQuery(\@operators,\@operands,\@indexes,\@limits,\@sort_by, 0, $lang);
518 sub _input_cgi_parse {
519 my @elements;
520 for my $this_cgi ( split('&',shift) ) {
521 next unless $this_cgi;
522 $this_cgi =~ /(.*?)=(.*)/;
523 push @elements, { input_name => $1, input_value => Encode::decode_utf8( uri_unescape($2) ) };
525 return @elements;
528 ## parse the query_cgi string and put it into a form suitable for <input>s
529 my @query_inputs = _input_cgi_parse($query_cgi);
530 $template->param ( QUERY_INPUTS => \@query_inputs );
532 ## parse the limit_cgi string and put it into a form suitable for <input>s
533 my @limit_inputs = $limit_cgi ? _input_cgi_parse($limit_cgi) : ();
535 # add OPAC 'hidelostitems'
536 #if (C4::Context->preference('hidelostitems') == 1) {
537 # # either lost ge 0 or no value in the lost register
538 # $query ="($query) and ( (lost,st-numeric <= 0) or ( allrecords,AlwaysMatches='' not lost,AlwaysMatches='') )";
541 # add OPAC suppression - requires at least one item indexed with Suppress
542 if (C4::Context->preference('OpacSuppression')) {
543 # OPAC suppression by IP address
544 if (C4::Context->preference('OpacSuppressionByIPRange')) {
545 my $IPAddress = $ENV{'REMOTE_ADDR'};
546 my $IPRange = C4::Context->preference('OpacSuppressionByIPRange');
547 if ($IPAddress !~ /^$IPRange/) {
548 if ( $query_type eq 'pqf' ) {
549 $query = '@not '.$query.' @attr 1=9011 1';
550 } else {
551 $query = "($query) not Suppress=1";
555 else {
556 if ( $query_type eq 'pqf' ) {
557 #$query = "($query) && -(suppress:1)"; #QP syntax
558 $query = '@not '.$query.' @attr 1=9011 1'; #PQF syntax
559 } else {
560 $query = "($query) not Suppress=1";
565 $template->param ( LIMIT_INPUTS => \@limit_inputs );
566 $template->param ( OPACResultsSidebar => C4::Context->preference('OPACResultsSidebar'));
568 ## II. DO THE SEARCH AND GET THE RESULTS
569 my $total = 0; # the total results for the whole set
570 my $facets; # this object stores the faceted results that display on the left-hand of the results page
571 my @results_array;
572 my $results_hashref;
573 my @coins;
575 if ($tag) {
576 $query_cgi = "tag=" .$tag . "&" . $query_cgi;
577 my $taglist = get_tags({term=>$tag, approved=>1});
578 $results_hashref->{biblioserver}->{hits} = scalar (@$taglist);
579 my @biblist = (map {GetBiblioData($_->{biblionumber})} @$taglist);
580 my @marclist = (map { (C4::Context->config('zebra_bib_index_mode') eq 'dom')? $_->{marcxml}: $_->{marc}; } @biblist);
581 $DEBUG and printf STDERR "taglist (%s biblionumber)\nmarclist (%s records)\n", scalar(@$taglist), scalar(@marclist);
582 $results_hashref->{biblioserver}->{RECORDS} = \@marclist;
583 # FIXME: tag search and standard search should work together, not exclusively
584 # FIXME: No facets for tags search.
585 } elsif ($build_grouped_results) {
586 eval {
587 ($error, $results_hashref, $facets) = C4::Search::pazGetRecords($query,$simple_query,\@sort_by,\@servers,$results_per_page,$offset,$expanded_facet,$branches,$query_type,$scan);
589 } else {
590 $pasarParams .= '&amp;query=' . uri_escape_utf8($query);
591 $pasarParams .= '&amp;count=' . uri_escape_utf8($results_per_page);
592 $pasarParams .= '&amp;simple_query=' . uri_escape_utf8($simple_query);
593 $pasarParams .= '&amp;query_type=' . uri_escape_utf8($query_type) if ($query_type);
594 eval {
595 ($error, $results_hashref, $facets) = getRecords($query,$simple_query,\@sort_by,\@servers,$results_per_page,$offset,$expanded_facet,$branches,$itemtypes,$query_type,$scan,1);
598 # This sorts the facets into alphabetical order
599 if ($facets) {
600 foreach my $f (@$facets) {
601 $f->{facets} = [ sort { uc($a->{facet_label_value}) cmp uc($b->{facet_label_value}) } @{ $f->{facets} } ];
603 @$facets = sort {$a->{expand} cmp $b->{expand}} @$facets;
606 # use Data::Dumper; print STDERR "-" x 25, "\n", Dumper($results_hashref);
607 if ($@ || $error) {
608 $template->param(query_error => $error.$@);
609 output_html_with_http_headers $cgi, $cookie, $template->output;
610 exit;
613 # At this point, each server has given us a result set
614 # now we build that set for template display
615 my @sup_results_array;
616 for (my $i=0;$i<@servers;$i++) {
617 my $server = $servers[$i];
618 if ($server && $server =~/biblioserver/) { # this is the local bibliographic server
619 $hits = $results_hashref->{$server}->{"hits"};
620 my $page = $cgi->param('page') || 0;
621 my @newresults;
622 if ($build_grouped_results) {
623 foreach my $group (@{ $results_hashref->{$server}->{"GROUPS"} }) {
624 # because pazGetRecords handles retieving only the records
625 # we want as specified by $offset and $results_per_page,
626 # we need to set the offset parameter of searchResults to 0
627 my @group_results = searchResults( 'opac', $query_desc, $group->{'group_count'},$results_per_page, 0, $scan,
628 $group->{"RECORDS"});
629 push @newresults, { group_label => $group->{'group_label'}, GROUP_RESULTS => \@group_results };
631 } else {
632 @newresults = searchResults('opac', $query_desc, $hits, $results_per_page, $offset, $scan,
633 $results_hashref->{$server}->{"RECORDS"});
635 $hits = 0 unless @newresults;
637 foreach my $res (@newresults) {
639 # must define a value for size if not present in DB
640 # in order to avoid problems generated by the default size value in TT
641 if ( not exists $res->{'size'} ) { $res->{'size'} = "" }
642 # while we're checking each line, see if item is in the cart
643 if ( grep {$_ eq $res->{'biblionumber'}} @cart_list) {
644 $res->{'incart'} = 1;
647 if (C4::Context->preference('COinSinOPACResults')) {
648 my $record = GetMarcBiblio($res->{'biblionumber'});
649 $res->{coins} = GetCOinSBiblio($record);
651 if ( C4::Context->preference( "Babeltheque" ) and $res->{normalized_isbn} ) {
652 if( my $isbn = Business::ISBN->new( $res->{normalized_isbn} ) ) {
653 $isbn = $isbn->as_isbn13->as_string;
654 $isbn =~ s/-//g;
655 my $social_datas = C4::SocialData::get_data( $isbn );
656 if ( $social_datas ) {
657 for my $key ( keys %$social_datas ) {
658 $res->{$key} = $$social_datas{$key};
659 if ( $key eq 'score_avg' ){
660 $res->{score_int} = sprintf("%.0f", $$social_datas{score_avg} );
667 if (C4::Context->preference('TagsEnabled') and
668 C4::Context->preference('TagsShowOnList')) {
669 if ( my $bibnum = $res->{biblionumber} ) {
670 $res->{itemsissued} = CountItemsIssued( $bibnum );
671 $res->{'TagLoop'} = get_tags({
672 biblionumber => $bibnum,
673 approved => 1,
674 sort => '-weight',
675 limit => C4::Context->preference('TagsShowOnList')
680 if ( C4::Context->preference('OpacStarRatings') eq 'all' ) {
681 my $rating = GetRating( $res->{'biblionumber'}, $borrowernumber );
682 $res->{'rating_value'} = $rating->{'rating_value'};
683 $res->{'rating_total'} = $rating->{'rating_total'};
684 $res->{'rating_avg'} = $rating->{'rating_avg'};
685 $res->{'rating_avg_int'} = $rating->{'rating_avg_int'};
689 if ($results_hashref->{$server}->{"hits"}){
690 $total = $total + $hits;
693 # Opac search history
694 if (C4::Context->preference('EnableOpacSearchHistory')) {
695 unless ( $offset ) {
696 my $path_info = $cgi->url(-path_info=>1);
697 my $query_cgi_history = $cgi->url(-query=>1);
698 $query_cgi_history =~ s/^$path_info\?//;
699 $query_cgi_history =~ s/;/&/g;
700 my $query_desc_history = join ", ", grep { defined $_ } $query_desc, $limit_desc;
702 unless ( $borrowernumber ) {
703 my $new_searches = C4::Search::History::add_to_session({
704 cgi => $cgi,
705 query_desc => $query_desc_history,
706 query_cgi => $query_cgi_history,
707 total => $total,
708 type => "biblio",
710 } else {
711 # To the session (the user is logged in)
712 C4::Search::History::add({
713 userid => $borrowernumber,
714 sessionid => $cgi->cookie("CGISESSID"),
715 query_desc => $query_desc_history,
716 query_cgi => $query_cgi_history,
717 total => $total,
718 type => "biblio",
722 $template->param( EnableOpacSearchHistory => 1 );
725 ## If there's just one result, redirect to the detail page
726 if ($total == 1 && $format ne 'rss2'
727 && $format ne 'opensearchdescription' && $format ne 'atom') {
728 my $biblionumber=$newresults[0]->{biblionumber};
729 if (C4::Context->preference('BiblioDefaultView') eq 'isbd') {
730 print $cgi->redirect("/cgi-bin/koha/opac-ISBDdetail.pl?biblionumber=$biblionumber");
731 } elsif (C4::Context->preference('BiblioDefaultView') eq 'marc') {
732 print $cgi->redirect("/cgi-bin/koha/opac-MARCdetail.pl?biblionumber=$biblionumber");
733 } else {
734 print $cgi->redirect("/cgi-bin/koha/opac-detail.pl?biblionumber=$biblionumber");
736 exit;
738 if ($hits) {
739 if ( !$build_grouped_results ) {
740 # We build the encrypted list of first OPACnumSearchResults biblios to pass with the search criteria for paging on opac-detail
741 $pasarParams .= '&amp;listBiblios=';
742 my $j = 0;
743 foreach (@newresults) {
744 my $bibnum = ($_->{biblionumber})?$_->{biblionumber}:0;
745 $pasarParams .= uri_escape_utf8($bibnum) . ',';
746 $j++;
747 last if ($j == $results_per_page);
749 chop $pasarParams if ($pasarParams =~ /,$/);
750 $pasarParams .= '&amp;total=' . uri_escape_utf8( int($total) ) if ($pasarParams !~ /total=(?:[0-9]+)?/);
751 if ($pasarParams) {
752 my $session = get_session($cgi->cookie("CGISESSID"));
753 $session->param('busc' => $pasarParams);
757 $template->param(total => $hits);
758 my $limit_cgi_not_availablity = $limit_cgi;
759 $limit_cgi_not_availablity =~ s/&limit=available//g if defined $limit_cgi_not_availablity;
760 $template->param(limit_cgi_not_availablity => $limit_cgi_not_availablity);
761 $template->param(limit_cgi => $limit_cgi);
762 $template->param(countrss => $countRSS );
763 $template->param(query_cgi => $query_cgi);
764 $template->param(query_desc => $query_desc);
765 $template->param(limit_desc => $limit_desc);
766 $template->param(offset => $offset);
767 $template->param(DisplayMultiPlaceHold => $DisplayMultiPlaceHold);
768 if ($query_desc || $limit_desc) {
769 $template->param(searchdesc => 1);
771 $template->param(stopwords_removed => "@$stopwords_removed") if $stopwords_removed;
772 $template->param(results_per_page => $results_per_page);
773 my $hide = C4::Context->preference('OpacHiddenItems');
774 $hide = ($hide =~ m/\S/) if $hide; # Just in case it has some spaces/new lines
775 my $branch = '';
776 if (C4::Context->userenv){
777 $branch = C4::Context->userenv->{branch};
779 if ( C4::Context->preference('HighlightOwnItemsOnOPAC') ) {
780 if (
781 ( ( C4::Context->preference('HighlightOwnItemsOnOPACWhich') eq 'PatronBranch' ) && $branch )
783 C4::Context->preference('HighlightOwnItemsOnOPACWhich') eq 'OpacURLBranch'
785 my $branchname;
786 if ( C4::Context->preference('HighlightOwnItemsOnOPACWhich') eq 'PatronBranch' ) {
787 $branchname = $branches->{$branch}->{'branchname'};
789 elsif ( C4::Context->preference('HighlightOwnItemsOnOPACWhich') eq 'OpacURLBranch' ) {
790 $branchname = $branches->{ $ENV{'BRANCHCODE'} }->{'branchname'};
793 foreach my $res ( @newresults ) {
794 my @new_loop;
795 my @top_loop;
796 my @old_loop = @{$res->{'available_items_loop'}};
797 foreach my $item ( @old_loop ) {
798 if ( $item->{'branchname'} eq $branchname ) {
799 $item->{'this_branch'} = 1;
800 push( @top_loop, $item );
801 } else {
802 push( @new_loop, $item );
805 my @complete_loop = ( @top_loop, @new_loop );
806 $res->{'available_items_loop'} = \@complete_loop;
811 $template->param(
812 SEARCH_RESULTS => \@newresults,
813 OPACItemsResultsDisplay => (C4::Context->preference("OPACItemsResultsDisplay")),
814 suppress_result_number => $hide,
816 if (C4::Context->preference("OPACLocalCoverImages")){
817 $template->param(OPACLocalCoverImages => 1);
818 $template->param(OPACLocalCoverImagesPriority => C4::Context->preference("OPACLocalCoverImagesPriority"));
820 ## Build the page numbers on the bottom of the page
821 my @page_numbers;
822 # total number of pages there will be
823 my $pages = ceil($hits / $results_per_page);
824 # default page number
825 my $current_page_number = 1;
826 if ($offset) {
827 $current_page_number = ( $offset / $results_per_page + 1 );
829 my $previous_page_offset;
830 if ( $offset >= $results_per_page ) {
831 $previous_page_offset = $offset - $results_per_page;
833 my $next_page_offset = $offset + $results_per_page;
834 # If we're within the first 10 pages, keep it simple
835 #warn "current page:".$current_page_number;
836 if ($current_page_number < 10) {
837 # just show the first 10 pages
838 # Loop through the pages
839 my $pages_to_show = 10;
840 $pages_to_show = $pages if $pages<10;
841 for ($i=1; $i<=$pages_to_show;$i++) {
842 # the offset for this page
843 my $this_offset = (($i*$results_per_page)-$results_per_page);
844 # the page number for this page
845 my $this_page_number = $i;
846 # put it in the array
847 push @page_numbers,
848 { offset => $this_offset,
849 pg => $this_page_number,
850 highlight => $this_page_number == $current_page_number,
851 sort_by => join ' ', @sort_by
857 # now, show twenty pages, with the current one smack in the middle
858 else {
859 for ($i=$current_page_number; $i<=($current_page_number + 20 );$i++) {
860 my $this_offset = ((($i-9)*$results_per_page)-$results_per_page);
861 my $this_page_number = $i-9;
862 if ( $this_page_number <= $pages ) {
863 push @page_numbers,
864 { offset => $this_offset,
865 pg => $this_page_number,
866 highlight => $this_page_number == $current_page_number,
867 sort_by => join ' ', @sort_by
873 $template->param( PAGE_NUMBERS => \@page_numbers,
874 previous_page_offset => $previous_page_offset) unless $pages < 2;
875 $template->param(next_page_offset => $next_page_offset) unless $pages eq $current_page_number;
877 # no hits
878 else {
879 my $nohits = C4::Context->preference('OPACNoResultsFound');
880 if ($nohits and $nohits=~/{QUERY_KW}/){
881 # extracting keywords in case of relaunching search
882 (my $query_kw=$query_desc)=~s/ and|or / /g;
883 $query_kw = Encode::decode_utf8($query_kw);
884 my @query_kw=($query_kw=~ /([-\w]+\b)(?:[^,:]|$)/g);
885 $query_kw=join('+',@query_kw);
886 $nohits=~s/{QUERY_KW}/$query_kw/g;
887 $template->param('OPACNoResultsFound' =>$nohits);
889 $template->param(
890 searchdesc => 1,
891 query_desc => $query_desc,
892 limit_desc => $limit_desc,
893 query_cgi => $query_cgi,
894 limit_cgi => $limit_cgi
897 } # end of the if local
898 # asynchronously search the authority server
899 elsif ($server && $server =~/authorityserver/) { # this is the local authority server
900 my @inner_sup_results_array;
901 for my $sup_record ( @{$results_hashref->{$server}->{"RECORDS"}} ) {
902 my $marc_record_object = MARC::Record->new_from_usmarc($sup_record);
903 my $title_field = $marc_record_object->field(100);
904 push @inner_sup_results_array, {
905 'title' => $title_field->subfield('a'),
906 'link' => "&amp;idx=an&amp;q=".$marc_record_object->field('001')->as_string(),
909 my $servername = $server;
910 push @sup_results_array, { servername => $servername,
911 inner_sup_results_loop => \@inner_sup_results_array} if @inner_sup_results_array;
913 # FIXME: can add support for other targets as needed here
914 $template->param( outer_sup_results_loop => \@sup_results_array);
915 } #/end of the for loop
916 #$template->param(FEDERATED_RESULTS => \@results_array);
918 for my $facet ( @$facets ) {
919 for my $entry ( @{ $facet->{facets} } ) {
920 my $index = $entry->{type_link_value};
921 my $value = $entry->{facet_link_value};
922 $entry->{active} = grep { $_->{input_value} eq qq{$index:$value} } @limit_inputs;
927 $template->param(
928 #classlist => $classlist,
929 total => $total,
930 opacfacets => 1,
931 facets_loop => $facets,
932 displayFacetCount=> C4::Context->preference('displayFacetCount')||0,
933 scan => $scan,
934 search_error => $error,
937 if ($query_desc || $limit_desc) {
938 $template->param(searchdesc => 1);
941 # VI. BUILD THE TEMPLATE
942 # Build drop-down list for 'Add To:' menu...
943 my ($totalref, $pubshelves, $barshelves)=
944 C4::VirtualShelves::GetSomeShelfNames($borrowernumber,'COMBO',1);
945 $template->param(
946 addbarshelves => $totalref->{bartotal},
947 addbarshelvesloop => $barshelves,
948 addpubshelves => $totalref->{pubtotal},
949 addpubshelvesloop => $pubshelves,
952 my $content_type = ($format eq 'rss' or $format eq 'atom') ? $format : 'html';
954 # If GoogleIndicTransliteration system preference is On Set paramter to load Google's javascript in OPAC search screens
955 if (C4::Context->preference('GoogleIndicTransliteration')) {
956 $template->param('GoogleIndicTransliteration' => 1);
959 $template->{VARS}->{DidYouMean} =
960 ( defined C4::Context->preference('OPACdidyoumean')
961 && C4::Context->preference('OPACdidyoumean') =~ m/enable/ );
962 $template->{VARS}->{IDreamBooksReviews} = C4::Context->preference('IDreamBooksReviews');
963 $template->{VARS}->{IDreamBooksReadometer} = C4::Context->preference('IDreamBooksReadometer');
964 $template->{VARS}->{IDreamBooksResults} = C4::Context->preference('IDreamBooksResults');
966 if ($offset == 0 && IsOverDriveEnabled()) {
967 $template->param(OverDriveEnabled => 1);
968 $template->param(OverDriveLibraryID => C4::Context->preference('OverDriveLibraryID'));
971 $template->param( borrowernumber => $borrowernumber);
972 output_with_http_headers $cgi, $cookie, $template->output, $content_type;