Bug 29781: Enable capture groups in batch item modification

This patch adds support for regular expression capture groups in
MarcModificationTemplates.

We escape double quotes in the replacement string, then quote the whole
string before applying the `ee` modifier to the final regex
application.

See https://blog.james.rcpt.to/2010/10/25/perl-search-and-replace-using-variables/
for further details.

Test plan
1) Attempt to use capture groups in your regular expression based
   batch item modification and note it does not work.
2) Apply the patch and try again, this time the capture group
   should yield the expected results.
3) Run t/SimpleMARC.t and confirm the tests still pass.

Signed-off-by: Andrew Fuerste-Henry <andrew@bywatersolutions.com>

Signed-off-by: Jo Hunter <jhunter@clicweb.org>

Signed-off-by: Nick Clemens <nick@bywatersolutions.com>
Signed-off-by: Fridolin Somers <fridolin.somers@biblibre.com>
This commit is contained in:
Martin Renvoize 2022-01-17 13:38:28 +00:00 committed by Fridolin Somers
parent 1516514f1a
commit bafd7cff70

View file

@ -363,13 +363,17 @@ sub batch_update {
return ( { modified_itemnumbers => \@modified_itemnumbers, modified_fields => $modified_fields }, $self );
}
sub apply_regex { # FIXME Should be moved outside of Koha::Items
sub apply_regex {
# FIXME Should be moved outside of Koha::Items
# FIXME This is nearly identical to Koha::SimpleMARC::_modify_values
my ($params) = @_;
my $search = $params->{search};
my $replace = $params->{replace};
my $modifiers = $params->{modifiers} || q{};
my $value = $params->{value};
$replace =~ s/"/\\"/g; # Protection from embedded code
$replace = '"' . $replace . '"'; # Put in a string for /ee
my @available_modifiers = qw( i g );
my $retained_modifiers = q||;
for my $modifier ( split //, $modifiers ) {
@ -377,16 +381,16 @@ sub apply_regex { # FIXME Should be moved outside of Koha::Items
if grep { /$modifier/ } @available_modifiers;
}
if ( $retained_modifiers =~ m/^(ig|gi)$/ ) {
$value =~ s/$search/$replace/ig;
$value =~ s/$search/$replace/igee;
}
elsif ( $retained_modifiers eq 'i' ) {
$value =~ s/$search/$replace/i;
$value =~ s/$search/$replace/iee;
}
elsif ( $retained_modifiers eq 'g' ) {
$value =~ s/$search/$replace/g;
$value =~ s/$search/$replace/gee;
}
else {
$value =~ s/$search/$replace/;
$value =~ s/$search/$replace/ee;
}
return $value;