Use Google Indic Transliteration API to allow users to transliterate english typed...
[koha.git] / opac / opac-search.pl
1 #!/usr/bin/perl
2 # Script to perform searching
3 # Mostly copied from search.pl, see POD there
4 use strict;            # always use
5 use warnings;
6
7 ## STEP 1. Load things that are used in both search page and
8 # results page and decide which template to load, operations 
9 # to perform, etc.
10 ## load Koha modules
11 use C4::Context;
12 use C4::Output;
13 use C4::Auth qw(:DEFAULT get_session);
14 use C4::Search;
15 use C4::Biblio;  # GetBiblioData
16 use C4::Koha;
17 use C4::Tags qw(get_tags);
18 use POSIX qw(ceil floor strftime);
19 use C4::Branch; # GetBranches
20
21 # create a new CGI object
22 # FIXME: no_undef_params needs to be tested
23 use CGI qw('-no_undef_params');
24 my $cgi = new CGI;
25
26 BEGIN {
27         if (C4::Context->preference('BakerTaylorEnabled')) {
28                 require C4::External::BakerTaylor;
29                 import C4::External::BakerTaylor qw(&image_url &link_url);
30         }
31 }
32
33 my ($template,$borrowernumber,$cookie);
34
35 # decide which template to use
36 my $template_name;
37 my $template_type = 'basic';
38 my @params = $cgi->param("limit");
39
40 my $build_grouped_results = C4::Context->preference('OPACGroupResults');
41 if ($cgi->param("format") && $cgi->param("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 ($cgi->param("format") && $cgi->param("format") eq 'rss2') {
64         $template->param("rss2" => 1);
65 }
66 elsif ($cgi->param("format") && $cgi->param("format") eq 'atom') {
67         $template->param("atom" => 1);
68     # FIXME - the timestamp is a hack - the biblio update timestamp should be used for each
69     # entry, but not sure if that's worth an extra database query for each bib
70     $template->param(timestamp => strftime("%Y-%m-%dT%H:%M:%S-00:00", gmtime));
71 }
72 elsif ($cgi->param("format") && $cgi->param("format") eq 'opensearchdescription') {
73         $template->param("opensearchdescription" => 1);
74 }
75 if (C4::Context->preference("marcflavour") eq "UNIMARC" ) {
76     $template->param('UNIMARC' => 1);
77 }
78 if (C4::Context->preference("marcflavour") eq "MARC21" ) {
79     $template->param('usmarc' => 1);
80 }
81
82 if (C4::Context->preference('BakerTaylorEnabled')) {
83         $template->param(
84                 BakerTaylorEnabled  => 1,
85                 BakerTaylorImageURL => &image_url(),
86                 BakerTaylorLinkURL  => &link_url(),
87                 BakerTaylorBookstoreURL => C4::Context->preference('BakerTaylorBookstoreURL'),
88         );
89 }
90 if (C4::Context->preference('TagsEnabled')) {
91         $template->param(TagsEnabled => 1);
92         foreach (qw(TagsShowOnList TagsInputOnList)) {
93                 C4::Context->preference($_) and $template->param($_ => 1);
94         }
95 }
96
97 ## URI Re-Writing
98 # Deprecated, but preserved because it's interesting :-)
99 # The same thing can be accomplished with mod_rewrite in
100 # a more elegant way
101 #                  
102 #my $rewrite_flag;
103 #my $uri = $cgi->url(-base => 1);
104 #my $relative_url = $cgi->url(-relative=>1);
105 #$uri.="/".$relative_url."?";
106 #warn "URI:$uri";
107 #my @cgi_params_list = $cgi->param();
108 #my $url_params = $cgi->Vars;
109 #
110 #for my $each_param_set (@cgi_params_list) {
111 #    $uri.= join "",  map "\&$each_param_set=".$_, split("\0",$url_params->{$each_param_set}) if $url_params->{$each_param_set};
112 #}
113 #warn "New URI:$uri";
114 # Only re-write a URI if there are params or if it already hasn't been re-written
115 #unless (($cgi->param('r')) || (!$cgi->param()) ) {
116 #    print $cgi->redirect(     -uri=>$uri."&r=1",
117 #                            -cookie => $cookie);
118 #    exit;
119 #}
120
121 # load the branches
122 my $mybranch = ( C4::Context->preference( 'SearchMyLibraryFirst' ) && C4::Context->userenv ) ? C4::Context->userenv->{branch} : '';
123 my $branches = GetBranches();
124 # FIXME: next line duplicates GetBranchesLoop(0,0);
125 my @branch_loop = map {
126                     {
127                         value => $_,
128                         branchname => $branches->{$_}->{branchname},
129                         selected => ( $mybranch eq $_ ) ? 1 : 0
130                     }
131                 } sort {
132                     $branches->{$a}->{branchname} cmp $branches->{$b}->{branchname}
133                 } keys %$branches;
134
135 my $categories = GetBranchCategories(undef,'searchdomain');
136
137 $template->param(branchloop => \@branch_loop, searchdomainloop => $categories);
138
139 # load the Type stuff
140 my $itemtypes = GetItemTypes;
141 # the index parameter is different for item-level itemtypes
142 my $itype_or_itemtype = (C4::Context->preference("item-level_itypes"))?'itype':'itemtype';
143 my @itemtypesloop;
144 my $selected=1;
145 my $cnt;
146 my $advanced_search_types = C4::Context->preference("AdvancedSearchTypes");
147
148 if (!$advanced_search_types or $advanced_search_types eq 'itemtypes') {
149         foreach my $thisitemtype ( sort {$itemtypes->{$a}->{'description'} cmp $itemtypes->{$b}->{'description'} } keys %$itemtypes ) {
150     my %row =(  number=>$cnt++,
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                                 ccl => $advanced_search_types,
168                 code => $thisitemtype->{authorised_value},
169                 selected => $selected,
170                 description => $thisitemtype->{'lib'},
171                 count5 => $cnt % 4,
172                 imageurl=> getitemtypeimagelocation( 'opac', $thisitemtype->{'imageurl'} ),
173             );
174                 push @itemtypesloop, \%row;
175         }
176         $template->param(itemtypeloop => \@itemtypesloop);
177 }
178
179 # # load the itypes (Called item types in the template -- just authorized values for searching)
180 # my ($itypecount,@itype_loop) = GetCcodes();
181 # $template->param(itypeloop=>\@itype_loop,);
182
183 # The following should only be loaded if we're bringing up the advanced search template
184 if ( $template_type && $template_type eq 'advsearch' ) {
185
186     # load the servers (used for searching -- to do federated searching, etc.)
187     my $primary_servers_loop;# = displayPrimaryServers();
188     $template->param(outer_servers_loop =>  $primary_servers_loop,);
189     
190     my $secondary_servers_loop;# = displaySecondaryServers();
191     $template->param(outer_sup_servers_loop => $secondary_servers_loop,);
192
193     # set the default sorting
194     my $default_sort_by = C4::Context->preference('OPACdefaultSortField')."_".C4::Context->preference('OPACdefaultSortOrder') 
195         if (C4::Context->preference('OPACdefaultSortField') && C4::Context->preference('OPACdefaultSortOrder'));
196     $template->param($default_sort_by => 1);
197
198     # determine what to display next to the search boxes (ie, boolean option
199     # shouldn't appear on the first one, scan indexes should, adding a new
200     # box should only appear on the last, etc.
201     my @search_boxes_array;
202     my $search_boxes_count = C4::Context->preference("OPACAdvSearchInputCount") || 3; # FIXME: should be a syspref
203     for (my $i=1;$i<=$search_boxes_count;$i++) {
204         # if it's the first one, don't display boolean option, but show scan indexes
205         if ($i==1) {
206             push @search_boxes_array,
207                 {
208                 scan_index => 1,
209                 };
210         
211         }
212         # if it's the last one, show the 'add field' box
213         elsif ($i==$search_boxes_count) {
214             push @search_boxes_array,
215                 {
216                 boolean => 1,
217                 add_field => 1,
218                 };
219         }
220         else {
221             push @search_boxes_array,
222                 {
223                 boolean => 1,
224                 };
225         }
226
227     }
228     $template->param(uc(C4::Context->preference("marcflavour")) => 1,
229                                           advsearch => 1,
230                       search_boxes_loop => \@search_boxes_array);
231
232 # use the global setting by default
233         if ( C4::Context->preference("expandedSearchOption") ) {
234                 $template->param( expanded_options => C4::Context->preference("expandedSearchOption") );
235         }
236         # but let the user override it
237         if ( $cgi->param("expanded_options") && (($cgi->param('expanded_options') == 0) || ($cgi->param('expanded_options') == 1 )) ) {
238         $template->param( expanded_options => $cgi->param('expanded_options'));
239         }
240
241     output_html_with_http_headers $cgi, $cookie, $template->output;
242     exit;
243 }
244
245 ### OK, if we're this far, we're performing an actual search
246
247 # Fetch the paramater list as a hash in scalar context:
248 #  * returns paramater list as tied hash ref
249 #  * we can edit the values by changing the key
250 #  * multivalued CGI paramaters are returned as a packaged string separated by "\0" (null)
251 my $params = $cgi->Vars;
252 my $tag;
253 $tag = $params->{tag} if $params->{tag};
254
255 # Params that can have more than one value
256 # sort by is used to sort the query
257 # in theory can have more than one but generally there's just one
258 my @sort_by;
259 my $default_sort_by = C4::Context->preference('OPACdefaultSortField')."_".C4::Context->preference('OPACdefaultSortOrder') 
260     if (C4::Context->preference('OPACdefaultSortField') && C4::Context->preference('OPACdefaultSortOrder'));
261
262 @sort_by = split("\0",$params->{'sort_by'}) if $params->{'sort_by'};
263 $sort_by[0] = $default_sort_by if !$sort_by[0] && defined($default_sort_by);
264 foreach my $sort (@sort_by) {
265     $template->param($sort => 1);
266 }
267 $template->param('sort_by' => $sort_by[0]);
268
269 # Use the servers defined, or just search our local catalog(default)
270 my @servers;
271 @servers = split("\0",$params->{'server'}) if $params->{'server'};
272 unless (@servers) {
273     #FIXME: this should be handled using Context.pm
274     @servers = ("biblioserver");
275     # @servers = C4::Context->config("biblioserver");
276 }
277
278 # operators include boolean and proximity operators and are used
279 # to evaluate multiple operands
280 my @operators;
281 @operators = split("\0",$params->{'op'}) if $params->{'op'};
282
283 # indexes are query qualifiers, like 'title', 'author', etc. They
284 # can be single or multiple parameters separated by comma: kw,right-Truncation 
285 my @indexes;
286 @indexes = split("\0",$params->{'idx'}) if $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 my @coins;
385
386 if ($tag) {
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 && $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                 }
449       
450         if ($results_hashref->{$server}->{"hits"}){
451             $total = $total + $results_hashref->{$server}->{"hits"};
452         }
453         ## If there's just one result, redirect to the detail page
454         if ($total == 1) {         
455             my $biblionumber=$newresults[0]->{biblionumber};
456             if (C4::Context->preference('BiblioDefaultView') eq 'isbd') {
457                 print $cgi->redirect("/cgi-bin/koha/opac-ISBDdetail.pl?biblionumber=$biblionumber");
458             } elsif  (C4::Context->preference('BiblioDefaultView') eq 'marc') {
459                 print $cgi->redirect("/cgi-bin/koha/opac-MARCdetail.pl?biblionumber=$biblionumber");
460             } else {
461                 print $cgi->redirect("/cgi-bin/koha/opac-detail.pl?biblionumber=$biblionumber");
462             } 
463             exit;
464         }
465         if ($hits) {
466             $template->param(total => $hits);
467             my $limit_cgi_not_availablity = $limit_cgi;
468             $limit_cgi_not_availablity =~ s/&limit=available//g if defined $limit_cgi_not_availablity;
469             $template->param(limit_cgi_not_availablity => $limit_cgi_not_availablity);
470             $template->param(limit_cgi => $limit_cgi);
471             $template->param(query_cgi => $query_cgi);
472             $template->param(query_desc => $query_desc);
473             $template->param(limit_desc => $limit_desc);
474             if ($query_desc || $limit_desc) {
475                 $template->param(searchdesc => 1);
476             }
477             $template->param(stopwords_removed => "@$stopwords_removed") if $stopwords_removed;
478             $template->param(results_per_page =>  $results_per_page);
479             $template->param(SEARCH_RESULTS => \@newresults,
480                                 OPACItemsResultsDisplay => (C4::Context->preference("OPACItemsResultsDisplay") eq "itemdetails"?1:0),
481                             );
482             ## Build the page numbers on the bottom of the page
483             my @page_numbers;
484             # total number of pages there will be
485             my $pages = ceil($hits / $results_per_page);
486             # default page number
487             my $current_page_number = 1;
488             $current_page_number = ($offset / $results_per_page + 1) if $offset;
489             my $previous_page_offset = $offset - $results_per_page unless ($offset - $results_per_page <0);
490             my $next_page_offset = $offset + $results_per_page;
491             # If we're within the first 10 pages, keep it simple
492             #warn "current page:".$current_page_number;
493             if ($current_page_number < 10) {
494                 # just show the first 10 pages
495                 # Loop through the pages
496                 my $pages_to_show = 10;
497                 $pages_to_show = $pages if $pages<10;
498                 for ($i=1; $i<=$pages_to_show;$i++) {
499                     # the offset for this page
500                     my $this_offset = (($i*$results_per_page)-$results_per_page);
501                     # the page number for this page
502                     my $this_page_number = $i;
503                     # it should only be highlighted if it's the current page
504                     my $highlight = 1 if ($this_page_number == $current_page_number);
505                     # put it in the array
506                     push @page_numbers, { offset => $this_offset, pg => $this_page_number, highlight => $highlight, sort_by => join " ",@sort_by };
507                                 
508                 }
509                         
510             }
511             # now, show twenty pages, with the current one smack in the middle
512             else {
513                 for ($i=$current_page_number; $i<=($current_page_number + 20 );$i++) {
514                     my $this_offset = ((($i-9)*$results_per_page)-$results_per_page);
515                     my $this_page_number = $i-9;
516                     my $highlight = 1 if ($this_page_number == $current_page_number);
517                     if ($this_page_number <= $pages) {
518                         push @page_numbers, { offset => $this_offset, pg => $this_page_number, highlight => $highlight, sort_by => join " ",@sort_by };
519                     }
520                 }
521                         
522             }
523             $template->param(   PAGE_NUMBERS => \@page_numbers,
524                                 previous_page_offset => $previous_page_offset) unless $pages < 2;
525             $template->param(next_page_offset => $next_page_offset) unless $pages eq $current_page_number;
526          }
527         # no hits
528         else {
529             $template->param(searchdesc => 1,query_desc => $query_desc,limit_desc => $limit_desc);
530         }
531     } # end of the if local
532     # asynchronously search the authority server
533     elsif ($server && $server =~/authorityserver/) { # this is the local authority server
534         my @inner_sup_results_array;
535         for my $sup_record ( @{$results_hashref->{$server}->{"RECORDS"}} ) {
536             my $marc_record_object = MARC::Record->new_from_usmarc($sup_record);
537             my $title_field = $marc_record_object->field(100);
538              warn "Authority Found: ".$marc_record_object->as_formatted();
539             push @inner_sup_results_array, {
540                 'title' => $title_field->subfield('a'),
541                 'link' => "&amp;idx=an&amp;q=".$marc_record_object->field('001')->as_string(),
542             };
543         }
544         my $servername = $server;
545         push @sup_results_array, {  servername => $servername,
546                                     inner_sup_results_loop => \@inner_sup_results_array} if @inner_sup_results_array;
547     }
548     # FIXME: can add support for other targets as needed here
549     $template->param(           outer_sup_results_loop => \@sup_results_array);
550 } #/end of the for loop
551 #$template->param(FEDERATED_RESULTS => \@results_array);
552
553 $template->param(
554             #classlist => $classlist,
555             total => $total,
556             opacfacets => 1,
557             facets_loop => $facets,
558             scan => $scan,
559             search_error => $error,
560 );
561
562 if ($query_desc || $limit_desc) {
563     $template->param(searchdesc => 1);
564 }
565
566 ## Now let's find out if we have any supplemental data to show the user
567 #  and in the meantime, save the current query for statistical purposes, etc.
568 my $koha_spsuggest; # a flag to tell if we've got suggestions coming from Koha
569 my @koha_spsuggest; # place we store the suggestions to be returned to the template as LOOP
570 my $phrases = $query_desc;
571 my $ipaddress;
572
573 if ( C4::Context->preference("kohaspsuggest") ) {
574         my ($suggest_host, $suggest_dbname, $suggest_user, $suggest_pwd) = split(':', C4::Context->preference("kohaspsuggest"));
575         eval {
576             my $koha_spsuggest_dbh;
577             # FIXME: this needs to be moved to Context.pm
578             eval {
579                 $koha_spsuggest_dbh=DBI->connect("DBI:mysql:$suggest_dbname:$suggest_host","$suggest_user","$suggest_pwd");
580             };
581             if ($@) { 
582                 warn "can't connect to spsuggest db";
583             }
584             else {
585                 my $koha_spsuggest_insert = "INSERT INTO phrase_log(phr_phrase,phr_resultcount,phr_ip) VALUES(?,?,?)";
586                 my $koha_spsuggest_query = "SELECT display FROM distincts WHERE strcmp(soundex(suggestion), soundex(?)) = 0 order by soundex(suggestion) limit 0,5";
587                 my $koha_spsuggest_sth = $koha_spsuggest_dbh->prepare($koha_spsuggest_query);
588                 $koha_spsuggest_sth->execute($phrases);
589                 while (my $spsuggestion = $koha_spsuggest_sth->fetchrow_array) {
590                     $spsuggestion =~ s/(:|\/)//g;
591                     my %line;
592                     $line{spsuggestion} = $spsuggestion;
593                     push @koha_spsuggest,\%line;
594                     $koha_spsuggest = 1;
595                 }
596
597                 # Now save the current query
598                 $koha_spsuggest_sth=$koha_spsuggest_dbh->prepare($koha_spsuggest_insert);
599                 #$koha_spsuggest_sth->execute($phrases,$results_per_page,$ipaddress);
600                 $koha_spsuggest_sth->finish;
601
602                 $template->param( koha_spsuggest => $koha_spsuggest ) unless $hits;
603                 $template->param( SPELL_SUGGEST => \@koha_spsuggest,
604                 );
605             }
606     };
607     if ($@) {
608             warn "Kohaspsuggest failure:".$@;
609     }
610 }
611
612 # VI. BUILD THE TEMPLATE
613 # Build drop-down list for 'Add To:' menu...
614 my $session = get_session($cgi->cookie("CGISESSID"));
615 my @addpubshelves;
616 my $pubshelves = $session->param('pubshelves');
617 my $barshelves = $session->param('barshelves');
618 foreach my $shelf (@$pubshelves) {
619         next if ( ($shelf->{'owner'} != ($borrowernumber ? $borrowernumber : -1)) && ($shelf->{'category'} < 3) );
620         push (@addpubshelves, $shelf);
621 }
622
623 if (@addpubshelves) {
624         $template->param( addpubshelves     => scalar (@addpubshelves));
625         $template->param( addpubshelvesloop => \@addpubshelves);
626 }
627
628 if (defined $barshelves) {
629         $template->param( addbarshelves     => scalar (@$barshelves));
630         $template->param( addbarshelvesloop => $barshelves);
631 }
632
633 my $content_type;
634
635 if ($cgi->param('format') && $cgi->param('format') =~ /rss/) {
636     $content_type = 'rss'
637 } elsif ($cgi->param('format') && $cgi->param('format') =~ /atom/) {
638     $content_type = 'atom'
639 } else {
640     $content_type = 'html'
641 }
642
643 # If GoogleIndicTransliteration system preference is On Set paramter to load Google's javascript in OPAC search screens 
644 if (C4::Context->preference('GoogleIndicTransliteration')) {
645         $template->param('GoogleIndicTransliteration' => 1);
646 }
647
648 output_with_http_headers $cgi, $cookie, $template->output, $content_type;