3 # This file is part of Koha.
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.
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.
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>.
21 use C4::Biblio; # GetMarcFromKohaField, GetBiblioData
22 use C4::Koha; # getFacets
28 use C4::Reserves; # GetReserveStatus
31 use Koha::AuthorisedValues;
35 use Koha::RecordProcessor;
40 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $DEBUG);
43 $DEBUG = ($ENV{DEBUG}) ? 1 : 0;
48 C4::Search - Functions for searching the Koha catalog.
52 See opac/opac-search.pl or catalogue/search.pl for example of usage
56 This module provides searching functions for Koha's bibliographic databases
70 &enabled_staff_search_views
73 # make all your functions, whether exported or not;
77 ($biblionumber,$biblionumber,$title) = FindDuplicate($record);
79 This function attempts to find duplicate records using a hard-coded, fairly simplistic algorithm
85 my $dbh = C4::Context->dbh;
86 my $result = TransformMarcToKoha( $record, '' );
90 # search duplicate on ISBN, easy and fast..
92 if ( $result->{isbn} ) {
93 $result->{isbn} =~ s/\(.*$//;
94 $result->{isbn} =~ s/\s+$//;
95 $query = "isbn:$result->{isbn}";
99 my $titleindex = 'ti,ext';
100 my $authorindex = 'au,ext';
103 $result->{title} =~ s /\\//g;
104 $result->{title} =~ s /\"//g;
105 $result->{title} =~ s /\(//g;
106 $result->{title} =~ s /\)//g;
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;
115 $query .= " $op $authorindex:\"$result->{author}\"";
119 my $searcher = Koha::SearchEngine::Search->new({index => $Koha::SearchEngine::BIBLIOS_INDEX});
120 my ( $error, $searchresults, undef ) = $searcher->simple_search_compat($query,0,50);
122 if (!defined $error) {
123 foreach my $possible_duplicate_record (@{$searchresults}) {
124 my $marcrecord = new_record_from_zebra(
126 $possible_duplicate_record
129 my $result = TransformMarcToKoha( $marcrecord, '' );
131 # FIXME :: why 2 $biblionumber ?
133 push @results, $result->{'biblionumber'};
134 push @results, $result->{'title'};
143 ( $error, $results, $total_hits ) = SimpleSearch( $query, $offset, $max_results, [@servers], [%options] );
145 This function provides a simple search API on the bibliographic catalog
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 = )
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
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
168 =item C<usage in the script:>
172 my ( $error, $marcresults, $total_hits ) = SimpleSearch($query);
174 if (defined $error) {
175 $template->param(query_error => $error);
176 warn "error: ".$error;
177 output_html_with_http_headers $input, $cookie, $template->output;
181 my $hits = @{$marcresults};
184 for my $r ( @{$marcresults} ) {
185 my $marcrecord = MARC::File::USMARC::decode($r);
186 my $biblio = TransformMarcToKoha($marcrecord,q{});
188 #build the iarray of hashs for the template.
190 title => $biblio->{'title'},
191 subtitle => $biblio->{'subtitle'},
192 biblionumber => $biblio->{'biblionumber'},
193 author => $biblio->{'author'},
194 publishercode => $biblio->{'publishercode'},
195 publicationyear => $biblio->{'publicationyear'},
200 $template->param(result=>\@results);
205 my ( $query, $offset, $max_results, $servers, %options ) = @_;
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' );
216 # Initialize & Search Zebra
217 for ( my $i = 0 ; $i < @servers ; $i++ ) {
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] );
226 $zconns[$i]->errmsg() . " ("
227 . $zconns[$i]->errcode() . ") "
228 . $zconns[$i]->addinfo() . " "
229 . $zconns[$i]->diagset();
231 return ( $error, undef, undef ) if $zconns[$i]->errcode();
235 # caught a ZOOM::Exception
239 . $@->addinfo() . " "
241 warn $error." for query: $query";
242 return ( $error, undef, undef );
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;
259 for my $j ( $first_record .. $last_record ) {
261 $tmpresults[ $i - 1 ]->record( $j - 1 )->raw()
264 push @{$results}, $record if defined $record;
269 foreach my $zoom_query (@zoom_queries) {
270 $zoom_query->destroy();
273 return ( undef, $results, $total_hits );
278 ( undef, $results_hashref, \@facets_loop ) = getRecords (
280 $koha_query, $simple_query, $sort_by_ref, $servers_ref,
281 $results_per_page, $offset, $branches, $itemtypes,
282 $query_type, $scan, $opac
285 The all singing, all dancing, multi-server, asynchronous, scanning,
286 searching, record nabbing, facet-building
288 See verbose embedded documentation.
294 $koha_query, $simple_query, $sort_by_ref, $servers_ref,
295 $results_per_page, $offset, $branches, $itemtypes,
296 $query_type, $scan, $opac
299 my @servers = @$servers_ref;
300 my @sort_by = @$sort_by_ref;
301 $offset = 0 if $offset < 0;
303 # Initialize variables for the ZOOM connection and results object
306 my $results_hashref = ();
308 # TODO simplify this structure ( { branchcode => $branchname } is enought) and remove this parameter
309 $branches ||= { map { $_->branchcode => { branchname => $_->branchname } } Koha::Libraries->search };
311 # Initialize variables for the faceted results objects
312 my $facets_counter = {};
313 my $facets_info = {};
314 my $facets = getFacets();
316 my @facets_loop; # stores the ref to array of hashes for template facets loop
318 ### LOOP THROUGH THE SERVERS
319 for ( my $i = 0 ; $i < @servers ; $i++ ) {
320 $zconns[$i] = C4::Context->Zconn( $servers[$i], 1 );
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;
326 #$query_to_use = $simple_query if $scan;
327 warn $simple_query if ( $scan and $DEBUG );
329 # Check if we've got a query_type defined, if so, use it
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]));
340 warn "Unknown query_type '$query_type'. Results undetermined.";
343 $results[$i] = $zconns[$i]->scan( ZOOM::Query::CCL2RPN->new($query_to_use, $zconns[$i]));
345 $results[$i] = $zconns[$i]->search(ZOOM::Query::CCL2RPN->new($query_to_use, $zconns[$i]));
349 warn "WARNING: query problem with $query_to_use " . $@;
352 # Concatenate the sort_by limits and pass them to the results object
353 # Note: sort will override rank
355 foreach my $sort (@sort_by) {
356 if ( $sort eq "author_az" || $sort eq "author_asc" ) {
357 $sort_by .= "1=1003 <i ";
359 elsif ( $sort eq "author_za" || $sort eq "author_dsc" ) {
360 $sort_by .= "1=1003 >i ";
362 elsif ( $sort eq "popularity_asc" ) {
363 $sort_by .= "1=9003 <i ";
365 elsif ( $sort eq "popularity_dsc" ) {
366 $sort_by .= "1=9003 >i ";
368 elsif ( $sort eq "call_number_asc" ) {
369 $sort_by .= "1=8007 <i ";
371 elsif ( $sort eq "call_number_dsc" ) {
372 $sort_by .= "1=8007 >i ";
374 elsif ( $sort eq "pubdate_asc" ) {
375 $sort_by .= "1=31 <i ";
377 elsif ( $sort eq "pubdate_dsc" ) {
378 $sort_by .= "1=31 >i ";
380 elsif ( $sort eq "acqdate_asc" ) {
381 $sort_by .= "1=32 <i ";
383 elsif ( $sort eq "acqdate_dsc" ) {
384 $sort_by .= "1=32 >i ";
386 elsif ( $sort eq "title_az" || $sort eq "title_asc" ) {
387 $sort_by .= "1=4 <i ";
389 elsif ( $sort eq "title_za" || $sort eq "title_dsc" ) {
390 $sort_by .= "1=4 >i ";
393 warn "Ignoring unrecognized sort '$sort' requested" if $sort_by;
396 if ( $sort_by && !$scan && $results[$i] ) {
397 if ( $results[$i]->sort( "yaz", $sort_by ) < 0 ) {
398 warn "WARNING sort $sort_by failed";
401 } # finished looping through servers
403 # The big moment: asynchronously retrieve results from all servers
408 my ( $i, $size ) = @_;
411 # loop through the results
412 $results_hash->{'hits'} = $size;
414 if ( $offset + $results_per_page <= $size ) {
415 $times = $offset + $results_per_page;
421 for ( my $j = $offset ; $j < $times ; $j++ ) {
424 ## Check if it's an index scan
426 my ( $term, $occ ) = $results[ $i - 1 ]->display_term($j);
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
431 my $tmprecord = MARC::Record->new();
432 $tmprecord->encoding('UTF-8');
436 # the minimal record in author/title (depending on MARC flavour)
437 if ( C4::Context->preference("marcflavour") eq
440 $tmptitle = MARC::Field->new(
445 $tmprecord->append_fields($tmptitle);
449 MARC::Field->new( '245', ' ', ' ', a => $term, );
451 MARC::Field->new( '100', ' ', ' ', a => $occ, );
452 $tmprecord->append_fields($tmptitle);
453 $tmprecord->append_fields($tmpauthor);
455 $results_hash->{'RECORDS'}[$j] =
456 $tmprecord->as_usmarc();
461 $record = $results[ $i - 1 ]->record($j)->raw();
462 # warn "RECORD $j:".$record;
463 $results_hash->{'RECORDS'}[$j] = $record;
467 $results_hashref->{ $servers[ $i - 1 ] } = $results_hash;
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 );
477 if ( $servers[ $i - 1 ] =~ /biblioserver/ ) {
479 sort { $a cmp $b } keys %$facets_counter
482 my @this_facets_array;
485 $facets_counter->{$link_value}
486 ->{$b} <=> $facets_counter->{$link_value}
488 } keys %{ $facets_counter->{$link_value} }
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;
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')
501 substr( $one_facet, 0, $facet_max_length )
503 if length($facet_label_value) >
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
515 $branches->{$one_facet}
519 $facet_label_value = "*";
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
532 $itemtypes->{$one_facet}
533 ->{translated_description};
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 : '';
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 : '';
551 # but we're down with the whole label being in the link's title.
552 push @this_facets_array,
555 $facets_counter->{$link_value}
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,
562 if ($facet_label_value);
567 type_link_value => $link_value,
568 type_id => $link_value . "_id",
570 . $facets_info->{$link_value}->{'label_value'} =>
572 facets => \@this_facets_array,
576 $facets_info->{$link_value}->{'label_value'} =~
579 and ( Koha::Libraries->search->count == 1 )
586 # This sorts the facets into alphabetical order
588 foreach my $f (@facets_loop) {
589 $f->{facets} = [ sort { uc($a->{facet_label_value}) cmp uc($b->{facet_label_value}) } @{ $f->{facets} } ];
593 return ( undef, $results_hashref, \@facets_loop );
601 my $use_zebra_facets = C4::Context->config('use_zebra_facets') // 0;
603 if ( $use_zebra_facets ) {
604 $facets = _get_facets_from_zebra( $rs );
606 $facets = _get_facets_from_records( $rs );
612 sub _get_facets_from_records {
616 my $facets_maxrecs = C4::Context->preference('maxRecordsForFacets') // 20;
617 my $facets_config = getFacets();
619 my $size = $rs->size();
620 my $jmax = $size > $facets_maxrecs
624 for ( my $j = 0 ; $j < $jmax ; $j++ ) {
626 my $marc_record = new_record_from_zebra (
628 $rs->record( $j )->raw()
631 if ( ! defined $marc_record ) {
632 warn "ERROR DECODING RECORD - $@: " .
633 $rs->record( $j )->raw();
637 _get_facets_data_from_record( $marc_record, $facets_config, $facets );
643 =head2 _get_facets_data_from_record
645 C4::Search::_get_facets_data_from_record( $marc_record, $facets, $facets_counter );
647 Internal function that extracts facets information from a MARC::Record object
648 and populates $facets_counter for using in getRecords.
650 $facets is expected to be filled with C4::Koha::getFacets output (i.e. the configured
655 sub _get_facets_data_from_record {
657 my ( $marc_record, $facets, $facets_counter ) = @_;
659 for my $facet (@$facets) {
663 foreach my $tag ( @{ $facet->{ tags } } ) {
665 # tag number is the first three digits
666 my $tag_num = substr( $tag, 0, 3 );
667 # subfields are the remainder
668 my $subfield_letters = substr( $tag, 3 );
670 my @fields = $marc_record->field( $tag_num );
671 foreach my $field (@fields) {
672 # If $field->indicator(1) eq 'z', it means it is a 'see from'
673 # field introduced because of IncludeSeeFromInSearches, so skip it
674 next if $field->indicator(1) eq 'z';
676 my $data = $field->as_string( $subfield_letters, $facet->{ sep } );
677 $data =~ s/\s*(?<!\p{Uppercase})[.\-,;]*\s*$//;
679 unless ( grep { $_ eq $data } @used_datas ) {
680 push @used_datas, $data;
681 $facets_counter->{ $facet->{ idx } }->{ $data }++;
688 =head2 _get_facets_from_zebra
690 my $facets = _get_facets_from_zebra( $result_set )
692 Retrieves facets for a specified result set. It loops through the facets defined
693 in C4::Koha::getFacets and returns a hash with the following structure:
703 sub _get_facets_from_zebra {
707 # save current elementSetName
708 my $elementSetName = $rs->option( 'elementSetName' );
710 my $facets_loop = getFacets();
711 my $facets_data = {};
712 # loop through defined facets and fill the facets hashref
713 foreach my $facet ( @$facets_loop ) {
715 my $idx = $facet->{ idx };
716 my $sep = $facet->{ sep };
717 my $facet_values = _get_facet_from_result_set( $idx, $rs, $sep );
718 if ( $facet_values ) {
719 # we've actually got a result
720 $facets_data->{ $idx } = $facet_values;
723 # set elementSetName to its previous value to avoid side effects
724 $rs->option( elementSetName => $elementSetName );
729 =head2 _get_facet_from_result_set
732 C4::Search::_get_facet_from_result_set( $facet_idx, $result_set, $sep )
734 Internal function that extracts facet information for a specific index ($facet_idx) and
735 returns a hash containing facet values and count:
738 $facet_value => $count ,
742 Warning: this function has the side effect of changing the elementSetName for the result
743 set. It is a helper function for the main loop, which takes care of backing it up for
748 sub _get_facet_from_result_set {
750 my $facet_idx = shift;
754 my $internal_sep = '<*>';
755 my $facetMaxCount = C4::Context->preference('FacetMaxCount') // 20;
757 return if ( ! defined $facet_idx || ! defined $rs );
758 # zebra's facet element, untokenized index
759 my $facet_element = 'zebra::facet::' . $facet_idx . ':0:' . $facetMaxCount;
760 # configure zebra results for retrieving the desired facet
761 $rs->option( elementSetName => $facet_element );
762 # get the facet record from result set
763 my $facet = $rs->record( 0 )->raw;
764 # if the facet has no restuls...
765 return if !defined $facet;
766 # TODO: benchmark DOM vs. SAX performance
767 my $facet_dom = XML::LibXML->load_xml(
770 my @terms = $facet_dom->getElementsByTagName('term');
774 foreach my $term ( @terms ) {
775 my $facet_value = $term->textContent;
776 $facet_value =~ s/\s*(?<!\p{Uppercase})[.\-,;]*\s*$//;
777 $facet_value =~ s/\Q$internal_sep\E/$sep/ if defined $sep;
778 $facets->{ $facet_value } += $term->getAttribute( 'occur' );
784 =head2 _get_facets_info
786 my $facets_info = C4::Search::_get_facets_info( $facets )
788 Internal function that extracts facets information and properly builds
789 the data structure needed to render facet labels.
793 sub _get_facets_info {
797 my $facets_info = {};
799 for my $facet ( @$facets ) {
800 $facets_info->{ $facet->{ idx } }->{ label_value } = $facet->{ label };
807 sub _detect_truncation {
808 my ( $operand, $index ) = @_;
809 my ( @nontruncated, @righttruncated, @lefttruncated, @rightlefttruncated,
812 my @wordlist = split( /\s/, $operand );
813 foreach my $word (@wordlist) {
814 if ( $word =~ s/^\*([^\*]+)\*$/$1/ ) {
815 push @rightlefttruncated, $word;
817 elsif ( $word =~ s/^\*([^\*]+)$/$1/ ) {
818 push @lefttruncated, $word;
820 elsif ( $word =~ s/^([^\*]+)\*$/$1/ ) {
821 push @righttruncated, $word;
823 elsif ( index( $word, "*" ) < 0 ) {
824 push @nontruncated, $word;
827 push @regexpr, $word;
831 \@nontruncated, \@righttruncated, \@lefttruncated,
832 \@rightlefttruncated, \@regexpr
837 sub _build_stemmed_operand {
838 my ($operand,$lang) = @_;
839 require Lingua::Stem::Snowball ;
840 my $stemmed_operand=q{};
842 # Stemmer needs language
843 return $operand unless $lang;
845 # If operand contains a digit, it is almost certainly an identifier, and should
846 # not be stemmed. This is particularly relevant for ISBNs and ISSNs, which
847 # can contain the letter "X" - for example, _build_stemmend_operand would reduce
848 # "014100018X" to "x ", which for a MARC21 database would bring up irrelevant
849 # results (e.g., "23 x 29 cm." from the 300$c). Bug 2098.
850 return $operand if $operand =~ /\d/;
852 # FIXME: the locale should be set based on the user's language and/or search choice
854 # Make sure we only use the first two letters from the language code
855 $lang = lc(substr($lang, 0, 2));
856 # The language codes for the two variants of Norwegian will now be "nb" and "nn",
857 # none of which Lingua::Stem::Snowball can use, so we need to "translate" them
858 if ($lang eq 'nb' || $lang eq 'nn') {
861 my $stemmer = Lingua::Stem::Snowball->new( lang => $lang,
862 encoding => "UTF-8" );
864 my @words = split( / /, $operand );
865 my @stems = $stemmer->stem(\@words);
866 for my $stem (@stems) {
867 $stemmed_operand .= "$stem";
868 $stemmed_operand .= "?"
869 unless ( $stem =~ /(and$|or$|not$)/ ) || ( length($stem) < 3 );
870 $stemmed_operand .= " ";
872 warn "STEMMED OPERAND: $stemmed_operand" if $DEBUG;
873 return $stemmed_operand;
877 sub _build_weighted_query {
879 # FIELD WEIGHTING - This is largely experimental stuff. What I'm committing works
880 # pretty well but could work much better if we had a smarter query parser
881 my ( $operand, $stemmed_operand, $index ) = @_;
882 my $stemming = C4::Context->preference("QueryStemming") || 0;
883 my $weight_fields = C4::Context->preference("QueryWeightFields") || 0;
884 my $fuzzy_enabled = C4::Context->preference("QueryFuzzy") || 0;
885 $operand =~ s/"/ /g; # Bug 7518: searches with quotation marks don't work
887 my $weighted_query .= "(rk=("; # Specifies that we're applying rank
889 # Keyword, or, no index specified
890 if ( ( $index eq 'kw' ) || ( !$index ) ) {
892 "Title-cover,ext,r1=\"$operand\""; # exact title-cover
893 $weighted_query .= " or ti,ext,r2=\"$operand\""; # exact title
894 $weighted_query .= " or Title-cover,phr,r3=\"$operand\""; # phrase title
895 $weighted_query .= " or ti,wrdl,r4=\"$operand\""; # words in title
896 #$weighted_query .= " or any,ext,r4=$operand"; # exact any
897 #$weighted_query .=" or kw,wrdl,r5=\"$operand\""; # word list any
898 $weighted_query .= " or wrdl,fuzzy,r8=\"$operand\""
899 if $fuzzy_enabled; # add fuzzy, word list
900 $weighted_query .= " or wrdl,right-Truncation,r9=\"$stemmed_operand\""
901 if ( $stemming and $stemmed_operand )
902 ; # add stemming, right truncation
903 $weighted_query .= " or wrdl,r9=\"$operand\"";
905 # embedded sorting: 0 a-z; 1 z-a
906 # $weighted_query .= ") or (sort1,aut=1";
909 # Barcode searches should skip this process
910 elsif ( $index eq 'bc' ) {
911 $weighted_query .= "bc=\"$operand\"";
914 # Authority-number searches should skip this process
915 elsif ( $index eq 'an' ) {
916 $weighted_query .= "an=\"$operand\"";
919 # If the index is numeric, don't autoquote it.
920 elsif ( $index =~ /,st-numeric$/ ) {
921 $weighted_query .= " $index=$operand";
924 # If the index already has more than one qualifier, wrap the operand
925 # in quotes and pass it back (assumption is that the user knows what they
926 # are doing and won't appreciate us mucking up their query
927 elsif ( $index =~ ',' ) {
928 $weighted_query .= " $index=\"$operand\"";
931 #TODO: build better cases based on specific search indexes
933 $weighted_query .= " $index,ext,r1=\"$operand\""; # exact index
934 #$weighted_query .= " or (title-sort-az=0 or $index,startswithnt,st-word,r3=$operand #)";
935 $weighted_query .= " or $index,phr,r3=\"$operand\""; # phrase index
936 $weighted_query .= " or $index,wrdl,r6=\"$operand\""; # word list index
937 $weighted_query .= " or $index,wrdl,fuzzy,r8=\"$operand\""
938 if $fuzzy_enabled; # add fuzzy, word list
939 $weighted_query .= " or $index,wrdl,rt,r9=\"$stemmed_operand\""
940 if ( $stemming and $stemmed_operand ); # add stemming, right truncation
943 $weighted_query .= "))"; # close rank specification
944 return $weighted_query;
949 Return an array with available indexes.
973 'Author-personal-bibliography',
983 'Chronological-subdivision',
993 'Conference-name-heading',
994 'Conference-name-see',
995 'Conference-name-seealso',
1000 'Corporate-name-heading',
1001 'Corporate-name-see',
1002 'Corporate-name-seealso',
1003 'Country-publication',
1006 'date-entered-on-file',
1007 'Date-of-acquisition',
1008 'Date-of-publication',
1009 'Date-time-last-modified',
1010 'Dewey-classification',
1011 'Dissertation-information',
1020 'Geographic-subdivision',
1023 'Heading-use-main-or-added-entry',
1024 'Heading-use-series-added-entry ',
1025 'Heading-use-subject-added-entry',
1029 'Identifier-standard',
1030 'Illustration-code',
1032 'Index-term-uncontrolled',
1033 'Interest-age-level',
1034 'Interest-grade-level',
1044 'language-original',
1054 'Local-classification',
1057 'Match-heading-see-from',
1065 'Name-geographic-heading',
1066 'Name-geographic-see',
1067 'Name-geographic-seealso',
1073 'Other-control-number',
1076 'Personal-name-heading',
1077 'Personal-name-see',
1078 'Personal-name-seealso',
1080 'Place-publication',
1087 'Reading-grade-level',
1088 'Record-control-number',
1099 'Subject-heading-thesaurus',
1100 'Subject-name-personal',
1101 'Subject-subdivision',
1110 'Term-genre-form-heading',
1111 'Term-genre-form-see',
1112 'Term-genre-form-seealso',
1118 'Title-uniform-heading',
1119 'Title-uniform-see',
1120 'Title-uniform-seealso',
1130 'classification-source',
1132 'coded-location-qualifier',
1143 'Local-classification',
1146 'materials-specified',
1151 'Number-local-acquisition',
1156 'replacementpricedate',
1174 $simple_query, $query_cgi,
1175 $query_desc, $limit,
1176 $limit_cgi, $limit_desc,
1177 $query_type ) = buildQuery ( $operators, $operands, $indexes, $limits, $sort_by, $scan, $lang);
1179 Build queries and limits in CCL, CGI, Human,
1180 handle truncation, stemming, field weighting, fuzziness, etc.
1182 See verbose embedded documentation.
1188 my ( $operators, $operands, $indexes, $limits, $sort_by, $scan, $lang) = @_;
1189 warn "---------\nEnter buildQuery\n---------" if $DEBUG;
1194 my @operators = $operators ? @$operators : ();
1195 my @indexes = $indexes ? @$indexes : ();
1196 my @operands = $operands ? @$operands : ();
1197 my @limits = $limits ? @$limits : ();
1198 my @sort_by = $sort_by ? @$sort_by : ();
1200 my $stemming = C4::Context->preference("QueryStemming") || 0;
1201 my $auto_truncation = C4::Context->preference("QueryAutoTruncate") || 0;
1202 my $weight_fields = C4::Context->preference("QueryWeightFields") || 0;
1203 my $fuzzy_enabled = C4::Context->preference("QueryFuzzy") || 0;
1205 my $query = $operands[0];
1206 my $simple_query = $operands[0];
1208 # initialize the variables we're passing back
1217 my $cclindexes = getIndexes();
1218 if ( $query !~ /\s*(ccl=|pqf=|cql=)/ ) {
1219 while ( !$cclq && $query =~ /(?:^|\W)([\w-]+)(,[\w-]+)*[:=]/g ) {
1221 $cclq = grep { lc($_) eq $dx } @$cclindexes;
1223 $query = "ccl=$query" if $cclq;
1226 # for handling ccl, cql, pqf queries in diagnostic mode, skip the rest of the steps
1228 if ( $query =~ /^ccl=/ ) {
1230 # This is needed otherwise ccl= and &limit won't work together, and
1231 # this happens when selecting a subject on the opac-detail page
1232 @limits = grep {!/^$/} @limits;
1233 my $original_q = $q; # without available part
1234 unless ( grep { $_ eq 'available' } @limits ) {
1235 $q =~ s| and \( \(allrecords,AlwaysMatches=''\) and \(not-onloan-count,st-numeric >= 1\) and \(lost,st-numeric=0\) \)||;
1239 if ( grep { $_ eq 'available' } @limits ) {
1240 $q .= q| and ( (allrecords,AlwaysMatches='') and (not-onloan-count,st-numeric >= 1) and (lost,st-numeric=0) )|;
1241 @limits = grep {!/^available$/} @limits;
1243 $q .= ' and '.join(' and ', @limits) if @limits;
1245 return ( undef, $q, $q, "q=ccl=".uri_escape_utf8($q), $original_q, '', '', '', 'ccl' );
1247 if ( $query =~ /^cql=/ ) {
1248 return ( undef, $', $', "q=cql=".uri_escape_utf8($'), $', '', '', '', 'cql' );
1250 if ( $query =~ /^pqf=/ ) {
1252 $query_cgi = "q=pqf=".uri_escape_utf8($');
1253 return ( undef, $', $', $query_cgi, $query_desc, '', '', '', 'pqf' );
1256 # pass nested queries directly
1257 # FIXME: need better handling of some of these variables in this case
1258 # Nested queries aren't handled well and this implementation is flawed and causes users to be
1259 # unable to search for anything containing () commenting out, will be rewritten for 3.4.0
1260 # if ( $query =~ /(\(|\))/ ) {
1262 # undef, $query, $simple_query, $query_cgi,
1263 # $query, $limit, $limit_cgi, $limit_desc,
1268 # Form-based queries are non-nested and fixed depth, so we can easily modify the incoming
1269 # query operands and indexes and add stemming, truncation, field weighting, etc.
1270 # Once we do so, we'll end up with a value in $query, just like if we had an
1271 # incoming $query from the user
1274 ; # clear it out so we can populate properly with field-weighted, stemmed, etc. query
1275 my $previous_operand
1276 ; # a flag used to keep track if there was a previous query
1277 # if there was, we can apply the current operator
1279 for ( my $i = 0 ; $i <= @operands ; $i++ ) {
1281 # COMBINE OPERANDS, INDEXES AND OPERATORS
1282 if ( ($operands[$i] // '') ne '' ) {
1283 $operands[$i]=~s/^\s+//;
1285 # A flag to determine whether or not to add the index to the query
1288 # If the user is sophisticated enough to specify an index, turn off field weighting, and stemming handling
1289 if ( $operands[$i] =~ /\w(:|=)/ || $scan ) {
1293 $operands[$i] =~ s/\?/{?}/g; # need to escape question marks
1295 my $operand = $operands[$i];
1296 my $index = $indexes[$i] || 'kw';
1298 # Add index-specific attributes
1300 #Afaik, this 'yr' condition will only ever be met in the staff interface advanced search
1301 #for "Publication date", since typing 'yr:YYYY' into the search box produces a CCL query,
1302 #which is processed higher up in this sub. Other than that, year searches are typically
1303 #handled as limits which are not processed her either.
1305 # Search ranges: Date of Publication, st-numeric
1306 if ( $index =~ /(yr|st-numeric)/ ) {
1307 #weight_fields/relevance search causes errors with date ranges
1308 #In the case of YYYY-, it will only return records with a 'yr' of YYYY (not the range)
1309 #In the case of YYYY-YYYY, it will return no results
1310 $stemming = $auto_truncation = $weight_fields = $fuzzy_enabled = 0;
1313 # Date of Acquisition
1314 elsif ( $index =~ /acqdate/ ) {
1315 #stemming and auto_truncation would have zero impact since it already is YYYY-MM-DD format
1316 #Weight_fields probably SHOULD be turned OFF, otherwise you'll get records floating to the
1317 #top of the results just because they have lots of item records matching that date.
1318 #Fuzzy actually only applies during _build_weighted_query, and is reset there anyway, so
1320 $stemming = $auto_truncation = $weight_fields = $fuzzy_enabled = 0;
1322 # ISBN,ISSN,Standard Number, don't need special treatment
1323 elsif ( $index eq 'nb' || $index eq 'ns' || $index eq 'hi' ) {
1325 $stemming, $auto_truncation,
1326 $weight_fields, $fuzzy_enabled
1329 if ( $index eq 'nb' ) {
1330 if ( C4::Context->preference("SearchWithISBNVariations") ) {
1331 my @isbns = C4::Koha::GetVariationsOfISBN( $operand );
1332 $operands[$i] = $operand = '(nb=' . join(' OR nb=', @isbns) . ')';
1333 $indexes[$i] = $index = 'kw';
1338 # Set default structure attribute (word list)
1339 my $struct_attr = q{};
1340 unless ( $indexes_set || $index =~ /,(st-|phr|ext|wrdl)/ || $index =~ /^(nb|ns)$/ ) {
1341 $struct_attr = ",wrdl";
1344 # Some helpful index variants
1345 my $index_plus = $index . $struct_attr . ':';
1346 my $index_plus_comma = $index . $struct_attr . ',';
1348 if ($auto_truncation){
1349 unless ( $index =~ /,(st-|phr|ext)/ ) {
1350 #FIXME only valid with LTR scripts
1351 $operand=join(" ",map{
1352 (index($_,"*")>0?"$_":"$_*")
1353 }split (/\s+/,$operand));
1354 warn $operand if $DEBUG;
1359 my $truncated_operand;
1360 my( $nontruncated, $righttruncated, $lefttruncated,
1361 $rightlefttruncated, $regexpr
1362 ) = _detect_truncation( $operand, $index );
1364 "TRUNCATION: NON:>@$nontruncated< RIGHT:>@$righttruncated< LEFT:>@$lefttruncated< RIGHTLEFT:>@$rightlefttruncated< REGEX:>@$regexpr<"
1369 scalar(@$righttruncated) + scalar(@$lefttruncated) +
1370 scalar(@$rightlefttruncated) > 0 )
1373 # Don't field weight or add the index to the query, we do it here
1375 undef $weight_fields;
1376 my $previous_truncation_operand;
1377 if (scalar @$nontruncated) {
1378 $truncated_operand .= "$index_plus @$nontruncated ";
1379 $previous_truncation_operand = 1;
1381 if (scalar @$righttruncated) {
1382 $truncated_operand .= "and " if $previous_truncation_operand;
1383 $truncated_operand .= $index_plus_comma . "rtrn:@$righttruncated ";
1384 $previous_truncation_operand = 1;
1386 if (scalar @$lefttruncated) {
1387 $truncated_operand .= "and " if $previous_truncation_operand;
1388 $truncated_operand .= $index_plus_comma . "ltrn:@$lefttruncated ";
1389 $previous_truncation_operand = 1;
1391 if (scalar @$rightlefttruncated) {
1392 $truncated_operand .= "and " if $previous_truncation_operand;
1393 $truncated_operand .= $index_plus_comma . "rltrn:@$rightlefttruncated ";
1394 $previous_truncation_operand = 1;
1397 $operand = $truncated_operand if $truncated_operand;
1398 warn "TRUNCATED OPERAND: >$truncated_operand<" if $DEBUG;
1401 my $stemmed_operand;
1402 $stemmed_operand = _build_stemmed_operand($operand, $lang)
1405 warn "STEMMED OPERAND: >$stemmed_operand<" if $DEBUG;
1407 # Handle Field Weighting
1408 my $weighted_operand;
1409 if ($weight_fields) {
1410 $weighted_operand = _build_weighted_query( $operand, $stemmed_operand, $index );
1411 $operand = $weighted_operand;
1415 warn "FIELD WEIGHTED OPERAND: >$weighted_operand<" if $DEBUG;
1417 #Use relevance ranking when not using a weighted query (which adds relevance ranking of its own)
1419 #N.B. Truncation is mutually exclusive with Weighted Queries,
1420 #so even if QueryWeightFields is turned on, QueryAutoTruncate will turn it off, thus
1421 #the need for this relevance wrapper.
1422 $operand = "(rk=($operand))" unless $weight_fields;
1424 ($query,$query_cgi,$query_desc,$previous_operand) = _build_initial_query({
1426 query_cgi => $query_cgi,
1427 query_desc => $query_desc,
1428 operator => ($operators[ $i - 1 ]) ? $operators[ $i - 1 ] : '',
1429 parsed_operand => $operand,
1430 original_operand => $operands[$i] // '',
1432 index_plus => $index_plus,
1433 indexes_set => $indexes_set,
1434 previous_operand => $previous_operand,
1440 warn "QUERY BEFORE LIMITS: >$query<" if $DEBUG;
1443 my %group_OR_limits;
1444 my $availability_limit;
1445 foreach my $this_limit (@limits) {
1446 next unless $this_limit;
1447 if ( $this_limit =~ /available/ ) {
1449 ## 'available' is defined as (items.onloan is NULL) and (items.itemlost = 0)
1451 ## all records not indexed in the onloan register (zebra) and all records with a value of lost equal to 0
1452 $availability_limit .=
1453 "( (allrecords,AlwaysMatches='') and (not-onloan-count,st-numeric >= 1) and (lost,st-numeric=0) )";
1454 $limit_cgi .= "&limit=available";
1458 # group_OR_limits, prefixed by mc-
1459 # OR every member of the group
1460 elsif ( $this_limit =~ /mc/ ) {
1461 my ($k,$v) = split(/:/, $this_limit,2);
1462 if ( $k !~ /mc-i(tem)?type/ ) {
1463 # in case the mc-ccode value has complicating chars like ()'s inside it we wrap in quotes
1464 $this_limit =~ tr/"//d;
1465 $this_limit = $k.':"'.$v.'"';
1468 $group_OR_limits{$k} .= " or " if $group_OR_limits{$k};
1469 $limit_desc .= " or " if $group_OR_limits{$k};
1470 $group_OR_limits{$k} .= "$this_limit";
1471 $limit_cgi .= "&limit=" . uri_escape_utf8($this_limit);
1472 $limit_desc .= " $this_limit";
1475 # Regular old limits
1477 $limit .= " and " if $limit || $query;
1478 $limit .= "$this_limit";
1479 $limit_cgi .= "&limit=" . uri_escape_utf8($this_limit);
1480 if ($this_limit =~ /^branch:(.+)/) {
1481 my $branchcode = $1;
1482 my $library = Koha::Libraries->find( $branchcode );
1483 if (defined $library) {
1484 $limit_desc .= " branch:" . $library->branchname;
1486 $limit_desc .= " $this_limit";
1489 $limit_desc .= " $this_limit";
1493 foreach my $k (keys (%group_OR_limits)) {
1494 $limit .= " and " if ( $query || $limit );
1495 $limit .= "($group_OR_limits{$k})";
1497 if ($availability_limit) {
1498 $limit .= " and " if ( $query || $limit );
1499 $limit .= "($availability_limit)";
1502 # Normalize the query and limit strings
1503 # This is flawed , means we can't search anything with : in it
1504 # if user wants to do ccl or cql, start the query with that
1505 # $query =~ s/:/=/g;
1506 #NOTE: We use several several different regexps here as you can't have variable length lookback assertions
1507 $query =~ s/(?<=(ti|au|pb|su|an|kw|mc|nb|ns)):/=/g;
1508 $query =~ s/(?<=(wrdl)):/=/g;
1509 $query =~ s/(?<=(trn|phr)):/=/g;
1510 $query =~ s/(?<=(st-numeric)):/=/g;
1511 $query =~ s/(?<=(st-year)):/=/g;
1512 $query =~ s/(?<=(st-date-normalized)):/=/g;
1514 # Removing warnings for later substitutions
1516 $query_desc //= q{};
1519 $limit_desc //= q{};
1521 for ( $query, $query_desc, $limit, $limit_desc ) {
1522 s/ +/ /g; # remove extra spaces
1523 s/^ //g; # remove any beginning spaces
1524 s/ $//g; # remove any ending spaces
1525 s/==/=/g; # remove double == from query
1527 $query_cgi =~ s/^&//; # remove unnecessary & from beginning of the query cgi
1529 for ($query_cgi,$simple_query) {
1532 # append the limit to the query
1533 $query .= " " . $limit;
1537 warn "QUERY:" . $query;
1538 warn "QUERY CGI:" . $query_cgi;
1539 warn "QUERY DESC:" . $query_desc;
1540 warn "LIMIT:" . $limit;
1541 warn "LIMIT CGI:" . $limit_cgi;
1542 warn "LIMIT DESC:" . $limit_desc;
1543 warn "---------\nLeave buildQuery\n---------";
1547 undef, $query, $simple_query, $query_cgi,
1548 $query_desc, $limit, $limit_cgi, $limit_desc,
1553 =head2 _build_initial_query
1555 ($query, $query_cgi, $query_desc, $previous_operand) = _build_initial_query($initial_query_params);
1557 Build a section of the initial query containing indexes, operators, and operands.
1561 sub _build_initial_query {
1565 if ($params->{previous_operand}){
1566 #If there is a previous operand, add a supplied operator or the default 'and'
1567 $operator = ($params->{operator}) ? " ".($params->{operator})." " : ' and ';
1570 #NOTE: indexes_set is typically set when doing truncation or field weighting
1571 my $operand = ($params->{indexes_set}) ? $params->{parsed_operand} : $params->{index_plus}.$params->{parsed_operand};
1573 #e.g. "kw,wrdl:test"
1574 #e.g. " and kw,wrdl:test"
1575 $params->{query} .= $operator . $operand;
1577 $params->{query_cgi} .= "&op=".uri_escape_utf8($operator) if $operator;
1578 $params->{query_cgi} .= "&idx=".uri_escape_utf8($params->{index}) if $params->{index};
1579 $params->{query_cgi} .= "&q=".uri_escape_utf8($params->{original_operand}) if $params->{original_operand};
1581 #e.g. " and kw,wrdl: test"
1582 $params->{query_desc} .= $operator . ( $params->{index_plus} // q{} ) . " " . ( $params->{original_operand} // q{} );
1584 $params->{previous_operand} = 1 unless $params->{previous_operand}; #If there is no previous operand, mark this as one
1586 return ($params->{query}, $params->{query_cgi}, $params->{query_desc}, $params->{previous_operand});
1589 =head2 searchResults
1591 my @search_results = searchResults($search_context, $searchdesc, $hits,
1592 $results_per_page, $offset, $scan,
1595 Format results in a form suitable for passing to the template
1599 # IMO this subroutine is pretty messy still -- it's responsible for
1600 # building the HTML output for the template
1602 my ( $search_context, $searchdesc, $hits, $results_per_page, $offset, $scan, $marcresults, $xslt_variables ) = @_;
1603 my $dbh = C4::Context->dbh;
1608 $search_context->{'interface'} = 'opac' if !$search_context->{'interface'} || $search_context->{'interface'} ne 'intranet';
1609 my ($is_opac, $hidelostitems);
1610 if ($search_context->{'interface'} eq 'opac') {
1611 $hidelostitems = C4::Context->preference('hidelostitems');
1615 my $record_processor = Koha::RecordProcessor->new({
1616 filters => 'ViewPolicy'
1619 #Build branchnames hash
1620 my %branches = map { $_->branchcode => $_->branchname } Koha::Libraries->search({}, { order_by => 'branchname' });
1622 # FIXME - We build an authorised values hash here, using the default framework
1623 # though it is possible to have different authvals for different fws.
1625 my $shelflocations =
1626 { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.location' } ) };
1628 # get notforloan authorised value list (see $shelflocations FIXME)
1629 my $av = Koha::MarcSubfieldStructures->search({ frameworkcode => '', kohafield => 'items.notforloan', authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] });
1630 my $notforloan_authorised_value = $av->count ? $av->next->authorised_value : undef;
1633 my $itemtypes = Koha::ItemTypes->search_with_localization;
1634 my %itemtypes = map { $_->{itemtype} => $_ } @{ $itemtypes->unblessed };
1636 #search item field code
1637 my ($itemtag, undef) = &GetMarcFromKohaField( "items.itemnumber" );
1639 ## find column names of items related to MARC
1640 my %subfieldstosearch;
1641 my @columns = Koha::Database->new()->schema()->resultset('Item')->result_source->columns;
1642 for my $column ( @columns ) {
1643 my ( $tagfield, $tagsubfield ) =
1644 &GetMarcFromKohaField( "items." . $column );
1645 if ( defined $tagsubfield ) {
1646 $subfieldstosearch{$column} = $tagsubfield;
1650 # handle which records to actually retrieve
1652 if ( $hits && $offset + $results_per_page <= $hits ) {
1653 $times = $offset + $results_per_page;
1656 $times = $hits; # FIXME: if $hits is undefined, why do we want to equal it?
1659 my $marcflavour = C4::Context->preference("marcflavour");
1660 # We get the biblionumber position in MARC
1661 my ($bibliotag,$bibliosubf)=GetMarcFromKohaField( 'biblio.biblionumber' );
1663 # set stuff for XSLT processing here once, not later again for every record we retrieved
1667 $xslsyspref = "OPACXSLTResultsDisplay";
1668 $xslfile = C4::Context->preference( $xslsyspref );
1670 $xslsyspref = "XSLTResultsDisplay";
1671 $xslfile = C4::Context->preference( $xslsyspref ) || "default";
1673 my $lang = $xslfile ? C4::Languages::getlanguage() : undef;
1674 my $sysxml = $xslfile ? C4::XSLT::get_xslt_sysprefs() : undef;
1676 my $userenv = C4::Context->userenv;
1678 = ( defined $userenv and $userenv->{number} )
1679 ? Koha::Patrons->find( $userenv->{number} )
1681 my $patron_category_hide_lost_items = ($logged_in_user) ? $logged_in_user->category->hidelostitems : 0;
1683 # loop through all of the records we've retrieved
1684 for ( my $i = $offset ; $i <= $times - 1 ; $i++ ) {
1688 # For Scan searches we built USMARC data
1689 $marcrecord = MARC::Record->new_from_usmarc( $marcresults->[$i]);
1691 # Normal search, render from Zebra's output
1692 $marcrecord = new_record_from_zebra(
1697 if ( ! defined $marcrecord ) {
1698 warn "ERROR DECODING RECORD - $@: " . $marcresults->[$i];
1706 ? GetFrameworkCode($marcrecord->field($bibliotag)->data)
1707 : GetFrameworkCode($marcrecord->subfield($bibliotag,$bibliosubf));
1709 SetUTF8Flag($marcrecord);
1710 my $oldbiblio = TransformMarcToKoha( $marcrecord, $fw );
1711 $oldbiblio->{result_number} = $i + 1;
1713 $oldbiblio->{normalized_upc} = GetNormalizedUPC( $marcrecord,$marcflavour);
1714 $oldbiblio->{normalized_ean} = GetNormalizedEAN( $marcrecord,$marcflavour);
1715 $oldbiblio->{normalized_oclc} = GetNormalizedOCLCNumber($marcrecord,$marcflavour);
1716 $oldbiblio->{normalized_isbn} = GetNormalizedISBN(undef,$marcrecord,$marcflavour);
1717 $oldbiblio->{content_identifier_exists} = 1 if ($oldbiblio->{normalized_isbn} or $oldbiblio->{normalized_oclc} or $oldbiblio->{normalized_ean} or $oldbiblio->{normalized_upc});
1719 # edition information, if any
1720 $oldbiblio->{edition} = $oldbiblio->{editionstatement};
1722 my $itemtype = $oldbiblio->{itemtype} ? $itemtypes{$oldbiblio->{itemtype}} : undef;
1723 # add imageurl to itemtype if there is one
1724 $oldbiblio->{imageurl} = $itemtype ? getitemtypeimagelocation( $search_context->{'interface'}, $itemtype->{imageurl} ) : q{};
1725 # Build summary if there is one (the summary is defined in the itemtypes table)
1726 $oldbiblio->{description} = $itemtype ? $itemtype->{translated_description} : q{};
1728 # FIXME: this is only used in the deprecated non-XLST opac results
1729 if ( !$xslfile && $is_opac && $itemtype && $itemtype->{summary} ) {
1730 my $summary = $itemtypes{ $oldbiblio->{itemtype} }->{summary};
1731 my @fields = $marcrecord->fields();
1734 foreach my $line ( "$summary\n" =~ /(.*)\n/g ){
1736 foreach my $tag ( $line =~ /\[(\d{3}[\w|\d])\]/ ) {
1737 $tag =~ /(.{3})(.)/;
1738 if($marcrecord->field($1)){
1739 my @abc = $marcrecord->field($1)->subfield($2);
1740 $tags->{$tag} = $#abc + 1 ;
1744 # We catch how many times to repeat this line
1746 foreach my $tag (keys(%$tags)){
1747 $max = $tags->{$tag} if($tags->{$tag} > $max);
1750 # we replace, and repeat each line
1751 for (my $i = 0 ; $i < $max ; $i++){
1752 my $newline = $line;
1754 foreach my $tag ( $newline =~ /\[(\d{3}[\w|\d])\]/g ) {
1755 $tag =~ /(.{3})(.)/;
1757 if($marcrecord->field($1)){
1758 my @repl = $marcrecord->field($1)->subfield($2);
1759 my $subfieldvalue = $repl[$i];
1760 $newline =~ s/\[$tag\]/$subfieldvalue/g;
1763 $newsummary .= "$newline\n";
1767 $newsummary =~ s/\[(.*?)]//g;
1768 $newsummary =~ s/\n/<br\/>/g;
1769 $oldbiblio->{summary} = $newsummary;
1772 # Pull out the items fields
1773 my @fields = $marcrecord->field($itemtag);
1774 my $marcflavor = C4::Context->preference("marcflavour");
1776 # adding linked items that belong to host records
1777 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
1778 my $analyticsfield = '773';
1779 if ($marcflavor eq 'MARC21' || $marcflavor eq 'NORMARC') {
1780 $analyticsfield = '773';
1781 } elsif ($marcflavor eq 'UNIMARC') {
1782 $analyticsfield = '461';
1784 foreach my $hostfield ( $marcrecord->field($analyticsfield)) {
1785 my $hostbiblionumber = $hostfield->subfield("0");
1786 my $linkeditemnumber = $hostfield->subfield("9");
1787 if( $hostbiblionumber ) {
1788 my $linkeditemmarc = C4::Items::GetMarcItem( $hostbiblionumber, $linkeditemnumber );
1789 if ($linkeditemmarc) {
1790 my $linkeditemfield = $linkeditemmarc->field($itemtag);
1791 if ($linkeditemfield) {
1792 push( @fields, $linkeditemfield );
1799 # Setting item statuses for display
1800 my @available_items_loop;
1801 my @onloan_items_loop;
1802 my @other_items_loop;
1804 my $available_items;
1808 my $ordered_count = 0;
1809 my $available_count = 0;
1810 my $onloan_count = 0;
1811 my $longoverdue_count = 0;
1812 my $other_count = 0;
1813 my $withdrawn_count = 0;
1814 my $itemlost_count = 0;
1815 my $hideatopac_count = 0;
1816 my $itembinding_count = 0;
1817 my $itemdamaged_count = 0;
1818 my $item_in_transit_count = 0;
1819 my $can_place_holds = 0;
1820 my $item_onhold_count = 0;
1821 my $notforloan_count = 0;
1822 my $items_count = scalar(@fields);
1823 my $maxitems_pref = C4::Context->preference('maxItemsinSearchResults');
1824 my $maxitems = $maxitems_pref ? $maxitems_pref - 1 : 1;
1825 my @hiddenitems; # hidden itemnumbers based on OpacHiddenItems syspref
1827 # loop through every item
1828 foreach my $field (@fields) {
1831 # populate the items hash
1832 foreach my $code ( keys %subfieldstosearch ) {
1833 $item->{$code} = $field->subfield( $subfieldstosearch{$code} );
1835 $item->{description} = $itemtypes{ $item->{itype} }{translated_description} if $item->{itype};
1839 # hidden because lost
1840 if ($hidelostitems && $item->{itemlost}) {
1841 $hideatopac_count++;
1844 # hidden based on OpacHiddenItems syspref
1845 my @hi = C4::Items::GetHiddenItemnumbers({ items=> [ $item ], borcat => $search_context->{category} });
1847 push @hiddenitems, @hi;
1848 $hideatopac_count++;
1853 my $hbranch = C4::Context->preference('StaffSearchResultsDisplayBranch');
1854 my $otherbranch = $hbranch eq 'homebranch' ? 'holdingbranch' : 'homebranch';
1856 # set item's branch name, use HomeOrHoldingBranch syspref first, fall back to the other one
1857 if ($item->{$hbranch}) {
1858 $item->{'branchname'} = $branches{$item->{$hbranch}};
1860 elsif ($item->{$otherbranch}) { # Last resort
1861 $item->{'branchname'} = $branches{$item->{$otherbranch}};
1865 ( $item->{$hbranch} ? $item->{$hbranch} . '--' : q{} )
1866 . ( $item->{location} ? $item->{location} : q{} )
1867 . ( $item->{itype} ? $item->{itype} : q{} )
1868 . ( $item->{itemcallnumber} ? $item->{itemcallnumber} : q{} );
1869 # For each grouping of items (onloan, available, unavailable), we build a key to store relevant info about that item
1870 if ( $item->{onloan}
1872 and !( $patron_category_hide_lost_items and $item->{itemlost} ) )
1875 my $key = $prefix . $item->{onloan} . $item->{barcode};
1876 $onloan_items->{$key}->{due_date} = $item->{onloan};
1877 $onloan_items->{$key}->{count}++ if $item->{$hbranch};
1878 $onloan_items->{$key}->{branchname} = $item->{branchname};
1879 $onloan_items->{$key}->{location} = $shelflocations->{ $item->{location} } if $item->{location};
1880 $onloan_items->{$key}->{itemcallnumber} = $item->{itemcallnumber};
1881 $onloan_items->{$key}->{description} = $item->{description};
1882 $onloan_items->{$key}->{imageurl} =
1883 getitemtypeimagelocation( $search_context->{'interface'}, $itemtypes{ $item->{itype} }->{imageurl} );
1885 # if something's checked out and lost, mark it as 'long overdue'
1886 if ( $item->{itemlost} ) {
1887 $onloan_items->{$key}->{longoverdue}++;
1888 $longoverdue_count++;
1890 else { # can place holds as long as item isn't lost
1891 $can_place_holds = 1;
1895 # items not on loan, but still unavailable ( lost, withdrawn, damaged )
1898 my $itemtype = C4::Context->preference("item-level_itypes")? $item->{itype}: $oldbiblio->{itemtype};
1899 $item->{notforloan} = 1 if !$item->{notforloan} &&
1900 $itemtype && $itemtypes{ $itemtype }->{notforloan};
1903 if ( $item->{notforloan} < 0 ) {
1905 } elsif ( $item->{notforloan} > 0 ) {
1906 $notforloan_count++;
1909 # is item in transit?
1910 my $transfertwhen = '';
1911 my ($transfertfrom, $transfertto);
1913 # is item on the reserve shelf?
1914 my $reservestatus = '';
1916 unless ($item->{withdrawn}
1917 || $item->{itemlost}
1919 || $item->{notforloan}
1920 || ( C4::Context->preference('MaxSearchResultsItemsPerRecordStatusCheck')
1921 && $items_count > C4::Context->preference('MaxSearchResultsItemsPerRecordStatusCheck') ) ) {
1923 # A couple heuristics to limit how many times
1924 # we query the database for item transfer information, sacrificing
1925 # accuracy in some cases for speed;
1927 # 1. don't query if item has one of the other statuses
1928 # 2. don't check transit status if the bib has
1929 # more than 20 items
1931 # FIXME: to avoid having the query the database like this, and to make
1932 # the in transit status count as unavailable for search limiting,
1933 # should map transit status to record indexed in Zebra.
1935 ($transfertwhen, $transfertfrom, $transfertto) = C4::Circulation::GetTransfers($item->{itemnumber});
1936 $reservestatus = C4::Reserves::GetReserveStatus( $item->{itemnumber} );
1939 # item is withdrawn, lost, damaged, not for loan, reserved or in transit
1940 if ( $item->{withdrawn}
1941 || $item->{itemlost}
1943 || $item->{notforloan}
1944 || $reservestatus eq 'Waiting'
1945 || ($transfertwhen && $transfertwhen ne ''))
1947 $withdrawn_count++ if $item->{withdrawn};
1948 $itemlost_count++ if $item->{itemlost};
1949 $itemdamaged_count++ if $item->{damaged};
1950 $item_in_transit_count++ if $transfertwhen && $transfertwhen ne '';
1951 $item_onhold_count++ if $reservestatus eq 'Waiting';
1952 $item->{status} = ($item->{withdrawn}//q{}) . "-" . ($item->{itemlost}//q{}) . "-" . ($item->{damaged}//q{}) . "-" . ($item->{notforloan}//q{});
1954 # can place a hold on a item if
1955 # not lost nor withdrawn
1956 # not damaged unless AllowHoldsOnDamagedItems is true
1957 # item is either for loan or on order (notforloan < 0)
1958 $can_place_holds = 1
1961 && !$item->{withdrawn}
1962 && ( !$item->{damaged} || C4::Context->preference('AllowHoldsOnDamagedItems') )
1963 && ( !$item->{notforloan} || $item->{notforloan} < 0 )
1968 my $key = $prefix . $item->{status};
1969 foreach (qw(withdrawn itemlost damaged branchname itemcallnumber)) {
1970 $other_items->{$key}->{$_} = $item->{$_};
1972 $other_items->{$key}->{intransit} = ( $transfertwhen ne '' ) ? 1 : 0;
1973 $other_items->{$key}->{onhold} = ($reservestatus) ? 1 : 0;
1974 $other_items->{$key}->{notforloan} = GetAuthorisedValueDesc('','',$item->{notforloan},'','',$notforloan_authorised_value) if $notforloan_authorised_value and $item->{notforloan};
1975 $other_items->{$key}->{count}++ if $item->{$hbranch};
1976 $other_items->{$key}->{location} = $shelflocations->{ $item->{location} } if $item->{location};
1977 $other_items->{$key}->{description} = $item->{description};
1978 $other_items->{$key}->{imageurl} = getitemtypeimagelocation( $search_context->{'interface'}, $itemtypes{ $item->{itype}//q{} }->{imageurl} );
1982 $can_place_holds = 1;
1984 $available_items->{$prefix}->{count}++ if $item->{$hbranch};
1985 foreach (qw(branchname itemcallnumber description)) {
1986 $available_items->{$prefix}->{$_} = $item->{$_};
1988 $available_items->{$prefix}->{location} = $shelflocations->{ $item->{location} } if $item->{location};
1989 $available_items->{$prefix}->{imageurl} = getitemtypeimagelocation( $search_context->{'interface'}, $itemtypes{ $item->{itype}//q{} }->{imageurl} );
1992 } # notforloan, item level and biblioitem level
1994 # if all items are hidden, do not show the record
1995 if ( C4::Context->preference('OpacHiddenItemsHidesRecord') && $items_count > 0 && $hideatopac_count == $items_count) {
1999 my ( $availableitemscount, $onloanitemscount, $otheritemscount );
2000 for my $key ( sort keys %$onloan_items ) {
2001 (++$onloanitemscount > $maxitems) and last;
2002 push @onloan_items_loop, $onloan_items->{$key};
2004 for my $key ( sort keys %$other_items ) {
2005 (++$otheritemscount > $maxitems) and last;
2006 push @other_items_loop, $other_items->{$key};
2008 for my $key ( sort keys %$available_items ) {
2009 (++$availableitemscount > $maxitems) and last;
2010 push @available_items_loop, $available_items->{$key}
2013 # XSLT processing of some stuff
2014 # we fetched the sysprefs already before the loop through all retrieved record!
2015 if (!$scan && $xslfile) {
2016 $record_processor->options({
2017 frameworkcode => $fw,
2018 interface => $search_context->{'interface'}
2021 $record_processor->process($marcrecord);
2022 $oldbiblio->{XSLTResultsRecord} = XSLTParse4Display($oldbiblio->{biblionumber}, $marcrecord, $xslsyspref, 1, \@hiddenitems, $sysxml, $xslfile, $lang, $xslt_variables);
2025 # if biblio level itypes are used and itemtype is notforloan, it can't be reserved either
2026 if (!C4::Context->preference("item-level_itypes")) {
2027 if ($itemtype && $itemtype->{notforloan}) {
2028 $can_place_holds = 0;
2031 $oldbiblio->{norequests} = 1 unless $can_place_holds;
2032 $oldbiblio->{items_count} = $items_count;
2033 $oldbiblio->{available_items_loop} = \@available_items_loop;
2034 $oldbiblio->{onloan_items_loop} = \@onloan_items_loop;
2035 $oldbiblio->{other_items_loop} = \@other_items_loop;
2036 $oldbiblio->{availablecount} = $available_count;
2037 $oldbiblio->{availableplural} = 1 if $available_count > 1;
2038 $oldbiblio->{onloancount} = $onloan_count;
2039 $oldbiblio->{onloanplural} = 1 if $onloan_count > 1;
2040 $oldbiblio->{othercount} = $other_count;
2041 $oldbiblio->{otherplural} = 1 if $other_count > 1;
2042 $oldbiblio->{withdrawncount} = $withdrawn_count;
2043 $oldbiblio->{itemlostcount} = $itemlost_count;
2044 $oldbiblio->{damagedcount} = $itemdamaged_count;
2045 $oldbiblio->{intransitcount} = $item_in_transit_count;
2046 $oldbiblio->{onholdcount} = $item_onhold_count;
2047 $oldbiblio->{orderedcount} = $ordered_count;
2048 $oldbiblio->{notforloancount} = $notforloan_count;
2050 if (C4::Context->preference("AlternateHoldingsField") && $items_count == 0) {
2051 my $fieldspec = C4::Context->preference("AlternateHoldingsField");
2052 my $subfields = substr $fieldspec, 3;
2053 my $holdingsep = C4::Context->preference("AlternateHoldingsSeparator") || ' ';
2054 my @alternateholdingsinfo = ();
2055 my @holdingsfields = $marcrecord->field(substr $fieldspec, 0, 3);
2056 my $alternateholdingscount = 0;
2058 for my $field (@holdingsfields) {
2059 my %holding = ( holding => '' );
2060 my $havesubfield = 0;
2061 for my $subfield ($field->subfields()) {
2062 if ((index $subfields, $$subfield[0]) >= 0) {
2063 $holding{'holding'} .= $holdingsep if (length $holding{'holding'} > 0);
2064 $holding{'holding'} .= $$subfield[1];
2068 if ($havesubfield) {
2069 push(@alternateholdingsinfo, \%holding);
2070 $alternateholdingscount++;
2074 $oldbiblio->{'ALTERNATEHOLDINGS'} = \@alternateholdingsinfo;
2075 $oldbiblio->{'alternateholdings_count'} = $alternateholdingscount;
2078 $oldbiblio->{biblio_object} = Koha::Biblios->find( $oldbiblio->{biblionumber} );
2080 push( @newresults, $oldbiblio );
2086 =head2 enabled_staff_search_views
2088 %hash = enabled_staff_search_views()
2090 This function returns a hash that contains three flags obtained from the system
2091 preferences, used to determine whether a particular staff search results view
2096 =item C<Output arg:>
2098 * $hash{can_view_MARC} is true only if the MARC view is enabled
2099 * $hash{can_view_ISBD} is true only if the ISBD view is enabled
2100 * $hash{can_view_labeledMARC} is true only if the Labeled MARC view is enabled
2102 =item C<usage in the script:>
2106 $template->param ( C4::Search::enabled_staff_search_views );
2110 sub enabled_staff_search_views
2113 can_view_MARC => C4::Context->preference('viewMARC'), # 1 if the staff search allows the MARC view
2114 can_view_ISBD => C4::Context->preference('viewISBD'), # 1 if the staff search allows the ISBD view
2115 can_view_labeledMARC => C4::Context->preference('viewLabeledMARC'), # 1 if the staff search allows the Labeled MARC view
2119 =head2 z3950_search_args
2121 $arrayref = z3950_search_args($matchpoints)
2123 This function returns an array reference that contains the search parameters to be
2124 passed to the Z39.50 search script (z3950_search.pl). The array elements
2125 are hash refs whose keys are name and value, and whose values are the
2126 name of a search parameter, the value of that search parameter and the URL encoded
2127 value of that parameter.
2129 The search parameter names are lccn, isbn, issn, title, author, dewey and subject.
2131 The search parameter values are obtained from the bibliographic record whose
2132 data is in a hash reference in $matchpoints, as returned by Biblio::GetBiblioData().
2134 If $matchpoints is a scalar, it is assumed to be an unnamed query descriptor, e.g.
2135 a general purpose search argument. In this case, the returned array contains only
2136 entry: the key is 'title' and the value is derived from $matchpoints.
2138 If a search parameter value is undefined or empty, it is not included in the returned
2141 The returned array reference may be passed directly to the template parameters.
2145 =item C<Output arg:>
2147 * $array containing hash refs as described above
2149 =item C<usage in the script:>
2153 $data = Biblio::GetBiblioData($bibno);
2154 $template->param ( MYLOOP => C4::Search::z3950_search_args($data) )
2158 $template->param ( MYLOOP => C4::Search::z3950_search_args($searchscalar) )
2162 sub z3950_search_args {
2165 my $isbn_string = ref( $bibrec ) ? $bibrec->{title} : $bibrec;
2166 my $isbn = Business::ISBN->new( $isbn_string );
2168 if (defined $isbn && $isbn->is_valid)
2170 if ( ref($bibrec) ) {
2171 $bibrec->{isbn} = $isbn_string;
2172 $bibrec->{title} = undef;
2174 $bibrec = { isbn => $isbn_string };
2178 $bibrec = { title => $bibrec } if !ref $bibrec;
2181 for my $field (qw/ lccn isbn issn title author dewey subject /)
2183 push @$array, { name => $field, value => $bibrec->{$field} }
2184 if defined $bibrec->{$field};
2189 =head2 GetDistinctValues($field);
2191 C<$field> is a reference to the fields array
2195 sub GetDistinctValues {
2196 my ($fieldname,$string)=@_;
2197 # returns a reference to a hash of references to branches...
2198 if ($fieldname=~/\./){
2199 my ($table,$column)=split /\./, $fieldname;
2200 my $dbh = C4::Context->dbh;
2201 warn "select DISTINCT($column) as value, count(*) as cnt from $table group by lib order by $column " if $DEBUG;
2202 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 ");
2204 my $elements=$sth->fetchall_arrayref({});
2209 my @servers=qw<biblioserver authorityserver>;
2210 my (@zconns,@results);
2211 for ( my $i = 0 ; $i < @servers ; $i++ ) {
2212 $zconns[$i] = C4::Context->Zconn( $servers[$i], 1 );
2215 ZOOM::Query::CCL2RPN->new( qq"$fieldname $string", $zconns[$i])
2218 # The big moment: asynchronously retrieve results from all servers
2224 my ( $i, $size ) = @_;
2225 for ( my $j = 0 ; $j < $size ; $j++ ) {
2227 @hashscan{qw(value cnt)} =
2228 $results[ $i - 1 ]->display_term($j);
2229 push @elements, \%hashscan;
2237 =head2 _ZOOM_event_loop
2239 _ZOOM_event_loop(\@zconns, \@results, sub {
2240 my ( $i, $size ) = @_;
2244 Processes a ZOOM event loop and passes control to a closure for
2245 processing the results, and destroying the resultsets.
2249 sub _ZOOM_event_loop {
2250 my ($zconns, $results, $callback) = @_;
2251 while ( ( my $i = ZOOM::event( $zconns ) ) != 0 ) {
2252 my $ev = $zconns->[ $i - 1 ]->last_event();
2253 if ( $ev == ZOOM::Event::ZEND ) {
2254 next unless $results->[ $i - 1 ];
2255 my $size = $results->[ $i - 1 ]->size();
2257 $callback->($i, $size);
2262 foreach my $result (@$results) {
2267 =head2 new_record_from_zebra
2269 Given raw data from a searchengine result set, return a MARC::Record object
2271 This helper function is needed to take into account all the involved
2272 system preferences and configuration variables to properly create the
2273 MARC::Record object.
2275 If we are using GRS-1, then the raw data we get from Zebra should be USMARC
2276 data. If we are using DOM, then it has to be MARCXML.
2278 If we are using elasticsearch, it'll already be a MARC::Record and this
2279 function needs a new name.
2283 sub new_record_from_zebra {
2286 my $raw_data = shift;
2287 # Set the default indexing modes
2288 my $search_engine = C4::Context->preference("SearchEngine");
2289 if ($search_engine eq 'Elasticsearch') {
2290 return ref $raw_data eq 'MARC::Record' ? $raw_data : MARC::Record->new_from_xml( $raw_data, 'UTF-8' );
2292 my $index_mode = ( $server eq 'biblioserver' )
2293 ? C4::Context->config('zebra_bib_index_mode') // 'dom'
2294 : C4::Context->config('zebra_auth_index_mode') // 'dom';
2296 my $marc_record = eval {
2297 if ( $index_mode eq 'dom' ) {
2298 MARC::Record->new_from_xml( $raw_data, 'UTF-8' );
2300 MARC::Record->new_from_usmarc( $raw_data );
2307 return $marc_record;
2312 END { } # module clean-up code here (global destructor)
2319 Koha Development Team <http://koha-community.org/>