Styling facets; correcting markup error in search results; removing language picker...
[koha.git] / opac / opac-search.pl
1 #!/usr/bin/perl
2 # Script to perform searching
3 # Copied from search.pl
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 <<<<<<< HEAD:opac/opac-search.pl
104 # load the ccodes
105 # my ($ccodecount,@ccode_loop) = GetCcodes();
106 # $template->param(ccodeloop=>\@ccode_loop,);
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 >>>>>>> Styling facets; correcting markup error in search results; removing language picker from opac-main (is now in the footer); continuing unfinished work on cart/lists buttons:opac/opac-search.pl
112
113 # The following should only be loaded if we're bringing up the advanced search template
114 if ( $template_type eq 'advsearch' ) {
115
116     # load the servers (used for searching -- to do federated searching, etc.)
117     my $primary_servers_loop;# = displayPrimaryServers();
118     $template->param(outer_servers_loop =>  $primary_servers_loop,);
119     
120     my $secondary_servers_loop;# = displaySecondaryServers();
121     $template->param(outer_sup_servers_loop => $secondary_servers_loop,);
122     
123     # determine what to display next to the search boxes (ie, boolean option
124     # shouldn't appear on the first one, scan indexes should, adding a new
125     # box should only appear on the last, etc.
126     my @search_boxes_array;
127     my $search_boxes_count = C4::Context->preference("OPACAdvSearchInputCount") | 3; # FIXME: should be a syspref
128     for (my $i=1;$i<=$search_boxes_count;$i++) {
129         # if it's the first one, don't display boolean option, but show scan indexes
130         if ($i==1) {
131             push @search_boxes_array,
132                 {
133                 scan_index => 1,
134                 };
135         
136         }
137         # if it's the last one, show the 'add field' box
138         elsif ($i==$search_boxes_count) {
139             push @search_boxes_array,
140                 {
141                 boolean => 1,
142                 add_field => 1,
143                 };
144         }
145         else {
146             push @search_boxes_array,
147                 {
148                 boolean => 1,
149                 };
150         }
151
152     }
153     $template->param(uc(C4::Context->preference("marcflavour")) => 1,
154                       search_boxes_loop => \@search_boxes_array);
155
156 <<<<<<< HEAD:opac/opac-search.pl
157     # load the language limits (for search)
158     my $languages_limit_loop = getAllLanguages();
159     $template->param(search_languages_loop => $languages_limit_loop,);
160
161     # use the global setting by default
162     if ( C4::Context->preference("expandedSearchOption") == 1) {
163         $template->param( expanded_options => C4::Context->preference("expandedSearchOption") );
164     }
165     # but let the user override it
166     if ( ($cgi->param('expanded_options') == 0) || ($cgi->param('expanded_options') == 1 ) ) {
167         $template->param( expanded_options => $cgi->param('expanded_options'));
168     }
169 =======
170 # use the global setting by default
171         if ( C4::Context->preference("expandedSearchOption") == 1) {
172                 $template->param( expanded_options => C4::Context->preference("expandedSearchOption") );
173         }
174         # but let the user override it
175         if ( ($cgi->param('expanded_options') == 0) || ($cgi->param('expanded_options') == 1 ) ) {
176         $template->param( expanded_options => $cgi->param('expanded_options'));
177         }
178 >>>>>>> Styling facets; correcting markup error in search results; removing language picker from opac-main (is now in the footer); continuing unfinished work on cart/lists buttons:opac/opac-search.pl
179
180     output_html_with_http_headers $cgi, $cookie, $template->output;
181     exit;
182 }
183
184 ### OK, if we're this far, we're performing an actual search
185
186 # Fetch the paramater list as a hash in scalar context:
187 #  * returns paramater list as tied hash ref
188 #  * we can edit the values by changing the key
189 #  * multivalued CGI paramaters are returned as a packaged string separated by "\0" (null)
190 my $params = $cgi->Vars;
191
192 # Params that can have more than one value
193 # sort by is used to sort the query
194 # in theory can have more than one but generally there's just one
195 my @sort_by;
196 my $default_sort_by = C4::Context->preference('OPACdefaultSortField')."_".C4::Context->preference('OPACdefaultSortOrder') 
197     if (C4::Context->preference('OPACdefaultSortField') && C4::Context->preference('OPACdefaultSortOrder'));
198
199 @sort_by = split("\0",$params->{'sort_by'}) if $params->{'sort_by'};
200 $sort_by[0] = $default_sort_by unless $sort_by[0];
201 foreach my $sort (@sort_by) {
202     $template->param($sort => 1);
203 }
204 $template->param('sort_by' => $sort_by[0]);
205
206 # Use the servers defined, or just search our local catalog(default)
207 my @servers;
208 @servers = split("\0",$params->{'server'}) if $params->{'server'};
209 unless (@servers) {
210     #FIXME: this should be handled using Context.pm
211     @servers = ("biblioserver");
212     # @servers = C4::Context->config("biblioserver");
213 }
214
215 # operators include boolean and proximity operators and are used
216 # to evaluate multiple operands
217 my @operators;
218 @operators = split("\0",$params->{'op'}) if $params->{'op'};
219
220 # indexes are query qualifiers, like 'title', 'author', etc. They
221 # can be single or multiple parameters separated by comma: kw,right-Truncation 
222 my @indexes = split("\0",$params->{'idx'});
223
224 # if a simple index (only one)  display the index used in the top search box
225 if ($indexes[0] && !$indexes[1]) {
226     $template->param("ms_".$indexes[0] => 1);
227 }
228 # an operand can be a single term, a phrase, or a complete ccl query
229 my @operands;
230 @operands = split("\0",$params->{'q'}) if $params->{'q'};
231
232 # if a simple search, display the value in the search box
233 if ($operands[0] && !$operands[1]) {
234     $template->param(ms_value => $operands[0]);
235 }
236
237 # limits are use to limit to results to a pre-defined category such as branch or language
238 my @limits;
239 @limits = split("\0",$params->{'limit'}) if $params->{'limit'};
240
241 if($params->{'multibranchlimit'}) {
242 push @limits, join(" or ", map { "branch: $_ "}  @{GetBranchesInCategory($params->{'multibranchlimit'})}) ;
243 }
244
245 my $available;
246 foreach my $limit(@limits) {
247     if ($limit =~/available/) {
248         $available = 1;
249     }
250 }
251 $template->param(available => $available);
252
253 # append year limits if they exist
254 if ($params->{'limit-yr'}) {
255     if ($params->{'limit-yr'} =~ /\d{4}-\d{4}/) {
256         my ($yr1,$yr2) = split(/-/, $params->{'limit-yr'});
257         push @limits, "yr,st-numeric,ge=$yr1 and yr,st-numeric,le=$yr2";
258     }
259     elsif ($params->{'limit-yr'} =~ /\d{4}/) {
260         push @limits, "yr,st-numeric=$params->{'limit-yr'}";
261     }
262     else {
263         #FIXME: Should return a error to the user, incorect date format specified
264     }
265 }
266
267 # Params that can only have one value
268 my $scan = $params->{'scan'};
269 my $count = C4::Context->preference('OPACnumSearchResults') || 20;
270 my $results_per_page = $params->{'count'} || $count;
271 my $offset = $params->{'offset'} || 0;
272 my $page = $cgi->param('page') || 1;
273 #my $offset = ($page-1)*$results_per_page;
274 my $hits;
275 my $expanded_facet = $params->{'expand'};
276
277 # Define some global variables
278 my ($error,$query,$simple_query,$query_cgi,$query_desc,$limit,$limit_cgi,$limit_desc,$stopwords_removed,$query_type);
279
280 my @results;
281
282 ## I. BUILD THE QUERY
283 ( $error,$query,$simple_query,$query_cgi,$query_desc,$limit,$limit_cgi,$limit_desc,$stopwords_removed,$query_type) = buildQuery(\@operators,\@operands,\@indexes,\@limits,\@sort_by);
284
285 sub _input_cgi_parse ($) { 
286     my @elements;
287     for my $this_cgi ( split('&',shift) ) {
288         next unless $this_cgi;
289         $this_cgi =~ /(.*)=(.*)/;
290         my $input_name = $1;
291         my $input_value = $2;
292         push @elements, { input_name => $input_name, input_value => $input_value };
293     }
294     return @elements;
295 }
296
297 ## parse the query_cgi string and put it into a form suitable for <input>s
298 my @query_inputs = _input_cgi_parse($query_cgi);
299 $template->param ( QUERY_INPUTS => \@query_inputs );
300
301 ## parse the limit_cgi string and put it into a form suitable for <input>s
302 my @limit_inputs = _input_cgi_parse($query_cgi);
303
304 # add OPAC 'hidelostitems'
305 if (C4::Context->preference('hidelostitems') == 1) {
306     # either lost ge 0 or no value in the lost register
307     $query ="($query) and ( (lost,st-numeric <= 0) or ( allrecords,AlwaysMatches='' not lost,AlwaysMatches='') )";
308 }
309
310 # add OPAC suppression - requires at least one item indexed with Suppress
311 if (C4::Context->preference('OpacSuppression')) {
312     $query = "($query) not Suppress=1";
313 }
314
315 $template->param ( LIMIT_INPUTS => \@limit_inputs );
316
317 ## II. DO THE SEARCH AND GET THE RESULTS
318 my $total; # the total results for the whole set
319 my $facets; # this object stores the faceted results that display on the left-hand of the results page
320 my @results_array;
321 my $results_hashref;
322
323 if (C4::Context->preference('NoZebra')) {
324     eval {
325         ($error, $results_hashref, $facets) = NZgetRecords($query,$simple_query,\@sort_by,\@servers,$results_per_page,$offset,$expanded_facet,$branches,$query_type,$scan);
326     };
327 } else {
328     eval {
329         ($error, $results_hashref, $facets) = getRecords($query,$simple_query,\@sort_by,\@servers,$results_per_page,$offset,$expanded_facet,$branches,$query_type,$scan);
330     };
331 }
332 if ($@ || $error) {
333     $template->param(query_error => $error.$@);
334     output_html_with_http_headers $cgi, $cookie, $template->output;
335     exit;
336 }
337
338 # At this point, each server has given us a result set
339 # now we build that set for template display
340 my @sup_results_array;
341 for (my $i=0;$i<=@servers;$i++) {
342     my $server = $servers[$i];
343     if ($server =~/biblioserver/) { # this is the local bibliographic server
344         $hits = $results_hashref->{$server}->{"hits"};
345         my $page = $cgi->param('page') || 0;
346         my @newresults = searchResults( $query_desc,$hits,$results_per_page,$offset,@{$results_hashref->{$server}->{"RECORDS"}});
347         $total = $total + $results_hashref->{$server}->{"hits"};
348         if ($hits) {
349             $template->param(total => $hits);
350             my $limit_cgi_not_availablity = $limit_cgi;
351             $limit_cgi_not_availablity =~ s/&limit=available//g;
352             $template->param(limit_cgi_not_availablity => $limit_cgi_not_availablity);
353             $template->param(limit_cgi => $limit_cgi);
354             $template->param(query_cgi => $query_cgi);
355             $template->param(query_desc => $query_desc);
356             $template->param(limit_desc => $limit_desc);
357             if ($query_desc || $limit_desc) {
358                 $template->param(searchdesc => 1);
359             }
360             $template->param(stopwords_removed => "@$stopwords_removed") if $stopwords_removed;
361             $template->param(results_per_page =>  $results_per_page);
362             $template->param(SEARCH_RESULTS => \@newresults,
363                                 OPACItemsResultsDisplay => (C4::Context->preference("OPACItemsResultsDisplay") eq "itemdetails"?1:0),
364                             );
365             ## Build the page numbers on the bottom of the page
366             my @page_numbers;
367             # total number of pages there will be
368             my $pages = ceil($hits / $results_per_page);
369             # default page number
370             my $current_page_number = 1;
371             $current_page_number = ($offset / $results_per_page + 1) if $offset;
372             my $previous_page_offset = $offset - $results_per_page unless ($offset - $results_per_page <0);
373             my $next_page_offset = $offset + $results_per_page;
374             # If we're within the first 10 pages, keep it simple
375             #warn "current page:".$current_page_number;
376             if ($current_page_number < 10) {
377                 # just show the first 10 pages
378                 # Loop through the pages
379                 my $pages_to_show = 10;
380                 $pages_to_show = $pages if $pages<10;
381                 for ($i=1; $i<=$pages_to_show;$i++) {
382                     # the offset for this page
383                     my $this_offset = (($i*$results_per_page)-$results_per_page);
384                     # the page number for this page
385                     my $this_page_number = $i;
386                     # it should only be highlighted if it's the current page
387                     my $highlight = 1 if ($this_page_number == $current_page_number);
388                     # put it in the array
389                     push @page_numbers, { offset => $this_offset, pg => $this_page_number, highlight => $highlight, sort_by => join " ",@sort_by };
390                                 
391                 }
392                         
393             }
394             # now, show twenty pages, with the current one smack in the middle
395             else {
396                 for ($i=$current_page_number; $i<=($current_page_number + 20 );$i++) {
397                     my $this_offset = ((($i-9)*$results_per_page)-$results_per_page);
398                     my $this_page_number = $i-9;
399                     my $highlight = 1 if ($this_page_number == $current_page_number);
400                     if ($this_page_number <= $pages) {
401                         push @page_numbers, { offset => $this_offset, pg => $this_page_number, highlight => $highlight, sort_by => join " ",@sort_by };
402                     }
403                 }
404                         
405             }
406             $template->param(   PAGE_NUMBERS => \@page_numbers,
407                                 previous_page_offset => $previous_page_offset) unless $pages < 2;
408             $template->param(next_page_offset => $next_page_offset) unless $pages eq $current_page_number;
409          }
410         # no hits
411         else {
412             $template->param(searchdesc => 1,query_desc => $query_desc,limit_desc => $limit_desc);
413         }
414     } # end of the if local
415     else {
416         # check if it's a z3950 or opensearch source
417         my $zed3950 = 0;  # FIXME :: Hardcoded value.
418         if ($zed3950) {
419             my @inner_sup_results_array;
420             for my $sup_record ( @{$results_hashref->{$server}->{"RECORDS"}} ) {
421                 my $marc_record_object = MARC::Record->new_from_usmarc($sup_record);
422                 my $control_number = $marc_record_object->field('010')->subfield('a') if $marc_record_object->field('010');
423                 $control_number =~ s/^ //g;
424                 my $link = "http://catalog.loc.gov/cgi-bin/Pwebrecon.cgi?SAB1=".$control_number."&BOOL1=all+of+these&FLD1=LC+Control+Number+LCCN+%28K010%29+%28K010%29&GRP1=AND+with+next+set&SAB2=&BOOL2=all+of+these&FLD2=Keyword+Anywhere+%28GKEY%29+%28GKEY%29&PID=6211&SEQ=20060816121838&CNT=25&HIST=1";
425                 my $title = $marc_record_object->title();
426                 push @inner_sup_results_array, {
427                     'title' => $title,
428                     'link' => $link,
429                 };
430             }
431             my $servername = $server;
432             push @sup_results_array, { servername => $servername, inner_sup_results_loop => \@inner_sup_results_array};
433             $template->param(outer_sup_results_loop => \@sup_results_array);
434         }
435     }
436
437 } #/end of the for loop
438 #$template->param(FEDERATED_RESULTS => \@results_array);
439
440
441 $template->param(
442             #classlist => $classlist,
443             total => $total,
444             opacfacets => 1,
445             facets_loop => $facets,
446             scan => $scan,
447             search_error => $error,
448 );
449
450 if ($query_desc || $limit_desc) {
451     $template->param(searchdesc => 1);
452 }
453
454 ## Now let's find out if we have any supplemental data to show the user
455 #  and in the meantime, save the current query for statistical purposes, etc.
456 my $koha_spsuggest; # a flag to tell if we've got suggestions coming from Koha
457 my @koha_spsuggest; # place we store the suggestions to be returned to the template as LOOP
458 my $phrases = $query_desc;
459 my $ipaddress;
460
461 if ( C4::Context->preference("kohaspsuggest") ) {
462         my ($suggest_host, $suggest_dbname, $suggest_user, $suggest_pwd) = split(':', C4::Context->preference("kohaspsuggest"));
463         eval {
464             my $koha_spsuggest_dbh;
465             # FIXME: this needs to be moved to Context.pm
466             eval {
467                 $koha_spsuggest_dbh=DBI->connect("DBI:mysql:$suggest_dbname:$suggest_host","$suggest_user","$suggest_pwd");
468             };
469             if ($@) { 
470                 warn "can't connect to spsuggest db";
471             }
472             else {
473                 my $koha_spsuggest_insert = "INSERT INTO phrase_log(phr_phrase,phr_resultcount,phr_ip) VALUES(?,?,?)";
474                 my $koha_spsuggest_query = "SELECT display FROM distincts WHERE strcmp(soundex(suggestion), soundex(?)) = 0 order by soundex(suggestion) limit 0,5";
475                 my $koha_spsuggest_sth = $koha_spsuggest_dbh->prepare($koha_spsuggest_query);
476                 $koha_spsuggest_sth->execute($phrases);
477                 while (my $spsuggestion = $koha_spsuggest_sth->fetchrow_array) {
478                     $spsuggestion =~ s/(:|\/)//g;
479                     my %line;
480                     $line{spsuggestion} = $spsuggestion;
481                     push @koha_spsuggest,\%line;
482                     $koha_spsuggest = 1;
483                 }
484
485                 # Now save the current query
486                 $koha_spsuggest_sth=$koha_spsuggest_dbh->prepare($koha_spsuggest_insert);
487                 #$koha_spsuggest_sth->execute($phrases,$results_per_page,$ipaddress);
488                 $koha_spsuggest_sth->finish;
489
490                 $template->param( koha_spsuggest => $koha_spsuggest ) unless $hits;
491                 $template->param( SPELL_SUGGEST => \@koha_spsuggest,
492                 );
493             }
494     };
495     if ($@) {
496             warn "Kohaspsuggest failure:".$@;
497     }
498 }
499
500 # VI. BUILD THE TEMPLATE
501 output_html_with_http_headers $cgi, $cookie, $template->output;