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