Bug 12478 - pile of elasticsearch code
[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::SearchEngine::Elasticsearch::QueryBuilder;
36 use Koha::ElasticSearch::Search;
37 use Koha::SearchEngine::Zebra::QueryBuilder;
38 use Koha::SearchEngine::Zebra::Search;
39
40 my $searchengine = C4::Context->preference("SearchEngine");
41 my ($builder, $searcher);
42 #$searchengine = 'Zebra'; # XXX
43 for ( $searchengine ) {
44     when ( /^Solr$/ ) {
45         warn "We use Solr";
46         require 'opac/search.pl';
47         exit;
48     }
49     when ( /^Zebra$/ ) {
50         $builder=Koha::SearchEngine::Zebra::QueryBuilder->new();
51         $searcher=Koha::SearchEngine::Zebra::Search->new();
52     }
53     when (/^Elasticsearch$/) {
54         # Should use the base QueryBuilder, but I don't have it wired up
55         # for moose yet.
56         $builder=Koha::SearchEngine::Elasticsearch::QueryBuilder->new();
57 #        $builder=Koha::SearchEngine::Zebra::QueryBuilder->new();
58         $searcher=Koha::ElasticSearch::Search->new({index => 'biblios'});
59     }
60 }
61
62 use C4::Output;
63 use C4::Auth qw(:DEFAULT get_session);
64 use C4::Languages qw(getLanguages);
65 use C4::Search;
66 use C4::Search::History;
67 use C4::Biblio;  # GetBiblioData
68 use C4::Koha;
69 use C4::Tags qw(get_tags);
70 use C4::Branch; # GetBranches
71 use C4::SocialData;
72 use C4::Ratings;
73 use C4::External::OverDrive;
74
75 use Koha::LibraryCategories;
76
77 use POSIX qw(ceil floor strftime);
78 use URI::Escape;
79 use JSON qw/decode_json encode_json/;
80 use Business::ISBN;
81
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);
86 my $cgi = new CGI;
87
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
94         $cgi->param(
95             -name => 'multibranchlimit',
96             -values => substr($branch_group_limit, 17)
97         );
98     } else {
99         $cgi->append(
100             -name => 'limit',
101             -values => [ $branch_group_limit ]
102         );
103     }
104 }
105
106 BEGIN {
107     if (C4::Context->preference('BakerTaylorEnabled')) {
108         require C4::External::BakerTaylor;
109         import C4::External::BakerTaylor qw(&image_url &link_url);
110     }
111 }
112
113 my ($template,$borrowernumber,$cookie);
114 # decide which template to use
115 my $template_name;
116 my $template_type = 'basic';
117 my @params = $cgi->param("limit");
118 my @searchCategories = $cgi->param('searchcat');
119
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';
124 }
125 elsif (@params && $build_grouped_results) {
126     $template_name = 'opac-results-grouped.tt';
127 }
128 elsif ((@params>=1) || ($cgi->param("q")) || ($cgi->param('multibranchlimit')) || ($cgi->param('limit-yr')) ) {
129     $template_name = 'opac-results.tt';
130 }
131 else {
132     $template_name = 'opac-advsearch.tt';
133     $template_type = 'advsearch';
134 }
135 # load the template
136 ($template, $borrowernumber, $cookie) = get_template_and_user({
137     template_name => $template_name,
138     query => $cgi,
139     type => "opac",
140     authnotrequired => ( C4::Context->preference("OpacPublic") ? 1 : 0 ),
141     }
142 );
143
144 my $lang = C4::Languages::getlanguage($cgi);
145
146 if ($template_name eq 'opac-results.tt') {
147    $template->param('COinSinOPACResults' => C4::Context->preference('COinSinOPACResults'));
148 }
149
150 # get biblionumbers stored in the cart
151 my @cart_list;
152
153 if($cgi->cookie("bib_list")){
154     my $cart_list = $cgi->cookie("bib_list");
155     @cart_list = split(/\//, $cart_list);
156 }
157
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
163 }
164 if (C4::Context->preference("marcflavour") eq "UNIMARC" ) {
165     $template->param('UNIMARC' => 1);
166 }
167 elsif (C4::Context->preference("marcflavour") eq "MARC21" ) {
168     $template->param('usmarc' => 1);
169 }
170
171 $template->param( 'OPACNoResultsFound' => C4::Context->preference('OPACNoResultsFound') );
172
173 $template->param(
174     OpacStarRatings => C4::Context->preference("OpacStarRatings") );
175
176 if (C4::Context->preference('BakerTaylorEnabled')) {
177     $template->param(
178         BakerTaylorEnabled  => 1,
179         BakerTaylorImageURL => &image_url(),
180         BakerTaylorLinkURL  => &link_url(),
181         BakerTaylorBookstoreURL => C4::Context->preference('BakerTaylorBookstoreURL'),
182     );
183 }
184
185 if (C4::Context->preference('TagsEnabled')) {
186     $template->param(TagsEnabled => 1);
187     foreach (qw(TagsShowOnList TagsInputOnList)) {
188         C4::Context->preference($_) and $template->param($_ => 1);
189     }
190 }
191
192 ## URI Re-Writing
193 # Deprecated, but preserved because it's interesting :-)
194 # The same thing can be accomplished with mod_rewrite in
195 # a more elegant way
196 #                  
197 #my $rewrite_flag;
198 #my $uri = $cgi->url(-base => 1);
199 #my $relative_url = $cgi->url(-relative=>1);
200 #$uri.="/".$relative_url."?";
201 #warn "URI:$uri";
202 #my @cgi_params_list = $cgi->param();
203 #my $url_params = $cgi->Vars;
204 #
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};
207 #}
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);
213 #    exit;
214 #}
215
216 # load the branches
217
218 if ($cgi->param("returntosearch")) {
219     $template->param('ReturnToSearch' => 1);
220 }
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');
225     }
226     elsif ($pathcode eq '"exs"') {
227          $template->param('ReturnPath' => '/cgi-bin/koha/opac-search.pl?expanded_options=1&returntosearch=1');
228     }
229     else {
230         warn "ReturnPath switch error";
231     }
232 }
233
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 );
237
238 # load the language limits (for search)
239 my $languages_limit_loop = getLanguages($lang, 1);
240 $template->param(search_languages_loop => $languages_limit_loop,);
241
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};
250 }
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;
256 my $cnt;
257 my $advanced_search_types = C4::Context->preference("AdvancedSearchTypes") || "itemtypes";
258 my @advanced_search_types = split(/\|/, $advanced_search_types);
259
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.
264     eval {
265         $hidingrules = YAML::Load($yaml);
266     };
267     if ($@) {
268         warn "Unable to parse OpacHiddenItems syspref : $@";
269     }
270 }
271
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
277         my @itypesloop;
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'},
289             );
290             if ( !$itemtypes->{$thisitemtype}->{'hideinopac'} ) {
291                 push @itypesloop, \%row;
292             }
293         }
294         my %search_code = (  advanced_search_type => $advanced_srch_type,
295                              code_loop => \@itypesloop );
296         push @advancedsearchesloop, \%search_code;
297     } else {
298     # covers all the other cases: non-itemtype authorized values
299        my $advsearchtypes = GetAuthorisedValues($advanced_srch_type, 'opac');
300         my @authvalueloop;
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}};
305                 my %row =(
306                                 number=>$cnt++,
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'} ),
312                 );
313                 push @authvalueloop, \%row;
314         }
315         my %search_code = (  advanced_search_type => $advanced_srch_type,
316                              code_loop => \@authvalueloop );
317         push @advancedsearchesloop, \%search_code;
318     }
319 }
320 $template->param(advancedsearchesloop => \@advancedsearchesloop);
321
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,);
327     
328     my $secondary_servers_loop;
329     $template->param(outer_sup_servers_loop => $secondary_servers_loop,);
330
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 );
338     }
339
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 );
346
347     if ($cgi->cookie("num_paragraph")){
348         $search_boxes_count = $cgi->cookie("num_paragraph");
349     }
350
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
353         if ($i==1) {
354             push @search_boxes_array,
355                 {
356                 scan_index => 1,
357                 };
358         
359         }
360         # if it's the last one, show the 'add field' box
361         elsif ($i==$search_boxes_count) {
362             push @search_boxes_array,
363                 {
364                 boolean => 1,
365                 add_field => 1,
366                 };
367         }
368         else {
369             push @search_boxes_array,
370                 {
371                 boolean => 1,
372                 };
373         }
374
375     }
376
377     my @advsearch_limits = split /,/, C4::Context->preference('OpacAdvSearchOptions');
378     my @advsearch_more_limits = split /,/,
379       C4::Context->preference('OpacAdvSearchMoreOptions');
380     $template->param(
381         uc( C4::Context->preference("marcflavour") ) => 1,    # we already did this for UNIMARC
382         advsearch         => 1,
383         search_boxes_loop => \@search_boxes_array,
384         OpacAdvSearchOptions     => \@advsearch_limits,
385         OpacAdvSearchMoreOptions => \@advsearch_more_limits,
386     );
387
388     # use the global setting by default
389     if ( C4::Context->preference("expandedSearchOption") == 1 ) {
390         $template->param( expanded_options => C4::Context->preference("expandedSearchOption") );
391     }
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'));
396         }
397     }
398
399     if (C4::Context->preference('OPACNumbersPreferPhrase')) {
400         $template->param('numbersphr' => 1);
401     }
402
403     output_html_with_http_headers $cgi, $cookie, $template->output;
404     exit;
405 }
406
407 ### OK, if we're this far, we're performing an actual search
408
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;
414 my $tag;
415 if ( $params->{tag} ) {
416     $tag = $params->{tag};
417     $template->param( tag => $tag );
418 }
419
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 (&amp;)
422 my $pasarParams = '';
423 my $j = 0;
424 for (keys %$params) {
425     my @pasarParam = $cgi->param($_);
426     for my $paramValue(@pasarParam) {
427         $pasarParams .= '&amp;' if ($j > 0);
428         $pasarParams .= $_ . '=' . uri_escape_utf8($paramValue);
429         $j++;
430     }
431 }
432
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
436 my @sort_by;
437 my $default_sort_by;
438 if (   C4::Context->preference('OPACdefaultSortField')
439     && C4::Context->preference('OPACdefaultSortOrder') ) {
440     $default_sort_by =
441         C4::Context->preference('OPACdefaultSortField') . '_'
442       . C4::Context->preference('OPACdefaultSortOrder');
443 }
444
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);
451     }
452 }
453 $template->param('sort_by' => $sort_by[0]);
454
455 # Use the servers defined, or just search our local catalog(default)
456 my @servers = $cgi->param('server');
457 unless (@servers) {
458     #FIXME: this should be handled using Context.pm
459     @servers = ("biblioserver");
460     # @servers = C4::Context->config("biblioserver");
461 }
462
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;
467
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;
472
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);
476 }
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;
480
481 $template->{VARS}->{querystring} = join(' ', @operands);
482
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);
488 }
489
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;
497
498 if (@searchCategories > 0) {
499     my @tabcat;
500     foreach my $typecategory (@searchCategories) {
501         push (@tabcat, GetItemTypesByCategory($typecategory));
502     }
503
504     foreach my $itemtypeInCategory (@tabcat) {
505         push (@limits, "mc-$itype_or_itemtype,phr:".$itemtypeInCategory);
506     }
507 }
508
509 @limits = map { uri_unescape($_) } @limits;
510
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  '()');
516 }
517
518 my $available;
519 foreach my $limit(@limits) {
520     if ($limit =~/available/) {
521         $available = 1;
522     }
523 }
524 $template->param(available => $available);
525
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";
531     }
532     elsif ($params->{'limit-yr'} =~ /\d{4}/) {
533         push @limits, "yr,st-numeric=$params->{'limit-yr'}";
534     }
535     else {
536         #FIXME: Should return a error to the user, incorect date format specified
537     }
538 }
539
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;
548 my $hits;
549 my $expanded_facet = $params->{'expand'};
550
551 # Define some global variables
552 my ($error,$query,$simple_query,$query_cgi,$query_desc,$limit,$limit_cgi,$limit_desc,$query_type);
553
554 my @results;
555
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);
558
559 sub _input_cgi_parse {
560     my @elements;
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) ) };
566     }
567     return @elements;
568 }
569
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 );
573
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) : ();
576
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='') )";
581 #}
582 #
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';
592             } else {
593                 $query = "($query) not Suppress=1";
594             }
595         }
596     }
597     else {
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
601         } else {
602             $query = "($query) not Suppress=1";
603         }
604     }
605 }
606
607 $template->param ( LIMIT_INPUTS => \@limit_inputs );
608 $template->param ( OPACResultsSidebar => C4::Context->preference('OPACResultsSidebar'));
609
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
613 my @results_array;
614 my $results_hashref;
615 my @coins;
616
617 if ($tag) {
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) {
628     eval {
629         ($error, $results_hashref, $facets) = C4::Search::pazGetRecords($query,$simple_query,\@sort_by,\@servers,$results_per_page,$offset,$expanded_facet,$branches,$query_type,$scan);
630     };
631 } else {
632     $pasarParams .= '&amp;query=' . uri_escape_utf8($query);
633     $pasarParams .= '&amp;count=' . uri_escape_utf8($results_per_page);
634     $pasarParams .= '&amp;simple_query=' . uri_escape_utf8($simple_query);
635     $pasarParams .= '&amp;query_type=' . uri_escape_utf8($query_type) if ($query_type);
636     eval {
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);
638 };
639 }
640
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} } ];
645     }
646     @$facets = sort {$a->{expand} cmp $b->{expand}} @$facets;
647 }
648
649 # use Data::Dumper; print STDERR "-" x 25, "\n", Dumper($results_hashref);
650 if ($@ || $error) {
651     $template->param(query_error => $error.$@);
652     output_html_with_http_headers $cgi, $cookie, $template->output;
653     exit;
654 }
655
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;
664         my @newresults;
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 };
673             }
674         } else {
675             @newresults = searchResults('opac', $query_desc, $hits, $results_per_page, $offset, $scan,
676                                         $results_hashref->{$server}->{"RECORDS"});
677         }
678         $hits = 0 unless @newresults;
679
680         foreach my $res (@newresults) {
681
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;
688             }
689
690             if (C4::Context->preference('COinSinOPACResults')) {
691                 my $record = GetMarcBiblio($res->{'biblionumber'});
692                 $res->{coins} = GetCOinSBiblio($record);
693             }
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;
697                     $isbn =~ s/-//g;
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} );
704                             }
705                         }
706                     }
707                 }
708             }
709
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,
716                         approved => 1,
717                         sort => '-weight',
718                         limit => C4::Context->preference('TagsShowOnList')
719                     });
720                 }
721             }
722
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'};
729             }
730         }
731
732         if ($results_hashref->{$server}->{"hits"}){
733             $total = $total + $hits;
734         }
735
736         # Opac search history
737         if (C4::Context->preference('EnableOpacSearchHistory')) {
738             unless ( $offset ) {
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;
744
745                 unless ( $borrowernumber ) {
746                     my $new_searches = C4::Search::History::add_to_session({
747                             cgi => $cgi,
748                             query_desc => $query_desc_history,
749                             query_cgi => $query_cgi_history,
750                             total => $total,
751                             type => "biblio",
752                     });
753                 } else {
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,
760                         total => $total,
761                         type => "biblio",
762                     });
763                 }
764             }
765             $template->param( EnableOpacSearchHistory => 1 );
766         }
767
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");
776             } else {
777                 print $cgi->redirect("/cgi-bin/koha/opac-detail.pl?biblionumber=$biblionumber");
778             } 
779             exit;
780         }
781         if ($hits) {
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 .= '&amp;listBiblios=';
785                 my $j = 0;
786                 foreach (@newresults) {
787                     my $bibnum = ($_->{biblionumber})?$_->{biblionumber}:0;
788                     $pasarParams .= uri_escape_utf8($bibnum) . ',';
789                     $j++;
790                     last if ($j == $results_per_page);
791                 }
792                 chop $pasarParams if ($pasarParams =~ /,$/);
793                 $pasarParams .= '&amp;total=' . uri_escape_utf8( int($total) ) if ($pasarParams !~ /total=(?:[0-9]+)?/);
794                 if ($pasarParams) {
795                     my $session = get_session($cgi->cookie("CGISESSID"));
796                     $session->param('busc' => $pasarParams);
797                 }
798                 #
799             }
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);
813             }
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
817             my $branch = '';
818             if (C4::Context->userenv){
819                 $branch = C4::Context->userenv->{branch};
820             }
821             if ( C4::Context->preference('HighlightOwnItemsOnOPAC') ) {
822                 if (
823                     ( ( C4::Context->preference('HighlightOwnItemsOnOPACWhich') eq 'PatronBranch' ) && $branch )
824                     ||
825                     C4::Context->preference('HighlightOwnItemsOnOPACWhich') eq 'OpacURLBranch'
826                 ) {
827                     my $branchname;
828                     if ( C4::Context->preference('HighlightOwnItemsOnOPACWhich') eq 'PatronBranch' ) {
829                         $branchname = $branches->{$branch}->{'branchname'};
830                     }
831                     elsif (  C4::Context->preference('HighlightOwnItemsOnOPACWhich') eq 'OpacURLBranch' ) {
832                         $branchname = $branches->{ $ENV{'BRANCHCODE'} }->{'branchname'};
833                     }
834
835                     foreach my $res ( @newresults ) {
836                         my @new_loop;
837                         my @top_loop;
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 );
843                             } else {
844                                 push( @new_loop, $item );
845                             }
846                         }
847                         my @complete_loop = ( @top_loop, @new_loop );
848                         $res->{'available_items_loop'} = \@complete_loop;
849                     }
850                 }
851             }
852
853             $template->param(
854                 SEARCH_RESULTS => \@newresults,
855                 OPACItemsResultsDisplay => (C4::Context->preference("OPACItemsResultsDisplay")),
856                 suppress_result_number => $hide,
857                             );
858             if (C4::Context->preference("OPACLocalCoverImages")){
859                 $template->param(OPACLocalCoverImages => 1);
860                 $template->param(OPACLocalCoverImagesPriority => C4::Context->preference("OPACLocalCoverImagesPriority"));
861             }
862             ## Build the page numbers on the bottom of the page
863             my @page_numbers;
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;
868             if ($offset) {
869                 $current_page_number = ( $offset / $results_per_page + 1 );
870             }
871             my $previous_page_offset;
872             if ( $offset >= $results_per_page ) {
873                 $previous_page_offset = $offset - $results_per_page;
874             }
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
889                     push @page_numbers,
890                       { offset    => $this_offset,
891                         pg        => $this_page_number,
892                         highlight => $this_page_number == $current_page_number,
893                         sort_by   => join ' ', @sort_by
894                       };
895
896                 }
897                         
898             }
899             # now, show twenty pages, with the current one smack in the middle
900             else {
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 ) {
905                         push @page_numbers,
906                           { offset    => $this_offset,
907                             pg        => $this_page_number,
908                             highlight => $this_page_number == $current_page_number,
909                             sort_by => join ' ', @sort_by
910                           };
911                     }
912                 }
913                         
914             }
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;
918         }
919         # no hits
920         else {
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);
929             }
930             $template->param(
931                 searchdesc => 1,
932                 query_desc => $query_desc,
933                 limit_desc => $limit_desc,
934                 query_cgi  => $query_cgi,
935                 limit_cgi  => $limit_cgi
936             );
937         }
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' => "&amp;idx=an&amp;q=".$marc_record_object->field('001')->as_string(),
948             };
949         }
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;
953     }
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);
958
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;
964     }
965 }
966
967
968 $template->param(
969             #classlist => $classlist,
970             total => $total,
971             opacfacets => 1,
972             facets_loop => $facets,
973             displayFacetCount=> C4::Context->preference('displayFacetCount')||0,
974             scan => $scan,
975             search_error => $error,
976 );
977
978 if ($query_desc || $limit_desc) {
979     $template->param(searchdesc => 1);
980 }
981
982 # VI. BUILD THE TEMPLATE
983 my $some_private_shelves = Koha::Virtualshelves->get_some_shelves(
984     {
985         borrowernumber => $borrowernumber,
986         add_allowed    => 1,
987         category       => 1,
988     }
989 );
990 my $some_public_shelves = Koha::Virtualshelves->get_some_shelves(
991     {
992         borrowernumber => $borrowernumber,
993         add_allowed    => 1,
994         category       => 2,
995     }
996 );
997
998 $template->param(
999     add_to_some_private_shelves => $some_private_shelves,
1000     add_to_some_public_shelves  => $some_public_shelves,
1001 );
1002
1003 my $content_type = ($format eq 'rss' or $format eq 'atom') ? $format : 'html';
1004
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);
1008 }
1009
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');
1016
1017 if ($offset == 0 && IsOverDriveEnabled()) {
1018     $template->param(OverDriveEnabled => 1);
1019     $template->param(OverDriveLibraryID => C4::Context->preference('OverDriveLibraryID'));
1020 }
1021
1022     $template->param( borrowernumber    => $borrowernumber);
1023 output_with_http_headers $cgi, $cookie, $template->output, $content_type;