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