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