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