Improving comments style and markup, adding highlighting for comments made by logged...
[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('opac');
95
96 foreach my $thisitemtype ( sort {$itemtypes->{$a}->{'description'} cmp $itemtypes->{$b}->{'description'} } keys %$itemtypes ) {
97     my %row =(  number=>$cnt++,
98                 imageurl=> $itemtypes->{$thisitemtype}->{'imageurl'}?($imgdir."/".$itemtypes->{$thisitemtype}->{'imageurl'}):"",
99                 code => $thisitemtype,
100                 selected => $selected,
101                 description => $itemtypes->{$thisitemtype}->{'description'},
102                 count5 => $cnt % 4,
103             );
104     $selected = 0 if ($selected) ;
105     push @itemtypesloop, \%row;
106 }
107 $template->param(itemtypeloop => \@itemtypesloop);
108
109 # # load the itypes (Called item types in the template -- just authorized values for searching)
110 # my ($itypecount,@itype_loop) = GetCcodes();
111 # $template->param(itypeloop=>\@itype_loop,);
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                                           advsearch => 1,
155                       search_boxes_loop => \@search_boxes_array);
156
157 # use the global setting by default
158         if ( C4::Context->preference("expandedSearchOption") == 1) {
159                 $template->param( expanded_options => C4::Context->preference("expandedSearchOption") );
160         }
161         # but let the user override it
162         if ( ($cgi->param('expanded_options') == 0) || ($cgi->param('expanded_options') == 1 ) ) {
163         $template->param( expanded_options => $cgi->param('expanded_options'));
164         }
165
166     output_html_with_http_headers $cgi, $cookie, $template->output;
167     exit;
168 }
169
170 ### OK, if we're this far, we're performing an actual search
171
172 # Fetch the paramater list as a hash in scalar context:
173 #  * returns paramater list as tied hash ref
174 #  * we can edit the values by changing the key
175 #  * multivalued CGI paramaters are returned as a packaged string separated by "\0" (null)
176 my $params = $cgi->Vars;
177
178 # Params that can have more than one value
179 # sort by is used to sort the query
180 # in theory can have more than one but generally there's just one
181 my @sort_by;
182 my $default_sort_by = C4::Context->preference('OPACdefaultSortField')."_".C4::Context->preference('OPACdefaultSortOrder') 
183     if (C4::Context->preference('OPACdefaultSortField') && C4::Context->preference('OPACdefaultSortOrder'));
184
185 @sort_by = split("\0",$params->{'sort_by'}) if $params->{'sort_by'};
186 $sort_by[0] = $default_sort_by unless $sort_by[0];
187 foreach my $sort (@sort_by) {
188     $template->param($sort => 1);
189 }
190 $template->param('sort_by' => $sort_by[0]);
191
192 # Use the servers defined, or just search our local catalog(default)
193 my @servers;
194 @servers = split("\0",$params->{'server'}) if $params->{'server'};
195 unless (@servers) {
196     #FIXME: this should be handled using Context.pm
197     @servers = ("biblioserver");
198     # @servers = C4::Context->config("biblioserver");
199 }
200
201 # operators include boolean and proximity operators and are used
202 # to evaluate multiple operands
203 my @operators;
204 @operators = split("\0",$params->{'op'}) if $params->{'op'};
205
206 # indexes are query qualifiers, like 'title', 'author', etc. They
207 # can be single or multiple parameters separated by comma: kw,right-Truncation 
208 my @indexes = split("\0",$params->{'idx'});
209
210 # if a simple index (only one)  display the index used in the top search box
211 if ($indexes[0] && !$indexes[1]) {
212     $template->param("ms_".$indexes[0] => 1);
213 }
214 # an operand can be a single term, a phrase, or a complete ccl query
215 my @operands;
216 @operands = split("\0",$params->{'q'}) if $params->{'q'};
217
218 # if a simple search, display the value in the search box
219 if ($operands[0] && !$operands[1]) {
220     $template->param(ms_value => $operands[0]);
221 }
222
223 # limits are use to limit to results to a pre-defined category such as branch or language
224 my @limits;
225 @limits = split("\0",$params->{'limit'}) if $params->{'limit'};
226
227 if($params->{'multibranchlimit'}) {
228 push @limits, join(" or ", map { "branch: $_ "}  @{GetBranchesInCategory($params->{'multibranchlimit'})}) ;
229 }
230
231 my $available;
232 foreach my $limit(@limits) {
233     if ($limit =~/available/) {
234         $available = 1;
235     }
236 }
237 $template->param(available => $available);
238
239 # append year limits if they exist
240 if ($params->{'limit-yr'}) {
241     if ($params->{'limit-yr'} =~ /\d{4}-\d{4}/) {
242         my ($yr1,$yr2) = split(/-/, $params->{'limit-yr'});
243         push @limits, "yr,st-numeric,ge=$yr1 and yr,st-numeric,le=$yr2";
244     }
245     elsif ($params->{'limit-yr'} =~ /\d{4}/) {
246         push @limits, "yr,st-numeric=$params->{'limit-yr'}";
247     }
248     else {
249         #FIXME: Should return a error to the user, incorect date format specified
250     }
251 }
252
253 # Params that can only have one value
254 my $scan = $params->{'scan'};
255 my $count = C4::Context->preference('OPACnumSearchResults') || 20;
256 my $results_per_page = $params->{'count'} || $count;
257 my $offset = $params->{'offset'} || 0;
258 my $page = $cgi->param('page') || 1;
259 #my $offset = ($page-1)*$results_per_page;
260 my $hits;
261 my $expanded_facet = $params->{'expand'};
262
263 # Define some global variables
264 my ($error,$query,$simple_query,$query_cgi,$query_desc,$limit,$limit_cgi,$limit_desc,$stopwords_removed,$query_type);
265
266 my @results;
267
268 ## I. BUILD THE QUERY
269 ( $error,$query,$simple_query,$query_cgi,$query_desc,$limit,$limit_cgi,$limit_desc,$stopwords_removed,$query_type) = buildQuery(\@operators,\@operands,\@indexes,\@limits,\@sort_by);
270
271 sub _input_cgi_parse ($) { 
272     my @elements;
273     for my $this_cgi ( split('&',shift) ) {
274         next unless $this_cgi;
275         $this_cgi =~ /(.*)=(.*)/;
276         my $input_name = $1;
277         my $input_value = $2;
278         push @elements, { input_name => $input_name, input_value => $input_value };
279     }
280     return @elements;
281 }
282
283 ## parse the query_cgi string and put it into a form suitable for <input>s
284 my @query_inputs = _input_cgi_parse($query_cgi);
285 $template->param ( QUERY_INPUTS => \@query_inputs );
286
287 ## parse the limit_cgi string and put it into a form suitable for <input>s
288 my @limit_inputs = _input_cgi_parse($limit_cgi);
289
290 # add OPAC 'hidelostitems'
291 if (C4::Context->preference('hidelostitems') == 1) {
292     # either lost ge 0 or no value in the lost register
293     $query ="($query) and ( (lost,st-numeric <= 0) or ( allrecords,AlwaysMatches='' not lost,AlwaysMatches='') )";
294 }
295
296 # add OPAC suppression - requires at least one item indexed with Suppress
297 if (C4::Context->preference('OpacSuppression')) {
298     $query = "($query) not Suppress=1";
299 }
300
301 $template->param ( LIMIT_INPUTS => \@limit_inputs );
302
303 ## II. DO THE SEARCH AND GET THE RESULTS
304 my $total; # the total results for the whole set
305 my $facets; # this object stores the faceted results that display on the left-hand of the results page
306 my @results_array;
307 my $results_hashref;
308
309 if (C4::Context->preference('NoZebra')) {
310     eval {
311         ($error, $results_hashref, $facets) = NZgetRecords($query,$simple_query,\@sort_by,\@servers,$results_per_page,$offset,$expanded_facet,$branches,$query_type,$scan);
312     };
313 } elsif ($build_grouped_results) {
314     eval {
315         ($error, $results_hashref, $facets) = C4::Search::pazGetRecords($query,$simple_query,\@sort_by,\@servers,$results_per_page,$offset,$expanded_facet,$branches,$query_type,$scan);
316     };
317 } else {
318     eval {
319         ($error, $results_hashref, $facets) = getRecords($query,$simple_query,\@sort_by,\@servers,$results_per_page,$offset,$expanded_facet,$branches,$query_type,$scan);
320     };
321 }
322 if ($@ || $error) {
323     $template->param(query_error => $error.$@);
324     output_html_with_http_headers $cgi, $cookie, $template->output;
325     exit;
326 }
327
328 # At this point, each server has given us a result set
329 # now we build that set for template display
330 my @sup_results_array;
331 for (my $i=0;$i<=@servers;$i++) {
332     my $server = $servers[$i];
333     if ($server =~/biblioserver/) { # this is the local bibliographic server
334         $hits = $results_hashref->{$server}->{"hits"};
335         my $page = $cgi->param('page') || 0;
336         my @newresults;
337         if ($build_grouped_results) {
338             foreach my $group (@{ $results_hashref->{$server}->{"GROUPS"} }) {
339                 # because pazGetRecords handles retieving only the records
340                 # we want as specified by $offset and $results_per_page,
341                 # we need to set the offset parameter of searchResults to 0
342                 my @group_results = searchResults( $query_desc, $group->{'group_count'},$results_per_page, 0,
343                                                    @{ $group->{"RECORDS"} });
344                 push @newresults, { group_label => $group->{'group_label'}, GROUP_RESULTS => \@group_results };
345             }
346         } else {
347             @newresults = searchResults( $query_desc,$hits,$results_per_page,$offset,@{$results_hashref->{$server}->{"RECORDS"}});
348         }
349         $total = $total + $results_hashref->{$server}->{"hits"};
350         ## If there's just one result, redirect to the detail page
351         if ($total == 1) {         
352             my $biblionumber=@newresults[0]->{biblionumber};
353             print $cgi->redirect("/cgi-bin/koha/opac-detail.pl?biblionumber=$biblionumber");
354             exit;
355         }
356         if ($hits) {
357             $template->param(total => $hits);
358             my $limit_cgi_not_availablity = $limit_cgi;
359             $limit_cgi_not_availablity =~ s/&limit=available//g;
360             $template->param(limit_cgi_not_availablity => $limit_cgi_not_availablity);
361             $template->param(limit_cgi => $limit_cgi);
362             $template->param(query_cgi => $query_cgi);
363             $template->param(query_desc => $query_desc);
364             $template->param(limit_desc => $limit_desc);
365             if ($query_desc || $limit_desc) {
366                 $template->param(searchdesc => 1);
367             }
368             $template->param(stopwords_removed => "@$stopwords_removed") if $stopwords_removed;
369             $template->param(results_per_page =>  $results_per_page);
370             $template->param(SEARCH_RESULTS => \@newresults,
371                                 OPACItemsResultsDisplay => (C4::Context->preference("OPACItemsResultsDisplay") eq "itemdetails"?1:0),
372                             );
373             ## Build the page numbers on the bottom of the page
374             my @page_numbers;
375             # total number of pages there will be
376             my $pages = ceil($hits / $results_per_page);
377             # default page number
378             my $current_page_number = 1;
379             $current_page_number = ($offset / $results_per_page + 1) if $offset;
380             my $previous_page_offset = $offset - $results_per_page unless ($offset - $results_per_page <0);
381             my $next_page_offset = $offset + $results_per_page;
382             # If we're within the first 10 pages, keep it simple
383             #warn "current page:".$current_page_number;
384             if ($current_page_number < 10) {
385                 # just show the first 10 pages
386                 # Loop through the pages
387                 my $pages_to_show = 10;
388                 $pages_to_show = $pages if $pages<10;
389                 for ($i=1; $i<=$pages_to_show;$i++) {
390                     # the offset for this page
391                     my $this_offset = (($i*$results_per_page)-$results_per_page);
392                     # the page number for this page
393                     my $this_page_number = $i;
394                     # it should only be highlighted if it's the current page
395                     my $highlight = 1 if ($this_page_number == $current_page_number);
396                     # put it in the array
397                     push @page_numbers, { offset => $this_offset, pg => $this_page_number, highlight => $highlight, sort_by => join " ",@sort_by };
398                                 
399                 }
400                         
401             }
402             # now, show twenty pages, with the current one smack in the middle
403             else {
404                 for ($i=$current_page_number; $i<=($current_page_number + 20 );$i++) {
405                     my $this_offset = ((($i-9)*$results_per_page)-$results_per_page);
406                     my $this_page_number = $i-9;
407                     my $highlight = 1 if ($this_page_number == $current_page_number);
408                     if ($this_page_number <= $pages) {
409                         push @page_numbers, { offset => $this_offset, pg => $this_page_number, highlight => $highlight, sort_by => join " ",@sort_by };
410                     }
411                 }
412                         
413             }
414             $template->param(   PAGE_NUMBERS => \@page_numbers,
415                                 previous_page_offset => $previous_page_offset) unless $pages < 2;
416             $template->param(next_page_offset => $next_page_offset) unless $pages eq $current_page_number;
417          }
418         # no hits
419         else {
420             $template->param(searchdesc => 1,query_desc => $query_desc,limit_desc => $limit_desc);
421         }
422     } # end of the if local
423     # asynchronously search the authority server
424     elsif ($server =~/authorityserver/) { # this is the local authority server
425         my @inner_sup_results_array;
426         for my $sup_record ( @{$results_hashref->{$server}->{"RECORDS"}} ) {
427             my $marc_record_object = MARC::Record->new_from_usmarc($sup_record);
428             my $title_field = $marc_record_object->field(100);
429              warn "Authority Found: ".$marc_record_object->as_formatted();
430             push @inner_sup_results_array, {
431                 'title' => $title_field->subfield('a'),
432                 'link' => "&amp;idx=an&amp;q=".$marc_record_object->field('001')->as_string(),
433             };
434         }
435         my $servername = $server;
436         push @sup_results_array, {  servername => $servername,
437                                     inner_sup_results_loop => \@inner_sup_results_array} if @inner_sup_results_array;
438     }
439     # FIXME: can add support for other targets as needed here
440     $template->param(           outer_sup_results_loop => \@sup_results_array);
441 } #/end of the for loop
442 #$template->param(FEDERATED_RESULTS => \@results_array);
443
444 $template->param(
445             #classlist => $classlist,
446             total => $total,
447             opacfacets => 1,
448             facets_loop => $facets,
449             scan => $scan,
450             search_error => $error,
451 );
452
453 if ($query_desc || $limit_desc) {
454     $template->param(searchdesc => 1);
455 }
456
457 ## Now let's find out if we have any supplemental data to show the user
458 #  and in the meantime, save the current query for statistical purposes, etc.
459 my $koha_spsuggest; # a flag to tell if we've got suggestions coming from Koha
460 my @koha_spsuggest; # place we store the suggestions to be returned to the template as LOOP
461 my $phrases = $query_desc;
462 my $ipaddress;
463
464 if ( C4::Context->preference("kohaspsuggest") ) {
465         my ($suggest_host, $suggest_dbname, $suggest_user, $suggest_pwd) = split(':', C4::Context->preference("kohaspsuggest"));
466         eval {
467             my $koha_spsuggest_dbh;
468             # FIXME: this needs to be moved to Context.pm
469             eval {
470                 $koha_spsuggest_dbh=DBI->connect("DBI:mysql:$suggest_dbname:$suggest_host","$suggest_user","$suggest_pwd");
471             };
472             if ($@) { 
473                 warn "can't connect to spsuggest db";
474             }
475             else {
476                 my $koha_spsuggest_insert = "INSERT INTO phrase_log(phr_phrase,phr_resultcount,phr_ip) VALUES(?,?,?)";
477                 my $koha_spsuggest_query = "SELECT display FROM distincts WHERE strcmp(soundex(suggestion), soundex(?)) = 0 order by soundex(suggestion) limit 0,5";
478                 my $koha_spsuggest_sth = $koha_spsuggest_dbh->prepare($koha_spsuggest_query);
479                 $koha_spsuggest_sth->execute($phrases);
480                 while (my $spsuggestion = $koha_spsuggest_sth->fetchrow_array) {
481                     $spsuggestion =~ s/(:|\/)//g;
482                     my %line;
483                     $line{spsuggestion} = $spsuggestion;
484                     push @koha_spsuggest,\%line;
485                     $koha_spsuggest = 1;
486                 }
487
488                 # Now save the current query
489                 $koha_spsuggest_sth=$koha_spsuggest_dbh->prepare($koha_spsuggest_insert);
490                 #$koha_spsuggest_sth->execute($phrases,$results_per_page,$ipaddress);
491                 $koha_spsuggest_sth->finish;
492
493                 $template->param( koha_spsuggest => $koha_spsuggest ) unless $hits;
494                 $template->param( SPELL_SUGGEST => \@koha_spsuggest,
495                 );
496             }
497     };
498     if ($@) {
499             warn "Kohaspsuggest failure:".$@;
500     }
501 }
502
503 # VI. BUILD THE TEMPLATE
504 output_html_with_http_headers $cgi, $cookie, $template->output;