Bug 9509 - batchMod.pl does not ensure each barcode is unique
[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 under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 2 of the License, or (at your option) any later
11 # version.
12 #
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License along
18 # with Koha; if not, write to the Free Software Foundation, Inc.,
19 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20
21 use CGI;
22 use strict;
23 #use warnings; FIXME - Bug 2505
24 use C4::Auth;
25 use C4::Output;
26 use C4::Biblio;
27 use C4::Items;
28 use C4::Circulation;
29 use C4::Context;
30 use C4::Koha; # XXX subfield_is_koha_internal_p
31 use C4::Branch; # XXX subfield_is_koha_internal_p
32 use C4::BackgroundJob;
33 use C4::ClassSource;
34 use C4::Dates;
35 use C4::Debug;
36 use MARC::File::XML;
37 use List::MoreUtils qw/uniq/;
38
39 my $input = new CGI;
40 my $dbh = C4::Context->dbh;
41 my $error        = $input->param('error');
42 my @itemnumbers  = $input->param('itemnumber');
43 my $biblionumber = $input->param('biblionumber');
44 my $op           = $input->param('op');
45 my $del          = $input->param('del');
46 my $del_records  = $input->param('del_records');
47 my $completedJobID = $input->param('completedJobID');
48 my $runinbackground = $input->param('runinbackground');
49 my $src          = $input->param('src');
50
51
52 my $template_name;
53 my $template_flag;
54 if (!defined $op) {
55     $template_name = "tools/batchMod.tmpl";
56     $template_flag = { tools => '*' };
57     $op = q{};
58 } else {
59     $template_name = ($del) ? "tools/batchMod-del.tmpl" : "tools/batchMod-edit.tmpl";
60     $template_flag = ($del) ? { tools => 'items_batchdel' }   : { tools => 'items_batchmod' };
61 }
62
63
64 my ($template, $loggedinuser, $cookie)
65     = get_template_and_user({template_name => $template_name,
66                  query => $input,
67                  type => "intranet",
68                  authnotrequired => 0,
69                  flagsrequired => $template_flag,
70                  });
71
72
73 my $today_iso = C4::Dates->today('iso');
74 $template->param(today_iso => $today_iso);
75 $template->param(del       => $del);
76
77 my $itemrecord;
78 my $nextop="";
79 my @errors; # store errors found while checking data BEFORE saving item.
80 my $items_display_hashref;
81 my $frameworkcode="";
82 my $tagslib = &GetMarcStructure(1,$frameworkcode);
83
84 my $deleted_items = 0;     # Number of deleted items
85 my $deleted_records = 0;   # Number of deleted records ( with no items attached )
86 my $not_deleted_items = 0; # Number of items that could not be deleted
87 my @not_deleted;           # List of the itemnumbers that could not be deleted
88
89 my %cookies = parse CGI::Cookie($cookie);
90 my $sessionID = $cookies{'CGISESSID'}->value;
91
92
93 #--- ----------------------------------------------------------------------------
94 if ($op eq "action") {
95 #-------------------------------------------------------------------------------
96     my @tags      = $input->param('tag');
97     my @subfields = $input->param('subfield');
98     my @values    = $input->param('field_value');
99     my @disabled  = $input->param('disable_input');
100     # build indicator hash.
101     my @ind_tag   = $input->param('ind_tag');
102     my @indicator = $input->param('indicator');
103
104     # Is there something to modify ?
105     # TODO : We shall use this var to warn the user in case no modification was done to the items
106     my $values_to_modify = scalar(grep {!/^$/} @values);
107     my $values_to_blank  = scalar(@disabled);
108     my $marcitem;
109
110     # Once the job is done
111     if ($completedJobID) {
112         # If we have a reasonable amount of items, we display them
113         if (scalar(@itemnumbers) <= 1000) {
114             $items_display_hashref=BuildItemsData(@itemnumbers);
115         } else {
116             # Else, we only display the barcode
117             my @simple_items_display = map {{ itemnumber => $_, barcode => (GetBarcodeFromItemnumber($_) or ""), biblionumber => (GetBiblionumberFromItemnumber($_) or "") }} @itemnumbers;
118             $template->param("simple_items_display" => \@simple_items_display);
119         }
120
121         # Setting the job as done
122         my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
123
124         # Calling the template
125         add_saved_job_results_to_template($template, $completedJobID);
126
127     } else {
128     # While the job is getting done
129
130         # Job size is the number of items we have to process
131         my $job_size = scalar(@itemnumbers);
132         my $job = undef;
133
134         # If we asked for background processing
135         if ($runinbackground) {
136             $job = put_in_background($job_size);
137         }
138
139         #initializing values for updates
140         my (  $itemtagfield,   $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
141         if ($values_to_modify){
142             my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
143         utf8::encode($xml);
144             $marcitem = MARC::Record::new_from_xml($xml, 'UTF-8');
145         }
146         if ($values_to_blank){
147             foreach my $disabledsubf (@disabled){
148                 if ($marcitem && $marcitem->field($itemtagfield)){
149                     $marcitem->field($itemtagfield)->update( $disabledsubf => "" );
150                 }
151                 else {
152                     $marcitem = MARC::Record->new();
153                     $marcitem->append_fields( MARC::Field->new( $itemtagfield, '', '', $disabledsubf => "" ) );
154                 }
155             }
156         }
157
158         # For each item
159         my $i = 1; 
160         foreach my $itemnumber(@itemnumbers){
161
162                 $job->progress($i) if $runinbackground;
163                 my $itemdata = GetItem($itemnumber);
164                 if ($input->param("del")){
165                         my $return = DelItemCheck(C4::Context->dbh, $itemdata->{'biblionumber'}, $itemdata->{'itemnumber'});
166                         if ($return == 1) {
167                             $deleted_items++;
168                         } else {
169                             $not_deleted_items++;
170                             push @not_deleted,
171                                 { biblionumber => $itemdata->{'biblionumber'},
172                                   itemnumber => $itemdata->{'itemnumber'},
173                                   barcode => $itemdata->{'barcode'},
174                                   title => $itemdata->{'title'},
175                                   $return => 1
176                                 };
177                         }
178
179                         # If there are no items left, delete the biblio
180                         if ( $del_records ) {
181                             my $itemscount = GetItemsCount($itemdata->{'biblionumber'});
182                             if ( $itemscount == 0 ) {
183                                 my $error = DelBiblio($itemdata->{'biblionumber'});
184                                 $deleted_records++ unless ( $error );
185                             }
186                         }
187                 } else {
188                     if ($values_to_modify || $values_to_blank) {
189                         my $localmarcitem = Item2Marc($itemdata);
190                         UpdateMarcWith( $marcitem, $localmarcitem );
191                         eval{
192                             if ( my $item = ModItemFromMarc( $localmarcitem, $itemdata->{biblionumber}, $itemnumber ) ) {
193                                 LostItem($itemnumber, 'MARK RETURNED', 'CHARGE FEE') if $item->{itemlost};
194                             }
195                         };
196                     }
197                 }
198                 $i++;
199         }
200     }
201 }
202 #
203 #-------------------------------------------------------------------------------
204 # build screen with existing items. and "new" one
205 #-------------------------------------------------------------------------------
206
207 if ($op eq "show"){
208     my $filefh = $input->upload('uploadfile');
209     my $filecontent = $input->param('filecontent');
210     my @notfoundbarcodes;
211
212     my @contentlist;
213     if ($filefh){
214         while (my $content=<$filefh>){
215             $content =~ s/[\r\n]*$//;
216             push @contentlist, $content if $content;
217         }
218
219         if ($filecontent eq 'barcode_file') {
220             foreach my $barcode (@contentlist) {
221
222                 my $itemnumber = GetItemnumberFromBarcode($barcode);
223                 if ($itemnumber) {
224                     push @itemnumbers,$itemnumber;
225                 } else {
226                     push @notfoundbarcodes, $barcode;
227                 }
228             }
229         }
230         elsif ( $filecontent eq 'itemid_file') {
231             @itemnumbers = @contentlist;
232         }
233     } else {
234         if (defined $biblionumber){
235             my @all_items = GetItemsInfo( $biblionumber );
236             foreach my $itm (@all_items) {
237                 push @itemnumbers, $itm->{itemnumber};
238             }
239         }
240         if ( my $list=$input->param('barcodelist')){
241             push my @barcodelist, uniq( split(/\s\n/, $list) );
242
243             foreach my $barcode (@barcodelist) {
244
245                 my $itemnumber = GetItemnumberFromBarcode($barcode);
246                 if ($itemnumber) {
247                     push @itemnumbers,$itemnumber;
248                 } else {
249                     push @notfoundbarcodes, $barcode;
250                 }
251             }
252
253         }
254     }
255
256     # Flag to tell the template there are valid results, hidden or not
257     if(scalar(@itemnumbers) > 0){ $template->param("itemresults" => 1); }
258     # Only display the items if there are no more than 1000
259     if (scalar(@itemnumbers) <= 1000) {
260         $items_display_hashref=BuildItemsData(@itemnumbers);
261     } else {
262         $template->param("too_many_items" => scalar(@itemnumbers));
263         # Even if we do not display the items, we need the itemnumbers
264         my @itemnumbers_hashref = map {{itemnumber => $_}} @itemnumbers;
265         $template->param("itemnumbers_hashref" => \@itemnumbers_hashref);
266     }
267 # now, build the item form for entering a new item
268 my @loop_data =();
269 my $i=0;
270 my $branch_limit = C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
271 my $query = qq{SELECT authorised_value, lib FROM authorised_values};
272 $query  .= qq{ LEFT JOIN authorised_values_branches ON ( id = av_id ) } if $branch_limit;
273 $query  .= qq{ WHERE category = ?};
274 $query  .= qq{ AND ( branchcode = ? OR branchcode IS NULL ) } if $branch_limit;
275 $query  .= qq{ GROUP BY lib ORDER BY lib, lib_opac};
276 my $authorised_values_sth = $dbh->prepare( $query );
277
278 my $branches = GetBranchesLoop();  # build once ahead of time, instead of multiple times later.
279
280 # Adding a default choice, in case the user does not want to modify the branch
281 my $nochange_branch = { branchname => '', value => '', selected => 1 };
282 unshift (@$branches, $nochange_branch);
283
284 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
285
286
287 foreach my $tag (sort keys %{$tagslib}) {
288     # loop through each subfield
289     foreach my $subfield (sort keys %{$tagslib->{$tag}}) {
290         next if subfield_is_koha_internal_p($subfield);
291         next if ($tagslib->{$tag}->{$subfield}->{'tab'} ne "10");
292         # barcode and stocknumber are not meant to be batch-modified
293         next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.barcode';
294         next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.stocknumber';
295         my %subfield_data;
296  
297         my $index_subfield = int(rand(1000000)); 
298         if ($subfield eq '@'){
299             $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
300         } else {
301             $subfield_data{id} = "tag_".$tag."_subfield_".$subfield."_".$index_subfield;
302         }
303         $subfield_data{tag}        = $tag;
304         $subfield_data{subfield}   = $subfield;
305         $subfield_data{random}     = int(rand(1000000));    # why do we need 2 different randoms?
306     #   $subfield_data{marc_lib}   = $tagslib->{$tag}->{$subfield}->{lib};
307         $subfield_data{marc_lib}   ="<span id=\"error$i\" title=\"".$tagslib->{$tag}->{$subfield}->{lib}."\">".$tagslib->{$tag}->{$subfield}->{lib}."</span>";
308         $subfield_data{mandatory}  = $tagslib->{$tag}->{$subfield}->{mandatory};
309         $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
310         my ($x,$value);
311         $value =~ s/"/&quot;/g;
312         unless ($value) {
313             $value = $tagslib->{$tag}->{$subfield}->{defaultvalue};
314             # get today date & replace YYYY, MM, DD if provided in the default value
315             my ( $year, $month, $day ) = split ',', $today_iso;     # FIXME: iso dates don't have commas!
316             $value =~ s/YYYY/$year/g;
317             $value =~ s/MM/$month/g;
318             $value =~ s/DD/$day/g;
319         }
320         $subfield_data{visibility} = "display:none;" if (($tagslib->{$tag}->{$subfield}->{hidden} > 4) || ($tagslib->{$tag}->{$subfield}->{hidden} < -4));
321         # testing branch value if IndependantBranches.
322
323         my $attributes_no_value = qq(tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="255" );
324         my $attributes          = qq($attributes_no_value value="$value" );
325
326         if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
327         my @authorised_values;
328         my %authorised_lib;
329         # builds list, depending on authorised value...
330   
331         if ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "branches" ) {
332             foreach my $thisbranch (@$branches) {
333                 push @authorised_values, $thisbranch->{value};
334                 $authorised_lib{$thisbranch->{value}} = $thisbranch->{branchname};
335             }
336         $value = "";
337         }
338         elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
339             push @authorised_values, "";
340             my $sth = $dbh->prepare("select itemtype,description from itemtypes order by description");
341             $sth->execute;
342             while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
343                 push @authorised_values, $itemtype;
344                 $authorised_lib{$itemtype} = $description;
345             }
346         $value = "";
347
348           #---- class_sources
349       }
350       elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
351           push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
352             
353           my $class_sources = GetClassSources();
354           my $default_source = C4::Context->preference("DefaultClassificationSource");
355           
356           foreach my $class_source (sort keys %$class_sources) {
357               next unless $class_sources->{$class_source}->{'used'} or
358                           ($value and $class_source eq $value)      or
359                           ($class_source eq $default_source);
360               push @authorised_values, $class_source;
361               $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
362           }
363                   $value = '';
364
365           #---- "true" authorised value
366       }
367       else {
368           push @authorised_values, ""; # unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
369           $authorised_values_sth->execute( $tagslib->{$tag}->{$subfield}->{authorised_value}, $branch_limit ? $branch_limit : () );
370           while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
371               push @authorised_values, $value;
372               $authorised_lib{$value} = $lib;
373           }
374           $value="";
375       }
376       $subfield_data{marc_value} =CGI::scrolling_list(      # FIXME: factor out scrolling_list
377           -name     => "field_value",
378           -values   => \@authorised_values,
379           -default  => $value,
380           -labels   => \%authorised_lib,
381           -override => 1,
382           -size     => 1,
383           -multiple => 0,
384           -tabindex => 1,
385           -id       => "tag_".$tag."_subfield_".$subfield."_".$index_subfield,
386           -class    => "input_marceditor",
387       );
388     # it's a thesaurus / authority field
389     }
390     elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode} ) {
391         $subfield_data{marc_value} = "<input type=\"text\" $attributes />
392             <a href=\"#\" class=\"buttonDot\"
393                 onclick=\"Dopop('/cgi-bin/koha/authorities/auth_finder.pl?authtypecode=".$tagslib->{$tag}->{$subfield}->{authtypecode}."&index=$subfield_data{id}','$subfield_data{id}'); return false;\" title=\"Tag Editor\">...</a>
394     ";
395     # it's a plugin field
396     }
397     elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) {
398         # opening plugin
399         my $plugin = C4::Context->intranetdir . "/cataloguing/value_builder/" . $tagslib->{$tag}->{$subfield}->{'value_builder'};
400         if (do $plugin) {
401                         my $temp;
402             my $extended_param = plugin_parameters( $dbh, $temp, $tagslib, $subfield_data{id}, \@loop_data );
403             my ( $function_name, $javascript ) = plugin_javascript( $dbh, $temp, $tagslib, $subfield_data{id}, \@loop_data );
404             $subfield_data{marc_value} = qq[<input type="text" $attributes
405                 onfocus="Focus$function_name($subfield_data{random}, '$subfield_data{id}');"
406                  onblur=" Blur$function_name($subfield_data{random}, '$subfield_data{id}');" />
407                 <a href="#" class="buttonDot" onclick="Clic$function_name('$subfield_data{id}'); return false;" title="Tag Editor">...</a>
408                 $javascript];
409         } else {
410             warn "Plugin Failed: $plugin";
411             $subfield_data{marc_value} = "<input type=\"text\" $attributes />"; # supply default input form
412         }
413     }
414     elsif ( $tag eq '' ) {       # it's an hidden field
415         $subfield_data{marc_value} = qq(<input type="hidden" $attributes />);
416     }
417     elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) {   # FIXME: shouldn't input type be "hidden" ?
418         $subfield_data{marc_value} = qq(<input type="text" $attributes />);
419     }
420     elsif ( length($value) > 100
421             or (C4::Context->preference("marcflavour") eq "UNIMARC" and
422                   300 <= $tag && $tag < 400 && $subfield eq 'a' )
423             or (C4::Context->preference("marcflavour") eq "MARC21"  and
424                   500 <= $tag && $tag < 600                     )
425           ) {
426         # oversize field (textarea)
427         $subfield_data{marc_value} = "<textarea $attributes_no_value>$value</textarea>\n";
428     } else {
429         # it's a standard field
430          $subfield_data{marc_value} = "<input type=\"text\" $attributes />";
431     }
432 #   $subfield_data{marc_value}="<input type=\"text\" name=\"field_value\">";
433     push (@loop_data, \%subfield_data);
434     $i++
435   }
436 } # -- End foreach tag
437 $authorised_values_sth->finish;
438
439
440
441     # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
442     $template->param(item => \@loop_data);
443     if (@notfoundbarcodes) { 
444         my @notfoundbarcodesloop = map{{barcode=>$_}}@notfoundbarcodes;
445         $template->param(notfoundbarcodes => \@notfoundbarcodesloop);
446     }
447     $nextop="action"
448 } # -- End action="show"
449
450 $template->param(%$items_display_hashref) if $items_display_hashref;
451 $template->param(
452     op      => $nextop,
453 );
454 $template->param( $op => 1 ) if $op;
455
456 if ($op eq "action") {
457
458     #my @not_deleted_loop = map{{itemnumber=>$_}}@not_deleted;
459
460     $template->param(
461         not_deleted_items => $not_deleted_items,
462         deleted_items => $deleted_items,
463         delete_records => $del_records,
464         deleted_records => $deleted_records,
465         not_deleted_loop => \@not_deleted 
466     );
467 }
468
469 foreach my $error (@errors) {
470     $template->param($error => 1) if $error;
471 }
472 $template->param(src => $src);
473 $template->param(biblionumber => $biblionumber);
474 output_html_with_http_headers $input, $cookie, $template->output;
475 exit;
476
477
478 # ---------------- Functions
479
480 sub BuildItemsData{
481         my @itemnumbers=@_;
482                 # now, build existiing item list
483                 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
484                 my @big_array;
485                 #---- finds where items.itemnumber is stored
486                 my (  $itemtagfield,   $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
487                 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField("items.homebranch", "");
488                 foreach my $itemnumber (@itemnumbers){
489                         my $itemdata=GetItem($itemnumber);
490                         my $itemmarc=Item2Marc($itemdata);
491                         my %this_row;
492                         foreach my $field (grep {$_->tag() eq $itemtagfield} $itemmarc->fields()) {
493                                 # loop through each subfield
494                                 my $itembranchcode=$field->subfield($branchtagsubfield);
495                                 if ($itembranchcode && C4::Context->preference("IndependantBranches")) {
496                                                 #verifying rights
497                                                 my $userenv = C4::Context->userenv();
498                                                 unless (($userenv->{'flags'} == 1) or (($userenv->{'branch'} eq $itembranchcode))){
499                                                                 $this_row{'nomod'}=1;
500                                                 }
501                                 }
502                                 my $tag=$field->tag();
503                                 foreach my $subfield ($field->subfields) {
504                                         my ($subfcode,$subfvalue)=@$subfield;
505                                         next if ($tagslib->{$tag}->{$subfcode}->{tab} ne 10 
506                                                         && $tag        ne $itemtagfield 
507                                                         && $subfcode   ne $itemtagsubfield);
508
509                                         $witness{$subfcode} = $tagslib->{$tag}->{$subfcode}->{lib} if ($tagslib->{$tag}->{$subfcode}->{tab}  eq 10);
510                                         if ($tagslib->{$tag}->{$subfcode}->{tab}  eq 10) {
511                                                 $this_row{$subfcode}=GetAuthorisedValueDesc( $tag,
512                                                                         $subfcode, $subfvalue, '', $tagslib) 
513                                                                         || $subfvalue;
514                                         }
515
516                                         $this_row{itemnumber} = $subfvalue if ($tag eq $itemtagfield && $subfcode eq $itemtagsubfield);
517                                 }
518                         }
519
520             # grab title, author, and ISBN to identify bib that the item
521             # belongs to in the display
522                          my $biblio=GetBiblioData($$itemdata{biblionumber});
523             $this_row{title} = $biblio->{title};
524             $this_row{author} = $biblio->{author};
525             $this_row{isbn} = $biblio->{isbn};
526             $this_row{biblionumber} = $biblio->{biblionumber};
527
528                         if (%this_row) {
529                                 push(@big_array, \%this_row);
530                         }
531                 }
532                 @big_array = sort {$a->{0} cmp $b->{0}} @big_array;
533
534                 # now, construct template !
535                 # First, the existing items for display
536                 my @item_value_loop;
537                 my @witnesscodessorted=sort keys %witness;
538                 for my $row ( @big_array ) {
539                         my %row_data;
540                         my @item_fields = map +{ field => $_ || '' }, @$row{ @witnesscodessorted };
541                         $row_data{item_value} = [ @item_fields ];
542                         $row_data{itemnumber} = $row->{itemnumber};
543                         #reporting this_row values
544                         $row_data{'nomod'} = $row->{'nomod'};
545       $row_data{bibinfo} = $row->{bibinfo};
546       $row_data{author} = $row->{author};
547       $row_data{title} = $row->{title};
548       $row_data{isbn} = $row->{isbn};
549       $row_data{biblionumber} = $row->{biblionumber};
550                         push(@item_value_loop,\%row_data);
551                 }
552                 my @header_loop=map { { header_value=> $witness{$_}} } @witnesscodessorted;
553
554         return { item_loop        => \@item_value_loop, item_header_loop => \@header_loop };
555 }
556
557 #BE WARN : it is not the general case 
558 # This function can be OK in the item marc record special case
559 # Where subfield is not repeated
560 # And where we are sure that field should correspond
561 # And $tag>10
562 sub UpdateMarcWith {
563   my ($marcfrom,$marcto)=@_;
564   #warn "FROM :",$marcfrom->as_formatted;
565         my (  $itemtag,   $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
566         my $fieldfrom=$marcfrom->field($itemtag);
567         my @fields_to=$marcto->field($itemtag);
568     foreach my $subfield ($fieldfrom->subfields()){
569                 foreach my $field_to_update (@fields_to){
570                     if ($subfield->[1]){
571                         $field_to_update->update($subfield->[0]=>$subfield->[1]);
572                     }
573                     else {
574                         $field_to_update->delete_subfield(code=> $subfield->[0]);
575                     }
576                 }
577     }
578   #warn "TO edited:",$marcto->as_formatted;
579 }
580
581 sub find_value {
582     my ($tagfield,$insubfield,$record) = @_;
583     my $result;
584     my $indicator;
585     foreach my $field ($record->field($tagfield)) {
586         my @subfields = $field->subfields();
587         foreach my $subfield (@subfields) {
588             if (@$subfield[0] eq $insubfield) {
589                 $result .= @$subfield[1];
590                 $indicator = $field->indicator(1).$field->indicator(2);
591             }
592         }
593     }
594     return($indicator,$result);
595 }
596
597 # ----------------------------
598 # Background functions
599
600
601 sub add_results_to_template {
602     my $template = shift;
603     my $results = shift;
604     $template->param(map { $_ => $results->{$_} } keys %{ $results });
605 }
606
607 sub add_saved_job_results_to_template {
608     my $template = shift;
609     my $completedJobID = shift;
610     my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
611     my $results = $job->results();
612     add_results_to_template($template, $results);
613 }
614
615 sub put_in_background {
616     my $job_size = shift;
617
618     my $job = C4::BackgroundJob->new($sessionID, "test", $ENV{'SCRIPT_NAME'}, $job_size);
619     my $jobID = $job->id();
620
621     # fork off
622     if (my $pid = fork) {
623         # parent
624         # return job ID as JSON
625
626         # prevent parent exiting from
627         # destroying the kid's database handle
628         # FIXME: according to DBI doc, this may not work for Oracle
629         $dbh->{InactiveDestroy}  = 1;
630
631         my $reply = CGI->new("");
632         print $reply->header(-type => 'text/html');
633         print '{"jobID":"' . $jobID . '"}';
634         exit 0;
635     } elsif (defined $pid) {
636         # child
637         # close STDOUT to signal to Apache that
638         # we're now running in the background
639         close STDOUT;
640         close STDERR;
641     } else {
642         # fork failed, so exit immediately
643         warn "fork failed while attempting to run $ENV{'SCRIPT_NAME'} as a background job";
644         exit 0;
645     }
646     return $job;
647 }
648
649
650