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