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