Bug 28445: Adjust code to handle regexs
[koha.git] / tools / batchMod.pl
1 #!/usr/bin/perl
2
3
4 # Copyright 2000-2002 Katipo Communications
5 #
6 # This file is part of Koha.
7 #
8 # Koha is free software; you can redistribute it and/or modify it
9 # under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # Koha is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with Koha; if not, see <http://www.gnu.org/licenses>.
20
21 use CGI qw ( -utf8 );
22 use Modern::Perl;
23 use Try::Tiny qw( catch try );
24
25 use C4::Auth qw( get_template_and_user haspermission );
26 use C4::Output qw( output_html_with_http_headers );
27 use C4::Biblio qw(
28     DelBiblio
29     GetAuthorisedValueDesc
30     GetMarcFromKohaField
31     GetMarcStructure
32     IsMarcStructureInternal
33     TransformHtmlToXml
34 );
35 use C4::Items qw( GetItemsInfo Item2Marc ModItemFromMarc );
36 use C4::Circulation qw( barcodedecode LostItem IsItemIssued );
37 use C4::Context;
38 use C4::Koha;
39 use C4::BackgroundJob;
40 use C4::ClassSource qw( GetClassSources GetClassSource );
41 use MARC::File::XML;
42 use List::MoreUtils qw( uniq );
43
44 use Koha::Database;
45 use Koha::Exceptions::Exception;
46 use Koha::AuthorisedValues;
47 use Koha::Biblios;
48 use Koha::DateUtils qw( dt_from_string );
49 use Koha::Items;
50 use Koha::ItemTypes;
51 use Koha::Patrons;
52 use Koha::SearchEngine::Indexer;
53 use Koha::UI::Form::Builder::Item;
54
55 my $input = CGI->new;
56 my $dbh = C4::Context->dbh;
57 my $error        = $input->param('error');
58 my @itemnumbers  = $input->multi_param('itemnumber');
59 my $biblionumber = $input->param('biblionumber');
60 my $op           = $input->param('op');
61 my $del          = $input->param('del');
62 my $del_records  = $input->param('del_records');
63 my $src          = $input->param('src');
64 my $use_default_values = $input->param('use_default_values');
65 my $exclude_from_local_holds_priority = $input->param('exclude_from_local_holds_priority');
66
67 my $template_name;
68 my $template_flag;
69 if (!defined $op) {
70     $template_name = "tools/batchMod.tt";
71     $template_flag = { tools => '*' };
72     $op = q{};
73 } else {
74     $template_name = ($del) ? "tools/batchMod-del.tt" : "tools/batchMod-edit.tt";
75     $template_flag = ($del) ? { tools => 'items_batchdel' }   : { tools => 'items_batchmod' };
76 }
77
78 my ($template, $loggedinuser, $cookie)
79     = get_template_and_user({template_name => $template_name,
80                  query => $input,
81                  type => "intranet",
82                  flagsrequired => $template_flag,
83                  });
84
85 $template->param( searchid => scalar $input->param('searchid'), );
86
87 # Does the user have a restricted item edition permission?
88 my $uid = $loggedinuser ? Koha::Patrons->find( $loggedinuser )->userid : undef;
89 my $restrictededition = $uid ? haspermission($uid,  {'tools' => 'items_batchmod_restricted'}) : undef;
90 # In case user is a superlibrarian, edition is not restricted
91 $restrictededition = 0 if ($restrictededition != 0 && C4::Context->IsSuperLibrarian());
92
93 $template->param(del       => $del);
94
95 my $nextop="";
96 my @errors; # store errors found while checking data BEFORE saving item.
97 my $items_display_hashref;
98 our $tagslib = &GetMarcStructure(1);
99
100 my $deleted_items = 0;     # Number of deleted items
101 my $deleted_records = 0;   # Number of deleted records ( with no items attached )
102 my $not_deleted_items = 0; # Number of items that could not be deleted
103 my @not_deleted;           # List of the itemnumbers that could not be deleted
104 my $modified_items = 0;    # Numbers of modified items
105 my $modified_fields = 0;   # Numbers of modified fields
106
107 my %cookies = parse CGI::Cookie($cookie);
108 my $sessionID = $cookies{'CGISESSID'}->value;
109
110
111 #--- ----------------------------------------------------------------------------
112 if ($op eq "action") {
113 #-------------------------------------------------------------------------------
114     my @tags      = $input->multi_param('tag');
115     my @subfields = $input->multi_param('subfield');
116     my @values    = $input->multi_param('field_value');
117     my @searches  = $input->multi_param('regex_search');
118     my @replaces  = $input->multi_param('regex_replace');
119     my @modifiers = $input->multi_param('regex_modifiers');
120
121     my $upd_biblionumbers;
122     my $del_biblionumbers;
123     if ( $del ) {
124         try {
125             my $schema = Koha::Database->new->schema;
126             $schema->txn_do(
127                 sub {
128                     foreach my $itemnumber (@itemnumbers) {
129                         my $item = Koha::Items->find($itemnumber);
130                         next
131                           unless $item
132                           ; # Should have been tested earlier, but just in case...
133                         my $itemdata = $item->unblessed;
134                         my $return = $item->safe_delete;
135                         if ( ref( $return ) ) {
136                             $deleted_items++;
137                             push @$upd_biblionumbers, $itemdata->{'biblionumber'};
138                         }
139                         else {
140                             $not_deleted_items++;
141                             push @not_deleted,
142                               {
143                                 biblionumber => $itemdata->{'biblionumber'},
144                                 itemnumber   => $itemdata->{'itemnumber'},
145                                 barcode      => $itemdata->{'barcode'},
146                                 title        => $itemdata->{'title'},
147                                 reason       => $return,
148                               };
149                         }
150
151                         # If there are no items left, delete the biblio
152                         if ($del_records) {
153                             my $itemscount = Koha::Biblios->find( $itemdata->{'biblionumber'} )->items->count;
154                             if ( $itemscount == 0 ) {
155                                 my $error = DelBiblio( $itemdata->{'biblionumber'}, { skip_record_index => 1 } );
156                                 unless ($error) {
157                                     $deleted_records++;
158                                     push @$del_biblionumbers, $itemdata->{'biblionumber'};
159                                     if ( $src eq 'CATALOGUING' ) {
160                                         # We are coming catalogue/detail.pl, there were items from a single bib record
161                                         $template->param( biblio_deleted => 1 );
162                                     }
163                                 }
164                             }
165                         }
166                     }
167                     if (@not_deleted) {
168                         Koha::Exceptions::Exception->throw(
169                             'Some items have not been deleted, rolling back');
170                     }
171                 }
172             );
173         }
174         catch {
175             warn $_;
176             if ( $_->isa('Koha::Exceptions::Exception') ) {
177                 $template->param( deletion_failed => 1 );
178             }
179             die "Something terrible has happened!"
180                 if ($_ =~ /Rollback failed/); # Rollback failed
181         };
182     }
183
184     else { # modification
185
186         my @columns = Koha::Items->columns;
187
188         my $new_item_data;
189         my @columns_with_regex;
190         for my $c ( @columns ) {
191             if ( $c eq 'more_subfields_xml' ) {
192                 my @more_subfields_xml = $input->multi_param("items.more_subfields_xml");
193                 my @unlinked_item_subfields;
194                 for my $subfield ( @more_subfields_xml ) {
195                     my $v = $input->param('items.more_subfields_xml_' . $subfield);
196                     push @unlinked_item_subfields, $subfield, $v;
197                 }
198                 if ( @unlinked_item_subfields ) {
199                     my $marc = MARC::Record->new();
200                     # use of tag 999 is arbitrary, and doesn't need to match the item tag
201                     # used in the framework
202                     $marc->append_fields(MARC::Field->new('999', ' ', ' ', @unlinked_item_subfields));
203                     $marc->encoding("UTF-8");
204                     # FIXME This is WRONG! We need to use the values that haven't been modified by the batch tool!
205                     $new_item_data->{more_subfields_xml} = $marc->as_xml("USMARC");
206                     next;
207                 }
208                 $new_item_data->{more_subfields_xml} = undef;
209                 # FIXME deal with more_subfields_xml and @subfields_to_blank
210             } elsif ( grep { $c eq $_ } @subfields_to_blank ) {
211                 # Empty this column
212                 $new_item_data->{$c} = undef
213             } else {
214
215                 my @v = grep { $_ ne "" }
216                     uniq $input->multi_param( "items." . $c );
217
218                 next unless @v;
219
220                 $new_item_data->{$c} = join ' | ', @v;
221             }
222
223             if ( my $regex_search = $input->param('items.'.$c.'_regex_search') ) {
224                 push @columns_with_regex, $c;
225             }
226         }
227
228         try {
229             my $schema = Koha::Database->new->schema;
230             $schema->txn_do(
231                 sub {
232
233                     foreach my $itemnumber (@itemnumbers) {
234                         my $item = Koha::Items->find($itemnumber);
235                         next
236                           unless $item
237                           ; # Should have been tested earlier, but just in case...
238                         my $itemdata = $item->unblessed;
239
240                         my $modified_holds_priority = 0;
241                         if ( defined $exclude_from_local_holds_priority && $exclude_from_local_holds_priority ne "" ) {
242                             if(!defined $item->exclude_from_local_holds_priority || $item->exclude_from_local_holds_priority != $exclude_from_local_holds_priority) {
243                                 $item->exclude_from_local_holds_priority($exclude_from_local_holds_priority)->store;
244                                 $modified_holds_priority = 1;
245                             }
246                         }
247
248                         my $modified = 0;
249                         for my $c ( @columns_with_regex ) {
250                             my $regex_search = $input->param('items.'.$c.'_regex_search');
251                             my $old_value = $item->$c;
252
253                             my $value = apply_regex(
254                                 {
255                                     search  => $regex_search,
256                                     replace => $input->param(
257                                         'items' . $c . '_regex_replace'
258                                     ),
259                                     modifiers => $input->param(
260                                         'items' . $c . '_regex_modifiers'
261                                     ),
262                                     value => $old_value,
263                                 }
264                             );
265                             unless ( $old_value eq $value ) {
266                                 $modified++;
267                                 $item->$c($value);
268                             }
269                         }
270
271                         $modified += scalar(keys %$new_item_data); # FIXME This is incorrect if old value == new value. Should we loop of the keys and compare the before/after values?
272                         if ( $modified) {
273                             my $itemlost_pre = $item->itemlost;
274                             $item->set($new_item_data)->store({skip_record_index => 1});
275
276                             push @$upd_biblionumbers, $itemdata->{'biblionumber'};
277
278                             LostItem(
279                                 $item->itemnumber, 'batchmod', undef,
280                                 { skip_record_index => 1 }
281                             ) if $item->itemlost
282                                   and not $itemlost_pre;
283                         }
284
285                         $modified_items++ if $modified || $modified_holds_priority;
286                         $modified_fields += $modified + $modified_holds_priority;
287                     }
288                 }
289             );
290         }
291         catch {
292             warn $_;
293             die "Something terrible has happened!"
294                 if ($_ =~ /Rollback failed/); # Rollback failed
295         };
296     }
297
298     $upd_biblionumbers = [ uniq @$upd_biblionumbers ]; # Only update each bib once
299
300     # Don't send specialUpdate for records we are going to delete
301     my %del_bib_hash = map{ $_ => undef } @$del_biblionumbers;
302     @$upd_biblionumbers = grep( ! exists( $del_bib_hash{$_} ), @$upd_biblionumbers );
303
304     my $indexer = Koha::SearchEngine::Indexer->new({ index => $Koha::SearchEngine::BIBLIOS_INDEX });
305     $indexer->index_records( $upd_biblionumbers, 'specialUpdate', "biblioserver", undef ) if @$upd_biblionumbers;
306     $indexer->index_records( $del_biblionumbers, 'recordDelete', "biblioserver", undef ) if @$del_biblionumbers;
307
308     # Once the job is done
309     # If we have a reasonable amount of items, we display them
310     my $max_items = $del ? C4::Context->preference("MaxItemsToDisplayForBatchDel") : C4::Context->preference("MaxItemsToDisplayForBatchMod");
311     if (scalar(@itemnumbers) <= $max_items ){
312         if (scalar(@itemnumbers) <= 1000 ) {
313             $items_display_hashref=BuildItemsData(@itemnumbers);
314         } else {
315             # Else, we only display the barcode
316             my @simple_items_display = map {
317                 my $itemnumber = $_;
318                 my $item = Koha::Items->find($itemnumber);
319                 {
320                     itemnumber   => $itemnumber,
321                     barcode      => $item ? ( $item->barcode // q{} ) : q{},
322                     biblionumber => $item ? $item->biblio->biblionumber : q{},
323                 };
324             } @itemnumbers;
325             $template->param("simple_items_display" => \@simple_items_display);
326         }
327     } else {
328         $template->param( "too_many_items_display" => scalar(@itemnumbers) );
329         $template->param( "job_completed" => 1 );
330     }
331
332
333     # Calling the template
334     $template->param(
335         modified_items => $modified_items,
336         modified_fields => $modified_fields,
337     );
338
339 }
340 #
341 #-------------------------------------------------------------------------------
342 # build screen with existing items. and "new" one
343 #-------------------------------------------------------------------------------
344
345 if ($op eq "show"){
346     my $filefh = $input->upload('uploadfile');
347     my $filecontent = $input->param('filecontent');
348     my ( @notfoundbarcodes, @notfounditemnumbers);
349
350     my $split_chars = C4::Context->preference('BarcodeSeparators');
351     if ($filefh){
352         binmode $filefh, ':encoding(UTF-8)';
353         my @contentlist;
354         while (my $content=<$filefh>){
355             $content =~ s/[\r\n]*$//;
356             push @contentlist, $content if $content;
357         }
358
359         if ($filecontent eq 'barcode_file') {
360             @contentlist = grep /\S/, ( map { split /[$split_chars]/ } @contentlist );
361             @contentlist = uniq @contentlist;
362             # Note: adding lc for case insensitivity
363             my %itemdata = map { lc($_->{barcode}) => $_->{itemnumber} } @{ Koha::Items->search({ barcode => \@contentlist }, { columns => [ 'itemnumber', 'barcode' ] } )->unblessed };
364             @itemnumbers = map { exists $itemdata{lc $_} ? $itemdata{lc $_} : () } @contentlist;
365             @notfoundbarcodes = grep { !exists $itemdata{lc $_} } @contentlist;
366         }
367         elsif ( $filecontent eq 'itemid_file') {
368             @contentlist = uniq @contentlist;
369             my %itemdata = map { $_->{itemnumber} => 1 } @{ Koha::Items->search({ itemnumber => \@contentlist }, { columns => [ 'itemnumber' ] } )->unblessed };
370             @itemnumbers = grep { exists $itemdata{$_} } @contentlist;
371             @notfounditemnumbers = grep { !exists $itemdata{$_} } @contentlist;
372         }
373     } else {
374         if (defined $biblionumber && !@itemnumbers){
375             my @all_items = GetItemsInfo( $biblionumber );
376             foreach my $itm (@all_items) {
377                 push @itemnumbers, $itm->{itemnumber};
378             }
379         }
380         if ( my $list = $input->param('barcodelist') ) {
381             my @barcodelist = grep /\S/, ( split /[$split_chars]/, $list );
382             @barcodelist = uniq @barcodelist;
383
384             @barcodelist = map { barcodedecode( $_ ) } @barcodelist;
385
386             # Note: adding lc for case insensitivity
387             my %itemdata = map { lc($_->{barcode}) => $_->{itemnumber} } @{ Koha::Items->search({ barcode => \@barcodelist }, { columns => [ 'itemnumber', 'barcode' ] } )->unblessed };
388             @itemnumbers = map { exists $itemdata{lc $_} ? $itemdata{lc $_} : () } @barcodelist;
389             @notfoundbarcodes = grep { !exists $itemdata{lc $_} } @barcodelist;
390         }
391     }
392
393     # Flag to tell the template there are valid results, hidden or not
394     if(scalar(@itemnumbers) > 0){ $template->param("itemresults" => 1); }
395     # Only display the items if there are no more than pref MaxItemsToProcessForBatchMod or MaxItemsToDisplayForBatchDel
396     my $max_display_items = $del
397         ? C4::Context->preference("MaxItemsToDisplayForBatchDel")
398         : C4::Context->preference("MaxItemsToDisplayForBatchMod");
399     $template->param("too_many_items_process" => scalar(@itemnumbers)) if !$del && scalar(@itemnumbers) > C4::Context->preference("MaxItemsToProcessForBatchMod");
400     if (scalar(@itemnumbers) <= ( $max_display_items // 1000 ) ) {
401         $items_display_hashref=BuildItemsData(@itemnumbers);
402     } else {
403         $template->param("too_many_items_display" => scalar(@itemnumbers));
404         # Even if we do not display the items, we need the itemnumbers
405         $template->param(itemnumbers_array => \@itemnumbers);
406     }
407     # now, build the item form for entering a new item
408     my @loop_data =();
409     my $branch_limit = C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
410
411     my $libraries = Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed;# build once ahead of time, instead of multiple times later.
412
413     # Adding a default choice, in case the user does not want to modify the branch
414     my $nochange_branch = { branchname => '', value => '', selected => 1 };
415     unshift (@$libraries, $nochange_branch);
416
417     my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
418
419     # Getting list of subfields to keep when restricted batchmod edit is enabled
420     my @subfields_to_allow = $restrictededition ? split ' ', C4::Context->preference('SubfieldsToAllowForRestrictedBatchmod') : ();
421
422     my $subfields = Koha::UI::Form::Builder::Item->new->edit_form(
423         {
424             restricted_editition => $restrictededition,
425             (
426                 @subfields_to_allow
427                 ? ( subfields_to_allow => \@subfields_to_allow )
428                 : ()
429             ),
430             subfields_to_ignore         => ['items.barcode'],
431             prefill_with_default_values => $use_default_values,
432         }
433     );
434
435
436
437     # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
438     $template->param(
439         subfields           => $subfields,
440         notfoundbarcodes    => \@notfoundbarcodes,
441         notfounditemnumbers => \@notfounditemnumbers
442     );
443     $nextop="action"
444 } # -- End action="show"
445
446 $template->param(%$items_display_hashref) if $items_display_hashref;
447 $template->param(
448     op      => $nextop,
449 );
450 $template->param( $op => 1 ) if $op;
451
452 if ($op eq "action") {
453
454     #my @not_deleted_loop = map{{itemnumber=>$_}}@not_deleted;
455
456     $template->param(
457         not_deleted_items => $not_deleted_items,
458         deleted_items => $deleted_items,
459         delete_records => $del_records,
460         deleted_records => $deleted_records,
461         not_deleted_loop => \@not_deleted 
462     );
463 }
464
465 foreach my $error (@errors) {
466     $template->param($error => 1) if $error;
467 }
468 $template->param(src => $src);
469 $template->param(biblionumber => $biblionumber);
470 output_html_with_http_headers $input, $cookie, $template->output;
471 exit;
472
473
474 # ---------------- Functions
475
476 sub BuildItemsData{
477         my @itemnumbers=@_;
478                 # now, build existiing item list
479                 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
480                 my @big_array;
481                 #---- finds where items.itemnumber is stored
482     my (  $itemtagfield,   $itemtagsubfield) = &GetMarcFromKohaField( "items.itemnumber" );
483     my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField( "items.homebranch" );
484                 foreach my $itemnumber (@itemnumbers){
485             my $itemdata = Koha::Items->find($itemnumber);
486             next unless $itemdata; # Should have been tested earlier, but just in case...
487             $itemdata = $itemdata->unblessed;
488                         my $itemmarc=Item2Marc($itemdata);
489                         my %this_row;
490                         foreach my $field (grep {$_->tag() eq $itemtagfield} $itemmarc->fields()) {
491                                 # loop through each subfield
492                                 my $itembranchcode=$field->subfield($branchtagsubfield);
493                 if ($itembranchcode && C4::Context->preference("IndependentBranches")) {
494                                                 #verifying rights
495                                                 my $userenv = C4::Context->userenv();
496                         unless (C4::Context->IsSuperLibrarian() or (($userenv->{'branch'} eq $itembranchcode))){
497                                                                 $this_row{'nomod'}=1;
498                                                 }
499                                 }
500                                 my $tag=$field->tag();
501                                 foreach my $subfield ($field->subfields) {
502                                         my ($subfcode,$subfvalue)=@$subfield;
503                                         next if ($tagslib->{$tag}->{$subfcode}->{tab} ne 10 
504                                                         && $tag        ne $itemtagfield 
505                                                         && $subfcode   ne $itemtagsubfield);
506
507                                         $witness{$subfcode} = $tagslib->{$tag}->{$subfcode}->{lib} if ($tagslib->{$tag}->{$subfcode}->{tab}  eq 10);
508                                         if ($tagslib->{$tag}->{$subfcode}->{tab}  eq 10) {
509                                                 $this_row{$subfcode}=GetAuthorisedValueDesc( $tag,
510                                                                         $subfcode, $subfvalue, '', $tagslib) 
511                                                                         || $subfvalue;
512                                         }
513
514                                         $this_row{itemnumber} = $subfvalue if ($tag eq $itemtagfield && $subfcode eq $itemtagsubfield);
515                                 }
516                         }
517
518             # grab title, author, and ISBN to identify bib that the item
519             # belongs to in the display
520             my $biblio = Koha::Biblios->find( $itemdata->{biblionumber} );
521             $this_row{title}        = $biblio->title;
522             $this_row{author}       = $biblio->author;
523             $this_row{isbn}         = $biblio->biblioitem->isbn;
524             $this_row{biblionumber} = $biblio->biblionumber;
525             $this_row{holds}        = $biblio->holds->count;
526             $this_row{item_holds}   = Koha::Holds->search( { itemnumber => $itemnumber } )->count;
527             $this_row{item}         = Koha::Items->find($itemnumber);
528
529                         if (%this_row) {
530                                 push(@big_array, \%this_row);
531                         }
532                 }
533                 @big_array = sort {$a->{0} cmp $b->{0}} @big_array;
534
535                 # now, construct template !
536                 # First, the existing items for display
537                 my @item_value_loop;
538                 my @witnesscodessorted=sort keys %witness;
539                 for my $row ( @big_array ) {
540                         my %row_data;
541                         my @item_fields = map +{ field => $_ || '' }, @$row{ @witnesscodessorted };
542                         $row_data{item_value} = [ @item_fields ];
543                         $row_data{itemnumber} = $row->{itemnumber};
544                         #reporting this_row values
545                         $row_data{'nomod'} = $row->{'nomod'};
546       $row_data{bibinfo} = $row->{bibinfo};
547       $row_data{author} = $row->{author};
548       $row_data{title} = $row->{title};
549       $row_data{isbn} = $row->{isbn};
550       $row_data{biblionumber} = $row->{biblionumber};
551       $row_data{holds}        = $row->{holds};
552       $row_data{item_holds}   = $row->{item_holds};
553       $row_data{item}         = $row->{item};
554       $row_data{safe_to_delete} = $row->{item}->safe_to_delete;
555       my $is_on_loan = C4::Circulation::IsItemIssued( $row->{itemnumber} );
556       $row_data{onloan} = $is_on_loan ? 1 : 0;
557                         push(@item_value_loop,\%row_data);
558                 }
559                 my @header_loop=map { { header_value=> $witness{$_}} } @witnesscodessorted;
560
561     my @cannot_be_deleted = map {
562         $_->{safe_to_delete} == 1 ? () : $_->{item}->barcode
563     } @item_value_loop;
564     return {
565         item_loop        => \@item_value_loop,
566         cannot_be_deleted => \@cannot_be_deleted,
567         item_header_loop => \@header_loop
568     };
569 }
570
571 #BE WARN : it is not the general case 
572 # This function can be OK in the item marc record special case
573 # Where subfield is not repeated
574 # And where we are sure that field should correspond
575 # And $tag>10
576 sub UpdateMarcWith {
577   my ($marcfrom,$marcto)=@_;
578     my (  $itemtag,   $itemtagsubfield) = &GetMarcFromKohaField( "items.itemnumber" );
579     my $fieldfrom=$marcfrom->field($itemtag);
580     my @fields_to=$marcto->field($itemtag);
581     my $modified = 0;
582
583     return $modified unless $fieldfrom;
584
585     foreach my $subfield ( $fieldfrom->subfields() ) {
586         foreach my $field_to_update ( @fields_to ) {
587             if ( $subfield->[1] ) {
588                 unless ( $field_to_update->subfield($subfield->[0]) eq $subfield->[1] ) {
589                     $modified++;
590                     $field_to_update->update( $subfield->[0] => $subfield->[1] );
591                 }
592             }
593             else {
594                 $modified++;
595                 $field_to_update->delete_subfield( code => $subfield->[0] );
596             }
597         }
598     }
599     return $modified;
600 }
601
602 sub apply_regex {
603     my ($params) = @_;
604     my $search   = $params->{search};
605     my $replace  = $params->{replace};
606     my $modifiers = $params->{modifiers} || [];
607     my $value = $params->{value};
608
609     my @available_modifiers = qw( i g );
610     my $retained_modifiers  = q||;
611     for my $modifier ( split //, @$modifiers ) {
612         $retained_modifiers .= $modifier
613           if grep { /$modifier/ } @available_modifiers;
614     }
615     if ( $retained_modifiers =~ m/^(ig|gi)$/ ) {
616         $value =~ s/$search/$replace/ig;
617     }
618     elsif ( $retained_modifiers eq 'i' ) {
619         $value =~ s/$search/$replace/i;
620     }
621     elsif ( $retained_modifiers eq 'g' ) {
622         $value =~ s/$search/$replace/g;
623     }
624     else {
625         $value =~ s/$search/$replace/;
626     }
627
628     return $value;
629 }