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