Bug 30082: Bibliographic details tab missing when user can't add local cover image
[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
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18 use Modern::Perl;
19 require Exporter;
20 use C4::Context;
21 use C4::Biblio;    # GetMarcFromKohaField, GetBiblioData
22 use C4::Koha;      # getFacets
23 use Koha::DateUtils;
24 use Koha::Libraries;
25 use Lingua::Stem;
26 use XML::Simple;
27 use C4::XSLT;
28 use C4::Reserves;    # GetReserveStatus
29 use C4::Debug;
30 use C4::Charset;
31 use Koha::AuthorisedValues;
32 use Koha::ItemTypes;
33 use Koha::Libraries;
34 use Koha::Patrons;
35 use Koha::RecordProcessor;
36 use URI::Escape;
37 use Business::ISBN;
38 use MARC::Record;
39 use MARC::Field;
40 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $DEBUG);
41
42 BEGIN {
43     $DEBUG = ($ENV{DEBUG}) ? 1 : 0;
44 }
45
46 =head1 NAME
47
48 C4::Search - Functions for searching the Koha catalog.
49
50 =head1 SYNOPSIS
51
52 See opac/opac-search.pl or catalogue/search.pl for example of usage
53
54 =head1 DESCRIPTION
55
56 This module provides searching functions for Koha's bibliographic databases
57
58 =head1 FUNCTIONS
59
60 =cut
61
62 @ISA    = qw(Exporter);
63 @EXPORT = qw(
64   &FindDuplicate
65   &SimpleSearch
66   &searchResults
67   &getRecords
68   &buildQuery
69   &GetDistinctValues
70   &enabled_staff_search_views
71 );
72
73 # make all your functions, whether exported or not;
74
75 =head2 FindDuplicate
76
77 ($biblionumber,$biblionumber,$title) = FindDuplicate($record);
78
79 This function attempts to find duplicate records using a hard-coded, fairly simplistic algorithm
80
81 =cut
82
83 sub FindDuplicate {
84     my ($record) = @_;
85     my $dbh = C4::Context->dbh;
86     my $result = TransformMarcToKoha( $record, '' );
87     my $sth;
88     my $query;
89
90     # search duplicate on ISBN, easy and fast..
91     # ... normalize first
92     if ( $result->{isbn} ) {
93         $result->{isbn} =~ s/\(.*$//;
94         $result->{isbn} =~ s/\s+$//;
95         $query = "isbn:$result->{isbn}";
96     }
97     else {
98
99         my $titleindex = 'ti,ext';
100         my $authorindex = 'au,ext';
101         my $op = 'and';
102
103         $result->{title} =~ s /\\//g;
104         $result->{title} =~ s /\"//g;
105         $result->{title} =~ s /\(//g;
106         $result->{title} =~ s /\)//g;
107
108         $query = "$titleindex:\"$result->{title}\"";
109         if   ( $result->{author} ) {
110             $result->{author} =~ s /\\//g;
111             $result->{author} =~ s /\"//g;
112             $result->{author} =~ s /\(//g;
113             $result->{author} =~ s /\)//g;
114
115             $query .= " $op $authorindex:\"$result->{author}\"";
116         }
117     }
118
119     my $searcher = Koha::SearchEngine::Search->new({index => $Koha::SearchEngine::BIBLIOS_INDEX});
120     my ( $error, $searchresults, undef ) = $searcher->simple_search_compat($query,0,50);
121     my @results;
122     if (!defined $error) {
123         foreach my $possible_duplicate_record (@{$searchresults}) {
124             my $marcrecord = new_record_from_zebra(
125                 'biblioserver',
126                 $possible_duplicate_record
127             );
128
129             my $result = TransformMarcToKoha( $marcrecord, '' );
130
131             # FIXME :: why 2 $biblionumber ?
132             if ($result) {
133                 push @results, $result->{'biblionumber'};
134                 push @results, $result->{'title'};
135             }
136         }
137     }
138     return @results;
139 }
140
141 =head2 SimpleSearch
142
143 ( $error, $results, $total_hits ) = SimpleSearch( $query, $offset, $max_results, [@servers], [%options] );
144
145 This function provides a simple search API on the bibliographic catalog
146
147 =over 2
148
149 =item C<input arg:>
150
151     * $query can be a simple keyword or a complete CCL query
152     * @servers is optional. Defaults to biblioserver as found in koha-conf.xml
153     * $offset - If present, represents the number of records at the beginning to omit. Defaults to 0
154     * $max_results - if present, determines the maximum number of records to fetch. undef is All. defaults to undef.
155     * %options is optional. (e.g. "skip_normalize" allows you to skip changing : to = )
156
157
158 =item C<Return:>
159
160     Returns an array consisting of three elements
161     * $error is undefined unless an error is detected
162     * $results is a reference to an array of records.
163     * $total_hits is the number of hits that would have been returned with no limit
164
165     If an error is returned the two other return elements are undefined. If error itself is undefined
166     the other two elements are always defined
167
168 =item C<usage in the script:>
169
170 =back
171
172 my ( $error, $marcresults, $total_hits ) = SimpleSearch($query);
173
174 if (defined $error) {
175     $template->param(query_error => $error);
176     warn "error: ".$error;
177     output_html_with_http_headers $input, $cookie, $template->output;
178     exit;
179 }
180
181 my $hits = @{$marcresults};
182 my @results;
183
184 for my $r ( @{$marcresults} ) {
185     my $marcrecord = MARC::File::USMARC::decode($r);
186     my $biblio = TransformMarcToKoha($marcrecord,q{});
187
188     #build the iarray of hashs for the template.
189     push @results, {
190         title           => $biblio->{'title'},
191         subtitle        => $biblio->{'subtitle'},
192         biblionumber    => $biblio->{'biblionumber'},
193         author          => $biblio->{'author'},
194         publishercode   => $biblio->{'publishercode'},
195         publicationyear => $biblio->{'publicationyear'},
196         };
197
198 }
199
200 $template->param(result=>\@results);
201
202 =cut
203
204 sub SimpleSearch {
205     my ( $query, $offset, $max_results, $servers, %options )  = @_;
206
207     return ( 'No query entered', undef, undef ) unless $query;
208     # FIXME hardcoded value. See catalog/search.pl & opac-search.pl too.
209     my @servers = defined ( $servers ) ? @$servers : ( 'biblioserver' );
210     my @zoom_queries;
211     my @tmpresults;
212     my @zconns;
213     my $results = [];
214     my $total_hits = 0;
215
216     # Initialize & Search Zebra
217     for ( my $i = 0 ; $i < @servers ; $i++ ) {
218         eval {
219             $zconns[$i] = C4::Context->Zconn( $servers[$i], 1 );
220             $query =~ s/:/=/g unless $options{skip_normalize};
221             $zoom_queries[$i] = ZOOM::Query::CCL2RPN->new( $query, $zconns[$i]);
222             $tmpresults[$i] = $zconns[$i]->search( $zoom_queries[$i] );
223
224             # error handling
225             my $error =
226                 $zconns[$i]->errmsg() . " ("
227               . $zconns[$i]->errcode() . ") "
228               . $zconns[$i]->addinfo() . " "
229               . $zconns[$i]->diagset();
230
231             return ( $error, undef, undef ) if $zconns[$i]->errcode();
232         };
233         if ($@) {
234
235             # caught a ZOOM::Exception
236             my $error =
237                 $@->message() . " ("
238               . $@->code() . ") "
239               . $@->addinfo() . " "
240               . $@->diagset();
241             warn $error." for query: $query";
242             return ( $error, undef, undef );
243         }
244     }
245
246     _ZOOM_event_loop(
247         \@zconns,
248         \@tmpresults,
249         sub {
250             my ($i, $size) = @_;
251             my $first_record = defined($offset) ? $offset + 1 : 1;
252             my $hits = $tmpresults[ $i - 1 ]->size();
253             $total_hits += $hits;
254             my $last_record = $hits;
255             if ( defined $max_results && $offset + $max_results < $hits ) {
256                 $last_record = $offset + $max_results;
257             }
258
259             for my $j ( $first_record .. $last_record ) {
260                 my $record = eval {
261                   $tmpresults[ $i - 1 ]->record( $j - 1 )->raw()
262                   ;    # 0 indexed
263                 };
264                 push @{$results}, $record if defined $record;
265             }
266         }
267     );
268
269     foreach my $zoom_query (@zoom_queries) {
270         $zoom_query->destroy();
271     }
272
273     return ( undef, $results, $total_hits );
274 }
275
276 =head2 getRecords
277
278 ( undef, $results_hashref, \@facets_loop ) = getRecords (
279
280         $koha_query,       $simple_query, $sort_by_ref,    $servers_ref,
281         $results_per_page, $offset,       $branches,       $itemtypes,
282         $query_type,       $scan,         $opac
283     );
284
285 The all singing, all dancing, multi-server, asynchronous, scanning,
286 searching, record nabbing, facet-building
287
288 See verbose embedded documentation.
289
290 =cut
291
292 sub getRecords {
293     my (
294         $koha_query,       $simple_query, $sort_by_ref,    $servers_ref,
295         $results_per_page, $offset,       $branches,         $itemtypes,
296         $query_type,       $scan,         $opac
297     ) = @_;
298
299     my @servers = @$servers_ref;
300     my @sort_by = @$sort_by_ref;
301     $offset = 0 if $offset < 0;
302
303     # Initialize variables for the ZOOM connection and results object
304     my @zconns;
305     my @results;
306     my $results_hashref = ();
307
308     # TODO simplify this structure ( { branchcode => $branchname } is enought) and remove this parameter
309     $branches ||= { map { $_->branchcode => { branchname => $_->branchname } } Koha::Libraries->search };
310
311     # Initialize variables for the faceted results objects
312     my $facets_counter = {};
313     my $facets_info    = {};
314     my $facets         = getFacets();
315
316     my @facets_loop;    # stores the ref to array of hashes for template facets loop
317
318     ### LOOP THROUGH THE SERVERS
319     for ( my $i = 0 ; $i < @servers ; $i++ ) {
320         $zconns[$i] = C4::Context->Zconn( $servers[$i], 1 );
321
322 # perform the search, create the results objects
323 # if this is a local search, use the $koha-query, if it's a federated one, use the federated-query
324         my $query_to_use = ($servers[$i] =~ /biblioserver/) ? $koha_query : $simple_query;
325
326         #$query_to_use = $simple_query if $scan;
327         warn $simple_query if ( $scan and $DEBUG );
328
329         # Check if we've got a query_type defined, if so, use it
330         eval {
331             if ($query_type) {
332                 if ($query_type =~ /^ccl/) {
333                     $query_to_use =~ s/\:/\=/g;    # change : to = last minute (FIXME)
334                     $results[$i] = $zconns[$i]->search(ZOOM::Query::CCL2RPN->new($query_to_use, $zconns[$i]));
335                 } elsif ($query_type =~ /^cql/) {
336                     $results[$i] = $zconns[$i]->search(ZOOM::Query::CQL->new($query_to_use, $zconns[$i]));
337                 } elsif ($query_type =~ /^pqf/) {
338                     $results[$i] = $zconns[$i]->search(ZOOM::Query::PQF->new($query_to_use, $zconns[$i]));
339                 } else {
340                     warn "Unknown query_type '$query_type'.  Results undetermined.";
341                 }
342             } elsif ($scan) {
343                     $results[$i] = $zconns[$i]->scan(  ZOOM::Query::CCL2RPN->new($query_to_use, $zconns[$i]));
344             } else {
345                     $results[$i] = $zconns[$i]->search(ZOOM::Query::CCL2RPN->new($query_to_use, $zconns[$i]));
346             }
347         };
348         if ($@) {
349             warn "WARNING: query problem with $query_to_use " . $@;
350         }
351
352         # Concatenate the sort_by limits and pass them to the results object
353         # Note: sort will override rank
354         my $sort_by;
355         foreach my $sort (@sort_by) {
356             if ( $sort eq "author_az" || $sort eq "author_asc" ) {
357                 $sort_by .= "1=1003 <i ";
358             }
359             elsif ( $sort eq "author_za" || $sort eq "author_dsc" ) {
360                 $sort_by .= "1=1003 >i ";
361             }
362             elsif ( $sort eq "popularity_asc" ) {
363                 $sort_by .= "1=9003 <i ";
364             }
365             elsif ( $sort eq "popularity_dsc" ) {
366                 $sort_by .= "1=9003 >i ";
367             }
368             elsif ( $sort eq "call_number_asc" ) {
369                 $sort_by .= "1=8007  <i ";
370             }
371             elsif ( $sort eq "call_number_dsc" ) {
372                 $sort_by .= "1=8007 >i ";
373             }
374             elsif ( $sort eq "pubdate_asc" ) {
375                 $sort_by .= "1=31 <i ";
376             }
377             elsif ( $sort eq "pubdate_dsc" ) {
378                 $sort_by .= "1=31 >i ";
379             }
380             elsif ( $sort eq "acqdate_asc" ) {
381                 $sort_by .= "1=32 <i ";
382             }
383             elsif ( $sort eq "acqdate_dsc" ) {
384                 $sort_by .= "1=32 >i ";
385             }
386             elsif ( $sort eq "title_az" || $sort eq "title_asc" ) {
387                 $sort_by .= "1=4 <i ";
388             }
389             elsif ( $sort eq "title_za" || $sort eq "title_dsc" ) {
390                 $sort_by .= "1=4 >i ";
391             }
392             else {
393                 warn "Ignoring unrecognized sort '$sort' requested" if $sort_by;
394             }
395         }
396         if ( $sort_by && !$scan && $results[$i] ) {
397             if ( $results[$i]->sort( "yaz", $sort_by ) < 0 ) {
398                 warn "WARNING sort $sort_by failed";
399             }
400         }
401     }    # finished looping through servers
402
403     # The big moment: asynchronously retrieve results from all servers
404         _ZOOM_event_loop(
405             \@zconns,
406             \@results,
407             sub {
408                 my ( $i, $size ) = @_;
409                 my $results_hash;
410
411                 # loop through the results
412                 $results_hash->{'hits'} = $size;
413                 my $times;
414                 if ( $offset + $results_per_page <= $size ) {
415                     $times = $offset + $results_per_page;
416                 }
417                 else {
418                     $times = $size;
419                 }
420
421                 for ( my $j = $offset ; $j < $times ; $j++ ) {
422                     my $record;
423
424                     ## Check if it's an index scan
425                     if ($scan) {
426                         my ( $term, $occ ) = $results[ $i - 1 ]->display_term($j);
427
428                  # here we create a minimal MARC record and hand it off to the
429                  # template just like a normal result ... perhaps not ideal, but
430                  # it works for now
431                         my $tmprecord = MARC::Record->new();
432                         $tmprecord->encoding('UTF-8');
433                         my $tmptitle;
434                         my $tmpauthor;
435
436                 # the minimal record in author/title (depending on MARC flavour)
437                         if ( C4::Context->preference("marcflavour") eq
438                             "UNIMARC" )
439                         {
440                             $tmptitle = MARC::Field->new(
441                                 '200', ' ', ' ',
442                                 a => $term,
443                                 f => $occ
444                             );
445                             $tmprecord->append_fields($tmptitle);
446                         }
447                         else {
448                             $tmptitle =
449                               MARC::Field->new( '245', ' ', ' ', a => $term, );
450                             $tmpauthor =
451                               MARC::Field->new( '100', ' ', ' ', a => $occ, );
452                             $tmprecord->append_fields($tmptitle);
453                             $tmprecord->append_fields($tmpauthor);
454                         }
455                         $results_hash->{'RECORDS'}[$j] =
456                           $tmprecord->as_usmarc();
457                     }
458
459                     # not an index scan
460                     else {
461                         $record = $results[ $i - 1 ]->record($j)->raw();
462                         # warn "RECORD $j:".$record;
463                         $results_hash->{'RECORDS'}[$j] = $record;
464                     }
465
466                 }
467                 $results_hashref->{ $servers[ $i - 1 ] } = $results_hash;
468
469                 # Fill the facets while we're looping, but only for the
470                 # biblioserver and not for a scan
471                 if ( !$scan && $servers[ $i - 1 ] =~ /biblioserver/ ) {
472                     $facets_counter = GetFacets( $results[ $i - 1 ] );
473                     $facets_info    = _get_facets_info( $facets );
474                 }
475
476                 # BUILD FACETS
477                 if ( $servers[ $i - 1 ] =~ /biblioserver/ ) {
478                     for my $link_value (
479                         sort { $a cmp $b } keys %$facets_counter
480                       )
481                     {
482                         my @this_facets_array;
483                         for my $one_facet (
484                             sort {
485                                 $facets_counter->{$link_value}
486                                   ->{$b} <=> $facets_counter->{$link_value}
487                                   ->{$a}
488                             } keys %{ $facets_counter->{$link_value} }
489                           )
490                         {
491 # Sanitize the link value : parenthesis, question and exclamation mark will cause errors with CCL
492                             my $facet_link_value = $one_facet;
493                             $facet_link_value =~ s/[()!?¡¿؟]/ /g;
494
495                             # fix the length that will display in the label,
496                             my $facet_label_value = $one_facet;
497                             my $facet_max_length  = C4::Context->preference(
498                                 'FacetLabelTruncationLength')
499                               || 20;
500                             $facet_label_value =
501                               substr( $one_facet, 0, $facet_max_length )
502                               . "..."
503                               if length($facet_label_value) >
504                                   $facet_max_length;
505
506                         # if it's a branch, label by the name, not the code,
507                             if ( $link_value =~ /branch/ ) {
508                                 if (   defined $branches
509                                     && ref($branches) eq "HASH"
510                                     && defined $branches->{$one_facet}
511                                     && ref( $branches->{$one_facet} ) eq
512                                     "HASH" )
513                                 {
514                                     $facet_label_value =
515                                       $branches->{$one_facet}
516                                       ->{'branchname'};
517                                 }
518                                 else {
519                                     $facet_label_value = "*";
520                                 }
521                             }
522
523                       # if it's a itemtype, label by the name, not the code,
524                             if ( $link_value =~ /itype/ ) {
525                                 if (   defined $itemtypes
526                                     && ref($itemtypes) eq "HASH"
527                                     && defined $itemtypes->{$one_facet}
528                                     && ref( $itemtypes->{$one_facet} ) eq
529                                     "HASH" )
530                                 {
531                                     $facet_label_value =
532                                       $itemtypes->{$one_facet}
533                                       ->{translated_description};
534                                 }
535                             }
536
537            # also, if it's a location code, use the name instead of the code
538                             if ( $link_value =~ /location/ ) {
539                                 # TODO Retrieve all authorised values at once, instead of 1 query per entry
540                                 my $av = Koha::AuthorisedValues->search({ category => 'LOC', authorised_value => $one_facet });
541                                 $facet_label_value = $av->count ? $av->next->opac_description : '';
542                             }
543
544                             # also, if it's a collection code, use the name instead of the code
545                             if ( $link_value =~ /ccode/ ) {
546                                 # TODO Retrieve all authorised values at once, instead of 1 query per entry
547                                 my $av = Koha::AuthorisedValues->search({ category => 'CCODE', authorised_value => $one_facet });
548                                 $facet_label_value = $av->count ? $av->next->opac_description : '';
549                             }
550
551             # but we're down with the whole label being in the link's title.
552                             push @this_facets_array,
553                               {
554                                 facet_count =>
555                                   $facets_counter->{$link_value}
556                                   ->{$one_facet},
557                                 facet_label_value => $facet_label_value,
558                                 facet_title_value => $one_facet,
559                                 facet_link_value  => $facet_link_value,
560                                 type_link_value   => $link_value,
561                               }
562                               if ($facet_label_value);
563                         }
564
565                         push @facets_loop,
566                           {
567                             type_link_value => $link_value,
568                             type_id         => $link_value . "_id",
569                             "type_label_"
570                               . $facets_info->{$link_value}->{'label_value'} =>
571                               1,
572                             facets     => \@this_facets_array,
573                           }
574                           unless (
575                             (
576                                 $facets_info->{$link_value}->{'label_value'} =~
577                                 /Libraries/
578                             )
579                             and ( Koha::Libraries->search->count == 1 )
580                           );
581                     }
582                 }
583             }
584         );
585
586     # This sorts the facets into alphabetical order
587     if (@facets_loop) {
588         foreach my $f (@facets_loop) {
589             if( C4::Context->preference('FacetOrder') eq 'Alphabetical' ){
590                 $f->{facets} =
591                     [ sort { uc($a->{facet_label_value}) cmp uc($b->{facet_label_value}) } @{ $f->{facets} } ];
592             }
593         }
594     }
595
596     return ( undef, $results_hashref, \@facets_loop );
597 }
598
599 sub GetFacets {
600
601     my $rs = shift;
602     my $facets;
603
604     my $use_zebra_facets = C4::Context->config('use_zebra_facets') // 0;
605
606     if ( $use_zebra_facets ) {
607         $facets = _get_facets_from_zebra( $rs );
608     } else {
609         $facets = _get_facets_from_records( $rs );
610     }
611
612     return $facets;
613 }
614
615 sub _get_facets_from_records {
616
617     my $rs = shift;
618
619     my $facets_maxrecs = C4::Context->preference('maxRecordsForFacets') // 20;
620     my $facets_config  = getFacets();
621     my $facets         = {};
622     my $size           = $rs->size();
623     my $jmax           = $size > $facets_maxrecs
624                             ? $facets_maxrecs
625                             : $size;
626
627     for ( my $j = 0 ; $j < $jmax ; $j++ ) {
628
629         my $marc_record = new_record_from_zebra (
630                 'biblioserver',
631                 $rs->record( $j )->raw()
632         );
633
634         if ( ! defined $marc_record ) {
635             warn "ERROR DECODING RECORD - $@: " .
636                 $rs->record( $j )->raw();
637             next;
638         }
639
640         _get_facets_data_from_record( $marc_record, $facets_config, $facets );
641     }
642
643     return $facets;
644 }
645
646 =head2 _get_facets_data_from_record
647
648     C4::Search::_get_facets_data_from_record( $marc_record, $facets, $facets_counter );
649
650 Internal function that extracts facets information from a MARC::Record object
651 and populates $facets_counter for using in getRecords.
652
653 $facets is expected to be filled with C4::Koha::getFacets output (i.e. the configured
654 facets for Zebra).
655
656 =cut
657
658 sub _get_facets_data_from_record {
659
660     my ( $marc_record, $facets, $facets_counter ) = @_;
661
662     for my $facet (@$facets) {
663
664         my @used_datas = ();
665
666         foreach my $tag ( @{ $facet->{ tags } } ) {
667
668             # tag number is the first three digits
669             my $tag_num          = substr( $tag, 0, 3 );
670             # subfields are the remainder
671             my $subfield_letters = substr( $tag, 3 );
672
673             my @fields = $marc_record->field( $tag_num );
674             foreach my $field (@fields) {
675                 # If $field->indicator(1) eq 'z', it means it is a 'see from'
676                 # field introduced because of IncludeSeeFromInSearches, so skip it
677                 next if $field->indicator(1) eq 'z';
678
679                 my $data = $field->as_string( $subfield_letters, $facet->{ sep } );
680                 $data =~ s/\s*(?<!\p{Uppercase})[.\-,;]*\s*$//;
681
682                 unless ( grep { $_ eq $data } @used_datas ) {
683                     push @used_datas, $data;
684                     $facets_counter->{ $facet->{ idx } }->{ $data }++;
685                 }
686             }
687         }
688     }
689 }
690
691 =head2 _get_facets_from_zebra
692
693     my $facets = _get_facets_from_zebra( $result_set )
694
695 Retrieves facets for a specified result set. It loops through the facets defined
696 in C4::Koha::getFacets and returns a hash with the following structure:
697
698    {  facet_idx => {
699             facet_value => count
700       },
701       ...
702    }
703
704 =cut
705
706 sub _get_facets_from_zebra {
707
708     my $rs = shift;
709
710     # save current elementSetName
711     my $elementSetName = $rs->option( 'elementSetName' );
712
713     my $facets_loop = getFacets();
714     my $facets_data  = {};
715     # loop through defined facets and fill the facets hashref
716     foreach my $facet ( @$facets_loop ) {
717
718         my $idx = $facet->{ idx };
719         my $sep = $facet->{ sep };
720         my $facet_values = _get_facet_from_result_set( $idx, $rs, $sep );
721         if ( $facet_values ) {
722             # we've actually got a result
723             $facets_data->{ $idx } = $facet_values;
724         }
725     }
726     # set elementSetName to its previous value to avoid side effects
727     $rs->option( elementSetName => $elementSetName );
728
729     return $facets_data;
730 }
731
732 =head2 _get_facet_from_result_set
733
734     my $facet_values =
735         C4::Search::_get_facet_from_result_set( $facet_idx, $result_set, $sep )
736
737 Internal function that extracts facet information for a specific index ($facet_idx) and
738 returns a hash containing facet values and count:
739
740     {
741         $facet_value => $count ,
742         ...
743     }
744
745 Warning: this function has the side effect of changing the elementSetName for the result
746 set. It is a helper function for the main loop, which takes care of backing it up for
747 restoring.
748
749 =cut
750
751 sub _get_facet_from_result_set {
752
753     my $facet_idx = shift;
754     my $rs        = shift;
755     my $sep       = shift;
756
757     my $internal_sep  = '<*>';
758     my $facetMaxCount = C4::Context->preference('FacetMaxCount') // 20;
759
760     return if ( ! defined $facet_idx || ! defined $rs );
761     # zebra's facet element, untokenized index
762     my $facet_element = 'zebra::facet::' . $facet_idx . ':0:' . $facetMaxCount;
763     # configure zebra results for retrieving the desired facet
764     $rs->option( elementSetName => $facet_element );
765     # get the facet record from result set
766     my $facet = $rs->record( 0 )->raw;
767     # if the facet has no restuls...
768     return if !defined $facet;
769     # TODO: benchmark DOM vs. SAX performance
770     my $facet_dom = XML::LibXML->load_xml(
771       string => ($facet)
772     );
773     my @terms = $facet_dom->getElementsByTagName('term');
774     return if ! @terms;
775
776     my $facets = {};
777     foreach my $term ( @terms ) {
778         my $facet_value = $term->textContent;
779         $facet_value =~ s/\s*(?<!\p{Uppercase})[.\-,;]*\s*$//;
780         $facet_value =~ s/\Q$internal_sep\E/$sep/ if defined $sep;
781         $facets->{ $facet_value } += $term->getAttribute( 'occur' );
782     }
783
784     return $facets;
785 }
786
787 =head2 _get_facets_info
788
789     my $facets_info = C4::Search::_get_facets_info( $facets )
790
791 Internal function that extracts facets information and properly builds
792 the data structure needed to render facet labels.
793
794 =cut
795
796 sub _get_facets_info {
797
798     my $facets = shift;
799
800     my $facets_info = {};
801
802     for my $facet ( @$facets ) {
803         $facets_info->{ $facet->{ idx } }->{ label_value } = $facet->{ label };
804     }
805
806     return $facets_info;
807 }
808
809 # TRUNCATION
810 sub _detect_truncation {
811     my ( $operand, $index ) = @_;
812     my ( @nontruncated, @righttruncated, @lefttruncated, @rightlefttruncated,
813         @regexpr );
814     $operand =~ s/^ //g;
815     my @wordlist = split( /\s/, $operand );
816     foreach my $word (@wordlist) {
817         if ( $word =~ s/^\*([^\*]+)\*$/$1/ ) {
818             push @rightlefttruncated, $word;
819         }
820         elsif ( $word =~ s/^\*([^\*]+)$/$1/ ) {
821             push @lefttruncated, $word;
822         }
823         elsif ( $word =~ s/^([^\*]+)\*$/$1/ ) {
824             push @righttruncated, $word;
825         }
826         elsif ( index( $word, "*" ) < 0 ) {
827             push @nontruncated, $word;
828         }
829         else {
830             push @regexpr, $word;
831         }
832     }
833     return (
834         \@nontruncated,       \@righttruncated, \@lefttruncated,
835         \@rightlefttruncated, \@regexpr
836     );
837 }
838
839 # STEMMING
840 sub _build_stemmed_operand {
841     my ($operand,$lang) = @_;
842     require Lingua::Stem::Snowball ;
843     my $stemmed_operand=q{};
844
845     # Stemmer needs language
846     return $operand unless $lang;
847
848     # If operand contains a digit, it is almost certainly an identifier, and should
849     # not be stemmed.  This is particularly relevant for ISBNs and ISSNs, which
850     # can contain the letter "X" - for example, _build_stemmend_operand would reduce
851     # "014100018X" to "x ", which for a MARC21 database would bring up irrelevant
852     # results (e.g., "23 x 29 cm." from the 300$c).  Bug 2098.
853     return $operand if $operand =~ /\d/;
854
855 # FIXME: the locale should be set based on the user's language and/or search choice
856     #warn "$lang";
857     # Make sure we only use the first two letters from the language code
858     $lang = lc(substr($lang, 0, 2));
859     # The language codes for the two variants of Norwegian will now be "nb" and "nn",
860     # none of which Lingua::Stem::Snowball can use, so we need to "translate" them
861     if ($lang eq 'nb' || $lang eq 'nn') {
862       $lang = 'no';
863     }
864     my $stemmer = Lingua::Stem::Snowball->new( lang => $lang,
865                                                encoding => "UTF-8" );
866
867     my @words = split( / /, $operand );
868     my @stems = $stemmer->stem(\@words);
869     for my $stem (@stems) {
870         $stemmed_operand .= "$stem";
871         $stemmed_operand .= "?"
872           unless ( $stem =~ /(and$|or$|not$)/ ) || ( length($stem) < 3 );
873         $stemmed_operand .= " ";
874     }
875     warn "STEMMED OPERAND: $stemmed_operand" if $DEBUG;
876     return $stemmed_operand;
877 }
878
879 # FIELD WEIGHTING
880 sub _build_weighted_query {
881
882 # FIELD WEIGHTING - This is largely experimental stuff. What I'm committing works
883 # pretty well but could work much better if we had a smarter query parser
884     my ( $operand, $stemmed_operand, $index ) = @_;
885     my $stemming      = C4::Context->preference("QueryStemming")     || 0;
886     my $weight_fields = C4::Context->preference("QueryWeightFields") || 0;
887     my $fuzzy_enabled = C4::Context->preference("QueryFuzzy")        || 0;
888     $operand =~ s/"/ /g;    # Bug 7518: searches with quotation marks don't work
889
890     my $weighted_query .= "(rk=(";    # Specifies that we're applying rank
891
892     # Keyword, or, no index specified
893     if ( ( $index eq 'kw' ) || ( !$index ) ) {
894         $weighted_query .=
895           "Title-cover,ext,r1=\"$operand\"";    # exact title-cover
896         $weighted_query .= " or ti,ext,r2=\"$operand\"";    # exact title
897         $weighted_query .= " or Title-cover,phr,r3=\"$operand\"";    # phrase title
898         $weighted_query .= " or ti,wrdl,r4=\"$operand\"";    # words in title
899           #$weighted_query .= " or any,ext,r4=$operand";               # exact any
900           #$weighted_query .=" or kw,wrdl,r5=\"$operand\"";            # word list any
901         $weighted_query .= " or wrdl,fuzzy,r8=\"$operand\""
902           if $fuzzy_enabled;    # add fuzzy, word list
903         $weighted_query .= " or wrdl,right-Truncation,r9=\"$stemmed_operand\""
904           if ( $stemming and $stemmed_operand )
905           ;                     # add stemming, right truncation
906         $weighted_query .= " or wrdl,r9=\"$operand\"";
907
908         # embedded sorting: 0 a-z; 1 z-a
909         # $weighted_query .= ") or (sort1,aut=1";
910     }
911
912     # Barcode searches should skip this process
913     elsif ( $index eq 'bc' ) {
914         $weighted_query .= "bc=\"$operand\"";
915     }
916
917     # Authority-number searches should skip this process
918     elsif ( $index eq 'an' ) {
919         $weighted_query .= "an=\"$operand\"";
920     }
921
922     # If the index is numeric, don't autoquote it.
923     elsif ( $index =~ /,st-numeric$/ ) {
924         $weighted_query .= " $index=$operand";
925     }
926
927     # If the index already has more than one qualifier, wrap the operand
928     # in quotes and pass it back (assumption is that the user knows what they
929     # are doing and won't appreciate us mucking up their query
930     elsif ( $index =~ ',' ) {
931         $weighted_query .= " $index=\"$operand\"";
932     }
933
934     #TODO: build better cases based on specific search indexes
935     else {
936         $weighted_query .= " $index,ext,r1=\"$operand\"";    # exact index
937           #$weighted_query .= " or (title-sort-az=0 or $index,startswithnt,st-word,r3=$operand #)";
938         $weighted_query .= " or $index,phr,r3=\"$operand\"";    # phrase index
939         $weighted_query .= " or $index,wrdl,r6=\"$operand\"";    # word list index
940         $weighted_query .= " or $index,wrdl,fuzzy,r8=\"$operand\""
941           if $fuzzy_enabled;    # add fuzzy, word list
942         $weighted_query .= " or $index,wrdl,rt,r9=\"$stemmed_operand\""
943           if ( $stemming and $stemmed_operand );    # add stemming, right truncation
944     }
945
946     $weighted_query .= "))";                       # close rank specification
947     return $weighted_query;
948 }
949
950 =head2 getIndexes
951
952 Return an array with available indexes.
953
954 =cut
955
956 sub getIndexes{
957     my @indexes = (
958                     # biblio indexes
959                     'ab',
960                     'Abstract',
961                     'acqdate',
962                     'allrecords',
963                     'an',
964                     'Any',
965                     'at',
966                     'arl',
967                     'arp',
968                     'au',
969                     'aub',
970                     'aud',
971                     'audience',
972                     'auo',
973                     'aut',
974                     'Author',
975                     'Author-in-order ',
976                     'Author-personal-bibliography',
977                     'Authority-Number',
978                     'authtype',
979                     'bc',
980                     'Bib-level',
981                     'biblionumber',
982                     'bio',
983                     'biography',
984                     'callnum',
985                     'cfn',
986                     'Chronological-subdivision',
987                     'cn-bib-source',
988                     'cn-bib-sort',
989                     'cn-class',
990                     'cn-item',
991                     'cn-prefix',
992                     'cn-suffix',
993                     'cpn',
994                     'Code-institution',
995                     'Conference-name',
996                     'Conference-name-heading',
997                     'Conference-name-see',
998                     'Conference-name-seealso',
999                     'Content-type',
1000                     'Control-number',
1001                     'copydate',
1002                     'Corporate-name',
1003                     'Corporate-name-heading',
1004                     'Corporate-name-see',
1005                     'Corporate-name-seealso',
1006                     'Country-publication',
1007                     'ctype',
1008                     'curriculum',
1009                     'date-entered-on-file',
1010                     'Date-of-acquisition',
1011                     'Date-of-publication',
1012                     'Date-time-last-modified',
1013                     'Dewey-classification',
1014                     'Dissertation-information',
1015                     'diss',
1016                     'dtlm',
1017                     'EAN',
1018                     'extent',
1019                     'fic',
1020                     'fiction',
1021                     'Form-subdivision',
1022                     'format',
1023                     'Geographic-subdivision',
1024                     'he',
1025                     'Heading',
1026                     'Heading-use-main-or-added-entry',
1027                     'Heading-use-series-added-entry ',
1028                     'Heading-use-subject-added-entry',
1029                     'Host-item',
1030                     'id-other',
1031                     'ident',
1032                     'Identifier-standard',
1033                     'Illustration-code',
1034                     'Index-term-genre',
1035                     'Index-term-uncontrolled',
1036                     'Interest-age-level',
1037                     'Interest-grade-level',
1038                     'ISBN',
1039                     'isbn',
1040                     'ISSN',
1041                     'issn',
1042                     'itemtype',
1043                     'kw',
1044                     'Koha-Auth-Number',
1045                     'l-format',
1046                     'language',
1047                     'language-original',
1048                     'lc-card',
1049                     'LC-card-number',
1050                     'lcn',
1051                     'lex',
1052                     'lexile-number',
1053                     'llength',
1054                     'ln',
1055                     'ln-audio',
1056                     'ln-subtitle',
1057                     'Local-classification',
1058                     'Local-number',
1059                     'Match-heading',
1060                     'Match-heading-see-from',
1061                     'Material-type',
1062                     'mc-itemtype',
1063                     'mc-rtype',
1064                     'mus',
1065                     'name',
1066                     'Music-number',
1067                     'Name-geographic',
1068                     'Name-geographic-heading',
1069                     'Name-geographic-see',
1070                     'Name-geographic-seealso',
1071                     'nb',
1072                     'Note',
1073                     'notes',
1074                     'ns',
1075                     'nt',
1076                     'Other-control-number',
1077                     'pb',
1078                     'Personal-name',
1079                     'Personal-name-heading',
1080                     'Personal-name-see',
1081                     'Personal-name-seealso',
1082                     'pl',
1083                     'Place-publication',
1084                     'pn',
1085                     'popularity',
1086                     'pubdate',
1087                     'Publisher',
1088                     'Provider',
1089                     'pv',
1090                     'Reading-grade-level',
1091                     'Record-control-number',
1092                     'rcn',
1093                     'Record-type',
1094                     'rtype',
1095                     'se',
1096                     'See',
1097                     'See-also',
1098                     'sn',
1099                     'Stock-number',
1100                     'su',
1101                     'Subject',
1102                     'Subject-heading-thesaurus',
1103                     'Subject-name-personal',
1104                     'Subject-subdivision',
1105                     'Summary',
1106                     'Suppress',
1107                     'su-geo',
1108                     'su-na',
1109                     'su-to',
1110                     'su-ut',
1111                     'ut',
1112                     'Term-genre-form',
1113                     'Term-genre-form-heading',
1114                     'Term-genre-form-see',
1115                     'Term-genre-form-seealso',
1116                     'ti',
1117                     'Title',
1118                     'Title-cover',
1119                     'Title-series',
1120                     'Title-uniform',
1121                     'Title-uniform-heading',
1122                     'Title-uniform-see',
1123                     'Title-uniform-seealso',
1124                     'totalissues',
1125                     'yr',
1126
1127                     # items indexes
1128                     'acqsource',
1129                     'barcode',
1130                     'bc',
1131                     'branch',
1132                     'ccode',
1133                     'classification-source',
1134                     'cn-sort',
1135                     'coded-location-qualifier',
1136                     'copynumber',
1137                     'damaged',
1138                     'datelastborrowed',
1139                     'datelastseen',
1140                     'holdingbranch',
1141                     'homebranch',
1142                     'issues',
1143                     'item',
1144                     'itemnumber',
1145                     'itype',
1146                     'Local-classification',
1147                     'location',
1148                     'lost',
1149                     'materials-specified',
1150                     'mc-ccode',
1151                     'mc-itype',
1152                     'mc-loc',
1153                     'notforloan',
1154                     'Number-local-acquisition',
1155                     'onloan',
1156                     'price',
1157                     'renewals',
1158                     'replacementprice',
1159                     'replacementpricedate',
1160                     'reserves',
1161                     'restricted',
1162                     'stack',
1163                     'stocknumber',
1164                     'inv',
1165                     'uri',
1166                     'withdrawn',
1167
1168                     # subject related
1169                   );
1170
1171     return \@indexes;
1172 }
1173
1174 =head2 buildQuery
1175
1176 ( $error, $query,
1177 $simple_query, $query_cgi,
1178 $query_desc, $limit,
1179 $limit_cgi, $limit_desc,
1180 $query_type ) = buildQuery ( $operators, $operands, $indexes, $limits, $sort_by, $scan, $lang);
1181
1182 Build queries and limits in CCL, CGI, Human,
1183 handle truncation, stemming, field weighting, fuzziness, etc.
1184
1185 See verbose embedded documentation.
1186
1187
1188 =cut
1189
1190 sub buildQuery {
1191     my ( $operators, $operands, $indexes, $limits, $sort_by, $scan, $lang) = @_;
1192     warn "---------\nEnter buildQuery\n---------" if $DEBUG;
1193
1194     my $query_desc;
1195
1196     # dereference
1197     my @operators = $operators ? @$operators : ();
1198     my @indexes   = $indexes   ? @$indexes   : ();
1199     my @operands  = $operands  ? @$operands  : ();
1200     my @limits    = $limits    ? @$limits    : ();
1201     my @sort_by   = $sort_by   ? @$sort_by   : ();
1202
1203     my $stemming         = C4::Context->preference("QueryStemming")        || 0;
1204     my $auto_truncation  = C4::Context->preference("QueryAutoTruncate")    || 0;
1205     my $weight_fields    = C4::Context->preference("QueryWeightFields")    || 0;
1206     my $fuzzy_enabled    = C4::Context->preference("QueryFuzzy")           || 0;
1207
1208     my $query        = $operands[0] // "";
1209     my $simple_query = $operands[0];
1210
1211     # initialize the variables we're passing back
1212     my $query_cgi;
1213     my $query_type;
1214
1215     my $limit;
1216     my $limit_cgi;
1217     my $limit_desc;
1218
1219     my $cclq       = 0;
1220     my $cclindexes = getIndexes();
1221     if ( $query !~ /\s*(ccl=|pqf=|cql=)/ ) {
1222         while ( !$cclq && $query =~ /(?:^|\W)([\w-]+)(,[\w-]+)*[:=]/g ) {
1223             my $dx = lc($1);
1224             $cclq = grep { lc($_) eq $dx } @$cclindexes;
1225         }
1226         $query = "ccl=$query" if $cclq;
1227     }
1228
1229 # for handling ccl, cql, pqf queries in diagnostic mode, skip the rest of the steps
1230 # DIAGNOSTIC ONLY!!
1231     if ( $query =~ /^ccl=/ ) {
1232         my $q=$';
1233         # This is needed otherwise ccl= and &limit won't work together, and
1234         # this happens when selecting a subject on the opac-detail page
1235         @limits = grep {!/^$/} @limits;
1236         my $original_q = $q; # without available part
1237         unless ( grep { $_ eq 'available' } @limits ) {
1238             $q =~ s| and \( \(allrecords,AlwaysMatches=''\) and \(not-onloan-count,st-numeric >= 1\) and \(lost,st-numeric=0\) \)||;
1239             $original_q = $q;
1240         }
1241         if ( @limits ) {
1242             if ( grep { $_ eq 'available' } @limits ) {
1243                 $q .= q| and ( (allrecords,AlwaysMatches='') and (not-onloan-count,st-numeric >= 1) and (lost,st-numeric=0) )|;
1244                 @limits = grep {!/^available$/} @limits;
1245             }
1246             $q .= ' and '.join(' and ', @limits) if @limits;
1247         }
1248         return ( undef, $q, $q, "q=ccl=".uri_escape_utf8($q), $original_q, '', '', '', 'ccl' );
1249     }
1250     if ( $query =~ /^cql=/ ) {
1251         return ( undef, $', $', "q=cql=".uri_escape_utf8($'), $', '', '', '', 'cql' );
1252     }
1253     if ( $query =~ /^pqf=/ ) {
1254         $query_desc = $';
1255         $query_cgi = "q=pqf=".uri_escape_utf8($');
1256         return ( undef, $', $', $query_cgi, $query_desc, '', '', '', 'pqf' );
1257     }
1258
1259     # pass nested queries directly
1260     # FIXME: need better handling of some of these variables in this case
1261     # Nested queries aren't handled well and this implementation is flawed and causes users to be
1262     # unable to search for anything containing () commenting out, will be rewritten for 3.4.0
1263 #    if ( $query =~ /(\(|\))/ ) {
1264 #        return (
1265 #            undef,              $query, $simple_query, $query_cgi,
1266 #            $query,             $limit, $limit_cgi,    $limit_desc,
1267 #            'ccl'
1268 #        );
1269 #    }
1270
1271 # Form-based queries are non-nested and fixed depth, so we can easily modify the incoming
1272 # query operands and indexes and add stemming, truncation, field weighting, etc.
1273 # Once we do so, we'll end up with a value in $query, just like if we had an
1274 # incoming $query from the user
1275     else {
1276         $query = ""
1277           ; # clear it out so we can populate properly with field-weighted, stemmed, etc. query
1278         my $previous_operand
1279           ;    # a flag used to keep track if there was a previous query
1280                # if there was, we can apply the current operator
1281                # for every operand
1282         for ( my $i = 0 ; $i <= @operands ; $i++ ) {
1283
1284             # COMBINE OPERANDS, INDEXES AND OPERATORS
1285             if ( ($operands[$i] // '') ne '' ) {
1286                 $operands[$i]=~s/^\s+//;
1287
1288               # A flag to determine whether or not to add the index to the query
1289                 my $indexes_set;
1290
1291 # If the user is sophisticated enough to specify an index, turn off field weighting, and stemming handling
1292                 if ( $operands[$i] =~ /\w(:|=)/ || $scan ) {
1293                     $weight_fields    = 0;
1294                     $stemming         = 0;
1295                 } else {
1296                     $operands[$i] =~ s/\?/{?}/g; # need to escape question marks
1297                 }
1298                 my $operand = $operands[$i];
1299                 my $index   = $indexes[$i] || 'kw';
1300
1301                 # Add index-specific attributes
1302
1303                 #Afaik, this 'yr' condition will only ever be met in the staff interface advanced search
1304                 #for "Publication date", since typing 'yr:YYYY' into the search box produces a CCL query,
1305                 #which is processed higher up in this sub. Other than that, year searches are typically
1306                 #handled as limits which are not processed her either.
1307
1308                 # Search ranges: Date of Publication, st-numeric
1309                 if ( $index =~ /(yr|st-numeric)/ ) {
1310                     #weight_fields/relevance search causes errors with date ranges
1311                     #In the case of YYYY-, it will only return records with a 'yr' of YYYY (not the range)
1312                     #In the case of YYYY-YYYY, it will return no results
1313                     $stemming = $auto_truncation = $weight_fields = $fuzzy_enabled = 0;
1314                 }
1315
1316                 # Date of Acquisition
1317                 elsif ( $index =~ /acqdate/ ) {
1318                     #stemming and auto_truncation would have zero impact since it already is YYYY-MM-DD format
1319                     #Weight_fields probably SHOULD be turned OFF, otherwise you'll get records floating to the
1320                       #top of the results just because they have lots of item records matching that date.
1321                     #Fuzzy actually only applies during _build_weighted_query, and is reset there anyway, so
1322                       #irrelevant here
1323                     $stemming = $auto_truncation = $weight_fields = $fuzzy_enabled = 0;
1324                 }
1325                 # ISBN,ISSN,Standard Number, don't need special treatment
1326                 elsif ( $index eq 'nb' || $index eq 'ns' || $index eq 'hi' ) {
1327                     (
1328                         $stemming,      $auto_truncation,
1329                         $weight_fields, $fuzzy_enabled
1330                     ) = ( 0, 0, 0, 0 );
1331
1332                     if ( $index eq 'nb' ) {
1333                         if ( C4::Context->preference("SearchWithISBNVariations") ) {
1334                             my @isbns = C4::Koha::GetVariationsOfISBN( $operand );
1335                             $operands[$i] = $operand =  '(nb=' . join(' OR nb=', @isbns) . ')';
1336                             $indexes[$i] = $index = 'kw';
1337                         }
1338                     }
1339                 }
1340
1341                 # Set default structure attribute (word list)
1342                 my $struct_attr = q{};
1343                 unless ( $indexes_set || $index =~ /,(st-|phr|ext|wrdl)/ || $index =~ /^(nb|ns)$/ ) {
1344                     $struct_attr = ",wrdl";
1345                 }
1346
1347                 # Some helpful index variants
1348                 my $index_plus       = $index . $struct_attr . ':';
1349                 my $index_plus_comma = $index . $struct_attr . ',';
1350
1351                 if ($auto_truncation){
1352                         unless ( $index =~ /,(st-|phr|ext)/ ) {
1353                                                 #FIXME only valid with LTR scripts
1354                                                 $operand=join(" ",map{
1355                                                                                         (index($_,"*")>0?"$_":"$_*")
1356                                                                                          }split (/\s+/,$operand));
1357                                                 warn $operand if $DEBUG;
1358                                         }
1359                                 }
1360
1361                 # Detect Truncation
1362                 my $truncated_operand = q{};
1363                 my( $nontruncated, $righttruncated, $lefttruncated,
1364                     $rightlefttruncated, $regexpr
1365                 ) = _detect_truncation( $operand, $index );
1366                 warn
1367 "TRUNCATION: NON:>@$nontruncated< RIGHT:>@$righttruncated< LEFT:>@$lefttruncated< RIGHTLEFT:>@$rightlefttruncated< REGEX:>@$regexpr<"
1368                   if $DEBUG;
1369
1370                 # Apply Truncation
1371                 if (
1372                     scalar(@$righttruncated) + scalar(@$lefttruncated) +
1373                     scalar(@$rightlefttruncated) > 0 )
1374                 {
1375
1376                # Don't field weight or add the index to the query, we do it here
1377                     $indexes_set = 1;
1378                     undef $weight_fields;
1379                     my $previous_truncation_operand;
1380                     if (scalar @$nontruncated) {
1381                         $truncated_operand .= "$index_plus @$nontruncated ";
1382                         $previous_truncation_operand = 1;
1383                     }
1384                     if (scalar @$righttruncated) {
1385                         $truncated_operand .= "and " if $previous_truncation_operand;
1386                         $truncated_operand .= $index_plus_comma . "rtrn:@$righttruncated ";
1387                         $previous_truncation_operand = 1;
1388                     }
1389                     if (scalar @$lefttruncated) {
1390                         $truncated_operand .= "and " if $previous_truncation_operand;
1391                         $truncated_operand .= $index_plus_comma . "ltrn:@$lefttruncated ";
1392                         $previous_truncation_operand = 1;
1393                     }
1394                     if (scalar @$rightlefttruncated) {
1395                         $truncated_operand .= "and " if $previous_truncation_operand;
1396                         $truncated_operand .= $index_plus_comma . "rltrn:@$rightlefttruncated ";
1397                         $previous_truncation_operand = 1;
1398                     }
1399                 }
1400                 $operand = $truncated_operand if $truncated_operand;
1401                 warn "TRUNCATED OPERAND: >$truncated_operand<" if $DEBUG;
1402
1403                 # Handle Stemming
1404                 my $stemmed_operand = q{};
1405                 $stemmed_operand = _build_stemmed_operand($operand, $lang)
1406                                                                                 if $stemming;
1407
1408                 warn "STEMMED OPERAND: >$stemmed_operand<" if $DEBUG;
1409
1410                 # Handle Field Weighting
1411                 my $weighted_operand = q{};
1412                 if ($weight_fields) {
1413                     $weighted_operand = _build_weighted_query( $operand, $stemmed_operand, $index );
1414                     $operand = $weighted_operand;
1415                     $indexes_set = 1;
1416                 }
1417
1418                 warn "FIELD WEIGHTED OPERAND: >$weighted_operand<" if $DEBUG;
1419
1420                 #Use relevance ranking when not using a weighted query (which adds relevance ranking of its own)
1421
1422                 #N.B. Truncation is mutually exclusive with Weighted Queries,
1423                 #so even if QueryWeightFields is turned on, QueryAutoTruncate will turn it off, thus
1424                 #the need for this relevance wrapper.
1425                 $operand = "(rk=($operand))" unless $weight_fields;
1426
1427                 ($query,$query_cgi,$query_desc,$previous_operand) = _build_initial_query({
1428                     query => $query,
1429                     query_cgi => $query_cgi,
1430                     query_desc => $query_desc,
1431                     operator => ($operators[ $i - 1 ]) ? $operators[ $i - 1 ] : '',
1432                     parsed_operand => $operand,
1433                     original_operand => $operands[$i] // '',
1434                     index => $index,
1435                     index_plus => $index_plus,
1436                     indexes_set => $indexes_set,
1437                     previous_operand => $previous_operand,
1438                 });
1439
1440             }    #/if $operands
1441         }    # /for
1442     }
1443     warn "QUERY BEFORE LIMITS: >$query<" if $DEBUG;
1444
1445     # add limits
1446     my %group_OR_limits;
1447     my $availability_limit;
1448     foreach my $this_limit (@limits) {
1449         next unless $this_limit;
1450         if ( $this_limit =~ /available/ ) {
1451 #
1452 ## 'available' is defined as (items.onloan is NULL) and (items.itemlost = 0)
1453 ## In English:
1454 ## all records not indexed in the onloan register (zebra) and all records with a value of lost equal to 0
1455             $availability_limit .=
1456 "( (allrecords,AlwaysMatches='') and (not-onloan-count,st-numeric >= 1) and (lost,st-numeric=0) )";
1457             $limit_cgi  .= "&limit=available";
1458             $limit_desc .= "";
1459         }
1460
1461         # group_OR_limits, prefixed by mc-
1462         # OR every member of the group
1463         elsif ( $this_limit =~ /mc/ ) {
1464             my ($k,$v) = split(/:/, $this_limit,2);
1465             if ( $k !~ /mc-i(tem)?type/ ) {
1466                 # in case the mc-ccode value has complicating chars like ()'s inside it we wrap in quotes
1467                 $this_limit =~ tr/"//d;
1468                 $this_limit = $k.':"'.$v.'"';
1469             }
1470
1471             $group_OR_limits{$k} .= " or " if $group_OR_limits{$k};
1472             $limit_desc      .= " or " if $group_OR_limits{$k};
1473             $group_OR_limits{$k} .= "$this_limit";
1474             $limit_cgi       .= "&limit=" . uri_escape_utf8($this_limit);
1475             $limit_desc      .= " $this_limit";
1476         }
1477         elsif ( $this_limit =~ '^multibranchlimit:|^branch:' ) {
1478             $limit_cgi  .= "&limit=" . uri_escape_utf8($this_limit);
1479             $limit .= " and " if $limit || $query;
1480             my $branchfield  = C4::Context->preference('SearchLimitLibrary');
1481             my @branchcodes;
1482             if(  $this_limit =~ '^multibranchlimit:' ){
1483                 my ($group_id) = ( $this_limit =~ /^multibranchlimit:(.*)$/ );
1484                 my $search_group = Koha::Library::Groups->find( $group_id );
1485                 @branchcodes  = map { $_->branchcode } $search_group->all_libraries;
1486                 @branchcodes = sort { $a cmp $b } @branchcodes;
1487             } else {
1488                 @branchcodes = ( $this_limit =~ /^branch:(.*)$/ );
1489             }
1490
1491             if (@branchcodes) {
1492                 if ( $branchfield eq "homebranch" ) {
1493                     $this_limit = sprintf "(%s)", join " or ", map { 'homebranch: ' . $_ } @branchcodes;
1494                 }
1495                 elsif ( $branchfield eq "holdingbranch" ) {
1496                     $this_limit = sprintf "(%s)", join " or ", map { 'holdingbranch: ' . $_ } @branchcodes;
1497                 }
1498                 else {
1499                     $this_limit =  sprintf "(%s or %s)",
1500                       join( " or ", map { 'homebranch: ' . $_ } @branchcodes ),
1501                       join( " or ", map { 'holdingbranch: ' . $_ } @branchcodes );
1502                 }
1503             }
1504             $limit .= "$this_limit";
1505             $limit_desc .= " $this_limit";
1506         }
1507
1508         # Regular old limits
1509         else {
1510             $limit .= " and " if $limit || $query;
1511             $limit      .= "$this_limit";
1512             $limit_cgi  .= "&limit=" . uri_escape_utf8($this_limit);
1513             $limit_desc .= " $this_limit";
1514         }
1515     }
1516     foreach my $k (keys (%group_OR_limits)) {
1517         $limit .= " and " if ( $query || $limit );
1518         $limit .= "($group_OR_limits{$k})";
1519     }
1520     if ($availability_limit) {
1521         $limit .= " and " if ( $query || $limit );
1522         $limit .= "($availability_limit)";
1523     }
1524
1525     # Normalize the query and limit strings
1526     # This is flawed , means we can't search anything with : in it
1527     # if user wants to do ccl or cql, start the query with that
1528 #    $query =~ s/:/=/g;
1529     #NOTE: We use several several different regexps here as you can't have variable length lookback assertions
1530     $query =~ s/(?<=(ti|au|pb|su|an|kw|mc|nb|ns)):/=/g;
1531     $query =~ s/(?<=(wrdl)):/=/g;
1532     $query =~ s/(?<=(trn|phr)):/=/g;
1533     $query =~ s/(?<=(st-numeric)):/=/g;
1534     $query =~ s/(?<=(st-year)):/=/g;
1535     $query =~ s/(?<=(st-date-normalized)):/=/g;
1536
1537     # Removing warnings for later substitutions
1538     $query        //= q{};
1539     $query_desc   //= q{};
1540     $query_cgi    //= q{};
1541     $limit        //= q{};
1542     $limit_desc   //= q{};
1543     $limit_cgi    //= q{};
1544     $simple_query //= q{};
1545     $limit =~ s/:/=/g;
1546     for ( $query, $query_desc, $limit, $limit_desc ) {
1547         s/  +/ /g;    # remove extra spaces
1548         s/^ //g;     # remove any beginning spaces
1549         s/ $//g;     # remove any ending spaces
1550         s/==/=/g;    # remove double == from query
1551     }
1552     $query_cgi =~ s/^&//; # remove unnecessary & from beginning of the query cgi
1553
1554     for ($query_cgi,$simple_query) {
1555         s/"//g;
1556     }
1557     # append the limit to the query
1558     $query .= " " . $limit;
1559
1560     # Warnings if DEBUG
1561     if ($DEBUG) {
1562         warn "QUERY:" . $query;
1563         warn "QUERY CGI:" . $query_cgi;
1564         warn "QUERY DESC:" . $query_desc;
1565         warn "LIMIT:" . $limit;
1566         warn "LIMIT CGI:" . $limit_cgi;
1567         warn "LIMIT DESC:" . $limit_desc;
1568         warn "---------\nLeave buildQuery\n---------";
1569     }
1570
1571     return (
1572         undef,              $query, $simple_query, $query_cgi,
1573         $query_desc,        $limit, $limit_cgi,    $limit_desc,
1574         $query_type
1575     );
1576 }
1577
1578 =head2 _build_initial_query
1579
1580   ($query, $query_cgi, $query_desc, $previous_operand) = _build_initial_query($initial_query_params);
1581
1582   Build a section of the initial query containing indexes, operators, and operands.
1583
1584 =cut
1585
1586 sub _build_initial_query {
1587     my ($params) = @_;
1588
1589     my $operator = "";
1590     if ($params->{previous_operand}){
1591         #If there is a previous operand, add a supplied operator or the default 'and'
1592         $operator = ($params->{operator}) ? " ".($params->{operator})." " : ' and ';
1593     }
1594
1595     #NOTE: indexes_set is typically set when doing truncation or field weighting
1596     my $operand = ($params->{indexes_set}) ? $params->{parsed_operand} : $params->{index_plus}.$params->{parsed_operand};
1597
1598     #e.g. "kw,wrdl:test"
1599     #e.g. " and kw,wrdl:test"
1600     $params->{query} .= $operator . $operand;
1601
1602     $params->{query_cgi} .= "&op=".uri_escape_utf8($operator) if $operator;
1603     $params->{query_cgi} .= "&idx=".uri_escape_utf8($params->{index}) if $params->{index};
1604     $params->{query_cgi} .= "&q=".uri_escape_utf8($params->{original_operand}) if ( $params->{original_operand} ne '' );
1605
1606     #e.g. " and kw,wrdl: test"
1607     $params->{query_desc} .= $operator . ( $params->{index_plus} // q{} ) . " " . ( $params->{original_operand} // q{} );
1608
1609     $params->{previous_operand} = 1 unless $params->{previous_operand}; #If there is no previous operand, mark this as one
1610
1611     return ($params->{query}, $params->{query_cgi}, $params->{query_desc}, $params->{previous_operand});
1612 }
1613
1614 =head2 searchResults
1615
1616   my @search_results = searchResults($search_context, $searchdesc, $hits, 
1617                                      $results_per_page, $offset, $scan, 
1618                                      @marcresults);
1619
1620 Format results in a form suitable for passing to the template
1621
1622 =cut
1623
1624 # IMO this subroutine is pretty messy still -- it's responsible for
1625 # building the HTML output for the template
1626 sub searchResults {
1627     my ( $search_context, $searchdesc, $hits, $results_per_page, $offset, $scan, $marcresults, $xslt_variables ) = @_;
1628     my $dbh = C4::Context->dbh;
1629     my @newresults;
1630
1631     require C4::Items;
1632
1633     $search_context->{'interface'} = 'opac' if !$search_context->{'interface'} || $search_context->{'interface'} ne 'intranet';
1634     my ($is_opac, $hidelostitems);
1635     if ($search_context->{'interface'} eq 'opac') {
1636         $hidelostitems = C4::Context->preference('hidelostitems');
1637         $is_opac       = 1;
1638     }
1639
1640     my $record_processor = Koha::RecordProcessor->new({
1641         filters => 'ViewPolicy'
1642     });
1643
1644     #Build branchnames hash
1645     my %branches = map { $_->branchcode => $_->branchname } Koha::Libraries->search({}, { order_by => 'branchname' });
1646
1647 # FIXME - We build an authorised values hash here, using the default framework
1648 # though it is possible to have different authvals for different fws.
1649
1650     my $shelflocations =
1651       { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.location' } ) };
1652
1653     # get notforloan authorised value list (see $shelflocations  FIXME)
1654     my $av = Koha::MarcSubfieldStructures->search({ frameworkcode => '', kohafield => 'items.notforloan', authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] });
1655     my $notforloan_authorised_value = $av->count ? $av->next->authorised_value : undef;
1656
1657     #Get itemtype hash
1658     my $itemtypes = Koha::ItemTypes->search_with_localization;
1659     my %itemtypes = map { $_->{itemtype} => $_ } @{ $itemtypes->unblessed };
1660
1661     #search item field code
1662     my ($itemtag, undef) = &GetMarcFromKohaField( "items.itemnumber" );
1663
1664     ## find column names of items related to MARC
1665     my %subfieldstosearch;
1666     my @columns = Koha::Database->new()->schema()->resultset('Item')->result_source->columns;
1667     for my $column ( @columns ) {
1668         my ( $tagfield, $tagsubfield ) =
1669           &GetMarcFromKohaField( "items." . $column );
1670         if ( defined $tagsubfield ) {
1671             $subfieldstosearch{$column} = $tagsubfield;
1672         }
1673     }
1674
1675     # handle which records to actually retrieve
1676     my $times; # Times is which record to process up to
1677     if ( $hits && $offset + $results_per_page <= $hits ) {
1678         $times = $offset + $results_per_page;
1679     }
1680     else {
1681         $times = $hits; # If less hits than results_per_page+offset we go to the end
1682     }
1683
1684     my $marcflavour = C4::Context->preference("marcflavour");
1685     # We get the biblionumber position in MARC
1686     my ($bibliotag,$bibliosubf)=GetMarcFromKohaField( 'biblio.biblionumber' );
1687
1688     # set stuff for XSLT processing here once, not later again for every record we retrieved
1689     my $xslfile;
1690     my $xslsyspref;
1691     if( $is_opac ){
1692         $xslsyspref = "OPACXSLTResultsDisplay";
1693         $xslfile = C4::Context->preference( $xslsyspref );
1694     } else {
1695         $xslsyspref = "XSLTResultsDisplay";
1696         $xslfile = C4::Context->preference( $xslsyspref ) || "default";
1697     }
1698     my $lang   = $xslfile ? C4::Languages::getlanguage()  : undef;
1699     my $sysxml = $xslfile ? C4::XSLT::get_xslt_sysprefs() : undef;
1700
1701     my $userenv = C4::Context->userenv;
1702     my $logged_in_user
1703         = ( defined $userenv and $userenv->{number} )
1704         ? Koha::Patrons->find( $userenv->{number} )
1705         : undef;
1706     my $patron_category_hide_lost_items = ($logged_in_user) ? $logged_in_user->category->hidelostitems : 0;
1707
1708     # loop through all of the records we've retrieved
1709     for ( my $i = $offset ; $i <= $times - 1 ; $i++ ) {
1710
1711         my $marcrecord;
1712         if ($scan) {
1713             # For Scan searches we built USMARC data
1714             $marcrecord = MARC::Record->new_from_usmarc( $marcresults->[$i]);
1715         } else {
1716             # Normal search, render from Zebra's output
1717             $marcrecord = new_record_from_zebra(
1718                 'biblioserver',
1719                 $marcresults->[$i]
1720             );
1721
1722             if ( ! defined $marcrecord ) {
1723                 warn "ERROR DECODING RECORD - $@: " . $marcresults->[$i];
1724                 next;
1725             }
1726         }
1727
1728         my $fw = $scan
1729              ? undef
1730              : $bibliotag < 10
1731                ? GetFrameworkCode($marcrecord->field($bibliotag)->data)
1732                : GetFrameworkCode($marcrecord->subfield($bibliotag,$bibliosubf));
1733
1734         SetUTF8Flag($marcrecord);
1735         my $oldbiblio = TransformMarcToKoha( $marcrecord, $fw, 'no_items' );
1736         $oldbiblio->{result_number} = $i + 1;
1737
1738                 $oldbiblio->{normalized_upc}  = GetNormalizedUPC(       $marcrecord,$marcflavour);
1739                 $oldbiblio->{normalized_ean}  = GetNormalizedEAN(       $marcrecord,$marcflavour);
1740                 $oldbiblio->{normalized_oclc} = GetNormalizedOCLCNumber($marcrecord,$marcflavour);
1741         $oldbiblio->{normalized_isbn} = GetNormalizedISBN($oldbiblio->{isbn},$marcrecord,$marcflavour); # Use existing ISBN from record if we got one
1742                 $oldbiblio->{content_identifier_exists} = 1 if ($oldbiblio->{normalized_isbn} or $oldbiblio->{normalized_oclc} or $oldbiblio->{normalized_ean} or $oldbiblio->{normalized_upc});
1743
1744                 # edition information, if any
1745         $oldbiblio->{edition} = $oldbiblio->{editionstatement};
1746
1747         my $itemtype = $oldbiblio->{itemtype} ? $itemtypes{$oldbiblio->{itemtype}} : undef;
1748         # add imageurl to itemtype if there is one
1749         $oldbiblio->{imageurl} = $itemtype ? getitemtypeimagelocation( $search_context->{'interface'}, $itemtype->{imageurl} ) : q{};
1750         # Build summary if there is one (the summary is defined in the itemtypes table)
1751         $oldbiblio->{description} = $itemtype ? $itemtype->{translated_description} : q{};
1752
1753         # FIXME: this is only used in the deprecated non-XLST opac results
1754         if ( !$xslfile && $is_opac && $itemtype && $itemtype->{summary} ) {
1755             my $summary = $itemtypes{ $oldbiblio->{itemtype} }->{summary};
1756             my @fields  = $marcrecord->fields();
1757
1758             my $newsummary;
1759             foreach my $line ( "$summary\n" =~ /(.*)\n/g ){
1760                 my $tags = {};
1761                 foreach my $tag ( $line =~ /\[(\d{3}[\w|\d])\]/ ) {
1762                     $tag =~ /(.{3})(.)/;
1763                     if($marcrecord->field($1)){
1764                         my @abc = $marcrecord->field($1)->subfield($2);
1765                         $tags->{$tag} = $#abc + 1 ;
1766                     }
1767                 }
1768
1769                 # We catch how many times to repeat this line
1770                 my $max = 0;
1771                 foreach my $tag (keys(%$tags)){
1772                     $max = $tags->{$tag} if($tags->{$tag} > $max);
1773                  }
1774
1775                 # we replace, and repeat each line
1776                 for (my $i = 0 ; $i < $max ; $i++){
1777                     my $newline = $line;
1778
1779                     foreach my $tag ( $newline =~ /\[(\d{3}[\w|\d])\]/g ) {
1780                         $tag =~ /(.{3})(.)/;
1781
1782                         if($marcrecord->field($1)){
1783                             my @repl = $marcrecord->field($1)->subfield($2);
1784                             my $subfieldvalue = $repl[$i];
1785                             $newline =~ s/\[$tag\]/$subfieldvalue/g;
1786                         }
1787                     }
1788                     $newsummary .= "$newline\n";
1789                 }
1790             }
1791
1792             $newsummary =~ s/\[(.*?)]//g;
1793             $newsummary =~ s/\n/<br\/>/g;
1794             $oldbiblio->{summary} = $newsummary;
1795         }
1796
1797         # Pull out the items fields
1798         my @fields = $marcrecord->field($itemtag);
1799         $marcrecord->delete_fields( @fields ) unless C4::Context->preference('PassItemMarcToXSLT');
1800         my $marcflavor = C4::Context->preference("marcflavour");
1801
1802         # adding linked items that belong to host records
1803         if ( C4::Context->preference('EasyAnalyticalRecords') ) {
1804             my $analyticsfield = '773';
1805             if ($marcflavor eq 'MARC21' || $marcflavor eq 'NORMARC') {
1806                 $analyticsfield = '773';
1807             } elsif ($marcflavor eq 'UNIMARC') {
1808                 $analyticsfield = '461';
1809             }
1810             foreach my $hostfield ( $marcrecord->field($analyticsfield)) {
1811                 my $hostbiblionumber = $hostfield->subfield("0");
1812                 my $linkeditemnumber = $hostfield->subfield("9");
1813                 if( $hostbiblionumber ) {
1814                     my $linkeditemmarc = C4::Items::GetMarcItem( $hostbiblionumber, $linkeditemnumber );
1815                     if ($linkeditemmarc) {
1816                         my $linkeditemfield = $linkeditemmarc->field($itemtag);
1817                         if ($linkeditemfield) {
1818                             push( @fields, $linkeditemfield );
1819                         }
1820                     }
1821                 }
1822             }
1823         }
1824
1825         # Setting item statuses for display
1826         my @available_items_loop;
1827         my @onloan_items_loop;
1828         my @other_items_loop;
1829
1830         my $available_items;
1831         my $onloan_items;
1832         my $other_items;
1833
1834         my $ordered_count         = 0;
1835         my $available_count       = 0;
1836         my $onloan_count          = 0;
1837         my $longoverdue_count     = 0;
1838         my $other_count           = 0;
1839         my $withdrawn_count        = 0;
1840         my $itemlost_count        = 0;
1841         my $hideatopac_count      = 0;
1842         my $itembinding_count     = 0;
1843         my $itemdamaged_count     = 0;
1844         my $item_in_transit_count = 0;
1845         my $item_onhold_count     = 0;
1846         my $notforloan_count      = 0;
1847         my $items_count           = scalar(@fields);
1848         my $maxitems_pref = C4::Context->preference('maxItemsinSearchResults');
1849         my $maxitems = $maxitems_pref ? $maxitems_pref - 1 : 1;
1850         my @hiddenitems; # hidden itemnumbers based on OpacHiddenItems syspref
1851
1852         # loop through every item
1853         foreach my $field (@fields) {
1854             my $item;
1855
1856             # populate the items hash
1857             foreach my $code ( keys %subfieldstosearch ) {
1858                 $item->{$code} = $field->subfield( $subfieldstosearch{$code} );
1859             }
1860             $item->{description} = $itemtypes{ $item->{itype} }{translated_description} if $item->{itype};
1861
1862                 # OPAC hidden items
1863             if ($is_opac) {
1864                 # hidden because lost
1865                 if ($hidelostitems && $item->{itemlost}) {
1866                     $hideatopac_count++;
1867                     next;
1868                 }
1869                 # hidden based on OpacHiddenItems syspref
1870                 my @hi = C4::Items::GetHiddenItemnumbers({ items=> [ $item ], borcat => $search_context->{category} });
1871                 if (scalar @hi) {
1872                     push @hiddenitems, @hi;
1873                     $hideatopac_count++;
1874                     next;
1875                 }
1876             }
1877
1878             my $hbranch     = C4::Context->preference('StaffSearchResultsDisplayBranch');
1879             my $otherbranch = $hbranch eq 'homebranch' ? 'holdingbranch' : 'homebranch';
1880
1881             # set item's branch name, use HomeOrHoldingBranch syspref first, fall back to the other one
1882             if ($item->{$hbranch}) {
1883                 $item->{'branchname'} = $branches{$item->{$hbranch}};
1884             }
1885             elsif ($item->{$otherbranch}) {     # Last resort
1886                 $item->{'branchname'} = $branches{$item->{$otherbranch}};
1887             }
1888
1889             my $prefix =
1890                 ( $item->{$hbranch} ? $item->{$hbranch} . '--' : q{} )
1891               . ( $item->{location} ? $item->{location} : q{} )
1892               . ( $item->{itype}    ? $item->{itype}    : q{} )
1893               . ( $item->{itemcallnumber} ? $item->{itemcallnumber} : q{} );
1894 # For each grouping of items (onloan, available, unavailable), we build a key to store relevant info about that item
1895             if ( $item->{onloan}
1896                 and $logged_in_user
1897                 and !( $patron_category_hide_lost_items and $item->{itemlost} ) )
1898             {
1899                 $onloan_count++;
1900                 my $key = $prefix . $item->{onloan} . $item->{barcode};
1901                 $onloan_items->{$key}->{due_date} = $item->{onloan};
1902                 $onloan_items->{$key}->{count}++ if $item->{$hbranch};
1903                 $onloan_items->{$key}->{branchname}     = $item->{branchname};
1904                 $onloan_items->{$key}->{location}       = $shelflocations->{ $item->{location} } if $item->{location};
1905                 $onloan_items->{$key}->{itemcallnumber} = $item->{itemcallnumber};
1906                 $onloan_items->{$key}->{description}    = $item->{description};
1907                 $onloan_items->{$key}->{imageurl} =
1908                   getitemtypeimagelocation( $search_context->{'interface'}, $itemtypes{ $item->{itype} }->{imageurl} );
1909
1910                 # if something's checked out and lost, mark it as 'long overdue'
1911                 if ( $item->{itemlost} ) {
1912                     $onloan_items->{$key}->{longoverdue}++;
1913                     $longoverdue_count++;
1914                 }
1915             }
1916
1917          # items not on loan, but still unavailable ( lost, withdrawn, damaged )
1918             else {
1919
1920                 my $itemtype = C4::Context->preference("item-level_itypes")? $item->{itype}: $oldbiblio->{itemtype};
1921                 $item->{notforloan} = 1 if !$item->{notforloan} &&
1922                     $itemtype && $itemtypes{ $itemtype }->{notforloan};
1923
1924                 # item is on order
1925                 if ( $item->{notforloan} < 0 ) {
1926                     $ordered_count++;
1927                 } elsif ( $item->{notforloan} > 0 ) {
1928                     $notforloan_count++;
1929                 }
1930
1931                 # is item in transit?
1932                 my $transfertwhen = '';
1933                 my ($transfertfrom, $transfertto);
1934
1935                 # is item on the reserve shelf?
1936                 my $reservestatus = '';
1937
1938                 unless ($item->{withdrawn}
1939                         || $item->{itemlost}
1940                         || $item->{damaged}
1941                         || $item->{notforloan}
1942                         || ( C4::Context->preference('MaxSearchResultsItemsPerRecordStatusCheck')
1943                         && $items_count > C4::Context->preference('MaxSearchResultsItemsPerRecordStatusCheck') ) ) {
1944
1945                     # A couple heuristics to limit how many times
1946                     # we query the database for item transfer information, sacrificing
1947                     # accuracy in some cases for speed;
1948                     #
1949                     # 1. don't query if item has one of the other statuses
1950                     # 2. don't check transit status if the bib has
1951                     #    more than 20 items
1952                     #
1953                     # FIXME: to avoid having the query the database like this, and to make
1954                     #        the in transit status count as unavailable for search limiting,
1955                     #        should map transit status to record indexed in Zebra.
1956                     #
1957                     ($transfertwhen, $transfertfrom, $transfertto) = C4::Circulation::GetTransfers($item->{itemnumber});
1958                     $reservestatus = C4::Reserves::GetReserveStatus( $item->{itemnumber} );
1959                 }
1960
1961                 # item is withdrawn, lost, damaged, not for loan, reserved or in transit
1962                 if (   $item->{withdrawn}
1963                     || $item->{itemlost}
1964                     || $item->{damaged}
1965                     || $item->{notforloan}
1966                     || $reservestatus eq 'Waiting'
1967                     || ($transfertwhen && $transfertwhen ne ''))
1968                 {
1969                     $withdrawn_count++        if $item->{withdrawn};
1970                     $itemlost_count++        if $item->{itemlost};
1971                     $itemdamaged_count++     if $item->{damaged};
1972                     $item_in_transit_count++ if $transfertwhen && $transfertwhen ne '';
1973                     $item_onhold_count++     if $reservestatus eq 'Waiting';
1974                     $item->{status} = ($item->{withdrawn}//q{}) . "-" . ($item->{itemlost}//q{}) . "-" . ($item->{damaged}//q{}) . "-" . ($item->{notforloan}//q{});
1975
1976                     $other_count++;
1977
1978                     my $key = $prefix . $item->{status};
1979                     foreach (qw(withdrawn itemlost damaged branchname itemcallnumber)) {
1980                         $other_items->{$key}->{$_} = $item->{$_};
1981                     }
1982                     $other_items->{$key}->{intransit} = ( $transfertwhen ne '' ) ? 1 : 0;
1983                     $other_items->{$key}->{onhold} = ($reservestatus) ? 1 : 0;
1984                     $other_items->{$key}->{notforloan} = GetAuthorisedValueDesc('','',$item->{notforloan},'','',$notforloan_authorised_value) if $notforloan_authorised_value and $item->{notforloan};
1985                     $other_items->{$key}->{count}++ if $item->{$hbranch};
1986                     $other_items->{$key}->{location} = $shelflocations->{ $item->{location} } if $item->{location};
1987                     $other_items->{$key}->{description} = $item->{description};
1988                     $other_items->{$key}->{imageurl} = getitemtypeimagelocation( $search_context->{'interface'}, $itemtypes{ $item->{itype}//q{} }->{imageurl} );
1989                 }
1990                 # item is available
1991                 else {
1992                     $available_count++;
1993                     $available_items->{$prefix}->{count}++ if $item->{$hbranch};
1994                     foreach (qw(branchname itemcallnumber description)) {
1995                         $available_items->{$prefix}->{$_} = $item->{$_};
1996                     }
1997                     $available_items->{$prefix}->{location} = $shelflocations->{ $item->{location} } if $item->{location};
1998                     $available_items->{$prefix}->{imageurl} = getitemtypeimagelocation( $search_context->{'interface'}, $itemtypes{ $item->{itype}//q{} }->{imageurl} );
1999                 }
2000             }
2001         }    # notforloan, item level and biblioitem level
2002
2003         # if all items are hidden, do not show the record
2004         if ( C4::Context->preference('OpacHiddenItemsHidesRecord') && $items_count > 0 && $hideatopac_count == $items_count) {
2005             next;
2006         }
2007
2008         my ( $availableitemscount, $onloanitemscount, $otheritemscount );
2009         for my $key ( sort keys %$onloan_items ) {
2010             (++$onloanitemscount > $maxitems) and last;
2011             push @onloan_items_loop, $onloan_items->{$key};
2012         }
2013         for my $key ( sort keys %$other_items ) {
2014             (++$otheritemscount > $maxitems) and last;
2015             push @other_items_loop, $other_items->{$key};
2016         }
2017         for my $key ( sort keys %$available_items ) {
2018             (++$availableitemscount > $maxitems) and last;
2019             push @available_items_loop, $available_items->{$key}
2020         }
2021
2022         # XSLT processing of some stuff
2023         # we fetched the sysprefs already before the loop through all retrieved record!
2024         if (!$scan && $xslfile) {
2025             $record_processor->options({
2026                 frameworkcode => $fw,
2027                 interface     => $search_context->{'interface'}
2028             });
2029
2030             $record_processor->process($marcrecord);
2031             $oldbiblio->{XSLTResultsRecord} = XSLTParse4Display($oldbiblio->{biblionumber}, $marcrecord, $xslsyspref, 1, \@hiddenitems, $sysxml, $xslfile, $lang, $xslt_variables);
2032         }
2033
2034         my $biblio_object = Koha::Biblios->find( $oldbiblio->{biblionumber} );
2035         $oldbiblio->{biblio_object} = $biblio_object;
2036
2037         my $can_place_holds = 1;
2038         # if biblio level itypes are used and itemtype is notforloan, it can't be reserved either
2039         if (!C4::Context->preference("item-level_itypes")) {
2040             if ($itemtype && $itemtype->{notforloan}) {
2041                 $can_place_holds = 0;
2042             }
2043         } else {
2044             $can_place_holds = $biblio_object->items->filter_by_for_hold()->count;
2045         }
2046         $oldbiblio->{norequests} = 1 unless $can_place_holds;
2047         $oldbiblio->{items_count}          = $items_count;
2048         $oldbiblio->{available_items_loop} = \@available_items_loop;
2049         $oldbiblio->{onloan_items_loop}    = \@onloan_items_loop;
2050         $oldbiblio->{other_items_loop}     = \@other_items_loop;
2051         $oldbiblio->{availablecount}       = $available_count;
2052         $oldbiblio->{availableplural}      = 1 if $available_count > 1;
2053         $oldbiblio->{onloancount}          = $onloan_count;
2054         $oldbiblio->{onloanplural}         = 1 if $onloan_count > 1;
2055         $oldbiblio->{othercount}           = $other_count;
2056         $oldbiblio->{otherplural}          = 1 if $other_count > 1;
2057         $oldbiblio->{withdrawncount}        = $withdrawn_count;
2058         $oldbiblio->{itemlostcount}        = $itemlost_count;
2059         $oldbiblio->{damagedcount}         = $itemdamaged_count;
2060         $oldbiblio->{intransitcount}       = $item_in_transit_count;
2061         $oldbiblio->{onholdcount}          = $item_onhold_count;
2062         $oldbiblio->{orderedcount}         = $ordered_count;
2063         $oldbiblio->{notforloancount}      = $notforloan_count;
2064
2065         if (C4::Context->preference("AlternateHoldingsField") && $items_count == 0) {
2066             my $fieldspec = C4::Context->preference("AlternateHoldingsField");
2067             my $subfields = substr $fieldspec, 3;
2068             my $holdingsep = C4::Context->preference("AlternateHoldingsSeparator") || ' ';
2069             my @alternateholdingsinfo = ();
2070             my @holdingsfields = $marcrecord->field(substr $fieldspec, 0, 3);
2071             my $alternateholdingscount = 0;
2072
2073             for my $field (@holdingsfields) {
2074                 my %holding = ( holding => '' );
2075                 my $havesubfield = 0;
2076                 for my $subfield ($field->subfields()) {
2077                     if ((index $subfields, $$subfield[0]) >= 0) {
2078                         $holding{'holding'} .= $holdingsep if (length $holding{'holding'} > 0);
2079                         $holding{'holding'} .= $$subfield[1];
2080                         $havesubfield++;
2081                     }
2082                 }
2083                 if ($havesubfield) {
2084                     push(@alternateholdingsinfo, \%holding);
2085                     $alternateholdingscount++;
2086                 }
2087             }
2088
2089             $oldbiblio->{'ALTERNATEHOLDINGS'} = \@alternateholdingsinfo;
2090             $oldbiblio->{'alternateholdings_count'} = $alternateholdingscount;
2091         }
2092
2093         push( @newresults, $oldbiblio );
2094     }
2095
2096     return @newresults;
2097 }
2098
2099 =head2 enabled_staff_search_views
2100
2101 %hash = enabled_staff_search_views()
2102
2103 This function returns a hash that contains three flags obtained from the system
2104 preferences, used to determine whether a particular staff search results view
2105 is enabled.
2106
2107 =over 2
2108
2109 =item C<Output arg:>
2110
2111     * $hash{can_view_MARC} is true only if the MARC view is enabled
2112     * $hash{can_view_ISBD} is true only if the ISBD view is enabled
2113     * $hash{can_view_labeledMARC} is true only if the Labeled MARC view is enabled
2114
2115 =item C<usage in the script:>
2116
2117 =back
2118
2119 $template->param ( C4::Search::enabled_staff_search_views );
2120
2121 =cut
2122
2123 sub enabled_staff_search_views
2124 {
2125         return (
2126                 can_view_MARC                   => C4::Context->preference('viewMARC'),                 # 1 if the staff search allows the MARC view
2127                 can_view_ISBD                   => C4::Context->preference('viewISBD'),                 # 1 if the staff search allows the ISBD view
2128                 can_view_labeledMARC    => C4::Context->preference('viewLabeledMARC'),  # 1 if the staff search allows the Labeled MARC view
2129         );
2130 }
2131
2132 =head2 z3950_search_args
2133
2134 $arrayref = z3950_search_args($matchpoints)
2135
2136 This function returns an array reference that contains the search parameters to be
2137 passed to the Z39.50 search script (z3950_search.pl). The array elements
2138 are hash refs whose keys are name and value, and whose values are the
2139 name of a search parameter, the value of that search parameter and the URL encoded
2140 value of that parameter.
2141
2142 The search parameter names are lccn, isbn, issn, title, author, dewey and subject.
2143
2144 The search parameter values are obtained from the bibliographic record whose
2145 data is in a hash reference in $matchpoints, as returned by Biblio::GetBiblioData().
2146
2147 If $matchpoints is a scalar, it is assumed to be an unnamed query descriptor, e.g.
2148 a general purpose search argument. In this case, the returned array contains only
2149 entry: the key is 'title' and the value is derived from $matchpoints.
2150
2151 If a search parameter value is undefined or empty, it is not included in the returned
2152 array.
2153
2154 The returned array reference may be passed directly to the template parameters.
2155
2156 =over 2
2157
2158 =item C<Output arg:>
2159
2160     * $array containing hash refs as described above
2161
2162 =item C<usage in the script:>
2163
2164 =back
2165
2166 $data = Biblio::GetBiblioData($bibno);
2167 $template->param ( MYLOOP => C4::Search::z3950_search_args($data) )
2168
2169 *OR*
2170
2171 $template->param ( MYLOOP => C4::Search::z3950_search_args($searchscalar) )
2172
2173 =cut
2174
2175 sub z3950_search_args {
2176     my $bibrec = shift;
2177
2178     my $isbn_string = ref( $bibrec ) ? $bibrec->{title} : $bibrec;
2179     my $isbn = Business::ISBN->new( $isbn_string );
2180
2181     if (defined $isbn && $isbn->is_valid)
2182     {
2183         if ( ref($bibrec) ) {
2184             $bibrec->{isbn} = $isbn_string;
2185             $bibrec->{title} = undef;
2186         } else {
2187             $bibrec = { isbn => $isbn_string };
2188         }
2189     }
2190     else {
2191         $bibrec = { title => $bibrec } if !ref $bibrec;
2192     }
2193     my $array = [];
2194     for my $field (qw/ lccn isbn issn title author dewey subject /)
2195     {
2196         push @$array, { name => $field, value => $bibrec->{$field} }
2197           if defined $bibrec->{$field};
2198     }
2199     return $array;
2200 }
2201
2202 =head2 GetDistinctValues($field);
2203
2204 C<$field> is a reference to the fields array
2205
2206 =cut
2207
2208 sub GetDistinctValues {
2209     my ($fieldname,$string)=@_;
2210     # returns a reference to a hash of references to branches...
2211     if ($fieldname=~/\./){
2212                         my ($table,$column)=split /\./, $fieldname;
2213                         my $dbh = C4::Context->dbh;
2214                         warn "select DISTINCT($column) as value, count(*) as cnt from $table group by lib order by $column " if $DEBUG;
2215                         my $sth = $dbh->prepare("select DISTINCT($column) as value, count(*) as cnt from $table ".($string?" where $column like \"$string%\"":"")."group by value order by $column ");
2216                         $sth->execute;
2217                         my $elements=$sth->fetchall_arrayref({});
2218                         return $elements;
2219    }
2220    else {
2221                 $string||= qq("");
2222                 my @servers=qw<biblioserver authorityserver>;
2223                 my (@zconns,@results);
2224         for ( my $i = 0 ; $i < @servers ; $i++ ) {
2225                 $zconns[$i] = C4::Context->Zconn( $servers[$i], 1 );
2226                         $results[$i] =
2227                       $zconns[$i]->scan(
2228                         ZOOM::Query::CCL2RPN->new( qq"$fieldname $string", $zconns[$i])
2229                       );
2230                 }
2231                 # The big moment: asynchronously retrieve results from all servers
2232                 my @elements;
2233         _ZOOM_event_loop(
2234             \@zconns,
2235             \@results,
2236             sub {
2237                 my ( $i, $size ) = @_;
2238                 for ( my $j = 0 ; $j < $size ; $j++ ) {
2239                     my %hashscan;
2240                     @hashscan{qw(value cnt)} =
2241                       $results[ $i - 1 ]->display_term($j);
2242                     push @elements, \%hashscan;
2243                 }
2244             }
2245         );
2246                 return \@elements;
2247    }
2248 }
2249
2250 =head2 _ZOOM_event_loop
2251
2252     _ZOOM_event_loop(\@zconns, \@results, sub {
2253         my ( $i, $size ) = @_;
2254         ....
2255     } );
2256
2257 Processes a ZOOM event loop and passes control to a closure for
2258 processing the results, and destroying the resultsets.
2259
2260 =cut
2261
2262 sub _ZOOM_event_loop {
2263     my ($zconns, $results, $callback) = @_;
2264     while ( ( my $i = ZOOM::event( $zconns ) ) != 0 ) {
2265         my $ev = $zconns->[ $i - 1 ]->last_event();
2266         if ( $ev == ZOOM::Event::ZEND ) {
2267             next unless $results->[ $i - 1 ];
2268             my $size = $results->[ $i - 1 ]->size();
2269             if ( $size > 0 ) {
2270                 $callback->($i, $size);
2271             }
2272         }
2273     }
2274
2275     foreach my $result (@$results) {
2276         $result->destroy();
2277     }
2278 }
2279
2280 =head2 new_record_from_zebra
2281
2282 Given raw data from a searchengine result set, return a MARC::Record object
2283
2284 This helper function is needed to take into account all the involved
2285 system preferences and configuration variables to properly create the
2286 MARC::Record object.
2287
2288 If we are using GRS-1, then the raw data we get from Zebra should be USMARC
2289 data. If we are using DOM, then it has to be MARCXML.
2290
2291 If we are using elasticsearch, it'll already be a MARC::Record and this
2292 function needs a new name.
2293
2294 =cut
2295
2296 sub new_record_from_zebra {
2297
2298     my $server   = shift;
2299     my $raw_data = shift;
2300     # Set the default indexing modes
2301     my $search_engine = C4::Context->preference("SearchEngine");
2302     if ($search_engine eq 'Elasticsearch') {
2303         return ref $raw_data eq 'MARC::Record' ? $raw_data : MARC::Record->new_from_xml( $raw_data, 'UTF-8' );
2304     }
2305     my $index_mode = ( $server eq 'biblioserver' )
2306                         ? C4::Context->config('zebra_bib_index_mode') // 'dom'
2307                         : C4::Context->config('zebra_auth_index_mode') // 'dom';
2308
2309     my $marc_record =  eval {
2310         if ( $index_mode eq 'dom' ) {
2311             MARC::Record->new_from_xml( $raw_data, 'UTF-8' );
2312         } else {
2313             MARC::Record->new_from_usmarc( $raw_data );
2314         }
2315     };
2316
2317     if ($@) {
2318         return;
2319     } else {
2320         return $marc_record;
2321     }
2322
2323 }
2324
2325 END { }    # module clean-up code here (global destructor)
2326
2327 1;
2328 __END__
2329
2330 =head1 AUTHOR
2331
2332 Koha Development Team <http://koha-community.org/>
2333
2334 =cut