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