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