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