Bug 20640: Add backend migration support to ILL
[koha.git] / tools / batchMod.pl
blobafb2d293b785311784cf216ba710abd07d6fa320
1 #!/usr/bin/perl
4 # Copyright 2000-2002 Katipo Communications
6 # This file is part of Koha.
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.
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.
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>.
21 use CGI qw ( -utf8 );
22 use Modern::Perl;
23 use C4::Auth;
24 use C4::Output;
25 use C4::Biblio;
26 use C4::Items;
27 use C4::Circulation;
28 use C4::Context;
29 use C4::Koha;
30 use C4::BackgroundJob;
31 use C4::ClassSource;
32 use C4::Debug;
33 use C4::Members;
34 use MARC::File::XML;
35 use List::MoreUtils qw/uniq/;
37 use Koha::AuthorisedValues;
38 use Koha::Biblios;
39 use Koha::DateUtils;
40 use Koha::Items;
41 use Koha::ItemTypes;
42 use Koha::Patrons;
44 my $input = new CGI;
45 my $dbh = C4::Context->dbh;
46 my $error = $input->param('error');
47 my @itemnumbers = $input->multi_param('itemnumber');
48 my $biblionumber = $input->param('biblionumber');
49 my $op = $input->param('op');
50 my $del = $input->param('del');
51 my $del_records = $input->param('del_records');
52 my $completedJobID = $input->param('completedJobID');
53 my $runinbackground = $input->param('runinbackground');
54 my $src = $input->param('src');
55 my $use_default_values = $input->param('use_default_values');
57 my $template_name;
58 my $template_flag;
59 if (!defined $op) {
60 $template_name = "tools/batchMod.tt";
61 $template_flag = { tools => '*' };
62 $op = q{};
63 } else {
64 $template_name = ($del) ? "tools/batchMod-del.tt" : "tools/batchMod-edit.tt";
65 $template_flag = ($del) ? { tools => 'items_batchdel' } : { tools => 'items_batchmod' };
69 my ($template, $loggedinuser, $cookie)
70 = get_template_and_user({template_name => $template_name,
71 query => $input,
72 type => "intranet",
73 authnotrequired => 0,
74 flagsrequired => $template_flag,
75 });
77 # Does the user have a restricted item edition permission?
78 my $uid = $loggedinuser ? Koha::Patrons->find( $loggedinuser )->userid : undef;
79 my $restrictededition = $uid ? haspermission($uid, {'tools' => 'items_batchmod_restricted'}) : undef;
80 # In case user is a superlibrarian, edition is not restricted
81 $restrictededition = 0 if ($restrictededition != 0 && C4::Context->IsSuperLibrarian());
83 $template->param(del => $del);
85 my $itemrecord;
86 my $nextop="";
87 my @errors; # store errors found while checking data BEFORE saving item.
88 my $items_display_hashref;
89 our $tagslib = &GetMarcStructure(1);
91 my $deleted_items = 0; # Number of deleted items
92 my $deleted_records = 0; # Number of deleted records ( with no items attached )
93 my $not_deleted_items = 0; # Number of items that could not be deleted
94 my @not_deleted; # List of the itemnumbers that could not be deleted
95 my $modified_items = 0; # Numbers of modified items
96 my $modified_fields = 0; # Numbers of modified fields
98 my %cookies = parse CGI::Cookie($cookie);
99 my $sessionID = $cookies{'CGISESSID'}->value;
102 #--- ----------------------------------------------------------------------------
103 if ($op eq "action") {
104 #-------------------------------------------------------------------------------
105 my @tags = $input->multi_param('tag');
106 my @subfields = $input->multi_param('subfield');
107 my @values = $input->multi_param('field_value');
108 my @disabled = $input->multi_param('disable_input');
109 # build indicator hash.
110 my @ind_tag = $input->multi_param('ind_tag');
111 my @indicator = $input->multi_param('indicator');
113 # Is there something to modify ?
114 # TODO : We shall use this var to warn the user in case no modification was done to the items
115 my $values_to_modify = scalar(grep {!/^$/} @values);
116 my $values_to_blank = scalar(@disabled);
117 my $marcitem;
119 # Once the job is done
120 if ($completedJobID) {
121 # If we have a reasonable amount of items, we display them
122 if (scalar(@itemnumbers) <= ( C4::Context->preference("MaxItemsToDisplayForBatchDel") // 1000 ) ) {
123 $items_display_hashref=BuildItemsData(@itemnumbers);
124 } else {
125 # Else, we only display the barcode
126 my @simple_items_display = map {
127 my $itemnumber = $_;
128 my $item = Koha::Items->find($itemnumber);
130 itemnumber => $itemnumber,
131 barcode => $item ? ( $item->barcode // q{} ) : q{},
132 biblionumber => $item ? $item->biblio->biblionumber : q{},
134 } @itemnumbers;
135 $template->param("simple_items_display" => \@simple_items_display);
138 # Setting the job as done
139 my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
141 # Calling the template
142 add_saved_job_results_to_template($template, $completedJobID);
144 } else {
145 # While the job is getting done
147 # Job size is the number of items we have to process
148 my $job_size = scalar(@itemnumbers);
149 my $job = undef;
151 # If we asked for background processing
152 if ($runinbackground) {
153 $job = put_in_background($job_size);
156 #initializing values for updates
157 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
158 if ($values_to_modify){
159 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
160 $marcitem = MARC::Record::new_from_xml($xml, 'UTF-8');
162 if ($values_to_blank){
163 foreach my $disabledsubf (@disabled){
164 if ($marcitem && $marcitem->field($itemtagfield)){
165 $marcitem->field($itemtagfield)->update( $disabledsubf => "" );
167 else {
168 $marcitem = MARC::Record->new();
169 $marcitem->append_fields( MARC::Field->new( $itemtagfield, '', '', $disabledsubf => "" ) );
174 # For each item
175 my $i = 1;
176 foreach my $itemnumber(@itemnumbers){
178 $job->progress($i) if $runinbackground;
179 my $itemdata = GetItem($itemnumber);
180 if ( $del ){
181 my $return = DelItemCheck( $itemdata->{'biblionumber'}, $itemdata->{'itemnumber'});
182 if ($return == 1) {
183 $deleted_items++;
184 } else {
185 $not_deleted_items++;
186 push @not_deleted,
187 { biblionumber => $itemdata->{'biblionumber'},
188 itemnumber => $itemdata->{'itemnumber'},
189 barcode => $itemdata->{'barcode'},
190 title => $itemdata->{'title'},
191 $return => 1
195 # If there are no items left, delete the biblio
196 if ( $del_records ) {
197 my $itemscount = Koha::Biblios->find( $itemdata->{'biblionumber'} )->items->count;
198 if ( $itemscount == 0 ) {
199 my $error = DelBiblio($itemdata->{'biblionumber'});
200 $deleted_records++ unless ( $error );
203 } else {
204 if ($values_to_modify || $values_to_blank) {
205 my $localmarcitem = Item2Marc($itemdata);
207 my $modified = UpdateMarcWith( $marcitem, $localmarcitem );
208 if ( $modified ) {
209 eval {
210 if ( my $item = ModItemFromMarc( $localmarcitem, $itemdata->{biblionumber}, $itemnumber ) ) {
211 LostItem($itemnumber, 'batchmod') if $item->{itemlost} and not $itemdata->{itemlost};
215 if ( $runinbackground ) {
216 $modified_items++ if $modified;
217 $modified_fields += $modified;
218 $job->set({
219 modified_items => $modified_items,
220 modified_fields => $modified_fields,
225 $i++;
230 #-------------------------------------------------------------------------------
231 # build screen with existing items. and "new" one
232 #-------------------------------------------------------------------------------
234 if ($op eq "show"){
235 my $filefh = $input->upload('uploadfile');
236 my $filecontent = $input->param('filecontent');
237 my ( @notfoundbarcodes, @notfounditemnumbers);
239 my @contentlist;
240 if ($filefh){
241 binmode $filefh, ':encoding(UTF-8)';
242 while (my $content=<$filefh>){
243 $content =~ s/[\r\n]*$//;
244 push @contentlist, $content if $content;
247 @contentlist = uniq @contentlist;
248 if ($filecontent eq 'barcode_file') {
249 my $existing_items = Koha::Items->search({ itemnumber => \@contentlist });
250 @itemnumbers = $existing_items->get_column('itemnumber');
251 my %exists = map {$_=>1} @{$existing_items->get_column('barcode')};
252 @notfoundbarcodes = grep { !$exists{$_} } @contentlist;
254 elsif ( $filecontent eq 'itemid_file') {
255 @itemnumbers = Koha::Items->search({ itemnumber => \@contentlist })->get_column('itemnumber');
256 my %exists = map {$_=>1} @itemnumbers;
257 @notfounditemnumbers = grep { !$exists{$_} } @contentlist;
259 } else {
260 if (defined $biblionumber){
261 my @all_items = GetItemsInfo( $biblionumber );
262 foreach my $itm (@all_items) {
263 push @itemnumbers, $itm->{itemnumber};
266 if ( my $list=$input->param('barcodelist')){
267 push my @barcodelist, uniq( split(/\s\n/, $list) );
269 my $existing_items = Koha::Items->search({ barcode => \@barcodelist });
270 @itemnumbers = $existing_items->get_column('itemnumber');
271 my @barcodes = $existing_items->get_column('barcode');
272 my %exists = map {$_=>1} @barcodes;
273 @notfoundbarcodes = grep { !$exists{$_} } @barcodelist;
277 # Flag to tell the template there are valid results, hidden or not
278 if(scalar(@itemnumbers) > 0){ $template->param("itemresults" => 1); }
279 # Only display the items if there are no more than pref MaxItemsToProcessForBatchMod or MaxItemsToDisplayForBatchDel
280 my $max_items = $del
281 ? C4::Context->preference("MaxItemsToDisplayForBatchDel")
282 : C4::Context->preference("MaxItemsToProcessForBatchMod");
283 if (scalar(@itemnumbers) <= ( $max_items // 1000 ) ) {
284 $items_display_hashref=BuildItemsData(@itemnumbers);
285 } else {
286 $template->param("too_many_items" => scalar(@itemnumbers));
287 # Even if we do not display the items, we need the itemnumbers
288 $template->param(itemnumbers_array => \@itemnumbers);
290 # now, build the item form for entering a new item
291 my @loop_data =();
292 my $i=0;
293 my $branch_limit = C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
295 my $libraries = Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed;# build once ahead of time, instead of multiple times later.
297 # Adding a default choice, in case the user does not want to modify the branch
298 my $nochange_branch = { branchname => '', value => '', selected => 1 };
299 unshift (@$libraries, $nochange_branch);
301 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
303 # Getting list of subfields to keep when restricted batchmod edit is enabled
304 my $subfieldsToAllowForBatchmod = C4::Context->preference('SubfieldsToAllowForRestrictedBatchmod');
305 my $allowAllSubfields = (
306 not defined $subfieldsToAllowForBatchmod
307 or $subfieldsToAllowForBatchmod eq q||
308 ) ? 1 : 0;
309 my @subfieldsToAllow = split(/ /, $subfieldsToAllowForBatchmod);
311 foreach my $tag (sort keys %{$tagslib}) {
312 # loop through each subfield
313 foreach my $subfield (sort keys %{$tagslib->{$tag}}) {
314 next if IsMarcStructureInternal( $tagslib->{$tag}{$subfield} );
315 next if (not $allowAllSubfields and $restrictededition && !grep { $tag . '$' . $subfield eq $_ } @subfieldsToAllow );
316 next if ($tagslib->{$tag}->{$subfield}->{'tab'} ne "10");
317 # barcode and stocknumber are not meant to be batch-modified
318 next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.barcode';
319 next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.stocknumber';
320 my %subfield_data;
322 my $index_subfield = int(rand(1000000));
323 if ($subfield eq '@'){
324 $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
325 } else {
326 $subfield_data{id} = "tag_".$tag."_subfield_".$subfield."_".$index_subfield;
328 $subfield_data{tag} = $tag;
329 $subfield_data{subfield} = $subfield;
330 $subfield_data{marc_lib} ="<span id=\"error$i\" title=\"".$tagslib->{$tag}->{$subfield}->{lib}."\">".$tagslib->{$tag}->{$subfield}->{lib}."</span>";
331 $subfield_data{mandatory} = $tagslib->{$tag}->{$subfield}->{mandatory};
332 $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
333 my ($x,$value);
334 if ( $use_default_values) {
335 $value = $tagslib->{$tag}->{$subfield}->{defaultvalue};
336 # get today date & replace YYYY, MM, DD if provided in the default value
337 my $today = dt_from_string;
338 my $year = $today->year;
339 my $month = $today->month;
340 my $day = $today->day;
341 $value =~ s/YYYY/$year/g;
342 $value =~ s/MM/$month/g;
343 $value =~ s/DD/$day/g;
345 $subfield_data{visibility} = "display:none;" if (($tagslib->{$tag}->{$subfield}->{hidden} > 4) || ($tagslib->{$tag}->{$subfield}->{hidden} < -4));
346 # testing branch value if IndependentBranches.
348 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
349 my @authorised_values;
350 my %authorised_lib;
351 # builds list, depending on authorised value...
353 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "branches" ) {
354 foreach my $library (@$libraries) {
355 push @authorised_values, $library->{branchcode};
356 $authorised_lib{$library->{branchcode}} = $library->{branchname};
358 $value = "";
360 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
361 push @authorised_values, "";
362 my $itemtypes = Koha::ItemTypes->search_with_localization;
363 while ( my $itemtype = $itemtypes->next ) {
364 push @authorised_values, $itemtype->itemtype;
365 $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description;
367 $value = "";
369 #---- class_sources
371 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
372 push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
374 my $class_sources = GetClassSources();
375 my $default_source = C4::Context->preference("DefaultClassificationSource");
377 foreach my $class_source (sort keys %$class_sources) {
378 next unless $class_sources->{$class_source}->{'used'} or
379 ($value and $class_source eq $value) or
380 ($class_source eq $default_source);
381 push @authorised_values, $class_source;
382 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
384 $value = '';
386 #---- "true" authorised value
388 else {
389 push @authorised_values, ""; # unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
391 my @avs = Koha::AuthorisedValues->search({ category => $tagslib->{$tag}->{$subfield}->{authorised_value}, branchcode => $branch_limit },{order_by=>'lib'});
392 for my $av ( @avs ) {
393 push @authorised_values, $av->authorised_value;
394 $authorised_lib{$av->authorised_value} = $av->lib;
396 $value="";
398 $subfield_data{marc_value} = {
399 type => 'select',
400 id => "tag_".$tag."_subfield_".$subfield."_".$index_subfield,
401 name => "field_value",
402 values => \@authorised_values,
403 labels => \%authorised_lib,
404 default => $value,
406 # it's a thesaurus / authority field
408 elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode} ) {
409 $subfield_data{marc_value} = {
410 type => 'text1',
411 id => $subfield_data{id},
412 value => $value,
413 authtypecode => $tagslib->{$tag}->{$subfield}->{authtypecode},
416 elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) { # plugin
417 require Koha::FrameworkPlugin;
418 my $plugin = Koha::FrameworkPlugin->new( {
419 name => $tagslib->{$tag}->{$subfield}->{'value_builder'},
420 item_style => 1,
422 my $temp;
423 my $pars= { dbh => $dbh, record => $temp, tagslib => $tagslib,
424 id => $subfield_data{id}, tabloop => \@loop_data };
425 $plugin->build( $pars );
426 if( !$plugin->errstr ) {
427 $subfield_data{marc_value} = {
428 type => 'text2',
429 id => $subfield_data{id},
430 value => $value,
431 javascript => $plugin->javascript,
432 noclick => $plugin->noclick,
434 } else {
435 warn $plugin->errstr;
436 $subfield_data{marc_value} = { # supply default input form
437 type => 'text',
438 id => $subfield_data{id},
439 value => $value,
443 elsif ( $tag eq '' ) { # it's an hidden field
444 $subfield_data{marc_value} = {
445 type => 'hidden',
446 id => $subfield_data{id},
447 value => $value,
450 elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
451 $subfield_data{marc_value} = {
452 type => 'text',
453 id => $subfield_data{id},
454 value => $value,
457 elsif ( length($value) > 100
458 or (C4::Context->preference("marcflavour") eq "UNIMARC" and
459 300 <= $tag && $tag < 400 && $subfield eq 'a' )
460 or (C4::Context->preference("marcflavour") eq "MARC21" and
461 500 <= $tag && $tag < 600 )
463 # oversize field (textarea)
464 $subfield_data{marc_value} = {
465 type => 'textarea',
466 id => $subfield_data{id},
467 value => $value,
469 } else {
470 # it's a standard field
471 $subfield_data{marc_value} = {
472 type => 'text',
473 id => $subfield_data{id},
474 value => $value,
477 # $subfield_data{marc_value}="<input type=\"text\" name=\"field_value\">";
478 push (@loop_data, \%subfield_data);
479 $i++
481 } # -- End foreach tag
485 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
486 $template->param(
487 item => \@loop_data,
488 notfoundbarcodes => \@notfoundbarcodes,
489 notfounditemnumbers => \@notfounditemnumbers
491 $nextop="action"
492 } # -- End action="show"
494 $template->param(%$items_display_hashref) if $items_display_hashref;
495 $template->param(
496 op => $nextop,
498 $template->param( $op => 1 ) if $op;
500 if ($op eq "action") {
502 #my @not_deleted_loop = map{{itemnumber=>$_}}@not_deleted;
504 $template->param(
505 not_deleted_items => $not_deleted_items,
506 deleted_items => $deleted_items,
507 delete_records => $del_records,
508 deleted_records => $deleted_records,
509 not_deleted_loop => \@not_deleted
513 foreach my $error (@errors) {
514 $template->param($error => 1) if $error;
516 $template->param(src => $src);
517 $template->param(biblionumber => $biblionumber);
518 output_html_with_http_headers $input, $cookie, $template->output;
519 exit;
522 # ---------------- Functions
524 sub BuildItemsData{
525 my @itemnumbers=@_;
526 # now, build existiing item list
527 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
528 my @big_array;
529 #---- finds where items.itemnumber is stored
530 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
531 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField("items.homebranch", "");
532 foreach my $itemnumber (@itemnumbers){
533 my $itemdata=GetItem($itemnumber);
534 my $itemmarc=Item2Marc($itemdata);
535 my %this_row;
536 foreach my $field (grep {$_->tag() eq $itemtagfield} $itemmarc->fields()) {
537 # loop through each subfield
538 my $itembranchcode=$field->subfield($branchtagsubfield);
539 if ($itembranchcode && C4::Context->preference("IndependentBranches")) {
540 #verifying rights
541 my $userenv = C4::Context->userenv();
542 unless (C4::Context->IsSuperLibrarian() or (($userenv->{'branch'} eq $itembranchcode))){
543 $this_row{'nomod'}=1;
546 my $tag=$field->tag();
547 foreach my $subfield ($field->subfields) {
548 my ($subfcode,$subfvalue)=@$subfield;
549 next if ($tagslib->{$tag}->{$subfcode}->{tab} ne 10
550 && $tag ne $itemtagfield
551 && $subfcode ne $itemtagsubfield);
553 $witness{$subfcode} = $tagslib->{$tag}->{$subfcode}->{lib} if ($tagslib->{$tag}->{$subfcode}->{tab} eq 10);
554 if ($tagslib->{$tag}->{$subfcode}->{tab} eq 10) {
555 $this_row{$subfcode}=GetAuthorisedValueDesc( $tag,
556 $subfcode, $subfvalue, '', $tagslib)
557 || $subfvalue;
560 $this_row{itemnumber} = $subfvalue if ($tag eq $itemtagfield && $subfcode eq $itemtagsubfield);
564 # grab title, author, and ISBN to identify bib that the item
565 # belongs to in the display
566 my $biblio = Koha::Biblios->find( $itemdata->{biblionumber} );
567 $this_row{title} = $biblio->title;
568 $this_row{author} = $biblio->author;
569 $this_row{isbn} = $biblio->biblioitem->isbn;
570 $this_row{biblionumber} = $biblio->biblionumber;
571 $this_row{holds} = $biblio->holds->count;
572 $this_row{item_holds} = Koha::Holds->search( itemnumber => $itemnumber )->count;
574 if (%this_row) {
575 push(@big_array, \%this_row);
578 @big_array = sort {$a->{0} cmp $b->{0}} @big_array;
580 # now, construct template !
581 # First, the existing items for display
582 my @item_value_loop;
583 my @witnesscodessorted=sort keys %witness;
584 for my $row ( @big_array ) {
585 my %row_data;
586 my @item_fields = map +{ field => $_ || '' }, @$row{ @witnesscodessorted };
587 $row_data{item_value} = [ @item_fields ];
588 $row_data{itemnumber} = $row->{itemnumber};
589 #reporting this_row values
590 $row_data{'nomod'} = $row->{'nomod'};
591 $row_data{bibinfo} = $row->{bibinfo};
592 $row_data{author} = $row->{author};
593 $row_data{title} = $row->{title};
594 $row_data{isbn} = $row->{isbn};
595 $row_data{biblionumber} = $row->{biblionumber};
596 $row_data{holds} = $row->{holds};
597 $row_data{item_holds} = $row->{item_holds};
598 my $is_on_loan = C4::Circulation::IsItemIssued( $row->{itemnumber} );
599 $row_data{onloan} = $is_on_loan ? 1 : 0;
600 push(@item_value_loop,\%row_data);
602 my @header_loop=map { { header_value=> $witness{$_}} } @witnesscodessorted;
604 return { item_loop => \@item_value_loop, item_header_loop => \@header_loop };
607 #BE WARN : it is not the general case
608 # This function can be OK in the item marc record special case
609 # Where subfield is not repeated
610 # And where we are sure that field should correspond
611 # And $tag>10
612 sub UpdateMarcWith {
613 my ($marcfrom,$marcto)=@_;
614 my ( $itemtag, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
615 my $fieldfrom=$marcfrom->field($itemtag);
616 my @fields_to=$marcto->field($itemtag);
617 my $modified = 0;
618 foreach my $subfield ( $fieldfrom->subfields() ) {
619 foreach my $field_to_update ( @fields_to ) {
620 if ( $subfield->[1] ) {
621 unless ( $field_to_update->subfield($subfield->[0]) eq $subfield->[1] ) {
622 $modified++;
623 $field_to_update->update( $subfield->[0] => $subfield->[1] );
626 else {
627 $modified++;
628 $field_to_update->delete_subfield( code => $subfield->[0] );
632 return $modified;
635 sub find_value {
636 my ($tagfield,$insubfield,$record) = @_;
637 my $result;
638 my $indicator;
639 foreach my $field ($record->field($tagfield)) {
640 my @subfields = $field->subfields();
641 foreach my $subfield (@subfields) {
642 if (@$subfield[0] eq $insubfield) {
643 $result .= @$subfield[1];
644 $indicator = $field->indicator(1).$field->indicator(2);
648 return($indicator,$result);
651 # ----------------------------
652 # Background functions
655 sub add_results_to_template {
656 my $template = shift;
657 my $results = shift;
658 $template->param(map { $_ => $results->{$_} } keys %{ $results });
661 sub add_saved_job_results_to_template {
662 my $template = shift;
663 my $completedJobID = shift;
664 my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
665 my $results = $job->results();
666 add_results_to_template($template, $results);
668 my $fields = $job->get("modified_fields");
669 my $items = $job->get("modified_items");
670 $template->param(
671 modified_items => $items,
672 modified_fields => $fields,
676 sub put_in_background {
677 my $job_size = shift;
679 my $job = C4::BackgroundJob->new($sessionID, "test", '/cgi-bin/koha/tools/batchMod.pl', $job_size);
680 my $jobID = $job->id();
682 # fork off
683 if (my $pid = fork) {
684 # parent
685 # return job ID as JSON
687 # prevent parent exiting from
688 # destroying the kid's database handle
689 # FIXME: according to DBI doc, this may not work for Oracle
690 $dbh->{InactiveDestroy} = 1;
692 my $reply = CGI->new("");
693 print $reply->header(-type => 'text/html');
694 print '{"jobID":"' . $jobID . '"}';
695 exit 0;
696 } elsif (defined $pid) {
697 # child
698 # close STDOUT to signal to Apache that
699 # we're now running in the background
700 close STDOUT;
701 close STDERR;
702 } else {
703 # fork failed, so exit immediately
704 warn "fork failed while attempting to run tools/batchMod.pl as a background job";
705 exit 0;
707 return $job;