Bug 12478 - authorities can now be stored in ES
[koha.git] / opac / opac-search.pl
1 #!/usr/bin/perl
2
3 # Copyright 2008 Garry Collum and the Koha Development team
4 # Copyright 2010 BibLibre
5 # Copyright 2011 KohaAloha, NZ
6 #
7 # This file is part of Koha.
8 #
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.
13 #
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.
18 #
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>.
21
22 # Script to perform searching
23 # Mostly copied from search.pl, see POD there
24 use Modern::Perl;
25
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/;
32
33 use Data::Dumper; # TODO remove
34
35 use Koha::ElasticSearch::Search;
36 use Koha::SearchEngine::QueryBuilder;
37 use Koha::SearchEngine::Zebra::Search;
38
39 my $searchengine = C4::Context->preference("SearchEngine");
40 my ($builder, $searcher);
41 #$searchengine = 'Zebra'; # XXX
42 $builder = Koha::SearchEngine::QueryBuilder->new();
43 for ( $searchengine ) {
44     when ( /^Solr$/ ) {
45         warn "We use Solr";
46         require 'opac/search.pl';
47         exit;
48     }
49     when ( /^Zebra$/ ) {
50         $searcher=Koha::SearchEngine::Zebra::Search->new();
51     }
52     when (/^Elasticsearch$/) {
53         $searcher=Koha::ElasticSearch::Search->new({index => 'biblios'});
54     }
55 }
56
57 use C4::Output;
58 use C4::Auth qw(:DEFAULT get_session);
59 use C4::Languages qw(getLanguages);
60 use C4::Search;
61 use C4::Search::History;
62 use C4::Biblio;  # GetBiblioData
63 use C4::Koha;
64 use C4::Tags qw(get_tags);
65 use C4::Branch; # GetBranches
66 use C4::SocialData;
67 use C4::Ratings;
68 use C4::External::OverDrive;
69
70 use Koha::LibraryCategories;
71
72 use POSIX qw(ceil floor strftime);
73 use URI::Escape;
74 use JSON qw/decode_json encode_json/;
75 use Business::ISBN;
76
77 my $DisplayMultiPlaceHold = C4::Context->preference("DisplayMultiPlaceHold");
78 # create a new CGI object
79 # FIXME: no_undef_params needs to be tested
80 use CGI qw('-no_undef_params' -utf8);
81 my $cgi = new CGI;
82
83 my $branch_group_limit = $cgi->param("branch_group_limit");
84 if ( $branch_group_limit ) {
85     if ( $branch_group_limit =~ /^multibranchlimit-/ ) {
86         # For search groups we are going to convert this branch_group_limit CGI
87         # parameter into a multibranchlimit CGI parameter for the purposes of
88         # actually performing the query
89         $cgi->param(
90             -name => 'multibranchlimit',
91             -values => substr($branch_group_limit, 17)
92         );
93     } else {
94         $cgi->append(
95             -name => 'limit',
96             -values => [ $branch_group_limit ]
97         );
98     }
99 }
100
101 BEGIN {
102     if (C4::Context->preference('BakerTaylorEnabled')) {
103         require C4::External::BakerTaylor;
104         import C4::External::BakerTaylor qw(&image_url &link_url);
105     }
106 }
107
108 my ($template,$borrowernumber,$cookie);
109 # decide which template to use
110 my $template_name;
111 my $template_type = 'basic';
112 my @params = $cgi->param("limit");
113 my @searchCategories = $cgi->param('searchcat');
114
115 my $format = $cgi->param("format") || '';
116 my $build_grouped_results = C4::Context->preference('OPACGroupResults');
117 if ($format =~ /(rss|atom|opensearchdescription)/) {
118     $template_name = 'opac-opensearch.tt';
119 }
120 elsif (@params && $build_grouped_results) {
121     $template_name = 'opac-results-grouped.tt';
122 }
123 elsif ((@params>=1) || ($cgi->param("q")) || ($cgi->param('multibranchlimit')) || ($cgi->param('limit-yr')) ) {
124     $template_name = 'opac-results.tt';
125 }
126 else {
127     $template_name = 'opac-advsearch.tt';
128     $template_type = 'advsearch';
129 }
130 # load the template
131 ($template, $borrowernumber, $cookie) = get_template_and_user({
132     template_name => $template_name,
133     query => $cgi,
134     type => "opac",
135     authnotrequired => ( C4::Context->preference("OpacPublic") ? 1 : 0 ),
136     }
137 );
138
139 my $lang = C4::Languages::getlanguage($cgi);
140
141 if ($template_name eq 'opac-results.tt') {
142    $template->param('COinSinOPACResults' => C4::Context->preference('COinSinOPACResults'));
143 }
144
145 # get biblionumbers stored in the cart
146 my @cart_list;
147
148 if($cgi->cookie("bib_list")){
149     my $cart_list = $cgi->cookie("bib_list");
150     @cart_list = split(/\//, $cart_list);
151 }
152
153 if ($format eq 'rss2' or $format eq 'opensearchdescription' or $format eq 'atom') {
154     $template->param($format => 1);
155     $template->param(timestamp => strftime("%Y-%m-%dT%H:%M:%S-00:00", gmtime)) if ($format eq 'atom'); 
156     # FIXME - the timestamp is a hack - the biblio update timestamp should be used for each
157     # entry, but not sure if that's worth an extra database query for each bib
158 }
159 if (C4::Context->preference("marcflavour") eq "UNIMARC" ) {
160     $template->param('UNIMARC' => 1);
161 }
162 elsif (C4::Context->preference("marcflavour") eq "MARC21" ) {
163     $template->param('usmarc' => 1);
164 }
165
166 $template->param( 'OPACNoResultsFound' => C4::Context->preference('OPACNoResultsFound') );
167
168 $template->param(
169     OpacStarRatings => C4::Context->preference("OpacStarRatings") );
170
171 if (C4::Context->preference('BakerTaylorEnabled')) {
172     $template->param(
173         BakerTaylorEnabled  => 1,
174         BakerTaylorImageURL => &image_url(),
175         BakerTaylorLinkURL  => &link_url(),
176         BakerTaylorBookstoreURL => C4::Context->preference('BakerTaylorBookstoreURL'),
177     );
178 }
179
180 if (C4::Context->preference('TagsEnabled')) {
181     $template->param(TagsEnabled => 1);
182     foreach (qw(TagsShowOnList TagsInputOnList)) {
183         C4::Context->preference($_) and $template->param($_ => 1);
184     }
185 }
186
187 ## URI Re-Writing
188 # Deprecated, but preserved because it's interesting :-)
189 # The same thing can be accomplished with mod_rewrite in
190 # a more elegant way
191 #                  
192 #my $rewrite_flag;
193 #my $uri = $cgi->url(-base => 1);
194 #my $relative_url = $cgi->url(-relative=>1);
195 #$uri.="/".$relative_url."?";
196 #warn "URI:$uri";
197 #my @cgi_params_list = $cgi->param();
198 #my $url_params = $cgi->Vars;
199 #
200 #for my $each_param_set (@cgi_params_list) {
201 #    $uri.= join "",  map "\&$each_param_set=".$_, split("\0",$url_params->{$each_param_set}) if $url_params->{$each_param_set};
202 #}
203 #warn "New URI:$uri";
204 # Only re-write a URI if there are params or if it already hasn't been re-written
205 #unless (($cgi->param('r')) || (!$cgi->param()) ) {
206 #    print $cgi->redirect(     -uri=>$uri."&r=1",
207 #                            -cookie => $cookie);
208 #    exit;
209 #}
210
211 # load the branches
212
213 if ($cgi->param("returntosearch")) {
214     $template->param('ReturnToSearch' => 1);
215 }
216 if ($cgi->cookie("search_path_code")) {
217     my $pathcode = $cgi->cookie("search_path_code");
218     if ($pathcode eq '"ads"') {
219         $template->param('ReturnPath' => '/cgi-bin/koha/opac-search.pl?returntosearch=1');
220     }
221     elsif ($pathcode eq '"exs"') {
222          $template->param('ReturnPath' => '/cgi-bin/koha/opac-search.pl?expanded_options=1&returntosearch=1');
223     }
224     else {
225         warn "ReturnPath switch error";
226     }
227 }
228
229 my $branches = GetBranches();   # used later in *getRecords, probably should be internalized by those functions after caching in C4::Branch is established
230 my $library_categories = Koha::LibraryCategories->search( { categorytype => 'searchdomain' }, { order_by => [ 'categorytype', 'categorycode' ] } );
231 $template->param( searchdomainloop => $library_categories );
232
233 # load the language limits (for search)
234 my $languages_limit_loop = getLanguages($lang, 1);
235 $template->param(search_languages_loop => $languages_limit_loop,);
236
237 # load the Type stuff
238 my $itemtypes = GetItemTypesCategorized;
239 # add translated_description to itemtypes
240 foreach my $itemtype ( keys %{$itemtypes} ) {
241     # Itemtypes search categories don't have (yet) translated descriptions, they are auth values
242     my $translated_description = getitemtypeinfo( $itemtype, 'opac' )->{translated_description};
243     $itemtypes->{$itemtype}->{translated_description} =
244             ( $translated_description ) ? $translated_description : $itemtypes->{$itemtype}->{description};
245 }
246 # Load the Type stuff without search categories for facets
247 my $itemtypes_nocategory = GetItemTypes;
248 # the index parameter is different for item-level itemtypes
249 my $itype_or_itemtype = (C4::Context->preference("item-level_itypes"))?'itype':'itemtype';
250 my @advancedsearchesloop;
251 my $cnt;
252 my $advanced_search_types = C4::Context->preference("AdvancedSearchTypes") || "itemtypes";
253 my @advanced_search_types = split(/\|/, $advanced_search_types);
254
255 my $hidingrules = {};
256 my $yaml = C4::Context->preference('OpacHiddenItems');
257 if ( $yaml =~ /\S/ ) {
258     $yaml = "$yaml\n\n"; # YAML expects trailing newline. Surplus does not hurt.
259     eval {
260         $hidingrules = YAML::Load($yaml);
261     };
262     if ($@) {
263         warn "Unable to parse OpacHiddenItems syspref : $@";
264     }
265 }
266
267 foreach my $advanced_srch_type (@advanced_search_types) {
268     $advanced_srch_type =~ s/^\s*//;
269     $advanced_srch_type =~ s/\s*$//;
270    if ($advanced_srch_type eq 'itemtypes') {
271    # itemtype is a special case, since it's not defined in authorized values
272         my @itypesloop;
273         foreach my $thisitemtype ( sort {$itemtypes->{$a}->{translated_description} cmp $itemtypes->{$b}->{translated_description} } keys %$itemtypes ) {
274             next if $hidingrules->{itype} && any { $_ eq $thisitemtype } @{$hidingrules->{itype}};
275             next if $hidingrules->{itemtype} && any { $_ eq $thisitemtype } @{$hidingrules->{itemtype}};
276             my %row =(  number=>$cnt++,
277                 ccl => "$itype_or_itemtype,phr",
278                 code => $thisitemtype,
279                 description => $itemtypes->{$thisitemtype}->{translated_description},
280                 imageurl=> getitemtypeimagelocation( 'opac', $itemtypes->{$thisitemtype}->{'imageurl'} ),
281                 cat => $itemtypes->{$thisitemtype}->{'iscat'},
282                 hideinopac => $itemtypes->{$thisitemtype}->{'hideinopac'},
283                 searchcategory => $itemtypes->{$thisitemtype}->{'searchcategory'},
284             );
285             if ( !$itemtypes->{$thisitemtype}->{'hideinopac'} ) {
286                 push @itypesloop, \%row;
287             }
288         }
289         my %search_code = (  advanced_search_type => $advanced_srch_type,
290                              code_loop => \@itypesloop );
291         push @advancedsearchesloop, \%search_code;
292     } else {
293     # covers all the other cases: non-itemtype authorized values
294        my $advsearchtypes = GetAuthorisedValues($advanced_srch_type, 'opac');
295         my @authvalueloop;
296         for my $thisitemtype (@$advsearchtypes) {
297             my $hiding_key = lc $thisitemtype->{category};
298             $hiding_key = "location" if $hiding_key eq 'loc';
299             next if $hidingrules->{$hiding_key} && any { $_ eq $thisitemtype->{authorised_value} } @{$hidingrules->{$hiding_key}};
300                 my %row =(
301                                 number=>$cnt++,
302                                 ccl => $advanced_srch_type,
303                 code => $thisitemtype->{authorised_value},
304                 description => $thisitemtype->{'lib_opac'} || $thisitemtype->{'lib'},
305                 searchcategory => $itemtypes->{$thisitemtype}->{'searchcategory'},
306                 imageurl => getitemtypeimagelocation( 'opac', $thisitemtype->{'imageurl'} ),
307                 );
308                 push @authvalueloop, \%row;
309         }
310         my %search_code = (  advanced_search_type => $advanced_srch_type,
311                              code_loop => \@authvalueloop );
312         push @advancedsearchesloop, \%search_code;
313     }
314 }
315 $template->param(advancedsearchesloop => \@advancedsearchesloop);
316
317 # The following should only be loaded if we're bringing up the advanced search template
318 if ( $template_type && $template_type eq 'advsearch' ) {
319     # load the servers (used for searching -- to do federated searching, etc.)
320     my $primary_servers_loop;# = displayPrimaryServers();
321     $template->param(outer_servers_loop =>  $primary_servers_loop,);
322     
323     my $secondary_servers_loop;
324     $template->param(outer_sup_servers_loop => $secondary_servers_loop,);
325
326     # set the default sorting
327     if (   C4::Context->preference('OPACdefaultSortField')
328         && C4::Context->preference('OPACdefaultSortOrder') ) {
329         my $default_sort_by =
330             C4::Context->preference('OPACdefaultSortField') . '_'
331           . C4::Context->preference('OPACdefaultSortOrder');
332         $template->param( sort_by => $default_sort_by );
333     }
334
335     # determine what to display next to the search boxes (ie, boolean option
336     # shouldn't appear on the first one, scan indexes should, adding a new
337     # box should only appear on the last, etc.
338     my @search_boxes_array;
339     my $search_boxes_count = 3; # begin whith 3 boxes
340     $template->param( search_boxes_count => $search_boxes_count );
341
342     if ($cgi->cookie("num_paragraph")){
343         $search_boxes_count = $cgi->cookie("num_paragraph");
344     }
345
346     for (my $i=1;$i<=$search_boxes_count;$i++) {
347         # if it's the first one, don't display boolean option, but show scan indexes
348         if ($i==1) {
349             push @search_boxes_array,
350                 {
351                 scan_index => 1,
352                 };
353         
354         }
355         # if it's the last one, show the 'add field' box
356         elsif ($i==$search_boxes_count) {
357             push @search_boxes_array,
358                 {
359                 boolean => 1,
360                 add_field => 1,
361                 };
362         }
363         else {
364             push @search_boxes_array,
365                 {
366                 boolean => 1,
367                 };
368         }
369
370     }
371
372     my @advsearch_limits = split /,/, C4::Context->preference('OpacAdvSearchOptions');
373     my @advsearch_more_limits = split /,/,
374       C4::Context->preference('OpacAdvSearchMoreOptions');
375     $template->param(
376         uc( C4::Context->preference("marcflavour") ) => 1,    # we already did this for UNIMARC
377         advsearch         => 1,
378         search_boxes_loop => \@search_boxes_array,
379         OpacAdvSearchOptions     => \@advsearch_limits,
380         OpacAdvSearchMoreOptions => \@advsearch_more_limits,
381     );
382
383     # use the global setting by default
384     if ( C4::Context->preference("expandedSearchOption") == 1 ) {
385         $template->param( expanded_options => C4::Context->preference("expandedSearchOption") );
386     }
387     # but let the user override it
388     if (defined $cgi->param('expanded_options')) {
389         if ( ($cgi->param('expanded_options') == 0) || ($cgi->param('expanded_options') == 1 ) ) {
390             $template->param( expanded_options => $cgi->param('expanded_options'));
391         }
392     }
393
394     if (C4::Context->preference('OPACNumbersPreferPhrase')) {
395         $template->param('numbersphr' => 1);
396     }
397
398     output_html_with_http_headers $cgi, $cookie, $template->output;
399     exit;
400 }
401
402 ### OK, if we're this far, we're performing an actual search
403
404 # Fetch the paramater list as a hash in scalar context:
405 #  * returns paramater list as tied hash ref
406 #  * we can edit the values by changing the key
407 #  * multivalued CGI paramaters are returned as a packaged string separated by "\0" (null)
408 my $params = $cgi->Vars;
409 my $tag;
410 if ( $params->{tag} ) {
411     $tag = $params->{tag};
412     $template->param( tag => $tag );
413 }
414
415 # String with params with the search criteria for the paging in opac-detail
416 # param value is URI encoded and params separator is HTML encode (&amp;)
417 my $pasarParams = '';
418 my $j = 0;
419 for (keys %$params) {
420     my @pasarParam = $cgi->param($_);
421     for my $paramValue(@pasarParam) {
422         $pasarParams .= '&amp;' if ($j > 0);
423         $pasarParams .= $_ . '=' . uri_escape_utf8($paramValue);
424         $j++;
425     }
426 }
427
428 # Params that can have more than one value
429 # sort by is used to sort the query
430 # in theory can have more than one but generally there's just one
431 my @sort_by;
432 my $default_sort_by;
433 if (   C4::Context->preference('OPACdefaultSortField')
434     && C4::Context->preference('OPACdefaultSortOrder') ) {
435     $default_sort_by =
436         C4::Context->preference('OPACdefaultSortField') . '_'
437       . C4::Context->preference('OPACdefaultSortOrder');
438 }
439
440 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/; 
441 @sort_by = $cgi->param('sort_by');
442 $sort_by[0] = $default_sort_by if !$sort_by[0] && defined($default_sort_by);
443 foreach my $sort (@sort_by) {
444     if ( grep { /^$sort$/ } @allowed_sortby ) {
445         $template->param($sort => 1);
446     }
447 }
448 $template->param('sort_by' => $sort_by[0]);
449
450 # Use the servers defined, or just search our local catalog(default)
451 my @servers = $cgi->param('server');
452 unless (@servers) {
453     #FIXME: this should be handled using Context.pm
454     @servers = ("biblioserver");
455     # @servers = C4::Context->config("biblioserver");
456 }
457
458 # operators include boolean and proximity operators and are used
459 # to evaluate multiple operands
460 my @operators = $cgi->param('op');
461 @operators = map { uri_unescape($_) } @operators;
462
463 # indexes are query qualifiers, like 'title', 'author', etc. They
464 # can be single or multiple parameters separated by comma: kw,right-Truncation 
465 my @indexes = $cgi->param('idx');
466 @indexes = map { uri_unescape($_) } @indexes;
467
468 # if a simple index (only one)  display the index used in the top search box
469 if ($indexes[0] && !$indexes[1]) {
470     $template->param("ms_".$indexes[0] => 1);
471 }
472 # an operand can be a single term, a phrase, or a complete ccl query
473 my @operands = $cgi->param('q');
474 @operands = map { uri_unescape($_) } @operands;
475
476 $template->{VARS}->{querystring} = join(' ', @operands);
477
478 # if a simple search, display the value in the search box
479 if ($operands[0] && !$operands[1]) {
480     my $ms_query = $operands[0];
481     $ms_query =~ s/ #\S+//;
482     $template->param(ms_value => $ms_query);
483 }
484
485 # limits are use to limit to results to a pre-defined category such as branch or language
486 my @limits = $cgi->param('limit');
487 @limits = map { uri_unescape($_) } @limits;
488 my @nolimits = $cgi->param('nolimit');
489 @nolimits = map { uri_unescape($_) } @nolimits;
490 my %is_nolimit = map { $_ => 1 } @nolimits;
491 @limits = grep { not $is_nolimit{$_} } @limits;
492
493 if (@searchCategories > 0) {
494     my @tabcat;
495     foreach my $typecategory (@searchCategories) {
496         push (@tabcat, GetItemTypesByCategory($typecategory));
497     }
498
499     foreach my $itemtypeInCategory (@tabcat) {
500         push (@limits, "mc-$itype_or_itemtype,phr:".$itemtypeInCategory);
501     }
502 }
503
504 @limits = map { uri_unescape($_) } @limits;
505
506 if($params->{'multibranchlimit'}) {
507     my $library_category = Koha::LibraryCategories->find( $params->{multibranchlimit} );
508     my @libraries = $library_category->libraries;
509     my $multibranch = '('.join( " or ", map { 'branch: ' . $_->id } @libraries ) .')';
510     push @limits, $multibranch if ($multibranch ne  '()');
511 }
512
513 my $available;
514 foreach my $limit(@limits) {
515     if ($limit =~/available/) {
516         $available = 1;
517     }
518 }
519 $template->param(available => $available);
520
521 # append year limits if they exist
522 if ($params->{'limit-yr'}) {
523     if ($params->{'limit-yr'} =~ /\d{4}-\d{4}/) {
524         my ($yr1,$yr2) = split(/-/, $params->{'limit-yr'});
525         push @limits, "yr,st-numeric,ge=$yr1 and yr,st-numeric,le=$yr2";
526     }
527     elsif ($params->{'limit-yr'} =~ /\d{4}/) {
528         push @limits, "yr,st-numeric=$params->{'limit-yr'}";
529     }
530     else {
531         #FIXME: Should return a error to the user, incorect date format specified
532     }
533 }
534
535 # Params that can only have one value
536 my $scan = $params->{'scan'};
537 my $count = C4::Context->preference('OPACnumSearchResults') || 20;
538 my $countRSS         = C4::Context->preference('numSearchRSSResults') || 50;
539 my $results_per_page = $params->{'count'} || $count;
540 my $offset = $params->{'offset'} || 0;
541 my $page = $cgi->param('page') || 1;
542 $offset = ($page-1)*$results_per_page if $page>1;
543 my $hits;
544 my $expanded_facet = $params->{'expand'};
545
546 # Define some global variables
547 my ($error,$query,$simple_query,$query_cgi,$query_desc,$limit,$limit_cgi,$limit_desc,$query_type);
548
549 my @results;
550
551 ## I. BUILD THE QUERY
552 ( $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);
553
554 sub _input_cgi_parse {
555     my @elements;
556     my $query_cgi = shift or return @elements;
557     for my $this_cgi ( split('&',$query_cgi) ) {
558         next unless $this_cgi;
559         $this_cgi =~ /(.*?)=(.*)/;
560         push @elements, { input_name => $1, input_value => Encode::decode_utf8( uri_unescape($2) ) };
561     }
562     return @elements;
563 }
564
565 ## parse the query_cgi string and put it into a form suitable for <input>s
566 my @query_inputs = _input_cgi_parse($query_cgi);
567 $template->param ( QUERY_INPUTS => \@query_inputs );
568
569 ## parse the limit_cgi string and put it into a form suitable for <input>s
570 my @limit_inputs = $limit_cgi ? _input_cgi_parse($limit_cgi) : ();
571
572 # add OPAC 'hidelostitems'
573 #if (C4::Context->preference('hidelostitems') == 1) {
574 #    # either lost ge 0 or no value in the lost register
575 #    $query ="($query) and ( (lost,st-numeric <= 0) or ( allrecords,AlwaysMatches='' not lost,AlwaysMatches='') )";
576 #}
577 #
578 # add OPAC suppression - requires at least one item indexed with Suppress
579 if (C4::Context->preference('OpacSuppression')) {
580     # OPAC suppression by IP address
581     if (C4::Context->preference('OpacSuppressionByIPRange')) {
582         my $IPAddress = $ENV{'REMOTE_ADDR'};
583         my $IPRange = C4::Context->preference('OpacSuppressionByIPRange');
584         if ($IPAddress !~ /^$IPRange/)  {
585             if ( $query_type eq 'pqf' ) {
586                 $query = '@not '.$query.' @attr 14=1 @attr 1=9011 1';
587             } else {
588                 $query = "($query) not Suppress=1";
589             }
590         }
591     }
592     else {
593         if ( $query_type eq 'pqf' ) {
594             #$query = "($query) && -(suppress:1)"; #QP syntax
595             $query = '@not '.$query.' @attr 14=1 @attr 1=9011 1'; #PQF syntax
596         } else {
597             $query = "($query) not Suppress=1";
598         }
599     }
600 }
601
602 $template->param ( LIMIT_INPUTS => \@limit_inputs );
603 $template->param ( OPACResultsSidebar => C4::Context->preference('OPACResultsSidebar'));
604
605 ## II. DO THE SEARCH AND GET THE RESULTS
606 my $total = 0; # the total results for the whole set
607 my $facets; # this object stores the faceted results that display on the left-hand of the results page
608 my @results_array;
609 my $results_hashref;
610 my @coins;
611
612 if ($tag) {
613     $query_cgi = "tag=" .$tag . "&" . $query_cgi;
614     my $taglist = get_tags({term=>$tag, approved=>1});
615     $results_hashref->{biblioserver}->{hits} = scalar (@$taglist);
616     my @biblist  = (map {GetBiblioData($_->{biblionumber})} @$taglist);
617     my @marclist = (map { (C4::Context->config('zebra_bib_index_mode') eq 'dom')? $_->{marcxml}: $_->{marc}; } @biblist);
618     $DEBUG and printf STDERR "taglist (%s biblionumber)\nmarclist (%s records)\n", scalar(@$taglist), scalar(@marclist);
619     $results_hashref->{biblioserver}->{RECORDS} = \@marclist;
620     # FIXME: tag search and standard search should work together, not exclusively
621     # FIXME: No facets for tags search.
622 } elsif ($build_grouped_results) {
623     eval {
624         ($error, $results_hashref, $facets) = C4::Search::pazGetRecords($query,$simple_query,\@sort_by,\@servers,$results_per_page,$offset,$expanded_facet,$branches,$query_type,$scan);
625     };
626 } else {
627     $pasarParams .= '&amp;query=' . uri_escape_utf8($query);
628     $pasarParams .= '&amp;count=' . uri_escape_utf8($results_per_page);
629     $pasarParams .= '&amp;simple_query=' . uri_escape_utf8($simple_query);
630     $pasarParams .= '&amp;query_type=' . uri_escape_utf8($query_type) if ($query_type);
631     eval {
632         ($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);
633 };
634 }
635
636 # This sorts the facets into alphabetical order
637 if ($facets && @$facets) {
638     foreach my $f (@$facets) {
639         $f->{facets} = [ sort { uc($a->{facet_label_value}) cmp uc($b->{facet_label_value}) } @{ $f->{facets} } ];
640     }
641     @$facets = sort {$a->{expand} cmp $b->{expand}} @$facets;
642 }
643
644 # use Data::Dumper; print STDERR "-" x 25, "\n", Dumper($results_hashref);
645 if ($@ || $error) {
646     $template->param(query_error => $error.$@);
647     output_html_with_http_headers $cgi, $cookie, $template->output;
648     exit;
649 }
650
651 # At this point, each server has given us a result set
652 # now we build that set for template display
653 my @sup_results_array;
654 for (my $i=0;$i<@servers;$i++) {
655     my $server = $servers[$i];
656     if ($server && $server =~/biblioserver/) { # this is the local bibliographic server
657         $hits = $results_hashref->{$server}->{"hits"};
658         my $page = $cgi->param('page') || 0;
659         my @newresults;
660         if ($build_grouped_results) {
661             foreach my $group (@{ $results_hashref->{$server}->{"GROUPS"} }) {
662                 # because pazGetRecords handles retieving only the records
663                 # we want as specified by $offset and $results_per_page,
664                 # we need to set the offset parameter of searchResults to 0
665                 my @group_results = searchResults( 'opac', $query_desc, $group->{'group_count'},$results_per_page, 0, $scan,
666                                                    $group->{"RECORDS"});
667                 push @newresults, { group_label => $group->{'group_label'}, GROUP_RESULTS => \@group_results };
668             }
669         } else {
670             @newresults = searchResults('opac', $query_desc, $hits, $results_per_page, $offset, $scan,
671                                         $results_hashref->{$server}->{"RECORDS"});
672         }
673         $hits = 0 unless @newresults;
674
675         foreach my $res (@newresults) {
676
677             # must define a value for size if not present in DB
678             # in order to avoid problems generated by the default size value in TT
679             if ( not exists $res->{'size'} ) { $res->{'size'} = "" }
680             # while we're checking each line, see if item is in the cart
681             if ( grep {$_ eq $res->{'biblionumber'}} @cart_list) {
682                 $res->{'incart'} = 1;
683             }
684
685             if (C4::Context->preference('COinSinOPACResults')) {
686                 my $record = GetMarcBiblio($res->{'biblionumber'});
687                 $res->{coins} = GetCOinSBiblio($record);
688             }
689             if ( C4::Context->preference( "Babeltheque" ) and $res->{normalized_isbn} ) {
690                 if( my $isbn = Business::ISBN->new( $res->{normalized_isbn} ) ) {
691                     $isbn = $isbn->as_isbn13->as_string;
692                     $isbn =~ s/-//g;
693                     my $social_datas = C4::SocialData::get_data( $isbn );
694                     if ( $social_datas ) {
695                         for my $key ( keys %$social_datas ) {
696                             $res->{$key} = $$social_datas{$key};
697                             if ( $key eq 'score_avg' ){
698                                 $res->{score_int} = sprintf("%.0f", $$social_datas{score_avg} );
699                             }
700                         }
701                     }
702                 }
703             }
704
705             if (C4::Context->preference('TagsEnabled') and
706                 C4::Context->preference('TagsShowOnList')) {
707                 if ( my $bibnum = $res->{biblionumber} ) {
708                     $res->{itemsissued} = CountItemsIssued( $bibnum );
709                     $res->{'TagLoop'} = get_tags({
710                         biblionumber => $bibnum,
711                         approved => 1,
712                         sort => '-weight',
713                         limit => C4::Context->preference('TagsShowOnList')
714                     });
715                 }
716             }
717
718             if ( C4::Context->preference('OpacStarRatings') eq 'all' ) {
719                 my $rating = GetRating( $res->{'biblionumber'}, $borrowernumber );
720                 $res->{'rating_value'}  = $rating->{'rating_value'};
721                 $res->{'rating_total'}  = $rating->{'rating_total'};
722                 $res->{'rating_avg'}    = $rating->{'rating_avg'};
723                 $res->{'rating_avg_int'} = $rating->{'rating_avg_int'};
724             }
725         }
726
727         if ($results_hashref->{$server}->{"hits"}){
728             $total = $total + $hits;
729         }
730
731         # Opac search history
732         if (C4::Context->preference('EnableOpacSearchHistory')) {
733             unless ( $offset ) {
734                 my $path_info = $cgi->url(-path_info=>1);
735                 my $query_cgi_history = $cgi->url(-query=>1);
736                 $query_cgi_history =~ s/^$path_info\?//;
737                 $query_cgi_history =~ s/;/&/g;
738                 my $query_desc_history = join ", ", grep { defined $_ } $query_desc, $limit_desc;
739
740                 unless ( $borrowernumber ) {
741                     my $new_searches = C4::Search::History::add_to_session({
742                             cgi => $cgi,
743                             query_desc => $query_desc_history,
744                             query_cgi => $query_cgi_history,
745                             total => $total,
746                             type => "biblio",
747                     });
748                 } else {
749                     # To the session (the user is logged in)
750                     C4::Search::History::add({
751                         userid => $borrowernumber,
752                         sessionid => $cgi->cookie("CGISESSID"),
753                         query_desc => $query_desc_history,
754                         query_cgi => $query_cgi_history,
755                         total => $total,
756                         type => "biblio",
757                     });
758                 }
759             }
760             $template->param( EnableOpacSearchHistory => 1 );
761         }
762
763         ## If there's just one result, redirect to the detail page
764         if ($total == 1 && $format ne 'rss2'
765         && $format ne 'opensearchdescription' && $format ne 'atom') {
766             my $biblionumber=$newresults[0]->{biblionumber};
767             if (C4::Context->preference('BiblioDefaultView') eq 'isbd') {
768                 print $cgi->redirect("/cgi-bin/koha/opac-ISBDdetail.pl?biblionumber=$biblionumber");
769             } elsif  (C4::Context->preference('BiblioDefaultView') eq 'marc') {
770                 print $cgi->redirect("/cgi-bin/koha/opac-MARCdetail.pl?biblionumber=$biblionumber");
771             } else {
772                 print $cgi->redirect("/cgi-bin/koha/opac-detail.pl?biblionumber=$biblionumber");
773             } 
774             exit;
775         }
776         if ($hits) {
777             if ( !$build_grouped_results ) {
778                 # We build the encrypted list of first OPACnumSearchResults biblios to pass with the search criteria for paging on opac-detail
779                 $pasarParams .= '&amp;listBiblios=';
780                 my $j = 0;
781                 foreach (@newresults) {
782                     my $bibnum = ($_->{biblionumber})?$_->{biblionumber}:0;
783                     $pasarParams .= uri_escape_utf8($bibnum) . ',';
784                     $j++;
785                     last if ($j == $results_per_page);
786                 }
787                 chop $pasarParams if ($pasarParams =~ /,$/);
788                 $pasarParams .= '&amp;total=' . uri_escape_utf8( int($total) ) if ($pasarParams !~ /total=(?:[0-9]+)?/);
789                 if ($pasarParams) {
790                     my $session = get_session($cgi->cookie("CGISESSID"));
791                     $session->param('busc' => $pasarParams);
792                 }
793                 #
794             }
795             $template->param(total => $hits);
796             my $limit_cgi_not_availablity = $limit_cgi;
797             $limit_cgi_not_availablity =~ s/&limit=available//g if defined $limit_cgi_not_availablity;
798             $template->param(limit_cgi_not_availablity => $limit_cgi_not_availablity);
799             $template->param(limit_cgi => $limit_cgi);
800             $template->param(countrss  => $countRSS );
801             $template->param(query_cgi => $query_cgi);
802             $template->param(query_desc => $query_desc);
803             $template->param(limit_desc => $limit_desc);
804             $template->param(offset     => $offset);
805             $template->param(DisplayMultiPlaceHold => $DisplayMultiPlaceHold);
806             if ($query_desc || $limit_desc) {
807                 $template->param(searchdesc => 1);
808             }
809             $template->param(results_per_page =>  $results_per_page);
810             my $hide = C4::Context->preference('OpacHiddenItems');
811             $hide = ($hide =~ m/\S/) if $hide; # Just in case it has some spaces/new lines
812             my $branch = '';
813             if (C4::Context->userenv){
814                 $branch = C4::Context->userenv->{branch};
815             }
816             if ( C4::Context->preference('HighlightOwnItemsOnOPAC') ) {
817                 if (
818                     ( ( C4::Context->preference('HighlightOwnItemsOnOPACWhich') eq 'PatronBranch' ) && $branch )
819                     ||
820                     C4::Context->preference('HighlightOwnItemsOnOPACWhich') eq 'OpacURLBranch'
821                 ) {
822                     my $branchname;
823                     if ( C4::Context->preference('HighlightOwnItemsOnOPACWhich') eq 'PatronBranch' ) {
824                         $branchname = $branches->{$branch}->{'branchname'};
825                     }
826                     elsif (  C4::Context->preference('HighlightOwnItemsOnOPACWhich') eq 'OpacURLBranch' ) {
827                         $branchname = $branches->{ $ENV{'BRANCHCODE'} }->{'branchname'};
828                     }
829
830                     foreach my $res ( @newresults ) {
831                         my @new_loop;
832                         my @top_loop;
833                         my @old_loop = @{$res->{'available_items_loop'}};
834                         foreach my $item ( @old_loop ) {
835                             if ( $item->{'branchname'} eq $branchname ) {
836                                 $item->{'this_branch'} = 1;
837                                 push( @top_loop, $item );
838                             } else {
839                                 push( @new_loop, $item );
840                             }
841                         }
842                         my @complete_loop = ( @top_loop, @new_loop );
843                         $res->{'available_items_loop'} = \@complete_loop;
844                     }
845                 }
846             }
847
848             $template->param(
849                 SEARCH_RESULTS => \@newresults,
850                 OPACItemsResultsDisplay => (C4::Context->preference("OPACItemsResultsDisplay")),
851                 suppress_result_number => $hide,
852                             );
853             if (C4::Context->preference("OPACLocalCoverImages")){
854                 $template->param(OPACLocalCoverImages => 1);
855                 $template->param(OPACLocalCoverImagesPriority => C4::Context->preference("OPACLocalCoverImagesPriority"));
856             }
857             ## Build the page numbers on the bottom of the page
858             my @page_numbers;
859             # total number of pages there will be
860             my $pages = ceil($hits / $results_per_page);
861             # default page number
862             my $current_page_number = 1;
863             if ($offset) {
864                 $current_page_number = ( $offset / $results_per_page + 1 );
865             }
866             my $previous_page_offset;
867             if ( $offset >= $results_per_page ) {
868                 $previous_page_offset = $offset - $results_per_page;
869             }
870             my $next_page_offset = $offset + $results_per_page;
871             # If we're within the first 10 pages, keep it simple
872             #warn "current page:".$current_page_number;
873             if ($current_page_number < 10) {
874                 # just show the first 10 pages
875                 # Loop through the pages
876                 my $pages_to_show = 10;
877                 $pages_to_show = $pages if $pages<10;
878                 for ($i=1; $i<=$pages_to_show;$i++) {
879                     # the offset for this page
880                     my $this_offset = (($i*$results_per_page)-$results_per_page);
881                     # the page number for this page
882                     my $this_page_number = $i;
883                     # put it in the array
884                     push @page_numbers,
885                       { offset    => $this_offset,
886                         pg        => $this_page_number,
887                         highlight => $this_page_number == $current_page_number,
888                         sort_by   => join ' ', @sort_by
889                       };
890
891                 }
892                         
893             }
894             # now, show twenty pages, with the current one smack in the middle
895             else {
896                 for ($i=$current_page_number; $i<=($current_page_number + 20 );$i++) {
897                     my $this_offset = ((($i-9)*$results_per_page)-$results_per_page);
898                     my $this_page_number = $i-9;
899                     if ( $this_page_number <= $pages ) {
900                         push @page_numbers,
901                           { offset    => $this_offset,
902                             pg        => $this_page_number,
903                             highlight => $this_page_number == $current_page_number,
904                             sort_by => join ' ', @sort_by
905                           };
906                     }
907                 }
908                         
909             }
910             $template->param(   PAGE_NUMBERS => \@page_numbers,
911                                 previous_page_offset => $previous_page_offset) unless $pages < 2;
912             $template->param(next_page_offset => $next_page_offset) unless $pages eq $current_page_number;
913         }
914         # no hits
915         else {
916             my $nohits = C4::Context->preference('OPACNoResultsFound');
917             if ($nohits and $nohits=~/{QUERY_KW}/){
918                 # extracting keywords in case of relaunching search
919                 (my $query_kw=$query_desc)=~s/ and|or / /g;
920                 my @query_kw=($query_kw=~ /([-\w]+\b)(?:[^,:]|$)/g);
921                 $query_kw=join('+',@query_kw);
922                 $nohits=~s/{QUERY_KW}/$query_kw/g;
923                 $template->param('OPACNoResultsFound' =>$nohits);
924             }
925             $template->param(
926                 searchdesc => 1,
927                 query_desc => $query_desc,
928                 limit_desc => $limit_desc,
929                 query_cgi  => $query_cgi,
930                 limit_cgi  => $limit_cgi
931             );
932         }
933     } # end of the if local
934     # asynchronously search the authority server
935     elsif ($server && $server =~/authorityserver/) { # this is the local authority server
936         my @inner_sup_results_array;
937         for my $sup_record ( @{$results_hashref->{$server}->{"RECORDS"}} ) {
938             my $marc_record_object = MARC::Record->new_from_usmarc($sup_record);
939             my $title_field = $marc_record_object->field(100);
940             push @inner_sup_results_array, {
941                 'title' => $title_field->subfield('a'),
942                 'link' => "&amp;idx=an&amp;q=".$marc_record_object->field('001')->as_string(),
943             };
944         }
945         my $servername = $server;
946         push @sup_results_array, {  servername => $servername,
947                                     inner_sup_results_loop => \@inner_sup_results_array} if @inner_sup_results_array;
948     }
949     # FIXME: can add support for other targets as needed here
950     $template->param(           outer_sup_results_loop => \@sup_results_array);
951 } #/end of the for loop
952 #$template->param(FEDERATED_RESULTS => \@results_array);
953
954 for my $facet ( @$facets ) {
955     for my $entry ( @{ $facet->{facets} } ) {
956         my $index = $entry->{type_link_value};
957         my $value = $entry->{facet_link_value};
958         $entry->{active} = grep { $_->{input_value} eq qq{$index:$value} } @limit_inputs;
959     }
960 }
961
962
963 $template->param(
964             #classlist => $classlist,
965             total => $total,
966             opacfacets => 1,
967             facets_loop => $facets,
968             displayFacetCount=> C4::Context->preference('displayFacetCount')||0,
969             scan => $scan,
970             search_error => $error,
971 );
972
973 if ($query_desc || $limit_desc) {
974     $template->param(searchdesc => 1);
975 }
976
977 # VI. BUILD THE TEMPLATE
978 my $some_private_shelves = Koha::Virtualshelves->get_some_shelves(
979     {
980         borrowernumber => $borrowernumber,
981         add_allowed    => 1,
982         category       => 1,
983     }
984 );
985 my $some_public_shelves = Koha::Virtualshelves->get_some_shelves(
986     {
987         borrowernumber => $borrowernumber,
988         add_allowed    => 1,
989         category       => 2,
990     }
991 );
992
993 $template->param(
994     add_to_some_private_shelves => $some_private_shelves,
995     add_to_some_public_shelves  => $some_public_shelves,
996 );
997
998 my $content_type = ($format eq 'rss' or $format eq 'atom') ? $format : 'html';
999
1000 # If GoogleIndicTransliteration system preference is On Set parameter to load Google's javascript in OPAC search screens
1001 if (C4::Context->preference('GoogleIndicTransliteration')) {
1002         $template->param('GoogleIndicTransliteration' => 1);
1003 }
1004
1005 $template->{VARS}->{DidYouMean} =
1006   ( defined C4::Context->preference('OPACdidyoumean')
1007       && C4::Context->preference('OPACdidyoumean') =~ m/enable/ );
1008 $template->{VARS}->{IDreamBooksReviews} = C4::Context->preference('IDreamBooksReviews');
1009 $template->{VARS}->{IDreamBooksReadometer} = C4::Context->preference('IDreamBooksReadometer');
1010 $template->{VARS}->{IDreamBooksResults} = C4::Context->preference('IDreamBooksResults');
1011
1012 if ($offset == 0 && IsOverDriveEnabled()) {
1013     $template->param(OverDriveEnabled => 1);
1014     $template->param(OverDriveLibraryID => C4::Context->preference('OverDriveLibraryID'));
1015 }
1016
1017     $template->param( borrowernumber    => $borrowernumber);
1018 output_with_http_headers $cgi, $cookie, $template->output, $content_type;