2 # Script to perform searching
3 # For documentation try 'perldoc /path/to/search'
7 # Copyright 2006 LibLime
9 # This file is part of Koha
11 # Koha is free software; you can redistribute it and/or modify it under the
12 # terms of the GNU General Public License as published by the Free Software
13 # Foundation; either version 2 of the License, or (at your option) any later
16 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
17 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
18 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
20 # You should have received a copy of the GNU General Public License along with
21 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
22 # Suite 330, Boston, MA 02111-1307 USA
26 search - a search script for finding records in a Koha system (Version 3)
30 This script utilizes a new search API for Koha 3. It is designed to be
31 simple to use and configure, yet capable of performing feats like stemming,
32 field weighting, relevance ranking, support for multiple query language
33 formats (CCL, CQL, PQF), full support for the bib1 attribute set, extended
34 attribute sets defined in Zebra profiles, access to the full range of Z39.50
35 and SRU query options, federated searches on Z39.50/SRU targets, etc.
37 The API as represented in this script is mostly sound, even if the individual
38 functions in Search.pm and Koha.pm need to be cleaned up. Of course, you are
41 I will attempt to describe what is happening at each part of this script.
42 -- Joshua Ferraro <jmf AT liblime DOT com>
46 This script performs two functions:
50 =item 1. interacts with Koha to retrieve and display the results of a search
52 =item 2. loads the advanced search page
56 These two functions share many of the same variables and modules, so the first
57 task is to load what they have in common and determine which template to use.
58 Once determined, proceed to only load the variables and procedures necessary
61 =head2 LOADING ADVANCED SEARCH PAGE
63 This is fairly straightforward, and I won't go into detail ;-)
65 =head2 PERFORMING A SEARCH
67 If we're performing a search, this script performs three primary
72 =item 1. builds query strings (yes, plural)
74 =item 2. perform the search and return the results array
76 =item 3. build the HTML for output to the template
80 There are several additional secondary functions performed that I will
83 =head3 1. Building Query Strings
85 There are several types of queries needed in the process of search and retrieve:
89 =item 1 $query - the fully-built query passed to zebra
91 This is the most complex query that needs to be built. The original design goal
92 was to use a custom CCL2PQF query parser to translate an incoming CCL query into
93 a multi-leaf query to pass to Zebra. It needs to be multi-leaf to allow field
94 weighting, koha-specific relevance ranking, and stemming. When I have a chance
95 I'll try to flesh out this section to better explain.
97 This query incorporates query profiles that aren't compatible with most non-Zebra
98 Z39.50 targets to acomplish the field weighting and relevance ranking.
100 =item 2 $simple_query - a simple query that doesn't contain the field weighting,
101 stemming, etc., suitable to pass off to other search targets
103 This query is just the user's query expressed in CCL CQL, or PQF for passing to a
104 non-zebra Z39.50 target (one that doesn't support the extended profile that Zebra does).
106 =item 3 $query_cgi - passed to the template / saved for future refinements of
109 This is a simple string that completely expresses the query as a CGI string that
110 can be used for future refinements of the query or as a part of a history feature.
112 =item 4 $query_desc - Human search description - what the user sees in search
115 This is a simple string that is human readable. It will contain '=', ',', etc.
119 =head3 2. Perform the Search
121 This section takes the query strings and performs searches on the named servers,
122 including the Koha Zebra server, stores the results in a deeply nested object,
123 builds 'faceted results', and returns these objects.
127 The final major section of this script takes the objects collected thusfar and
128 builds the HTML for output to the template and user.
130 =head3 Additional Notes
136 use strict; # always use
138 ## STEP 1. Load things that are used in both search page and
139 # results page and decide which template to load, operations
147 use C4::Languages qw(getAllLanguages);
149 use POSIX qw(ceil floor);
150 use C4::Branch; # GetBranches
152 # create a new CGI object
153 # FIXME: no_undef_params needs to be tested
154 use CGI qw('-no_undef_params');
157 my ($template,$borrowernumber,$cookie);
159 # decide which template to use
162 my @params = $cgi->param("limit");
163 if ((@params>=1) || ($cgi->param("q")) || ($cgi->param('multibranchlimit')) || ($cgi->param('limit-yr')) ) {
164 $template_name = 'catalogue/results.tmpl';
167 $template_name = 'catalogue/advsearch.tmpl';
168 $template_type = 'advsearch';
171 ($template, $borrowernumber, $cookie) = get_template_and_user({
172 template_name => $template_name,
175 authnotrequired => 0,
176 flagsrequired => { catalogue => 1 },
179 if (C4::Context->preference("marcflavour") eq "UNIMARC" ) {
180 $template->param('UNIMARC' => 1);
184 # Deprecated, but preserved because it's interesting :-)
185 # The same thing can be accomplished with mod_rewrite in
189 #my $uri = $cgi->url(-base => 1);
190 #my $relative_url = $cgi->url(-relative=>1);
191 #$uri.="/".$relative_url."?";
193 #my @cgi_params_list = $cgi->param();
194 #my $url_params = $cgi->Vars;
196 #for my $each_param_set (@cgi_params_list) {
197 # $uri.= join "", map "\&$each_param_set=".$_, split("\0",$url_params->{$each_param_set}) if $url_params->{$each_param_set};
199 #warn "New URI:$uri";
200 # Only re-write a URI if there are params or if it already hasn't been re-written
201 #unless (($cgi->param('r')) || (!$cgi->param()) ) {
202 # print $cgi->redirect( -uri=>$uri."&r=1",
203 # -cookie => $cookie);
208 my $branches = GetBranches();
211 for my $branch_hash (sort { $branches->{$a}->{branchname} cmp $branches->{$b}->{branchname} } keys %$branches) {
212 push @branch_loop, {value => "$branch_hash" , branchname => $branches->{$branch_hash}->{'branchname'}, };
215 my $categories = GetBranchCategories(undef,'searchdomain');
217 $template->param(branchloop => \@branch_loop, searchdomainloop => $categories);
219 # load the Type stuff
220 # load the Type stuff
221 my $itemtypes = GetItemTypes;
222 # the index parameter is different for item-level itemtypes
223 my $itype_or_itemtype = (C4::Context->preference("item-level_itypes"))?'itype':'itemtype';
227 my $advanced_search_types = C4::Context->preference("AdvancedSearchTypes");
229 if (!$advanced_search_types or $advanced_search_types eq 'itemtypes') { foreach my $thisitemtype ( sort {$itemtypes->{$a}->{'description'} cmp $itemtypes->{$b}->{'description'} } keys %$itemtypes ) {
230 my %row =( number=>$cnt++,
231 imageurl=> getitemtypeimagelocation( 'intranet', $itemtypes->{$thisitemtype}->{'imageurl'} ),
232 ccl => $itype_or_itemtype,
233 code => $thisitemtype,
234 selected => $selected,
235 description => $itemtypes->{$thisitemtype}->{'description'},
237 imageurl=> getitemtypeimagelocation( 'intranet', $itemtypes->{$thisitemtype}->{'imageurl'} ),
239 $selected = 0 if ($selected) ;
240 push @itemtypesloop, \%row;
242 $template->param(itemtypeloop => \@itemtypesloop);
244 my $advsearchtypes = GetAuthorisedValues($advanced_search_types);
245 for my $thisitemtype (@$advsearchtypes) {
248 imageurl=> getitemtypeimagelocation( 'intranet', $thisitemtype->{'imageurl'} ),
249 ccl => $advanced_search_types,
250 code => $thisitemtype->{authorised_value},
251 selected => $selected,
252 description => $thisitemtype->{'lib'},
254 imageurl=> getitemtypeimagelocation( 'intranet', $thisitemtype->{'imageurl'} ),
256 push @itemtypesloop, \%row;
258 $template->param(itemtypeloop => \@itemtypesloop);
261 # The following should only be loaded if we're bringing up the advanced search template
262 if ( $template_type eq 'advsearch' ) {
264 # load the servers (used for searching -- to do federated searching, etc.)
265 my $primary_servers_loop;# = displayPrimaryServers();
266 $template->param(outer_servers_loop => $primary_servers_loop,);
268 my $secondary_servers_loop;# = displaySecondaryServers();
269 $template->param(outer_sup_servers_loop => $secondary_servers_loop,);
271 # set the default sorting
272 my $default_sort_by = C4::Context->preference('defaultSortField')."_".C4::Context->preference('defaultSortOrder')
273 if (C4::Context->preference('OPACdefaultSortField') && C4::Context->preference('OPACdefaultSortOrder'));
274 $template->param($default_sort_by => 1);
276 # determine what to display next to the search boxes (ie, boolean option
277 # shouldn't appear on the first one, scan indexes should, adding a new
278 # box should only appear on the last, etc.
279 my @search_boxes_array;
280 my $search_boxes_count = C4::Context->preference("OPACAdvSearchInputCount") | 3; # FIXME: should be a syspref
281 for (my $i=1;$i<=$search_boxes_count;$i++) {
282 # if it's the first one, don't display boolean option, but show scan indexes
284 push @search_boxes_array,
290 # if it's the last one, show the 'add field' box
291 elsif ($i==$search_boxes_count) {
292 push @search_boxes_array,
299 push @search_boxes_array,
306 $template->param(uc(C4::Context->preference("marcflavour")) => 1,
307 search_boxes_loop => \@search_boxes_array);
309 # load the language limits (for search)
310 my $languages_limit_loop = getAllLanguages();
311 $template->param(search_languages_loop => $languages_limit_loop,);
313 # use the global setting by default
314 if ( C4::Context->preference("expandedSearchOption") == 1) {
315 $template->param( expanded_options => C4::Context->preference("expandedSearchOption") );
317 # but let the user override it
318 if ( ($cgi->param('expanded_options') == 0) || ($cgi->param('expanded_options') == 1 ) ) {
319 $template->param( expanded_options => $cgi->param('expanded_options'));
322 output_html_with_http_headers $cgi, $cookie, $template->output;
326 ### OK, if we're this far, we're performing a search, not just loading the advanced search page
328 # Fetch the paramater list as a hash in scalar context:
329 # * returns paramater list as tied hash ref
330 # * we can edit the values by changing the key
331 # * multivalued CGI paramaters are returned as a packaged string separated by "\0" (null)
332 my $params = $cgi->Vars;
334 # Params that can have more than one value
335 # sort by is used to sort the query
336 # in theory can have more than one but generally there's just one
338 my $default_sort_by = C4::Context->preference('defaultSortField')."_".C4::Context->preference('defaultSortOrder')
339 if (C4::Context->preference('defaultSortField') && C4::Context->preference('defaultSortOrder'));
341 @sort_by = split("\0",$params->{'sort_by'}) if $params->{'sort_by'};
342 $sort_by[0] = $default_sort_by unless $sort_by[0];
343 foreach my $sort (@sort_by) {
344 $template->param($sort => 1);
346 $template->param('sort_by' => $sort_by[0]);
348 # Use the servers defined, or just search our local catalog(default)
350 @servers = split("\0",$params->{'server'}) if $params->{'server'};
352 #FIXME: this should be handled using Context.pm
353 @servers = ("biblioserver");
354 # @servers = C4::Context->config("biblioserver");
356 # operators include boolean and proximity operators and are used
357 # to evaluate multiple operands
359 @operators = split("\0",$params->{'op'}) if $params->{'op'};
361 # indexes are query qualifiers, like 'title', 'author', etc. They
362 # can be single or multiple parameters separated by comma: kw,right-Truncation
364 @indexes = split("\0",$params->{'idx'});
366 # if a simple index (only one) display the index used in the top search box
367 if ($indexes[0] && !$indexes[1]) {
368 $template->param("ms_".$indexes[0] => 1);}
371 # an operand can be a single term, a phrase, or a complete ccl query
373 @operands = split("\0",$params->{'q'}) if $params->{'q'};
375 # limits are use to limit to results to a pre-defined category such as branch or language
377 @limits = split("\0",$params->{'limit'}) if $params->{'limit'};
379 if($params->{'multibranchlimit'}) {
380 push @limits, join(" or ", map { "branch: $_ "} @{GetBranchesInCategory($params->{'multibranchlimit'})}) ;
384 foreach my $limit(@limits) {
385 if ($limit =~/available/) {
389 $template->param(available => $available);
391 # append year limits if they exist
394 if ($params->{'limit-yr'}) {
395 if ($params->{'limit-yr'} =~ /\d{4}-\d{4}/) {
396 my ($yr1,$yr2) = split(/-/, $params->{'limit-yr'});
397 $limit_yr = "yr,st-numeric,ge=$yr1 and yr,st-numeric,le=$yr2";
398 $limit_yr_value = "$yr1-$yr2";
400 elsif ($params->{'limit-yr'} =~ /\d{4}/) {
401 $limit_yr = "yr,st-numeric=$params->{'limit-yr'}";
402 $limit_yr_value = $params->{'limit-yr'};
404 push @limits,$limit_yr;
405 #FIXME: Should return a error to the user, incorect date format specified
408 # Params that can only have one value
409 my $scan = $params->{'scan'};
410 my $count = C4::Context->preference('numSearchResults') || 20;
411 my $results_per_page = $params->{'count'} || $count;
412 my $offset = $params->{'offset'} || 0;
413 my $page = $cgi->param('page') || 1;
414 #my $offset = ($page-1)*$results_per_page;
416 my $expanded_facet = $params->{'expand'};
418 # Define some global variables
419 my ( $error,$query,$simple_query,$query_cgi,$query_desc,$limit,$limit_cgi,$limit_desc,$stopwords_removed,$query_type);
423 ## I. BUILD THE QUERY
424 ( $error,$query,$simple_query,$query_cgi,$query_desc,$limit,$limit_cgi,$limit_desc,$stopwords_removed,$query_type) = buildQuery(\@operators,\@operands,\@indexes,\@limits,\@sort_by,$scan);
426 ## parse the query_cgi string and put it into a form suitable for <input>s
428 my $scan_index_to_use;
430 for my $this_cgi ( split('&',$query_cgi) ) {
431 next unless $this_cgi;
432 $this_cgi =~ m/(.*=)(.*)/;
434 my $input_value = $2;
435 $input_name =~ s/=$//;
436 push @query_inputs, { input_name => $input_name, input_value => $input_value };
437 if ($input_name eq 'idx') {
438 $scan_index_to_use = $input_value; # unless $scan_index_to_use;
441 $template->param ( QUERY_INPUTS => \@query_inputs,
442 scan_index_to_use => $scan_index_to_use );
444 ## parse the limit_cgi string and put it into a form suitable for <input>s
446 for my $this_cgi ( split('&',$limit_cgi) ) {
447 next unless $this_cgi;
448 # handle special case limit-yr
449 if ($this_cgi =~ /yr,st-numeric/) {
450 push @limit_inputs, { input_name => 'limit-yr', input_value => $limit_yr_value };
453 $this_cgi =~ m/(.*=)(.*)/;
455 my $input_value = $2;
456 $input_name =~ s/=$//;
457 push @limit_inputs, { input_name => $input_name, input_value => $input_value };
459 $template->param ( LIMIT_INPUTS => \@limit_inputs );
461 ## II. DO THE SEARCH AND GET THE RESULTS
462 my $total; # the total results for the whole set
463 my $facets; # this object stores the faceted results that display on the left-hand of the results page
467 if (C4::Context->preference('NoZebra')) {
468 $query=~s/yr(:|=)\s*([\d]{1,4})-([\d]{1,4})/(yr>=$2 and yr<=$3)/g;
469 $simple_query=~s/yr\s*(:|=)([\d]{1,4})-([\d]{1,4})/(yr>=$2 and yr<=$3)/g;
472 ($error, $results_hashref, $facets) = NZgetRecords($query,$simple_query,\@sort_by,\@servers,$results_per_page,$offset,$expanded_facet,$branches,$query_type,$scan);
476 ($error, $results_hashref, $facets) = getRecords($query,$simple_query,\@sort_by,\@servers,$results_per_page,$offset,$expanded_facet,$branches,$query_type,$scan);
480 $template->param(query_error => $error.$@);
482 output_html_with_http_headers $cgi, $cookie, $template->output;
486 # At this point, each server has given us a result set
487 # now we build that set for template display
488 my @sup_results_array;
489 for (my $i=0;$i<@servers;$i++) {
490 my $server = $servers[$i];
491 if ($server =~/biblioserver/) { # this is the local bibliographic server
492 $hits = $results_hashref->{$server}->{"hits"};
493 my $page = $cgi->param('page') || 0;
494 my @newresults = searchResults( $query_desc,$hits,$results_per_page,$offset,$scan,@{$results_hashref->{$server}->{"RECORDS"}});
495 $total = $total + $results_hashref->{$server}->{"hits"};
496 ## If there's just one result, redirect to the detail page
498 my $biblionumber=@newresults[0]->{biblionumber};
499 if (C4::Context->preference('IntranetBiblioDefaultView') eq 'isbd') {
500 print $cgi->redirect("/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber");
501 } elsif (C4::Context->preference('IntranetBiblioDefaultView') eq 'marc') {
502 print $cgi->redirect("/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber");
504 print $cgi->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber");
512 $template->param(total => $hits);
513 my $limit_cgi_not_availablity = $limit_cgi;
514 $limit_cgi_not_availablity =~ s/&limit=available//g;
515 $template->param(limit_cgi_not_availablity => $limit_cgi_not_availablity);
516 $template->param(limit_cgi => $limit_cgi);
517 $template->param(query_cgi => $query_cgi);
518 $template->param(query_desc => $query_desc);
519 $template->param(limit_desc => $limit_desc);
520 if ($query_desc || $limit_desc) {
521 $template->param(searchdesc => 1);
523 $template->param(stopwords_removed => "@$stopwords_removed") if $stopwords_removed;
524 $template->param(results_per_page => $results_per_page);
525 $template->param(SEARCH_RESULTS => \@newresults);
527 ## FIXME: add a global function for this, it's better than the current global one
528 ## Build the page numbers on the bottom of the page
530 # total number of pages there will be
531 my $pages = ceil($hits / $results_per_page);
532 # default page number
533 my $current_page_number = 1;
534 $current_page_number = ($offset / $results_per_page + 1) if $offset;
535 my $previous_page_offset = $offset - $results_per_page unless ($offset - $results_per_page <0);
536 my $next_page_offset = $offset + $results_per_page;
537 # If we're within the first 10 pages, keep it simple
538 #warn "current page:".$current_page_number;
539 if ($current_page_number < 10) {
540 # just show the first 10 pages
541 # Loop through the pages
542 my $pages_to_show = 10;
543 $pages_to_show = $pages if $pages<10;
544 for (my $i=1; $i<=$pages_to_show;$i++) {
545 # the offset for this page
546 my $this_offset = (($i*$results_per_page)-$results_per_page);
547 # the page number for this page
548 my $this_page_number = $i;
549 # it should only be highlighted if it's the current page
550 my $highlight = 1 if ($this_page_number == $current_page_number);
551 # put it in the array
552 push @page_numbers, { offset => $this_offset, pg => $this_page_number, highlight => $highlight, sort_by => join " ",@sort_by };
560 # now, show twenty pages, with the current one smack in the middle
562 for (my $i=$current_page_number; $i<=($current_page_number + 20 );$i++) {
563 my $this_offset = ((($i-9)*$results_per_page)-$results_per_page);
564 my $this_page_number = $i-9;
565 my $highlight = 1 if ($this_page_number == $current_page_number);
566 if ($this_page_number <= $pages) {
567 push @page_numbers, { offset => $this_offset, pg => $this_page_number, highlight => $highlight, sort_by => join " ",@sort_by };
572 # FIXME: no previous_page_offset when pages < 2
573 $template->param( PAGE_NUMBERS => \@page_numbers,
574 previous_page_offset => $previous_page_offset) unless $pages < 2;
575 $template->param( next_page_offset => $next_page_offset) unless $pages eq $current_page_number;
584 $template->param(searchdesc => 1,query_desc => $query_desc,limit_desc => $limit_desc);
591 } # end of the if local
593 # asynchronously search the authority server
594 elsif ($server =~/authorityserver/) { # this is the local authority server
595 my @inner_sup_results_array;
596 for my $sup_record ( @{$results_hashref->{$server}->{"RECORDS"}} ) {
597 my $marc_record_object = MARC::Record->new_from_usmarc($sup_record);
598 # warn "Authority Found: ".$marc_record_object->as_formatted();
599 push @inner_sup_results_array, {
600 'title' => $marc_record_object->field(100)->subfield('a'),
601 'link' => "&idx=an&q=".$marc_record_object->field('001')->as_string(),
604 my $servername = $server;
605 push @sup_results_array, { servername => $servername,
606 inner_sup_results_loop => \@inner_sup_results_array} if @inner_sup_results_array;
608 # FIXME: can add support for other targets as needed here
609 $template->param( outer_sup_results_loop => \@sup_results_array);
610 } #/end of the for loop
611 #$template->param(FEDERATED_RESULTS => \@results_array);
615 #classlist => $classlist,
618 facets_loop => $facets,
620 search_error => $error,
623 if ($query_desc || $limit_desc) {
624 $template->param(searchdesc => 1);
627 ## Now let's find out if we have any supplemental data to show the user
628 # and in the meantime, save the current query for statistical purposes, etc.
629 my $koha_spsuggest; # a flag to tell if we've got suggestions coming from Koha
630 my @koha_spsuggest; # place we store the suggestions to be returned to the template as LOOP
631 my $phrases = $query_desc;
634 if ( C4::Context->preference("kohaspsuggest") ) {
635 my ($suggest_host, $suggest_dbname, $suggest_user, $suggest_pwd) = split(':', C4::Context->preference("kohaspsuggest"));
637 my $koha_spsuggest_dbh;
638 # FIXME: this needs to be moved to Context.pm
640 $koha_spsuggest_dbh=DBI->connect("DBI:mysql:$suggest_dbname:$suggest_host","$suggest_user","$suggest_pwd");
643 warn "can't connect to spsuggest db";
646 my $koha_spsuggest_insert = "INSERT INTO phrase_log(phr_phrase,phr_resultcount,phr_ip) VALUES(?,?,?)";
647 my $koha_spsuggest_query = "SELECT display FROM distincts WHERE strcmp(soundex(suggestion), soundex(?)) = 0 order by soundex(suggestion) limit 0,5";
648 my $koha_spsuggest_sth = $koha_spsuggest_dbh->prepare($koha_spsuggest_query);
649 $koha_spsuggest_sth->execute($phrases);
650 while (my $spsuggestion = $koha_spsuggest_sth->fetchrow_array) {
651 $spsuggestion =~ s/(:|\/)//g;
653 $line{spsuggestion} = $spsuggestion;
654 push @koha_spsuggest,\%line;
658 # Now save the current query
659 $koha_spsuggest_sth=$koha_spsuggest_dbh->prepare($koha_spsuggest_insert);
660 #$koha_spsuggest_sth->execute($phrases,$results_per_page,$ipaddress);
661 $koha_spsuggest_sth->finish;
663 $template->param( koha_spsuggest => $koha_spsuggest ) unless $hits;
664 $template->param( SPELL_SUGGEST => \@koha_spsuggest,
669 warn "Kohaspsuggest failure:".$@;
673 # VI. BUILD THE TEMPLATE
674 output_html_with_http_headers $cgi, $cookie, $template->output;