switching from searchdesc to query_desc and limit_desc,
[koha.git] / C4 / Search.pm
1 package C4::Search;
2
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it under the
6 # terms of the GNU General Public License as published by the Free Software
7 # Foundation; either version 2 of the License, or (at your option) any later
8 # version.
9 #
10 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
11 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License along with
15 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
16 # Suite 330, Boston, MA  02111-1307 USA
17
18 use strict;
19 require Exporter;
20 use C4::Context;
21 use C4::Biblio;    # GetMarcFromKohaField
22 use C4::Koha;      # getFacets
23 use Lingua::Stem;
24 use C4::Date;
25
26 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
27
28 # set the version for version checking
29 $VERSION = 3.00;
30 $DEBUG=1;
31
32 =head1 NAME
33
34 C4::Search - Functions for searching the Koha catalog.
35
36 =head1 SYNOPSIS
37
38 see opac/opac-search.pl or catalogue/search.pl for example of usage
39
40 =head1 DESCRIPTION
41
42 This module provides the searching facilities for the Koha into a zebra catalog.
43
44 =head1 FUNCTIONS
45
46 =cut
47
48 @ISA    = qw(Exporter);
49 @EXPORT = qw(
50   &SimpleSearch
51   &findseealso
52   &FindDuplicate
53   &searchResults
54   &getRecords
55   &buildQuery
56   &NZgetRecords
57   &ModBiblios
58 );
59
60 # make all your functions, whether exported or not;
61
62 =head2 findseealso($dbh,$fields);
63
64 C<$dbh> is a link to the DB handler.
65
66 use C4::Context;
67 my $dbh =C4::Context->dbh;
68
69 C<$fields> is a reference to the fields array
70
71 This function modify the @$fields array and add related fields to search on.
72
73 =cut
74
75 sub findseealso {
76     my ( $dbh, $fields ) = @_;
77     my $tagslib = GetMarcStructure( 1 );
78     for ( my $i = 0 ; $i <= $#{$fields} ; $i++ ) {
79         my ($tag)      = substr( @$fields[$i], 1, 3 );
80         my ($subfield) = substr( @$fields[$i], 4, 1 );
81         @$fields[$i] .= ',' . $tagslib->{$tag}->{$subfield}->{seealso}
82           if ( $tagslib->{$tag}->{$subfield}->{seealso} );
83     }
84 }
85
86 =head2 FindDuplicate
87
88 ($biblionumber,$biblionumber,$title) = FindDuplicate($record);
89
90 =cut
91
92 sub FindDuplicate {
93     my ($record) = @_;
94     my $dbh = C4::Context->dbh;
95     my $result = TransformMarcToKoha( $dbh, $record, '' );
96     my $sth;
97     my $query;
98     my $search;
99     my $type;
100     my ( $biblionumber, $title );
101
102     # search duplicate on ISBN, easy and fast..
103     # ... normalize first
104     if ( $result->{isbn} ) {
105         $result->{isbn} =~ s/\(.*$//;
106         $result->{isbn} =~ s/\s+$//; 
107     }
108     #$search->{'avoidquerylog'}=1;
109     if ( $result->{isbn} ) {
110         $query = "isbn=$result->{isbn}";
111     }
112     else {
113         $result->{title} =~ s /\\//g;
114         $result->{title} =~ s /\"//g;
115         $result->{title} =~ s /\(//g;
116         $result->{title} =~ s /\)//g;
117         # remove valid operators
118         $result->{title} =~ s/(and|or|not)//g;
119         $query = "ti,ext=$result->{title}";
120         $query .= " and mt=$result->{itemtype}" if ($result->{itemtype});    
121         if ($result->{author}){
122           $result->{author} =~ s /\\//g;
123           $result->{author} =~ s /\"//g;
124           $result->{author} =~ s /\(//g;
125           $result->{author} =~ s /\)//g;
126           # remove valid operators
127           $result->{author} =~ s/(and|or|not)//g;
128           $query .= " and au,ext=$result->{author}";
129         }     
130     }
131     my ($error,$searchresults) =
132       SimpleSearch($query); # FIXME :: hardcoded !
133     my @results;
134     foreach my $possible_duplicate_record (@$searchresults) {
135         my $marcrecord =
136           MARC::Record->new_from_usmarc($possible_duplicate_record);
137         my $result = TransformMarcToKoha( $dbh, $marcrecord, '' );
138         
139         # FIXME :: why 2 $biblionumber ?
140         if ($result){
141           push @results, $result->{'biblionumber'};
142           push @results, $result->{'title'};
143         }
144     }
145     return @results;  
146 }
147
148 =head2 SimpleSearch
149
150 ($error,$results) = SimpleSearch($query,@servers);
151
152 this function performs a simple search on the catalog using zoom.
153
154 =over 2
155
156 =item C<input arg:>
157
158     * $query could be a simple keyword or a complete CCL query wich is depending on your ccl file.
159     * @servers is optionnal. default one is read on koha.xml
160
161 =item C<Output arg:>
162     * $error is a string which containt the description error if there is one. Else it's empty.
163     * \@results is an array of marc record.
164
165 =item C<usage in the script:>
166
167 =back
168
169 my ($error, $marcresults) = SimpleSearch($query);
170
171 if (defined $error) {
172     $template->param(query_error => $error);
173     warn "error: ".$error;
174     output_html_with_http_headers $input, $cookie, $template->output;
175     exit;
176 }
177
178 my $hits = scalar @$marcresults;
179 my @results;
180
181 for(my $i=0;$i<$hits;$i++) {
182     my %resultsloop;
183     my $marcrecord = MARC::File::USMARC::decode($marcresults->[$i]);
184     my $biblio = TransformMarcToKoha(C4::Context->dbh,$marcrecord,'');
185
186     #build the hash for the template.
187     $resultsloop{highlight}       = ($i % 2)?(1):(0);
188     $resultsloop{title}           = $biblio->{'title'};
189     $resultsloop{subtitle}        = $biblio->{'subtitle'};
190     $resultsloop{biblionumber}    = $biblio->{'biblionumber'};
191     $resultsloop{author}          = $biblio->{'author'};
192     $resultsloop{publishercode}   = $biblio->{'publishercode'};
193     $resultsloop{publicationyear} = $biblio->{'publicationyear'};
194
195     push @results, \%resultsloop;
196 }
197 $template->param(result=>\@results);
198
199 =cut
200
201 sub SimpleSearch {
202     my $query   = shift;
203     if (C4::Context->preference('NoZebra')) {
204         my $result = NZorder(NZanalyse($query))->{'biblioserver'}->{'RECORDS'};
205         return (undef,$result);
206     } else {
207         my @servers = @_;
208         my @results;
209         my @tmpresults;
210         my @zconns;
211         return ( "No query entered", undef ) unless $query;
212     
213         #@servers = (C4::Context->config("biblioserver")) unless @servers;
214         @servers =
215         ("biblioserver") unless @servers
216         ;    # FIXME hardcoded value. See catalog/search.pl & opac-search.pl too.
217     
218         # Connect & Search
219         for ( my $i = 0 ; $i < @servers ; $i++ ) {
220             $zconns[$i] = C4::Context->Zconn( $servers[$i], 1 );
221             $tmpresults[$i] =
222             $zconns[$i]
223             ->search( new ZOOM::Query::CCL2RPN( $query, $zconns[$i] ) );
224     
225             # getting error message if one occured.
226             my $error =
227                 $zconns[$i]->errmsg() . " ("
228             . $zconns[$i]->errcode() . ") "
229             . $zconns[$i]->addinfo() . " "
230             . $zconns[$i]->diagset();
231     
232             return ( $error, undef ) if $zconns[$i]->errcode();
233         }
234         my $hits;
235         my $ev;
236         while ( ( my $i = ZOOM::event( \@zconns ) ) != 0 ) {
237             $ev = $zconns[ $i - 1 ]->last_event();
238             if ( $ev == ZOOM::Event::ZEND ) {
239                 $hits = $tmpresults[ $i - 1 ]->size();
240             }
241             if ( $hits > 0 ) {
242                 for ( my $j = 0 ; $j < $hits ; $j++ ) {
243                     my $record = $tmpresults[ $i - 1 ]->record($j)->raw();
244                     push @results, $record;
245                 }
246             }
247         }
248         return ( undef, \@results );
249     }
250 }
251
252 # performs the search
253 sub getRecords {
254     my (
255         $koha_query,     $simple_query,  $sort_by_ref,
256         $servers_ref,    $results_per_page, $offset,
257         $expanded_facet, $branches,         $query_type,
258         $scan
259     ) = @_;
260 #     warn "Query : $koha_query";
261     my @servers = @$servers_ref;
262     my @sort_by = @$sort_by_ref;
263
264     # create the zoom connection and query object
265     my $zconn;
266     my @zconns;
267     my @results;
268     my $results_hashref = ();
269
270     ### FACETED RESULTS
271     my $facets_counter = ();
272     my $facets_info    = ();
273     my $facets         = getFacets();
274
275     #### INITIALIZE SOME VARS USED CREATE THE FACETED RESULTS
276     my @facets_loop;    # stores the ref to array of hashes for template
277     for ( my $i = 0 ; $i < @servers ; $i++ ) {
278         $zconns[$i] = C4::Context->Zconn( $servers[$i], 1 );
279
280 # perform the search, create the results objects
281 # if this is a local search, use the $koha-query, if it's a federated one, use the federated-query
282         my $query_to_use;
283         if ( $servers[$i] =~ /biblioserver/ ) {
284             $query_to_use = $koha_query;
285         }
286         else {
287             $query_to_use = $simple_query;
288         }
289
290                 $query_to_use = $simple_query if $scan;
291
292         # check if we've got a query_type defined
293         eval {
294             if ($query_type)
295             {
296                 if ( $query_type =~ /^ccl/ ) {
297                     $query_to_use =~
298                       s/\:/\=/g;    # change : to = last minute (FIXME)
299
300                     #                 warn "CCL : $query_to_use";
301                     $results[$i] =
302                       $zconns[$i]->search(
303                         new ZOOM::Query::CCL2RPN( $query_to_use, $zconns[$i] )
304                       );
305                 }
306                 elsif ( $query_type =~ /^cql/ ) {
307
308                     #                 warn "CQL : $query_to_use";
309                     $results[$i] =
310                       $zconns[$i]->search(
311                         new ZOOM::Query::CQL( $query_to_use, $zconns[$i] ) );
312                 }
313                 elsif ( $query_type =~ /^pqf/ ) {
314
315                     #                 warn "PQF : $query_to_use";
316                     $results[$i] =
317                       $zconns[$i]->search(
318                         new ZOOM::Query::PQF( $query_to_use, $zconns[$i] ) );
319                 }
320             }
321             else {
322                 if ($scan) {
323                                      warn "preparing to scan:$query_to_use";
324                     $results[$i] =
325                       $zconns[$i]->scan(
326                         new ZOOM::Query::CCL2RPN( $query_to_use, $zconns[$i] )
327                       );
328                 }
329                 else {
330                     #             warn "LAST : $query_to_use";
331                     $results[$i] =
332                       $zconns[$i]->search(
333                         new ZOOM::Query::CCL2RPN( $query_to_use, $zconns[$i] )
334                       );
335                 }
336             }
337         };
338         if ($@) {
339             warn "WARNING: query problem with $query_to_use " . $@;
340         }
341
342         # concatenate the sort_by limits and pass them to the results object
343         my $sort_by;
344         foreach my $sort (@sort_by) {
345             if ($sort eq "author_az") {
346                 $sort_by.="1=1003 <i ";
347             }
348             elsif ($sort eq "author_za") {
349                 $sort_by.="1=1003 >i ";
350             }
351             elsif ($sort eq "popularity_asc") {
352                 $sort_by.="1=9003 <i ";
353             }
354             elsif ($sort eq "popularity_dsc") {
355                 $sort_by.="1=9003 >i ";
356             }
357             elsif ($sort eq "call_number_asc") {
358                 $sort_by.="1=20  <i ";
359             }
360             elsif ($sort eq "call_number_dsc") {
361                 $sort_by.="1=20 >i ";
362             }
363             elsif ($sort eq "pubdate_asc") {
364                 $sort_by.="1=31 <i ";
365             }
366             elsif ($sort eq "pubdate_dsc") {
367                 $sort_by.="1=31 >i ";
368             }
369             elsif ($sort eq "acqdate_asc") {
370                 $sort_by.="1=32 <i ";
371             }
372             elsif ($sort eq "acqdate_dsc") {
373                 $sort_by.="1=32 >i ";
374             }
375             elsif ($sort eq "title_az") {
376                 $sort_by.="1=4 <i ";
377             }
378             elsif ($sort eq "title_za") {
379                 $sort_by.="1=4 >i ";
380             }
381         }
382         if ($sort_by) {
383             if ( $results[$i]->sort( "yaz", $sort_by ) < 0) {
384                 warn "WARNING sort $sort_by failed";
385             }
386         }
387     }
388     while ( ( my $i = ZOOM::event( \@zconns ) ) != 0 ) {
389         my $ev = $zconns[ $i - 1 ]->last_event();
390         if ( $ev == ZOOM::Event::ZEND ) {
391             my $size = $results[ $i - 1 ]->size();
392             if ( $size > 0 ) {
393                 my $results_hash;
394                 #$results_hash->{'server'} = $servers[$i-1];
395                 # loop through the results
396                 $results_hash->{'hits'} = $size;
397                 my $times;
398                 if ( $offset + $results_per_page <= $size ) {
399                     $times = $offset + $results_per_page;
400                 }
401                 else {
402                     $times = $size;
403                 }
404                 for ( my $j = $offset ; $j < $times ; $j++ )
405                 {   #(($offset+$count<=$size) ? ($offset+$count):$size) ; $j++){
406                     my $records_hash;
407                     my $record;
408                     my $facet_record;
409                     ## This is just an index scan
410                     if ($scan) {
411                         my ( $term, $occ ) = $results[ $i - 1 ]->term($j);
412                  # here we create a minimal MARC record and hand it off to the
413                  # template just like a normal result ... perhaps not ideal, but
414                  # it works for now
415                         my $tmprecord = MARC::Record->new();
416                         $tmprecord->encoding('UTF-8');
417                         my $tmptitle;
418
419                         # srote the minimal record in author/title (depending on MARC flavour)
420                         if ( C4::Context->preference("marcflavour") eq
421                             "UNIMARC" )
422                         {
423                             $tmptitle = MARC::Field->new(
424                                 '200', ' ', ' ',
425                                 a => $term,
426                                 f => $occ
427                             );
428                         }
429                         else {
430                             $tmptitle = MARC::Field->new(
431                                 '245', ' ', ' ',
432                                 a => $term,
433                                 b => $occ
434                             );
435                         }
436                         $tmprecord->append_fields($tmptitle);
437                         $results_hash->{'RECORDS'}[$j] =
438                           $tmprecord->as_usmarc();
439                     }
440                     else {
441                         $record = $results[ $i - 1 ]->record($j)->raw();
442
443                         #warn "RECORD $j:".$record;
444                         $results_hash->{'RECORDS'}[$j] =
445                           $record;    # making a reference to a hash
446                                       # Fill the facets while we're looping
447                         $facet_record = MARC::Record->new_from_usmarc($record);
448
449                         #warn $servers[$i-1].$facet_record->title();
450                         for ( my $k = 0 ; $k <= @$facets ; $k++ ) {
451                             if ( $facets->[$k] ) {
452                                 my @fields;
453                                 for my $tag ( @{ $facets->[$k]->{'tags'} } ) {
454                                     push @fields, $facet_record->field($tag);
455                                 }
456                                 for my $field (@fields) {
457                                     my @subfields = $field->subfields();
458                                     for my $subfield (@subfields) {
459                                         my ( $code, $data ) = @$subfield;
460                                         if ( $code eq
461                                             $facets->[$k]->{'subfield'} )
462                                         {
463                                             $facets_counter->{ $facets->[$k]
464                                                   ->{'link_value'} }->{$data}++;
465                                         }
466                                     }
467                                 }
468                                 $facets_info->{ $facets->[$k]->{'link_value'} }
469                                   ->{'label_value'} =
470                                   $facets->[$k]->{'label_value'};
471                                 $facets_info->{ $facets->[$k]->{'link_value'} }
472                                   ->{'expanded'} = $facets->[$k]->{'expanded'};
473                             }
474                         }
475                     }
476                 }
477                 $results_hashref->{ $servers[ $i - 1 ] } = $results_hash;
478             }
479
480             #print "connection ", $i-1, ": $size hits";
481             #print $results[$i-1]->record(0)->render() if $size > 0;
482             # BUILD FACETS
483             for my $link_value (
484                 sort { $facets_counter->{$b} <=> $facets_counter->{$a} }
485                 keys %$facets_counter
486               )
487             {
488                 my $expandable;
489                 my $number_of_facets;
490                 my @this_facets_array;
491                 for my $one_facet (
492                     sort {
493                         $facets_counter->{$link_value}
494                           ->{$b} <=> $facets_counter->{$link_value}->{$a}
495                     } keys %{ $facets_counter->{$link_value} }
496                   )
497                 {
498                     $number_of_facets++;
499                     if (   ( $number_of_facets < 6 )
500                         || ( $expanded_facet eq $link_value )
501                         || ( $facets_info->{$link_value}->{'expanded'} ) )
502                     {
503
504                        # sanitize the link value ), ( will cause errors with CCL
505                         my $facet_link_value = $one_facet;
506                         $facet_link_value =~ s/(\(|\))/ /g;
507
508                         # fix the length that will display in the label
509                         my $facet_label_value = $one_facet;
510                         $facet_label_value = substr( $one_facet, 0, 20 ) . "..."
511                           unless length($facet_label_value) <= 20;
512
513                        # well, if it's a branch, label by the name, not the code
514                         if ( $link_value =~ /branch/ ) {
515                             $facet_label_value =
516                               $branches->{$one_facet}->{'branchname'};
517                         }
518
519                  # but we're down with the whole label being in the link's title
520                         my $facet_title_value = $one_facet;
521
522                         push @this_facets_array,
523                           (
524                             {
525                                 facet_count =>
526                                   $facets_counter->{$link_value}->{$one_facet},
527                                 facet_label_value => $facet_label_value,
528                                 facet_title_value => $facet_title_value,
529                                 facet_link_value  => $facet_link_value,
530                                 type_link_value   => $link_value,
531                             },
532                           );
533                     }
534                 }
535                 unless ( $facets_info->{$link_value}->{'expanded'} ) {
536                     $expandable = 1
537                       if ( ( $number_of_facets > 6 )
538                         && ( $expanded_facet ne $link_value ) );
539                 }
540                 push @facets_loop,
541                   (
542                     {
543                         type_link_value => $link_value,
544                         type_id         => $link_value . "_id",
545                         type_label      =>
546                           $facets_info->{$link_value}->{'label_value'},
547                         facets     => \@this_facets_array,
548                         expandable => $expandable,
549                         expand     => $link_value,
550                     }
551                   );
552             }
553         }
554     }
555     return ( undef, $results_hashref, \@facets_loop );
556 }
557
558 # STOPWORDS
559 sub _remove_stopwords {
560     my ($operand,$index) = @_;
561     # phrase and exact-qualified indexes shoudln't have stopwords removed
562     if ($index!~m/phr|ext/){
563     # remove stopwords from operand : parse all stopwords & remove them (case insensitive)
564     #       we use IsAlpha unicode definition, to deal correctly with diacritics.
565     #       otherwise, a french word like "leçon" woudl be split into "le" "çon", le 
566     #       is an empty word, we get "çon" and wouldn't find anything...
567         foreach (keys %{C4::Context->stopwords}) {
568             next if ($_ =~/(and|or|not)/); # don't remove operators 
569             $operand=~ s/\P{IsAlpha}$_\P{IsAlpha}/ /i;
570             $operand=~ s/^$_\P{IsAlpha}/ /i;
571             $operand=~ s/\P{IsAlpha}$_$/ /i;
572         }
573     }
574     return $operand;
575 }
576
577 # TRUNCATION
578 sub _detect_truncation {
579     my ($operand,$index) = @_;
580     my (@nontruncated,@righttruncated,@lefttruncated,@rightlefttruncated,@regexpr);
581     $operand =~s/^ //g;
582     my @wordlist= split (/\s/,$operand);
583     foreach my $word (@wordlist){
584         if ($word=~s/^\*([^\*]+)\*$/$1/){
585             push @rightlefttruncated,$word;
586         } 
587         elsif($word=~s/^\*([^\*]+)$/$1/){
588             push @lefttruncated,$word;
589         } 
590         elsif ($word=~s/^([^\*]+)\*$/$1/){
591             push @righttruncated,$word;
592         } 
593         elsif (index($word,"*")<0){
594             push @nontruncated,$word;
595         }
596         else {
597             push @regexpr,$word;
598         }
599     }
600     return (\@nontruncated,\@righttruncated,\@lefttruncated,\@rightlefttruncated,\@regexpr);
601 }
602
603 sub _build_stemmed_operand {
604     my ($operand) = @_;
605     my $stemmed_operand;
606     # FIXME: the locale should be set based on the user's language and/or search choice
607     my $stemmer = Lingua::Stem->new( -locale => 'EN-US' );
608     # FIXME: these should be stored in the db so the librarian can modify the behavior
609     $stemmer->add_exceptions(
610             {
611                 'and' => 'and',
612                 'or'  => 'or',
613                 'not' => 'not',
614             }
615                     
616         );
617     my @words = split( / /, $operand );
618     my $stems = $stemmer->stem(@words);
619     for my $stem (@$stems) {
620             $stemmed_operand .= "$stem";
621             $stemmed_operand .= "?" unless ( $stem =~ /(and$|or$|not$)/ ) || ( length($stem) < 3 );
622             $stemmed_operand .= " ";
623     }
624     #warn "STEMMED OPERAND: $stemmed_operand";
625     return $stemmed_operand;
626 }
627
628 sub _build_weighted_query {
629     # FIELD WEIGHTING - This is largely experimental stuff. What I'm committing works
630     # pretty well but will work much better when we have an actual query parser
631     my ($operand,$stemmed_operand,$index) = @_;
632     my $stemming      = C4::Context->preference("QueryStemming")     || 0;
633     my $weight_fields = C4::Context->preference("QueryWeightFields") || 0;
634     my $fuzzy_enabled = C4::Context->preference("QueryFuzzy") || 0;
635
636     my $weighted_query .= "(rk=(";     # Specifies that we're applying rank
637
638     # Keyword, or, no index specified
639     if ( ( $index eq 'kw' ) || ( !$index ) ) {
640         $weighted_query .= "Title-cover,ext,r1=\"$operand\"";       # exact title-cover
641         $weighted_query .= " or ti,ext,r2=\"$operand\"";            # exact title
642         $weighted_query .= " or ti,phr,r3=\"$operand\"";            # phrase title
643        #$weighted_query .= " or any,ext,r4=$operand";               # exact any
644        #$weighted_query .=" or kw,wrdl,r5=\"$operand\"";            # word list any
645         $weighted_query .= " or wrd,fuzzy,r8=\"$operand\"" if $fuzzy_enabled; # add fuzzy, word list
646         $weighted_query .= " or wrd,right-Truncation,r9=\"$stemmed_operand\"" if ($stemming and $stemmed_operand); # add stemming, right truncation
647        # embedded sorting: 0 a-z; 1 z-a
648        # $weighted_query .= ") or (sort1,aut=1";
649     }
650     # if the index already has more than one qualifier, just wrap the operand 
651     # in quotes and pass it back
652     elsif ($index =~ ',') {
653         $weighted_query .=" $index=\"$operand\"";
654     }
655     #TODO: build better cases based on specific search indexes
656     else {
657        $weighted_query .= " $index,ext,r1=\"$operand\"";            # exact index
658        #$weighted_query .= " or (title-sort-az=0 or $index,startswithnt,st-word,r3=$operand #)";
659        $weighted_query .= " or $index,phr,r3=\"$operand\"";         # phrase index
660        $weighted_query .= " or $index,rt,wrd,r3=\"$operand\"";      # word list index
661     }
662     $weighted_query .= "))";    # close rank specification
663     return $weighted_query;
664 }
665
666 # build the query itself
667 sub buildQuery {
668     my ( $operators, $operands, $indexes, $limits, $sort_by ) = @_;
669
670     my @operators = @$operators if $operators;
671     my @indexes   = @$indexes   if $indexes;
672     my @operands  = @$operands  if $operands;
673     my @limits    = @$limits    if $limits;
674     my @sort_by   = @$sort_by   if $sort_by;
675
676     my $stemming      = C4::Context->preference("QueryStemming")     || 0;
677     my $weight_fields = C4::Context->preference("QueryWeightFields") || 0;
678     my $fuzzy_enabled = C4::Context->preference("QueryFuzzy") || 0;
679
680     my $query = $operands[0];
681         my $simple_query = $operands[0];
682         my $query_cgi;
683         my $query_search_desc;
684
685         my $limit;
686         my $limit_cgi;
687         my $limit_desc;
688
689 # STEP I: determine if this is a form-based / simple query or if it's complex (if complex,
690 # pass it off to zebra directly)
691
692 # check if this is a known query language query, if it is, return immediately,
693 # the user is responsible for constructing valid syntax:
694     if ( $query =~ /^ccl=/ ) {
695         return ( undef, $', $', $', '', '', '', 'ccl' );
696     }
697     if ( $query =~ /^cql=/ ) {
698         return ( undef, $', $', $', '', '', '', 'cql' );
699     }
700     if ( $query =~ /^pqf=/ ) {
701         return ( undef, $', $', $', '', '', '', 'pqf' );
702     }
703
704 # FIXME: this is bound to be broken now
705     if ( $query =~ /(\(|\))/ ) {    # sorry, too complex, assume CCL
706         return ( undef, $query, $query_cgi, $query_search_desc, $limit, $limit_cgi, $limit_desc, 'ccl' );
707     }
708
709 # form-based queries are limited to non-nested at a specific depth, so we can easily
710 # modify the incoming query operands and indexes to do stemming and field weighting
711 # Once we do so, we'll end up with a value in $query, just like if we had an
712 # incoming $query from the user
713     else {
714         $query = ""; # clear it out so we can populate properly with field-weighted stemmed query
715         my $previous_operand;    # a flag used to keep track if there was a previous query
716                                 # if there was, we can apply the current operator
717         # for every operand
718         for ( my $i = 0 ; $i <= @operands ; $i++ ) {
719
720             # COMBINE OPERANDS, INDEXES AND OPERATORS
721             if ( $operands[$i] ) {
722
723                                 $weight_fields = 0 if $operands[$i] =~ /(:|=)/;
724                 my $operand = $operands[$i];
725                 my $index   = $indexes[$i];
726
727                 # if there's no index, don't use one, it will throw a CCL error
728                 my $index_plus = "$index:" if $index;
729                 my $index_plus_comma="$index," if $index;
730
731                 # Remove Stopwords  
732                 $operand = _remove_stopwords($operand,$index);
733                 warn "OPERAND w/out STOPWORDS: >$operand<" if $DEBUG;
734
735                 my $indexes_set;
736
737                 # Detect Truncation
738                 my ($nontruncated,$righttruncated,$lefttruncated,$rightlefttruncated,$regexpr);
739                 my $truncated_operand;
740                 ($nontruncated,$righttruncated,$lefttruncated,$rightlefttruncated,$regexpr) = _detect_truncation($operand,$index);
741                 warn "TRUNCATION: NON:>@$nontruncated< RIGHT:>@$righttruncated< LEFT:>@$lefttruncated< RIGHTLEFT:>@$rightlefttruncated< REGEX:>@$regexpr<" if $DEBUG;
742                 # Apply Truncation
743                 # Problem is when build_weights gets ahold if this is wraps in quotes which breaks the truncation :/
744                 if (scalar(@$righttruncated)+scalar(@$lefttruncated)+scalar(@$rightlefttruncated)>0){
745                     $indexes_set = 1;
746                     undef $weight_fields;
747                     my $previous_truncation_operand;
748                     if (scalar(@$nontruncated)>0) {
749                         $truncated_operand.= "$index_plus @$nontruncated ";
750                         $previous_truncation_operand = 1;
751                     }
752                     if (scalar(@$righttruncated)>0){
753                         $truncated_operand .= "and " if $previous_truncation_operand;
754                         $truncated_operand .= "$index_plus_comma"."rtrn:@$righttruncated ";
755                         $previous_truncation_operand = 1;
756                     }
757                     if (scalar(@$lefttruncated)>0){
758                         $truncated_operand .= "and " if $previous_truncation_operand;
759                         $truncated_operand .= "$index_plus_comma"."ltrn:@$lefttruncated ";
760                         $previous_truncation_operand = 1;
761                     }
762                     if (scalar(@$rightlefttruncated)>0){
763                         $truncated_operand .= "and " if $previous_truncation_operand;
764                         $truncated_operand .= "$index_plus_comma"."rltrn:@$rightlefttruncated ";
765                         $previous_truncation_operand = 1;
766                     }
767                 }
768                 $operand = $truncated_operand if $truncated_operand;
769                 warn "TRUNCATED OPERAND: >$truncated_operand<" if $DEBUG;
770
771                 # Handle Stemming
772                 my $stemmed_operand;
773                 $stemmed_operand = _build_stemmed_operand($operand) if $stemming;
774                 warn "STEMMED OPERAND: >$stemmed_operand<" if $DEBUG;
775
776                 # Handle Field Weighting
777                 my $weighted_operand;
778                 $weighted_operand = _build_weighted_query($operand,$stemmed_operand,$index) if $weight_fields;
779                 warn "FIELD WEIGHTED OPERAND: >$weighted_operand<" if $DEBUG;
780                 $operand = $weighted_operand if $weight_fields;
781                 $indexes_set = 1 if $weight_fields;
782
783                 # If there's a previous operand, we need to add an operator
784                 if ($previous_operand) {
785
786                     # user-specified operator
787                     if ( $operators[$i-1] ) {
788                         $query .= " $operators[$i-1] ";
789                         $query .= " $index_plus " unless $indexes_set;
790                         $query .= " $operand";
791                                                 $query_cgi .="&op=$operators[$i-1]";
792                                                 $query_cgi .="&idx=$index" if $index;
793                                                 $query_cgi .="&q=$operands[$i]" if $operands[$i];
794                                                 $query_search_desc .=" $operators[$i-1] $index_plus $operands[$i]";
795                     }
796
797                     # the default operator is and
798                     else {
799                         $query .= " and ";
800                         $query .= "$index_plus " unless $indexes_set;
801                         $query .= "$operand";
802                                                 $query_cgi .="&op=and&idx=$index" if $index;
803                                                 $query_cgi .="&q=$operands[$i]" if $operands[$i];
804                         $query_search_desc .= " and $index_plus $operands[$i]";
805                     }
806                 }
807
808                 else { 
809                                         # field-weighted queries already have indexes set
810                                         $query .=" $index_plus " unless $indexes_set;
811                                         $query .= $operand;
812                                         $query_search_desc .= " $index_plus $operands[$i]";
813                                         $query_cgi.="&idx=$index" if $index;
814                                         $query_cgi.="&q=$operands[$i]" if $operands[$i];
815
816                     $previous_operand = 1;
817                 }
818             }    #/if $operands
819         }    # /for
820     }
821     warn "QUERY BEFORE LIMITS: >$query<" if $DEBUG;
822
823     # add limits
824         my $group_OR_limits;
825     foreach my $this_limit (@limits) {
826         if ( $this_limit =~ /available/ ) {
827                         # FIXME: switch to zebra search for null values
828             $limit .= " (($query and datedue=0000-00-00) or ($query and datedue=0000-00-00 not lost=1) or ($query and datedue=0000-00-00 not lost=2))";
829                         $limit_cgi .= "&limit=available";
830                         $limit_desc .="";
831         }
832
833                 # these are treated as OR
834         elsif ( $this_limit =~ /mc/ ) {
835             $group_OR_limits .= " or " if $group_OR_limits;
836                         $limit_desc .=" or " if $group_OR_limits;
837                         $group_OR_limits .= "$this_limit";
838                         $limit_cgi .="&limit=$this_limit";
839                         $limit_desc .= "$this_limit";
840         }
841
842                 # regular old limits
843                 else {
844                         $limit .= " and " if $limit || $query;
845                         $limit .= "$this_limit";
846                         $limit_cgi .="&limit=$this_limit";
847                         $limit_desc .=" and $this_limit";
848                 }
849     }
850         if ($group_OR_limits) {
851                 $limit.=" and " if ($query || $limit );
852                 $limit.="($group_OR_limits)";
853         }
854         # normalize the strings
855         for ($query, $query_search_desc, $limit, $limit_desc) {
856                 $_ =~ s/  / /g;    # remove extra spaces
857         $_ =~ s/^ //g;     # remove any beginning spaces
858                 $_ =~ s/ $//g;     # remove any beginning spaces
859         $_ =~ s/:/=/g;     # causes probs for server
860         $_ =~ s/==/=/g;    # remove double == from query
861
862         }
863                 
864         $query_cgi =~ s/^&//;
865
866         # append the limit to the query
867         $query .= $limit;
868
869     warn "QUERY:".$query if $DEBUG;
870         warn "QUERY CGI:".$query_cgi if $DEBUG;
871     warn "QUERY DESC:".$query_search_desc if $DEBUG;
872     warn "LIMIT:".$limit if $DEBUG;
873     warn "LIMIT CGI:".$limit_cgi if $DEBUG;
874     warn "LIMIT DESC:".$limit_desc if $DEBUG;
875
876         return ( undef, $query,$simple_query,$query_cgi,$query_search_desc,$limit,$limit_cgi,$limit_desc );
877 }
878
879 # IMO this subroutine is pretty messy still -- it's responsible for
880 # building the HTML output for the template
881 sub searchResults {
882     my ( $searchdesc, $hits, $results_per_page, $offset, @marcresults ) = @_;
883
884     my $dbh = C4::Context->dbh;
885     my $toggle;
886     my $even = 1;
887     my @newresults;
888     my $span_terms_hashref;
889     for my $span_term ( split( / /, $searchdesc ) ) {
890         $span_term =~ s/(.*=|\)|\(|\+|\.)//g;
891         $span_terms_hashref->{$span_term}++;
892     }
893
894     #Build brancnames hash
895     #find branchname
896     #get branch information.....
897     my %branches;
898     my $bsth =
899       $dbh->prepare("SELECT branchcode,branchname FROM branches")
900       ;    # FIXME : use C4::Koha::GetBranches
901     $bsth->execute();
902     while ( my $bdata = $bsth->fetchrow_hashref ) {
903         $branches{ $bdata->{'branchcode'} } = $bdata->{'branchname'};
904     }
905
906     #Build itemtype hash
907     #find itemtype & itemtype image
908     my %itemtypes;
909     $bsth =
910       $dbh->prepare("SELECT itemtype,description,imageurl,summary,notforloan FROM itemtypes");
911     $bsth->execute();
912     while ( my $bdata = $bsth->fetchrow_hashref ) {
913         $itemtypes{ $bdata->{'itemtype'} }->{description} =
914           $bdata->{'description'};
915         $itemtypes{ $bdata->{'itemtype'} }->{imageurl} = $bdata->{'imageurl'};
916         $itemtypes{ $bdata->{'itemtype'} }->{summary} = $bdata->{'summary'};
917         $itemtypes{ $bdata->{'itemtype'} }->{notforloan} = $bdata->{'notforloan'};
918     }
919
920     #search item field code
921     my $sth =
922       $dbh->prepare(
923 "select tagfield from marc_subfield_structure where kohafield like 'items.itemnumber'"
924       );
925     $sth->execute;
926     my ($itemtag) = $sth->fetchrow;
927
928     ## find column names of items related to MARC
929     my $sth2 = $dbh->prepare("SHOW COLUMNS from items");
930     $sth2->execute;
931     my %subfieldstosearch;
932     while ( ( my $column ) = $sth2->fetchrow ) {
933         my ( $tagfield, $tagsubfield ) =
934           &GetMarcFromKohaField( "items." . $column, "" );
935         $subfieldstosearch{$column} = $tagsubfield;
936     }
937     my $times;
938
939     if ( $hits && $offset + $results_per_page <= $hits ) {
940         $times = $offset + $results_per_page;
941     }
942     else {
943         $times = $hits;
944     }
945
946     for ( my $i = $offset ; $i <= $times - 1 ; $i++ ) {
947         my $marcrecord;
948         $marcrecord = MARC::File::USMARC::decode( $marcresults[$i] );
949         my $oldbiblio = TransformMarcToKoha( $dbh, $marcrecord, '' );
950         # add image url if there is one
951         if ( $itemtypes{ $oldbiblio->{itemtype} }->{imageurl} =~ /^http:/ ) {
952             $oldbiblio->{imageurl} =
953               $itemtypes{ $oldbiblio->{itemtype} }->{imageurl};
954             $oldbiblio->{description} =
955               $itemtypes{ $oldbiblio->{itemtype} }->{description};
956         }
957         else {
958             $oldbiblio->{imageurl} =
959               getitemtypeimagesrc() . "/"
960               . $itemtypes{ $oldbiblio->{itemtype} }->{imageurl}
961               if ( $itemtypes{ $oldbiblio->{itemtype} }->{imageurl} );
962             $oldbiblio->{description} =
963               $itemtypes{ $oldbiblio->{itemtype} }->{description};
964         }
965         #
966         # build summary if there is one (the summary is defined in itemtypes table
967         #
968         if ($itemtypes{ $oldbiblio->{itemtype} }->{summary}) {
969             my $summary = $itemtypes{ $oldbiblio->{itemtype} }->{summary};
970             my @fields = $marcrecord->fields();
971             foreach my $field (@fields) {
972                 my $tag = $field->tag();
973                 my $tagvalue = $field->as_string();
974                 $summary =~ s/\[(.?.?.?.?)$tag\*(.*?)]/$1$tagvalue$2\[$1$tag$2]/g;
975                 unless ($tag<10) {
976                     my @subf = $field->subfields;
977                     for my $i (0..$#subf) {
978                         my $subfieldcode = $subf[$i][0];
979                         my $subfieldvalue = $subf[$i][1];
980                         my $tagsubf = $tag.$subfieldcode;
981                         $summary =~ s/\[(.?.?.?.?)$tagsubf(.*?)]/$1$subfieldvalue$2\[$1$tagsubf$2]/g;
982                     }
983                 }
984             }
985             $summary =~ s/\[(.*?)]//g;
986             $summary =~ s/\n/<br>/g;
987             $oldbiblio->{summary} = $summary;
988         }
989         # add spans to search term in results for search term highlighting
990         foreach my $term ( keys %$span_terms_hashref ) {
991             my $old_term = $term;
992             if ( length($term) > 3 ) {
993                 $term =~ s/(.*=|\)|\(|\+|\.|\?|\[|\])//g;
994                 $term =~ s/\\//g;
995                 $term =~ s/\*//g;
996
997                 #FIXME: is there a better way to do this?
998                 $oldbiblio->{'title'} =~ s/$term/<span class=\"term\">$&<\/span>/gi;
999                 $oldbiblio->{'subtitle'} =~
1000                   s/$term/<span class=\"term\">$&<\/span>/gi;
1001
1002                 $oldbiblio->{'author'} =~ s/$term/<span class=\"term\">$&<\/span>/gi;
1003                 $oldbiblio->{'publishercode'} =~ s/$term/<span class=\"term\">$&<\/span>/gi;
1004                 $oldbiblio->{'place'} =~ s/$term/<span class=\"term\">$&<\/span>/gi;
1005                 $oldbiblio->{'pages'} =~ s/$term/<span class=\"term\">$&<\/span>/gi;
1006                 $oldbiblio->{'notes'} =~ s/$term/<span class=\"term\">$&<\/span>/gi;
1007                 $oldbiblio->{'size'}  =~ s/$term/<span class=\"term\">$&<\/span>/gi;
1008             }
1009         }
1010
1011         if ( $i % 2 ) {
1012             $toggle = "#ffffcc";
1013         }
1014         else {
1015             $toggle = "white";
1016         }
1017         $oldbiblio->{'toggle'} = $toggle;
1018         my @fields = $marcrecord->field($itemtag);
1019         my @items_loop;
1020         my $items;
1021         my $ordered_count     = 0;
1022         my $onloan_count      = 0;
1023         my $wthdrawn_count    = 0;
1024         my $itemlost_count    = 0;
1025         my $norequests        = 1;
1026
1027         #
1028         # check the loan status of the item : 
1029         # it is not stored in the MARC record, for pref (zebra reindexing)
1030         # reason. Thus, we have to get the status from a specific SQL query
1031         #
1032         my $sth_issue = $dbh->prepare("
1033             SELECT date_due,returndate 
1034             FROM issues 
1035             WHERE itemnumber=? AND returndate IS NULL");
1036         my $items_count=scalar(@fields);
1037         foreach my $field (@fields) {
1038             my $item;
1039             foreach my $code ( keys %subfieldstosearch ) {
1040                 $item->{$code} = $field->subfield( $subfieldstosearch{$code} );
1041             }
1042             $sth_issue->execute($item->{itemnumber});
1043             $item->{due_date} = format_date($sth_issue->fetchrow);
1044             $item->{onloan} = 1 if $item->{due_date};
1045             # at least one item can be reserved : suppose no
1046             $norequests = 1;
1047             if ( $item->{wthdrawn} ) {
1048                 $wthdrawn_count++;
1049                 $items->{ $item->{'homebranch'}.'--'.$item->{'itemcallnumber'} }->{unavailable}=1;
1050                 $items->{ $item->{'homebranch'}.'--'.$item->{'itemcallnumber'} }->{wthdrawn}=1;
1051             }
1052             elsif ( $item->{itemlost} ) {
1053                 $itemlost_count++;
1054                 $items->{ $item->{'homebranch'}.'--'.$item->{'itemcallnumber'} }->{unavailable}=1;
1055                 $items->{ $item->{'homebranch'}.'--'.$item->{'itemcallnumber'} }->{itemlost}=1;
1056             }
1057             unless ( $item->{notforloan}) {
1058                 # OK, this one can be issued, so at least one can be reserved
1059                 $norequests = 0;
1060             }
1061             if ( ( $item->{onloan} ) && ( $item->{onloan} != '0000-00-00' ) )
1062             {
1063                 $items->{ $item->{'homebranch'}.'--'.$item->{'itemcallnumber'} }->{unavailable}=1;
1064                 $items->{ $item->{'homebranch'}.'--'.$item->{'itemcallnumber'} }->{onloancount} = 1;
1065                 $items->{ $item->{'homebranch'}.'--'.$item->{'itemcallnumber'} }->{due_date} = $item->{due_date};
1066                 $onloan_count++;
1067             }
1068             if ( $item->{'homebranch'} ) {
1069                 $items->{ $item->{'homebranch'}.'--'.$item->{'itemcallnumber'} }->{count}++;
1070             }
1071
1072             # Last resort
1073             elsif ( $item->{'holdingbranch'} ) {
1074                 $items->{ $item->{'holdingbranch'} }->{count}++;
1075             }
1076             $items->{ $item->{'homebranch'}.'--'.$item->{'itemcallnumber'} }->{itemcallnumber} =                $item->{itemcallnumber};
1077             $items->{ $item->{'homebranch'}.'--'.$item->{'itemcallnumber'} }->{location} =                $item->{location};
1078             $items->{ $item->{'homebranch'}.'--'.$item->{'itemcallnumber'} }->{branchcode} =               $item->{homebranch};
1079         }    # notforloan, item level and biblioitem level
1080
1081         # last check for norequest : if itemtype is notforloan, it can't be reserved either, whatever the items
1082         $norequests = 1 if $itemtypes{$oldbiblio->{itemtype}}->{notforloan};
1083
1084         for my $key ( sort keys %$items ) {
1085             my $this_item = {
1086                 branchname     => $branches{$items->{$key}->{branchcode}},
1087                 branchcode     => $items->{$key}->{branchcode},
1088                 count          => $items->{$key}->{count},
1089                 itemcallnumber => $items->{$key}->{itemcallnumber},
1090                 location => $items->{$key}->{location},
1091                 onloancount      => $items->{$key}->{onloancount},
1092                 due_date         => $items->{$key}->{due_date},
1093                 wthdrawn      => $items->{$key}->{wthdrawn},
1094                 lost         => $items->{$key}->{itemlost},
1095             };
1096             push @items_loop, $this_item;
1097         }
1098         $oldbiblio->{norequests}    = $norequests;
1099         $oldbiblio->{items_count}    = $items_count;
1100         $oldbiblio->{items_loop}    = \@items_loop;
1101         $oldbiblio->{onloancount}   = $onloan_count;
1102         $oldbiblio->{wthdrawncount} = $wthdrawn_count;
1103         $oldbiblio->{itemlostcount} = $itemlost_count;
1104         $oldbiblio->{orderedcount}  = $ordered_count;
1105         $oldbiblio->{isbn}          =~ s/-//g; # deleting - in isbn to enable amazon content 
1106         push( @newresults, $oldbiblio );
1107     }
1108     return @newresults;
1109 }
1110
1111
1112
1113 #----------------------------------------------------------------------
1114 #
1115 # Non-Zebra GetRecords#
1116 #----------------------------------------------------------------------
1117
1118 =head2 NZgetRecords
1119
1120   NZgetRecords has the same API as zera getRecords, even if some parameters are not managed
1121
1122 =cut
1123
1124 sub NZgetRecords {
1125     my (
1126         $koha_query,     $simple_query,  $sort_by_ref,
1127         $servers_ref,    $results_per_page, $offset,
1128         $expanded_facet, $branches,         $query_type,
1129         $scan
1130     ) = @_;
1131     my $result = NZanalyse($koha_query);
1132     return (undef,NZorder($result,@$sort_by_ref[0],$results_per_page,$offset),undef);
1133 }
1134
1135 =head2 NZanalyse
1136
1137   NZanalyse : get a CQL string as parameter, and returns a list of biblionumber;title,biblionumber;title,...
1138   the list is builded from inverted index in nozebra SQL table
1139   note that title is here only for convenience : the sorting will be very fast when requested on title
1140   if the sorting is requested on something else, we will have to reread all results, and that may be longer.
1141
1142 =cut
1143
1144 sub NZanalyse {
1145     my ($string,$server) = @_;
1146     # $server contains biblioserver or authorities, depending on what we search on.
1147     #warn "querying : $string on $server";
1148     $server='biblioserver' unless $server;
1149     # if we have a ", replace the content to discard temporarily any and/or/not inside
1150     my $commacontent;
1151     if ($string =~/"/) {
1152         $string =~ s/"(.*?)"/__X__/;
1153         $commacontent = $1;
1154 #         print "commacontent : $commacontent\n";
1155     }
1156     # split the query string in 3 parts : X AND Y means : $left="X", $operand="AND" and $right="Y"
1157     # then, call again NZanalyse with $left and $right
1158     # (recursive until we find a leaf (=> something without and/or/not)
1159     $string =~ /(.*)( and | or | not | AND | OR | NOT )(.*)/;
1160     my $left = $1;
1161     my $right = $3;
1162     my $operand = lc($2);
1163     # it's not a leaf, we have a and/or/not
1164     if ($operand) {
1165         # reintroduce comma content if needed
1166         $right =~ s/__X__/"$commacontent"/ if $commacontent;
1167         $left =~ s/__X__/"$commacontent"/ if $commacontent;
1168 #         warn "node : $left / $operand / $right\n";
1169         my $leftresult = NZanalyse($left,$server);
1170         my $rightresult = NZanalyse($right,$server);
1171         # OK, we have the results for right and left part of the query
1172         # depending of operand, intersect, union or exclude both lists
1173         # to get a result list
1174         if ($operand eq ' and ') {
1175             my @leftresult = split /;/, $leftresult;
1176 #             my @rightresult = split /;/,$leftresult;
1177             my $finalresult;
1178             # parse the left results, and if the biblionumber exist in the right result, save it in finalresult
1179             # the result is stored twice, to have the same weight for AND than OR.
1180             # example : TWO : 61,61,64,121 (two is twice in the biblio #61) / TOWER : 61,64,130
1181             # result : 61,61,61,61,64,64 for two AND tower : 61 has more weight than 64
1182             foreach (@leftresult) {
1183                 if ($rightresult =~ "$_;") {
1184                     $finalresult .= "$_;$_;";
1185                 }
1186             }
1187             return $finalresult;
1188         } elsif ($operand eq ' or ') {
1189             # just merge the 2 strings
1190             return $leftresult.$rightresult;
1191         } elsif ($operand eq ' not ') {
1192             my @leftresult = split /;/, $leftresult;
1193 #             my @rightresult = split /;/,$leftresult;
1194             my $finalresult;
1195             foreach (@leftresult) {
1196                 unless ($rightresult =~ "$_;") {
1197                     $finalresult .= "$_;";
1198                 }
1199             }
1200             return $finalresult;
1201         } else {
1202             # this error is impossible, because of the regexp that isolate the operand, but just in case...
1203             die "error : operand unknown : $operand for $string";
1204         }
1205     # it's a leaf, do the real SQL query and return the result
1206     } else {
1207         $string =~  s/__X__/"$commacontent"/ if $commacontent;
1208         $string =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|&|\+|\*|\// /g;
1209 #         warn "leaf : $string\n";
1210         # parse the string in in operator/operand/value again
1211         $string =~ /(.*)(>=|<=)(.*)/;
1212         my $left = $1;
1213         my $operator = $2;
1214         my $right = $3;
1215         unless ($operator) {
1216             $string =~ /(.*)(>|<|=)(.*)/;
1217             $left = $1;
1218             $operator = $2;
1219             $right = $3;
1220         }
1221         my $results;
1222         # automatic replace for short operators
1223         $left='title' if $left =~ '^ti';
1224         $left='author' if $left =~ '^au';
1225         $left='publisher' if $left =~ '^pb';
1226         $left='subject' if $left =~ '^su';
1227         $left='koha-Auth-Number' if $left =~ '^an';
1228         $left='keyword' if $left =~ '^kw';
1229         if ($operator) {
1230             #do a specific search
1231             my $dbh = C4::Context->dbh;
1232             $operator='LIKE' if $operator eq '=' and $right=~ /%/;
1233             my $sth = $dbh->prepare("SELECT biblionumbers,value FROM nozebra WHERE server=? AND indexname=? AND value $operator ?");
1234             warn "$left / $operator / $right\n";
1235             # split each word, query the DB and build the biblionumbers result
1236             foreach (split / /,$right) {
1237                 my ($biblionumbers,$value);
1238                 next unless $_;
1239                 warn "EXECUTE : $server, $left, $_";
1240                 $sth->execute($server, $left, $_);
1241                 while (my ($line,$value) = $sth->fetchrow) {
1242                     # if we are dealing with a numeric value, use only numeric results (in case of >=, <=, > or <)
1243                     # otherwise, fill the result
1244                     $biblionumbers .= $line unless ($right =~ /\d/ && $value =~ /\D/);
1245                     warn "result : $value ". ($right =~ /\d/) . "==".(!$value =~ /\d/) ;#= $line";
1246                 }
1247                 # do a AND with existing list if there is one, otherwise, use the biblionumbers list as 1st result list
1248                 if ($results) {
1249                     my @leftresult = split /;/, $biblionumbers;
1250                     my $temp;
1251                     foreach my $entry (@leftresult) { # $_ contains biblionumber,title-weight
1252                         # remove weight at the end
1253                         my $cleaned = $entry;
1254                         $cleaned =~ s/-\d*$//;
1255                         # if the entry already in the hash, take it & increase weight
1256 #                         warn "===== $cleaned =====";
1257                         if ($results =~ "$cleaned") {
1258                             $temp .= "$entry;$entry;";
1259 #                             warn "INCLUDING $entry";
1260                         }
1261                     }
1262                     $results = $temp;
1263                 } else {
1264                     $results = $biblionumbers;
1265                 }
1266             }
1267         } else {
1268             #do a complete search (all indexes)
1269             my $dbh = C4::Context->dbh;
1270             my $sth = $dbh->prepare("SELECT biblionumbers FROM nozebra WHERE server=? AND value LIKE ?");
1271             # split each word, query the DB and build the biblionumbers result
1272             foreach (split / /,$string) {
1273                 next if C4::Context->stopwords->{uc($_)}; # skip if stopword
1274                 #warn "search on all indexes on $_";
1275                 my $biblionumbers;
1276                 next unless $_;
1277                 $sth->execute($server, $_);
1278                 while (my $line = $sth->fetchrow) {
1279                     $biblionumbers .= $line;
1280                 }
1281                 # do a AND with existing list if there is one, otherwise, use the biblionumbers list as 1st result list
1282                 if ($results) {
1283 #                 warn "RES for $_ = $biblionumbers";
1284                     my @leftresult = split /;/, $biblionumbers;
1285                     my $temp;
1286                     foreach my $entry (@leftresult) { # $_ contains biblionumber,title-weight
1287                         # remove weight at the end
1288                         my $cleaned = $entry;
1289                         $cleaned =~ s/-\d*$//;
1290                         # if the entry already in the hash, take it & increase weight
1291 #                         warn "===== $cleaned =====";
1292                         if ($results =~ "$cleaned") {
1293                             $temp .= "$entry;$entry;";
1294 #                             warn "INCLUDING $entry";
1295                         }
1296                     }
1297                     $results = $temp;
1298                 } else {
1299 #                 warn "NEW RES for $_ = $biblionumbers";
1300                     $results = $biblionumbers;
1301                 }
1302             }
1303         }
1304 #         warn "return : $results for LEAF : $string";
1305         return $results;
1306     }
1307 }
1308
1309 =head2 NZorder
1310
1311   $finalresult = NZorder($biblionumbers, $ordering,$results_per_page,$offset);
1312   
1313   TODO :: Description
1314
1315 =cut
1316
1317
1318 sub NZorder {
1319     my ($biblionumbers, $ordering,$results_per_page,$offset) = @_;
1320     # order title asc by default
1321 #     $ordering = '1=36 <i' unless $ordering;
1322     $results_per_page=20 unless $results_per_page;
1323     $offset = 0 unless $offset;
1324     my $dbh = C4::Context->dbh;
1325     #
1326     # order by POPULARITY
1327     #
1328     if ($ordering =~ /popularity/) {
1329         my %result;
1330         my %popularity;
1331         # popularity is not in MARC record, it's builded from a specific query
1332         my $sth = $dbh->prepare("select sum(issues) from items where biblionumber=?");
1333         foreach (split /;/,$biblionumbers) {
1334             my ($biblionumber,$title) = split /,/,$_;
1335             $result{$biblionumber}=GetMarcBiblio($biblionumber);
1336             $sth->execute($biblionumber);
1337             my $popularity= $sth->fetchrow ||0;
1338             # hint : the key is popularity.title because we can have
1339             # many results with the same popularity. In this cas, sub-ordering is done by title
1340             # we also have biblionumber to avoid bug for 2 biblios with the same title & popularity
1341             # (un-frequent, I agree, but we won't forget anything that way ;-)
1342             $popularity{sprintf("%10d",$popularity).$title.$biblionumber} = $biblionumber;
1343         }
1344         # sort the hash and return the same structure as GetRecords (Zebra querying)
1345         my $result_hash;
1346         my $numbers=0;
1347         if ($ordering eq 'popularity_dsc') { # sort popularity DESC
1348             foreach my $key (sort {$b cmp $a} (keys %popularity)) {
1349                 $result_hash->{'RECORDS'}[$numbers++] = $result{$popularity{$key}}->as_usmarc();
1350             }
1351         } else { # sort popularity ASC
1352             foreach my $key (sort (keys %popularity)) {
1353                 $result_hash->{'RECORDS'}[$numbers++] = $result{$popularity{$key}}->as_usmarc();
1354             }
1355         }
1356         my $finalresult=();
1357         $result_hash->{'hits'} = $numbers;
1358         $finalresult->{'biblioserver'} = $result_hash;
1359         return $finalresult;
1360     #
1361     # ORDER BY author
1362     #
1363     } elsif ($ordering =~/author/){
1364         my %result;
1365         foreach (split /;/,$biblionumbers) {
1366             my ($biblionumber,$title) = split /,/,$_;
1367             my $record=GetMarcBiblio($biblionumber);
1368             my $author;
1369             if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
1370                 $author=$record->subfield('200','f');
1371                 $author=$record->subfield('700','a') unless $author;
1372             } else {
1373                 $author=$record->subfield('100','a');
1374             }
1375             # hint : the result is sorted by title.biblionumber because we can have X biblios with the same title
1376             # and we don't want to get only 1 result for each of them !!!
1377             $result{$author.$biblionumber}=$record;
1378         }
1379         # sort the hash and return the same structure as GetRecords (Zebra querying)
1380         my $result_hash;
1381         my $numbers=0;
1382         if ($ordering eq 'author_za') { # sort by author desc
1383             foreach my $key (sort { $b cmp $a } (keys %result)) {
1384                 $result_hash->{'RECORDS'}[$numbers++] = $result{$key}->as_usmarc();
1385             }
1386         } else { # sort by author ASC
1387             foreach my $key (sort (keys %result)) {
1388                 $result_hash->{'RECORDS'}[$numbers++] = $result{$key}->as_usmarc();
1389             }
1390         }
1391         my $finalresult=();
1392         $result_hash->{'hits'} = $numbers;
1393         $finalresult->{'biblioserver'} = $result_hash;
1394         return $finalresult;
1395     #
1396     # ORDER BY callnumber
1397     #
1398     } elsif ($ordering =~/callnumber/){
1399         my %result;
1400         foreach (split /;/,$biblionumbers) {
1401             my ($biblionumber,$title) = split /,/,$_;
1402             my $record=GetMarcBiblio($biblionumber);
1403             my $callnumber;
1404             my ($callnumber_tag,$callnumber_subfield)=GetMarcFromKohaField($dbh,'items.itemcallnumber');
1405             ($callnumber_tag,$callnumber_subfield)= GetMarcFromKohaField('biblioitems.callnumber') unless $callnumber_tag;
1406             if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
1407                 $callnumber=$record->subfield('200','f');
1408             } else {
1409                 $callnumber=$record->subfield('100','a');
1410             }
1411             # hint : the result is sorted by title.biblionumber because we can have X biblios with the same title
1412             # and we don't want to get only 1 result for each of them !!!
1413             $result{$callnumber.$biblionumber}=$record;
1414         }
1415         # sort the hash and return the same structure as GetRecords (Zebra querying)
1416         my $result_hash;
1417         my $numbers=0;
1418         if ($ordering eq 'call_number_dsc') { # sort by title desc
1419             foreach my $key (sort { $b cmp $a } (keys %result)) {
1420                 $result_hash->{'RECORDS'}[$numbers++] = $result{$key}->as_usmarc();
1421             }
1422         } else { # sort by title ASC
1423             foreach my $key (sort { $a cmp $b } (keys %result)) {
1424                 $result_hash->{'RECORDS'}[$numbers++] = $result{$key}->as_usmarc();
1425             }
1426         }
1427         my $finalresult=();
1428         $result_hash->{'hits'} = $numbers;
1429         $finalresult->{'biblioserver'} = $result_hash;
1430         return $finalresult;
1431     } elsif ($ordering =~ /pubdate/){ #pub year
1432         my %result;
1433         foreach (split /;/,$biblionumbers) {
1434             my ($biblionumber,$title) = split /,/,$_;
1435             my $record=GetMarcBiblio($biblionumber);
1436             my ($publicationyear_tag,$publicationyear_subfield)=GetMarcFromKohaField('biblioitems.publicationyear','');
1437             my $publicationyear=$record->subfield($publicationyear_tag,$publicationyear_subfield);
1438             # hint : the result is sorted by title.biblionumber because we can have X biblios with the same title
1439             # and we don't want to get only 1 result for each of them !!!
1440             $result{$publicationyear.$biblionumber}=$record;
1441         }
1442         # sort the hash and return the same structure as GetRecords (Zebra querying)
1443         my $result_hash;
1444         my $numbers=0;
1445         if ($ordering eq 'pubdate_dsc') { # sort by pubyear desc
1446             foreach my $key (sort { $b cmp $a } (keys %result)) {
1447                 $result_hash->{'RECORDS'}[$numbers++] = $result{$key}->as_usmarc();
1448             }
1449         } else { # sort by pub year ASC
1450             foreach my $key (sort (keys %result)) {
1451                 $result_hash->{'RECORDS'}[$numbers++] = $result{$key}->as_usmarc();
1452             }
1453         }
1454         my $finalresult=();
1455         $result_hash->{'hits'} = $numbers;
1456         $finalresult->{'biblioserver'} = $result_hash;
1457         return $finalresult;
1458     #
1459     # ORDER BY title
1460     #
1461     } elsif ($ordering =~ /title/) { 
1462         # the title is in the biblionumbers string, so we just need to build a hash, sort it and return
1463         my %result;
1464         foreach (split /;/,$biblionumbers) {
1465             my ($biblionumber,$title) = split /,/,$_;
1466             # hint : the result is sorted by title.biblionumber because we can have X biblios with the same title
1467             # and we don't want to get only 1 result for each of them !!!
1468             # hint & speed improvement : we can order without reading the record
1469             # so order, and read records only for the requested page !
1470             $result{$title.$biblionumber}=$biblionumber;
1471         }
1472         # sort the hash and return the same structure as GetRecords (Zebra querying)
1473         my $result_hash;
1474         my $numbers=0;
1475         if ($ordering eq 'title_az') { # sort by title desc
1476             foreach my $key (sort (keys %result)) {
1477                 $result_hash->{'RECORDS'}[$numbers++] = $result{$key};
1478             }
1479         } else { # sort by title ASC
1480             foreach my $key (sort { $b cmp $a } (keys %result)) {
1481                 $result_hash->{'RECORDS'}[$numbers++] = $result{$key};
1482             }
1483         }
1484         # limit the $results_per_page to result size if it's more
1485         $results_per_page = $numbers-1 if $numbers < $results_per_page;
1486         # for the requested page, replace biblionumber by the complete record
1487         # speed improvement : avoid reading too much things
1488         for (my $counter=$offset;$counter<=$offset+$results_per_page;$counter++) {
1489             $result_hash->{'RECORDS'}[$counter] = GetMarcBiblio($result_hash->{'RECORDS'}[$counter])->as_usmarc;
1490         }
1491         my $finalresult=();
1492         $result_hash->{'hits'} = $numbers;
1493         $finalresult->{'biblioserver'} = $result_hash;
1494         return $finalresult;
1495     } else {
1496     #
1497     # order by ranking
1498     #
1499         # we need 2 hashes to order by ranking : the 1st one to count the ranking, the 2nd to order by ranking
1500         my %result;
1501         my %count_ranking;
1502         foreach (split /;/,$biblionumbers) {
1503             my ($biblionumber,$title) = split /,/,$_;
1504             $title =~ /(.*)-(\d)/;
1505             # get weight 
1506             my $ranking =$2;
1507             # note that we + the ranking because ranking is calculated on weight of EACH term requested.
1508             # if we ask for "two towers", and "two" has weight 2 in biblio N, and "towers" has weight 4 in biblio N
1509             # biblio N has ranking = 6
1510             $count_ranking{$biblionumber} += $ranking;
1511         }
1512         # build the result by "inverting" the count_ranking hash
1513         # hing : as usual, we don't order by ranking only, to avoid having only 1 result for each rank. We build an hash on concat(ranking,biblionumber) instead
1514 #         warn "counting";
1515         foreach (keys %count_ranking) {
1516             $result{sprintf("%10d",$count_ranking{$_}).'-'.$_} = $_;
1517         }
1518         # sort the hash and return the same structure as GetRecords (Zebra querying)
1519         my $result_hash;
1520         my $numbers=0;
1521             foreach my $key (sort {$b cmp $a} (keys %result)) {
1522                 $result_hash->{'RECORDS'}[$numbers++] = $result{$key};
1523             }
1524         # limit the $results_per_page to result size if it's more
1525         $results_per_page = $numbers-1 if $numbers < $results_per_page;
1526         # for the requested page, replace biblionumber by the complete record
1527         # speed improvement : avoid reading too much things
1528         for (my $counter=$offset;$counter<=$offset+$results_per_page;$counter++) {
1529             $result_hash->{'RECORDS'}[$counter] = GetMarcBiblio($result_hash->{'RECORDS'}[$counter])->as_usmarc if $result_hash->{'RECORDS'}[$counter];
1530         }
1531         my $finalresult=();
1532         $result_hash->{'hits'} = $numbers;
1533         $finalresult->{'biblioserver'} = $result_hash;
1534         return $finalresult;
1535     }
1536 }
1537 =head2 ModBiblios
1538
1539 ($countchanged,$listunchanged) = ModBiblios($listbiblios, $tagsubfield,$initvalue,$targetvalue,$test);
1540
1541 this function changes all the values $initvalue in subfield $tag$subfield in any record in $listbiblios
1542 test parameter if set donot perform change to records in database.
1543
1544 =over 2
1545
1546 =item C<input arg:>
1547
1548     * $listbiblios is an array ref to marcrecords to be changed
1549     * $tagsubfield is the reference of the subfield to change.
1550     * $initvalue is the value to search the record for
1551     * $targetvalue is the value to set the subfield to
1552     * $test is to be set only not to perform changes in database.
1553
1554 =item C<Output arg:>
1555     * $countchanged counts all the changes performed.
1556     * $listunchanged contains the list of all the biblionumbers of records unchanged.
1557
1558 =item C<usage in the script:>
1559
1560 =back
1561
1562 my ($countchanged, $listunchanged) = EditBiblios($results->{RECORD}, $tagsubfield,$initvalue,$targetvalue);;
1563 #If one wants to display unchanged records, you should get biblios foreach @$listunchanged 
1564 $template->param(countchanged => $countchanged, loopunchanged=>$listunchanged);
1565
1566 =cut
1567
1568 sub ModBiblios{
1569   my ($listbiblios,$tagsubfield,$initvalue,$targetvalue,$test)=@_;
1570   my $countmatched;
1571   my @unmatched;
1572   my ($tag,$subfield)=($1,$2) if ($tagsubfield=~/^(\d{1,3})([a-z0-9A-Z@])?$/); 
1573   if ((length($tag)<3)&& $subfield=~/0-9/){
1574     $tag=$tag.$subfield;
1575     undef $subfield;
1576   } 
1577   my ($bntag,$bnsubf) = GetMarcFromKohaField('biblio.biblionumber');
1578   my ($itemtag,$itemsubf) = GetMarcFromKohaField('items.itemnumber');
1579   foreach my $usmarc (@$listbiblios){
1580     my $record; 
1581     $record=eval{MARC::Record->new_from_usmarc($usmarc)};
1582     my $biblionumber;
1583     if ($@){
1584       # usmarc is not a valid usmarc May be a biblionumber
1585       if ($tag eq $itemtag){
1586         my $bib=GetBiblioFromItemNumber($usmarc);   
1587         $record=GetMarcItem($bib->{'biblionumber'},$usmarc) ;   
1588         $biblionumber=$bib->{'biblionumber'};
1589       } else {   
1590         $record=GetMarcBiblio($usmarc);   
1591         $biblionumber=$usmarc;
1592       }   
1593     }  else {
1594       if ($bntag >= 010){
1595         $biblionumber = $record->subfield($bntag,$bnsubf);
1596       }else {
1597         $biblionumber=$record->field($bntag)->data;
1598       }
1599     }  
1600     #GetBiblionumber is to be written.
1601     #Could be replaced by TransformMarcToKoha (But Would be longer)
1602     if ($record->field($tag)){
1603       my $modify=0;  
1604       foreach my $field ($record->field($tag)){
1605         if ($subfield){
1606           if ($field->delete_subfield('code' =>$subfield,'match'=>qr($initvalue))){
1607             $countmatched++;
1608             $modify=1;      
1609             $field->update($subfield,$targetvalue) if ($targetvalue);
1610           }
1611         } else {
1612           if ($tag >= 010){
1613             if ($field->delete_field($field)){
1614               $countmatched++;
1615               $modify=1;      
1616             }
1617           } else {
1618             $field->data=$targetvalue if ($field->data=~qr($initvalue));
1619           }     
1620         }    
1621       }
1622 #       warn $record->as_formatted;
1623       if ($modify){
1624         ModBiblio($record,$biblionumber,GetFrameworkCode($biblionumber)) unless ($test);
1625       } else {
1626         push @unmatched, $biblionumber;   
1627       }      
1628     } else {
1629       push @unmatched, $biblionumber;
1630     }
1631   }
1632   return ($countmatched,\@unmatched);
1633 }
1634
1635 END { }    # module clean-up code here (global destructor)
1636
1637 1;
1638 __END__
1639
1640 =head1 AUTHOR
1641
1642 Koha Developement team <info@koha.org>
1643
1644 =cut