2 # Script to perform searching
3 # Copied from search.pl
4 use strict; # always use
6 ## STEP 1. Load things that are used in both search page and
7 # results page and decide which template to load, operations
15 use POSIX qw(ceil floor);
16 use C4::Branch; # GetBranches
18 # create a new CGI object
19 # FIXME: no_undef_params needs to be tested
20 use CGI qw('-no_undef_params');
23 my ($template,$borrowernumber,$cookie);
25 # decide which template to use
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';
33 $template_name = 'opac-advsearch.tmpl';
34 $template_type = 'advsearch';
37 ($template, $borrowernumber, $cookie) = get_template_and_user({
38 template_name => $template_name,
44 if (C4::Context->preference("marcflavour") eq "UNIMARC" ) {
45 $template->param('UNIMARC' => 1);
49 # Deprecated, but preserved because it's interesting :-)
50 # The same thing can be accomplished with mod_rewrite in
54 #my $uri = $cgi->url(-base => 1);
55 #my $relative_url = $cgi->url(-relative=>1);
56 #$uri.="/".$relative_url."?";
58 #my @cgi_params_list = $cgi->param();
59 #my $url_params = $cgi->Vars;
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};
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);
73 my $branches = GetBranches();
76 for my $branch_hash (sort keys %$branches) {
77 push @branch_loop, {value => "$branch_hash" , branchname => $branches->{$branch_hash}->{'branchname'}, };
80 my $categories = GetBranchCategories(undef,'searchdomain');
82 $template->param(branchloop => \@branch_loop, searchdomainloop => $categories);
85 my $itemtypes = GetItemTypes;
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'},
98 $selected = 0 if ($selected) ;
99 push @itemtypesloop, \%row;
101 $template->param(itemtypeloop => \@itemtypesloop);
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,);
107 # The following should only be loaded if we're bringing up the advanced search template
108 if ( $template_type eq 'advsearch' ) {
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,);
114 my $secondary_servers_loop;# = displaySecondaryServers();
115 $template->param(outer_sup_servers_loop => $secondary_servers_loop,);
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
125 push @search_boxes_array,
131 # if it's the last one, show the 'add field' box
132 elsif ($i==$search_boxes_count) {
133 push @search_boxes_array,
140 push @search_boxes_array,
147 $template->param(uc(C4::Context->preference("marcflavour")) => 1,
148 search_boxes_loop => \@search_boxes_array);
150 # use the global setting by default
151 if ( C4::Context->preference("expandedSearchOption") == 1) {
152 $template->param( expanded_options => C4::Context->preference("expandedSearchOption") );
154 # but let the user override it
155 if ( ($cgi->param('expanded_options') == 0) || ($cgi->param('expanded_options') == 1 ) ) {
156 $template->param( expanded_options => $cgi->param('expanded_options'));
159 output_html_with_http_headers $cgi, $cookie, $template->output;
163 ### OK, if we're this far, we're performing an actual search
165 # Fetch the paramater list as a hash in scalar context:
166 # * returns paramater list as tied hash ref
167 # * we can edit the values by changing the key
168 # * multivalued CGI paramaters are returned as a packaged string separated by "\0" (null)
169 my $params = $cgi->Vars;
171 # Params that can have more than one value
172 # sort by is used to sort the query
173 # in theory can have more than one but generally there's just one
175 my $default_sort_by = C4::Context->preference('OPACdefaultSortField')."_".C4::Context->preference('OPACdefaultSortOrder')
176 if (C4::Context->preference('OPACdefaultSortField') && C4::Context->preference('OPACdefaultSortOrder'));
178 @sort_by = split("\0",$params->{'sort_by'}) if $params->{'sort_by'};
179 $sort_by[0] = $default_sort_by unless $sort_by[0];
180 foreach my $sort (@sort_by) {
181 $template->param($sort => 1);
183 $template->param('sort_by' => $sort_by[0]);
185 # Use the servers defined, or just search our local catalog(default)
187 @servers = split("\0",$params->{'server'}) if $params->{'server'};
189 #FIXME: this should be handled using Context.pm
190 @servers = ("biblioserver");
191 # @servers = C4::Context->config("biblioserver");
194 # operators include boolean and proximity operators and are used
195 # to evaluate multiple operands
197 @operators = split("\0",$params->{'op'}) if $params->{'op'};
199 # indexes are query qualifiers, like 'title', 'author', etc. They
200 # can be single or multiple parameters separated by comma: kw,right-Truncation
201 my @indexes = split("\0",$params->{'idx'});
203 # if a simple index (only one) display the index used in the top search box
204 if ($indexes[0] && !$indexes[1]) {
205 $template->param("ms_".$indexes[0] => 1);
207 # an operand can be a single term, a phrase, or a complete ccl query
209 @operands = split("\0",$params->{'q'}) if $params->{'q'};
211 # if a simple search, display the value in the search box
212 if ($operands[0] && !$operands[1]) {
213 $template->param(ms_value => $operands[0]);
216 # limits are use to limit to results to a pre-defined category such as branch or language
218 @limits = split("\0",$params->{'limit'}) if $params->{'limit'};
220 if($params->{'multibranchlimit'}) {
221 push @limits, join(" or ", map { "branch: $_ "} @{GetBranchesInCategory($params->{'multibranchlimit'})}) ;
225 foreach my $limit(@limits) {
226 if ($limit =~/available/) {
230 $template->param(available => $available);
232 # append year limits if they exist
233 if ($params->{'limit-yr'}) {
234 if ($params->{'limit-yr'} =~ /\d{4}-\d{4}/) {
235 my ($yr1,$yr2) = split(/-/, $params->{'limit-yr'});
236 push @limits, "yr,st-numeric,ge=$yr1 and yr,st-numeric,le=$yr2";
238 elsif ($params->{'limit-yr'} =~ /\d{4}/) {
239 push @limits, "yr,st-numeric=$params->{'limit-yr'}";
242 #FIXME: Should return a error to the user, incorect date format specified
246 # Params that can only have one value
247 my $scan = $params->{'scan'};
248 my $count = C4::Context->preference('OPACnumSearchResults') || 20;
249 my $results_per_page = $params->{'count'} || $count;
250 my $offset = $params->{'offset'} || 0;
251 my $page = $cgi->param('page') || 1;
252 #my $offset = ($page-1)*$results_per_page;
254 my $expanded_facet = $params->{'expand'};
256 # Define some global variables
257 my ($error,$query,$simple_query,$query_cgi,$query_desc,$limit,$limit_cgi,$limit_desc,$stopwords_removed,$query_type);
261 ## I. BUILD THE QUERY
262 ( $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 sub _input_cgi_parse ($) {
266 for my $this_cgi ( split('&',shift) ) {
267 next unless $this_cgi;
268 $this_cgi =~ /(.*)=(.*)/;
270 my $input_value = $2;
271 push @elements, { input_name => $input_name, input_value => $input_value };
276 ## parse the query_cgi string and put it into a form suitable for <input>s
277 my @query_inputs = _input_cgi_parse($query_cgi);
278 $template->param ( QUERY_INPUTS => \@query_inputs );
280 ## parse the limit_cgi string and put it into a form suitable for <input>s
281 my @limit_inputs = _input_cgi_parse($query_cgi);
283 # add OPAC 'hidelostitems'
284 if (C4::Context->preference('hidelostitems') == 1) {
285 # either lost ge 0 or no value in the lost register
286 $query ="($query) and ( (lost,st-numeric <= 0) or ( allrecords,AlwaysMatches='' not lost,AlwaysMatches='') )";
289 # add OPAC suppression - requires at least one item indexed with Suppress
290 if (C4::Context->preference('OpacSuppression')) {
291 $query = "($query) not Suppress=1";
294 $template->param ( LIMIT_INPUTS => \@limit_inputs );
296 ## II. DO THE SEARCH AND GET THE RESULTS
297 my $total; # the total results for the whole set
298 my $facets; # this object stores the faceted results that display on the left-hand of the results page
302 if (C4::Context->preference('NoZebra')) {
304 ($error, $results_hashref, $facets) = NZgetRecords($query,$simple_query,\@sort_by,\@servers,$results_per_page,$offset,$expanded_facet,$branches,$query_type,$scan);
308 ($error, $results_hashref, $facets) = getRecords($query,$simple_query,\@sort_by,\@servers,$results_per_page,$offset,$expanded_facet,$branches,$query_type,$scan);
312 $template->param(query_error => $error.$@);
313 output_html_with_http_headers $cgi, $cookie, $template->output;
317 # At this point, each server has given us a result set
318 # now we build that set for template display
319 my @sup_results_array;
320 for (my $i=0;$i<=@servers;$i++) {
321 my $server = $servers[$i];
322 if ($server =~/biblioserver/) { # this is the local bibliographic server
323 $hits = $results_hashref->{$server}->{"hits"};
324 my $page = $cgi->param('page') || 0;
325 my @newresults = searchResults( $query_desc,$hits,$results_per_page,$offset,@{$results_hashref->{$server}->{"RECORDS"}});
326 $total = $total + $results_hashref->{$server}->{"hits"};
328 $template->param(total => $hits);
329 my $limit_cgi_not_availablity = $limit_cgi;
330 $limit_cgi_not_availablity =~ s/&limit=available//g;
331 $template->param(limit_cgi_not_availablity => $limit_cgi_not_availablity);
332 $template->param(limit_cgi => $limit_cgi);
333 $template->param(query_cgi => $query_cgi);
334 $template->param(query_desc => $query_desc);
335 $template->param(limit_desc => $limit_desc);
336 if ($query_desc || $limit_desc) {
337 $template->param(searchdesc => 1);
339 $template->param(stopwords_removed => "@$stopwords_removed") if $stopwords_removed;
340 $template->param(results_per_page => $results_per_page);
341 $template->param(SEARCH_RESULTS => \@newresults,
342 OPACItemsResultsDisplay => (C4::Context->preference("OPACItemsResultsDisplay") eq "itemdetails"?1:0),
344 ## Build the page numbers on the bottom of the page
346 # total number of pages there will be
347 my $pages = ceil($hits / $results_per_page);
348 # default page number
349 my $current_page_number = 1;
350 $current_page_number = ($offset / $results_per_page + 1) if $offset;
351 my $previous_page_offset = $offset - $results_per_page unless ($offset - $results_per_page <0);
352 my $next_page_offset = $offset + $results_per_page;
353 # If we're within the first 10 pages, keep it simple
354 #warn "current page:".$current_page_number;
355 if ($current_page_number < 10) {
356 # just show the first 10 pages
357 # Loop through the pages
358 my $pages_to_show = 10;
359 $pages_to_show = $pages if $pages<10;
360 for ($i=1; $i<=$pages_to_show;$i++) {
361 # the offset for this page
362 my $this_offset = (($i*$results_per_page)-$results_per_page);
363 # the page number for this page
364 my $this_page_number = $i;
365 # it should only be highlighted if it's the current page
366 my $highlight = 1 if ($this_page_number == $current_page_number);
367 # put it in the array
368 push @page_numbers, { offset => $this_offset, pg => $this_page_number, highlight => $highlight, sort_by => join " ",@sort_by };
373 # now, show twenty pages, with the current one smack in the middle
375 for ($i=$current_page_number; $i<=($current_page_number + 20 );$i++) {
376 my $this_offset = ((($i-9)*$results_per_page)-$results_per_page);
377 my $this_page_number = $i-9;
378 my $highlight = 1 if ($this_page_number == $current_page_number);
379 if ($this_page_number <= $pages) {
380 push @page_numbers, { offset => $this_offset, pg => $this_page_number, highlight => $highlight, sort_by => join " ",@sort_by };
385 $template->param( PAGE_NUMBERS => \@page_numbers,
386 previous_page_offset => $previous_page_offset) unless $pages < 2;
387 $template->param(next_page_offset => $next_page_offset) unless $pages eq $current_page_number;
391 $template->param(searchdesc => 1,query_desc => $query_desc,limit_desc => $limit_desc);
393 } # end of the if local
395 # check if it's a z3950 or opensearch source
396 my $zed3950 = 0; # FIXME :: Hardcoded value.
398 my @inner_sup_results_array;
399 for my $sup_record ( @{$results_hashref->{$server}->{"RECORDS"}} ) {
400 my $marc_record_object = MARC::Record->new_from_usmarc($sup_record);
401 my $control_number = $marc_record_object->field('010')->subfield('a') if $marc_record_object->field('010');
402 $control_number =~ s/^ //g;
403 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";
404 my $title = $marc_record_object->title();
405 push @inner_sup_results_array, {
410 my $servername = $server;
411 push @sup_results_array, { servername => $servername, inner_sup_results_loop => \@inner_sup_results_array};
412 $template->param(outer_sup_results_loop => \@sup_results_array);
416 } #/end of the for loop
417 #$template->param(FEDERATED_RESULTS => \@results_array);
421 #classlist => $classlist,
424 facets_loop => $facets,
426 search_error => $error,
429 if ($query_desc || $limit_desc) {
430 $template->param(searchdesc => 1);
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;
440 if ( C4::Context->preference("kohaspsuggest") ) {
441 my ($suggest_host, $suggest_dbname, $suggest_user, $suggest_pwd) = split(':', C4::Context->preference("kohaspsuggest"));
443 my $koha_spsuggest_dbh;
444 # FIXME: this needs to be moved to Context.pm
446 $koha_spsuggest_dbh=DBI->connect("DBI:mysql:$suggest_dbname:$suggest_host","$suggest_user","$suggest_pwd");
449 warn "can't connect to spsuggest db";
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;
459 $line{spsuggestion} = $spsuggestion;
460 push @koha_spsuggest,\%line;
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;
469 $template->param( koha_spsuggest => $koha_spsuggest ) unless $hits;
470 $template->param( SPELL_SUGGEST => \@koha_spsuggest,
475 warn "Kohaspsuggest failure:".$@;
479 # VI. BUILD THE TEMPLATE
480 output_html_with_http_headers $cgi, $cookie, $template->output;