Merge branch '20.11.x-security' into 20.11.x
[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 Try::Tiny;
24
25 use C4::Auth;
26 use C4::Output;
27 use C4::Biblio;
28 use C4::Items;
29 use C4::Circulation;
30 use C4::Context;
31 use C4::Koha;
32 use C4::BackgroundJob;
33 use C4::ClassSource;
34 use C4::Debug;
35 use C4::Members;
36 use MARC::File::XML;
37 use List::MoreUtils qw/uniq/;
38
39 use Koha::Database;
40 use Koha::Exceptions::Exception;
41 use Koha::AuthorisedValues;
42 use Koha::Biblios;
43 use Koha::DateUtils;
44 use Koha::Items;
45 use Koha::ItemTypes;
46 use Koha::Patrons;
47 use Koha::SearchEngine::Indexer;
48
49 my $input = CGI->new;
50 my $dbh = C4::Context->dbh;
51 my $error        = $input->param('error');
52 my @itemnumbers  = $input->multi_param('itemnumber');
53 my $biblionumber = $input->param('biblionumber');
54 my $op           = $input->param('op');
55 my $del          = $input->param('del');
56 my $del_records  = $input->param('del_records');
57 my $completedJobID = $input->param('completedJobID');
58 my $runinbackground = $input->param('runinbackground');
59 my $src          = $input->param('src');
60 my $use_default_values = $input->param('use_default_values');
61 my $exclude_from_local_holds_priority = $input->param('exclude_from_local_holds_priority');
62
63 my $template_name;
64 my $template_flag;
65 if (!defined $op) {
66     $template_name = "tools/batchMod.tt";
67     $template_flag = { tools => '*' };
68     $op = q{};
69 } else {
70     $template_name = ($del) ? "tools/batchMod-del.tt" : "tools/batchMod-edit.tt";
71     $template_flag = ($del) ? { tools => 'items_batchdel' }   : { tools => 'items_batchmod' };
72 }
73
74 my ($template, $loggedinuser, $cookie)
75     = get_template_and_user({template_name => $template_name,
76                  query => $input,
77                  type => "intranet",
78                  flagsrequired => $template_flag,
79                  });
80
81 $template->param( searchid => scalar $input->param('searchid'), );
82
83 # Does the user have a restricted item edition permission?
84 my $uid = $loggedinuser ? Koha::Patrons->find( $loggedinuser )->userid : undef;
85 my $restrictededition = $uid ? haspermission($uid,  {'tools' => 'items_batchmod_restricted'}) : undef;
86 # In case user is a superlibrarian, edition is not restricted
87 $restrictededition = 0 if ($restrictededition != 0 && C4::Context->IsSuperLibrarian());
88
89 $template->param(del       => $del);
90
91 my $nextop="";
92 my @errors; # store errors found while checking data BEFORE saving item.
93 my $items_display_hashref;
94 our $tagslib = &GetMarcStructure(1);
95
96 my $deleted_items = 0;     # Number of deleted items
97 my $deleted_records = 0;   # Number of deleted records ( with no items attached )
98 my $not_deleted_items = 0; # Number of items that could not be deleted
99 my @not_deleted;           # List of the itemnumbers that could not be deleted
100 my $modified_items = 0;    # Numbers of modified items
101 my $modified_fields = 0;   # Numbers of modified fields
102
103 my %cookies = parse CGI::Cookie($cookie);
104 my $sessionID = $cookies{'CGISESSID'}->value;
105
106
107 #--- ----------------------------------------------------------------------------
108 if ($op eq "action") {
109 #-------------------------------------------------------------------------------
110     my @tags      = $input->multi_param('tag');
111     my @subfields = $input->multi_param('subfield');
112     my @values    = $input->multi_param('field_value');
113     my @searches  = $input->multi_param('regex_search');
114     my @replaces  = $input->multi_param('regex_replace');
115     my @modifiers = $input->multi_param('regex_modifiers');
116     my @disabled  = $input->multi_param('disable_input');
117     # build indicator hash.
118     my @ind_tag   = $input->multi_param('ind_tag');
119     my @indicator = $input->multi_param('indicator');
120
121     # Is there something to modify ?
122     # TODO : We shall use this var to warn the user in case no modification was done to the items
123     my $values_to_modify = scalar(grep {!/^$/} @values) || scalar(grep {!/^$/} @searches);
124     my $values_to_blank  = scalar(@disabled);
125
126     # Clear the fields we are not editing, leave fields we are blanking
127     foreach( my $i = 0; $i < scalar @values; $i++ ){
128         unless( $values[$i] ne q{} || $searches[$i] ne q{}  || grep { $subfields[$i] } @disabled ){
129             splice(@values,$i,1);
130             splice(@subfields,$i,1);
131             splice(@tags,$i,1);
132             splice(@searches,$i,1);
133             splice(@replaces,$i,1);
134             splice(@modifiers,$i,1);
135             $i--; # We made the arrays smaller - go back a step in iteration
136         }
137     }
138
139     my $marcitem;
140
141     # Once the job is done
142     if ($completedJobID) {
143         # If we have a reasonable amount of items, we display them
144     my $max_items = $del ? C4::Context->preference("MaxItemsToDisplayForBatchDel") : C4::Context->preference("MaxItemsToDisplayForBatchMod");
145     if (scalar(@itemnumbers) <= $max_items ){
146         if (scalar(@itemnumbers) <= 1000 ) {
147             $items_display_hashref=BuildItemsData(@itemnumbers);
148         } else {
149             # Else, we only display the barcode
150             my @simple_items_display = map {
151                 my $itemnumber = $_;
152                 my $item = Koha::Items->find($itemnumber);
153                 {
154                     itemnumber   => $itemnumber,
155                     barcode      => $item ? ( $item->barcode // q{} ) : q{},
156                     biblionumber => $item ? $item->biblio->biblionumber : q{},
157                 };
158             } @itemnumbers;
159             $template->param("simple_items_display" => \@simple_items_display);
160         }
161     } else {
162         $template->param( "too_many_items_display" => scalar(@itemnumbers) );
163         $template->param( "job_completed" => 1 );
164     }
165
166         # Setting the job as done
167         my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
168
169         # Calling the template
170         add_saved_job_results_to_template($template, $completedJobID, $items_display_hashref);
171
172     } else {
173     # While the job is getting done
174
175         # Job size is the number of items we have to process
176         my $job_size = scalar(@itemnumbers);
177         my $job = undef;
178
179         # If we asked for background processing
180         if ($runinbackground) {
181             $job = put_in_background($job_size);
182         }
183
184         #initializing values for updates
185     my (  $itemtagfield,   $itemtagsubfield) = &GetMarcFromKohaField( "items.itemnumber" );
186         if ($values_to_modify){
187             my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
188             $marcitem = MARC::Record::new_from_xml($xml, 'UTF-8');
189         }
190         if ($values_to_blank){
191             foreach my $disabledsubf (@disabled){
192                 if ($marcitem && $marcitem->field($itemtagfield)){
193                     $marcitem->field($itemtagfield)->update( $disabledsubf => "" );
194                 }
195                 else {
196                     $marcitem = MARC::Record->new();
197                     $marcitem->append_fields( MARC::Field->new( $itemtagfield, '', '', $disabledsubf => "" ) );
198                 }
199             }
200         }
201
202         my $yesno = Koha::AuthorisedValues->search({category => 'YES_NO'});
203         my $ynhash = {};
204
205         while(my $yn = $yesno->next) {
206             $ynhash->{'av'.$yn->authorised_value} = $yn->lib;
207         }
208
209         my $upd_biblionumbers;
210         my $del_biblionumbers;
211         try {
212             my $schema = Koha::Database->new->schema;
213             $schema->txn_do(
214                 sub {
215                     # For each item
216                     my $i = 1;
217                     my $extra_headers = {};
218                     foreach my $itemnumber (@itemnumbers) {
219                         $job->progress($i) if $runinbackground;
220                         my $item = Koha::Items->find($itemnumber);
221                         next
222                           unless $item
223                           ; # Should have been tested earlier, but just in case...
224                         my $itemdata = $item->unblessed;
225                         if ($del) {
226                             my $return = $item->safe_delete;
227                             if ( ref( $return ) ) {
228                                 $deleted_items++;
229                                 push @$upd_biblionumbers, $itemdata->{'biblionumber'};
230                             }
231                             else {
232                                 $not_deleted_items++;
233                                 push @not_deleted,
234                                   {
235                                     biblionumber => $itemdata->{'biblionumber'},
236                                     itemnumber   => $itemdata->{'itemnumber'},
237                                     barcode      => $itemdata->{'barcode'},
238                                     title        => $itemdata->{'title'},
239                                     reason       => $return,
240                                   };
241                             }
242
243                             # If there are no items left, delete the biblio
244                             if ($del_records) {
245                                 my $itemscount = Koha::Biblios->find( $itemdata->{'biblionumber'} )->items->count;
246                                 if ( $itemscount == 0 ) {
247                                     my $error = DelBiblio( $itemdata->{'biblionumber'}, { skip_record_index => 1 } );
248                                     unless ($error) {
249                                         $deleted_records++;
250                                         push @$del_biblionumbers, $itemdata->{'biblionumber'};
251                                         if ( $src eq 'CATALOGUING' ) {
252                                             # We are coming catalogue/detail.pl, there were items from a single bib record
253                                             $template->param( biblio_deleted => 1 );
254                                         }
255                                     }
256                                 }
257                             }
258                         }
259                         else {
260                             my $modified_holds_priority = 0;
261                             if ( defined $exclude_from_local_holds_priority && $exclude_from_local_holds_priority ne "" ) {
262                                 if(!defined $item->exclude_from_local_holds_priority || $item->exclude_from_local_holds_priority != $exclude_from_local_holds_priority) {
263                                 $item->exclude_from_local_holds_priority($exclude_from_local_holds_priority)->store;
264                                 $modified_holds_priority = 1;
265                             }
266                                 $extra_headers->{exclude_from_local_holds_priority} = {name => 'Exclude from local holds priority', items => {}} unless defined $extra_headers->{exclude_from_local_holds_priority};
267                                 $extra_headers->{exclude_from_local_holds_priority}->{items}->{$item->itemnumber} = $ynhash->{'av'.$item->exclude_from_local_holds_priority};
268                             }
269                             my $modified = 0;
270                             if ( $values_to_modify || $values_to_blank ) {
271                                 my $localmarcitem = Item2Marc($itemdata);
272
273                                 for ( my $i = 0 ; $i < @tags ; $i++ ) {
274                                     my $search = $searches[$i];
275                                     next unless $search;
276
277                                     my $tag = $tags[$i];
278                                     my $subfield = $subfields[$i];
279                                     my $replace = $replaces[$i];
280
281                                     my $value = $localmarcitem->field( $tag )->subfield( $subfield );
282                                     my $old_value = $value;
283
284                                     my @available_modifiers = qw( i g );
285                                     my $retained_modifiers = q||;
286                                     for my $modifier ( split //, $modifiers[$i] ) {
287                                         $retained_modifiers .= $modifier
288                                             if grep {/$modifier/} @available_modifiers;
289                                     }
290                                     if ( $retained_modifiers =~ m/^(ig|gi)$/ ) {
291                                         $value =~ s/$search/$replace/ig;
292                                     }
293                                     elsif ( $retained_modifiers eq 'i' ) {
294                                         $value =~ s/$search/$replace/i;
295                                     }
296                                     elsif ( $retained_modifiers eq 'g' ) {
297                                         $value =~ s/$search/$replace/g;
298                                     }
299                                     else {
300                                         $value =~ s/$search/$replace/;
301                                     }
302
303                                     my @fields_to = $localmarcitem->field($tag);
304                                     foreach my $field_to_update ( @fields_to ) {
305                                         unless ( $old_value eq $value ) {
306                                             $modified++;
307                                             $field_to_update->update( $subfield => $value );
308                                         }
309                                     }
310                                 }
311
312                                 $modified += UpdateMarcWith( $marcitem, $localmarcitem );
313                                 if ($modified) {
314                                     eval {
315                                         if (
316                                             my $item = ModItemFromMarc(
317                                                 $localmarcitem,
318                                                 $itemdata->{biblionumber},
319                                                 $itemnumber,
320                                                 { skip_record_index => 1 },
321                                             )
322                                           )
323                                         {
324                                             LostItem(
325                                                 $itemnumber,
326                                                 'batchmod',
327                                                 undef,
328                                                 { skip_record_index => 1 }
329                                             ) if $item->{itemlost}
330                                               and not $itemdata->{itemlost};
331                                         }
332                                     };
333                                     push @$upd_biblionumbers, $itemdata->{'biblionumber'};
334                                 }
335                             }
336                             if ($runinbackground) {
337                                 $modified_items++ if $modified || $modified_holds_priority;
338                                 $modified_fields += $modified + $modified_holds_priority;
339                                 $job->set(
340                                     {
341                                         modified_items  => $modified_items,
342                                         modified_fields => $modified_fields,
343                                         extra_headers => $extra_headers,
344                                     }
345                                 );
346                             }
347                         }
348                         $i++;
349                     }
350                     if (@not_deleted) {
351                         Koha::Exceptions::Exception->throw(
352                             'Some items have not been deleted, rolling back');
353                     }
354                 }
355             );
356         }
357         catch {
358             if ( $_->isa('Koha::Exceptions::Exception') ) {
359                 $template->param( deletion_failed => 1 );
360             }
361             die "Something terrible has happened!"
362                 if ($_ =~ /Rollback failed/); # Rollback failed
363         };
364         $upd_biblionumbers = [ uniq @$upd_biblionumbers ]; # Only update each bib once
365
366         # Don't send specialUpdate for records we are going to delete
367         my %del_bib_hash = map{ $_ => undef } @$del_biblionumbers;
368         @$upd_biblionumbers = grep( ! exists( $del_bib_hash{$_} ), @$upd_biblionumbers );
369
370         my $indexer = Koha::SearchEngine::Indexer->new({ index => $Koha::SearchEngine::BIBLIOS_INDEX });
371         $indexer->index_records( $upd_biblionumbers, 'specialUpdate', "biblioserver", undef ) if @$upd_biblionumbers;
372         $indexer->index_records( $del_biblionumbers, 'recordDelete', "biblioserver", undef ) if @$del_biblionumbers;
373     }
374 }
375 #
376 #-------------------------------------------------------------------------------
377 # build screen with existing items. and "new" one
378 #-------------------------------------------------------------------------------
379
380 if ($op eq "show"){
381     my $filefh = $input->upload('uploadfile');
382     my $filecontent = $input->param('filecontent');
383     my ( @notfoundbarcodes, @notfounditemnumbers);
384
385     my $split_chars = C4::Context->preference('BarcodeSeparators');
386     if ($filefh){
387         binmode $filefh, ':encoding(UTF-8)';
388         my @contentlist;
389         while (my $content=<$filefh>){
390             $content =~ s/[\r\n]*$//;
391             push @contentlist, $content if $content;
392         }
393
394         if ($filecontent eq 'barcode_file') {
395             @contentlist = grep /\S/, ( map { split /[$split_chars]/ } @contentlist );
396             @contentlist = uniq @contentlist;
397             # Note: adding lc for case insensitivity
398             my %itemdata = map { lc($_->{barcode}) => $_->{itemnumber} } @{ Koha::Items->search({ barcode => \@contentlist }, { columns => [ 'itemnumber', 'barcode' ] } )->unblessed };
399             @itemnumbers = map { exists $itemdata{lc $_} ? $itemdata{lc $_} : () } @contentlist;
400             @notfoundbarcodes = grep { !exists $itemdata{lc $_} } @contentlist;
401         }
402         elsif ( $filecontent eq 'itemid_file') {
403             @contentlist = uniq @contentlist;
404             my %itemdata = map { $_->{itemnumber} => 1 } @{ Koha::Items->search({ itemnumber => \@contentlist }, { columns => [ 'itemnumber' ] } )->unblessed };
405             @itemnumbers = grep { exists $itemdata{$_} } @contentlist;
406             @notfounditemnumbers = grep { !exists $itemdata{$_} } @contentlist;
407         }
408     } else {
409         if (defined $biblionumber && !@itemnumbers){
410             my @all_items = GetItemsInfo( $biblionumber );
411             foreach my $itm (@all_items) {
412                 push @itemnumbers, $itm->{itemnumber};
413             }
414         }
415         if ( my $list = $input->param('barcodelist') ) {
416             my @barcodelist = grep /\S/, ( split /[$split_chars]/, $list );
417             @barcodelist = uniq @barcodelist;
418             # Note: adding lc for case insensitivity
419             my %itemdata = map { lc($_->{barcode}) => $_->{itemnumber} } @{ Koha::Items->search({ barcode => \@barcodelist }, { columns => [ 'itemnumber', 'barcode' ] } )->unblessed };
420             @itemnumbers = map { exists $itemdata{lc $_} ? $itemdata{lc $_} : () } @barcodelist;
421             @notfoundbarcodes = grep { !exists $itemdata{lc $_} } @barcodelist;
422         }
423     }
424
425     # Flag to tell the template there are valid results, hidden or not
426     if(scalar(@itemnumbers) > 0){ $template->param("itemresults" => 1); }
427     # Only display the items if there are no more than pref MaxItemsToProcessForBatchMod or MaxItemsToDisplayForBatchDel
428     my $max_display_items = $del
429         ? C4::Context->preference("MaxItemsToDisplayForBatchDel")
430         : C4::Context->preference("MaxItemsToDisplayForBatchMod");
431     $template->param("too_many_items_process" => scalar(@itemnumbers)) if !$del && scalar(@itemnumbers) > C4::Context->preference("MaxItemsToProcessForBatchMod");
432     if (scalar(@itemnumbers) <= ( $max_display_items // 1000 ) ) {
433         $items_display_hashref=BuildItemsData(@itemnumbers);
434     } else {
435         $template->param("too_many_items_display" => scalar(@itemnumbers));
436         # Even if we do not display the items, we need the itemnumbers
437         $template->param(itemnumbers_array => \@itemnumbers);
438     }
439 # now, build the item form for entering a new item
440 my @loop_data =();
441 my $i=0;
442 my $branch_limit = C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
443
444 my $libraries = Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed;# build once ahead of time, instead of multiple times later.
445
446 # Adding a default choice, in case the user does not want to modify the branch
447 my $nochange_branch = { branchname => '', value => '', selected => 1 };
448 unshift (@$libraries, $nochange_branch);
449
450 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
451
452 # Getting list of subfields to keep when restricted batchmod edit is enabled
453 my $subfieldsToAllowForBatchmod = C4::Context->preference('SubfieldsToAllowForRestrictedBatchmod');
454 my $allowAllSubfields = (
455     not defined $subfieldsToAllowForBatchmod
456       or $subfieldsToAllowForBatchmod eq q||
457 ) ? 1 : 0;
458 my @subfieldsToAllow = split(/ /, $subfieldsToAllowForBatchmod);
459
460 foreach my $tag (sort keys %{$tagslib}) {
461     # loop through each subfield
462     foreach my $subfield (sort keys %{$tagslib->{$tag}}) {
463         next if IsMarcStructureInternal( $tagslib->{$tag}{$subfield} );
464         next if (not $allowAllSubfields and $restrictededition && !grep { $tag . '$' . $subfield eq $_ } @subfieldsToAllow );
465         next if ($tagslib->{$tag}->{$subfield}->{'tab'} ne "10");
466         # barcode is not meant to be batch-modified
467         next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.barcode';
468         my %subfield_data;
469  
470         my $index_subfield = int(rand(1000000)); 
471         if ($subfield eq '@'){
472             $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
473         } else {
474             $subfield_data{id} = "tag_".$tag."_subfield_".$subfield."_".$index_subfield;
475         }
476         $subfield_data{tag}        = $tag;
477         $subfield_data{subfield}   = $subfield;
478         $subfield_data{marc_lib}   ="<span id=\"error$i\" title=\"".$tagslib->{$tag}->{$subfield}->{lib}."\">".$tagslib->{$tag}->{$subfield}->{lib}."</span>";
479         $subfield_data{mandatory}  = $tagslib->{$tag}->{$subfield}->{mandatory};
480         $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
481     my $value;
482     if ( $use_default_values) {
483             $value = $tagslib->{$tag}->{$subfield}->{defaultvalue};
484             # get today date & replace YYYY, MM, DD if provided in the default value
485             my $today = dt_from_string;
486             my $year  = $today->year;
487             my $month = $today->month;
488             my $day   = $today->day;
489             $value =~ s/YYYY/$year/g;
490             $value =~ s/MM/$month/g;
491             $value =~ s/DD/$day/g;
492         }
493         $subfield_data{visibility} = "display:none;" if (($tagslib->{$tag}->{$subfield}->{hidden} > 4) || ($tagslib->{$tag}->{$subfield}->{hidden} < -4));
494     # testing branch value if IndependentBranches.
495
496         if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
497         my @authorised_values;
498         my %authorised_lib;
499         # builds list, depending on authorised value...
500
501     if ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "branches" ) {
502         foreach my $library (@$libraries) {
503             push @authorised_values, $library->{branchcode};
504             $authorised_lib{$library->{branchcode}} = $library->{branchname};
505         }
506         $value = "";
507     }
508     elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
509         push @authorised_values, "";
510         my $itemtypes = Koha::ItemTypes->search_with_localization;
511         while ( my $itemtype = $itemtypes->next ) {
512             push @authorised_values, $itemtype->itemtype;
513             $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description;
514         }
515         $value = "";
516
517           #---- class_sources
518       }
519       elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
520           push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
521             
522           my $class_sources = GetClassSources();
523           my $default_source = C4::Context->preference("DefaultClassificationSource");
524           
525           foreach my $class_source (sort keys %$class_sources) {
526               next unless $class_sources->{$class_source}->{'used'} or
527                           ($value and $class_source eq $value)      or
528                           ($class_source eq $default_source);
529               push @authorised_values, $class_source;
530               $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
531           }
532                   $value = '';
533
534           #---- "true" authorised value
535       }
536       else {
537           push @authorised_values, ""; # unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
538
539           my @avs = Koha::AuthorisedValues->search({ category => $tagslib->{$tag}->{$subfield}->{authorised_value}, branchcode => $branch_limit },{order_by=>'lib'});
540           for my $av ( @avs ) {
541               push @authorised_values, $av->authorised_value;
542               $authorised_lib{$av->authorised_value} = $av->lib;
543           }
544           $value="";
545       }
546         $subfield_data{marc_value} = {
547             type    => 'select',
548             id      => "tag_".$tag."_subfield_".$subfield."_".$index_subfield,
549             name    => "field_value",
550             values  => \@authorised_values,
551             labels  => \%authorised_lib,
552             default => $value,
553         };
554     # it's a thesaurus / authority field
555     }
556     elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode} ) {
557         $subfield_data{marc_value} = {
558             type         => 'text1',
559             id           => $subfield_data{id},
560             value        => $value,
561             authtypecode => $tagslib->{$tag}->{$subfield}->{authtypecode},
562         }
563     }
564     elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) { # plugin
565         require Koha::FrameworkPlugin;
566         my $plugin = Koha::FrameworkPlugin->new( {
567             name => $tagslib->{$tag}->{$subfield}->{'value_builder'},
568             item_style => 1,
569         });
570         my $temp;
571         my $pars= { dbh => $dbh, record => $temp, tagslib => $tagslib,
572             id => $subfield_data{id}, tabloop => \@loop_data };
573         $plugin->build( $pars );
574         if( !$plugin->errstr ) {
575             $subfield_data{marc_value} = {
576                 type       => 'text2',
577                 id         => $subfield_data{id},
578                 value      => $value,
579                 javascript => $plugin->javascript,
580                 noclick    => $plugin->noclick,
581             };
582         } else {
583             warn $plugin->errstr;
584             $subfield_data{marc_value} = { # supply default input form
585                 type       => 'text',
586                 id         => $subfield_data{id},
587                 value      => $value,
588             };
589         }
590     }
591     elsif ( $tag eq '' ) {       # it's an hidden field
592             $subfield_data{marc_value} = {
593                 type       => 'hidden',
594                 id         => $subfield_data{id},
595                 value      => $value,
596             };
597     }
598     elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) {   # FIXME: shouldn't input type be "hidden" ?
599         $subfield_data{marc_value} = {
600                 type       => 'text',
601                 id         => $subfield_data{id},
602                 value      => $value,
603         };
604     }
605     elsif ( length($value) > 100
606             or (C4::Context->preference("marcflavour") eq "UNIMARC" and
607                   300 <= $tag && $tag < 400 && $subfield eq 'a' )
608             or (C4::Context->preference("marcflavour") eq "MARC21"  and
609                   500 <= $tag && $tag < 600                     )
610           ) {
611         # oversize field (textarea)
612         $subfield_data{marc_value} = {
613                 type       => 'textarea',
614                 id         => $subfield_data{id},
615                 value      => $value,
616         };
617     } else {
618         # it's a standard field
619         $subfield_data{marc_value} = {
620                 type       => 'text',
621                 id         => $subfield_data{id},
622                 value      => $value,
623         };
624     }
625 #   $subfield_data{marc_value}="<input type=\"text\" name=\"field_value\">";
626     push (@loop_data, \%subfield_data);
627     $i++
628   }
629 } # -- End foreach tag
630
631
632
633     # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
634     $template->param(
635         item                => \@loop_data,
636         notfoundbarcodes    => \@notfoundbarcodes,
637         notfounditemnumbers => \@notfounditemnumbers
638     );
639     $nextop="action"
640 } # -- End action="show"
641
642 $template->param(%$items_display_hashref) if $items_display_hashref;
643 $template->param(
644     op      => $nextop,
645 );
646 $template->param( $op => 1 ) if $op;
647
648 if ($op eq "action") {
649
650     #my @not_deleted_loop = map{{itemnumber=>$_}}@not_deleted;
651
652     $template->param(
653         not_deleted_items => $not_deleted_items,
654         deleted_items => $deleted_items,
655         delete_records => $del_records,
656         deleted_records => $deleted_records,
657         not_deleted_loop => \@not_deleted 
658     );
659 }
660
661 foreach my $error (@errors) {
662     $template->param($error => 1) if $error;
663 }
664 $template->param(src => $src);
665 $template->param(biblionumber => $biblionumber);
666 output_html_with_http_headers $input, $cookie, $template->output;
667 exit;
668
669
670 # ---------------- Functions
671
672 sub BuildItemsData{
673         my @itemnumbers=@_;
674                 # now, build existiing item list
675                 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
676                 my @big_array;
677                 #---- finds where items.itemnumber is stored
678     my (  $itemtagfield,   $itemtagsubfield) = &GetMarcFromKohaField( "items.itemnumber" );
679     my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField( "items.homebranch" );
680                 foreach my $itemnumber (@itemnumbers){
681             my $itemdata = Koha::Items->find($itemnumber);
682             next unless $itemdata; # Should have been tested earlier, but just in case...
683             $itemdata = $itemdata->unblessed;
684                         my $itemmarc=Item2Marc($itemdata);
685                         my %this_row;
686                         foreach my $field (grep {$_->tag() eq $itemtagfield} $itemmarc->fields()) {
687                                 # loop through each subfield
688                                 my $itembranchcode=$field->subfield($branchtagsubfield);
689                 if ($itembranchcode && C4::Context->preference("IndependentBranches")) {
690                                                 #verifying rights
691                                                 my $userenv = C4::Context->userenv();
692                         unless (C4::Context->IsSuperLibrarian() or (($userenv->{'branch'} eq $itembranchcode))){
693                                                                 $this_row{'nomod'}=1;
694                                                 }
695                                 }
696                                 my $tag=$field->tag();
697                                 foreach my $subfield ($field->subfields) {
698                                         my ($subfcode,$subfvalue)=@$subfield;
699                                         next if ($tagslib->{$tag}->{$subfcode}->{tab} ne 10 
700                                                         && $tag        ne $itemtagfield 
701                                                         && $subfcode   ne $itemtagsubfield);
702
703                                         $witness{$subfcode} = $tagslib->{$tag}->{$subfcode}->{lib} if ($tagslib->{$tag}->{$subfcode}->{tab}  eq 10);
704                                         if ($tagslib->{$tag}->{$subfcode}->{tab}  eq 10) {
705                                                 $this_row{$subfcode}=GetAuthorisedValueDesc( $tag,
706                                                                         $subfcode, $subfvalue, '', $tagslib) 
707                                                                         || $subfvalue;
708                                         }
709
710                                         $this_row{itemnumber} = $subfvalue if ($tag eq $itemtagfield && $subfcode eq $itemtagsubfield);
711                                 }
712                         }
713
714             # grab title, author, and ISBN to identify bib that the item
715             # belongs to in the display
716             my $biblio = Koha::Biblios->find( $itemdata->{biblionumber} );
717             $this_row{title}        = $biblio->title;
718             $this_row{author}       = $biblio->author;
719             $this_row{isbn}         = $biblio->biblioitem->isbn;
720             $this_row{biblionumber} = $biblio->biblionumber;
721             $this_row{holds}        = $biblio->holds->count;
722             $this_row{item_holds}   = Koha::Holds->search( { itemnumber => $itemnumber } )->count;
723             $this_row{item}         = Koha::Items->find($itemnumber);
724
725                         if (%this_row) {
726                                 push(@big_array, \%this_row);
727                         }
728                 }
729                 @big_array = sort {$a->{0} cmp $b->{0}} @big_array;
730
731                 # now, construct template !
732                 # First, the existing items for display
733                 my @item_value_loop;
734                 my @witnesscodessorted=sort keys %witness;
735                 for my $row ( @big_array ) {
736                         my %row_data;
737                         my @item_fields = map +{ field => $_ || '' }, @$row{ @witnesscodessorted };
738                         $row_data{item_value} = [ @item_fields ];
739                         $row_data{itemnumber} = $row->{itemnumber};
740                         #reporting this_row values
741                         $row_data{'nomod'} = $row->{'nomod'};
742       $row_data{bibinfo} = $row->{bibinfo};
743       $row_data{author} = $row->{author};
744       $row_data{title} = $row->{title};
745       $row_data{isbn} = $row->{isbn};
746       $row_data{biblionumber} = $row->{biblionumber};
747       $row_data{holds}        = $row->{holds};
748       $row_data{item_holds}   = $row->{item_holds};
749       $row_data{item}         = $row->{item};
750       $row_data{safe_to_delete} = $row->{item}->safe_to_delete;
751       my $is_on_loan = C4::Circulation::IsItemIssued( $row->{itemnumber} );
752       $row_data{onloan} = $is_on_loan ? 1 : 0;
753                         push(@item_value_loop,\%row_data);
754                 }
755                 my @header_loop=map { { header_value=> $witness{$_}} } @witnesscodessorted;
756
757     my @cannot_be_deleted = map {
758         $_->{safe_to_delete} == 1 ? () : $_->{item}->barcode
759     } @item_value_loop;
760     return {
761         item_loop        => \@item_value_loop,
762         cannot_be_deleted => \@cannot_be_deleted,
763         item_header_loop => \@header_loop
764     };
765 }
766
767 #BE WARN : it is not the general case 
768 # This function can be OK in the item marc record special case
769 # Where subfield is not repeated
770 # And where we are sure that field should correspond
771 # And $tag>10
772 sub UpdateMarcWith {
773   my ($marcfrom,$marcto)=@_;
774     my (  $itemtag,   $itemtagsubfield) = &GetMarcFromKohaField( "items.itemnumber" );
775     my $fieldfrom=$marcfrom->field($itemtag);
776     my @fields_to=$marcto->field($itemtag);
777     my $modified = 0;
778
779     return $modified unless $fieldfrom;
780
781     foreach my $subfield ( $fieldfrom->subfields() ) {
782         foreach my $field_to_update ( @fields_to ) {
783             if ( $subfield->[1] ) {
784                 unless ( $field_to_update->subfield($subfield->[0]) eq $subfield->[1] ) {
785                     $modified++;
786                     $field_to_update->update( $subfield->[0] => $subfield->[1] );
787                 }
788             }
789             else {
790                 $modified++;
791                 $field_to_update->delete_subfield( code => $subfield->[0] );
792             }
793         }
794     }
795     return $modified;
796 }
797
798 sub find_value {
799     my ($tagfield,$insubfield,$record) = @_;
800     my $result;
801     my $indicator;
802     foreach my $field ($record->field($tagfield)) {
803         my @subfields = $field->subfields();
804         foreach my $subfield (@subfields) {
805             if (@$subfield[0] eq $insubfield) {
806                 $result .= @$subfield[1];
807                 $indicator = $field->indicator(1).$field->indicator(2);
808             }
809         }
810     }
811     return($indicator,$result);
812 }
813
814 # ----------------------------
815 # Background functions
816
817
818 sub add_results_to_template {
819     my $template = shift;
820     my $results = shift;
821     $template->param(map { $_ => $results->{$_} } keys %{ $results });
822 }
823
824 sub add_saved_job_results_to_template {
825     my $template = shift;
826     my $completedJobID = shift;
827     my $items_display_hashref= shift;
828     my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
829     my $results = $job->results();
830     add_results_to_template($template, $results);
831
832     my $fields = $job->get("modified_fields");
833     my $items = $job->get("modified_items");
834     my $extra_headers = $job->get("extra_headers");
835
836     foreach my $header (keys %{$extra_headers}) {
837         push @{$items_display_hashref->{item_header_loop}}, {header_value => $extra_headers->{$header}->{name}};
838         foreach my $row (@{$items_display_hashref->{item_loop}}) {
839             push @{$row->{item_value}}, {field => $extra_headers->{$header}->{items}->{$row->{itemnumber}}};
840         }
841     }
842
843     $template->param(
844         modified_items => $items,
845         modified_fields => $fields,
846     );
847 }
848
849 sub put_in_background {
850     my $job_size = shift;
851
852     my $job = C4::BackgroundJob->new($sessionID, "test", '/cgi-bin/koha/tools/batchMod.pl', $job_size);
853     my $jobID = $job->id();
854
855     # fork off
856     if (my $pid = fork) {
857         # parent
858         # return job ID as JSON
859
860         # prevent parent exiting from
861         # destroying the kid's database handle
862         # FIXME: according to DBI doc, this may not work for Oracle
863         $dbh->{InactiveDestroy}  = 1;
864
865         my $reply = CGI->new("");
866         print $reply->header(-type => 'text/html');
867         print '{"jobID":"' . $jobID . '"}';
868         exit 0;
869     } elsif (defined $pid) {
870         # child
871         # close STDOUT to signal to Apache that
872         # we're now running in the background
873         close STDOUT;
874         close STDERR;
875     } else {
876         # fork failed, so exit immediately
877         warn "fork failed while attempting to run tools/batchMod.pl as a background job";
878         exit 0;
879     }
880     return $job;
881 }
882
883
884