3 # Script to perform searching
4 # For documentation try 'perldoc /path/to/search'
8 # Copyright 2006 LibLime
10 # This file is part of Koha
12 # Koha is free software; you can redistribute it and/or modify it under the
13 # terms of the GNU General Public License as published by the Free Software
14 # Foundation; either version 2 of the License, or (at your option) any later
17 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
18 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
19 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
21 # You should have received a copy of the GNU General Public License along with
22 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
23 # Suite 330, Boston, MA 02111-1307 USA
27 search - a search script for finding records in a Koha system (Version 2.4)
31 This script contains a demonstration of a new search API for Koha 2.4. It is
32 designed to be simple to use and configure, yet capable of performing feats
33 like stemming, field weighting, relevance ranking, support for multiple
34 query language formats (CCL, CQL, PQF), full or nearly full support for the
35 bib1 attribute set, extended attribute sets defined in Zebra profiles, access
36 to the full range of Z39.50 query options, federated searches on Z39.50
39 I believe the API as represented in this script is mostly sound, even if the
40 individual functions in Search.pm and Koha.pm need to be cleaned up. Of course,
41 you are free to disagree :-)
43 I will attempt to describe what is happening at each part of this script.
48 This script performs two functions:
52 =item 1. interacts with Koha to retrieve and display the results of a search
54 =item 2. loads the advanced search page
58 These two functions share many of the same variables and modules, so the first
59 task is to load what they have in common and determine which template to use.
60 Once determined, proceed to only load the variables and procedures necessary
63 =head2 THE ADVANCED SEARCH PAGE
65 If we're loading the advanced search page this script will call a number of
66 display* routines which populate objects that are sent to the template for
67 display of things like search indexes, languages, search limits, branches,
68 etc. These are not stored in the template for two reasons:
72 =item 1. Efficiency - we have more control over objects inside the script, and it's possible to not duplicate things like indexes (if the search indexes were stored in the template they would need to be repeated)
74 =item 2. Customization - if these elements were moved to the sql database it would allow a simple librarian to determine which fields to display on the page without editing any html (also how the fields should behave when being searched).
78 However, they create one problem : the strings aren't translated. I have an idea
79 for how to do this that I will purusue soon.
81 =head2 PERFORMING A SEARCH
83 If we're performing a search, this script performs three primary
88 =item 1. builds query strings (yes, plural)
90 =item 2. perform the search and return the results array
92 =item 3. build the HTML for output to the template
96 There are several additional secondary functions performed that I will
99 =head3 1. Building Query Strings
101 There are several types of queries needed in the process of search and retrieve:
105 =item 1 Koha query - the query that is passed to Zebra
107 This is the most complex query that needs to be built.The original design goal was to use a custom CCL2PQF query parser to translate an incoming CCL query into a multi-leaf query to pass to Zebra. It needs to be multi-leaf to allow field weighting, koha-specific relevance ranking, and stemming. When I have a chance I'll try to flesh out this section to better explain.
109 This query incorporates query profiles that aren't compatible with non-Zebra Z39.50 targets to acomplish the field weighting and relevance ranking.
111 =item 2 Federated query - the query that is passed to other Z39.50 targets
113 This query is just the user's query expressed in CCL CQL, or PQF for passing to a non-zebra Z39.50 target (one that doesn't support the extended profile that Zebra does).
115 =item 3 Search description - passed to the template / saved for future refinements of the query (by user)
117 This is a simple string that completely expresses the query in a way that can be parsed by Koha for future refinements of the query or as a part of a history feature. It differs from the human search description in several ways:
119 1. it does not contain commas or = signs
122 =item 4 Human search description - what the user sees in the search_desc area
124 This is a simple string nearly identical to the Search description, but more human readable. It will contain = signs or commas, etc.
128 =head3 2. Perform the Search
130 This section takes the query strings and performs searches on the named servers, including the Koha Zebra server, stores the results in a deeply nested object, builds 'faceted results', and returns these objects.
134 The final major section of this script takes the objects collected thusfar and builds the HTML for output to the template and user.
136 =head3 Additional Notes
142 use strict; # always use
144 #use warnings; # use only for development
146 ## STEP 1. Load things that are used in both search page and
147 # results page and decide which template to load, operations
154 use C4::Languages; # getAllLanguages
156 use C4::Branch; # GetBranches
157 use POSIX qw(ceil floor);
159 # create a new CGI object
160 # not sure undef_params option is working, need to test
161 use CGI qw('-no_undef_params');
164 my ( $template, $borrowernumber, $cookie );
166 # decide which template to use
168 my @params = $cgi->param("limit");
169 if ( ( @params > 1 ) || ( $cgi->param("q") ) ) {
171 $template_name = 'opac-results.tmpl';
175 $template_name = 'opac-advsearch.tmpl';
179 ( $template, $borrowernumber, $cookie ) = get_template_and_user(
181 template_name => $template_name,
184 authnotrequired => 1,
188 =head1 BUGS and FIXMEs
190 There are many, most are documented in the code. The one that
191 isn't fully documented, but referred to is the need for a full
197 # FIXME: URI re-writing should be tested more carefully and may better
198 # handled by mod_rewrite or something else. The code below almost works,
199 # but doesn't quite handle limits correctly when they are the only
200 # param passed -- I'll work on this soon -- JF
202 #my $uri = $cgi->url(-base => 1);
203 #my $relative_url = $cgi->url(-relative=>1);
204 #$uri.="/".$relative_url."?";
206 #my @cgi_params_list = $cgi->param();
207 #my $url_params = $cgi->Vars;
209 #for my $each_param_set (@cgi_params_list) {
210 # $uri.= join "", map "\&$each_param_set=".$_, split("\0",$url_params->{$each_param_set}) if $url_params->{$each_param_set};
212 #warn "New URI:$uri";
213 # Only re-write a URI if there are params or if it already hasn't been re-written
214 #unless (($cgi->param('r')) || (!$cgi->param()) ) {
215 # print $cgi->redirect( -uri=>$uri."&r=1",
216 # -cookie => $cookie);
221 my $branches = GetBranches();
223 for my $branch_hash (sort keys %$branches ) {
224 my $selected=(C4::Context->userenv && ($branch_hash eq C4::Context->userenv->{branch})) if (C4::Context->preference('SearchMyLibraryFirst'));
227 value => "branch: $branch_hash",
228 branchname => $branches->{$branch_hash}->{'branchname'},
229 selected => $selected
232 $template->param( branchloop => \@branch_loop, "mylibraryfirst"=>C4::Context->preference("SearchMyLibraryFirst"));
234 # load the itemtypes (Called Collection Codes in the template -- used for circ rules )
235 my $itemtypes = GetItemTypes;
239 my $imgdir = getitemtypeimagesrc();
240 foreach my $thisitemtype ( sort {$itemtypes->{$a}->{'description'} cmp $itemtypes->{$b}->{'description'} } keys %$itemtypes ) {
243 imageurl => $imgdir . "/" . $itemtypes->{$thisitemtype}->{'imageurl'},
244 code => $thisitemtype,
245 selected => $selected,
246 description => $itemtypes->{$thisitemtype}->{'description'},
249 $selected = 0 if ($selected);
250 push @itemtypesloop, \%row;
252 $template->param( itemtypeloop => \@itemtypesloop );
254 # # load the itypes (Called item types in the template -- just authorized values for searching)
255 # my ($itypecount,@itype_loop) = GetCcodes();
256 # $template->param(itypeloop=>\@itype_loop,);
258 # load the languages ( for switching from one template to another )
259 # my @languages_options = displayLanguages($cgi);
260 # my $languages_count = @languages_options;
261 # if($languages_count > 1){
262 # $template->param(languages => \@languages_options);
265 # The following should only be loaded if we're bringing up the advanced search template
266 if ( $template_name eq "opac-advsearch.tmpl" ) {
268 # load the servers (used for searching -- to do federated searching, etc.)
269 my $primary_servers_loop; # = displayPrimaryServers();
270 $template->param( outer_servers_loop => $primary_servers_loop, );
272 my $secondary_servers_loop; # = displaySecondaryServers();
273 $template->param( outer_sup_servers_loop => $secondary_servers_loop, );
275 # determine what to display next to the search boxes (ie, boolean option
276 # shouldn't appear on the first one, scan indexes should, adding a new
277 # box should only appear on the last, etc.
278 # FIXME: this stuff should be cleaned up a bit and the html should be turned
279 # into flags for the template -- I'll work on that soon -- JF
280 my @search_boxes_array;
281 my $search_boxes_count = 1; # should be a syspref
282 for ( my $i = 0 ; $i <= $search_boxes_count ; $i++ ) {
284 push @search_boxes_array,
286 search_boxes_label => "<span class='labels'>Search for:</span>",
291 elsif ( $i == $search_boxes_count ) {
292 push @search_boxes_array,
295 " <select name='op'><option value='and' selected='selected'>and</option><option value='or'>or</option><option value='not'>not</option></select>",
300 push @search_boxes_array,
303 " <select name='op'><option value='and' selected='selected'>and</option><option value='or'>or</option><option value='not'>not</option></select>",
308 uc( C4::Context->preference("marcflavour") ) => 1,
309 search_boxes_loop => \@search_boxes_array
312 # load the language limits (for search)
313 my $languages_limit_loop = getAllLanguages();
314 $template->param( search_languages_loop => $languages_limit_loop, );
316 my $expanded_options;
317 if ( C4::Context->preference("expandedSearchOption") ) {
318 $expanded_options = C4::Context->preference("expandedSearchOption");
321 $expanded_options = $cgi->param('expanded_options');
324 $template->param( expanded_options => $expanded_options );
326 # load the sort_by options for the template
327 my $sort_by = $cgi->param('sort_by');
328 $sort_by=$1.($2 eq "lt"?'d':'a') if ($sort_by=~/1=(\d+) \&([a-z]+)\;/);
329 $template->param( sort_by => $sort_by);
331 output_html_with_http_headers $cgi, $cookie, $template->output;
335 ### OK, if we're this far, we're performing an actual search
337 # Fetch the paramater list as a hash in scalar context:
338 # * returns paramater list as tied hash ref
339 # * we can edit the values by changing the key
340 # * multivalued CGI paramaters are returned as a packaged string separated by "\0" (null)
341 my $params = $cgi->Vars;
343 # Params that can have more than one value
344 # sort by is used to sort the query
346 @sort_by = split( "\0", $params->{'sort_by'} ) if $params->{'sort_by'};
348 # load the sort_by options for the template
349 my $sort_by = $params->{'sort_by'};
350 $sort_by=~$1.($2 eq "lt"?'d':'a') if ($sort_by=~/1=(\d+) \&([a-z]+)\;/);
351 $template->param( sort_by => $sort_by);
354 # Use the servers defined, or just search our local catalog(default)
356 @servers = split( "\0", $params->{'server'} ) if $params->{'server'};
359 #FIXME: this should be handled using Context.pm
360 @servers = ("biblioserver");
362 # @servers = C4::Context->config("biblioserver");
365 # operators include boolean and proximity operators and are used
366 # to evaluate multiple operands
368 @operators = split( "\0", $params->{'op'} ) if $params->{'op'};
370 # indexes are query qualifiers, like 'title', 'author', etc. They
371 # can be simple or complex
373 if ($params->{'idx'}) {
374 @indexes = split("\0",$params->{'idx'});
376 $indexes[0] = 'kw,wrdl';
379 # an operand can be a single term, a phrase, or a complete ccl query
381 @operands = split( "\0", $params->{'q'} ) if $params->{'q'};
383 # limits are use to limit to results to a pre-defined category such as branch or language
385 @limits = split( "\0", $params->{'limit'} ) if $params->{'limit'};
388 foreach my $limit (@limits) {
389 if ( $limit =~ /available/ ) {
393 $template->param( available => $available );
394 push @limits, map "yr:" . $_, split( "\0", $params->{'limit-yr'} )
395 if $params->{'limit-yr'};
397 # Params that can only have one value
398 my $query = $params->{'q'};
399 my $scan = $params->{'scan'};
400 my $results_per_page = $params->{'count'} || 20;
401 my $offset = $params->{'offset'} || 0;
403 my $expanded_facet = $params->{'expand'};
405 # Define some global variables
406 my $error; # used for error handling
407 my $search_desc; # the query expressed in terms that humans understand
408 my $koha_query; # the query expressed in terms that zoom understands with field weighting and stemming
410 my $query_type; # usually not needed, but can be used to trigger ccl, cql, or pqf queries if set
413 ## I. BUILD THE QUERY
414 ( $error, $search_desc, $koha_query, $federated_query, $query_type ) =
415 buildQuery( $query, \@operators, \@operands, \@indexes, \@limits );
417 # warn "query : $koha_query";
418 ## II. DO THE SEARCH AND GET THE RESULTS
419 my $total; # the total results for the whole set
420 my $facets; # this object stores the faceted results that display on the left-hand of the results page
424 if (C4::Context->preference('NoZebra')) {
426 ($error, $results_hashref, $facets) = NZgetRecords($koha_query,$federated_query,\@sort_by,\@servers,$results_per_page,$offset,$expanded_facet,$branches,$query_type,$scan);
430 ($error, $results_hashref, $facets) = getRecords($koha_query,$federated_query,\@sort_by,\@servers,$results_per_page,$offset,$expanded_facet,$branches,$query_type,$scan);
433 if ( $@ || $error ) {
434 $template->param( query_error => $error . $@ );
436 # warn "error: ".$error.$@;
437 output_html_with_http_headers $cgi, $cookie, $template->output;
441 # At this point, each server has given us a result set
442 # now we build that set for template display
443 my @sup_results_array;
444 for ( my $i = 0 ; $i <= @servers ; $i++ ) {
445 my $server = $servers[$i];
446 if ( $server =~ /biblioserver/ ) { # this is the local bibliographic server
447 $hits = $results_hashref->{$server}->{"hits"};
449 searchResults( $search_desc, $hits, $results_per_page, $offset,
450 @{ $results_hashref->{$server}->{"RECORDS"} } );
451 $total = $total + $results_hashref->{$server}->{"hits"};
453 $template->param( total => $hits );
454 $template->param( searchdesc => $search_desc );
455 $template->param( results_per_page => $results_per_page );
456 $template->param( SEARCH_RESULTS => \@newresults );
459 my $pages = ceil( $hits / $results_per_page );
460 my $current_page_number = 1;
461 $current_page_number = ( $offset / $results_per_page + 1 )
463 my $previous_page_offset = $offset - $results_per_page
464 unless ( $offset - $results_per_page < 0 );
465 my $next_page_offset = $offset + $results_per_page;
466 for ( $i = 1 ; $i <= $pages ; $i++ ) {
468 ( ( $i * $results_per_page ) - $results_per_page );
469 my $this_page_number = $i;
471 if ( $this_page_number == $current_page_number );
472 if ($this_page_number <= $pages) {
475 offset => $this_offset,
476 pg => $this_page_number,
477 highlight => $highlight,
484 PAGE_NUMBERS => \@page_numbers,
485 previous_page_offset => $previous_page_offset,
486 next_page_offset => $next_page_offset
489 } # end of the if local
492 # check if it's a z3950 or opensearch source
493 my $zed3950 = 0; # FIXME :: Hardcoded value.
495 my @inner_sup_results_array;
496 for my $sup_record ( @{ $results_hashref->{$server}->{"RECORDS"} } )
498 my $marc_record_object =
499 MARC::Record->new_from_usmarc($sup_record);
501 $marc_record_object->field('010')->subfield('a')
502 if $marc_record_object->field('010');
503 $control_number =~ s/^ //g;
505 "http://catalog.loc.gov/cgi-bin/Pwebrecon.cgi?SAB1="
507 . "&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";
508 my $title = $marc_record_object->title();
509 push @inner_sup_results_array,
515 my $servername = $server;
516 push @sup_results_array,
518 servername => $servername,
519 inner_sup_results_loop => \@inner_sup_results_array
521 $template->param( outer_sup_results_loop => \@sup_results_array );
525 } #/end of the for loop
527 #$template->param(FEDERATED_RESULTS => \@results_array);
528 # adding the $RequestOnOpac param
530 if (C4::Context->preference("RequestOnOpac")) {
533 # get site URL (for RSS link)
534 $cgi->url() =~ /(.*)\/(.*)/;
539 #classlist => $classlist,
541 searchdesc => $search_desc,
543 facets_loop => $facets,
544 "BiblioDefaultView" . C4::Context->preference("BiblioDefaultView") => 1,
546 search_error => $error,
547 RequestOnOpac => $RequestOnOpac,
549 site_url => $site_url,
551 ## Now let's find out if we have any supplemental data to show the user
552 # and in the meantime, save the current query for statistical purposes, etc.
553 my $koha_spsuggest; # a flag to tell if we've got suggestions coming from Koha
555 ; # place we store the suggestions to be returned to the template as LOOP
556 my $phrases = $search_desc;
559 if ( C4::Context->preference("kohaspsuggest") ) {
560 my ($suggest_host, $suggest_dbname, $suggest_user, $suggest_pwd) = split(':', C4::Context->preference("kohaspsuggest"));
562 my $koha_spsuggest_dbh;
564 # FIXME: this needs to be moved to Context.pm
566 $koha_spsuggest_dbh=DBI->connect("DBI:mysql:$suggest_dbname:$suggest_host","$suggest_user","$suggest_pwd");
569 warn "can't connect to spsuggest db";
572 my $koha_spsuggest_insert =
573 "INSERT INTO phrase_log(phr_phrase,phr_resultcount,phr_ip) VALUES(?,?,?)";
574 my $koha_spsuggest_query =
575 "SELECT display FROM distincts WHERE strcmp(soundex(suggestion), soundex(?)) = 0 order by soundex(suggestion) limit 0,5";
576 my $koha_spsuggest_sth =
577 $koha_spsuggest_dbh->prepare($koha_spsuggest_query);
578 $koha_spsuggest_sth->execute($phrases);
579 while ( my $spsuggestion = $koha_spsuggest_sth->fetchrow_array ) {
580 $spsuggestion =~ s/(:|\/)//g;
582 $line{spsuggestion} = $spsuggestion;
583 push @koha_spsuggest, \%line;
587 # Now save the current query
588 $koha_spsuggest_sth =
589 $koha_spsuggest_dbh->prepare($koha_spsuggest_insert);
591 #$koha_spsuggest_sth->execute($phrases,$results_per_page,$ipaddress);
592 $koha_spsuggest_sth->finish;
593 $template->param( koha_spsuggest => $koha_spsuggest ) unless $hits;
594 $template->param( SPELL_SUGGEST => \@koha_spsuggest, );
598 warn "Kohaspsuggest failure:" . $@;
602 # VI. BUILD THE TEMPLATE
603 output_html_with_http_headers $cgi, $cookie, $template->output;