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