Bug 26351: Add plugin hooks to transform item barcodes
[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( barcodedecode 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
376             @barcodelist = map { barcodedecode( $_ ) } @barcodelist;
377
378             # Note: adding lc for case insensitivity
379             my %itemdata = map { lc($_->{barcode}) => $_->{itemnumber} } @{ Koha::Items->search({ barcode => \@barcodelist }, { columns => [ 'itemnumber', 'barcode' ] } )->unblessed };
380             @itemnumbers = map { exists $itemdata{lc $_} ? $itemdata{lc $_} : () } @barcodelist;
381             @notfoundbarcodes = grep { !exists $itemdata{lc $_} } @barcodelist;
382         }
383     }
384
385     # Flag to tell the template there are valid results, hidden or not
386     if(scalar(@itemnumbers) > 0){ $template->param("itemresults" => 1); }
387     # Only display the items if there are no more than pref MaxItemsToProcessForBatchMod or MaxItemsToDisplayForBatchDel
388     my $max_display_items = $del
389         ? C4::Context->preference("MaxItemsToDisplayForBatchDel")
390         : C4::Context->preference("MaxItemsToDisplayForBatchMod");
391     $template->param("too_many_items_process" => scalar(@itemnumbers)) if !$del && scalar(@itemnumbers) > C4::Context->preference("MaxItemsToProcessForBatchMod");
392     if (scalar(@itemnumbers) <= ( $max_display_items // 1000 ) ) {
393         $items_display_hashref=BuildItemsData(@itemnumbers);
394     } else {
395         $template->param("too_many_items_display" => scalar(@itemnumbers));
396         # Even if we do not display the items, we need the itemnumbers
397         $template->param(itemnumbers_array => \@itemnumbers);
398     }
399 # now, build the item form for entering a new item
400 my @loop_data =();
401 my $i=0;
402 my $branch_limit = C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
403
404 my $libraries = Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed;# build once ahead of time, instead of multiple times later.
405
406 # Adding a default choice, in case the user does not want to modify the branch
407 my $nochange_branch = { branchname => '', value => '', selected => 1 };
408 unshift (@$libraries, $nochange_branch);
409
410 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
411
412 # Getting list of subfields to keep when restricted batchmod edit is enabled
413 my $subfieldsToAllowForBatchmod = C4::Context->preference('SubfieldsToAllowForRestrictedBatchmod');
414 my $allowAllSubfields = (
415     not defined $subfieldsToAllowForBatchmod
416       or $subfieldsToAllowForBatchmod eq q||
417 ) ? 1 : 0;
418 my @subfieldsToAllow = split(/ /, $subfieldsToAllowForBatchmod);
419
420 foreach my $tag (sort keys %{$tagslib}) {
421     # loop through each subfield
422     foreach my $subfield (sort keys %{$tagslib->{$tag}}) {
423         next if IsMarcStructureInternal( $tagslib->{$tag}{$subfield} );
424         next if (not $allowAllSubfields and $restrictededition && !grep { $tag . '$' . $subfield eq $_ } @subfieldsToAllow );
425         next if ($tagslib->{$tag}->{$subfield}->{'tab'} ne "10");
426         # barcode is not meant to be batch-modified
427         next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.barcode';
428         my %subfield_data;
429  
430         my $index_subfield = int(rand(1000000)); 
431         if ($subfield eq '@'){
432             $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
433         } else {
434             $subfield_data{id} = "tag_".$tag."_subfield_".$subfield."_".$index_subfield;
435         }
436         $subfield_data{tag}        = $tag;
437         $subfield_data{subfield}   = $subfield;
438         $subfield_data{marc_lib}   ="<span id=\"error$i\" title=\"".$tagslib->{$tag}->{$subfield}->{lib}."\">".$tagslib->{$tag}->{$subfield}->{lib}."</span>";
439         $subfield_data{mandatory}  = $tagslib->{$tag}->{$subfield}->{mandatory};
440         $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
441     my $value;
442     if ( $use_default_values) {
443             $value = $tagslib->{$tag}->{$subfield}->{defaultvalue};
444             # get today date & replace YYYY, MM, DD if provided in the default value
445             my $today = dt_from_string;
446             my $year  = $today->year;
447             my $month = $today->month;
448             my $day   = $today->day;
449             $value =~ s/YYYY/$year/g;
450             $value =~ s/MM/$month/g;
451             $value =~ s/DD/$day/g;
452         }
453         $subfield_data{visibility} = "display:none;" if (($tagslib->{$tag}->{$subfield}->{hidden} > 4) || ($tagslib->{$tag}->{$subfield}->{hidden} < -4));
454     # testing branch value if IndependentBranches.
455
456         if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
457         my @authorised_values;
458         my %authorised_lib;
459         # builds list, depending on authorised value...
460
461     if ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "branches" ) {
462         foreach my $library (@$libraries) {
463             push @authorised_values, $library->{branchcode};
464             $authorised_lib{$library->{branchcode}} = $library->{branchname};
465         }
466         $value = "";
467     }
468     elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
469         push @authorised_values, "";
470         my $itemtypes = Koha::ItemTypes->search_with_localization;
471         while ( my $itemtype = $itemtypes->next ) {
472             push @authorised_values, $itemtype->itemtype;
473             $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description;
474         }
475         $value = "";
476
477           #---- class_sources
478       }
479       elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
480           push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
481             
482           my $class_sources = GetClassSources();
483           my $default_source = C4::Context->preference("DefaultClassificationSource");
484           
485           foreach my $class_source (sort keys %$class_sources) {
486               next unless $class_sources->{$class_source}->{'used'} or
487                           ($value and $class_source eq $value)      or
488                           ($class_source eq $default_source);
489               push @authorised_values, $class_source;
490               $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
491           }
492                   $value = '';
493
494           #---- "true" authorised value
495       }
496       else {
497           push @authorised_values, ""; # unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
498
499           my @avs = Koha::AuthorisedValues->search_with_library_limits(
500               {
501                   category   => $tagslib->{$tag}->{$subfield}->{authorised_value}
502               },
503               { order_by => 'lib' },
504               $branch_limit
505           );
506           for my $av ( @avs ) {
507               push @authorised_values, $av->authorised_value;
508               $authorised_lib{$av->authorised_value} = $av->lib;
509           }
510           $value="";
511       }
512         $subfield_data{marc_value} = {
513             type    => 'select',
514             id      => "tag_".$tag."_subfield_".$subfield."_".$index_subfield,
515             name    => "field_value",
516             values  => \@authorised_values,
517             labels  => \%authorised_lib,
518             default => $value,
519         };
520     # it's a thesaurus / authority field
521     }
522     elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode} ) {
523         $subfield_data{marc_value} = {
524             type         => 'text1',
525             id           => $subfield_data{id},
526             value        => $value,
527             authtypecode => $tagslib->{$tag}->{$subfield}->{authtypecode},
528         }
529     }
530     elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) { # plugin
531         require Koha::FrameworkPlugin;
532         my $plugin = Koha::FrameworkPlugin->new( {
533             name => $tagslib->{$tag}->{$subfield}->{'value_builder'},
534             item_style => 1,
535         });
536         my $temp;
537         my $pars= { dbh => $dbh, record => $temp, tagslib => $tagslib,
538             id => $subfield_data{id}, tabloop => \@loop_data };
539         $plugin->build( $pars );
540         if( !$plugin->errstr ) {
541             $subfield_data{marc_value} = {
542                 type       => 'text2',
543                 id         => $subfield_data{id},
544                 value      => $value,
545                 javascript => $plugin->javascript,
546                 noclick    => $plugin->noclick,
547             };
548         } else {
549             warn $plugin->errstr;
550             $subfield_data{marc_value} = { # supply default input form
551                 type       => 'text',
552                 id         => $subfield_data{id},
553                 value      => $value,
554             };
555         }
556     }
557     elsif ( $tag eq '' ) {       # it's an hidden field
558             $subfield_data{marc_value} = {
559                 type       => 'hidden',
560                 id         => $subfield_data{id},
561                 value      => $value,
562             };
563     }
564     elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) {   # FIXME: shouldn't input type be "hidden" ?
565         $subfield_data{marc_value} = {
566                 type       => 'text',
567                 id         => $subfield_data{id},
568                 value      => $value,
569         };
570     }
571     elsif ( length($value) > 100
572             or (C4::Context->preference("marcflavour") eq "UNIMARC" and
573                   300 <= $tag && $tag < 400 && $subfield eq 'a' )
574             or (C4::Context->preference("marcflavour") eq "MARC21"  and
575                   500 <= $tag && $tag < 600                     )
576           ) {
577         # oversize field (textarea)
578         $subfield_data{marc_value} = {
579                 type       => 'textarea',
580                 id         => $subfield_data{id},
581                 value      => $value,
582         };
583     } else {
584         # it's a standard field
585         $subfield_data{marc_value} = {
586                 type       => 'text',
587                 id         => $subfield_data{id},
588                 value      => $value,
589         };
590     }
591 #   $subfield_data{marc_value}="<input type=\"text\" name=\"field_value\">";
592     push (@loop_data, \%subfield_data);
593     $i++
594   }
595 } # -- End foreach tag
596
597
598
599     # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
600     $template->param(
601         item                => \@loop_data,
602         notfoundbarcodes    => \@notfoundbarcodes,
603         notfounditemnumbers => \@notfounditemnumbers
604     );
605     $nextop="action"
606 } # -- End action="show"
607
608 $template->param(%$items_display_hashref) if $items_display_hashref;
609 $template->param(
610     op      => $nextop,
611 );
612 $template->param( $op => 1 ) if $op;
613
614 if ($op eq "action") {
615
616     #my @not_deleted_loop = map{{itemnumber=>$_}}@not_deleted;
617
618     $template->param(
619         not_deleted_items => $not_deleted_items,
620         deleted_items => $deleted_items,
621         delete_records => $del_records,
622         deleted_records => $deleted_records,
623         not_deleted_loop => \@not_deleted 
624     );
625 }
626
627 foreach my $error (@errors) {
628     $template->param($error => 1) if $error;
629 }
630 $template->param(src => $src);
631 $template->param(biblionumber => $biblionumber);
632 output_html_with_http_headers $input, $cookie, $template->output;
633 exit;
634
635
636 # ---------------- Functions
637
638 sub BuildItemsData{
639         my @itemnumbers=@_;
640                 # now, build existiing item list
641                 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
642                 my @big_array;
643                 #---- finds where items.itemnumber is stored
644     my (  $itemtagfield,   $itemtagsubfield) = &GetMarcFromKohaField( "items.itemnumber" );
645     my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField( "items.homebranch" );
646                 foreach my $itemnumber (@itemnumbers){
647             my $itemdata = Koha::Items->find($itemnumber);
648             next unless $itemdata; # Should have been tested earlier, but just in case...
649             $itemdata = $itemdata->unblessed;
650                         my $itemmarc=Item2Marc($itemdata);
651                         my %this_row;
652                         foreach my $field (grep {$_->tag() eq $itemtagfield} $itemmarc->fields()) {
653                                 # loop through each subfield
654                                 my $itembranchcode=$field->subfield($branchtagsubfield);
655                 if ($itembranchcode && C4::Context->preference("IndependentBranches")) {
656                                                 #verifying rights
657                                                 my $userenv = C4::Context->userenv();
658                         unless (C4::Context->IsSuperLibrarian() or (($userenv->{'branch'} eq $itembranchcode))){
659                                                                 $this_row{'nomod'}=1;
660                                                 }
661                                 }
662                                 my $tag=$field->tag();
663                                 foreach my $subfield ($field->subfields) {
664                                         my ($subfcode,$subfvalue)=@$subfield;
665                                         next if ($tagslib->{$tag}->{$subfcode}->{tab} ne 10 
666                                                         && $tag        ne $itemtagfield 
667                                                         && $subfcode   ne $itemtagsubfield);
668
669                                         $witness{$subfcode} = $tagslib->{$tag}->{$subfcode}->{lib} if ($tagslib->{$tag}->{$subfcode}->{tab}  eq 10);
670                                         if ($tagslib->{$tag}->{$subfcode}->{tab}  eq 10) {
671                                                 $this_row{$subfcode}=GetAuthorisedValueDesc( $tag,
672                                                                         $subfcode, $subfvalue, '', $tagslib) 
673                                                                         || $subfvalue;
674                                         }
675
676                                         $this_row{itemnumber} = $subfvalue if ($tag eq $itemtagfield && $subfcode eq $itemtagsubfield);
677                                 }
678                         }
679
680             # grab title, author, and ISBN to identify bib that the item
681             # belongs to in the display
682             my $biblio = Koha::Biblios->find( $itemdata->{biblionumber} );
683             $this_row{title}        = $biblio->title;
684             $this_row{author}       = $biblio->author;
685             $this_row{isbn}         = $biblio->biblioitem->isbn;
686             $this_row{biblionumber} = $biblio->biblionumber;
687             $this_row{holds}        = $biblio->holds->count;
688             $this_row{item_holds}   = Koha::Holds->search( { itemnumber => $itemnumber } )->count;
689             $this_row{item}         = Koha::Items->find($itemnumber);
690
691                         if (%this_row) {
692                                 push(@big_array, \%this_row);
693                         }
694                 }
695                 @big_array = sort {$a->{0} cmp $b->{0}} @big_array;
696
697                 # now, construct template !
698                 # First, the existing items for display
699                 my @item_value_loop;
700                 my @witnesscodessorted=sort keys %witness;
701                 for my $row ( @big_array ) {
702                         my %row_data;
703                         my @item_fields = map +{ field => $_ || '' }, @$row{ @witnesscodessorted };
704                         $row_data{item_value} = [ @item_fields ];
705                         $row_data{itemnumber} = $row->{itemnumber};
706                         #reporting this_row values
707                         $row_data{'nomod'} = $row->{'nomod'};
708       $row_data{bibinfo} = $row->{bibinfo};
709       $row_data{author} = $row->{author};
710       $row_data{title} = $row->{title};
711       $row_data{isbn} = $row->{isbn};
712       $row_data{biblionumber} = $row->{biblionumber};
713       $row_data{holds}        = $row->{holds};
714       $row_data{item_holds}   = $row->{item_holds};
715       $row_data{item}         = $row->{item};
716       $row_data{safe_to_delete} = $row->{item}->safe_to_delete;
717       my $is_on_loan = C4::Circulation::IsItemIssued( $row->{itemnumber} );
718       $row_data{onloan} = $is_on_loan ? 1 : 0;
719                         push(@item_value_loop,\%row_data);
720                 }
721                 my @header_loop=map { { header_value=> $witness{$_}} } @witnesscodessorted;
722
723     my @cannot_be_deleted = map {
724         $_->{safe_to_delete} == 1 ? () : $_->{item}->barcode
725     } @item_value_loop;
726     return {
727         item_loop        => \@item_value_loop,
728         cannot_be_deleted => \@cannot_be_deleted,
729         item_header_loop => \@header_loop
730     };
731 }
732
733 #BE WARN : it is not the general case 
734 # This function can be OK in the item marc record special case
735 # Where subfield is not repeated
736 # And where we are sure that field should correspond
737 # And $tag>10
738 sub UpdateMarcWith {
739   my ($marcfrom,$marcto)=@_;
740     my (  $itemtag,   $itemtagsubfield) = &GetMarcFromKohaField( "items.itemnumber" );
741     my $fieldfrom=$marcfrom->field($itemtag);
742     my @fields_to=$marcto->field($itemtag);
743     my $modified = 0;
744
745     return $modified unless $fieldfrom;
746
747     foreach my $subfield ( $fieldfrom->subfields() ) {
748         foreach my $field_to_update ( @fields_to ) {
749             if ( $subfield->[1] ) {
750                 unless ( $field_to_update->subfield($subfield->[0]) eq $subfield->[1] ) {
751                     $modified++;
752                     $field_to_update->update( $subfield->[0] => $subfield->[1] );
753                 }
754             }
755             else {
756                 $modified++;
757                 $field_to_update->delete_subfield( code => $subfield->[0] );
758             }
759         }
760     }
761     return $modified;
762 }