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