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