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