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