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