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