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