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