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