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