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