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