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