-
Notifications
You must be signed in to change notification settings - Fork 257
/
Search.pm
2341 lines (1983 loc) · 88.8 KB
/
Search.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package C4::Search;
# This file is part of Koha.
#
# Koha is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# Koha is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Koha; if not, see <http://www.gnu.org/licenses>.
use Modern::Perl;
use C4::Context;
use C4::Biblio qw( TransformMarcToKoha GetMarcFromKohaField GetFrameworkCode GetAuthorisedValueDesc GetBiblioData );
use C4::Koha qw( getFacets GetVariationsOfISBN GetNormalizedUPC GetNormalizedEAN GetNormalizedOCLCNumber GetNormalizedISBN getitemtypeimagelocation );
use Koha::DateUtils;
use Koha::Libraries;
use Koha::SearchEngine::QueryBuilder;
use Lingua::Stem;
use XML::Simple;
use C4::XSLT qw( XSLTParse4Display );
use C4::Reserves qw( GetReserveStatus );
use C4::Charset qw( SetUTF8Flag );
use Koha::AuthorisedValues;
use Koha::ItemTypes;
use Koha::Libraries;
use Koha::Logger;
use Koha::Patrons;
use Koha::Recalls;
use Koha::RecordProcessor;
use Koha::SearchFilters;
use URI::Escape;
use Business::ISBN;
use MARC::Record;
use MARC::Field;
our (@ISA, @EXPORT_OK);
BEGIN {
require Exporter;
@ISA = qw(Exporter);
@EXPORT_OK = qw(
FindDuplicate
SimpleSearch
searchResults
getRecords
buildQuery
GetDistinctValues
enabled_staff_search_views
new_record_from_zebra
z3950_search_args
getIndexes
);
}
=head1 NAME
C4::Search - Functions for searching the Koha catalog.
=head1 SYNOPSIS
See opac/opac-search.pl or catalogue/search.pl for example of usage
=head1 DESCRIPTION
This module provides searching functions for Koha's bibliographic databases
=head1 FUNCTIONS
=cut
# make all your functions, whether exported or not;
=head2 FindDuplicate
($biblionumber,$biblionumber,$title) = FindDuplicate($record);
This function attempts to find duplicate records using a hard-coded, fairly simplistic algorithm
=cut
sub FindDuplicate {
my ($record) = @_;
my $dbh = C4::Context->dbh;
my $result = TransformMarcToKoha({ record => $record });
my $sth;
my $query;
# search duplicate on ISBN, easy and fast..
# ... normalize first
if ( $result->{isbn} ) {
$result->{isbn} =~ s/\(.*$//;
$result->{isbn} =~ s/\s+$//;
$result->{isbn} =~ s/\|/OR/;
$query = "isbn:$result->{isbn}";
}
else {
my $titleindex = 'ti,ext';
my $authorindex = 'au,ext';
my $op = 'AND';
$result->{title} =~ s /\\//g;
$result->{title} =~ s /\"//g;
$result->{title} =~ s /\(//g;
$result->{title} =~ s /\)//g;
$query = "$titleindex:\"$result->{title}\"";
if ( $result->{author} ) {
$result->{author} =~ s /\\//g;
$result->{author} =~ s /\"//g;
$result->{author} =~ s /\(//g;
$result->{author} =~ s /\)//g;
$query .= " $op $authorindex:\"$result->{author}\"";
}
}
my $searcher = Koha::SearchEngine::Search->new({index => $Koha::SearchEngine::BIBLIOS_INDEX});
my ( $error, $searchresults, undef ) = $searcher->simple_search_compat($query,0,50);
my @results;
if (!defined $error) {
foreach my $possible_duplicate_record (@{$searchresults}) {
my $marcrecord = new_record_from_zebra(
'biblioserver',
$possible_duplicate_record
);
my $result = TransformMarcToKoha({ record => $marcrecord });
# FIXME :: why 2 $biblionumber ?
if ($result) {
push @results, $result->{'biblionumber'};
push @results, $result->{'title'};
}
}
}
return @results;
}
=head2 SimpleSearch
( $error, $results, $total_hits ) = SimpleSearch( $query, $offset, $max_results, [@servers], [%options] );
This function provides a simple search API on the bibliographic catalog
=over 2
=item C<input arg:>
* $query can be a simple keyword or a complete CCL query
* @servers is optional. Defaults to biblioserver as found in koha-conf.xml
* $offset - If present, represents the number of records at the beginning to omit. Defaults to 0
* $max_results - if present, determines the maximum number of records to fetch. undef is All. defaults to undef.
* %options is optional. (e.g. "skip_normalize" allows you to skip changing : to = )
=item C<Return:>
Returns an array consisting of three elements
* $error is undefined unless an error is detected
* $results is a reference to an array of records.
* $total_hits is the number of hits that would have been returned with no limit
If an error is returned the two other return elements are undefined. If error itself is undefined
the other two elements are always defined
=item C<usage in the script:>
=back
my ( $error, $marcresults, $total_hits ) = SimpleSearch($query);
if (defined $error) {
$template->param(query_error => $error);
warn "error: ".$error;
output_html_with_http_headers $input, $cookie, $template->output;
exit;
}
my $hits = @{$marcresults};
my @results;
for my $r ( @{$marcresults} ) {
my $marcrecord = MARC::File::USMARC::decode($r);
my $biblio = TransformMarcToKoha({ record => $marcrecord });
#build the iarray of hashs for the template.
push @results, {
title => $biblio->{'title'},
subtitle => $biblio->{'subtitle'},
biblionumber => $biblio->{'biblionumber'},
author => $biblio->{'author'},
publishercode => $biblio->{'publishercode'},
publicationyear => $biblio->{'publicationyear'},
};
}
$template->param(result=>\@results);
=cut
sub SimpleSearch {
my ( $query, $offset, $max_results, $servers, %options ) = @_;
return ( 'No query entered', undef, undef ) unless $query;
# FIXME hardcoded value. See catalog/search.pl & opac-search.pl too.
my @servers = defined ( $servers ) ? @$servers : ( 'biblioserver' );
my @zoom_queries;
my @tmpresults;
my @zconns;
my $results = [];
my $total_hits = 0;
# Initialize & Search Zebra
for ( my $i = 0 ; $i < @servers ; $i++ ) {
eval {
$zconns[$i] = C4::Context->Zconn( $servers[$i], 1 );
$query =~ s/:/=/g unless $options{skip_normalize};
$zoom_queries[$i] = ZOOM::Query::CCL2RPN->new( $query, $zconns[$i]);
$tmpresults[$i] = $zconns[$i]->search( $zoom_queries[$i] );
# error handling
my $error =
$zconns[$i]->errmsg() . " ("
. $zconns[$i]->errcode() . ") "
. $zconns[$i]->addinfo() . " "
. $zconns[$i]->diagset();
return ( $error, undef, undef ) if $zconns[$i]->errcode();
};
if ($@) {
# caught a ZOOM::Exception
my $error =
$@->message() . " ("
. $@->code() . ") "
. $@->addinfo() . " "
. $@->diagset();
warn $error." for query: $query";
return ( $error, undef, undef );
}
}
_ZOOM_event_loop(
\@zconns,
\@tmpresults,
sub {
my ($i, $size) = @_;
my $first_record = defined($offset) ? $offset + 1 : 1;
my $hits = $tmpresults[ $i - 1 ]->size();
$total_hits += $hits;
my $last_record = $hits;
if ( defined $max_results && $offset + $max_results < $hits ) {
$last_record = $offset + $max_results;
}
for my $j ( $first_record .. $last_record ) {
my $record = eval {
$tmpresults[ $i - 1 ]->record( $j - 1 )->raw()
; # 0 indexed
};
push @{$results}, $record if defined $record;
}
}
);
foreach my $zoom_query (@zoom_queries) {
$zoom_query->destroy();
}
return ( undef, $results, $total_hits );
}
=head2 getRecords
( undef, $results_hashref, \@facets_loop ) = getRecords (
$koha_query, $simple_query, $sort_by_ref, $servers_ref,
$results_per_page, $offset, $branches, $itemtypes,
$query_type, $scan, $opac
);
The all singing, all dancing, multi-server, asynchronous, scanning,
searching, record nabbing, facet-building
See verbose embedded documentation.
=cut
sub getRecords {
my (
$koha_query, $simple_query, $sort_by_ref, $servers_ref,
$results_per_page, $offset, $branches, $itemtypes,
$query_type, $scan, $opac
) = @_;
my @servers = @$servers_ref;
my @sort_by = @$sort_by_ref;
$offset = 0 if $offset < 0;
# Initialize variables for the ZOOM connection and results object
my @zconns;
my @results;
my $results_hashref = ();
# TODO simplify this structure ( { branchcode => $branchname } is enought) and remove this parameter
$branches ||= { map { $_->branchcode => { branchname => $_->branchname } } Koha::Libraries->search->as_list };
# Initialize variables for the faceted results objects
my $facets_counter = {};
my $facets_info = {};
my $facets = getFacets();
my @facets_loop; # stores the ref to array of hashes for template facets loop
### LOOP THROUGH THE SERVERS
for ( my $i = 0 ; $i < @servers ; $i++ ) {
$zconns[$i] = C4::Context->Zconn( $servers[$i], 1 );
# perform the search, create the results objects
# if this is a local search, use the $koha-query, if it's a federated one, use the federated-query
my $query_to_use = ($servers[$i] =~ /biblioserver/) ? $koha_query : $simple_query;
Koha::Logger->get->debug($simple_query) if $scan;
# Check if we've got a query_type defined, if so, use it
eval {
if ($query_type) {
if ($query_type =~ /^ccl/) {
$query_to_use =~ s/\:/\=/g; # change : to = last minute (FIXME)
$results[$i] = $zconns[$i]->search(ZOOM::Query::CCL2RPN->new($query_to_use, $zconns[$i]));
} elsif ($query_type =~ /^cql/) {
$results[$i] = $zconns[$i]->search(ZOOM::Query::CQL->new($query_to_use, $zconns[$i]));
} elsif ($query_type =~ /^pqf/) {
$results[$i] = $zconns[$i]->search(ZOOM::Query::PQF->new($query_to_use, $zconns[$i]));
} else {
warn "Unknown query_type '$query_type'. Results undetermined.";
}
} elsif ($scan) {
$results[$i] = $zconns[$i]->scan( ZOOM::Query::CCL2RPN->new($query_to_use, $zconns[$i]));
} else {
$results[$i] = $zconns[$i]->search(ZOOM::Query::CCL2RPN->new($query_to_use, $zconns[$i]));
}
};
if ($@) {
warn "WARNING: query problem with $query_to_use " . $@;
}
# Concatenate the sort_by limits and pass them to the results object
# Note: sort will override rank
my $sort_by;
foreach my $sort (@sort_by) {
if ( $sort eq "author_az" || $sort eq "author_asc" ) {
$sort_by .= "1=1003 <i ";
}
elsif ( $sort eq "author_za" || $sort eq "author_dsc" ) {
$sort_by .= "1=1003 >i ";
}
elsif ( $sort eq "popularity_asc" ) {
$sort_by .= "1=9003,4=109 <i ";
}
elsif ( $sort eq "popularity_dsc" ) {
$sort_by .= "1=9003,4=109 >i ";
}
elsif ( $sort eq "call_number_asc" ) {
$sort_by .= "1=8007 <i ";
}
elsif ( $sort eq "call_number_dsc" ) {
$sort_by .= "1=8007 >i ";
}
elsif ( $sort eq "pubdate_asc" ) {
$sort_by .= "1=31 <i ";
}
elsif ( $sort eq "pubdate_dsc" ) {
$sort_by .= "1=31 >i ";
}
elsif ( $sort eq "acqdate_asc" ) {
$sort_by .= "1=32 <i ";
}
elsif ( $sort eq "acqdate_dsc" ) {
$sort_by .= "1=32 >i ";
}
elsif ( $sort eq "title_az" || $sort eq "title_asc" ) {
$sort_by .= "1=4 <i ";
}
elsif ( $sort eq "title_za" || $sort eq "title_dsc" ) {
$sort_by .= "1=4 >i ";
}
elsif ( $sort eq "biblionumber_az" || $sort eq "biblionumber_asc" ) {
$sort_by .= "1=12 <i ";
}
elsif ( $sort eq "biblionumber_za" || $sort eq "biblionumber_dsc" ) {
$sort_by .= "1=12 >i ";
}
else {
warn "Ignoring unrecognized sort '$sort' requested" if $sort_by;
}
}
if ( $sort_by && !$scan && $results[$i] ) {
if ( $results[$i]->sort( "yaz", $sort_by ) < 0 ) {
warn "WARNING sort $sort_by failed";
}
}
} # finished looping through servers
# The big moment: asynchronously retrieve results from all servers
_ZOOM_event_loop(
\@zconns,
\@results,
sub {
my ( $i, $size ) = @_;
my $results_hash;
# loop through the results
$results_hash->{'hits'} = $size;
my $times;
if ( $offset + $results_per_page <= $size ) {
$times = $offset + $results_per_page;
}
else {
$times = $size;
}
for ( my $j = $offset ; $j < $times ; $j++ ) {
my $record;
## Check if it's an index scan
if ($scan) {
my ( $term, $occ ) = $results[ $i - 1 ]->display_term($j);
# here we create a minimal MARC record and hand it off to the
# template just like a normal result ... perhaps not ideal, but
# it works for now
my $tmprecord = MARC::Record->new();
$tmprecord->encoding('UTF-8');
my $tmptitle;
my $tmpauthor;
# the minimal record in author/title (depending on MARC flavour)
if ( C4::Context->preference("marcflavour") eq
"UNIMARC" )
{
$tmptitle = MARC::Field->new(
'200', ' ', ' ',
a => $term,
f => $occ
);
$tmprecord->append_fields($tmptitle);
}
else {
$tmptitle =
MARC::Field->new( '245', ' ', ' ', a => $term, );
$tmpauthor =
MARC::Field->new( '100', ' ', ' ', a => $occ, );
$tmprecord->append_fields($tmptitle);
$tmprecord->append_fields($tmpauthor);
}
$results_hash->{'RECORDS'}[$j] =
$tmprecord->as_usmarc();
}
# not an index scan
else {
$record = $results[ $i - 1 ]->record($j)->raw();
# warn "RECORD $j:".$record;
$results_hash->{'RECORDS'}[$j] = $record;
}
}
$results_hashref->{ $servers[ $i - 1 ] } = $results_hash;
# Fill the facets while we're looping, but only for the
# biblioserver and not for a scan
if ( !$scan && $servers[ $i - 1 ] =~ /biblioserver/ ) {
$facets_counter = GetFacets( $results[ $i - 1 ] );
$facets_info = _get_facets_info( $facets );
}
# BUILD FACETS
if ( $servers[ $i - 1 ] =~ /biblioserver/ ) {
for my $link_value (
sort { $a cmp $b } keys %$facets_counter
)
{
my @this_facets_array;
for my $one_facet (
sort {
$facets_counter->{$link_value}
->{$b} <=> $facets_counter->{$link_value}
->{$a}
} keys %{ $facets_counter->{$link_value} }
)
{
# Sanitize the link value : parenthesis, question and exclamation mark will cause errors with CCL
my $facet_link_value = $one_facet;
$facet_link_value =~ s/[()!?¡¿؟]/ /g;
# fix the length that will display in the label,
my $facet_label_value = $one_facet;
my $facet_max_length = C4::Context->preference(
'FacetLabelTruncationLength')
|| 20;
$facet_label_value =
substr( $one_facet, 0, $facet_max_length )
. "..."
if length($facet_label_value) >
$facet_max_length;
# if it's a branch, label by the name, not the code,
if ( $link_value =~ /branch/ ) {
if ( defined $branches
&& ref($branches) eq "HASH"
&& defined $branches->{$one_facet}
&& ref( $branches->{$one_facet} ) eq
"HASH" )
{
$facet_label_value =
$branches->{$one_facet}
->{'branchname'};
}
else {
$facet_label_value = "*";
}
}
# if it's a itemtype, label by the name, not the code,
if ( $link_value =~ /itype/ ) {
if ( defined $itemtypes
&& ref($itemtypes) eq "HASH"
&& defined $itemtypes->{$one_facet}
&& ref( $itemtypes->{$one_facet} ) eq
"HASH" )
{
$facet_label_value =
$itemtypes->{$one_facet}
->{translated_description};
}
}
# also, if it's a location code, use the name instead of the code
if ( $link_value =~ /location/ ) {
# TODO Retrieve all authorised values at once, instead of 1 query per entry
my $av = Koha::AuthorisedValues->search({ category => 'LOC', authorised_value => $one_facet });
$facet_label_value = $av->count ? $av->next->opac_description : '';
}
# also, if it's a collection code, use the name instead of the code
if ( $link_value =~ /ccode/ ) {
# TODO Retrieve all authorised values at once, instead of 1 query per entry
my $av = Koha::AuthorisedValues->search({ category => 'CCODE', authorised_value => $one_facet });
$facet_label_value = $av->count ? $av->next->opac_description : '';
}
# but we're down with the whole label being in the link's title.
push @this_facets_array,
{
facet_count =>
$facets_counter->{$link_value}
->{$one_facet},
facet_label_value => $facet_label_value,
facet_title_value => $one_facet,
facet_link_value => $facet_link_value,
type_link_value => $link_value,
}
if ($facet_label_value);
}
push @facets_loop,
{
type_link_value => $link_value,
type_id => $link_value . "_id",
"type_label_"
. $facets_info->{$link_value}->{'label_value'} =>
1,
label => $facets_info->{$link_value}->{'label_value'},
facets => \@this_facets_array,
}
unless (
(
$facets_info->{$link_value}->{'label_value'} =~
/Libraries/
)
and ( Koha::Libraries->search->count == 1 )
);
}
}
}
);
# This sorts the facets into alphabetical order
if (@facets_loop) {
foreach my $f (@facets_loop) {
if( C4::Context->preference('FacetOrder') eq 'Alphabetical' ){
$f->{facets} =
[ sort { uc($a->{facet_label_value}) cmp uc($b->{facet_label_value}) } @{ $f->{facets} } ];
}
}
}
return ( undef, $results_hashref, \@facets_loop );
}
sub GetFacets {
my $rs = shift;
my $facets;
my $use_zebra_facets = C4::Context->config('use_zebra_facets') // 0;
if ( $use_zebra_facets ) {
$facets = _get_facets_from_zebra( $rs );
} else {
$facets = _get_facets_from_records( $rs );
}
return $facets;
}
sub _get_facets_from_records {
my $rs = shift;
my $facets_maxrecs = C4::Context->preference('maxRecordsForFacets') // 20;
my $facets_config = getFacets();
my $facets = {};
my $size = $rs->size();
my $jmax = $size > $facets_maxrecs
? $facets_maxrecs
: $size;
for ( my $j = 0 ; $j < $jmax ; $j++ ) {
my $marc_record = new_record_from_zebra (
'biblioserver',
$rs->record( $j )->raw()
);
if ( ! defined $marc_record ) {
warn "ERROR DECODING RECORD - $@: " .
$rs->record( $j )->raw();
next;
}
_get_facets_data_from_record( $marc_record, $facets_config, $facets );
}
return $facets;
}
=head2 _get_facets_data_from_record
C4::Search::_get_facets_data_from_record( $marc_record, $facets, $facets_counter );
Internal function that extracts facets information from a MARC::Record object
and populates $facets_counter for using in getRecords.
$facets is expected to be filled with C4::Koha::getFacets output (i.e. the configured
facets for Zebra).
=cut
sub _get_facets_data_from_record {
my ( $marc_record, $facets, $facets_counter ) = @_;
for my $facet (@$facets) {
my @used_datas = ();
foreach my $tag ( @{ $facet->{ tags } } ) {
# tag number is the first three digits
my $tag_num = substr( $tag, 0, 3 );
# subfields are the remainder
my $subfield_letters = substr( $tag, 3 );
my @fields = $marc_record->field( $tag_num );
foreach my $field (@fields) {
# If $field->indicator(1) eq 'z', it means it is a 'see from'
# field introduced because of IncludeSeeFromInSearches, so skip it
next if $field->indicator(1) eq 'z';
my $data = $field->as_string( $subfield_letters, $facet->{ sep } );
$data =~ s/\s*(?<!\p{Uppercase})[.\-,;]*\s*$//;
unless ( grep { $_ eq $data } @used_datas ) {
push @used_datas, $data;
$facets_counter->{ $facet->{ idx } }->{ $data }++;
}
}
}
}
}
=head2 _get_facets_from_zebra
my $facets = _get_facets_from_zebra( $result_set )
Retrieves facets for a specified result set. It loops through the facets defined
in C4::Koha::getFacets and returns a hash with the following structure:
{ facet_idx => {
facet_value => count
},
...
}
=cut
sub _get_facets_from_zebra {
my $rs = shift;
# save current elementSetName
my $elementSetName = $rs->option( 'elementSetName' );
my $facets_loop = getFacets();
my $facets_data = {};
# loop through defined facets and fill the facets hashref
foreach my $facet ( @$facets_loop ) {
my $idx = $facet->{ idx };
my $sep = $facet->{ sep };
my $facet_values = _get_facet_from_result_set( $idx, $rs, $sep );
if ( $facet_values ) {
# we've actually got a result
$facets_data->{ $idx } = $facet_values;
}
}
# set elementSetName to its previous value to avoid side effects
$rs->option( elementSetName => $elementSetName );
return $facets_data;
}
=head2 _get_facet_from_result_set
my $facet_values =
C4::Search::_get_facet_from_result_set( $facet_idx, $result_set, $sep )
Internal function that extracts facet information for a specific index ($facet_idx) and
returns a hash containing facet values and count:
{
$facet_value => $count ,
...
}
Warning: this function has the side effect of changing the elementSetName for the result
set. It is a helper function for the main loop, which takes care of backing it up for
restoring.
=cut
sub _get_facet_from_result_set {
my $facet_idx = shift;
my $rs = shift;
my $sep = shift;
my $internal_sep = '<*>';
my $facetMaxCount = C4::Context->preference('FacetMaxCount') // 20;
return if ( ! defined $facet_idx || ! defined $rs );
# zebra's facet element, untokenized index
my $facet_element = 'zebra::facet::' . $facet_idx . ':0:' . $facetMaxCount;
# configure zebra results for retrieving the desired facet
$rs->option( elementSetName => $facet_element );
# get the facet record from result set
my $facet = $rs->record( 0 )->raw;
# if the facet has no restuls...
return if !defined $facet;
# TODO: benchmark DOM vs. SAX performance
my $facet_dom = XML::LibXML->load_xml(
string => ($facet)
);
my @terms = $facet_dom->getElementsByTagName('term');
return if ! @terms;
my $facets = {};
foreach my $term ( @terms ) {
my $facet_value = $term->textContent;
$facet_value =~ s/\s*(?<!\p{Uppercase})[.\-,;]*\s*$//;
$facet_value =~ s/\Q$internal_sep\E/$sep/ if defined $sep;
$facets->{ $facet_value } += $term->getAttribute( 'occur' );
}
return $facets;
}
=head2 _get_facets_info
my $facets_info = C4::Search::_get_facets_info( $facets )
Internal function that extracts facets information and properly builds
the data structure needed to render facet labels.
=cut
sub _get_facets_info {
my $facets = shift;
my $facets_info = {};
for my $facet ( @$facets ) {
$facets_info->{ $facet->{ idx } }->{ label_value } = $facet->{ label };
}
return $facets_info;
}
# TRUNCATION
sub _detect_truncation {
my ( $operand, $index ) = @_;
my ( @nontruncated, @righttruncated, @lefttruncated, @rightlefttruncated,
@regexpr );
$operand =~ s/^ //g;
my @wordlist = split( /\s/, $operand );
foreach my $word (@wordlist) {
if ( $word =~ s/^\*([^\*]+)\*$/$1/ ) {
push @rightlefttruncated, $word;
}
elsif ( $word =~ s/^\*([^\*]+)$/$1/ ) {
push @lefttruncated, $word;
}
elsif ( $word =~ s/^([^\*]+)\*$/$1/ ) {
push @righttruncated, $word;
}
elsif ( index( $word, "*" ) < 0 ) {
push @nontruncated, $word;
}
else {
push @regexpr, $word;
}
}
return (
\@nontruncated, \@righttruncated, \@lefttruncated,
\@rightlefttruncated, \@regexpr
);
}
# STEMMING
sub _build_stemmed_operand {
my ($operand,$lang) = @_;
require Lingua::Stem::Snowball ;
my $stemmed_operand=q{};
# Stemmer needs language
return $operand unless $lang;
# If operand contains a digit, it is almost certainly an identifier, and should
# not be stemmed. This is particularly relevant for ISBNs and ISSNs, which
# can contain the letter "X" - for example, _build_stemmend_operand would reduce
# "014100018X" to "x ", which for a MARC21 database would bring up irrelevant
# results (e.g., "23 x 29 cm." from the 300$c). Bug 2098.
return $operand if $operand =~ /\d/;
# FIXME: the locale should be set based on the user's language and/or search choice
#warn "$lang";
# Make sure we only use the first two letters from the language code
$lang = lc(substr($lang, 0, 2));
# The language codes for the two variants of Norwegian will now be "nb" and "nn",
# none of which Lingua::Stem::Snowball can use, so we need to "translate" them
if ($lang eq 'nb' || $lang eq 'nn') {
$lang = 'no';
}
my $stemmer = Lingua::Stem::Snowball->new( lang => $lang,
encoding => "UTF-8" );
my @words = split( / /, $operand );
my @stems = $stemmer->stem(\@words);
for my $stem (@stems) {
$stemmed_operand .= "$stem";
$stemmed_operand .= "?"
unless ( $stem =~ /(and$|or$|not$)/ ) || ( length($stem) < 3 );
$stemmed_operand .= " ";
}
Koha::Logger->get->debug("STEMMED OPERAND: $stemmed_operand");
return $stemmed_operand;
}
# FIELD WEIGHTING
sub _build_weighted_query {
# FIELD WEIGHTING - This is largely experimental stuff. What I'm committing works
# pretty well but could work much better if we had a smarter query parser
my ( $operand, $stemmed_operand, $index ) = @_;
my $stemming = C4::Context->preference("QueryStemming") || 0;
my $weight_fields = C4::Context->preference("QueryWeightFields") || 0;
my $fuzzy_enabled = C4::Context->preference("QueryFuzzy") || 0;
$operand =~ s/"/ /g; # Bug 7518: searches with quotation marks don't work
my $weighted_query = "(rk=("; # Specifies that we're applying rank
# Keyword, or, no index specified
if ( ( $index eq 'kw' ) || ( !$index ) ) {
$weighted_query .=
"Title-cover,ext,r1=\"$operand\""; # exact title-cover
$weighted_query .= " or ti,ext,r2=\"$operand\""; # exact title
$weighted_query .= " or Title-cover,phr,r3=\"$operand\""; # phrase title
$weighted_query .= " or ti,wrdl,r4=\"$operand\""; # words in title
#$weighted_query .= " or any,ext,r4=$operand"; # exact any
#$weighted_query .=" or kw,wrdl,r5=\"$operand\""; # word list any
$weighted_query .= " or wrdl,fuzzy,r8=\"$operand\""
if $fuzzy_enabled; # add fuzzy, word list
$weighted_query .= " or wrdl,right-Truncation,r9=\"$stemmed_operand\""
if ( $stemming and $stemmed_operand )
; # add stemming, right truncation
$weighted_query .= " or wrdl,r9=\"$operand\"";
# embedded sorting: 0 a-z; 1 z-a
# $weighted_query .= ") or (sort1,aut=1";
}
# Barcode searches should skip this process
elsif ( $index eq 'bc' ) {
$weighted_query .= "bc=\"$operand\"";
}
# Authority-number searches should skip this process
elsif ( $index eq 'an' ) {
$weighted_query .= "an=\"$operand\"";
}
# If the index is numeric, don't autoquote it.
elsif ( $index =~ /,st-numeric$/ ) {
$weighted_query .= " $index=$operand";
}
# If the index already has more than one qualifier, wrap the operand
# in quotes and pass it back (assumption is that the user knows what they
# are doing and won't appreciate us mucking up their query
elsif ( $index =~ ',' ) {
$weighted_query .= " $index=\"$operand\"";
}
#TODO: build better cases based on specific search indexes
else {
$weighted_query .= " $index,ext,r1=\"$operand\""; # exact index
#$weighted_query .= " or (title-sort-az=0 or $index,startswithnt,st-word,r3=$operand #)";
$weighted_query .= " or $index,phr,r3=\"$operand\""; # phrase index
$weighted_query .= " or $index,wrdl,r6=\"$operand\""; # word list index
$weighted_query .= " or $index,wrdl,fuzzy,r8=\"$operand\""
if $fuzzy_enabled; # add fuzzy, word list
$weighted_query .= " or $index,wrdl,rt,r9=\"$stemmed_operand\""
if ( $stemming and $stemmed_operand ); # add stemming, right truncation
}
$weighted_query .= "))"; # close rank specification
return $weighted_query;
}
=head2 getIndexes
Return an array with available indexes.
=cut
sub getIndexes{
my @indexes = (
# biblio indexes
'ab',
'Abstract',
'acqdate',
'allrecords',
'an',
'Any',
'at',
'arl',
'arp',
'au',
'aub',
'aud',
'audience',
'auo',
'aut',
'Author',
'Author-in-order ',
'Author-personal-bibliography',
'Authority-Number',
'authtype',
'bc',
'Bib-level',
'biblionumber',
'bio',
'biography',
'callnum',
'cfn',
'Chronological-subdivision',
'cn-bib-source',
'cn-bib-sort',