Bug 23077: Don't fill cardnumber with empty string
[koha.git] / tools / batchMod.pl
blobe5b6032900bbc9cd519cd87214c95c652616a030
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 my $max_items = $del ? C4::Context->preference("MaxItemsToDisplayForBatchDel") : C4::Context->preference("MaxItemsToDisplayForBatchMod");
123 if (scalar(@itemnumbers) <= $max_items ){
124 if (scalar(@itemnumbers) <= 1000 ) {
125 $items_display_hashref=BuildItemsData(@itemnumbers);
126 } else {
127 # Else, we only display the barcode
128 my @simple_items_display = map {
129 my $itemnumber = $_;
130 my $item = Koha::Items->find($itemnumber);
132 itemnumber => $itemnumber,
133 barcode => $item ? ( $item->barcode // q{} ) : q{},
134 biblionumber => $item ? $item->biblio->biblionumber : q{},
136 } @itemnumbers;
137 $template->param("simple_items_display" => \@simple_items_display);
139 } else {
140 $template->param( "too_many_items_display" => scalar(@itemnumbers) );
141 $template->param( "job_completed" => 1 );
144 # Setting the job as done
145 my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
147 # Calling the template
148 add_saved_job_results_to_template($template, $completedJobID);
150 } else {
151 # While the job is getting done
153 # Job size is the number of items we have to process
154 my $job_size = scalar(@itemnumbers);
155 my $job = undef;
157 # If we asked for background processing
158 if ($runinbackground) {
159 $job = put_in_background($job_size);
162 #initializing values for updates
163 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
164 if ($values_to_modify){
165 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
166 $marcitem = MARC::Record::new_from_xml($xml, 'UTF-8');
168 if ($values_to_blank){
169 foreach my $disabledsubf (@disabled){
170 if ($marcitem && $marcitem->field($itemtagfield)){
171 $marcitem->field($itemtagfield)->update( $disabledsubf => "" );
173 else {
174 $marcitem = MARC::Record->new();
175 $marcitem->append_fields( MARC::Field->new( $itemtagfield, '', '', $disabledsubf => "" ) );
180 # For each item
181 my $i = 1;
182 foreach my $itemnumber(@itemnumbers){
184 $job->progress($i) if $runinbackground;
185 my $itemdata = Koha::Items->find($itemnumber);
186 next unless $itemdata; # Should have been tested earlier, but just in case...
187 $itemdata = $itemdata->unblessed;
188 if ( $del ){
189 my $return = DelItemCheck( $itemdata->{'biblionumber'}, $itemdata->{'itemnumber'});
190 if ($return == 1) {
191 $deleted_items++;
192 } else {
193 $not_deleted_items++;
194 push @not_deleted,
195 { biblionumber => $itemdata->{'biblionumber'},
196 itemnumber => $itemdata->{'itemnumber'},
197 barcode => $itemdata->{'barcode'},
198 title => $itemdata->{'title'},
199 $return => 1
203 # If there are no items left, delete the biblio
204 if ( $del_records ) {
205 my $itemscount = Koha::Biblios->find( $itemdata->{'biblionumber'} )->items->count;
206 if ( $itemscount == 0 ) {
207 my $error = DelBiblio($itemdata->{'biblionumber'});
208 $deleted_records++ unless ( $error );
211 } else {
212 if ($values_to_modify || $values_to_blank) {
213 my $localmarcitem = Item2Marc($itemdata);
215 my $modified = UpdateMarcWith( $marcitem, $localmarcitem );
216 if ( $modified ) {
217 eval {
218 if ( my $item = ModItemFromMarc( $localmarcitem, $itemdata->{biblionumber}, $itemnumber ) ) {
219 LostItem($itemnumber, 'batchmod') if $item->{itemlost} and not $itemdata->{itemlost};
223 if ( $runinbackground ) {
224 $modified_items++ if $modified;
225 $modified_fields += $modified;
226 $job->set({
227 modified_items => $modified_items,
228 modified_fields => $modified_fields,
233 $i++;
238 #-------------------------------------------------------------------------------
239 # build screen with existing items. and "new" one
240 #-------------------------------------------------------------------------------
242 if ($op eq "show"){
243 my $filefh = $input->upload('uploadfile');
244 my $filecontent = $input->param('filecontent');
245 my ( @notfoundbarcodes, @notfounditemnumbers);
247 my @contentlist;
248 if ($filefh){
249 binmode $filefh, ':encoding(UTF-8)';
250 while (my $content=<$filefh>){
251 $content =~ s/[\r\n]*$//;
252 push @contentlist, $content if $content;
255 @contentlist = uniq @contentlist;
256 if ($filecontent eq 'barcode_file') {
257 my $existing_items = Koha::Items->search({ barcode => \@contentlist });
258 @itemnumbers = $existing_items->get_column('itemnumber');
259 my %exists = map {$_=>1} $existing_items->get_column('barcode');
260 @notfoundbarcodes = grep { !$exists{$_} } @contentlist;
262 elsif ( $filecontent eq 'itemid_file') {
263 @itemnumbers = Koha::Items->search({ itemnumber => \@contentlist })->get_column('itemnumber');
264 my %exists = map {$_=>1} @itemnumbers;
265 @notfounditemnumbers = grep { !$exists{$_} } @contentlist;
267 } else {
268 if (defined $biblionumber){
269 my @all_items = GetItemsInfo( $biblionumber );
270 foreach my $itm (@all_items) {
271 push @itemnumbers, $itm->{itemnumber};
274 if ( my $list=$input->param('barcodelist')){
275 push my @barcodelist, uniq( split(/\s\n/, $list) );
277 my $existing_items = Koha::Items->search({ barcode => \@barcodelist });
278 @itemnumbers = $existing_items->get_column('itemnumber');
279 my @barcodes = $existing_items->get_column('barcode');
280 my %exists = map {$_=>1} @barcodes;
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_display_items = $del
289 ? C4::Context->preference("MaxItemsToDisplayForBatchDel")
290 : C4::Context->preference("MaxItemsToDisplayForBatchMod");
291 $template->param("too_many_items_process" => scalar(@itemnumbers)) if !$del && scalar(@itemnumbers) >= C4::Context->preference("MaxItemsToProcessForBatchMod");
292 if (scalar(@itemnumbers) <= ( $max_display_items // 1000 ) ) {
293 $items_display_hashref=BuildItemsData(@itemnumbers);
294 } else {
295 $template->param("too_many_items_display" => scalar(@itemnumbers));
296 # Even if we do not display the items, we need the itemnumbers
297 $template->param(itemnumbers_array => \@itemnumbers);
299 # now, build the item form for entering a new item
300 my @loop_data =();
301 my $i=0;
302 my $branch_limit = C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
304 my $libraries = Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed;# build once ahead of time, instead of multiple times later.
306 # Adding a default choice, in case the user does not want to modify the branch
307 my $nochange_branch = { branchname => '', value => '', selected => 1 };
308 unshift (@$libraries, $nochange_branch);
310 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
312 # Getting list of subfields to keep when restricted batchmod edit is enabled
313 my $subfieldsToAllowForBatchmod = C4::Context->preference('SubfieldsToAllowForRestrictedBatchmod');
314 my $allowAllSubfields = (
315 not defined $subfieldsToAllowForBatchmod
316 or $subfieldsToAllowForBatchmod eq q||
317 ) ? 1 : 0;
318 my @subfieldsToAllow = split(/ /, $subfieldsToAllowForBatchmod);
320 foreach my $tag (sort keys %{$tagslib}) {
321 # loop through each subfield
322 foreach my $subfield (sort keys %{$tagslib->{$tag}}) {
323 next if IsMarcStructureInternal( $tagslib->{$tag}{$subfield} );
324 next if (not $allowAllSubfields and $restrictededition && !grep { $tag . '$' . $subfield eq $_ } @subfieldsToAllow );
325 next if ($tagslib->{$tag}->{$subfield}->{'tab'} ne "10");
326 # barcode and stocknumber are not meant to be batch-modified
327 next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.barcode';
328 next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.stocknumber';
329 my %subfield_data;
331 my $index_subfield = int(rand(1000000));
332 if ($subfield eq '@'){
333 $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
334 } else {
335 $subfield_data{id} = "tag_".$tag."_subfield_".$subfield."_".$index_subfield;
337 $subfield_data{tag} = $tag;
338 $subfield_data{subfield} = $subfield;
339 $subfield_data{marc_lib} ="<span id=\"error$i\" title=\"".$tagslib->{$tag}->{$subfield}->{lib}."\">".$tagslib->{$tag}->{$subfield}->{lib}."</span>";
340 $subfield_data{mandatory} = $tagslib->{$tag}->{$subfield}->{mandatory};
341 $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
342 my ($x,$value);
343 if ( $use_default_values) {
344 $value = $tagslib->{$tag}->{$subfield}->{defaultvalue};
345 # get today date & replace YYYY, MM, DD if provided in the default value
346 my $today = dt_from_string;
347 my $year = $today->year;
348 my $month = $today->month;
349 my $day = $today->day;
350 $value =~ s/YYYY/$year/g;
351 $value =~ s/MM/$month/g;
352 $value =~ s/DD/$day/g;
354 $subfield_data{visibility} = "display:none;" if (($tagslib->{$tag}->{$subfield}->{hidden} > 4) || ($tagslib->{$tag}->{$subfield}->{hidden} < -4));
355 # testing branch value if IndependentBranches.
357 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
358 my @authorised_values;
359 my %authorised_lib;
360 # builds list, depending on authorised value...
362 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "branches" ) {
363 foreach my $library (@$libraries) {
364 push @authorised_values, $library->{branchcode};
365 $authorised_lib{$library->{branchcode}} = $library->{branchname};
367 $value = "";
369 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
370 push @authorised_values, "";
371 my $itemtypes = Koha::ItemTypes->search_with_localization;
372 while ( my $itemtype = $itemtypes->next ) {
373 push @authorised_values, $itemtype->itemtype;
374 $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description;
376 $value = "";
378 #---- class_sources
380 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
381 push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
383 my $class_sources = GetClassSources();
384 my $default_source = C4::Context->preference("DefaultClassificationSource");
386 foreach my $class_source (sort keys %$class_sources) {
387 next unless $class_sources->{$class_source}->{'used'} or
388 ($value and $class_source eq $value) or
389 ($class_source eq $default_source);
390 push @authorised_values, $class_source;
391 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
393 $value = '';
395 #---- "true" authorised value
397 else {
398 push @authorised_values, ""; # unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
400 my @avs = Koha::AuthorisedValues->search({ category => $tagslib->{$tag}->{$subfield}->{authorised_value}, branchcode => $branch_limit },{order_by=>'lib'});
401 for my $av ( @avs ) {
402 push @authorised_values, $av->authorised_value;
403 $authorised_lib{$av->authorised_value} = $av->lib;
405 $value="";
407 $subfield_data{marc_value} = {
408 type => 'select',
409 id => "tag_".$tag."_subfield_".$subfield."_".$index_subfield,
410 name => "field_value",
411 values => \@authorised_values,
412 labels => \%authorised_lib,
413 default => $value,
415 # it's a thesaurus / authority field
417 elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode} ) {
418 $subfield_data{marc_value} = {
419 type => 'text1',
420 id => $subfield_data{id},
421 value => $value,
422 authtypecode => $tagslib->{$tag}->{$subfield}->{authtypecode},
425 elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) { # plugin
426 require Koha::FrameworkPlugin;
427 my $plugin = Koha::FrameworkPlugin->new( {
428 name => $tagslib->{$tag}->{$subfield}->{'value_builder'},
429 item_style => 1,
431 my $temp;
432 my $pars= { dbh => $dbh, record => $temp, tagslib => $tagslib,
433 id => $subfield_data{id}, tabloop => \@loop_data };
434 $plugin->build( $pars );
435 if( !$plugin->errstr ) {
436 $subfield_data{marc_value} = {
437 type => 'text2',
438 id => $subfield_data{id},
439 value => $value,
440 javascript => $plugin->javascript,
441 noclick => $plugin->noclick,
443 } else {
444 warn $plugin->errstr;
445 $subfield_data{marc_value} = { # supply default input form
446 type => 'text',
447 id => $subfield_data{id},
448 value => $value,
452 elsif ( $tag eq '' ) { # it's an hidden field
453 $subfield_data{marc_value} = {
454 type => 'hidden',
455 id => $subfield_data{id},
456 value => $value,
459 elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
460 $subfield_data{marc_value} = {
461 type => 'text',
462 id => $subfield_data{id},
463 value => $value,
466 elsif ( length($value) > 100
467 or (C4::Context->preference("marcflavour") eq "UNIMARC" and
468 300 <= $tag && $tag < 400 && $subfield eq 'a' )
469 or (C4::Context->preference("marcflavour") eq "MARC21" and
470 500 <= $tag && $tag < 600 )
472 # oversize field (textarea)
473 $subfield_data{marc_value} = {
474 type => 'textarea',
475 id => $subfield_data{id},
476 value => $value,
478 } else {
479 # it's a standard field
480 $subfield_data{marc_value} = {
481 type => 'text',
482 id => $subfield_data{id},
483 value => $value,
486 # $subfield_data{marc_value}="<input type=\"text\" name=\"field_value\">";
487 push (@loop_data, \%subfield_data);
488 $i++
490 } # -- End foreach tag
494 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
495 $template->param(
496 item => \@loop_data,
497 notfoundbarcodes => \@notfoundbarcodes,
498 notfounditemnumbers => \@notfounditemnumbers
500 $nextop="action"
501 } # -- End action="show"
503 $template->param(%$items_display_hashref) if $items_display_hashref;
504 $template->param(
505 op => $nextop,
507 $template->param( $op => 1 ) if $op;
509 if ($op eq "action") {
511 #my @not_deleted_loop = map{{itemnumber=>$_}}@not_deleted;
513 $template->param(
514 not_deleted_items => $not_deleted_items,
515 deleted_items => $deleted_items,
516 delete_records => $del_records,
517 deleted_records => $deleted_records,
518 not_deleted_loop => \@not_deleted
522 foreach my $error (@errors) {
523 $template->param($error => 1) if $error;
525 $template->param(src => $src);
526 $template->param(biblionumber => $biblionumber);
527 output_html_with_http_headers $input, $cookie, $template->output;
528 exit;
531 # ---------------- Functions
533 sub BuildItemsData{
534 my @itemnumbers=@_;
535 # now, build existiing item list
536 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
537 my @big_array;
538 #---- finds where items.itemnumber is stored
539 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
540 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField("items.homebranch", "");
541 foreach my $itemnumber (@itemnumbers){
542 my $itemdata = Koha::Items->find($itemnumber);
543 next unless $itemdata; # Should have been tested earlier, but just in case...
544 $itemdata = $itemdata->unblessed;
545 my $itemmarc=Item2Marc($itemdata);
546 my %this_row;
547 foreach my $field (grep {$_->tag() eq $itemtagfield} $itemmarc->fields()) {
548 # loop through each subfield
549 my $itembranchcode=$field->subfield($branchtagsubfield);
550 if ($itembranchcode && C4::Context->preference("IndependentBranches")) {
551 #verifying rights
552 my $userenv = C4::Context->userenv();
553 unless (C4::Context->IsSuperLibrarian() or (($userenv->{'branch'} eq $itembranchcode))){
554 $this_row{'nomod'}=1;
557 my $tag=$field->tag();
558 foreach my $subfield ($field->subfields) {
559 my ($subfcode,$subfvalue)=@$subfield;
560 next if ($tagslib->{$tag}->{$subfcode}->{tab} ne 10
561 && $tag ne $itemtagfield
562 && $subfcode ne $itemtagsubfield);
564 $witness{$subfcode} = $tagslib->{$tag}->{$subfcode}->{lib} if ($tagslib->{$tag}->{$subfcode}->{tab} eq 10);
565 if ($tagslib->{$tag}->{$subfcode}->{tab} eq 10) {
566 $this_row{$subfcode}=GetAuthorisedValueDesc( $tag,
567 $subfcode, $subfvalue, '', $tagslib)
568 || $subfvalue;
571 $this_row{itemnumber} = $subfvalue if ($tag eq $itemtagfield && $subfcode eq $itemtagsubfield);
575 # grab title, author, and ISBN to identify bib that the item
576 # belongs to in the display
577 my $biblio = Koha::Biblios->find( $itemdata->{biblionumber} );
578 $this_row{title} = $biblio->title;
579 $this_row{author} = $biblio->author;
580 $this_row{isbn} = $biblio->biblioitem->isbn;
581 $this_row{biblionumber} = $biblio->biblionumber;
582 $this_row{holds} = $biblio->holds->count;
583 $this_row{item_holds} = Koha::Holds->search( itemnumber => $itemnumber )->count;
585 if (%this_row) {
586 push(@big_array, \%this_row);
589 @big_array = sort {$a->{0} cmp $b->{0}} @big_array;
591 # now, construct template !
592 # First, the existing items for display
593 my @item_value_loop;
594 my @witnesscodessorted=sort keys %witness;
595 for my $row ( @big_array ) {
596 my %row_data;
597 my @item_fields = map +{ field => $_ || '' }, @$row{ @witnesscodessorted };
598 $row_data{item_value} = [ @item_fields ];
599 $row_data{itemnumber} = $row->{itemnumber};
600 #reporting this_row values
601 $row_data{'nomod'} = $row->{'nomod'};
602 $row_data{bibinfo} = $row->{bibinfo};
603 $row_data{author} = $row->{author};
604 $row_data{title} = $row->{title};
605 $row_data{isbn} = $row->{isbn};
606 $row_data{biblionumber} = $row->{biblionumber};
607 $row_data{holds} = $row->{holds};
608 $row_data{item_holds} = $row->{item_holds};
609 my $is_on_loan = C4::Circulation::IsItemIssued( $row->{itemnumber} );
610 $row_data{onloan} = $is_on_loan ? 1 : 0;
611 push(@item_value_loop,\%row_data);
613 my @header_loop=map { { header_value=> $witness{$_}} } @witnesscodessorted;
615 return { item_loop => \@item_value_loop, item_header_loop => \@header_loop };
618 #BE WARN : it is not the general case
619 # This function can be OK in the item marc record special case
620 # Where subfield is not repeated
621 # And where we are sure that field should correspond
622 # And $tag>10
623 sub UpdateMarcWith {
624 my ($marcfrom,$marcto)=@_;
625 my ( $itemtag, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
626 my $fieldfrom=$marcfrom->field($itemtag);
627 my @fields_to=$marcto->field($itemtag);
628 my $modified = 0;
629 foreach my $subfield ( $fieldfrom->subfields() ) {
630 foreach my $field_to_update ( @fields_to ) {
631 if ( $subfield->[1] ) {
632 unless ( $field_to_update->subfield($subfield->[0]) eq $subfield->[1] ) {
633 $modified++;
634 $field_to_update->update( $subfield->[0] => $subfield->[1] );
637 else {
638 $modified++;
639 $field_to_update->delete_subfield( code => $subfield->[0] );
643 return $modified;
646 sub find_value {
647 my ($tagfield,$insubfield,$record) = @_;
648 my $result;
649 my $indicator;
650 foreach my $field ($record->field($tagfield)) {
651 my @subfields = $field->subfields();
652 foreach my $subfield (@subfields) {
653 if (@$subfield[0] eq $insubfield) {
654 $result .= @$subfield[1];
655 $indicator = $field->indicator(1).$field->indicator(2);
659 return($indicator,$result);
662 # ----------------------------
663 # Background functions
666 sub add_results_to_template {
667 my $template = shift;
668 my $results = shift;
669 $template->param(map { $_ => $results->{$_} } keys %{ $results });
672 sub add_saved_job_results_to_template {
673 my $template = shift;
674 my $completedJobID = shift;
675 my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
676 my $results = $job->results();
677 add_results_to_template($template, $results);
679 my $fields = $job->get("modified_fields");
680 my $items = $job->get("modified_items");
681 $template->param(
682 modified_items => $items,
683 modified_fields => $fields,
687 sub put_in_background {
688 my $job_size = shift;
690 my $job = C4::BackgroundJob->new($sessionID, "test", '/cgi-bin/koha/tools/batchMod.pl', $job_size);
691 my $jobID = $job->id();
693 # fork off
694 if (my $pid = fork) {
695 # parent
696 # return job ID as JSON
698 # prevent parent exiting from
699 # destroying the kid's database handle
700 # FIXME: according to DBI doc, this may not work for Oracle
701 $dbh->{InactiveDestroy} = 1;
703 my $reply = CGI->new("");
704 print $reply->header(-type => 'text/html');
705 print '{"jobID":"' . $jobID . '"}';
706 exit 0;
707 } elsif (defined $pid) {
708 # child
709 # close STDOUT to signal to Apache that
710 # we're now running in the background
711 close STDOUT;
712 close STDERR;
713 } else {
714 # fork failed, so exit immediately
715 warn "fork failed while attempting to run tools/batchMod.pl as a background job";
716 exit 0;
718 return $job;