Updating updatedatabase and kohaversion.pl for new reports tables
[koha.git] / catalogue / search.pl
1 #!/usr/bin/perl
2 # Script to perform searching
3 # For documentation try 'perldoc /path/to/search'
4 #
5 # $Header$
6 #
7 # Copyright 2006 LibLime
8 #
9 # This file is part of Koha
10 #
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
14 # version.
15 #
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.
19 #
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
23
24 =head1 NAME
25
26 search - a search script for finding records in a Koha system (Version 2.4)
27
28 =head1 OVERVIEW
29
30 This script contains a demonstration of a new search API for Koha 2.4. It is
31 designed to be simple to use and configure, yet capable of performing feats
32 like stemming, field weighting, relevance ranking, support for multiple 
33 query language 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
36 targets, etc.
37
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 :-)
41
42 I will attempt to describe what is happening at each part of this script.
43 -- JF
44
45 =head2 INTRO
46
47 This script performs two functions:
48
49 =over 
50
51 =item 1. interacts with Koha to retrieve and display the results of a search
52
53 =item 2. loads the advanced search page
54
55 =back
56
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
60 for that function.
61
62 =head2 THE ADVANCED SEARCH PAGE
63
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:
68
69 =over
70
71 =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)
72
73 =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).
74
75 =back
76
77 However, they create one problem : the strings aren't translated. I have an idea
78 for how to do this that I will purusue soon.
79
80 =head2 PERFORMING A SEARCH
81
82 If we're performing a search, this script  performs three primary
83 operations:
84
85 =over 
86
87 =item 1. builds query strings (yes, plural)
88
89 =item 2. perform the search and return the results array
90
91 =item 3. build the HTML for output to the template
92
93 =back
94
95 There are several additional secondary functions performed that I will
96 not cover in detail.
97
98 =head3 1. Building Query Strings
99     
100 There are several types of queries needed in the process of search and retrieve:
101
102 =over
103
104 =item 1 Koha query - the query that is passed to Zebra
105
106 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.
107
108 This query incorporates query profiles that aren't compatible with non-Zebra Z39.50 targets to acomplish the field weighting and relevance ranking.
109
110 =item 2 Federated query - the query that is passed to other Z39.50 targets
111
112 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).
113
114 =item 3 Search description - passed to the template / saved for future refinements of the query (by user)
115
116 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:
117
118 1. it does not contain commas or = signs
119 2. 
120
121 =item 4 Human search description - what the user sees in the search_desc area
122
123 This is a simple string nearly identical to the Search description, but more human readable. It will contain = signs or commas, etc.
124
125 =back
126
127 =head3 2. Perform the Search
128
129 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.
130
131 =head3 3. Build HTML
132
133 The final major section of this script takes the objects collected thusfar and builds the HTML for output to the template and user.
134
135 =head3 Additional Notes
136
137 Not yet completed...
138
139 =cut
140
141 use strict;            # always use
142
143 ## STEP 1. Load things that are used in both search page and
144 # results page and decide which template to load, operations 
145 # to perform, etc.
146 ## load Koha modules
147 use C4::Context;
148 use C4::Output;
149 use C4::Auth;
150 use C4::Search;
151 use C4::Languages; # getAllLanguages
152 use C4::Koha;
153 use POSIX qw(ceil floor);
154 use C4::Branch; # GetBranches
155 # create a new CGI object
156 # not sure undef_params option is working, need to test
157 use CGI qw('-no_undef_params');
158 my $cgi = new CGI;
159
160 my ($template,$borrowernumber,$cookie);
161
162 # decide which template to use
163 my $template_name;
164 my @params = $cgi->param("limit");
165 if ((@params>=1) || ($cgi->param("q")) || ($cgi->param('multibranchlimit')) ) {
166     $template_name = 'catalogue/results.tmpl';
167 }
168 else {
169     $template_name = 'catalogue/advsearch.tmpl';
170 }
171 # load the template
172 ($template, $borrowernumber, $cookie) = get_template_and_user({
173     template_name => $template_name,
174     query => $cgi,
175     type => "intranet",
176     authnotrequired => 0,
177     flagsrequired   => { catalogue => 1 },
178     }
179 );
180
181 =head1 BUGS and FIXMEs
182
183 There are many, most are documented in the code. The one that
184 isn't fully documented, but referred to is the need for a full
185 query parser.
186
187 =cut
188
189 ## URI Re-Writing
190 # FIXME: URI re-writing should be tested more carefully and may better
191 # handled by mod_rewrite or something else. The code below almost works,
192 # but doesn't quite handle limits correctly when they are the only
193 # param passed -- I'll work on this soon -- JF
194 #my $rewrite_flag;
195 #my $uri = $cgi->url(-base => 1);
196 #my $relative_url = $cgi->url(-relative=>1);
197 #$uri.="/".$relative_url."?";
198 #warn "URI:$uri";
199 #my @cgi_params_list = $cgi->param();
200 #my $url_params = $cgi->Vars;
201
202 #for my $each_param_set (@cgi_params_list) {
203 #    $uri.= join "",  map "\&$each_param_set=".$_, split("\0",$url_params->{$each_param_set}) if $url_params->{$each_param_set};
204 #}
205 #warn "New URI:$uri";
206 # Only re-write a URI if there are params or if it already hasn't been re-written
207 #unless (($cgi->param('r')) || (!$cgi->param()) ) {
208 #    print $cgi->redirect(     -uri=>$uri."&r=1",
209 #                            -cookie => $cookie);
210 #    exit;
211 #}
212
213 # load the branches
214 my $branches = GetBranches();
215 my @branch_loop;
216 #push @branch_loop, {value => "", branchname => "All Branches", };
217 for my $branch_hash (sort keys %$branches) {
218     push @branch_loop, {value => "branch:$branch_hash" , branchname => $branches->{$branch_hash}->{'branchname'}, };
219 }
220
221 my $categories = GetBranchCategories(undef,'searchdomain');
222
223 $template->param(branchloop => \@branch_loop, searchdomainloop => $categories);
224
225 # load the itemtypes (Called Collection Codes in the template -- used for circ rules )
226 my $itemtypes = GetItemTypes;
227 my @itemtypesloop;
228 my $selected=1;
229 my $cnt;
230 my $imgdir = getitemtypeimagesrc();
231 foreach my $thisitemtype ( sort {$itemtypes->{$a}->{'description'} cmp $itemtypes->{$b}->{'description'} } keys %$itemtypes ) {
232     my %row =(  number=>$cnt++,
233                 imageurl=> $itemtypes->{$thisitemtype}->{'imageurl'}?($imgdir."/".$itemtypes->{$thisitemtype}->{'imageurl'}):"",
234                 code => $thisitemtype,
235                 selected => $selected,
236                 description => $itemtypes->{$thisitemtype}->{'description'},
237                 count5 => $cnt % 4,
238             );
239     $selected = 0 if ($selected) ;
240     push @itemtypesloop, \%row;
241 }
242 $template->param(itemtypeloop => \@itemtypesloop);
243
244 # # load the itypes (Called item types in the template -- just authorized values for searching)
245 # my ($itypecount,@itype_loop) = GetCcodes();
246 # $template->param(itypeloop=>\@itype_loop,);
247
248 # load the languages ( for switching from one template to another )
249 # my @languages_options = displayLanguages($cgi);
250 # my $languages_count = @languages_options;
251 # if($languages_count > 1){
252 #         $template->param(languages => \@languages_options);
253 # }
254
255 # The following should only be loaded if we're bringing up the advanced search template
256 if ( $template_name eq "catalogue/advsearch.tmpl" ) {
257     # load the servers (used for searching -- to do federated searching, etc.)
258     my $primary_servers_loop;# = displayPrimaryServers();
259     $template->param(outer_servers_loop =>  $primary_servers_loop,);
260     
261     my $secondary_servers_loop;# = displaySecondaryServers();
262     $template->param(outer_sup_servers_loop => $secondary_servers_loop,);
263     
264     # determine what to display next to the search boxes (ie, boolean option
265     # shouldn't appear on the first one, scan indexes should, adding a new
266     # box should only appear on the last, etc.
267     # FIXME: this stuff should be cleaned up a bit and the html should be turned
268     # into flags for the template -- I'll work on that soon -- JF
269     my @search_boxes_array;
270     my $search_boxes_count = 1; # should be a syspref
271     for (my $i=0;$i<=$search_boxes_count;$i++) {
272         if ($i==0) {
273             push @search_boxes_array,
274                 {
275                 search_boxes_label => 1,
276                 scan_index => 1,
277                 };
278         
279         }
280         elsif ($i==$search_boxes_count) {
281             push @search_boxes_array,
282                 {
283                 add_field => "1",};
284         }
285
286     }
287     $template->param(uc(C4::Context->preference("marcflavour")) => 1,
288                       search_boxes_loop => \@search_boxes_array);
289
290     # load the language limits (for search)
291     my $languages_limit_loop = getAllLanguages();
292     $template->param(search_languages_loop => $languages_limit_loop,);
293     
294     my $expanded_options;
295     if (not defined $cgi->param('expanded_options')){
296         $expanded_options = C4::Context->preference("expandedSearchOption");
297     }
298     else {
299         $expanded_options = $cgi->param('expanded_options');
300     }
301     $template->param(expanded_options => $expanded_options);
302
303     # load the sort_by options for the template
304     my $sort_by = $cgi->param('sort_by');
305
306     output_html_with_http_headers $cgi, $cookie, $template->output;
307     exit;
308 }
309
310 ### OK, if we're this far, we're performing an actual search
311
312 # Fetch the paramater list as a hash in scalar context:
313 #  * returns paramater list as tied hash ref
314 #  * we can edit the values by changing the key
315 #  * multivalued CGI paramaters are returned as a packaged string separated by "\0" (null)
316 my $params = $cgi->Vars;
317
318 # Params that can have more than one value
319 # sort by is used to sort the query
320 my @sort_by;
321 @sort_by = split("\0",$params->{'sort_by'}) if $params->{'sort_by'};
322 #
323 # Use the servers defined, or just search our local catalog(default)
324 my @servers;
325 @servers = split("\0",$params->{'server'}) if $params->{'server'};
326 unless (@servers) {
327     #FIXME: this should be handled using Context.pm
328     @servers = ("biblioserver");
329     # @servers = C4::Context->config("biblioserver");
330 }
331
332 # operators include boolean and proximity operators and are used
333 # to evaluate multiple operands
334 my @operators;
335 @operators = split("\0",$params->{'op'}) if $params->{'op'};
336
337 # indexes are query qualifiers, like 'title', 'author', etc. They
338 # can be simple or complex
339 my @indexes;
340 if ($params->{'idx'}) {
341     @indexes = split("\0",$params->{'idx'});
342 } else {
343     $indexes[0] = 'kw,wrdl';
344 }
345
346 # an operand can be a single term, a phrase, or a complete ccl query
347 my @operands;
348 @operands = split("\0",$params->{'q'}) if $params->{'q'};
349
350 # limits are use to limit to results to a pre-defined category such as branch or language
351 my @limits;
352 @limits = split("\0",$params->{'limit'}) if $params->{'limit'};
353
354 if($params->{'multibranchlimit'}) {
355 push @limits, join(" or ", map { "branch: $_ "}  @{GetBranchesInCategory($params->{'multibranchlimit'})}) ;
356 }
357
358 my $available;
359 foreach my $limit(@limits) {
360     if ($limit =~/available/) {
361         $available = 1;
362     }
363 }
364 $template->param(available => $available);
365 push @limits, map "yr:".$_, split("\0",$params->{'limit-yr'}) if $params->{'limit-yr'};
366
367 # Params that can only have one value
368 my $query = $params->{'q'};
369 my $scan = $params->{'scan'};
370 my $results_per_page = $params->{'count'} || 20;
371 my $page = $cgi->param('page') || 1;
372 my $offset = ($page-1)*$results_per_page;
373 my $hits;
374 my $expanded_facet = $params->{'expand'};
375
376 # Define some global variables
377 my $error; # used for error handling
378 my $search_desc; # the query expressed in terms that humans understand
379 my $koha_query; # the query expressed in terms that zoom understands with field weighting and stemming
380 my $federated_query;
381 my $query_type; # usually not needed, but can be used to trigger ccl, cql, or pqf queries if set
382 my @results;
383 ## I. BUILD THE QUERY
384 ($error,$search_desc,$koha_query,$federated_query,$query_type) = buildQuery($query,\@operators,\@operands,\@indexes,\@limits);
385
386 ## II. DO THE SEARCH AND GET THE RESULTS
387 my $total; # the total results for the whole set
388 my $facets; # this object stores the faceted results that display on the left-hand of the results page
389 my @results_array;
390 my $results_hashref;
391
392 if (C4::Context->preference('NoZebra')) {
393     eval {
394         ($error, $results_hashref, $facets) = NZgetRecords($koha_query,$federated_query,\@sort_by,\@servers,$results_per_page,$offset,$expanded_facet,$branches,$query_type,$scan);
395     };
396 } else {
397     eval {
398         ($error, $results_hashref, $facets) = getRecords($koha_query,$federated_query,\@sort_by,\@servers,$results_per_page,$offset,$expanded_facet,$branches,$query_type,$scan);
399     };
400 }
401 if ($@ || $error) {
402     $template->param(query_error => $error.$@);
403
404     output_html_with_http_headers $cgi, $cookie, $template->output;
405     exit;
406 }
407 my $op=$cgi->param("operation");
408 if ($op eq "bulkedit"){
409         my ($countchanged,$listunchanged)=
410           ModBiblios($results_hashref->{'biblioserver'}->{"RECORDS"},
411                       $params->{"tagsubfield"},
412                       $params->{"inputvalue"},
413                       $params->{"targetvalue"},
414                       $params->{"test"}
415                       );
416         $template->param(bulkeditresults=>1,
417                       tagsubfield=>$params->{"tagsubfield"},
418                       inputvalue=>$params->{"inputvalue"},
419                       targetvalue=>$params->{"targetvalue"},
420                       countchanged=>$countchanged,
421                       countunchanged=>scalar(@$listunchanged),
422                       listunchanged=>$listunchanged);
423 }
424
425 if (C4::Context->userenv->{'flags'}==1 ||(C4::Context->userenv->{'flags'} & ( 2**9 ) )){
426 #Edit Catalogue Permissions
427   $template->param(bulkedit => 1);
428   $template->param(tagsubfields=>GetManagedTagSubfields());
429 }
430 # At this point, each server has given us a result set
431 # now we build that set for template display
432 my @sup_results_array;
433 for (my $i=0;$i<=@servers;$i++) {
434     my $server = $servers[$i];
435     if ($server =~/biblioserver/) { # this is the local bibliographic server
436         $hits = $results_hashref->{$server}->{"hits"};
437         my $page = $cgi->param('page') || 0;
438         my @newresults = searchResults( $search_desc,$hits,$results_per_page,$offset,@{$results_hashref->{$server}->{"RECORDS"}});
439         $total = $total + $results_hashref->{$server}->{"hits"};
440         if ($hits) {
441             $template->param(total => $hits);
442             $template->param(searchdesc => ($query_type?"$query_type=":"")."$search_desc" );
443             $template->param(results_per_page =>  $results_per_page);
444             $template->param(SEARCH_RESULTS => \@newresults);
445
446 #             my @page_numbers;
447 #             my $pages = ceil($hits / $results_per_page);
448 #             my $previous_page_offset = $offset - $results_per_page unless ($offset - $results_per_page <0);
449 #             my $next_page_offset = $offset + $results_per_page;
450 #             for (my $j=1; $j<=$pages;$j++) {
451 #                 my $this_offset = (($j*$results_per_page)-$results_per_page);
452 #                 my $this_page_number = $j;
453 #                 my $highlight = 1 if ($this_page_number == $current_page_number);
454 #                 if ($this_page_number <= $pages) {
455 #                 push @page_numbers, { offset => $this_offset, pg => $this_page_number, highlight => $highlight, sort_by => join " ",@sort_by };
456 #                 }
457 #             }
458 #             $template->param(PAGE_NUMBERS => \@page_numbers,
459 #                             previous_page_offset => $previous_page_offset,
460 #                             next_page_offset => $next_page_offset) unless $pages < 2;
461       my $link="/cgi-bin/koha/catalogue/search.pl?q=$search_desc&";
462       foreach my $sort (@sort_by){      
463         $link.="&sort_by=".$sort."&";
464       }        
465                         $template->param(
466                                 pagination_bar => pagination_bar(
467                         $link,
468                         getnbpages($hits, $results_per_page),
469                         $page,
470                         'page'
471                                 ),
472                         );
473          }
474     } # end of the if local
475     else {
476         # check if it's a z3950 or opensearch source
477         my $zed3950 = 0;  # FIXME :: Hardcoded value.
478         if ($zed3950) {
479             my @inner_sup_results_array;
480             for my $sup_record ( @{$results_hashref->{$server}->{"RECORDS"}} ) {
481                 my $marc_record_object = MARC::Record->new_from_usmarc($sup_record);
482                 my $control_number = $marc_record_object->field('010')->subfield('a') if $marc_record_object->field('010');
483                 $control_number =~ s/^ //g;
484                 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";
485                 my $title = $marc_record_object->title();
486                 push @inner_sup_results_array, {
487                     'title' => $title,
488                     'link' => $link,
489                 };
490             }
491             my $servername = $server;
492             push @sup_results_array, { servername => $servername, inner_sup_results_loop => \@inner_sup_results_array};
493             $template->param(outer_sup_results_loop => \@sup_results_array);
494         }
495     }
496
497 } #/end of the for loop
498 #$template->param(FEDERATED_RESULTS => \@results_array);
499
500
501 $template->param(
502             #classlist => $classlist,
503             total => $total,
504             searchdesc => ($query_type?"$query_type=":"")."$search_desc",
505             opacfacets => 1,
506             facets_loop => $facets,
507             scan_use => $scan,
508             search_error => $error,
509 );
510 ## Now let's find out if we have any supplemental data to show the user
511 #  and in the meantime, save the current query for statistical purposes, etc.
512 my $koha_spsuggest; # a flag to tell if we've got suggestions coming from Koha
513 my @koha_spsuggest; # place we store the suggestions to be returned to the template as LOOP
514 my $phrases = $search_desc;
515 my $ipaddress;
516
517 if ( C4::Context->preference("kohaspsuggest") ) {
518                 my ($suggest_host, $suggest_dbname, $suggest_user, $suggest_pwd) = split(':', C4::Context->preference("kohaspsuggest"));
519         eval {
520             my $koha_spsuggest_dbh;
521             # FIXME: this needs to be moved to Context.pm
522             eval {
523                 $koha_spsuggest_dbh=DBI->connect("DBI:mysql:$suggest_dbname:$suggest_host","$suggest_user","$suggest_pwd");
524             };
525             if ($@) { 
526                 warn "can't connect to spsuggest db";
527             }
528             else {
529                 my $koha_spsuggest_insert = "INSERT INTO phrase_log(phr_phrase,phr_resultcount,phr_ip) VALUES(?,?,?)";
530                 my $koha_spsuggest_query = "SELECT display FROM distincts WHERE strcmp(soundex(suggestion), soundex(?)) = 0 order by soundex(suggestion) limit 0,5";
531                 my $koha_spsuggest_sth = $koha_spsuggest_dbh->prepare($koha_spsuggest_query);
532                 $koha_spsuggest_sth->execute($phrases);
533                 while (my $spsuggestion = $koha_spsuggest_sth->fetchrow_array) {
534                     $spsuggestion =~ s/(:|\/)//g;
535                     my %line;
536                     $line{spsuggestion} = $spsuggestion;
537                     push @koha_spsuggest,\%line;
538                     $koha_spsuggest = 1;
539                 }
540
541                 # Now save the current query
542                 $koha_spsuggest_sth=$koha_spsuggest_dbh->prepare($koha_spsuggest_insert);
543                 #$koha_spsuggest_sth->execute($phrases,$results_per_page,$ipaddress);
544                 $koha_spsuggest_sth->finish;
545
546                 $template->param( koha_spsuggest => $koha_spsuggest ) unless $hits;
547                 $template->param( SPELL_SUGGEST => \@koha_spsuggest,
548                 );
549             }
550     };
551     if ($@) {
552             warn "Kohaspsuggest failure:".$@;
553     }
554 }
555
556 # VI. BUILD THE TEMPLATE
557 output_html_with_http_headers $cgi, $cookie, $template->output;