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
12 use C4::Auth qw(:DEFAULT get_session);
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
36 my $template_type = 'basic';
37 my @params = $cgi->param("limit");
39 my $build_grouped_results = C4::Context->preference('OPACGroupResults');
40 if ($cgi->param("format") && $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") && $cgi->param("format") eq 'rss2') {
63 $template->param("rss2" => 1);
65 elsif ($cgi->param("format") && $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") && $cgi->param("format") eq 'opensearchdescription') {
72 $template->param("opensearchdescription" => 1);
74 if (C4::Context->preference("marcflavour") eq "UNIMARC" ) {
75 $template->param('UNIMARC' => 1);
77 if (C4::Context->preference("marcflavour") eq "MARC21" ) {
78 $template->param('usmarc' => 1);
81 if (C4::Context->preference('BakerTaylorEnabled')) {
83 BakerTaylorEnabled => 1,
84 BakerTaylorImageURL => &image_url(),
85 BakerTaylorLinkURL => &link_url(),
86 BakerTaylorBookstoreURL => C4::Context->preference('BakerTaylorBookstoreURL'),
89 if (C4::Context->preference('TagsEnabled')) {
90 $template->param(TagsEnabled => 1);
91 foreach (qw(TagsShowOnList TagsInputOnList)) {
92 C4::Context->preference($_) and $template->param($_ => 1);
97 # Deprecated, but preserved because it's interesting :-)
98 # The same thing can be accomplished with mod_rewrite in
102 #my $uri = $cgi->url(-base => 1);
103 #my $relative_url = $cgi->url(-relative=>1);
104 #$uri.="/".$relative_url."?";
106 #my @cgi_params_list = $cgi->param();
107 #my $url_params = $cgi->Vars;
109 #for my $each_param_set (@cgi_params_list) {
110 # $uri.= join "", map "\&$each_param_set=".$_, split("\0",$url_params->{$each_param_set}) if $url_params->{$each_param_set};
112 #warn "New URI:$uri";
113 # Only re-write a URI if there are params or if it already hasn't been re-written
114 #unless (($cgi->param('r')) || (!$cgi->param()) ) {
115 # print $cgi->redirect( -uri=>$uri."&r=1",
116 # -cookie => $cookie);
121 my $mybranch = ( C4::Context->preference( 'SearchMyLibraryFirst' ) && C4::Context->userenv ) ? C4::Context->userenv->{branch} : '';
122 my $branches = GetBranches();
123 # FIXME: next line duplicates GetBranchesLoop(0,0);
124 my @branch_loop = map {
127 branchname => $branches->{$_}->{branchname},
128 selected => ( $mybranch eq $_ ) ? 1 : 0
131 $branches->{$a}->{branchname} cmp $branches->{$b}->{branchname}
134 my $categories = GetBranchCategories(undef,'searchdomain');
136 $template->param(branchloop => \@branch_loop, searchdomainloop => $categories);
138 # load the Type stuff
139 my $itemtypes = GetItemTypes;
140 # the index parameter is different for item-level itemtypes
141 my $itype_or_itemtype = (C4::Context->preference("item-level_itypes"))?'itype':'itemtype';
145 my $advanced_search_types = C4::Context->preference("AdvancedSearchTypes");
147 if (!$advanced_search_types or $advanced_search_types eq 'itemtypes') {
148 foreach my $thisitemtype ( sort {$itemtypes->{$a}->{'description'} cmp $itemtypes->{$b}->{'description'} } keys %$itemtypes ) {
149 my %row =( number=>$cnt++,
150 ccl => $itype_or_itemtype,
151 code => $thisitemtype,
152 selected => $selected,
153 description => $itemtypes->{$thisitemtype}->{'description'},
155 imageurl=> getitemtypeimagelocation( 'opac', $itemtypes->{$thisitemtype}->{'imageurl'} ),
157 $selected = 0 if ($selected) ;
158 push @itemtypesloop, \%row;
160 $template->param(itemtypeloop => \@itemtypesloop);
162 my $advsearchtypes = GetAuthorisedValues($advanced_search_types);
163 for my $thisitemtype (@$advsearchtypes) {
166 ccl => $advanced_search_types,
167 code => $thisitemtype->{authorised_value},
168 selected => $selected,
169 description => $thisitemtype->{'lib'},
171 imageurl=> getitemtypeimagelocation( 'opac', $thisitemtype->{'imageurl'} ),
173 push @itemtypesloop, \%row;
175 $template->param(itemtypeloop => \@itemtypesloop);
178 # # load the itypes (Called item types in the template -- just authorized values for searching)
179 # my ($itypecount,@itype_loop) = GetCcodes();
180 # $template->param(itypeloop=>\@itype_loop,);
182 # The following should only be loaded if we're bringing up the advanced search template
183 if ( $template_type eq 'advsearch' ) {
185 # load the servers (used for searching -- to do federated searching, etc.)
186 my $primary_servers_loop;# = displayPrimaryServers();
187 $template->param(outer_servers_loop => $primary_servers_loop,);
189 my $secondary_servers_loop;# = displaySecondaryServers();
190 $template->param(outer_sup_servers_loop => $secondary_servers_loop,);
192 # set the default sorting
193 my $default_sort_by = C4::Context->preference('OPACdefaultSortField')."_".C4::Context->preference('OPACdefaultSortOrder')
194 if (C4::Context->preference('OPACdefaultSortField') && C4::Context->preference('OPACdefaultSortOrder'));
195 $template->param($default_sort_by => 1);
197 # determine what to display next to the search boxes (ie, boolean option
198 # shouldn't appear on the first one, scan indexes should, adding a new
199 # box should only appear on the last, etc.
200 my @search_boxes_array;
201 my $search_boxes_count = C4::Context->preference("OPACAdvSearchInputCount") || 3; # FIXME: should be a syspref
202 for (my $i=1;$i<=$search_boxes_count;$i++) {
203 # if it's the first one, don't display boolean option, but show scan indexes
205 push @search_boxes_array,
211 # if it's the last one, show the 'add field' box
212 elsif ($i==$search_boxes_count) {
213 push @search_boxes_array,
220 push @search_boxes_array,
227 $template->param(uc(C4::Context->preference("marcflavour")) => 1,
229 search_boxes_loop => \@search_boxes_array);
231 # use the global setting by default
232 if ( C4::Context->preference("expandedSearchOption") ) {
233 $template->param( expanded_options => C4::Context->preference("expandedSearchOption") );
235 # but let the user override it
236 if ( $cgi->param("expanded_options") && (($cgi->param('expanded_options') == 0) || ($cgi->param('expanded_options') == 1 )) ) {
237 $template->param( expanded_options => $cgi->param('expanded_options'));
240 output_html_with_http_headers $cgi, $cookie, $template->output;
244 ### OK, if we're this far, we're performing an actual search
246 # Fetch the paramater list as a hash in scalar context:
247 # * returns paramater list as tied hash ref
248 # * we can edit the values by changing the key
249 # * multivalued CGI paramaters are returned as a packaged string separated by "\0" (null)
250 my $params = $cgi->Vars;
252 $tag = $params->{tag} if $params->{tag};
254 # Params that can have more than one value
255 # sort by is used to sort the query
256 # in theory can have more than one but generally there's just one
258 my $default_sort_by = C4::Context->preference('OPACdefaultSortField')."_".C4::Context->preference('OPACdefaultSortOrder')
259 if (C4::Context->preference('OPACdefaultSortField') && C4::Context->preference('OPACdefaultSortOrder'));
261 @sort_by = split("\0",$params->{'sort_by'}) if $params->{'sort_by'};
262 $sort_by[0] = $default_sort_by if !$sort_by[0] && defined($default_sort_by);
263 foreach my $sort (@sort_by) {
264 $template->param($sort => 1);
266 $template->param('sort_by' => $sort_by[0]);
268 # Use the servers defined, or just search our local catalog(default)
270 @servers = split("\0",$params->{'server'}) if $params->{'server'};
272 #FIXME: this should be handled using Context.pm
273 @servers = ("biblioserver");
274 # @servers = C4::Context->config("biblioserver");
277 # operators include boolean and proximity operators and are used
278 # to evaluate multiple operands
280 @operators = split("\0",$params->{'op'}) if $params->{'op'};
282 # indexes are query qualifiers, like 'title', 'author', etc. They
283 # can be single or multiple parameters separated by comma: kw,right-Truncation
284 my @indexes = exists($params->{'idx'}) ? split("\0",$params->{'idx'}) : ();
286 # if a simple index (only one) display the index used in the top search box
287 if ($indexes[0] && !$indexes[1]) {
288 $template->param("ms_".$indexes[0] => 1);
290 # an operand can be a single term, a phrase, or a complete ccl query
292 @operands = split("\0",$params->{'q'}) if $params->{'q'};
294 # if a simple search, display the value in the search box
295 if ($operands[0] && !$operands[1]) {
296 $template->param(ms_value => $operands[0]);
299 # limits are use to limit to results to a pre-defined category such as branch or language
301 @limits = split("\0",$params->{'limit'}) if $params->{'limit'};
303 if($params->{'multibranchlimit'}) {
304 push @limits, join(" or ", map { "branch: $_ "} @{GetBranchesInCategory($params->{'multibranchlimit'})}) ;
308 foreach my $limit(@limits) {
309 if ($limit =~/available/) {
313 $template->param(available => $available);
315 # append year limits if they exist
316 if ($params->{'limit-yr'}) {
317 if ($params->{'limit-yr'} =~ /\d{4}-\d{4}/) {
318 my ($yr1,$yr2) = split(/-/, $params->{'limit-yr'});
319 push @limits, "yr,st-numeric,ge=$yr1 and yr,st-numeric,le=$yr2";
321 elsif ($params->{'limit-yr'} =~ /\d{4}/) {
322 push @limits, "yr,st-numeric=$params->{'limit-yr'}";
325 #FIXME: Should return a error to the user, incorect date format specified
329 # Params that can only have one value
330 my $scan = $params->{'scan'};
331 my $count = C4::Context->preference('OPACnumSearchResults') || 20;
332 my $results_per_page = $params->{'count'} || $count;
333 my $offset = $params->{'offset'} || 0;
334 my $page = $cgi->param('page') || 1;
335 $offset = ($page-1)*$results_per_page if $page>1;
337 my $expanded_facet = $params->{'expand'};
339 # Define some global variables
340 my ($error,$query,$simple_query,$query_cgi,$query_desc,$limit,$limit_cgi,$limit_desc,$stopwords_removed,$query_type);
344 ## I. BUILD THE QUERY
345 ( $error,$query,$simple_query,$query_cgi,$query_desc,$limit,$limit_cgi,$limit_desc,$stopwords_removed,$query_type) = buildQuery(\@operators,\@operands,\@indexes,\@limits,\@sort_by);
347 sub _input_cgi_parse ($) {
349 for my $this_cgi ( split('&',shift) ) {
350 next unless $this_cgi;
351 $this_cgi =~ /(.*?)=(.*)/;
352 push @elements, { input_name => $1, input_value => $2 };
357 ## parse the query_cgi string and put it into a form suitable for <input>s
358 my @query_inputs = _input_cgi_parse($query_cgi);
359 $template->param ( QUERY_INPUTS => \@query_inputs );
361 ## parse the limit_cgi string and put it into a form suitable for <input>s
362 my @limit_inputs = $limit_cgi ? _input_cgi_parse($limit_cgi) : ();
364 # add OPAC 'hidelostitems'
365 if (C4::Context->preference('hidelostitems') == 1) {
366 # either lost ge 0 or no value in the lost register
367 $query ="($query) and ( (lost,st-numeric <= 0) or ( allrecords,AlwaysMatches='' not lost,AlwaysMatches='') )";
370 # add OPAC suppression - requires at least one item indexed with Suppress
371 if (C4::Context->preference('OpacSuppression')) {
372 $query = "($query) not Suppress=1";
375 $template->param ( LIMIT_INPUTS => \@limit_inputs );
377 ## II. DO THE SEARCH AND GET THE RESULTS
378 my $total = 0; # the total results for the whole set
379 my $facets; # this object stores the faceted results that display on the left-hand of the results page
385 my $taglist = get_tags({term=>$tag, approved=>1});
386 $results_hashref->{biblioserver}->{hits} = scalar (@$taglist);
387 my @biblist = (map {GetBiblioData($_->{biblionumber})} @$taglist);
388 my @marclist = (map {$_->{marc}} @biblist );
389 $DEBUG and printf STDERR "taglist (%s biblionumber)\nmarclist (%s records)\n", scalar(@$taglist), scalar(@marclist);
390 $results_hashref->{biblioserver}->{RECORDS} = \@marclist;
391 # FIXME: tag search and standard search should work together, not exclusively
392 # FIXME: No facets for tags search.
394 elsif (C4::Context->preference('NoZebra')) {
396 ($error, $results_hashref, $facets) = NZgetRecords($query,$simple_query,\@sort_by,\@servers,$results_per_page,$offset,$expanded_facet,$branches,$query_type,$scan);
398 } elsif ($build_grouped_results) {
400 ($error, $results_hashref, $facets) = C4::Search::pazGetRecords($query,$simple_query,\@sort_by,\@servers,$results_per_page,$offset,$expanded_facet,$branches,$query_type,$scan);
404 ($error, $results_hashref, $facets) = getRecords($query,$simple_query,\@sort_by,\@servers,$results_per_page,$offset,$expanded_facet,$branches,$query_type,$scan);
407 # use Data::Dumper; print STDERR "-" x 25, "\n", Dumper($results_hashref);
409 $template->param(query_error => $error.$@);
410 output_html_with_http_headers $cgi, $cookie, $template->output;
414 # At this point, each server has given us a result set
415 # now we build that set for template display
416 my @sup_results_array;
417 for (my $i=0;$i<=@servers;$i++) {
418 my $server = $servers[$i];
419 if ($server && $server =~/biblioserver/) { # this is the local bibliographic server
420 $hits = $results_hashref->{$server}->{"hits"};
421 my $page = $cgi->param('page') || 0;
423 if ($build_grouped_results) {
424 foreach my $group (@{ $results_hashref->{$server}->{"GROUPS"} }) {
425 # because pazGetRecords handles retieving only the records
426 # we want as specified by $offset and $results_per_page,
427 # we need to set the offset parameter of searchResults to 0
428 my @group_results = searchResults( $query_desc, $group->{'group_count'},$results_per_page, 0, $scan,
429 @{ $group->{"RECORDS"} });
430 push @newresults, { group_label => $group->{'group_label'}, GROUP_RESULTS => \@group_results };
433 @newresults = searchResults( $query_desc,$hits,$results_per_page,$offset,$scan,@{$results_hashref->{$server}->{"RECORDS"}});
436 if (C4::Context->preference('TagsEnabled') and
437 $tag_quantity = C4::Context->preference('TagsShowOnList')) {
438 foreach (@newresults) {
439 my $bibnum = $_->{biblionumber} or next;
440 $_ ->{'TagLoop'} = get_tags({biblionumber=>$bibnum, approved=>1, 'sort'=>'-weight',
441 limit=>$tag_quantity });
444 foreach (@newresults) {
445 $_->{coins} = GetCOinSBiblio($_->{'biblionumber'});
447 $total = $total + $results_hashref->{$server}->{"hits"} if $results_hashref->{$server}->{"hits"};
448 ## If there's just one result, redirect to the detail page
450 my $biblionumber=$newresults[0]->{biblionumber};
451 if (C4::Context->preference('BiblioDefaultView') eq 'isbd') {
452 print $cgi->redirect("/cgi-bin/koha/opac-ISBDdetail.pl?biblionumber=$biblionumber");
453 } elsif (C4::Context->preference('BiblioDefaultView') eq 'marc') {
454 print $cgi->redirect("/cgi-bin/koha/opac-MARCdetail.pl?biblionumber=$biblionumber");
456 print $cgi->redirect("/cgi-bin/koha/opac-detail.pl?biblionumber=$biblionumber");
461 $template->param(total => $hits);
462 my $limit_cgi_not_availablity = $limit_cgi;
463 $limit_cgi_not_availablity =~ s/&limit=available//g if defined $limit_cgi_not_availablity;
464 $template->param(limit_cgi_not_availablity => $limit_cgi_not_availablity);
465 $template->param(limit_cgi => $limit_cgi);
466 $template->param(query_cgi => $query_cgi);
467 $template->param(query_desc => $query_desc);
468 $template->param(limit_desc => $limit_desc);
469 if ($query_desc || $limit_desc) {
470 $template->param(searchdesc => 1);
472 $template->param(stopwords_removed => "@$stopwords_removed") if $stopwords_removed;
473 $template->param(results_per_page => $results_per_page);
474 $template->param(SEARCH_RESULTS => \@newresults,
475 OPACItemsResultsDisplay => (C4::Context->preference("OPACItemsResultsDisplay") eq "itemdetails"?1:0),
477 ## Build the page numbers on the bottom of the page
479 # total number of pages there will be
480 my $pages = ceil($hits / $results_per_page);
481 # default page number
482 my $current_page_number = 1;
483 $current_page_number = ($offset / $results_per_page + 1) if $offset;
484 my $previous_page_offset = $offset - $results_per_page unless ($offset - $results_per_page <0);
485 my $next_page_offset = $offset + $results_per_page;
486 # If we're within the first 10 pages, keep it simple
487 #warn "current page:".$current_page_number;
488 if ($current_page_number < 10) {
489 # just show the first 10 pages
490 # Loop through the pages
491 my $pages_to_show = 10;
492 $pages_to_show = $pages if $pages<10;
493 for ($i=1; $i<=$pages_to_show;$i++) {
494 # the offset for this page
495 my $this_offset = (($i*$results_per_page)-$results_per_page);
496 # the page number for this page
497 my $this_page_number = $i;
498 # it should only be highlighted if it's the current page
499 my $highlight = 1 if ($this_page_number == $current_page_number);
500 # put it in the array
501 push @page_numbers, { offset => $this_offset, pg => $this_page_number, highlight => $highlight, sort_by => join " ",@sort_by };
506 # now, show twenty pages, with the current one smack in the middle
508 for ($i=$current_page_number; $i<=($current_page_number + 20 );$i++) {
509 my $this_offset = ((($i-9)*$results_per_page)-$results_per_page);
510 my $this_page_number = $i-9;
511 my $highlight = 1 if ($this_page_number == $current_page_number);
512 if ($this_page_number <= $pages) {
513 push @page_numbers, { offset => $this_offset, pg => $this_page_number, highlight => $highlight, sort_by => join " ",@sort_by };
518 $template->param( PAGE_NUMBERS => \@page_numbers,
519 previous_page_offset => $previous_page_offset) unless $pages < 2;
520 $template->param(next_page_offset => $next_page_offset) unless $pages eq $current_page_number;
524 $template->param(searchdesc => 1,query_desc => $query_desc,limit_desc => $limit_desc);
526 } # end of the if local
527 # asynchronously search the authority server
528 elsif ($server && $server =~/authorityserver/) { # this is the local authority server
529 my @inner_sup_results_array;
530 for my $sup_record ( @{$results_hashref->{$server}->{"RECORDS"}} ) {
531 my $marc_record_object = MARC::Record->new_from_usmarc($sup_record);
532 my $title_field = $marc_record_object->field(100);
533 warn "Authority Found: ".$marc_record_object->as_formatted();
534 push @inner_sup_results_array, {
535 'title' => $title_field->subfield('a'),
536 'link' => "&idx=an&q=".$marc_record_object->field('001')->as_string(),
539 my $servername = $server;
540 push @sup_results_array, { servername => $servername,
541 inner_sup_results_loop => \@inner_sup_results_array} if @inner_sup_results_array;
543 # FIXME: can add support for other targets as needed here
544 $template->param( outer_sup_results_loop => \@sup_results_array);
545 } #/end of the for loop
546 #$template->param(FEDERATED_RESULTS => \@results_array);
549 #classlist => $classlist,
552 facets_loop => $facets,
554 search_error => $error,
557 if ($query_desc || $limit_desc) {
558 $template->param(searchdesc => 1);
561 ## Now let's find out if we have any supplemental data to show the user
562 # and in the meantime, save the current query for statistical purposes, etc.
563 my $koha_spsuggest; # a flag to tell if we've got suggestions coming from Koha
564 my @koha_spsuggest; # place we store the suggestions to be returned to the template as LOOP
565 my $phrases = $query_desc;
568 if ( C4::Context->preference("kohaspsuggest") ) {
569 my ($suggest_host, $suggest_dbname, $suggest_user, $suggest_pwd) = split(':', C4::Context->preference("kohaspsuggest"));
571 my $koha_spsuggest_dbh;
572 # FIXME: this needs to be moved to Context.pm
574 $koha_spsuggest_dbh=DBI->connect("DBI:mysql:$suggest_dbname:$suggest_host","$suggest_user","$suggest_pwd");
577 warn "can't connect to spsuggest db";
580 my $koha_spsuggest_insert = "INSERT INTO phrase_log(phr_phrase,phr_resultcount,phr_ip) VALUES(?,?,?)";
581 my $koha_spsuggest_query = "SELECT display FROM distincts WHERE strcmp(soundex(suggestion), soundex(?)) = 0 order by soundex(suggestion) limit 0,5";
582 my $koha_spsuggest_sth = $koha_spsuggest_dbh->prepare($koha_spsuggest_query);
583 $koha_spsuggest_sth->execute($phrases);
584 while (my $spsuggestion = $koha_spsuggest_sth->fetchrow_array) {
585 $spsuggestion =~ s/(:|\/)//g;
587 $line{spsuggestion} = $spsuggestion;
588 push @koha_spsuggest,\%line;
592 # Now save the current query
593 $koha_spsuggest_sth=$koha_spsuggest_dbh->prepare($koha_spsuggest_insert);
594 #$koha_spsuggest_sth->execute($phrases,$results_per_page,$ipaddress);
595 $koha_spsuggest_sth->finish;
597 $template->param( koha_spsuggest => $koha_spsuggest ) unless $hits;
598 $template->param( SPELL_SUGGEST => \@koha_spsuggest,
603 warn "Kohaspsuggest failure:".$@;
607 # VI. BUILD THE TEMPLATE
608 # NOTE: not using application/atom+xml or application/rss+xml beccause of Internet Explorer 6;
610 my $content_type = ($cgi->param('format') && $cgi->param('format') =~ /rss|atom/) ? "application/xml" :
613 # Build drop-down list for 'Add To:' menu...
614 my $session = get_session($cgi->cookie("CGISESSID"));
616 my $pubshelves = $session->param('pubshelves');
617 my $barshelves = $session->param('barshelves');
618 foreach my $shelf (@$pubshelves) {
619 next if ( ($shelf->{'owner'} != ($borrowernumber ? $borrowernumber : -1)) && ($shelf->{'category'} < 3) );
620 push (@addpubshelves, $shelf);
623 if (@addpubshelves) {
624 $template->param( addpubshelves => scalar (@addpubshelves));
625 $template->param( addpubshelvesloop => \@addpubshelves);
628 if (defined $barshelves) {
629 $template->param( addbarshelves => scalar (@$barshelves));
630 $template->param( addbarshelvesloop => $barshelves);
633 output_html_with_http_headers $cgi, $cookie, $template->output, $content_type;