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