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.0)
30 This script contains a new search API for Koha 3.0. 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 or nearly full support for the
34 bib1 attribute set, extended attribute sets defined in Zebra profiles, access
35 to the full range of Z39.50 query options, federated searches on Z39.50
38 I believe the API as represented in this script is mostly sound, even if the
39 individual functions in Search.pm and Koha.pm need to be cleaned up. Of course,
40 you are free to disagree :-)
42 I will attempt to describe what is happening at each part of this script.
47 This script performs two functions:
51 =item 1. interacts with Koha to retrieve and display the results of a search
53 =item 2. loads the advanced search page
57 These two functions share many of the same variables and modules, so the first
58 task is to load what they have in common and determine which template to use.
59 Once determined, proceed to only load the variables and procedures necessary
62 =head2 THE ADVANCED SEARCH PAGE
64 If we're loading the advanced search page this script will call a number of
65 display* routines which populate objects that are sent to the template for
66 display of things like search indexes, languages, search limits, branches,
67 etc. These are not stored in the template for two reasons:
71 =item 1. Efficiency - we have more control over objects inside the script,
72 and it's possible to not duplicate things like indexes (if the search indexes
73 were stored in the template they would need to be repeated)
75 =item 2. Customization - if these elements were moved to the sql database it
76 would allow a simple librarian to determine which fields to display on the page
77 without editing any html (also how the fields should behave when being searched).
81 However, they create one problem : the strings aren't translated. I have an idea
82 for how to do this that I will purusue soon.
84 =head2 PERFORMING A SEARCH
86 If we're performing a search, this script performs three primary
91 =item 1. builds query strings (yes, plural)
93 =item 2. perform the search and return the results array
95 =item 3. build the HTML for output to the template
99 There are several additional secondary functions performed that I will
102 =head3 1. Building Query Strings
104 There are several types of queries needed in the process of search and retrieve:
108 =item 1 Koha query - the query that is passed to Zebra
110 This is the most complex query that needs to be built. The original design goal
111 was to use a custom CCL2PQF query parser to translate an incoming CCL query into
112 a multi-leaf query to pass to Zebra. It needs to be multi-leaf to allow field
113 weighting, koha-specific relevance ranking, and stemming. When I have a chance
114 I'll try to flesh out this section to better explain.
116 This query incorporates query profiles that aren't compatible with non-Zebra
117 Z39.50 targets to acomplish the field weighting and relevance ranking.
119 =item 2 Federated query - the query that is passed to other Z39.50 targets
121 This query is just the user's query expressed in CCL CQL, or PQF for passing to a
122 non-zebra Z39.50 target (one that doesn't support the extended profile that Zebra does).
124 =item 3 Search description - passed to the template / saved for future refinements of
127 This is a simple string that completely expresses the query in a way that can be parsed
128 by Koha for future refinements of the query or as a part of a history feature. It differs
129 from the human search description:
131 1. it does not contain commas or = signs
133 =item 4 Human search description - what the user sees in the search_desc area
135 This is a simple string nearly identical to the Search description, but more human
136 readable. It will contain = signs or commas, etc.
140 =head3 2. Perform the Search
142 This section takes the query strings and performs searches on the named servers, including
143 the Koha Zebra server, stores the results in a deeply nested object, builds 'faceted results',
144 and returns these objects.
148 The final major section of this script takes the objects collected thusfar and builds the
149 HTML for output to the template and user.
151 =head3 Additional Notes
157 use strict; # always use
159 ## STEP 1. Load things that are used in both search page and
160 # results page and decide which template to load, operations
167 use C4::Languages; # getAllLanguages
169 use POSIX qw(ceil floor);
170 use C4::Branch; # GetBranches
171 # create a new CGI object
172 # not sure undef_params option is working, need to test
173 use CGI qw('-no_undef_params');
176 my ($template,$borrowernumber,$cookie);
178 # decide which template to use
181 my @params = $cgi->param("limit");
182 if ((@params>=1) || ($cgi->param("q")) || ($cgi->param('multibranchlimit')) || ($cgi->param('limit-yr')) ) {
183 $template_name = 'opac-results.tmpl';
186 $template_name = 'opac-advsearch.tmpl';
187 $template_type = 'advsearch';
190 ($template, $borrowernumber, $cookie) = get_template_and_user({
191 template_name => $template_name,
194 authnotrequired => 1,
197 if (C4::Context->preference("marcflavour") eq "UNIMARC" ) {
198 $template->param('UNIMARC' => 1);
201 =head1 BUGS and FIXMEs
203 There are many, most are documented in the code. The one that
204 isn't fully documented, but referred to is the need for a full
210 # Deprecated, but preserved because it's interesting :-)
212 #my $uri = $cgi->url(-base => 1);
213 #my $relative_url = $cgi->url(-relative=>1);
214 #$uri.="/".$relative_url."?";
216 #my @cgi_params_list = $cgi->param();
217 #my $url_params = $cgi->Vars;
219 #for my $each_param_set (@cgi_params_list) {
220 # $uri.= join "", map "\&$each_param_set=".$_, split("\0",$url_params->{$each_param_set}) if $url_params->{$each_param_set};
222 #warn "New URI:$uri";
223 # Only re-write a URI if there are params or if it already hasn't been re-written
224 #unless (($cgi->param('r')) || (!$cgi->param()) ) {
225 # print $cgi->redirect( -uri=>$uri."&r=1",
226 # -cookie => $cookie);
231 my $branches = GetBranches();
233 #push @branch_loop, {value => "", branchname => "All Branches", };
234 for my $branch_hash (sort keys %$branches) {
235 push @branch_loop, {value => "$branch_hash" , branchname => $branches->{$branch_hash}->{'branchname'}, };
238 my $categories = GetBranchCategories(undef,'searchdomain');
240 $template->param(branchloop => \@branch_loop, searchdomainloop => $categories);
243 my $itemtypes = GetItemTypes;
247 my $imgdir = getitemtypeimagesrc();
248 foreach my $thisitemtype ( sort {$itemtypes->{$a}->{'description'} cmp $itemtypes->{$b}->{'description'} } keys %$itemtypes ) {
249 my %row =( number=>$cnt++,
250 imageurl=> $itemtypes->{$thisitemtype}->{'imageurl'}?($imgdir."/".$itemtypes->{$thisitemtype}->{'imageurl'}):"",
251 code => $thisitemtype,
252 selected => $selected,
253 description => $itemtypes->{$thisitemtype}->{'description'},
256 $selected = 0 if ($selected) ;
257 push @itemtypesloop, \%row;
259 $template->param(itemtypeloop => \@itemtypesloop);
261 # # load the itypes (Called item types in the template -- just authorized values for searching)
262 # my ($itypecount,@itype_loop) = GetCcodes();
263 # $template->param(itypeloop=>\@itype_loop,);
265 # load the languages ( for switching from one template to another )
266 $template->param(languages_loop => getTranslatedLanguages('intranet','prog'));
268 # The following should only be loaded if we're bringing up the advanced search template
269 if ( $template_type eq 'advsearch' ) {
270 # load the servers (used for searching -- to do federated searching, etc.)
271 my $primary_servers_loop;# = displayPrimaryServers();
272 $template->param(outer_servers_loop => $primary_servers_loop,);
274 my $secondary_servers_loop;# = displaySecondaryServers();
275 $template->param(outer_sup_servers_loop => $secondary_servers_loop,);
277 # determine what to display next to the search boxes (ie, boolean option
278 # shouldn't appear on the first one, scan indexes should, adding a new
279 # box should only appear on the last, etc.
280 my @search_boxes_array;
281 my $search_boxes_count = C4::Context->preference("OPACAdvSearchInputCount") | 3; # FIXME: should be a syspref
282 for (my $i=1;$i<=$search_boxes_count;$i++) {
283 # if it's the first one, don't display boolean option, but show scan indexes
285 push @search_boxes_array,
291 # if it's the last one, show the 'add field' box
292 elsif ($i==$search_boxes_count) {
293 push @search_boxes_array,
300 push @search_boxes_array,
307 $template->param(uc(C4::Context->preference("marcflavour")) => 1,
308 search_boxes_loop => \@search_boxes_array);
310 # load the language limits (for search)
311 my $languages_limit_loop = getAllLanguages();
312 $template->param(search_languages_loop => $languages_limit_loop,);
314 # use the global setting by default
315 if ( C4::Context->preference("expandedSearchOption") == 1) {
316 $template->param( expanded_options => C4::Context->preference("expandedSearchOption") );
318 # but let the user override it
319 if ( ($cgi->param('expanded_options') == 0) || ($cgi->param('expanded_options') == 1 ) ) {
320 $template->param( expanded_options => $cgi->param('expanded_options'));
323 output_html_with_http_headers $cgi, $cookie, $template->output;
327 ### OK, if we're this far, we're performing an actual search
329 # Fetch the paramater list as a hash in scalar context:
330 # * returns paramater list as tied hash ref
331 # * we can edit the values by changing the key
332 # * multivalued CGI paramaters are returned as a packaged string separated by "\0" (null)
333 my $params = $cgi->Vars;
335 # Params that can have more than one value
336 # sort by is used to sort the query
337 # in theory can have more than one but generally there's just one
338 my $default_sort_by = C4::Context->preference('OPACdefaultSortField')."_".C4::Context->preference('OPACdefaultSortOrder')
339 if (C4::Context->preference('OPACdefaultSortField') && C4::Context->preference('OPACdefaultSortOrder'));
342 @sort_by = split("\0",$params->{'sort_by'}) if $params->{'sort_by'};
343 $sort_by[0] = $default_sort_by unless $sort_by[0];
344 foreach my $sort (@sort_by) {
345 $template->param($sort => 1);
347 $template->param('sort_by' => $sort_by[0]);
349 # Use the servers defined, or just search our local catalog(default)
351 @servers = split("\0",$params->{'server'}) if $params->{'server'};
353 #FIXME: this should be handled using Context.pm
354 @servers = ("biblioserver");
355 # @servers = C4::Context->config("biblioserver");
358 # operators include boolean and proximity operators and are used
359 # to evaluate multiple operands
361 @operators = split("\0",$params->{'op'}) if $params->{'op'};
363 # indexes are query qualifiers, like 'title', 'author', etc. They
364 # can be single or multiple parameters separated by comma: kw,right-Truncation
365 my @indexes = split("\0",$params->{'idx'});
367 # if a simple index (only one) display the index used in the top search box
368 if ($indexes[0] && !$indexes[1]) {
369 $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 # if a simple search, display the value in the search box
376 if ($operands[0] && !$operands[1]) {
377 $template->param(ms_value => $operands[0]);
380 # limits are use to limit to results to a pre-defined category such as branch or language
382 @limits = split("\0",$params->{'limit'}) if $params->{'limit'};
384 if($params->{'multibranchlimit'}) {
385 push @limits, join(" or ", map { "branch: $_ "} @{GetBranchesInCategory($params->{'multibranchlimit'})}) ;
389 foreach my $limit(@limits) {
390 if ($limit =~/available/) {
394 $template->param(available => $available);
396 # append year limits if they exist
397 push @limits, map "yr:".$_, split("\0",$params->{'limit-yr'}) if $params->{'limit-yr'};
399 # Params that can only have one value
400 my $scan = $params->{'scan'};
401 my $count = C4::Context->preference('OPACnumSearchResults') || 20;
402 my $results_per_page = $params->{'count'} || $count;
403 my $offset = $params->{'offset'} || 0;
404 my $page = $cgi->param('page') || 1;
405 #my $offset = ($page-1)*$results_per_page;
407 my $expanded_facet = $params->{'expand'};
409 # Define some global variables
410 my ($error,$query,$simple_query,$query_cgi,$query_desc,$limit,$limit_cgi,$limit_desc,$stopwords_removed,$query_type);
414 ## I. BUILD THE QUERY
415 ( $error,$query,$simple_query,$query_cgi,$query_desc,$limit,$limit_cgi,$limit_desc,$stopwords_removed,$query_type) = buildQuery(\@operators,\@operands,\@indexes,\@limits,\@sort_by);
417 sub _input_cgi_parse ($) {
419 for my $this_cgi ( split('&',shift) ) {
420 next unless $this_cgi;
421 $this_cgi =~ /(.*)=(.*)/;
423 my $input_value = $2;
424 push @elements, { input_name => $input_name, input_value => $input_value };
429 ## parse the query_cgi string and put it into a form suitable for <input>s
430 my @query_inputs = _input_cgi_parse($query_cgi);
431 $template->param ( QUERY_INPUTS => \@query_inputs );
433 ## parse the limit_cgi string and put it into a form suitable for <input>s
434 my @limit_inputs = _input_cgi_parse($query_cgi);
436 # add OPAC 'hidelostitems'
438 if (C4::Context->preference('hidelostitems') == 1) {
439 $query ="($query) not ((lost,st-numeric gt 0) or ( allrecords,AlwaysMatches='' not lost,AlwaysMatches=''))";
442 # add OPAC suppression - requires at least one item indexed with Suppress
443 if (C4::Context->preference('OpacSuppression')) {
444 $query = "($query) not Suppress=1";
446 $template->param ( LIMIT_INPUTS => \@limit_inputs );
448 ## II. DO THE SEARCH AND GET THE RESULTS
449 my $total; # the total results for the whole set
450 my $facets; # this object stores the faceted results that display on the left-hand of the results page
454 if (C4::Context->preference('NoZebra')) {
456 ($error, $results_hashref, $facets) = NZgetRecords($query,$simple_query,\@sort_by,\@servers,$results_per_page,$offset,$expanded_facet,$branches,$query_type,$scan);
460 ($error, $results_hashref, $facets) = getRecords($query,$simple_query,\@sort_by,\@servers,$results_per_page,$offset,$expanded_facet,$branches,$query_type,$scan);
464 $template->param(query_error => $error.$@);
465 output_html_with_http_headers $cgi, $cookie, $template->output;
469 # FIXME: This belongs in tools/ not in the primary search results page
470 my $op=$cgi->param("operation");
471 if ($op eq "bulkedit"){
472 my ($countchanged,$listunchanged)=
473 ModBiblios($results_hashref->{'biblioserver'}->{"RECORDS"},
474 $params->{"tagsubfield"},
475 $params->{"inputvalue"},
476 $params->{"targetvalue"},
479 $template->param(bulkeditresults=>1,
480 tagsubfield=>$params->{"tagsubfield"},
481 inputvalue=>$params->{"inputvalue"},
482 targetvalue=>$params->{"targetvalue"},
483 countchanged=>$countchanged,
484 countunchanged=>scalar(@$listunchanged),
485 listunchanged=>$listunchanged);
487 if (C4::Context->userenv->{'flags'}==1 ||(C4::Context->userenv->{'flags'} & ( 2**9 ) )){
488 #Edit Catalogue Permissions
489 $template->param(bulkedit => 1);
490 $template->param(tagsubfields=>GetManagedTagSubfields());
493 # At this point, each server has given us a result set
494 # now we build that set for template display
495 my @sup_results_array;
496 for (my $i=0;$i<=@servers;$i++) {
497 my $server = $servers[$i];
498 if ($server =~/biblioserver/) { # this is the local bibliographic server
499 $hits = $results_hashref->{$server}->{"hits"};
500 my $page = $cgi->param('page') || 0;
501 my @newresults = searchResults( $query_desc,$hits,$results_per_page,$offset,@{$results_hashref->{$server}->{"RECORDS"}});
502 $total = $total + $results_hashref->{$server}->{"hits"};
504 $template->param(total => $hits);
505 my $limit_cgi_not_availablity = $limit_cgi;
506 $limit_cgi_not_availablity =~ s/&limit=available//g;
507 $template->param(limit_cgi_not_availablity => $limit_cgi_not_availablity);
508 $template->param(limit_cgi => $limit_cgi);
509 $template->param(query_cgi => $query_cgi);
510 $template->param(query_desc => $query_desc);
511 $template->param(limit_desc => $limit_desc);
512 if ($query_desc || $limit_desc) {
513 $template->param(searchdesc => 1);
515 $template->param(stopwords_removed => "@$stopwords_removed") if $stopwords_removed;
516 $template->param(results_per_page => $results_per_page);
517 $template->param(SEARCH_RESULTS => \@newresults);
518 ## Build the page numbers on the bottom of the page
520 # total number of pages there will be
521 my $pages = ceil($hits / $results_per_page);
522 # default page number
523 my $current_page_number = 1;
524 $current_page_number = ($offset / $results_per_page + 1) if $offset;
525 my $previous_page_offset = $offset - $results_per_page unless ($offset - $results_per_page <0);
526 my $next_page_offset = $offset + $results_per_page;
527 # If we're within the first 10 pages, keep it simple
528 #warn "current page:".$current_page_number;
529 if ($current_page_number < 10) {
530 # just show the first 10 pages
531 # Loop through the pages
532 my $pages_to_show = 10;
533 $pages_to_show = $pages if $pages<10;
534 for ($i=1; $i<=$pages_to_show;$i++) {
535 # the offset for this page
536 my $this_offset = (($i*$results_per_page)-$results_per_page);
537 # the page number for this page
538 my $this_page_number = $i;
539 # it should only be highlighted if it's the current page
540 my $highlight = 1 if ($this_page_number == $current_page_number);
541 # put it in the array
542 push @page_numbers, { offset => $this_offset, pg => $this_page_number, highlight => $highlight, sort_by => join " ",@sort_by };
547 # now, show twenty pages, with the current one smack in the middle
549 for ($i=$current_page_number; $i<=($current_page_number + 20 );$i++) {
550 my $this_offset = ((($i-9)*$results_per_page)-$results_per_page);
551 my $this_page_number = $i-9;
552 my $highlight = 1 if ($this_page_number == $current_page_number);
553 if ($this_page_number <= $pages) {
554 push @page_numbers, { offset => $this_offset, pg => $this_page_number, highlight => $highlight, sort_by => join " ",@sort_by };
559 $template->param( PAGE_NUMBERS => \@page_numbers,
560 previous_page_offset => $previous_page_offset) unless $pages < 2;
561 $template->param(next_page_offset => $next_page_offset) unless $pages eq $current_page_number;
564 # Here we must handle cases where no results are returned otherwise the template gives a malformed message. -fbcit
565 $template->param(query_desc => $query_desc);
567 } # end of the if local
569 # check if it's a z3950 or opensearch source
570 my $zed3950 = 0; # FIXME :: Hardcoded value.
572 my @inner_sup_results_array;
573 for my $sup_record ( @{$results_hashref->{$server}->{"RECORDS"}} ) {
574 my $marc_record_object = MARC::Record->new_from_usmarc($sup_record);
575 my $control_number = $marc_record_object->field('010')->subfield('a') if $marc_record_object->field('010');
576 $control_number =~ s/^ //g;
577 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";
578 my $title = $marc_record_object->title();
579 push @inner_sup_results_array, {
584 my $servername = $server;
585 push @sup_results_array, { servername => $servername, inner_sup_results_loop => \@inner_sup_results_array};
586 $template->param(outer_sup_results_loop => \@sup_results_array);
590 } #/end of the for loop
591 #$template->param(FEDERATED_RESULTS => \@results_array);
595 #classlist => $classlist,
598 facets_loop => $facets,
600 search_error => $error,
603 if ($query_desc || $limit_desc) {
604 $template->param(searchdesc => 1);
607 ## Now let's find out if we have any supplemental data to show the user
608 # and in the meantime, save the current query for statistical purposes, etc.
609 my $koha_spsuggest; # a flag to tell if we've got suggestions coming from Koha
610 my @koha_spsuggest; # place we store the suggestions to be returned to the template as LOOP
611 my $phrases = $query_desc;
614 if ( C4::Context->preference("kohaspsuggest") ) {
615 my ($suggest_host, $suggest_dbname, $suggest_user, $suggest_pwd) = split(':', C4::Context->preference("kohaspsuggest"));
617 my $koha_spsuggest_dbh;
618 # FIXME: this needs to be moved to Context.pm
620 $koha_spsuggest_dbh=DBI->connect("DBI:mysql:$suggest_dbname:$suggest_host","$suggest_user","$suggest_pwd");
623 warn "can't connect to spsuggest db";
626 my $koha_spsuggest_insert = "INSERT INTO phrase_log(phr_phrase,phr_resultcount,phr_ip) VALUES(?,?,?)";
627 my $koha_spsuggest_query = "SELECT display FROM distincts WHERE strcmp(soundex(suggestion), soundex(?)) = 0 order by soundex(suggestion) limit 0,5";
628 my $koha_spsuggest_sth = $koha_spsuggest_dbh->prepare($koha_spsuggest_query);
629 $koha_spsuggest_sth->execute($phrases);
630 while (my $spsuggestion = $koha_spsuggest_sth->fetchrow_array) {
631 $spsuggestion =~ s/(:|\/)//g;
633 $line{spsuggestion} = $spsuggestion;
634 push @koha_spsuggest,\%line;
638 # Now save the current query
639 $koha_spsuggest_sth=$koha_spsuggest_dbh->prepare($koha_spsuggest_insert);
640 #$koha_spsuggest_sth->execute($phrases,$results_per_page,$ipaddress);
641 $koha_spsuggest_sth->finish;
643 $template->param( koha_spsuggest => $koha_spsuggest ) unless $hits;
644 $template->param( SPELL_SUGGEST => \@koha_spsuggest,
649 warn "Kohaspsuggest failure:".$@;
653 # VI. BUILD THE TEMPLATE
654 output_html_with_http_headers $cgi, $cookie, $template->output;