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