FRBR: fixed paging through grouped results
[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::Koha;
15 use POSIX qw(ceil floor);
16 use C4::Branch; # GetBranches
17
18 # create a new CGI object
19 # FIXME: no_undef_params needs to be tested
20 use CGI qw('-no_undef_params');
21 my $cgi = new CGI;
22
23 my ($template,$borrowernumber,$cookie);
24
25 # decide which template to use
26 my $template_name;
27 my $template_type;
28 my @params = $cgi->param("limit");
29
30 my $build_grouped_results = C4::Context->preference('OPACGroupResults');
31 if ($build_grouped_results) {
32     $template_name = 'opac-results-grouped.tmpl';
33
34 elsif ((@params>=1) || ($cgi->param("q")) || ($cgi->param('multibranchlimit')) || ($cgi->param('limit-yr')) ) {
35     $template_name = 'opac-results.tmpl';
36 }
37 else {
38     $template_name = 'opac-advsearch.tmpl';
39     $template_type = 'advsearch';
40 }
41 # load the template
42 ($template, $borrowernumber, $cookie) = get_template_and_user({
43     template_name => $template_name,
44     query => $cgi,
45     type => "opac",
46     authnotrequired => 1,
47     }
48 );
49 if (C4::Context->preference("marcflavour") eq "UNIMARC" ) {
50     $template->param('UNIMARC' => 1);
51 }
52
53 ## URI Re-Writing
54 # Deprecated, but preserved because it's interesting :-)
55 # The same thing can be accomplished with mod_rewrite in
56 # a more elegant way
57 #                  
58 #my $rewrite_flag;
59 #my $uri = $cgi->url(-base => 1);
60 #my $relative_url = $cgi->url(-relative=>1);
61 #$uri.="/".$relative_url."?";
62 #warn "URI:$uri";
63 #my @cgi_params_list = $cgi->param();
64 #my $url_params = $cgi->Vars;
65 #
66 #for my $each_param_set (@cgi_params_list) {
67 #    $uri.= join "",  map "\&$each_param_set=".$_, split("\0",$url_params->{$each_param_set}) if $url_params->{$each_param_set};
68 #}
69 #warn "New URI:$uri";
70 # Only re-write a URI if there are params or if it already hasn't been re-written
71 #unless (($cgi->param('r')) || (!$cgi->param()) ) {
72 #    print $cgi->redirect(     -uri=>$uri."&r=1",
73 #                            -cookie => $cookie);
74 #    exit;
75 #}
76
77 # load the branches
78 my $branches = GetBranches();
79 my @branch_loop;
80
81 for my $branch_hash (sort keys %$branches) {
82     push @branch_loop, {value => "$branch_hash" , branchname => $branches->{$branch_hash}->{'branchname'}, };
83 }
84
85 my $categories = GetBranchCategories(undef,'searchdomain');
86
87 $template->param(branchloop => \@branch_loop, searchdomainloop => $categories);
88
89 # load the itemtypes
90 my $itemtypes = GetItemTypes;
91 my @itemtypesloop;
92 my $selected=1;
93 my $cnt;
94 my $imgdir = getitemtypeimagesrc();
95 foreach my $thisitemtype ( sort {$itemtypes->{$a}->{'description'} cmp $itemtypes->{$b}->{'description'} } keys %$itemtypes ) {
96     my %row =(  number=>$cnt++,
97                 imageurl=> $itemtypes->{$thisitemtype}->{'imageurl'}?($imgdir."/".$itemtypes->{$thisitemtype}->{'imageurl'}):"",
98                 code => $thisitemtype,
99                 selected => $selected,
100                 description => $itemtypes->{$thisitemtype}->{'description'},
101                 count5 => $cnt % 4,
102             );
103     $selected = 0 if ($selected) ;
104     push @itemtypesloop, \%row;
105 }
106 $template->param(itemtypeloop => \@itemtypesloop);
107
108 # # load the itypes (Called item types in the template -- just authorized values for searching)
109 # my ($itypecount,@itype_loop) = GetCcodes();
110 # $template->param(itypeloop=>\@itype_loop,);
111
112 # The following should only be loaded if we're bringing up the advanced search template
113 if ( $template_type eq 'advsearch' ) {
114
115     # load the servers (used for searching -- to do federated searching, etc.)
116     my $primary_servers_loop;# = displayPrimaryServers();
117     $template->param(outer_servers_loop =>  $primary_servers_loop,);
118     
119     my $secondary_servers_loop;# = displaySecondaryServers();
120     $template->param(outer_sup_servers_loop => $secondary_servers_loop,);
121     
122     # determine what to display next to the search boxes (ie, boolean option
123     # shouldn't appear on the first one, scan indexes should, adding a new
124     # box should only appear on the last, etc.
125     my @search_boxes_array;
126     my $search_boxes_count = C4::Context->preference("OPACAdvSearchInputCount") | 3; # FIXME: should be a syspref
127     for (my $i=1;$i<=$search_boxes_count;$i++) {
128         # if it's the first one, don't display boolean option, but show scan indexes
129         if ($i==1) {
130             push @search_boxes_array,
131                 {
132                 scan_index => 1,
133                 };
134         
135         }
136         # if it's the last one, show the 'add field' box
137         elsif ($i==$search_boxes_count) {
138             push @search_boxes_array,
139                 {
140                 boolean => 1,
141                 add_field => 1,
142                 };
143         }
144         else {
145             push @search_boxes_array,
146                 {
147                 boolean => 1,
148                 };
149         }
150
151     }
152     $template->param(uc(C4::Context->preference("marcflavour")) => 1,
153                                           advsearch => 1,
154                       search_boxes_loop => \@search_boxes_array);
155
156 # use the global setting by default
157         if ( C4::Context->preference("expandedSearchOption") == 1) {
158                 $template->param( expanded_options => C4::Context->preference("expandedSearchOption") );
159         }
160         # but let the user override it
161         if ( ($cgi->param('expanded_options') == 0) || ($cgi->param('expanded_options') == 1 ) ) {
162         $template->param( expanded_options => $cgi->param('expanded_options'));
163         }
164
165     output_html_with_http_headers $cgi, $cookie, $template->output;
166     exit;
167 }
168
169 ### OK, if we're this far, we're performing an actual search
170
171 # Fetch the paramater list as a hash in scalar context:
172 #  * returns paramater list as tied hash ref
173 #  * we can edit the values by changing the key
174 #  * multivalued CGI paramaters are returned as a packaged string separated by "\0" (null)
175 my $params = $cgi->Vars;
176
177 # Params that can have more than one value
178 # sort by is used to sort the query
179 # in theory can have more than one but generally there's just one
180 my @sort_by;
181 my $default_sort_by = C4::Context->preference('OPACdefaultSortField')."_".C4::Context->preference('OPACdefaultSortOrder') 
182     if (C4::Context->preference('OPACdefaultSortField') && C4::Context->preference('OPACdefaultSortOrder'));
183
184 @sort_by = split("\0",$params->{'sort_by'}) if $params->{'sort_by'};
185 $sort_by[0] = $default_sort_by unless $sort_by[0];
186 foreach my $sort (@sort_by) {
187     $template->param($sort => 1);
188 }
189 $template->param('sort_by' => $sort_by[0]);
190
191 # Use the servers defined, or just search our local catalog(default)
192 my @servers;
193 @servers = split("\0",$params->{'server'}) if $params->{'server'};
194 unless (@servers) {
195     #FIXME: this should be handled using Context.pm
196     @servers = ("biblioserver");
197     # @servers = C4::Context->config("biblioserver");
198 }
199
200 # operators include boolean and proximity operators and are used
201 # to evaluate multiple operands
202 my @operators;
203 @operators = split("\0",$params->{'op'}) if $params->{'op'};
204
205 # indexes are query qualifiers, like 'title', 'author', etc. They
206 # can be single or multiple parameters separated by comma: kw,right-Truncation 
207 my @indexes = split("\0",$params->{'idx'});
208
209 # if a simple index (only one)  display the index used in the top search box
210 if ($indexes[0] && !$indexes[1]) {
211     $template->param("ms_".$indexes[0] => 1);
212 }
213 # an operand can be a single term, a phrase, or a complete ccl query
214 my @operands;
215 @operands = split("\0",$params->{'q'}) if $params->{'q'};
216
217 # if a simple search, display the value in the search box
218 if ($operands[0] && !$operands[1]) {
219     $template->param(ms_value => $operands[0]);
220 }
221
222 # limits are use to limit to results to a pre-defined category such as branch or language
223 my @limits;
224 @limits = split("\0",$params->{'limit'}) if $params->{'limit'};
225
226 if($params->{'multibranchlimit'}) {
227 push @limits, join(" or ", map { "branch: $_ "}  @{GetBranchesInCategory($params->{'multibranchlimit'})}) ;
228 }
229
230 my $available;
231 foreach my $limit(@limits) {
232     if ($limit =~/available/) {
233         $available = 1;
234     }
235 }
236 $template->param(available => $available);
237
238 # append year limits if they exist
239 if ($params->{'limit-yr'}) {
240     if ($params->{'limit-yr'} =~ /\d{4}-\d{4}/) {
241         my ($yr1,$yr2) = split(/-/, $params->{'limit-yr'});
242         push @limits, "yr,st-numeric,ge=$yr1 and yr,st-numeric,le=$yr2";
243     }
244     elsif ($params->{'limit-yr'} =~ /\d{4}/) {
245         push @limits, "yr,st-numeric=$params->{'limit-yr'}";
246     }
247     else {
248         #FIXME: Should return a error to the user, incorect date format specified
249     }
250 }
251
252 # Params that can only have one value
253 my $scan = $params->{'scan'};
254 my $count = C4::Context->preference('OPACnumSearchResults') || 20;
255 my $results_per_page = $params->{'count'} || $count;
256 my $offset = $params->{'offset'} || 0;
257 my $page = $cgi->param('page') || 1;
258 #my $offset = ($page-1)*$results_per_page;
259 my $hits;
260 my $expanded_facet = $params->{'expand'};
261
262 # Define some global variables
263 my ($error,$query,$simple_query,$query_cgi,$query_desc,$limit,$limit_cgi,$limit_desc,$stopwords_removed,$query_type);
264
265 my @results;
266
267 ## I. BUILD THE QUERY
268 ( $error,$query,$simple_query,$query_cgi,$query_desc,$limit,$limit_cgi,$limit_desc,$stopwords_removed,$query_type) = buildQuery(\@operators,\@operands,\@indexes,\@limits,\@sort_by);
269
270 sub _input_cgi_parse ($) { 
271     my @elements;
272     for my $this_cgi ( split('&',shift) ) {
273         next unless $this_cgi;
274         $this_cgi =~ /(.*)=(.*)/;
275         my $input_name = $1;
276         my $input_value = $2;
277         push @elements, { input_name => $input_name, input_value => $input_value };
278     }
279     return @elements;
280 }
281
282 ## parse the query_cgi string and put it into a form suitable for <input>s
283 my @query_inputs = _input_cgi_parse($query_cgi);
284 $template->param ( QUERY_INPUTS => \@query_inputs );
285
286 ## parse the limit_cgi string and put it into a form suitable for <input>s
287 my @limit_inputs = _input_cgi_parse($limit_cgi);
288
289 # add OPAC 'hidelostitems'
290 if (C4::Context->preference('hidelostitems') == 1) {
291     # either lost ge 0 or no value in the lost register
292     $query ="($query) and ( (lost,st-numeric <= 0) or ( allrecords,AlwaysMatches='' not lost,AlwaysMatches='') )";
293 }
294
295 # add OPAC suppression - requires at least one item indexed with Suppress
296 if (C4::Context->preference('OpacSuppression')) {
297     $query = "($query) not Suppress=1";
298 }
299
300 $template->param ( LIMIT_INPUTS => \@limit_inputs );
301
302 ## II. DO THE SEARCH AND GET THE RESULTS
303 my $total; # the total results for the whole set
304 my $facets; # this object stores the faceted results that display on the left-hand of the results page
305 my @results_array;
306 my $results_hashref;
307
308 if (C4::Context->preference('NoZebra')) {
309     eval {
310         ($error, $results_hashref, $facets) = NZgetRecords($query,$simple_query,\@sort_by,\@servers,$results_per_page,$offset,$expanded_facet,$branches,$query_type,$scan);
311     };
312 } elsif ($build_grouped_results) {
313     eval {
314         ($error, $results_hashref, $facets) = C4::Search::pazGetRecords($query,$simple_query,\@sort_by,\@servers,$results_per_page,$offset,$expanded_facet,$branches,$query_type,$scan);
315     };
316 } else {
317     eval {
318         ($error, $results_hashref, $facets) = getRecords($query,$simple_query,\@sort_by,\@servers,$results_per_page,$offset,$expanded_facet,$branches,$query_type,$scan);
319     };
320 }
321 if ($@ || $error) {
322     $template->param(query_error => $error.$@);
323     output_html_with_http_headers $cgi, $cookie, $template->output;
324     exit;
325 }
326
327 # At this point, each server has given us a result set
328 # now we build that set for template display
329 my @sup_results_array;
330 for (my $i=0;$i<=@servers;$i++) {
331     my $server = $servers[$i];
332     if ($server =~/biblioserver/) { # this is the local bibliographic server
333         $hits = $results_hashref->{$server}->{"hits"};
334         my $page = $cgi->param('page') || 0;
335         my @newresults;
336         if ($build_grouped_results) {
337             foreach my $group (@{ $results_hashref->{$server}->{"GROUPS"} }) {
338                 # because pazGetRecords handles retieving only the records
339                 # we want as specified by $offset and $results_per_page,
340                 # we need to set the offset parameter of searchResults to 0
341                 my @group_results = searchResults( $query_desc, $group->{'group_count'},$results_per_page, 0,
342                                                    @{ $group->{"RECORDS"} });
343                 push @newresults, { group_label => $group->{'group_label'}, GROUP_RESULTS => \@group_results };
344             }
345         } else {
346             @newresults = searchResults( $query_desc,$hits,$results_per_page,$offset,@{$results_hashref->{$server}->{"RECORDS"}});
347         }
348         $total = $total + $results_hashref->{$server}->{"hits"};
349         if ($hits) {
350             $template->param(total => $hits);
351             my $limit_cgi_not_availablity = $limit_cgi;
352             $limit_cgi_not_availablity =~ s/&limit=available//g;
353             $template->param(limit_cgi_not_availablity => $limit_cgi_not_availablity);
354             $template->param(limit_cgi => $limit_cgi);
355             $template->param(query_cgi => $query_cgi);
356             $template->param(query_desc => $query_desc);
357             $template->param(limit_desc => $limit_desc);
358             if ($query_desc || $limit_desc) {
359                 $template->param(searchdesc => 1);
360             }
361             $template->param(stopwords_removed => "@$stopwords_removed") if $stopwords_removed;
362             $template->param(results_per_page =>  $results_per_page);
363             $template->param(SEARCH_RESULTS => \@newresults,
364                                 OPACItemsResultsDisplay => (C4::Context->preference("OPACItemsResultsDisplay") eq "itemdetails"?1:0),
365                             );
366             ## Build the page numbers on the bottom of the page
367             my @page_numbers;
368             # total number of pages there will be
369             my $pages = ceil($hits / $results_per_page);
370             # default page number
371             my $current_page_number = 1;
372             $current_page_number = ($offset / $results_per_page + 1) if $offset;
373             my $previous_page_offset = $offset - $results_per_page unless ($offset - $results_per_page <0);
374             my $next_page_offset = $offset + $results_per_page;
375             # If we're within the first 10 pages, keep it simple
376             #warn "current page:".$current_page_number;
377             if ($current_page_number < 10) {
378                 # just show the first 10 pages
379                 # Loop through the pages
380                 my $pages_to_show = 10;
381                 $pages_to_show = $pages if $pages<10;
382                 for ($i=1; $i<=$pages_to_show;$i++) {
383                     # the offset for this page
384                     my $this_offset = (($i*$results_per_page)-$results_per_page);
385                     # the page number for this page
386                     my $this_page_number = $i;
387                     # it should only be highlighted if it's the current page
388                     my $highlight = 1 if ($this_page_number == $current_page_number);
389                     # put it in the array
390                     push @page_numbers, { offset => $this_offset, pg => $this_page_number, highlight => $highlight, sort_by => join " ",@sort_by };
391                                 
392                 }
393                         
394             }
395             # now, show twenty pages, with the current one smack in the middle
396             else {
397                 for ($i=$current_page_number; $i<=($current_page_number + 20 );$i++) {
398                     my $this_offset = ((($i-9)*$results_per_page)-$results_per_page);
399                     my $this_page_number = $i-9;
400                     my $highlight = 1 if ($this_page_number == $current_page_number);
401                     if ($this_page_number <= $pages) {
402                         push @page_numbers, { offset => $this_offset, pg => $this_page_number, highlight => $highlight, sort_by => join " ",@sort_by };
403                     }
404                 }
405                         
406             }
407             $template->param(   PAGE_NUMBERS => \@page_numbers,
408                                 previous_page_offset => $previous_page_offset) unless $pages < 2;
409             $template->param(next_page_offset => $next_page_offset) unless $pages eq $current_page_number;
410          }
411         # no hits
412         else {
413             $template->param(searchdesc => 1,query_desc => $query_desc,limit_desc => $limit_desc);
414         }
415     } # end of the if local
416     # asynchronously search the authority server
417     elsif ($server =~/authorityserver/) { # this is the local authority server
418         my @inner_sup_results_array;
419         for my $sup_record ( @{$results_hashref->{$server}->{"RECORDS"}} ) {
420             my $marc_record_object = MARC::Record->new_from_usmarc($sup_record);
421             my $title_field = $marc_record_object->field(100);
422              warn "Authority Found: ".$marc_record_object->as_formatted();
423             push @inner_sup_results_array, {
424                 'title' => $title_field->subfield('a'),
425                 'link' => "&amp;idx=an&amp;q=".$marc_record_object->field('001')->as_string(),
426             };
427         }
428         my $servername = $server;
429         push @sup_results_array, {  servername => $servername,
430                                     inner_sup_results_loop => \@inner_sup_results_array} if @inner_sup_results_array;
431     }
432     # FIXME: can add support for other targets as needed here
433     $template->param(           outer_sup_results_loop => \@sup_results_array);
434 } #/end of the for loop
435 #$template->param(FEDERATED_RESULTS => \@results_array);
436
437 $template->param(
438             #classlist => $classlist,
439             total => $total,
440             opacfacets => 1,
441             facets_loop => $facets,
442             scan => $scan,
443             search_error => $error,
444 );
445
446 if ($query_desc || $limit_desc) {
447     $template->param(searchdesc => 1);
448 }
449
450 ## Now let's find out if we have any supplemental data to show the user
451 #  and in the meantime, save the current query for statistical purposes, etc.
452 my $koha_spsuggest; # a flag to tell if we've got suggestions coming from Koha
453 my @koha_spsuggest; # place we store the suggestions to be returned to the template as LOOP
454 my $phrases = $query_desc;
455 my $ipaddress;
456
457 if ( C4::Context->preference("kohaspsuggest") ) {
458         my ($suggest_host, $suggest_dbname, $suggest_user, $suggest_pwd) = split(':', C4::Context->preference("kohaspsuggest"));
459         eval {
460             my $koha_spsuggest_dbh;
461             # FIXME: this needs to be moved to Context.pm
462             eval {
463                 $koha_spsuggest_dbh=DBI->connect("DBI:mysql:$suggest_dbname:$suggest_host","$suggest_user","$suggest_pwd");
464             };
465             if ($@) { 
466                 warn "can't connect to spsuggest db";
467             }
468             else {
469                 my $koha_spsuggest_insert = "INSERT INTO phrase_log(phr_phrase,phr_resultcount,phr_ip) VALUES(?,?,?)";
470                 my $koha_spsuggest_query = "SELECT display FROM distincts WHERE strcmp(soundex(suggestion), soundex(?)) = 0 order by soundex(suggestion) limit 0,5";
471                 my $koha_spsuggest_sth = $koha_spsuggest_dbh->prepare($koha_spsuggest_query);
472                 $koha_spsuggest_sth->execute($phrases);
473                 while (my $spsuggestion = $koha_spsuggest_sth->fetchrow_array) {
474                     $spsuggestion =~ s/(:|\/)//g;
475                     my %line;
476                     $line{spsuggestion} = $spsuggestion;
477                     push @koha_spsuggest,\%line;
478                     $koha_spsuggest = 1;
479                 }
480
481                 # Now save the current query
482                 $koha_spsuggest_sth=$koha_spsuggest_dbh->prepare($koha_spsuggest_insert);
483                 #$koha_spsuggest_sth->execute($phrases,$results_per_page,$ipaddress);
484                 $koha_spsuggest_sth->finish;
485
486                 $template->param( koha_spsuggest => $koha_spsuggest ) unless $hits;
487                 $template->param( SPELL_SUGGEST => \@koha_spsuggest,
488                 );
489             }
490     };
491     if ($@) {
492             warn "Kohaspsuggest failure:".$@;
493     }
494 }
495
496 # VI. BUILD THE TEMPLATE
497 output_html_with_http_headers $cgi, $cookie, $template->output;