Bug 5981 - OPAC: Add limits to search history
[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 under the
10 # terms of the GNU General Public License as published by the Free Software
11 # Foundation; either version 2 of the License, or (at your option) any later
12 # version.
13 #
14 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
15 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
16 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License along
19 # with Koha; if not, write to the Free Software Foundation, Inc.,
20 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21
22 # Script to perform searching
23 # Mostly copied from search.pl, see POD there
24 use strict;            # always use
25 use warnings;
26
27 ## STEP 1. Load things that are used in both search page and
28 # results page and decide which template to load, operations 
29 # to perform, etc.
30 ## load Koha modules
31 use C4::Context;
32 use C4::Output;
33 use C4::Auth qw(:DEFAULT get_session);
34 use C4::Languages qw(getAllLanguages);
35 use C4::Search;
36 use C4::Biblio;  # GetBiblioData
37 use C4::Koha;
38 use C4::Tags qw(get_tags);
39 use C4::Branch; # GetBranches
40 use C4::SocialData;
41 use C4::Ratings;
42
43 use POSIX qw(ceil floor strftime);
44 use URI::Escape;
45 use Storable qw(thaw freeze);
46 use Business::ISBN;
47
48 my $DisplayMultiPlaceHold = C4::Context->preference("DisplayMultiPlaceHold");
49 # create a new CGI object
50 # FIXME: no_undef_params needs to be tested
51 use CGI qw('-no_undef_params');
52 my $cgi = new CGI;
53
54 BEGIN {
55     if (C4::Context->preference('BakerTaylorEnabled')) {
56         require C4::External::BakerTaylor;
57         import C4::External::BakerTaylor qw(&image_url &link_url);
58     }
59 }
60
61 my ($template,$borrowernumber,$cookie);
62
63 # decide which template to use
64 my $template_name;
65 my $template_type = 'basic';
66 my @params = $cgi->param("limit");
67
68 my $format = $cgi->param("format") || '';
69 my $build_grouped_results = C4::Context->preference('OPACGroupResults');
70 if ($format =~ /(rss|atom|opensearchdescription)/) {
71     $template_name = 'opac-opensearch.tmpl';
72 }
73 elsif (@params && $build_grouped_results) {
74     $template_name = 'opac-results-grouped.tmpl';
75 }
76 elsif ((@params>=1) || ($cgi->param("q")) || ($cgi->param('multibranchlimit')) || ($cgi->param('limit-yr')) ) {
77     $template_name = 'opac-results.tmpl';
78 }
79 else {
80     $template_name = 'opac-advsearch.tmpl';
81     $template_type = 'advsearch';
82 }
83 # load the template
84 ($template, $borrowernumber, $cookie) = get_template_and_user({
85     template_name => $template_name,
86     query => $cgi,
87     type => "opac",
88     authnotrequired => ( C4::Context->preference("OpacPublic") ? 1 : 0 ),
89     }
90 );
91 if ($template_name eq 'opac-results.tmpl') {
92    $template->param('COinSinOPACResults' => C4::Context->preference('COinSinOPACResults'));
93 }
94
95 # get biblionumbers stored in the cart
96 my @cart_list;
97
98 if($cgi->cookie("bib_list")){
99     my $cart_list = $cgi->cookie("bib_list");
100     @cart_list = split(/\//, $cart_list);
101 }
102
103 if ($format eq 'rss2' or $format eq 'opensearchdescription' or $format eq 'atom') {
104     $template->param($format => 1);
105     $template->param(timestamp => strftime("%Y-%m-%dT%H:%M:%S-00:00", gmtime)) if ($format eq 'atom'); 
106     # FIXME - the timestamp is a hack - the biblio update timestamp should be used for each
107     # entry, but not sure if that's worth an extra database query for each bib
108 }
109 if (C4::Context->preference("marcflavour") eq "UNIMARC" ) {
110     $template->param('UNIMARC' => 1);
111 }
112 elsif (C4::Context->preference("marcflavour") eq "MARC21" ) {
113     $template->param('usmarc' => 1);
114 }
115 $template->param( 'AllowOnShelfHolds' => C4::Context->preference('AllowOnShelfHolds') );
116 $template->param( 'OPACNoResultsFound' => C4::Context->preference('OPACNoResultsFound') );
117
118 $template->param(
119     OpacStarRatings => C4::Context->preference("OpacStarRatings") );
120
121 if (C4::Context->preference('BakerTaylorEnabled')) {
122     $template->param(
123         BakerTaylorEnabled  => 1,
124         BakerTaylorImageURL => &image_url(),
125         BakerTaylorLinkURL  => &link_url(),
126         BakerTaylorBookstoreURL => C4::Context->preference('BakerTaylorBookstoreURL'),
127     );
128 }
129
130 if (C4::Context->preference('TagsEnabled')) {
131     $template->param(TagsEnabled => 1);
132     foreach (qw(TagsShowOnList TagsInputOnList)) {
133         C4::Context->preference($_) and $template->param($_ => 1);
134     }
135 }
136
137 ## URI Re-Writing
138 # Deprecated, but preserved because it's interesting :-)
139 # The same thing can be accomplished with mod_rewrite in
140 # a more elegant way
141 #                  
142 #my $rewrite_flag;
143 #my $uri = $cgi->url(-base => 1);
144 #my $relative_url = $cgi->url(-relative=>1);
145 #$uri.="/".$relative_url."?";
146 #warn "URI:$uri";
147 #my @cgi_params_list = $cgi->param();
148 #my $url_params = $cgi->Vars;
149 #
150 #for my $each_param_set (@cgi_params_list) {
151 #    $uri.= join "",  map "\&$each_param_set=".$_, split("\0",$url_params->{$each_param_set}) if $url_params->{$each_param_set};
152 #}
153 #warn "New URI:$uri";
154 # Only re-write a URI if there are params or if it already hasn't been re-written
155 #unless (($cgi->param('r')) || (!$cgi->param()) ) {
156 #    print $cgi->redirect(     -uri=>$uri."&r=1",
157 #                            -cookie => $cookie);
158 #    exit;
159 #}
160
161 # load the branches
162
163 my $branches = GetBranches();   # used later in *getRecords, probably should be internalized by those functions after caching in C4::Branch is established
164 $template->param(
165     searchdomainloop => GetBranchCategories(undef,'searchdomain'),
166 );
167
168 # load the language limits (for search)
169 my $languages_limit_loop = getAllLanguages();
170 $template->param(search_languages_loop => $languages_limit_loop,);
171
172 # load the Type stuff
173 my $itemtypes = GetItemTypes;
174 # the index parameter is different for item-level itemtypes
175 my $itype_or_itemtype = (C4::Context->preference("item-level_itypes"))?'itype':'itemtype';
176 my @advancedsearchesloop;
177 my $cnt;
178 my $advanced_search_types = C4::Context->preference("AdvancedSearchTypes") || "itemtypes";
179 my @advanced_search_types = split(/\|/, $advanced_search_types);
180
181 foreach my $advanced_srch_type (@advanced_search_types) {
182    if ($advanced_srch_type eq 'itemtypes') {
183    # itemtype is a special case, since it's not defined in authorized values
184         my @itypesloop;
185         foreach my $thisitemtype ( sort {$itemtypes->{$a}->{'description'} cmp $itemtypes->{$b}->{'description'} } keys %$itemtypes ) {
186             my %row =(  number=>$cnt++,
187                 ccl => "$itype_or_itemtype,phr",
188                 code => $thisitemtype,
189                 description => $itemtypes->{$thisitemtype}->{'description'},
190                 imageurl=> getitemtypeimagelocation( 'opac', $itemtypes->{$thisitemtype}->{'imageurl'} ),
191             );
192             push @itypesloop, \%row;
193         }
194         my %search_code = (  advanced_search_type => $advanced_srch_type,
195                              code_loop => \@itypesloop );
196         push @advancedsearchesloop, \%search_code;
197     } else {
198     # covers all the other cases: non-itemtype authorized values
199        my $advsearchtypes = GetAuthorisedValues($advanced_srch_type, '', 'opac');
200         my @authvalueloop;
201         for my $thisitemtype (@$advsearchtypes) {
202                 my %row =(
203                                 number=>$cnt++,
204                                 ccl => $advanced_srch_type,
205                 code => $thisitemtype->{authorised_value},
206                 description => $thisitemtype->{'lib_opac'} || $thisitemtype->{'lib'},
207                 imageurl => getitemtypeimagelocation( 'opac', $thisitemtype->{'imageurl'} ),
208                 );
209                 push @authvalueloop, \%row;
210         }
211         my %search_code = (  advanced_search_type => $advanced_srch_type,
212                              code_loop => \@authvalueloop );
213         push @advancedsearchesloop, \%search_code;
214     }
215 }
216 $template->param(advancedsearchesloop => \@advancedsearchesloop);
217
218 # # load the itypes (Called item types in the template -- just authorized values for searching)
219 # my ($itypecount,@itype_loop) = GetCcodes();
220 # $template->param(itypeloop=>\@itype_loop,);
221
222 # The following should only be loaded if we're bringing up the advanced search template
223 if ( $template_type && $template_type eq 'advsearch' ) {
224     # load the servers (used for searching -- to do federated searching, etc.)
225     my $primary_servers_loop;# = displayPrimaryServers();
226     $template->param(outer_servers_loop =>  $primary_servers_loop,);
227     
228     my $secondary_servers_loop;
229     $template->param(outer_sup_servers_loop => $secondary_servers_loop,);
230
231     # set the default sorting
232     if (   C4::Context->preference('OPACdefaultSortField')
233         && C4::Context->preference('OPACdefaultSortOrder') ) {
234         my $default_sort_by =
235             C4::Context->preference('OPACdefaultSortField') . '_'
236           . C4::Context->preference('OPACdefaultSortOrder');
237         $template->param( sort_by => $default_sort_by );
238     }
239
240     # determine what to display next to the search boxes (ie, boolean option
241     # shouldn't appear on the first one, scan indexes should, adding a new
242     # box should only appear on the last, etc.
243     my @search_boxes_array;
244     my $search_boxes_count = 3; # begin whith 3 boxes
245     for (my $i=1;$i<=$search_boxes_count;$i++) {
246         # if it's the first one, don't display boolean option, but show scan indexes
247         if ($i==1) {
248             push @search_boxes_array,
249                 {
250                 scan_index => 1,
251                 };
252         
253         }
254         # if it's the last one, show the 'add field' box
255         elsif ($i==$search_boxes_count) {
256             push @search_boxes_array,
257                 {
258                 boolean => 1,
259                 add_field => 1,
260                 };
261         }
262         else {
263             push @search_boxes_array,
264                 {
265                 boolean => 1,
266                 };
267         }
268
269     }
270     $template->param(uc(    C4::Context->preference("marcflavour")) => 1,   # we already did this for UNIMARC
271                             advsearch => 1,
272                             search_boxes_loop => \@search_boxes_array);
273
274     # use the global setting by default
275     if ( C4::Context->preference("expandedSearchOption") == 1 ) {
276         $template->param( expanded_options => C4::Context->preference("expandedSearchOption") );
277     }
278     # but let the user override it
279     if (defined $cgi->param('expanded_options')) {
280         if ( ($cgi->param('expanded_options') == 0) || ($cgi->param('expanded_options') == 1 ) ) {
281             $template->param( expanded_options => $cgi->param('expanded_options'));
282         }
283     }
284     output_html_with_http_headers $cgi, $cookie, $template->output;
285     exit;
286 }
287
288 ### OK, if we're this far, we're performing an actual search
289
290 # Fetch the paramater list as a hash in scalar context:
291 #  * returns paramater list as tied hash ref
292 #  * we can edit the values by changing the key
293 #  * multivalued CGI paramaters are returned as a packaged string separated by "\0" (null)
294 my $params = $cgi->Vars;
295 my $tag;
296 $tag = $params->{tag} if $params->{tag};
297
298
299 # String with params with the search criteria for the paging in opac-detail
300 my $pasarParams = '';
301 my $j = 0;
302 for (keys %$params) {
303     my @pasarParam = split("\0", $params->{$_});
304     for my $paramValue(@pasarParam) {
305         $pasarParams .= '&amp;' if ($j > 0);
306         $pasarParams .= $_ . '=' . $paramValue;
307         $j++;
308     }
309 }
310
311 # Params that can have more than one value
312 # sort by is used to sort the query
313 # in theory can have more than one but generally there's just one
314 my @sort_by;
315 my $default_sort_by;
316 if (   C4::Context->preference('OPACdefaultSortField')
317     && C4::Context->preference('OPACdefaultSortOrder') ) {
318     $default_sort_by =
319         C4::Context->preference('OPACdefaultSortField') . '_'
320       . C4::Context->preference('OPACdefaultSortOrder');
321 }
322
323 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/; 
324 @sort_by = split("\0",$params->{'sort_by'}) if $params->{'sort_by'};
325 $sort_by[0] = $default_sort_by if !$sort_by[0] && defined($default_sort_by);
326 foreach my $sort (@sort_by) {
327     if ( $sort ~~ @allowed_sortby ) {
328         $template->param($sort => 1);
329     }
330 }
331 $template->param('sort_by' => $sort_by[0]);
332
333 # Use the servers defined, or just search our local catalog(default)
334 my @servers;
335 @servers = split("\0",$params->{'server'}) if $params->{'server'};
336 unless (@servers) {
337     #FIXME: this should be handled using Context.pm
338     @servers = ("biblioserver");
339     # @servers = C4::Context->config("biblioserver");
340 }
341
342 # operators include boolean and proximity operators and are used
343 # to evaluate multiple operands
344 my @operators;
345 @operators = split("\0",$params->{'op'}) if $params->{'op'};
346
347 # indexes are query qualifiers, like 'title', 'author', etc. They
348 # can be single or multiple parameters separated by comma: kw,right-Truncation 
349 my @indexes;
350 @indexes = split("\0",$params->{'idx'}) if $params->{'idx'};
351
352 # if a simple index (only one)  display the index used in the top search box
353 if ($indexes[0] && !$indexes[1]) {
354     $template->param("ms_".$indexes[0] => 1);
355 }
356 # an operand can be a single term, a phrase, or a complete ccl query
357 my @operands;
358 @operands = split("\0",$params->{'q'}) if $params->{'q'};
359
360 # if a simple search, display the value in the search box
361 if ($operands[0] && !$operands[1]) {
362     $template->param(ms_value => $operands[0]);
363 }
364
365 # limits are use to limit to results to a pre-defined category such as branch or language
366 my @limits;
367 @limits = split("\0",$params->{'limit'}) if $params->{'limit'};
368
369 if($params->{'multibranchlimit'}) {
370     push @limits, '('.join( " or ", map { "branch: $_ " } @{ GetBranchesInCategory( $params->{'multibranchlimit'} ) } ).')';
371 }
372
373 my $available;
374 foreach my $limit(@limits) {
375     if ($limit =~/available/) {
376         $available = 1;
377     }
378 }
379 $template->param(available => $available);
380
381 # append year limits if they exist
382 if ($params->{'limit-yr'}) {
383     if ($params->{'limit-yr'} =~ /\d{4}-\d{4}/) {
384         my ($yr1,$yr2) = split(/-/, $params->{'limit-yr'});
385         push @limits, "yr,st-numeric,ge=$yr1 and yr,st-numeric,le=$yr2";
386     }
387     elsif ($params->{'limit-yr'} =~ /\d{4}/) {
388         push @limits, "yr,st-numeric=$params->{'limit-yr'}";
389     }
390     else {
391         #FIXME: Should return a error to the user, incorect date format specified
392     }
393 }
394
395 # Params that can only have one value
396 my $scan = $params->{'scan'};
397 my $count = C4::Context->preference('OPACnumSearchResults') || 20;
398 my $countRSS         = C4::Context->preference('numSearchRSSResults') || 50;
399 my $results_per_page = $params->{'count'} || $count;
400 my $offset = $params->{'offset'} || 0;
401 my $page = $cgi->param('page') || 1;
402 $offset = ($page-1)*$results_per_page if $page>1;
403 my $hits;
404 my $expanded_facet = $params->{'expand'};
405
406 # Define some global variables
407 my ($error,$query,$simple_query,$query_cgi,$query_desc,$limit,$limit_cgi,$limit_desc,$stopwords_removed,$query_type);
408
409 my @results;
410
411 ## I. BUILD THE QUERY
412 my $lang = C4::Templates::getlanguage($cgi, 'opac');
413 ( $error,$query,$simple_query,$query_cgi,$query_desc,$limit,$limit_cgi,$limit_desc,$stopwords_removed,$query_type) = buildQuery(\@operators,\@operands,\@indexes,\@limits,\@sort_by, 0, $lang);
414
415 sub _input_cgi_parse {
416     my @elements;
417     for my $this_cgi ( split('&',shift) ) {
418         next unless $this_cgi;
419         $this_cgi =~ /(.*?)=(.*)/;
420         push @elements, { input_name => $1, input_value => $2 };
421     }
422     return @elements;
423 }
424
425 ## parse the query_cgi string and put it into a form suitable for <input>s
426 my @query_inputs = _input_cgi_parse($query_cgi);
427 $template->param ( QUERY_INPUTS => \@query_inputs );
428
429 ## parse the limit_cgi string and put it into a form suitable for <input>s
430 my @limit_inputs = $limit_cgi ? _input_cgi_parse($limit_cgi) : ();
431
432 # add OPAC 'hidelostitems'
433 #if (C4::Context->preference('hidelostitems') == 1) {
434 #    # either lost ge 0 or no value in the lost register
435 #    $query ="($query) and ( (lost,st-numeric <= 0) or ( allrecords,AlwaysMatches='' not lost,AlwaysMatches='') )";
436 #}
437 #
438 # add OPAC suppression - requires at least one item indexed with Suppress
439 if (C4::Context->preference('OpacSuppression')) {
440     $query = "($query) not Suppress=1";
441 }
442
443 $template->param ( LIMIT_INPUTS => \@limit_inputs );
444 $template->param ( OPACResultsSidebar => C4::Context->preference('OPACResultsSidebar'));
445
446 ## II. DO THE SEARCH AND GET THE RESULTS
447 my $total = 0; # the total results for the whole set
448 my $facets; # this object stores the faceted results that display on the left-hand of the results page
449 my @results_array;
450 my $results_hashref;
451 my @coins;
452
453 if ($tag) {
454     $query_cgi = "tag=" .$tag . "&" . $query_cgi;
455     my $taglist = get_tags({term=>$tag, approved=>1});
456     $results_hashref->{biblioserver}->{hits} = scalar (@$taglist);
457     my @biblist  = (map {GetBiblioData($_->{biblionumber})} @$taglist);
458     my @marclist = (map {$_->{marc}} @biblist );
459     $DEBUG and printf STDERR "taglist (%s biblionumber)\nmarclist (%s records)\n", scalar(@$taglist), scalar(@marclist);
460     $results_hashref->{biblioserver}->{RECORDS} = \@marclist;
461     # FIXME: tag search and standard search should work together, not exclusively
462     # FIXME: No facets for tags search.
463 }
464 elsif (C4::Context->preference('NoZebra')) {
465     eval {
466         ($error, $results_hashref, $facets) = NZgetRecords($query,$simple_query,\@sort_by,\@servers,$results_per_page,$offset,$expanded_facet,$branches,$query_type,$scan);
467     };
468 } elsif ($build_grouped_results) {
469     eval {
470         ($error, $results_hashref, $facets) = C4::Search::pazGetRecords($query,$simple_query,\@sort_by,\@servers,$results_per_page,$offset,$expanded_facet,$branches,$query_type,$scan);
471     };
472 } else {
473     $pasarParams .= '&amp;query=' . $query;
474     $pasarParams .= '&amp;count=' . $results_per_page;
475     $pasarParams .= '&amp;simple_query=' . $simple_query;
476     $pasarParams .= '&amp;query_type=' . $query_type if ($query_type);
477     eval {
478         ($error, $results_hashref, $facets) = getRecords($query,$simple_query,\@sort_by,\@servers,$results_per_page,$offset,$expanded_facet,$branches,$itemtypes,$query_type,$scan);
479     };
480 }
481 # This sorts the facets into alphabetical order
482 if ($facets) {
483     foreach my $f (@$facets) {
484         $f->{facets} = [ sort { uc($a->{facet_title_value}) cmp uc($b->{facet_title_value}) } @{ $f->{facets} } ];
485     }
486     @$facets = sort {$a->{expand} cmp $b->{expand}} @$facets;
487 }
488
489 # use Data::Dumper; print STDERR "-" x 25, "\n", Dumper($results_hashref);
490 if ($@ || $error) {
491     $template->param(query_error => $error.$@);
492     output_html_with_http_headers $cgi, $cookie, $template->output;
493     exit;
494 }
495
496 # At this point, each server has given us a result set
497 # now we build that set for template display
498 my @sup_results_array;
499 for (my $i=0;$i<@servers;$i++) {
500     my $server = $servers[$i];
501     if ($server && $server =~/biblioserver/) { # this is the local bibliographic server
502         $hits = $results_hashref->{$server}->{"hits"};
503         my $page = $cgi->param('page') || 0;
504         my @newresults;
505         if ($build_grouped_results) {
506             foreach my $group (@{ $results_hashref->{$server}->{"GROUPS"} }) {
507                 # because pazGetRecords handles retieving only the records
508                 # we want as specified by $offset and $results_per_page,
509                 # we need to set the offset parameter of searchResults to 0
510                 my @group_results = searchResults( 'opac', $query_desc, $group->{'group_count'},$results_per_page, 0, $scan,
511                                                    $group->{"RECORDS"});
512                 push @newresults, { group_label => $group->{'group_label'}, GROUP_RESULTS => \@group_results };
513             }
514         } else {
515             @newresults = searchResults('opac', $query_desc, $hits, $results_per_page, $offset, $scan,
516                                         $results_hashref->{$server}->{"RECORDS"});
517         }
518
519         # must define a value for size if not present in DB
520         # in order to avoid problems generated by the default size value in TT
521         foreach my $line (@newresults) {
522             if ( not exists $line->{'size'} ) { $line->{'size'} = "" }
523             # while we're checking each line, see if item is in the cart
524             if ( grep {$_ eq $line->{'biblionumber'}} @cart_list) {
525                 $line->{'incart'} = 1;
526             }
527         }
528
529
530         my $tag_quantity;
531         if (C4::Context->preference('TagsEnabled') and
532             $tag_quantity = C4::Context->preference('TagsShowOnList')) {
533             foreach (@newresults) {
534                 my $bibnum = $_->{biblionumber} or next;
535                 $_->{itemsissued} = CountItemsIssued( $bibnum );
536                 $_ ->{'TagLoop'} = get_tags({biblionumber=>$bibnum, approved=>1, 'sort'=>'-weight',
537                                         limit=>$tag_quantity });
538             }
539         }
540
541         if (C4::Context->preference('COinSinOPACResults')) {
542             foreach (@newresults) {
543                 my $record = GetMarcBiblio($_->{'biblionumber'});
544                 $_->{coins} = GetCOinSBiblio($record);
545                 if ( C4::Context->preference( "Babeltheque" ) and $_->{normalized_isbn} ) {
546                     my $isbn = Business::ISBN->new( $_->{normalized_isbn} );
547                     next if not $isbn;
548                     $isbn = $isbn->as_isbn13->as_string;
549                     $isbn =~ s/-//g;
550                     my $social_datas = C4::SocialData::get_data( $isbn );
551                     next if not $social_datas;
552                     for my $key ( keys %$social_datas ) {
553                         $_->{$key} = $$social_datas{$key};
554                         if ( $key eq 'score_avg' ){
555                             $_->{score_int} = sprintf("%.0f", $$social_datas{score_avg} );
556                         }
557                     }
558                 }
559             }
560         }
561
562
563         if ( C4::Context->preference('OpacStarRatings') eq 'all' ) {
564             foreach my $res (@newresults) {
565                 my $rating = GetRating( $res->{'biblionumber'}, $borrowernumber );
566                 $res->{'rating_value'}  = $rating->{'rating_value'};
567                 $res->{'rating_total'}  = $rating->{'rating_total'};
568                 $res->{'rating_avg'}    = $rating->{'rating_avg'};
569                 $res->{'rating_avg_int'} = $rating->{'rating_avg_int'};
570             }
571         }
572
573         if ($results_hashref->{$server}->{"hits"}){
574             $total = $total + $results_hashref->{$server}->{"hits"};
575         }
576
577         # Opac search history
578         my $newsearchcookie;
579         if (C4::Context->preference('EnableOpacSearchHistory')) {
580             my @recentSearches;
581
582             # Getting the (maybe) already sent cookie
583             my $searchcookie = $cgi->cookie('KohaOpacRecentSearches');
584             if ($searchcookie){
585                 $searchcookie = uri_unescape($searchcookie);
586                 if (thaw($searchcookie)) {
587                     @recentSearches = @{thaw($searchcookie)};
588                 }
589             }
590
591             # Adding the new search if needed
592             my $path_info = $cgi->url(-path_info=>1);
593             $query_cgi = $cgi->url(-query=>1);
594             $query_cgi =~ s/^$path_info\?//;
595             $query_cgi =~ s/;/&/g;
596             $query_desc .= ", $limit_desc";
597
598             if (!$borrowernumber || $borrowernumber eq '') {
599                 # To a cookie (the user is not logged in)
600                 if (($params->{'offset'}||'') eq '') {
601                     push @recentSearches, {
602                                 "query_desc" => $query_desc || "unknown",
603                                 "query_cgi"  => $query_cgi  || "unknown",
604                                 "time"       => time(),
605                                 "total"      => $total
606                               };
607                     $template->param(ShowOpacRecentSearchLink => 1);
608                 }
609
610                 shift @recentSearches if (@recentSearches > 15);
611                 # Pushing the cookie back
612                 $newsearchcookie = $cgi->cookie(
613                             -name => 'KohaOpacRecentSearches',
614                             # We uri_escape the whole freezed structure so we're sure we won't have any encoding problems
615                             -value => uri_escape(freeze(\@recentSearches)),
616                             -expires => ''
617                 );
618                 $cookie = [$cookie, $newsearchcookie];
619             }
620             else {
621                 # To the session (the user is logged in)
622                 if (($params->{'offset'}||'') eq '') {
623                     AddSearchHistory($borrowernumber, $cgi->cookie("CGISESSID"), $query_desc, $query_cgi, $total);
624                     $template->param(ShowOpacRecentSearchLink => 1);
625                 }
626             }
627         }
628         ## If there's just one result, redirect to the detail page
629         if ($total == 1 && $format ne 'rss2'
630         && $format ne 'opensearchdescription' && $format ne 'atom') {
631             my $biblionumber=$newresults[0]->{biblionumber};
632             if (C4::Context->preference('BiblioDefaultView') eq 'isbd') {
633                 print $cgi->redirect("/cgi-bin/koha/opac-ISBDdetail.pl?biblionumber=$biblionumber");
634             } elsif  (C4::Context->preference('BiblioDefaultView') eq 'marc') {
635                 print $cgi->redirect("/cgi-bin/koha/opac-MARCdetail.pl?biblionumber=$biblionumber");
636             } else {
637                 print $cgi->redirect("/cgi-bin/koha/opac-detail.pl?biblionumber=$biblionumber");
638             } 
639             exit;
640         }
641         if ($hits) {
642             if (!C4::Context->preference('NoZebra') && !$build_grouped_results) {
643                 # We build the encrypted list of first OPACnumSearchResults biblios to pass with the search criteria for paging on opac-detail
644                 $pasarParams .= '&amp;listBiblios=';
645                 my $j = 0;
646                 foreach (@newresults) {
647                     my $bibnum = ($_->{biblionumber})?$_->{biblionumber}:0;
648                     $pasarParams .= $bibnum . ',';
649                     $j++;
650                     last if ($j == $results_per_page);
651                 }
652                 chop $pasarParams if ($pasarParams =~ /,$/);
653                 $pasarParams .= '&amp;total=' . int($total) if ($pasarParams !~ /total=(?:[0-9]+)?/);
654                 if ($pasarParams) {
655                     my $session = get_session($cgi->cookie("CGISESSID"));
656                     $session->param('busc' => $pasarParams);
657                 }
658                 #
659             }
660             $template->param(total => $hits);
661             my $limit_cgi_not_availablity = $limit_cgi;
662             $limit_cgi_not_availablity =~ s/&limit=available//g if defined $limit_cgi_not_availablity;
663             $template->param(limit_cgi_not_availablity => $limit_cgi_not_availablity);
664             $template->param(limit_cgi => $limit_cgi);
665             $template->param(countrss  => $countRSS );
666             $template->param(query_cgi => $query_cgi);
667             $template->param(query_desc => $query_desc);
668             $template->param(limit_desc => $limit_desc);
669             $template->param(offset     => $offset);
670             $template->param(DisplayMultiPlaceHold => $DisplayMultiPlaceHold);
671             if ($query_desc || $limit_desc) {
672                 $template->param(searchdesc => 1);
673             }
674             $template->param(stopwords_removed => "@$stopwords_removed") if $stopwords_removed;
675             $template->param(results_per_page =>  $results_per_page);
676             my $hide = C4::Context->preference('OpacHiddenItems');
677             $hide = ($hide =~ m/\S/) if $hide; # Just in case it has some spaces/new lines
678             $template->param(
679                 SEARCH_RESULTS => \@newresults,
680                 OPACItemsResultsDisplay => (C4::Context->preference("OPACItemsResultsDisplay") eq "itemdetails"?1:0),
681                 suppress_result_number => $hide,
682                             );
683             if (C4::Context->preference("OPACLocalCoverImages")){
684                 $template->param(OPACLocalCoverImages => 1);
685                 $template->param(OPACLocalCoverImagesPriority => C4::Context->preference("OPACLocalCoverImagesPriority"));
686             }
687             ## Build the page numbers on the bottom of the page
688             my @page_numbers;
689             # total number of pages there will be
690             my $pages = ceil($hits / $results_per_page);
691             # default page number
692             my $current_page_number = 1;
693             if ($offset) {
694                 $current_page_number = ( $offset / $results_per_page + 1 );
695             }
696             my $previous_page_offset;
697             if ( $offset >= $results_per_page ) {
698                 $previous_page_offset = $offset - $results_per_page;
699             }
700             my $next_page_offset = $offset + $results_per_page;
701             # If we're within the first 10 pages, keep it simple
702             #warn "current page:".$current_page_number;
703             if ($current_page_number < 10) {
704                 # just show the first 10 pages
705                 # Loop through the pages
706                 my $pages_to_show = 10;
707                 $pages_to_show = $pages if $pages<10;
708                 for ($i=1; $i<=$pages_to_show;$i++) {
709                     # the offset for this page
710                     my $this_offset = (($i*$results_per_page)-$results_per_page);
711                     # the page number for this page
712                     my $this_page_number = $i;
713                     # put it in the array
714                     push @page_numbers,
715                       { offset    => $this_offset,
716                         pg        => $this_page_number,
717                         highlight => $this_page_number == $current_page_number,
718                         sort_by   => join ' ', @sort_by
719                       };
720
721                 }
722                         
723             }
724             # now, show twenty pages, with the current one smack in the middle
725             else {
726                 for ($i=$current_page_number; $i<=($current_page_number + 20 );$i++) {
727                     my $this_offset = ((($i-9)*$results_per_page)-$results_per_page);
728                     my $this_page_number = $i-9;
729                     if ( $this_page_number <= $pages ) {
730                         push @page_numbers,
731                           { offset    => $this_offset,
732                             pg        => $this_page_number,
733                             highlight => $this_page_number == $current_page_number,
734                             sort_by => join ' ', @sort_by
735                           };
736                     }
737                 }
738                         
739             }
740             $template->param(   PAGE_NUMBERS => \@page_numbers,
741                                 previous_page_offset => $previous_page_offset) unless $pages < 2;
742             $template->param(next_page_offset => $next_page_offset) unless $pages eq $current_page_number;
743         }
744         # no hits
745         else {
746             $template->param(
747                 searchdesc => 1,
748                 query_desc => $query_desc,
749                 limit_desc => $limit_desc,
750                 query_cgi  => $query_cgi,
751                 limit_cgi  => $limit_cgi
752             );
753         }
754     } # end of the if local
755     # asynchronously search the authority server
756     elsif ($server && $server =~/authorityserver/) { # this is the local authority server
757         my @inner_sup_results_array;
758         for my $sup_record ( @{$results_hashref->{$server}->{"RECORDS"}} ) {
759             my $marc_record_object = MARC::Record->new_from_usmarc($sup_record);
760             my $title_field = $marc_record_object->field(100);
761             push @inner_sup_results_array, {
762                 'title' => $title_field->subfield('a'),
763                 'link' => "&amp;idx=an&amp;q=".$marc_record_object->field('001')->as_string(),
764             };
765         }
766         my $servername = $server;
767         push @sup_results_array, {  servername => $servername,
768                                     inner_sup_results_loop => \@inner_sup_results_array} if @inner_sup_results_array;
769     }
770     # FIXME: can add support for other targets as needed here
771     $template->param(           outer_sup_results_loop => \@sup_results_array);
772 } #/end of the for loop
773 #$template->param(FEDERATED_RESULTS => \@results_array);
774
775 $template->param(
776             #classlist => $classlist,
777             total => $total,
778             opacfacets => 1,
779             facets_loop => $facets,
780             displayFacetCount=> C4::Context->preference('displayFacetCount')||0,
781             scan => $scan,
782             search_error => $error,
783 );
784
785 if ($query_desc || $limit_desc) {
786     $template->param(searchdesc => 1);
787 }
788
789 # VI. BUILD THE TEMPLATE
790 # Build drop-down list for 'Add To:' menu...
791 my ($totalref, $pubshelves, $barshelves)=
792         C4::VirtualShelves::GetSomeShelfNames($borrowernumber,'COMBO',1);
793 $template->param(
794         addbarshelves     => $totalref->{bartotal},
795         addbarshelvesloop => $barshelves,
796         addpubshelves     => $totalref->{pubtotal},
797         addpubshelvesloop => $pubshelves,
798         );
799
800 my $content_type = ($format eq 'rss' or $format eq 'atom') ? $format : 'html';
801
802 # If GoogleIndicTransliteration system preference is On Set paramter to load Google's javascript in OPAC search screens 
803 if (C4::Context->preference('GoogleIndicTransliteration')) {
804         $template->param('GoogleIndicTransliteration' => 1);
805 }
806
807     $template->param( borrowernumber    => $borrowernumber);
808 output_with_http_headers $cgi, $cookie, $template->output, $content_type;