2 # Script to perform searching
3 # Mostly copied from search.pl, see POD there
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
14 use C4
::Biblio
; # GetBiblioData
16 use C4
::Tags
qw(get_tags);
17 use POSIX
qw(ceil floor strftime);
18 use C4
::Branch
; # GetBranches
20 # create a new CGI object
21 # FIXME: no_undef_params needs to be tested
22 use CGI
qw('-no_undef_params');
26 if (C4
::Context
->preference('BakerTaylorEnabled')) {
27 require C4
::External
::BakerTaylor
;
28 import C4
::External
::BakerTaylor
qw(&image_url &link_url);
32 my ($template,$borrowernumber,$cookie);
34 # decide which template to use
37 my @params = $cgi->param("limit");
39 my $build_grouped_results = C4
::Context
->preference('OPACGroupResults');
40 if ($cgi->param("format") =~ /(rss|atom|opensearchdescription)/) {
41 $template_name = 'opac-opensearch.tmpl';
43 elsif ($build_grouped_results) {
44 $template_name = 'opac-results-grouped.tmpl';
46 elsif ((@params>=1) || ($cgi->param("q")) || ($cgi->param('multibranchlimit')) || ($cgi->param('limit-yr')) ) {
47 $template_name = 'opac-results.tmpl';
50 $template_name = 'opac-advsearch.tmpl';
51 $template_type = 'advsearch';
54 ($template, $borrowernumber, $cookie) = get_template_and_user
({
55 template_name
=> $template_name,
62 if ($cgi->param("format") eq 'rss2') {
63 $template->param("rss2" => 1);
65 elsif ($cgi->param("format") eq 'atom') {
66 $template->param("atom" => 1);
67 # FIXME - the timestamp is a hack - the biblio update timestamp should be used for each
68 # entry, but not sure if that's worth an extra database query for each bib
69 $template->param(timestamp
=> strftime
("%Y-%m-%dT%H:%M:%S-00:00", gmtime));
71 elsif ($cgi->param("format") eq 'opensearchdescription') {
72 $template->param("opensearchdescription" => 1);
74 if (C4
::Context
->preference("marcflavour") eq "UNIMARC" ) {
75 $template->param('UNIMARC' => 1);
78 if (C4
::Context
->preference('BakerTaylorEnabled')) {
80 BakerTaylorEnabled
=> 1,
81 BakerTaylorImageURL
=> &image_url
(),
82 BakerTaylorLinkURL
=> &link_url
(),
83 BakerTaylorBookstoreURL
=> C4
::Context
->preference('BakerTaylorBookstoreURL'),
86 if (C4
::Context
->preference('TagsEnabled')) {
87 $template->param(TagsEnabled
=> 1);
88 foreach (qw(TagsShowOnList TagsInputOnList)) {
89 C4
::Context
->preference($_) and $template->param($_ => 1);
94 # Deprecated, but preserved because it's interesting :-)
95 # The same thing can be accomplished with mod_rewrite in
99 #my $uri = $cgi->url(-base => 1);
100 #my $relative_url = $cgi->url(-relative=>1);
101 #$uri.="/".$relative_url."?";
103 #my @cgi_params_list = $cgi->param();
104 #my $url_params = $cgi->Vars;
106 #for my $each_param_set (@cgi_params_list) {
107 # $uri.= join "", map "\&$each_param_set=".$_, split("\0",$url_params->{$each_param_set}) if $url_params->{$each_param_set};
109 #warn "New URI:$uri";
110 # Only re-write a URI if there are params or if it already hasn't been re-written
111 #unless (($cgi->param('r')) || (!$cgi->param()) ) {
112 # print $cgi->redirect( -uri=>$uri."&r=1",
113 # -cookie => $cookie);
118 my $branches = GetBranches
();
121 for my $branch_hash (sort keys %$branches) {
122 push @branch_loop, {value
=> "$branch_hash" , branchname
=> $branches->{$branch_hash}->{'branchname'}, };
125 my $categories = GetBranchCategories
(undef,'searchdomain');
127 $template->param(branchloop
=> \
@branch_loop, searchdomainloop
=> $categories);
129 # load the Type stuff
130 my $itemtypes = GetItemTypes
;
131 # the index parameter is different for item-level itemtypes
132 my $itype_or_itemtype = (C4
::Context
->preference("item-level_itypes"))?
'itype':'itemtype';
136 my $imgdir = getitemtypeimagesrc
('opac');
137 my $advanced_search_types = C4
::Context
->preference("AdvancedSearchTypes");
139 if (!$advanced_search_types or $advanced_search_types eq 'itemtypes') {
140 foreach my $thisitemtype ( sort {$itemtypes->{$a}->{'description'} cmp $itemtypes->{$b}->{'description'} } keys %$itemtypes ) {
141 my %row =( number
=>$cnt++,
142 imageurl
=> $itemtypes->{$thisitemtype}->{'imageurl'}?
($imgdir."/".$itemtypes->{$thisitemtype}->{'imageurl'}):"",
143 ccl
=> $itype_or_itemtype,
144 code
=> $thisitemtype,
145 selected
=> $selected,
146 description
=> $itemtypes->{$thisitemtype}->{'description'},
149 $selected = 0 if ($selected) ;
150 push @itemtypesloop, \
%row;
152 $template->param(itemtypeloop
=> \
@itemtypesloop);
154 my $advsearchtypes = GetAuthorisedValues
($advanced_search_types);
155 for my $thisitemtype (@
$advsearchtypes) {
158 imageurl
=> $imgdir."/".$thisitemtype->{'imageurl'},
159 ccl
=> $advanced_search_types,
160 code
=> $thisitemtype->{authorised_value
},
161 selected
=> $selected,
162 description
=> $thisitemtype->{'lib'},
165 push @itemtypesloop, \
%row;
167 $template->param(itemtypeloop
=> \
@itemtypesloop);
170 # # load the itypes (Called item types in the template -- just authorized values for searching)
171 # my ($itypecount,@itype_loop) = GetCcodes();
172 # $template->param(itypeloop=>\@itype_loop,);
174 # The following should only be loaded if we're bringing up the advanced search template
175 if ( $template_type eq 'advsearch' ) {
177 # load the servers (used for searching -- to do federated searching, etc.)
178 my $primary_servers_loop;# = displayPrimaryServers();
179 $template->param(outer_servers_loop
=> $primary_servers_loop,);
181 my $secondary_servers_loop;# = displaySecondaryServers();
182 $template->param(outer_sup_servers_loop
=> $secondary_servers_loop,);
184 # determine what to display next to the search boxes (ie, boolean option
185 # shouldn't appear on the first one, scan indexes should, adding a new
186 # box should only appear on the last, etc.
187 my @search_boxes_array;
188 my $search_boxes_count = C4
::Context
->preference("OPACAdvSearchInputCount") | 3; # FIXME: should be a syspref
189 for (my $i=1;$i<=$search_boxes_count;$i++) {
190 # if it's the first one, don't display boolean option, but show scan indexes
192 push @search_boxes_array,
198 # if it's the last one, show the 'add field' box
199 elsif ($i==$search_boxes_count) {
200 push @search_boxes_array,
207 push @search_boxes_array,
214 $template->param(uc(C4
::Context
->preference("marcflavour")) => 1,
216 search_boxes_loop
=> \
@search_boxes_array);
218 # use the global setting by default
219 if ( C4
::Context
->preference("expandedSearchOption") == 1) {
220 $template->param( expanded_options
=> C4
::Context
->preference("expandedSearchOption") );
222 # but let the user override it
223 if ( ($cgi->param('expanded_options') == 0) || ($cgi->param('expanded_options') == 1 ) ) {
224 $template->param( expanded_options
=> $cgi->param('expanded_options'));
227 output_html_with_http_headers
$cgi, $cookie, $template->output;
231 ### OK, if we're this far, we're performing an actual search
233 # Fetch the paramater list as a hash in scalar context:
234 # * returns paramater list as tied hash ref
235 # * we can edit the values by changing the key
236 # * multivalued CGI paramaters are returned as a packaged string separated by "\0" (null)
237 my $params = $cgi->Vars;
239 $tag = $params->{tag
} if $params->{tag
};
241 # Params that can have more than one value
242 # sort by is used to sort the query
243 # in theory can have more than one but generally there's just one
245 my $default_sort_by = C4
::Context
->preference('OPACdefaultSortField')."_".C4
::Context
->preference('OPACdefaultSortOrder')
246 if (C4
::Context
->preference('OPACdefaultSortField') && C4
::Context
->preference('OPACdefaultSortOrder'));
248 @sort_by = split("\0",$params->{'sort_by'}) if $params->{'sort_by'};
249 $sort_by[0] = $default_sort_by unless $sort_by[0];
250 foreach my $sort (@sort_by) {
251 $template->param($sort => 1);
253 $template->param('sort_by' => $sort_by[0]);
255 # Use the servers defined, or just search our local catalog(default)
257 @servers = split("\0",$params->{'server'}) if $params->{'server'};
259 #FIXME: this should be handled using Context.pm
260 @servers = ("biblioserver");
261 # @servers = C4::Context->config("biblioserver");
264 # operators include boolean and proximity operators and are used
265 # to evaluate multiple operands
267 @operators = split("\0",$params->{'op'}) if $params->{'op'};
269 # indexes are query qualifiers, like 'title', 'author', etc. They
270 # can be single or multiple parameters separated by comma: kw,right-Truncation
271 my @indexes = split("\0",$params->{'idx'});
273 # if a simple index (only one) display the index used in the top search box
274 if ($indexes[0] && !$indexes[1]) {
275 $template->param("ms_".$indexes[0] => 1);
277 # an operand can be a single term, a phrase, or a complete ccl query
279 @operands = split("\0",$params->{'q'}) if $params->{'q'};
281 # if a simple search, display the value in the search box
282 if ($operands[0] && !$operands[1]) {
283 $template->param(ms_value
=> $operands[0]);
286 # limits are use to limit to results to a pre-defined category such as branch or language
288 @limits = split("\0",$params->{'limit'}) if $params->{'limit'};
290 if($params->{'multibranchlimit'}) {
291 push @limits, join(" or ", map { "branch: $_ "} @
{GetBranchesInCategory
($params->{'multibranchlimit'})}) ;
295 foreach my $limit(@limits) {
296 if ($limit =~/available/) {
300 $template->param(available
=> $available);
302 # append year limits if they exist
303 if ($params->{'limit-yr'}) {
304 if ($params->{'limit-yr'} =~ /\d{4}-\d{4}/) {
305 my ($yr1,$yr2) = split(/-/, $params->{'limit-yr'});
306 push @limits, "yr,st-numeric,ge=$yr1 and yr,st-numeric,le=$yr2";
308 elsif ($params->{'limit-yr'} =~ /\d{4}/) {
309 push @limits, "yr,st-numeric=$params->{'limit-yr'}";
312 #FIXME: Should return a error to the user, incorect date format specified
316 # Params that can only have one value
317 my $scan = $params->{'scan'};
318 my $count = C4
::Context
->preference('OPACnumSearchResults') || 20;
319 my $results_per_page = $params->{'count'} || $count;
320 my $offset = $params->{'offset'} || 0;
321 my $page = $cgi->param('page') || 1;
322 $offset = ($page-1)*$results_per_page if $page>1;
324 my $expanded_facet = $params->{'expand'};
326 # Define some global variables
327 my ($error,$query,$simple_query,$query_cgi,$query_desc,$limit,$limit_cgi,$limit_desc,$stopwords_removed,$query_type);
331 ## I. BUILD THE QUERY
332 ( $error,$query,$simple_query,$query_cgi,$query_desc,$limit,$limit_cgi,$limit_desc,$stopwords_removed,$query_type) = buildQuery
(\
@operators,\
@operands,\
@indexes,\
@limits,\
@sort_by);
334 sub _input_cgi_parse
($) {
336 for my $this_cgi ( split('&',shift) ) {
337 next unless $this_cgi;
338 $this_cgi =~ /(.*)=(.*)/;
339 push @elements, { input_name
=> $1, input_value
=> $2 };
344 ## parse the query_cgi string and put it into a form suitable for <input>s
345 my @query_inputs = _input_cgi_parse
($query_cgi);
346 $template->param ( QUERY_INPUTS
=> \
@query_inputs );
348 ## parse the limit_cgi string and put it into a form suitable for <input>s
349 my @limit_inputs = _input_cgi_parse
($limit_cgi);
351 # add OPAC 'hidelostitems'
352 if (C4
::Context
->preference('hidelostitems') == 1) {
353 # either lost ge 0 or no value in the lost register
354 $query ="($query) and ( (lost,st-numeric <= 0) or ( allrecords,AlwaysMatches='' not lost,AlwaysMatches='') )";
357 # add OPAC suppression - requires at least one item indexed with Suppress
358 if (C4
::Context
->preference('OpacSuppression')) {
359 $query = "($query) not Suppress=1";
362 $template->param ( LIMIT_INPUTS
=> \
@limit_inputs );
364 ## II. DO THE SEARCH AND GET THE RESULTS
365 my $total; # the total results for the whole set
366 my $facets; # this object stores the faceted results that display on the left-hand of the results page
371 my $taglist = get_tags
({term
=>$tag, approved
=>1});
372 $results_hashref->{biblioserver
}->{hits
} = scalar (@
$taglist);
373 my @biblist = (map {GetBiblioData
($_->{biblionumber
})} @
$taglist);
374 my @marclist = (map {$_->{marc
}} @biblist );
375 $DEBUG and printf STDERR
"taglist (%s biblionumber)\nmarclist (%s records)\n", scalar(@
$taglist), scalar(@marclist);
376 $results_hashref->{biblioserver
}->{RECORDS
} = \
@marclist;
377 # FIXME: tag search and standard search should work together, not exclusively
378 # FIXME: No facets for tags search.
380 elsif (C4
::Context
->preference('NoZebra')) {
382 ($error, $results_hashref, $facets) = NZgetRecords
($query,$simple_query,\
@sort_by,\
@servers,$results_per_page,$offset,$expanded_facet,$branches,$query_type,$scan);
384 } elsif ($build_grouped_results) {
386 ($error, $results_hashref, $facets) = C4
::Search
::pazGetRecords
($query,$simple_query,\
@sort_by,\
@servers,$results_per_page,$offset,$expanded_facet,$branches,$query_type,$scan);
390 ($error, $results_hashref, $facets) = getRecords
($query,$simple_query,\
@sort_by,\
@servers,$results_per_page,$offset,$expanded_facet,$branches,$query_type,$scan);
393 # use Data::Dumper; print STDERR "-" x 25, "\n", Dumper($results_hashref);
395 $template->param(query_error
=> $error.$@
);
396 output_html_with_http_headers
$cgi, $cookie, $template->output;
400 # At this point, each server has given us a result set
401 # now we build that set for template display
402 my @sup_results_array;
403 for (my $i=0;$i<=@servers;$i++) {
404 my $server = $servers[$i];
405 if ($server =~/biblioserver/) { # this is the local bibliographic server
406 $hits = $results_hashref->{$server}->{"hits"};
407 my $page = $cgi->param('page') || 0;
409 if ($build_grouped_results) {
410 foreach my $group (@
{ $results_hashref->{$server}->{"GROUPS"} }) {
411 # because pazGetRecords handles retieving only the records
412 # we want as specified by $offset and $results_per_page,
413 # we need to set the offset parameter of searchResults to 0
414 my @group_results = searchResults
( $query_desc, $group->{'group_count'},$results_per_page, 0,
415 @
{ $group->{"RECORDS"} });
416 push @newresults, { group_label
=> $group->{'group_label'}, GROUP_RESULTS
=> \
@group_results };
419 @newresults = searchResults
( $query_desc,$hits,$results_per_page,$offset,@
{$results_hashref->{$server}->{"RECORDS"}});
422 if (C4
::Context
->preference('TagsEnabled') and
423 $tag_quantity = C4
::Context
->preference('TagsShowOnList')) {
424 foreach (@newresults) {
425 my $bibnum = $_->{biblionumber
} or next;
426 $_ ->{'TagLoop'} = get_tags
({biblionumber
=>$bibnum, approved
=>1, 'sort'=>'-weight',
427 limit
=>$tag_quantity });
430 foreach (@newresults) {
431 my $clean = $_->{isbn
} or next;
433 $clean =~ /\b(\d{13})\b/ or
434 $clean =~ /\b(\d{10})\b/ or
435 $clean =~ /\b(\d{9}X)\b/i
439 $_ ->{'clean_isbn'} = $1;
441 $total = $total + $results_hashref->{$server}->{"hits"};
442 ## If there's just one result, redirect to the detail page
444 my $biblionumber=@newresults[0]->{biblionumber
};
445 if (C4
::Context
->preference('BiblioDefaultView') eq 'isbd') {
446 print $cgi->redirect("/cgi-bin/koha/opac-ISBDdetail.pl?biblionumber=$biblionumber");
447 } elsif (C4
::Context
->preference('BiblioDefaultView') eq 'marc') {
448 print $cgi->redirect("/cgi-bin/koha/opac-MARCdetail.pl?biblionumber=$biblionumber");
450 print $cgi->redirect("/cgi-bin/koha/opac-detail.pl?biblionumber=$biblionumber");
455 $template->param(total
=> $hits);
456 my $limit_cgi_not_availablity = $limit_cgi;
457 $limit_cgi_not_availablity =~ s/&limit=available//g;
458 $template->param(limit_cgi_not_availablity
=> $limit_cgi_not_availablity);
459 $template->param(limit_cgi
=> $limit_cgi);
460 $template->param(query_cgi
=> $query_cgi);
461 $template->param(query_desc
=> $query_desc);
462 $template->param(limit_desc
=> $limit_desc);
463 if ($query_desc || $limit_desc) {
464 $template->param(searchdesc
=> 1);
466 $template->param(stopwords_removed
=> "@$stopwords_removed") if $stopwords_removed;
467 $template->param(results_per_page
=> $results_per_page);
468 $template->param(SEARCH_RESULTS
=> \
@newresults,
469 OPACItemsResultsDisplay
=> (C4
::Context
->preference("OPACItemsResultsDisplay") eq "itemdetails"?
1:0),
471 ## Build the page numbers on the bottom of the page
473 # total number of pages there will be
474 my $pages = ceil
($hits / $results_per_page);
475 # default page number
476 my $current_page_number = 1;
477 $current_page_number = ($offset / $results_per_page + 1) if $offset;
478 my $previous_page_offset = $offset - $results_per_page unless ($offset - $results_per_page <0);
479 my $next_page_offset = $offset + $results_per_page;
480 # If we're within the first 10 pages, keep it simple
481 #warn "current page:".$current_page_number;
482 if ($current_page_number < 10) {
483 # just show the first 10 pages
484 # Loop through the pages
485 my $pages_to_show = 10;
486 $pages_to_show = $pages if $pages<10;
487 for ($i=1; $i<=$pages_to_show;$i++) {
488 # the offset for this page
489 my $this_offset = (($i*$results_per_page)-$results_per_page);
490 # the page number for this page
491 my $this_page_number = $i;
492 # it should only be highlighted if it's the current page
493 my $highlight = 1 if ($this_page_number == $current_page_number);
494 # put it in the array
495 push @page_numbers, { offset
=> $this_offset, pg
=> $this_page_number, highlight
=> $highlight, sort_by
=> join " ",@sort_by };
500 # now, show twenty pages, with the current one smack in the middle
502 for ($i=$current_page_number; $i<=($current_page_number + 20 );$i++) {
503 my $this_offset = ((($i-9)*$results_per_page)-$results_per_page);
504 my $this_page_number = $i-9;
505 my $highlight = 1 if ($this_page_number == $current_page_number);
506 if ($this_page_number <= $pages) {
507 push @page_numbers, { offset
=> $this_offset, pg
=> $this_page_number, highlight
=> $highlight, sort_by
=> join " ",@sort_by };
512 $template->param( PAGE_NUMBERS
=> \
@page_numbers,
513 previous_page_offset
=> $previous_page_offset) unless $pages < 2;
514 $template->param(next_page_offset
=> $next_page_offset) unless $pages eq $current_page_number;
518 $template->param(searchdesc
=> 1,query_desc
=> $query_desc,limit_desc
=> $limit_desc);
520 } # end of the if local
521 # asynchronously search the authority server
522 elsif ($server =~/authorityserver/) { # this is the local authority server
523 my @inner_sup_results_array;
524 for my $sup_record ( @
{$results_hashref->{$server}->{"RECORDS"}} ) {
525 my $marc_record_object = MARC
::Record
->new_from_usmarc($sup_record);
526 my $title_field = $marc_record_object->field(100);
527 warn "Authority Found: ".$marc_record_object->as_formatted();
528 push @inner_sup_results_array, {
529 'title' => $title_field->subfield('a'),
530 'link' => "&idx=an&q=".$marc_record_object->field('001')->as_string(),
533 my $servername = $server;
534 push @sup_results_array, { servername
=> $servername,
535 inner_sup_results_loop
=> \
@inner_sup_results_array} if @inner_sup_results_array;
537 # FIXME: can add support for other targets as needed here
538 $template->param( outer_sup_results_loop
=> \
@sup_results_array);
539 } #/end of the for loop
540 #$template->param(FEDERATED_RESULTS => \@results_array);
543 #classlist => $classlist,
546 facets_loop
=> $facets,
548 search_error
=> $error,
551 if ($query_desc || $limit_desc) {
552 $template->param(searchdesc
=> 1);
555 ## Now let's find out if we have any supplemental data to show the user
556 # and in the meantime, save the current query for statistical purposes, etc.
557 my $koha_spsuggest; # a flag to tell if we've got suggestions coming from Koha
558 my @koha_spsuggest; # place we store the suggestions to be returned to the template as LOOP
559 my $phrases = $query_desc;
562 if ( C4
::Context
->preference("kohaspsuggest") ) {
563 my ($suggest_host, $suggest_dbname, $suggest_user, $suggest_pwd) = split(':', C4
::Context
->preference("kohaspsuggest"));
565 my $koha_spsuggest_dbh;
566 # FIXME: this needs to be moved to Context.pm
568 $koha_spsuggest_dbh=DBI
->connect("DBI:mysql:$suggest_dbname:$suggest_host","$suggest_user","$suggest_pwd");
571 warn "can't connect to spsuggest db";
574 my $koha_spsuggest_insert = "INSERT INTO phrase_log(phr_phrase,phr_resultcount,phr_ip) VALUES(?,?,?)";
575 my $koha_spsuggest_query = "SELECT display FROM distincts WHERE strcmp(soundex(suggestion), soundex(?)) = 0 order by soundex(suggestion) limit 0,5";
576 my $koha_spsuggest_sth = $koha_spsuggest_dbh->prepare($koha_spsuggest_query);
577 $koha_spsuggest_sth->execute($phrases);
578 while (my $spsuggestion = $koha_spsuggest_sth->fetchrow_array) {
579 $spsuggestion =~ s/(:|\/)//g
;
581 $line{spsuggestion
} = $spsuggestion;
582 push @koha_spsuggest,\
%line;
586 # Now save the current query
587 $koha_spsuggest_sth=$koha_spsuggest_dbh->prepare($koha_spsuggest_insert);
588 #$koha_spsuggest_sth->execute($phrases,$results_per_page,$ipaddress);
589 $koha_spsuggest_sth->finish;
591 $template->param( koha_spsuggest
=> $koha_spsuggest ) unless $hits;
592 $template->param( SPELL_SUGGEST
=> \
@koha_spsuggest,
597 warn "Kohaspsuggest failure:".$@
;
601 # VI. BUILD THE TEMPLATE
602 # NOTE: not using application/atom+xml or application/rss+xml beccause of Internet Explorer 6;
604 my $content_type = $cgi->param('format') =~ /rss|atom/ ?
"application/xml" :
606 output_html_with_http_headers
$cgi, $cookie, $template->output, $content_type;