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