-
Notifications
You must be signed in to change notification settings - Fork 38
/
bibtex.pm
1857 lines (1600 loc) · 70.2 KB
/
bibtex.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 Biber::Input::file::bibtex;
use v5.24;
use strict;
use warnings;
use sigtrap qw(handler TBSIG SEGV);
use Carp;
use Text::BibTeX qw(:nameparts :joinmethods :metatypes);
use Text::BibTeX::Name;
use Text::BibTeX::NameFormat;
use Biber::Annotation;
use Biber::Constants;
use Biber::DataModel;
use Biber::Entries;
use Biber::Entry;
use Biber::Entry::Names;
use Biber::Entry::Name;
use Biber::Sections;
use Biber::Section;
use Biber::Utils;
use Biber::Config;
use Encode;
use File::Spec;
use File::Slurper;
use File::Temp;
use Log::Log4perl qw(:no_extra_logdie_message);
use List::AllUtils qw( :all );
use Scalar::Util qw(looks_like_number);
use URI;
use Unicode::Normalize;
use Unicode::GCString;
use XML::LibXML::Simple;
my $logger = Log::Log4perl::get_logger('main');
state $cache; # state variable so it's persistent across calls to extract_entries()
use vars qw($cache);
=head2 init_cache
Invalidate the T::B object cache. Used only in tests when e.g. we change the encoding
settings and therefore must force a re-read of the data
=cut
sub init_cache {
$cache = {};
}
# Determine handlers from data model
my $dm = Biber::Config->get_dm;
my $handlers = {
'custom' => {'annotation' => \&_annotation},
'field' => {
'default' => {
'code' => \&_literal,
'date' => \&_datetime,
'datepart' => \&_literal,
'entrykey' => \&_literal,
'integer' => \&_literal,
'key' => \&_literal,
'literal' => \&_literal,
'range' => \&_range,
'verbatim' => \&_verbatim,
'uri' => \&_uri
},
'xsv' => {
'entrykey' => \&_xsv,
'keyword' => \&_xsv,
'option' => \&_xsv,
}
},
'list' => {
'default' => {
'key' => \&_list,
'literal' => \&_list,
'name' => \&_name,
'verbatim' => \&_list,
'uri' => \&_urilist
}
}
};
=head2 TBSIG
Signal handler to catch fatal Text::BibTex SEGFAULTS. It has bugs
and we want to say at least something if it coredumps
=cut
sub TBSIG {
my $sig = shift;
$logger->logdie("Caught signal: $sig\nLikely your .bib has a very bad entry which causes libbtparse to crash: $!");
}
=head2 extract_entries
Main data extraction routine.
Accepts a data source identifier, preprocesses the file and then
looks for the passed keys, creating entries when it finds them and
passes out an array of keys it didn't find.
=cut
sub extract_entries {
my ($source, $encoding, $keys) = @_;
my $secnum = $Biber::MASTER->get_current_section;
my $section = $Biber::MASTER->sections->get_section($secnum);
my $filename;
my @rkeys = $keys->@*;
my $tf; # Up here so that the temp file has enough scope to survive until we've used it
if ($logger->is_trace()) {# performance tune
$logger->trace("Entering extract_entries() in driver 'bibtex'");
}
# Get a reference to the correct sourcemap sections, if they exist
my $smaps = [];
# Maps are applied in order USER->STYLE->DRIVER
if (defined(Biber::Config->getoption('sourcemap'))) {
# User maps, allow multiple \DeclareSourcemap
if (my @m = grep {$_->{datatype} eq 'bibtex' and $_->{level} eq 'user' } Biber::Config->getoption('sourcemap')->@* ) {
push $smaps->@*, @m;
}
# Style maps
# Allow multiple style maps from multiple \DeclareStyleSourcemap
if (my @m = grep {$_->{datatype} eq 'bibtex' and $_->{level} eq 'style' } Biber::Config->getoption('sourcemap')->@* ) {
push $smaps->@*, @m;
}
# Driver default maps
if (my $m = first {$_->{datatype} eq 'bibtex' and $_->{level} eq 'driver'} Biber::Config->getoption('sourcemap')->@* ) {
push $smaps->@*, $m;
}
}
# If it's a remote data file, fetch it first
if ($source =~ m/\A(?:http|ftp)(s?):\/\//xms) {
$logger->info("Data source '$source' is a remote BibTeX data source - fetching ...");
if (my $cf = $REMOTE_MAP{$source}) {
$logger->info("Found '$source' in remote source cache");
$filename = $cf;
}
else {
if ($1) { # HTTPS/FTPS
# use IO::Socket::SSL qw(debug99); # useful for debugging SSL issues
# We have to explicitly set the cert path because otherwise the https module
# can't find the .pem when PAR::Packer'ed
# Have to explicitly try to require Mozilla::CA here to get it into %INC below
# It may, however, have been removed by some biber unpacked dists
if (not exists($ENV{PERL_LWP_SSL_CA_FILE}) and
not exists($ENV{PERL_LWP_SSL_CA_PATH}) and
not defined(Biber::Config->getoption('ssl-nointernalca')) and
eval {require Mozilla::CA}) {
# we assume that the default CA file is in .../Mozilla/CA/cacert.pem
(my $vol, my $dir, undef) = File::Spec->splitpath( $INC{"Mozilla/CA.pm"} );
$dir =~ s/\/$//; # splitpath sometimes leaves a trailing '/'
$ENV{PERL_LWP_SSL_CA_FILE} = File::Spec->catpath($vol, "$dir/CA", 'cacert.pem');
}
# fallbacks for, e.g., linux
unless (exists($ENV{PERL_LWP_SSL_CA_FILE})) {
foreach my $ca_bundle (qw{
/etc/ssl/certs/ca-certificates.crt
/etc/pki/tls/certs/ca-bundle.crt
/etc/ssl/ca-bundle.pem
}) {
next if ! -e $ca_bundle;
$ENV{PERL_LWP_SSL_CA_FILE} = $ca_bundle;
last;
}
foreach my $ca_path (qw{
/etc/ssl/certs/
/etc/pki/tls/
}) {
next if ! -d $ca_path;
$ENV{PERL_LWP_SSL_CA_PATH} = $ca_path;
last;
}
}
if (defined(Biber::Config->getoption('ssl-noverify-host'))) {
$ENV{PERL_LWP_SSL_VERIFY_HOSTNAME} = 0;
}
require LWP::Protocol::https;
}
require LWP::Simple;
$tf = File::Temp->new(TEMPLATE => 'biber_remote_data_source_XXXXX',
DIR => $Biber::MASTER->biber_tempdir,
SUFFIX => '.bib');
# Pretend to be a browser otherwise some sites refuse the default LWP UA string
$LWP::Simple::ua->agent('Mozilla/5.0');
my $retcode = LWP::Simple::getstore($source, $tf->filename);
unless (LWP::Simple::is_success($retcode)) {
biber_error("Could not fetch '$source' (HTTP code: $retcode)");
}
$filename = $tf->filename;
# cache any remote so it persists and so we don't fetch it again
$REMOTE_MAP{$source} = $filename;
}
}
else {
# Need to get the filename even if using cache so we increment
# the filename count for preambles at the bottom of this sub
unless ($filename = locate_biber_file($source)) {
biber_error("Cannot find '$source'!")
}
}
# Text::BibTeX can't be controlled by Log4perl so we have to do something clumsy
# We can't redirect STDERR to a variable as libbtparse doesnt' use PerlIO, just stdio
# so it doesn't understand this. It does understand normal file redirection though as
# that's standard stdio.
# The Log4Perl setup outputs only to STDOUT so redirecting all STDERR like this is
# ok since only libbtparse will be writing there
# Don't do this if we are debugging or tracing because some errors in libbtparse cause
# sudden death and can't be output as the read/output of the saved STDERR is never reached.
# so, if debugging/tracing, output STDERR errors immediately.
my $tberr;
my $tberr_name;
unless ($logger->is_debug() or $logger->is_trace()) {
$tberr = File::Temp->new(TEMPLATE => 'biber_Text_BibTeX_STDERR_XXXXX',
DIR => $Biber::MASTER->biber_tempdir);
$tberr_name = $tberr->filename;
open OLDERR, '>&', \*STDERR;
open STDERR, '>', $tberr_name;
}
# Increment the number of times each datafile has been referenced
# For example, a datafile might be referenced in more than one section.
# Some things find this information useful, for example, setting preambles is global
# and so we need to know if we've already saved the preamble for a datafile.
$cache->{counts}{$filename}++;
# Don't read the file again if it's already cached
unless ($cache->{data}{$filename}) {
if ($logger->is_debug()) {# performance tune
$logger->debug("Caching data for BibTeX format file '$filename' for section $secnum");
}
cache_data($filename, $encoding);
}
else {
if ($logger->is_debug()) {# performance tune
$logger->debug("Using cached data for BibTeX format file '$filename' for section $secnum");
}
}
if ($section->is_allkeys) {
if ($logger->is_debug()) {# performance tune
$logger->debug("All citekeys will be used for section '$secnum'");
}
# Loop over all entries, creating objects
while (my ($key, $entry) = each $cache->{data}{$filename}->%*) {
# Record a key->datasource name mapping for error reporting
$section->set_keytods($key, $filename);
unless (create_entry($key, $entry, $source, $smaps, \@rkeys)) {
# if create entry returns false, remove the key from the cache
$cache->{orig_key_order}{$filename}->@* = grep {$key ne $_} $cache->{orig_key_order}{$filename}->@*;
}
}
# Loop over all aliases, creating data in section object
# Since this is allkeys, we are guaranteed that the real entry for the alias
# will be available
while (my ($alias, $key) = each $cache->{data}{citekey_aliases}->%*) {
$section->set_citekey_alias($alias, $key);
}
# If allkeys, push all bibdata keys into citekeys (if they are not already there).
# We are using the special "orig_key_order" array which is used to deal with the
# situation when sorting=none and allkeys is set. We need an array rather than the
# keys from the bibentries hash because we need to preserve the original order of
# the .bib as in this case the sorting sub "citeorder" means "bib order" as there are
# no explicitly cited keys
$section->add_citekeys($cache->{orig_key_order}{$filename}->@*);
if ($logger->is_debug()) {# performance tune
$logger->debug("Added all citekeys to section '$secnum': " . join(', ', $section->get_citekeys));
}
# Special case when allkeys but also some dynamic set entries. These keys must also be
# in the section or they will be missed on output.
if ($section->has_dynamic_sets) {
$section->add_citekeys($section->dynamic_set_keys->@*);
if ($logger->is_debug()) {# performance tune
$logger->debug("Added dynamic sets to section '$secnum': " . join(', ', $section->dynamic_set_keys->@*));
}
}
}
else {
# loop over all keys we're looking for and create objects
if ($logger->is_debug()) {# performance tune
$logger->debug('Text::BibTeX cache keys: ' . join(', ', keys $cache->{data}{$filename}->%*));
$logger->debug('Wanted keys: ' . join(', ', $keys->@*));
}
foreach my $wanted_key ($keys->@*) {
if ($logger->is_debug()) {# performance tune
$logger->debug("Looking for key '$wanted_key' in Text::BibTeX cache");
}
# Record a key->datasource name mapping for error reporting
$section->set_keytods($wanted_key, $filename);
if (my $entry = $cache->{data}{$filename}{$wanted_key}) {
if ($logger->is_debug()) {# performance tune
$logger->debug("Found key '$wanted_key' in Text::BibTeX cache");
}
# Skip creation if it's already been done, for example, via a citekey alias
unless ($section->bibentries->entry_exists($wanted_key)) {
create_entry($wanted_key, $entry, $source, $smaps, \@rkeys);
}
# found a key, remove it from the list of keys we want
@rkeys = grep {$wanted_key ne $_} @rkeys;
}
elsif (my $rk = $cache->{data}{citekey_aliases}{$wanted_key}) {
$section->set_citekey_alias($wanted_key, $rk);
# Make sure there is a real, cited entry for the citekey alias
# just in case only the alias is cited. However, make sure that the real entry
# is actually cited before adding to the section citekeys list in case this real
# entry is only needed as an aliased Xref and shouldn't necessarily be in
# the bibliography (minXrefs will take care of adding it there if necessary).
unless ($section->bibentries->entry_exists($rk)) {
if (my $entry = $cache->{data}{GLOBALDS}{$rk}) {# Look in cache of all datasource keys
create_entry($rk, $entry, $source, $smaps, \@rkeys);
if ($section->has_cited_citekey($wanted_key)) {
$section->add_citekeys($rk);
}
}
}
# found an alias key, remove it from the list of keys we want
@rkeys = grep {$wanted_key ne $_} @rkeys;
}
elsif (my $okey = $section->has_badcasekey($wanted_key)) {
biber_warn("Possible typo (case mismatch) between citation and datasource keys: '$wanted_key' and '$okey' in file '$filename'");
}
if ($logger->is_debug()) {# performance tune
$logger->debug('Wanted keys now: ' . join(', ', @rkeys));
}
}
}
unless ($logger->is_debug() or $logger->is_trace()) {
open STDERR, '>&', \*OLDERR;
close OLDERR;
# Put any Text::BibTeX errors into the biber warnings/errors collections
# We are parsing the libbtparse library error/warning strings a little here
# This is not so bad as they have a clean structure (see error.c in libbtparse)
open my $tbe, '<', $tberr_name;
while (<$tbe>) {
next if /overriding\sexisting\sdefinition\sof\smacro/; # ignore macro redefs
if (/error:/) {
chomp;
biber_error("BibTeX subsystem: $_");
}
elsif (/warning:/) {
chomp;
biber_warn("BibTeX subsystem: $_");
}
}
close($tbe);
}
# Only push the preambles from the file if we haven't seen this data file before
# and there are some preambles to push
if ($cache->{counts}{$filename} < 2 and $cache->{preamble}{$filename}->@*) {
push $Biber::MASTER->{preamble}->@*, $cache->{preamble}{$filename}->@*;
}
# Save comments if in tool mode
if (Biber::Config->getoption('tool')) {
if ($cache->{comments}{$filename}) {
$Biber::MASTER->{comments} = $cache->{comments}{$filename};
}
}
return @rkeys;
}
=head2 create_entry
Create a Biber::Entry object from a Text::BibTeX object
Be careful in here, all T::B set methods are UTF-8/NFC boundaries
so be careful to encode(NFC()) on calls. Windows won't handle UTF-8
in T::B btparse gracefully and will die.
=cut
sub create_entry {
# We have to pass in $rkeys so that the new/clone operations can remove the new/clone
# key from the list of wanted keys because new/cloned entries will never appear to the normal
# key search loop
my ($key, $entry, $datasource, $smaps, $rkeys) = @_;
my $secnum = $Biber::MASTER->get_current_section;
my $section = $Biber::MASTER->sections->get_section($secnum);
if ( $entry->metatype == BTE_REGULAR ) {
my %newentries; # In case we create a new entry in a map
# Save entry and work on a clone so that modifications do not propagate to
# other refsections
my $saved_entry = $entry;
$entry = $entry->clone;
# Datasource mapping applied in $smap order (USER->STYLE->DRIVER)
foreach my $smap ($smaps->@*) {
$smap->{map_overwrite} = $smap->{map_overwrite} // 0; # default
my $level = $smap->{level};
MAP: foreach my $map ($smap->{map}->@*) {
# Skip if this map element specifies a particular refsection and it is not this one
if (exists($map->{refsection})) {
next unless $secnum == $map->{refsection};
}
# Check pertype restrictions
# Logic is "-(-P v Q)" which is equivalent to "P & -Q" but -Q is an array check so
# messier to write than Q
unless (not exists($map->{per_type}) or
first {lc($_->{content}) eq $entry->type} $map->{per_type}->@*) {
next;
}
# Check negated pertype restrictions
if (exists($map->{per_nottype}) and
first {lc($_->{content}) eq $entry->type} $map->{per_nottype}->@*) {
next;
}
# Check per_datasource restrictions
# Don't compare case insensitively - this might not be correct
# Logic is "-(-P v Q)" which is equivalent to "P & -Q" but -Q is an array check so
# messier to write than Q
unless (not exists($map->{per_datasource}) or
first {$_->{content} eq $datasource} $map->{per_datasource}->@*) {
next;
}
my $last_type = $entry->type; # defaults to the entrytype unless changed below
my $last_field = undef;
my $last_fieldval = undef;
my @imatches; # For persisting parenthetical matches over several steps
# Set up any mapping foreach loop
my @maploop = ('');
if (my $foreach = $map->{map_foreach}) {
if (my $dslist = $DATAFIELD_SETS{lc($foreach)}) { # datafield set list
@maploop = $dslist->@*;
}
elsif (my $felist = $entry->get(lc($foreach))) { # datafield
@maploop = split(/\s*,\s*/, $felist);
}
else { # explicit CSV
@maploop = split(/\s*,\s*/, $foreach);
}
}
foreach my $maploop (@maploop) {
my $MAPUNIQVAL;
# loop over mapping steps
foreach my $step ($map->{map_step}->@*) {
# entry deletion. Really only useful with allkeys or tool mode
if ($step->{map_entry_null}) {
if ($logger->is_debug()) { # performance tune
$logger->debug("Source mapping (type=$level, key=$key): Ignoring entry completely");
}
return 0; # don't create an entry at all
}
# new entry
if (my $newkey = maploopreplace($step->{map_entry_new}, $maploop)) {
# Now re-instate any unescaped $1 .. $9 to get round these being
# dynamically scoped and being null when we get here from any
# previous map_match
$newkey =~ s/(?<!\\)\$(\d)/$imatches[$1-1]/ge;
my $newentrytype;
unless ($newentrytype = maploopreplace($step->{map_entry_newtype}, $maploop)) {
biber_warn("Source mapping (type=$level, key=$key): Missing type for new entry '$newkey', skipping step ...");
next;
}
if ($logger->is_debug()) { # performance tune
$logger->debug("Source mapping (type=$level, key=$key): Creating new entry with key '$newkey'");
}
my $newentry = Text::BibTeX::Entry->new();
$newentry->set_metatype(BTE_REGULAR);
$newentry->set_key(encode('UTF-8', NFC($newkey)));
$newentry->set_type(encode('UTF-8', NFC($newentrytype)));
# found a new entry key, remove it from the list of keys we want since we
# have "found" it by creating it
if ($logger->is_debug()) { # performance tune
$logger->debug("Source mapping (type=$level, key=$key): created '$newkey', removing from dependent list");
}
$rkeys->@* = grep {$newkey ne $_} $rkeys->@*;
# Add to the section if explicitly nocited in the map
if ($step->{map_entry_nocite}) {
$section->add_citekeys($newkey);
}
# Need to add the new key to the section if allkeys is set since all keys
# are cleared for allkeys sections initially
if ($section->is_allkeys) {
$section->add_citekeys($newkey);
}
$newentries{$newkey} = $newentry;
}
# entry clone
if (my $clonekey = maploopreplace($step->{map_entry_clone}, $maploop)) {
# Now re-instate any unescaped $1 .. $9 to get round these being
# dynamically scoped and being null when we get here from any
# previous map_match
$clonekey =~ s/(?<!\\)\$(\d)/$imatches[$1-1]/ge;
if ($logger->is_debug()) { # performance tune
$logger->debug("Source mapping (type=$level, key=$key): cloning entry with new key '$clonekey'");
}
# found a clone key, remove it from the list of keys we want since we
# have "found" it by creating it along with its clone parent
if ($logger->is_debug()) { # performance tune
$logger->debug("Source mapping (type=$level, key=$key): created '$clonekey', removing from dependent list");
}
$rkeys->@* = grep {$clonekey ne $_} $rkeys->@*;
# Add to the section if explicitly nocited in the map
if ($step->{map_entry_nocite}) {
$section->add_citekeys($clonekey);
}
# Need to add the clone key to the section if allkeys is set since all keys
# are cleared for allkeys sections initially
if ($section->is_allkeys) {
$section->add_citekeys($clonekey);
}
$newentries{$clonekey} = $entry->clone;
}
# An entry created by map_entry_new or map_entry_clone previously can be
# the target for field setting options
# A newly created entry as target of operations doesn't make sense in all situations
# so it's limited to being the target for field sets
my $etarget;
my $etargetkey;
if ($etargetkey = maploopreplace($step->{map_entrytarget}, $maploop)) {
# Now re-instate any unescaped $1 .. $9 to get round these being
# dynamically scoped and being null when we get here from any
# previous map_match
$etargetkey =~ s/(?<!\\)\$(\d)/$imatches[$1-1]/ge;
unless ($etarget = $newentries{$etargetkey}) {
biber_warn("Source mapping (type=$level, key=$key): Dynamically created entry target '$etargetkey' does not exist skipping step ...");
next;
}
}
else { # default is that we operate on the same entry
$etarget = $entry;
$etargetkey = $key;
}
# Entrytype map
if (my $typesource = maploopreplace($step->{map_type_source}, $maploop)) {
$typesource = lc($typesource);
unless ($etarget->type eq $typesource) {
# Skip the rest of the map if this step doesn't match and match is final
if ($step->{map_final}) {
if ($logger->is_debug()) { # performance tune
$logger->debug("Source mapping (type=$level, key=$etargetkey): Entry type is '" . $etarget->type . "' but map wants '$typesource' and step has 'final' set, skipping rest of map ...");
}
next MAP;
}
else {
# just ignore this step
if ($logger->is_debug()) { # performance tune
$logger->debug("Source mapping (type=$level, key=$etargetkey): Entry type is '" . $etarget->type . "' but map wants '$typesource', skipping step ...");
}
next;
}
}
# Change entrytype if requested
$last_type = $etarget->type;
my $t = lc(maploopreplace($step->{map_type_target}, $maploop));
if ($logger->is_debug()) { # performance tune
$logger->debug("Source mapping (type=$level, key=$etargetkey): Changing entry type from '$last_type' to $t");
}
$etarget->set_type(encode('UTF-8', NFC($t)));
}
my $fieldcontinue = 0;
my $fieldsource;
my $nfieldsource;
# Negated source field map
if ($nfieldsource = maploopreplace($step->{map_notfield}, $maploop)) {
$nfieldsource = lc($nfieldsource);
if ($etarget->exists($nfieldsource)) {
if ($step->{map_final}) {
if ($logger->is_debug()) { # performance tune
$logger->debug("Source mapping (type=$level, key=$etargetkey): Field '$nfieldsource' exists and step has 'final' set, skipping rest of map ...");
}
next MAP;
}
else {
# just ignore this step
if ($logger->is_debug()) { # performance tune
$logger->debug("Source mapping (type=$level, key=$etargetkey): Field '$nfieldsource' exists, skipping step ...");
}
next;
}
}
$fieldcontinue = 1;
}
# Field map
if ($fieldsource = maploopreplace($step->{map_field_source}, $maploop)) {
$fieldsource = lc($fieldsource);
# key is a pseudo-field. It's guaranteed to exist so
# just check if that's what's being asked for
unless ($fieldsource eq 'entrykey' or
$etarget->exists($fieldsource)) {
# Skip the rest of the map if this step doesn't match and match is final
if ($step->{map_final}) {
if ($logger->is_debug()) { # performance tune
$logger->debug("Source mapping (type=$level, key=$etargetkey): No field '$fieldsource' and step has 'final' set, skipping rest of map ...");
}
next MAP;
}
else {
# just ignore this step
if ($logger->is_debug()) { # performance tune
$logger->debug("Source mapping (type=$level, key=$etargetkey): No field '$fieldsource', skipping step ...");
}
next;
}
}
$fieldcontinue = 1;
}
if ($fieldcontinue) {
$last_field = $fieldsource;
$last_fieldval = $fieldsource eq 'entrykey' ? $etarget->key : $etarget->get($fieldsource);
my $negmatch = 0;
# Negated matches are a normal match with a special flag
if (my $nm = $step->{map_notmatch}) {
$step->{map_match} = $nm;
$negmatch = 1;
}
# map fields to targets
if (my $m = maploopreplace($step->{map_match}, $maploop)) {
if (defined($step->{map_replace})) { # replace can be null
# Can't modify entrykey
if ($fieldsource eq 'entrykey') {
if ($logger->is_debug()) { # performance tune
$logger->debug("Source mapping (type=$level, key=$etargetkey): Field '$fieldsource' is 'entrykey'- cannot remap the value of this field, skipping ...");
}
next;
}
my $r = maploopreplace($step->{map_replace}, $maploop);
if ($logger->is_debug()) { # performance tune
$logger->debug("Source mapping (type=$level, key=$etargetkey): Doing match/replace '$m' -> '$r' on field '$fieldsource'");
}
$etarget->set($fieldsource,
encode('UTF-8', NFC(ireplace($last_fieldval, $m, $r))));
}
else {
# Now re-instate any unescaped $1 .. $9 to get round these being
# dynamically scoped and being null when we get here from any
# previous map_match
# Be aware that imatch() uses m//g so @imatches can have multiple paren group
# captures which might be useful
$m =~ s/(?<!\\)\$(\d)/$imatches[$1-1]/ge;
unless (@imatches = imatch($last_fieldval, $m, $negmatch)) {
# Skip the rest of the map if this step doesn't match and match is final
if ($step->{map_final}) {
if ($logger->is_debug()) { # performance tune
$logger->debug("Source mapping (type=$level, key=$etargetkey): Field '$fieldsource' does not match '$m' and step has 'final' set, skipping rest of map ...");
}
next MAP;
}
else {
# just ignore this step
if ($logger->is_debug()) { # performance tune
$logger->debug("Source mapping (type=$level, key=$etargetkey): Field '$fieldsource' does not match '$m', skipping step ...");
}
next;
}
}
}
}
# Set to a different target if there is one
if (my $target = maploopreplace($step->{map_field_target}, $maploop)) {
$target = lc($target);
# Can't remap entry key pseudo-field
if ($fieldsource eq 'entrykey') {
if ($logger->is_debug()) { # performance tune
$logger->debug("Source mapping (type=$level, key=$etargetkey): Field '$fieldsource' is 'entrykey'- cannot map this to a new field as you must have an entrykey, skipping ...");
}
next;
}
if ($etarget->exists($target)) {
if ($map->{map_overwrite} // $smap->{map_overwrite}) {
if ($logger->is_debug()) { # performance tune
$logger->debug("Source mapping (type=$level, key=$etargetkey): Overwriting existing field '$target'");
}
}
else {
if ($logger->is_debug()) { # performance tune
$logger->debug("Source mapping (type=$level, key=$etargetkey): Field '$fieldsource' is mapped to field '$target' but both are defined, skipping ...");
}
next;
}
}
$etarget->set($target, encode('UTF-8', NFC($entry->get($fieldsource))));
$etarget->delete($fieldsource);
}
}
# field changes
if (my $field = maploopreplace($step->{map_field_set}, $maploop)) {
$field = lc($field);
# Deal with special tokens
if ($step->{map_null}) {
if ($logger->is_debug()) { # performance tune
$logger->debug("Source mapping (type=$level, key=$etargetkey): Deleting field '$field'");
}
$etarget->delete($field);
}
else {
if ($etarget->exists($field)) {
unless ($map->{map_overwrite} // $smap->{map_overwrite}) {
if ($step->{map_final}) {
# map_final is set, ignore and skip rest of step
if ($logger->is_debug()) { # performance tune
$logger->debug("Source mapping (type=$level, key=$etargetkey): Field '$field' exists, overwrite is not set and step has 'final' set, skipping rest of map ...");
}
next MAP;
}
else {
# just ignore this step
if ($logger->is_debug()) { # performance tune
$logger->debug("Source mapping (type=$level, key=$etargetkey): Field '$field' exists and overwrite is not set, skipping step ...");
}
next;
}
}
}
# If append is set, keep the original value and append the new
my $orig = $step->{map_append} ? $etarget->get($field) : '';
if ($step->{map_origentrytype}) {
next unless $last_type;
if ($logger->is_debug()) { # performance tune
$logger->debug("Source mapping (type=$level, key=$etargetkey): Setting field '$field' to '${orig}${last_type}'");
}
$etarget->set($field, encode('UTF-8', NFC($orig . $last_type)));
}
elsif ($step->{map_origfieldval}) {
next unless $last_fieldval;
if ($logger->is_debug()) { # performance tune
$logger->debug("Source mapping (type=$level, key=$etargetkey): Setting field '$field' to '${orig}${last_fieldval}'");
}
$etarget->set($field, encode('UTF-8', NFC($orig . $last_fieldval)));
}
elsif ($step->{map_origfield}) {
next unless $last_field;
if ($logger->is_debug()) { # performance tune
$logger->debug("Source mapping (type=$level, key=$etargetkey): Setting field '$field' to '${orig}${last_field}'");
}
$etarget->set($field, encode('UTF-8', NFC($orig . $last_field)));
}
else {
my $fv = maploopreplace($step->{map_field_value}, $maploop);
# Now re-instate any unescaped $1 .. $9 to get round these being
# dynamically scoped and being null when we get here from any
# previous map_match
$fv =~ s/(?<!\\)\$(\d)/$imatches[$1-1]/ge;
if ($logger->is_debug()) { # performance tune
$logger->debug("Source mapping (type=$level, key=$etargetkey): Setting field '$field' to '${orig}${fv}'");
}
$etarget->set($field, encode('UTF-8', NFC($orig . $fv)));
}
}
}
}
}
}
}
_create_entry($key, $entry);
# reinstate original entry before modifications so that further refsections
# have a clean slate
$entry = $saved_entry;
# Need to also instantiate fields in any new entries created by map
while (my ($k, $e) = each %newentries) {
_create_entry($k, $e);
}
}
return 1;
}
sub _create_entry {
my ($k, $e) = @_;
return unless $e; # newentry might be undef
my $secnum = $Biber::MASTER->get_current_section;
my $section = $Biber::MASTER->sections->get_section($secnum);
my $ds = $section->get_keytods($k);
my $bibentry = Biber::Entry->new();
$bibentry->set_field('citekey', $k);
if ($logger->is_debug()) {# performance tune
$logger->debug("Creating biber Entry object with key '$k'");
}
# Save pre-mapping data. Might be useful somewhere
$bibentry->set_field('rawdata', $e->print_s);
my $entrytype = $e->type;
# We put all the fields we find modulo field aliases into the object
# validation happens later and is not datasource dependent
foreach my $f ($e->fieldlist) {
# We have to process local options as early as possible in order
# to make them available for things that need them like parsename()
if ($f eq 'options') {
my $value = $e->get($f);
my $Srx = Biber::Config->getoption('xsvsep');
my $S = qr/$Srx/;
process_entry_options($k, [ split(/$S/, $value) ]);
}
# Now run any defined handler
if ($dm->is_field($f)) {
my $handler = _get_handler($f);
my $v = $handler->($bibentry, $e, $f, $k);
# Don't set datafields with empty contents like 'language = {}'
if (defined($v) and $e->get($f) ne '') {
$bibentry->set_datafield($f, $v);
}
}
elsif (Biber::Config->getoption('validate_datamodel')) {
biber_warn("Datamodel: Entry '$k' ($ds): Field '$f' invalid in data model - ignoring", $bibentry);
}
}
$bibentry->set_field('entrytype', $entrytype);
$bibentry->set_field('datatype', 'bibtex');
if ($logger->is_debug()) {# performance tune
$logger->debug("Adding entry with key '$k' to entry list");
}
$section->bibentries->add_entry($k, $bibentry);
return;
}
# HANDLERS
# ========
# Data annotation fields
sub _annotation {
my ($bibentry, $entry, $field, $key) = @_;
my $value = $entry->get($field);
my $ann = quotemeta(Biber::Config->getoption('annotation_marker'));
$field =~ s/$ann$//;
foreach my $a (split(/\s*;\s*/, $value)) {
my ($count, $part, $annotations) = $a =~ /^\s*(\d+)?:?([^=]+)?=(.+)/;
if ($part) {
Biber::Annotation->set_annotation('part', $key, $field, $annotations, $count, $part);
}
elsif ($count) {
Biber::Annotation->set_annotation('item', $key, $field, $annotations, $count);
}
else {
Biber::Annotation->set_annotation('field', $key, $field, $annotations);
}
}
return;
}
# Literal fields
sub _literal {
my ($bibentry, $entry, $field, $key) = @_;
my $value = $entry->get($field);
# If we have already split some date fields into literal fields
# like date -> year/month/day, don't overwrite them with explicit
# year/month
if ($field eq 'year') {
return if $bibentry->get_datafield('year');
if ($value and not looks_like_number($value)and not $entry->get('sortyear')) {
biber_warn("year field '$value' in entry '$key' is not an integer - this will probably not sort properly.");
}
}
if ($field eq 'month') {
return if $bibentry->get_datafield('month');
if ($value and not looks_like_number($value)) {
biber_warn("month field '$value' in entry '$key' is not an integer - this will probably not sort properly.");
}
}
# Deal with ISBN options
if ($field eq 'isbn') {
require Business::ISBN;
my ($vol, $dir, undef) = File::Spec->splitpath( $INC{"Business/ISBN.pm"} );
$dir =~ s/\/$//; # splitpath sometimes leaves a trailing '/'
# Just in case it is already set. We also need to fake this in tests or it will
# look for it in the blib dir
unless (exists($ENV{ISBN_RANGE_MESSAGE})) {
$ENV{ISBN_RANGE_MESSAGE} = File::Spec->catpath($vol, "$dir/ISBN/", 'RangeMessage.xml');
}
my $isbn = Business::ISBN->new($value);
# Ignore invalid ISBNs
if (not $isbn or not $isbn->is_valid) {
biber_warn("ISBN '$value' in entry '$key' is invalid - run biber with '--validate_datamodel' for details.");
return $value;
}
# Force to a specified format
if (Biber::Config->getoption('isbn13')) {
$isbn = $isbn->as_isbn13;
$value = $isbn->isbn;
}
elsif (Biber::Config->getoption('isbn10')) {
$isbn = $isbn->as_isbn10;
$value = $isbn->isbn;
}
# Normalise if requested
if (Biber::Config->getoption('isbn_normalise')) {
$value = $isbn->as_string;
}
}
# Try to sanitise months to biblatex requirements
if ($field eq 'month') {
return _hack_month($value);
}
# Rationalise any bcp47 style langids into babel/polyglossia names
# biblatex will convert these back again when loading .lbx files
# We need this until babel/polyglossia support proper bcp47 language/locales
elsif ($field eq 'langid' and my $map = $LOCALE_MAP_R{$value}) {
return $map;
}
else {
return $value;
}
}
# URI fields
sub _uri {
my ($bibentry, $entry, $field) = @_;
my $value = $entry->get($field);
return $value;
}
# xSV field form
sub _xsv {
my $Srx = Biber::Config->getoption('xsvsep');
my $S = qr/$Srx/;
my ($bibentry, $entry, $field) = @_;
return [ split(/$S/, $entry->get($field)) ];
}
# Verbatim fields
sub _verbatim {
my ($bibentry, $entry, $field) = @_;
my $value = $entry->get($field);
return $value;
}
# Range fields
# m-n -> [m, n]
# m -> [m, undef]
# m- -> [m, '']
# -n -> ['', n]
# - -> ['', undef]
sub _range {