Translation updates for Koha 18.11.12
[koha.git] / tools / batchMod.pl
blob8ee28871e20a2da64bcb7e7131764cc6a6df8cc6
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({ barcode => \@contentlist });
250 @itemnumbers = $existing_items->get_column('itemnumber');
251 my %exists = map {lc($_)=>1} $existing_items->get_column('barcode');
252 # to avoid problems with case sensitivity
253 foreach my $barcode (@contentlist) {
254 $barcode = lc($barcode);
256 @notfoundbarcodes = grep { !$exists{$_} } @contentlist;
258 elsif ( $filecontent eq 'itemid_file') {
259 @itemnumbers = Koha::Items->search({ itemnumber => \@contentlist })->get_column('itemnumber');
260 my %exists = map {$_=>1} @itemnumbers;
261 @notfounditemnumbers = grep { !$exists{$_} } @contentlist;
263 } else {
264 if (defined $biblionumber){
265 my @all_items = GetItemsInfo( $biblionumber );
266 foreach my $itm (@all_items) {
267 push @itemnumbers, $itm->{itemnumber};
270 if ( my $list=$input->param('barcodelist')){
271 push my @barcodelist, uniq( split(/\s\n/, $list) );
273 my $existing_items = Koha::Items->search({ barcode => \@barcodelist });
274 @itemnumbers = $existing_items->get_column('itemnumber');
275 my @barcodes = $existing_items->get_column('barcode');
276 my %exists = map {lc($_)=>1} @barcodes;
277 # to avoid problems with case sensitivity
278 foreach my $barcode (@barcodelist) {
279 $barcode = lc($barcode);
281 @notfoundbarcodes = grep { !$exists{$_} } @barcodelist;
285 # Flag to tell the template there are valid results, hidden or not
286 if(scalar(@itemnumbers) > 0){ $template->param("itemresults" => 1); }
287 # Only display the items if there are no more than pref MaxItemsToProcessForBatchMod or MaxItemsToDisplayForBatchDel
288 my $max_items = $del
289 ? C4::Context->preference("MaxItemsToDisplayForBatchDel")
290 : C4::Context->preference("MaxItemsToProcessForBatchMod");
291 if (scalar(@itemnumbers) <= ( $max_items // 1000 ) ) {
292 $items_display_hashref=BuildItemsData(@itemnumbers);
293 } else {
294 $template->param("too_many_items" => scalar(@itemnumbers));
295 # Even if we do not display the items, we need the itemnumbers
296 $template->param(itemnumbers_array => \@itemnumbers);
298 # now, build the item form for entering a new item
299 my @loop_data =();
300 my $i=0;
301 my $branch_limit = C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
303 my $libraries = Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed;# build once ahead of time, instead of multiple times later.
305 # Adding a default choice, in case the user does not want to modify the branch
306 my $nochange_branch = { branchname => '', value => '', selected => 1 };
307 unshift (@$libraries, $nochange_branch);
309 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
311 # Getting list of subfields to keep when restricted batchmod edit is enabled
312 my $subfieldsToAllowForBatchmod = C4::Context->preference('SubfieldsToAllowForRestrictedBatchmod');
313 my $allowAllSubfields = (
314 not defined $subfieldsToAllowForBatchmod
315 or $subfieldsToAllowForBatchmod eq q||
316 ) ? 1 : 0;
317 my @subfieldsToAllow = split(/ /, $subfieldsToAllowForBatchmod);
319 foreach my $tag (sort keys %{$tagslib}) {
320 # loop through each subfield
321 foreach my $subfield (sort keys %{$tagslib->{$tag}}) {
322 next if IsMarcStructureInternal( $tagslib->{$tag}{$subfield} );
323 next if (not $allowAllSubfields and $restrictededition && !grep { $tag . '$' . $subfield eq $_ } @subfieldsToAllow );
324 next if ($tagslib->{$tag}->{$subfield}->{'tab'} ne "10");
325 # barcode and stocknumber are not meant to be batch-modified
326 next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.barcode';
327 next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.stocknumber';
328 my %subfield_data;
330 my $index_subfield = int(rand(1000000));
331 if ($subfield eq '@'){
332 $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
333 } else {
334 $subfield_data{id} = "tag_".$tag."_subfield_".$subfield."_".$index_subfield;
336 $subfield_data{tag} = $tag;
337 $subfield_data{subfield} = $subfield;
338 $subfield_data{marc_lib} ="<span id=\"error$i\" title=\"".$tagslib->{$tag}->{$subfield}->{lib}."\">".$tagslib->{$tag}->{$subfield}->{lib}."</span>";
339 $subfield_data{mandatory} = $tagslib->{$tag}->{$subfield}->{mandatory};
340 $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
341 my ($x,$value);
342 if ( $use_default_values) {
343 $value = $tagslib->{$tag}->{$subfield}->{defaultvalue};
344 # get today date & replace YYYY, MM, DD if provided in the default value
345 my $today = dt_from_string;
346 my $year = $today->year;
347 my $month = $today->month;
348 my $day = $today->day;
349 $value =~ s/YYYY/$year/g;
350 $value =~ s/MM/$month/g;
351 $value =~ s/DD/$day/g;
353 $subfield_data{visibility} = "display:none;" if (($tagslib->{$tag}->{$subfield}->{hidden} > 4) || ($tagslib->{$tag}->{$subfield}->{hidden} < -4));
354 # testing branch value if IndependentBranches.
356 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
357 my @authorised_values;
358 my %authorised_lib;
359 # builds list, depending on authorised value...
361 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "branches" ) {
362 foreach my $library (@$libraries) {
363 push @authorised_values, $library->{branchcode};
364 $authorised_lib{$library->{branchcode}} = $library->{branchname};
366 $value = "";
368 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
369 push @authorised_values, "";
370 my $itemtypes = Koha::ItemTypes->search_with_localization;
371 while ( my $itemtype = $itemtypes->next ) {
372 push @authorised_values, $itemtype->itemtype;
373 $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description;
375 $value = "";
377 #---- class_sources
379 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
380 push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
382 my $class_sources = GetClassSources();
383 my $default_source = C4::Context->preference("DefaultClassificationSource");
385 foreach my $class_source (sort keys %$class_sources) {
386 next unless $class_sources->{$class_source}->{'used'} or
387 ($value and $class_source eq $value) or
388 ($class_source eq $default_source);
389 push @authorised_values, $class_source;
390 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
392 $value = '';
394 #---- "true" authorised value
396 else {
397 push @authorised_values, ""; # unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
399 my @avs = Koha::AuthorisedValues->search({ category => $tagslib->{$tag}->{$subfield}->{authorised_value}, branchcode => $branch_limit },{order_by=>'lib'});
400 for my $av ( @avs ) {
401 push @authorised_values, $av->authorised_value;
402 $authorised_lib{$av->authorised_value} = $av->lib;
404 $value="";
406 $subfield_data{marc_value} = {
407 type => 'select',
408 id => "tag_".$tag."_subfield_".$subfield."_".$index_subfield,
409 name => "field_value",
410 values => \@authorised_values,
411 labels => \%authorised_lib,
412 default => $value,
414 # it's a thesaurus / authority field
416 elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode} ) {
417 $subfield_data{marc_value} = {
418 type => 'text1',
419 id => $subfield_data{id},
420 value => $value,
421 authtypecode => $tagslib->{$tag}->{$subfield}->{authtypecode},
424 elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) { # plugin
425 require Koha::FrameworkPlugin;
426 my $plugin = Koha::FrameworkPlugin->new( {
427 name => $tagslib->{$tag}->{$subfield}->{'value_builder'},
428 item_style => 1,
430 my $temp;
431 my $pars= { dbh => $dbh, record => $temp, tagslib => $tagslib,
432 id => $subfield_data{id}, tabloop => \@loop_data };
433 $plugin->build( $pars );
434 if( !$plugin->errstr ) {
435 $subfield_data{marc_value} = {
436 type => 'text2',
437 id => $subfield_data{id},
438 value => $value,
439 javascript => $plugin->javascript,
440 noclick => $plugin->noclick,
442 } else {
443 warn $plugin->errstr;
444 $subfield_data{marc_value} = { # supply default input form
445 type => 'text',
446 id => $subfield_data{id},
447 value => $value,
451 elsif ( $tag eq '' ) { # it's an hidden field
452 $subfield_data{marc_value} = {
453 type => 'hidden',
454 id => $subfield_data{id},
455 value => $value,
458 elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
459 $subfield_data{marc_value} = {
460 type => 'text',
461 id => $subfield_data{id},
462 value => $value,
465 elsif ( length($value) > 100
466 or (C4::Context->preference("marcflavour") eq "UNIMARC" and
467 300 <= $tag && $tag < 400 && $subfield eq 'a' )
468 or (C4::Context->preference("marcflavour") eq "MARC21" and
469 500 <= $tag && $tag < 600 )
471 # oversize field (textarea)
472 $subfield_data{marc_value} = {
473 type => 'textarea',
474 id => $subfield_data{id},
475 value => $value,
477 } else {
478 # it's a standard field
479 $subfield_data{marc_value} = {
480 type => 'text',
481 id => $subfield_data{id},
482 value => $value,
485 # $subfield_data{marc_value}="<input type=\"text\" name=\"field_value\">";
486 push (@loop_data, \%subfield_data);
487 $i++
489 } # -- End foreach tag
493 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
494 $template->param(
495 item => \@loop_data,
496 notfoundbarcodes => \@notfoundbarcodes,
497 notfounditemnumbers => \@notfounditemnumbers
499 $nextop="action"
500 } # -- End action="show"
502 $template->param(%$items_display_hashref) if $items_display_hashref;
503 $template->param(
504 op => $nextop,
506 $template->param( $op => 1 ) if $op;
508 if ($op eq "action") {
510 #my @not_deleted_loop = map{{itemnumber=>$_}}@not_deleted;
512 $template->param(
513 not_deleted_items => $not_deleted_items,
514 deleted_items => $deleted_items,
515 delete_records => $del_records,
516 deleted_records => $deleted_records,
517 not_deleted_loop => \@not_deleted
521 foreach my $error (@errors) {
522 $template->param($error => 1) if $error;
524 $template->param(src => $src);
525 $template->param(biblionumber => $biblionumber);
526 output_html_with_http_headers $input, $cookie, $template->output;
527 exit;
530 # ---------------- Functions
532 sub BuildItemsData{
533 my @itemnumbers=@_;
534 # now, build existiing item list
535 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
536 my @big_array;
537 #---- finds where items.itemnumber is stored
538 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
539 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField("items.homebranch", "");
540 foreach my $itemnumber (@itemnumbers){
541 my $itemdata=GetItem($itemnumber);
542 my $itemmarc=Item2Marc($itemdata);
543 my %this_row;
544 foreach my $field (grep {$_->tag() eq $itemtagfield} $itemmarc->fields()) {
545 # loop through each subfield
546 my $itembranchcode=$field->subfield($branchtagsubfield);
547 if ($itembranchcode && C4::Context->preference("IndependentBranches")) {
548 #verifying rights
549 my $userenv = C4::Context->userenv();
550 unless (C4::Context->IsSuperLibrarian() or (($userenv->{'branch'} eq $itembranchcode))){
551 $this_row{'nomod'}=1;
554 my $tag=$field->tag();
555 foreach my $subfield ($field->subfields) {
556 my ($subfcode,$subfvalue)=@$subfield;
557 next if ($tagslib->{$tag}->{$subfcode}->{tab} ne 10
558 && $tag ne $itemtagfield
559 && $subfcode ne $itemtagsubfield);
561 $witness{$subfcode} = $tagslib->{$tag}->{$subfcode}->{lib} if ($tagslib->{$tag}->{$subfcode}->{tab} eq 10);
562 if ($tagslib->{$tag}->{$subfcode}->{tab} eq 10) {
563 $this_row{$subfcode}=GetAuthorisedValueDesc( $tag,
564 $subfcode, $subfvalue, '', $tagslib)
565 || $subfvalue;
568 $this_row{itemnumber} = $subfvalue if ($tag eq $itemtagfield && $subfcode eq $itemtagsubfield);
572 # grab title, author, and ISBN to identify bib that the item
573 # belongs to in the display
574 my $biblio = Koha::Biblios->find( $itemdata->{biblionumber} );
575 $this_row{title} = $biblio->title;
576 $this_row{author} = $biblio->author;
577 $this_row{isbn} = $biblio->biblioitem->isbn;
578 $this_row{biblionumber} = $biblio->biblionumber;
579 $this_row{holds} = $biblio->holds->count;
580 $this_row{item_holds} = Koha::Holds->search( itemnumber => $itemnumber )->count;
582 if (%this_row) {
583 push(@big_array, \%this_row);
586 @big_array = sort {$a->{0} cmp $b->{0}} @big_array;
588 # now, construct template !
589 # First, the existing items for display
590 my @item_value_loop;
591 my @witnesscodessorted=sort keys %witness;
592 for my $row ( @big_array ) {
593 my %row_data;
594 my @item_fields = map +{ field => $_ || '' }, @$row{ @witnesscodessorted };
595 $row_data{item_value} = [ @item_fields ];
596 $row_data{itemnumber} = $row->{itemnumber};
597 #reporting this_row values
598 $row_data{'nomod'} = $row->{'nomod'};
599 $row_data{bibinfo} = $row->{bibinfo};
600 $row_data{author} = $row->{author};
601 $row_data{title} = $row->{title};
602 $row_data{isbn} = $row->{isbn};
603 $row_data{biblionumber} = $row->{biblionumber};
604 $row_data{holds} = $row->{holds};
605 $row_data{item_holds} = $row->{item_holds};
606 my $is_on_loan = C4::Circulation::IsItemIssued( $row->{itemnumber} );
607 $row_data{onloan} = $is_on_loan ? 1 : 0;
608 push(@item_value_loop,\%row_data);
610 my @header_loop=map { { header_value=> $witness{$_}} } @witnesscodessorted;
612 return { item_loop => \@item_value_loop, item_header_loop => \@header_loop };
615 #BE WARN : it is not the general case
616 # This function can be OK in the item marc record special case
617 # Where subfield is not repeated
618 # And where we are sure that field should correspond
619 # And $tag>10
620 sub UpdateMarcWith {
621 my ($marcfrom,$marcto)=@_;
622 my ( $itemtag, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
623 my $fieldfrom=$marcfrom->field($itemtag);
624 my @fields_to=$marcto->field($itemtag);
625 my $modified = 0;
626 foreach my $subfield ( $fieldfrom->subfields() ) {
627 foreach my $field_to_update ( @fields_to ) {
628 if ( $subfield->[1] ) {
629 unless ( $field_to_update->subfield($subfield->[0]) eq $subfield->[1] ) {
630 $modified++;
631 $field_to_update->update( $subfield->[0] => $subfield->[1] );
634 else {
635 $modified++;
636 $field_to_update->delete_subfield( code => $subfield->[0] );
640 return $modified;
643 sub find_value {
644 my ($tagfield,$insubfield,$record) = @_;
645 my $result;
646 my $indicator;
647 foreach my $field ($record->field($tagfield)) {
648 my @subfields = $field->subfields();
649 foreach my $subfield (@subfields) {
650 if (@$subfield[0] eq $insubfield) {
651 $result .= @$subfield[1];
652 $indicator = $field->indicator(1).$field->indicator(2);
656 return($indicator,$result);
659 # ----------------------------
660 # Background functions
663 sub add_results_to_template {
664 my $template = shift;
665 my $results = shift;
666 $template->param(map { $_ => $results->{$_} } keys %{ $results });
669 sub add_saved_job_results_to_template {
670 my $template = shift;
671 my $completedJobID = shift;
672 my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
673 my $results = $job->results();
674 add_results_to_template($template, $results);
676 my $fields = $job->get("modified_fields");
677 my $items = $job->get("modified_items");
678 $template->param(
679 modified_items => $items,
680 modified_fields => $fields,
684 sub put_in_background {
685 my $job_size = shift;
687 my $job = C4::BackgroundJob->new($sessionID, "test", '/cgi-bin/koha/tools/batchMod.pl', $job_size);
688 my $jobID = $job->id();
690 # fork off
691 if (my $pid = fork) {
692 # parent
693 # return job ID as JSON
695 # prevent parent exiting from
696 # destroying the kid's database handle
697 # FIXME: according to DBI doc, this may not work for Oracle
698 $dbh->{InactiveDestroy} = 1;
700 my $reply = CGI->new("");
701 print $reply->header(-type => 'text/html');
702 print '{"jobID":"' . $jobID . '"}';
703 exit 0;
704 } elsif (defined $pid) {
705 # child
706 # close STDOUT to signal to Apache that
707 # we're now running in the background
708 close STDOUT;
709 close STDERR;
710 } else {
711 # fork failed, so exit immediately
712 warn "fork failed while attempting to run tools/batchMod.pl as a background job";
713 exit 0;
715 return $job;