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