Bug 12740: Make the error message translatable
[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 my $use_default_values = $input->param('use_default_values');
51
52 my $template_name;
53 my $template_flag;
54 if (!defined $op) {
55     $template_name = "tools/batchMod.tt";
56     $template_flag = { tools => '*' };
57     $op = q{};
58 } else {
59     $template_name = ($del) ? "tools/batchMod-del.tt" : "tools/batchMod-edit.tt";
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 $tagslib = &GetMarcStructure(1);
82
83 my $deleted_items = 0;     # Number of deleted items
84 my $deleted_records = 0;   # Number of deleted records ( with no items attached )
85 my $not_deleted_items = 0; # Number of items that could not be deleted
86 my @not_deleted;           # List of the itemnumbers that could not be deleted
87 my $modified_items = 0;    # Numbers of modified items
88 my $modified_fields = 0;   # Numbers of modified fields
89
90 my %cookies = parse CGI::Cookie($cookie);
91 my $sessionID = $cookies{'CGISESSID'}->value;
92
93
94 #--- ----------------------------------------------------------------------------
95 if ($op eq "action") {
96 #-------------------------------------------------------------------------------
97     my @tags      = $input->param('tag');
98     my @subfields = $input->param('subfield');
99     my @values    = $input->param('field_value');
100     my @disabled  = $input->param('disable_input');
101     # build indicator hash.
102     my @ind_tag   = $input->param('ind_tag');
103     my @indicator = $input->param('indicator');
104
105     # Is there something to modify ?
106     # TODO : We shall use this var to warn the user in case no modification was done to the items
107     my $values_to_modify = scalar(grep {!/^$/} @values);
108     my $values_to_blank  = scalar(@disabled);
109     my $marcitem;
110
111     # Once the job is done
112     if ($completedJobID) {
113         # If we have a reasonable amount of items, we display them
114     if (scalar(@itemnumbers) <= ( C4::Context->preference("MaxItemsForBatch") // 1000 ) ) {
115             $items_display_hashref=BuildItemsData(@itemnumbers);
116         } else {
117             # Else, we only display the barcode
118             my @simple_items_display = map {{ itemnumber => $_, barcode => (GetBarcodeFromItemnumber($_) or ""), biblionumber => (GetBiblionumberFromItemnumber($_) or "") }} @itemnumbers;
119             $template->param("simple_items_display" => \@simple_items_display);
120         }
121
122         # Setting the job as done
123         my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
124
125         # Calling the template
126         add_saved_job_results_to_template($template, $completedJobID);
127
128     } else {
129     # While the job is getting done
130
131         # Job size is the number of items we have to process
132         my $job_size = scalar(@itemnumbers);
133         my $job = undef;
134
135         # If we asked for background processing
136         if ($runinbackground) {
137             $job = put_in_background($job_size);
138         }
139
140         #initializing values for updates
141         my (  $itemtagfield,   $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
142         if ($values_to_modify){
143             my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
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 ( $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
191                 my $modified = UpdateMarcWith( $marcitem, $localmarcitem );
192                 if ( $modified ) {
193                     eval {
194                         if ( my $item = ModItemFromMarc( $localmarcitem, $itemdata->{biblionumber}, $itemnumber ) ) {
195                             LostItem($itemnumber, 'MARK RETURNED') if $item->{itemlost};
196                         }
197                     };
198                 }
199                 if ( $runinbackground ) {
200                     $modified_items++ if $modified;
201                     $modified_fields += $modified;
202                     $job->set({
203                         modified_items  => $modified_items,
204                         modified_fields => $modified_fields,
205                     });
206                 }
207                     }
208                 }
209                 $i++;
210         }
211     }
212 }
213 #
214 #-------------------------------------------------------------------------------
215 # build screen with existing items. and "new" one
216 #-------------------------------------------------------------------------------
217
218 if ($op eq "show"){
219     my $filefh = $input->upload('uploadfile');
220     my $filecontent = $input->param('filecontent');
221     my @notfoundbarcodes;
222
223     my @contentlist;
224     if ($filefh){
225         while (my $content=<$filefh>){
226             $content =~ s/[\r\n]*$//;
227             push @contentlist, $content if $content;
228         }
229
230         if ($filecontent eq 'barcode_file') {
231             foreach my $barcode (@contentlist) {
232
233                 my $itemnumber = GetItemnumberFromBarcode($barcode);
234                 if ($itemnumber) {
235                     push @itemnumbers,$itemnumber;
236                 } else {
237                     push @notfoundbarcodes, $barcode;
238                 }
239             }
240         }
241         elsif ( $filecontent eq 'itemid_file') {
242             @itemnumbers = @contentlist;
243         }
244     } else {
245         if (defined $biblionumber){
246             my @all_items = GetItemsInfo( $biblionumber );
247             foreach my $itm (@all_items) {
248                 push @itemnumbers, $itm->{itemnumber};
249             }
250         }
251         if ( my $list=$input->param('barcodelist')){
252             push my @barcodelist, uniq( split(/\s\n/, $list) );
253
254             foreach my $barcode (@barcodelist) {
255
256                 my $itemnumber = GetItemnumberFromBarcode($barcode);
257                 if ($itemnumber) {
258                     push @itemnumbers,$itemnumber;
259                 } else {
260                     push @notfoundbarcodes, $barcode;
261                 }
262             }
263
264         }
265     }
266
267     # Flag to tell the template there are valid results, hidden or not
268     if(scalar(@itemnumbers) > 0){ $template->param("itemresults" => 1); }
269     # Only display the items if there are no more than pref MaxItemsForBatch
270     if (scalar(@itemnumbers) <= ( C4::Context->preference("MaxItemsForBatch") // 1000 ) ) {
271         $items_display_hashref=BuildItemsData(@itemnumbers);
272     } else {
273         $template->param("too_many_items" => scalar(@itemnumbers));
274         # Even if we do not display the items, we need the itemnumbers
275         $template->param(itemnumbers_array => \@itemnumbers);
276     }
277 # now, build the item form for entering a new item
278 my @loop_data =();
279 my $i=0;
280 my $branch_limit = C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
281 my $query = qq{SELECT authorised_value, lib FROM authorised_values};
282 $query  .= qq{ LEFT JOIN authorised_values_branches ON ( id = av_id ) } if $branch_limit;
283 $query  .= qq{ WHERE category = ?};
284 $query  .= qq{ AND ( branchcode = ? OR branchcode IS NULL ) } if $branch_limit;
285 $query  .= qq{ GROUP BY lib ORDER BY lib, lib_opac};
286 my $authorised_values_sth = $dbh->prepare( $query );
287
288 my $branches = GetBranchesLoop();  # build once ahead of time, instead of multiple times later.
289
290 # Adding a default choice, in case the user does not want to modify the branch
291 my $nochange_branch = { branchname => '', value => '', selected => 1 };
292 unshift (@$branches, $nochange_branch);
293
294 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
295
296
297 foreach my $tag (sort keys %{$tagslib}) {
298     # loop through each subfield
299     foreach my $subfield (sort keys %{$tagslib->{$tag}}) {
300         next if subfield_is_koha_internal_p($subfield);
301         next if ($tagslib->{$tag}->{$subfield}->{'tab'} ne "10");
302         # barcode and stocknumber are not meant to be batch-modified
303         next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.barcode';
304         next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.stocknumber';
305         my %subfield_data;
306  
307         my $index_subfield = int(rand(1000000)); 
308         if ($subfield eq '@'){
309             $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
310         } else {
311             $subfield_data{id} = "tag_".$tag."_subfield_".$subfield."_".$index_subfield;
312         }
313         $subfield_data{tag}        = $tag;
314         $subfield_data{subfield}   = $subfield;
315         $subfield_data{random}     = int(rand(1000000));    # why do we need 2 different randoms?
316     #   $subfield_data{marc_lib}   = $tagslib->{$tag}->{$subfield}->{lib};
317         $subfield_data{marc_lib}   ="<span id=\"error$i\" title=\"".$tagslib->{$tag}->{$subfield}->{lib}."\">".$tagslib->{$tag}->{$subfield}->{lib}."</span>";
318         $subfield_data{mandatory}  = $tagslib->{$tag}->{$subfield}->{mandatory};
319         $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
320         my ($x,$value);
321         $value =~ s/"/&quot;/g;
322    if ( !$value && $use_default_values) {
323             $value = $tagslib->{$tag}->{$subfield}->{defaultvalue};
324             # get today date & replace YYYY, MM, DD if provided in the default value
325             my ( $year, $month, $day ) = split ',', $today_iso;     # FIXME: iso dates don't have commas!
326             $value =~ s/YYYY/$year/g;
327             $value =~ s/MM/$month/g;
328             $value =~ s/DD/$day/g;
329         }
330         $subfield_data{visibility} = "display:none;" if (($tagslib->{$tag}->{$subfield}->{hidden} > 4) || ($tagslib->{$tag}->{$subfield}->{hidden} < -4));
331     # testing branch value if IndependentBranches.
332
333         if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
334         my @authorised_values;
335         my %authorised_lib;
336         # builds list, depending on authorised value...
337   
338         if ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "branches" ) {
339             foreach my $thisbranch (@$branches) {
340                 push @authorised_values, $thisbranch->{value};
341                 $authorised_lib{$thisbranch->{value}} = $thisbranch->{branchname};
342             }
343         $value = "";
344         }
345         elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
346             push @authorised_values, "";
347             my $sth = $dbh->prepare("select itemtype,description from itemtypes order by description");
348             $sth->execute;
349             while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
350                 push @authorised_values, $itemtype;
351                 $authorised_lib{$itemtype} = $description;
352             }
353         $value = "";
354
355           #---- class_sources
356       }
357       elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
358           push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
359             
360           my $class_sources = GetClassSources();
361           my $default_source = C4::Context->preference("DefaultClassificationSource");
362           
363           foreach my $class_source (sort keys %$class_sources) {
364               next unless $class_sources->{$class_source}->{'used'} or
365                           ($value and $class_source eq $value)      or
366                           ($class_source eq $default_source);
367               push @authorised_values, $class_source;
368               $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
369           }
370                   $value = '';
371
372           #---- "true" authorised value
373       }
374       else {
375           push @authorised_values, ""; # unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
376           $authorised_values_sth->execute( $tagslib->{$tag}->{$subfield}->{authorised_value}, $branch_limit ? $branch_limit : () );
377           while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
378               push @authorised_values, $value;
379               $authorised_lib{$value} = $lib;
380           }
381           $value="";
382       }
383         $subfield_data{marc_value} = {
384             type    => 'select',
385             id      => "tag_".$tag."_subfield_".$subfield."_".$index_subfield,
386             name    => "field_value",
387             values  => \@authorised_values,
388             labels  => \%authorised_lib,
389             default => $value,
390         };
391     # it's a thesaurus / authority field
392     }
393     elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode} ) {
394         $subfield_data{marc_value} = {
395             type         => 'text1',
396             id           => $subfield_data{id},
397             value        => $value,
398             authtypecode => $tagslib->{$tag}->{$subfield}->{authtypecode},
399         }
400     # it's a plugin field
401     }
402     elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) {
403         # opening plugin
404         my $plugin = C4::Context->intranetdir . "/cataloguing/value_builder/" . $tagslib->{$tag}->{$subfield}->{'value_builder'};
405         if (do $plugin) {
406                         my $temp;
407             my $extended_param = plugin_parameters( $dbh, $temp, $tagslib, $subfield_data{id}, \@loop_data );
408             my ( $function_name, $javascript ) = plugin_javascript( $dbh, $temp, $tagslib, $subfield_data{id}, \@loop_data );
409             $subfield_data{marc_value} = {
410                 type       => 'text2',
411                 id         => $subfield_data{id},
412                 value      => $value,
413                 function   => $function_name,
414                 random     => $subfield_data{random},
415                 javascript => $javascript,
416             };
417         } else {
418             warn "Plugin Failed: $plugin";
419             $subfield_data{marc_value} = {                                      # supply default input form
420                 type       => 'text',
421                 id         => $subfield_data{id},
422                 value      => $value,
423             };
424         }
425     }
426     elsif ( $tag eq '' ) {       # it's an hidden field
427             $subfield_data{marc_value} = {
428                 type       => 'hidden',
429                 id         => $subfield_data{id},
430                 value      => $value,
431             };
432     }
433     elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) {   # FIXME: shouldn't input type be "hidden" ?
434         $subfield_data{marc_value} = {
435                 type       => 'text',
436                 id         => $subfield_data{id},
437                 value      => $value,
438         };
439     }
440     elsif ( length($value) > 100
441             or (C4::Context->preference("marcflavour") eq "UNIMARC" and
442                   300 <= $tag && $tag < 400 && $subfield eq 'a' )
443             or (C4::Context->preference("marcflavour") eq "MARC21"  and
444                   500 <= $tag && $tag < 600                     )
445           ) {
446         # oversize field (textarea)
447         $subfield_data{marc_value} = {
448                 type       => 'textarea',
449                 id         => $subfield_data{id},
450                 value      => $value,
451         };
452     } else {
453         # it's a standard field
454         $subfield_data{marc_value} = {
455                 type       => 'text',
456                 id         => $subfield_data{id},
457                 value      => $value,
458         };
459     }
460 #   $subfield_data{marc_value}="<input type=\"text\" name=\"field_value\">";
461     push (@loop_data, \%subfield_data);
462     $i++
463   }
464 } # -- End foreach tag
465 $authorised_values_sth->finish;
466
467
468
469     # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
470     $template->param(item => \@loop_data);
471     if (@notfoundbarcodes) { 
472         my @notfoundbarcodesloop = map{{barcode=>$_}}@notfoundbarcodes;
473         $template->param(notfoundbarcodes => \@notfoundbarcodesloop);
474     }
475     $nextop="action"
476 } # -- End action="show"
477
478 $template->param(%$items_display_hashref) if $items_display_hashref;
479 $template->param(
480     op      => $nextop,
481 );
482 $template->param( $op => 1 ) if $op;
483
484 if ($op eq "action") {
485
486     #my @not_deleted_loop = map{{itemnumber=>$_}}@not_deleted;
487
488     $template->param(
489         not_deleted_items => $not_deleted_items,
490         deleted_items => $deleted_items,
491         delete_records => $del_records,
492         deleted_records => $deleted_records,
493         not_deleted_loop => \@not_deleted 
494     );
495 }
496
497 foreach my $error (@errors) {
498     $template->param($error => 1) if $error;
499 }
500 $template->param(src => $src);
501 $template->param(biblionumber => $biblionumber);
502 output_html_with_http_headers $input, $cookie, $template->output;
503 exit;
504
505
506 # ---------------- Functions
507
508 sub BuildItemsData{
509         my @itemnumbers=@_;
510                 # now, build existiing item list
511                 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
512                 my @big_array;
513                 #---- finds where items.itemnumber is stored
514                 my (  $itemtagfield,   $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
515                 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField("items.homebranch", "");
516                 foreach my $itemnumber (@itemnumbers){
517                         my $itemdata=GetItem($itemnumber);
518                         my $itemmarc=Item2Marc($itemdata);
519                         my %this_row;
520                         foreach my $field (grep {$_->tag() eq $itemtagfield} $itemmarc->fields()) {
521                                 # loop through each subfield
522                                 my $itembranchcode=$field->subfield($branchtagsubfield);
523                 if ($itembranchcode && C4::Context->preference("IndependentBranches")) {
524                                                 #verifying rights
525                                                 my $userenv = C4::Context->userenv();
526                         unless (C4::Context->IsSuperLibrarian() or (($userenv->{'branch'} eq $itembranchcode))){
527                                                                 $this_row{'nomod'}=1;
528                                                 }
529                                 }
530                                 my $tag=$field->tag();
531                                 foreach my $subfield ($field->subfields) {
532                                         my ($subfcode,$subfvalue)=@$subfield;
533                                         next if ($tagslib->{$tag}->{$subfcode}->{tab} ne 10 
534                                                         && $tag        ne $itemtagfield 
535                                                         && $subfcode   ne $itemtagsubfield);
536
537                                         $witness{$subfcode} = $tagslib->{$tag}->{$subfcode}->{lib} if ($tagslib->{$tag}->{$subfcode}->{tab}  eq 10);
538                                         if ($tagslib->{$tag}->{$subfcode}->{tab}  eq 10) {
539                                                 $this_row{$subfcode}=GetAuthorisedValueDesc( $tag,
540                                                                         $subfcode, $subfvalue, '', $tagslib) 
541                                                                         || $subfvalue;
542                                         }
543
544                                         $this_row{itemnumber} = $subfvalue if ($tag eq $itemtagfield && $subfcode eq $itemtagsubfield);
545                                 }
546                         }
547
548             # grab title, author, and ISBN to identify bib that the item
549             # belongs to in the display
550                          my $biblio=GetBiblioData($$itemdata{biblionumber});
551             $this_row{title} = $biblio->{title};
552             $this_row{author} = $biblio->{author};
553             $this_row{isbn} = $biblio->{isbn};
554             $this_row{biblionumber} = $biblio->{biblionumber};
555
556                         if (%this_row) {
557                                 push(@big_array, \%this_row);
558                         }
559                 }
560                 @big_array = sort {$a->{0} cmp $b->{0}} @big_array;
561
562                 # now, construct template !
563                 # First, the existing items for display
564                 my @item_value_loop;
565                 my @witnesscodessorted=sort keys %witness;
566                 for my $row ( @big_array ) {
567                         my %row_data;
568                         my @item_fields = map +{ field => $_ || '' }, @$row{ @witnesscodessorted };
569                         $row_data{item_value} = [ @item_fields ];
570                         $row_data{itemnumber} = $row->{itemnumber};
571                         #reporting this_row values
572                         $row_data{'nomod'} = $row->{'nomod'};
573       $row_data{bibinfo} = $row->{bibinfo};
574       $row_data{author} = $row->{author};
575       $row_data{title} = $row->{title};
576       $row_data{isbn} = $row->{isbn};
577       $row_data{biblionumber} = $row->{biblionumber};
578       my $is_on_loan = C4::Circulation::IsItemIssued( $row->{itemnumber} );
579       $row_data{onloan} = $is_on_loan ? 1 : 0;
580                         push(@item_value_loop,\%row_data);
581                 }
582                 my @header_loop=map { { header_value=> $witness{$_}} } @witnesscodessorted;
583
584         return { item_loop        => \@item_value_loop, item_header_loop => \@header_loop };
585 }
586
587 #BE WARN : it is not the general case 
588 # This function can be OK in the item marc record special case
589 # Where subfield is not repeated
590 # And where we are sure that field should correspond
591 # And $tag>10
592 sub UpdateMarcWith {
593   my ($marcfrom,$marcto)=@_;
594     my (  $itemtag,   $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
595     my $fieldfrom=$marcfrom->field($itemtag);
596     my @fields_to=$marcto->field($itemtag);
597     my $modified = 0;
598     foreach my $subfield ( $fieldfrom->subfields() ) {
599         foreach my $field_to_update ( @fields_to ) {
600             if ( $subfield->[1] ) {
601                 unless ( $field_to_update->subfield($subfield->[0]) eq $subfield->[1] ) {
602                     $modified++;
603                     $field_to_update->update( $subfield->[0] => $subfield->[1] );
604                 }
605             }
606             else {
607                 $modified++;
608                 $field_to_update->delete_subfield( code => $subfield->[0] );
609             }
610         }
611     }
612     return $modified;
613 }
614
615 sub find_value {
616     my ($tagfield,$insubfield,$record) = @_;
617     my $result;
618     my $indicator;
619     foreach my $field ($record->field($tagfield)) {
620         my @subfields = $field->subfields();
621         foreach my $subfield (@subfields) {
622             if (@$subfield[0] eq $insubfield) {
623                 $result .= @$subfield[1];
624                 $indicator = $field->indicator(1).$field->indicator(2);
625             }
626         }
627     }
628     return($indicator,$result);
629 }
630
631 # ----------------------------
632 # Background functions
633
634
635 sub add_results_to_template {
636     my $template = shift;
637     my $results = shift;
638     $template->param(map { $_ => $results->{$_} } keys %{ $results });
639 }
640
641 sub add_saved_job_results_to_template {
642     my $template = shift;
643     my $completedJobID = shift;
644     my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
645     my $results = $job->results();
646     add_results_to_template($template, $results);
647
648     my $fields = $job->get("modified_fields");
649     my $items = $job->get("modified_items");
650     $template->param(
651         modified_items => $items,
652         modified_fields => $fields,
653     );
654 }
655
656 sub put_in_background {
657     my $job_size = shift;
658
659     my $job = C4::BackgroundJob->new($sessionID, "test", $ENV{'SCRIPT_NAME'}, $job_size);
660     my $jobID = $job->id();
661
662     # fork off
663     if (my $pid = fork) {
664         # parent
665         # return job ID as JSON
666
667         # prevent parent exiting from
668         # destroying the kid's database handle
669         # FIXME: according to DBI doc, this may not work for Oracle
670         $dbh->{InactiveDestroy}  = 1;
671
672         my $reply = CGI->new("");
673         print $reply->header(-type => 'text/html');
674         print '{"jobID":"' . $jobID . '"}';
675         exit 0;
676     } elsif (defined $pid) {
677         # child
678         # close STDOUT to signal to Apache that
679         # we're now running in the background
680         close STDOUT;
681         close STDERR;
682     } else {
683         # fork failed, so exit immediately
684         warn "fork failed while attempting to run $ENV{'SCRIPT_NAME'} as a background job";
685         exit 0;
686     }
687     return $job;
688 }
689
690
691