Bug 28158: Remove additional backgroundjob related code
[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 $completedJobID = $input->param('completedJobID');
58 my $src          = $input->param('src');
59 my $use_default_values = $input->param('use_default_values');
60 my $exclude_from_local_holds_priority = $input->param('exclude_from_local_holds_priority');
61
62 my $template_name;
63 my $template_flag;
64 if (!defined $op) {
65     $template_name = "tools/batchMod.tt";
66     $template_flag = { tools => '*' };
67     $op = q{};
68 } else {
69     $template_name = ($del) ? "tools/batchMod-del.tt" : "tools/batchMod-edit.tt";
70     $template_flag = ($del) ? { tools => 'items_batchdel' }   : { tools => 'items_batchmod' };
71 }
72
73 my ($template, $loggedinuser, $cookie)
74     = get_template_and_user({template_name => $template_name,
75                  query => $input,
76                  type => "intranet",
77                  flagsrequired => $template_flag,
78                  });
79
80 $template->param( searchid => scalar $input->param('searchid'), );
81
82 # Does the user have a restricted item edition permission?
83 my $uid = $loggedinuser ? Koha::Patrons->find( $loggedinuser )->userid : undef;
84 my $restrictededition = $uid ? haspermission($uid,  {'tools' => 'items_batchmod_restricted'}) : undef;
85 # In case user is a superlibrarian, edition is not restricted
86 $restrictededition = 0 if ($restrictededition != 0 && C4::Context->IsSuperLibrarian());
87
88 $template->param(del       => $del);
89
90 my $nextop="";
91 my @errors; # store errors found while checking data BEFORE saving item.
92 my $items_display_hashref;
93 our $tagslib = &GetMarcStructure(1);
94
95 my $deleted_items = 0;     # Number of deleted items
96 my $deleted_records = 0;   # Number of deleted records ( with no items attached )
97 my $not_deleted_items = 0; # Number of items that could not be deleted
98 my @not_deleted;           # List of the itemnumbers that could not be deleted
99 my $modified_items = 0;    # Numbers of modified items
100 my $modified_fields = 0;   # Numbers of modified fields
101
102 my %cookies = parse CGI::Cookie($cookie);
103 my $sessionID = $cookies{'CGISESSID'}->value;
104
105
106 #--- ----------------------------------------------------------------------------
107 if ($op eq "action") {
108 #-------------------------------------------------------------------------------
109     my @tags      = $input->multi_param('tag');
110     my @subfields = $input->multi_param('subfield');
111     my @values    = $input->multi_param('field_value');
112     my @searches  = $input->multi_param('regex_search');
113     my @replaces  = $input->multi_param('regex_replace');
114     my @modifiers = $input->multi_param('regex_modifiers');
115     my @disabled  = $input->multi_param('disable_input');
116     # build indicator hash.
117     my @ind_tag   = $input->multi_param('ind_tag');
118     my @indicator = $input->multi_param('indicator');
119
120     # Is there something to modify ?
121     # TODO : We shall use this var to warn the user in case no modification was done to the items
122     my $values_to_modify = scalar(grep {!/^$/} @values) || scalar(grep {!/^$/} @searches);
123     my $values_to_blank  = scalar(@disabled);
124
125     my $marcitem;
126
127     # Once the job is done
128     if ($completedJobID) {
129         # If we have a reasonable amount of items, we display them
130     my $max_items = $del ? C4::Context->preference("MaxItemsToDisplayForBatchDel") : C4::Context->preference("MaxItemsToDisplayForBatchMod");
131     if (scalar(@itemnumbers) <= $max_items ){
132         if (scalar(@itemnumbers) <= 1000 ) {
133             $items_display_hashref=BuildItemsData(@itemnumbers);
134         } else {
135             # Else, we only display the barcode
136             my @simple_items_display = map {
137                 my $itemnumber = $_;
138                 my $item = Koha::Items->find($itemnumber);
139                 {
140                     itemnumber   => $itemnumber,
141                     barcode      => $item ? ( $item->barcode // q{} ) : q{},
142                     biblionumber => $item ? $item->biblio->biblionumber : q{},
143                 };
144             } @itemnumbers;
145             $template->param("simple_items_display" => \@simple_items_display);
146         }
147     } else {
148         $template->param( "too_many_items_display" => scalar(@itemnumbers) );
149         $template->param( "job_completed" => 1 );
150     }
151
152     } else {
153     # While the job is getting done
154
155         #initializing values for updates
156     my (  $itemtagfield,   $itemtagsubfield) = &GetMarcFromKohaField( "items.itemnumber" );
157         if ($values_to_modify){
158             my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
159             $marcitem = MARC::Record::new_from_xml($xml, 'UTF-8');
160         }
161         if ($values_to_blank){
162             foreach my $disabledsubf (@disabled){
163                 if ($marcitem && $marcitem->field($itemtagfield)){
164                     $marcitem->field($itemtagfield)->update( $disabledsubf => "" );
165                 }
166                 else {
167                     $marcitem = MARC::Record->new();
168                     $marcitem->append_fields( MARC::Field->new( $itemtagfield, '', '', $disabledsubf => "" ) );
169                 }
170             }
171         }
172
173         my $upd_biblionumbers;
174         my $del_biblionumbers;
175         try {
176             my $schema = Koha::Database->new->schema;
177             $schema->txn_do(
178                 sub {
179                     # For each item
180                     my $i = 1;
181                     foreach my $itemnumber (@itemnumbers) {
182                         my $item = Koha::Items->find($itemnumber);
183                         next
184                           unless $item
185                           ; # Should have been tested earlier, but just in case...
186                         my $itemdata = $item->unblessed;
187                         if ($del) {
188                             my $return = $item->safe_delete;
189                             if ( ref( $return ) ) {
190                                 $deleted_items++;
191                                 push @$upd_biblionumbers, $itemdata->{'biblionumber'};
192                             }
193                             else {
194                                 $not_deleted_items++;
195                                 push @not_deleted,
196                                   {
197                                     biblionumber => $itemdata->{'biblionumber'},
198                                     itemnumber   => $itemdata->{'itemnumber'},
199                                     barcode      => $itemdata->{'barcode'},
200                                     title        => $itemdata->{'title'},
201                                     reason       => $return,
202                                   };
203                             }
204
205                             # If there are no items left, delete the biblio
206                             if ($del_records) {
207                                 my $itemscount = Koha::Biblios->find( $itemdata->{'biblionumber'} )->items->count;
208                                 if ( $itemscount == 0 ) {
209                                     my $error = DelBiblio( $itemdata->{'biblionumber'}, { skip_record_index => 1 } );
210                                     unless ($error) {
211                                         $deleted_records++;
212                                         push @$del_biblionumbers, $itemdata->{'biblionumber'};
213                                         if ( $src eq 'CATALOGUING' ) {
214                                             # We are coming catalogue/detail.pl, there were items from a single bib record
215                                             $template->param( biblio_deleted => 1 );
216                                         }
217                                     }
218                                 }
219                             }
220                         }
221                         else {
222                             my $modified_holds_priority = 0;
223                             if ( defined $exclude_from_local_holds_priority && $exclude_from_local_holds_priority ne "" ) {
224                                 if(!defined $item->exclude_from_local_holds_priority || $item->exclude_from_local_holds_priority != $exclude_from_local_holds_priority) {
225                                 $item->exclude_from_local_holds_priority($exclude_from_local_holds_priority)->store;
226                                 $modified_holds_priority = 1;
227                             }
228                             }
229                             my $modified = 0;
230                             if ( $values_to_modify || $values_to_blank ) {
231                                 my $localmarcitem = Item2Marc($itemdata);
232
233                                 for ( my $i = 0 ; $i < @tags ; $i++ ) {
234                                     my $search = $searches[$i];
235                                     next unless $search;
236
237                                     my $tag = $tags[$i];
238                                     my $subfield = $subfields[$i];
239                                     my $replace = $replaces[$i];
240
241                                     my $value = $localmarcitem->field( $tag )->subfield( $subfield );
242                                     my $old_value = $value;
243
244                                     my @available_modifiers = qw( i g );
245                                     my $retained_modifiers = q||;
246                                     for my $modifier ( split //, $modifiers[$i] ) {
247                                         $retained_modifiers .= $modifier
248                                             if grep {/$modifier/} @available_modifiers;
249                                     }
250                                     if ( $retained_modifiers =~ m/^(ig|gi)$/ ) {
251                                         $value =~ s/$search/$replace/ig;
252                                     }
253                                     elsif ( $retained_modifiers eq 'i' ) {
254                                         $value =~ s/$search/$replace/i;
255                                     }
256                                     elsif ( $retained_modifiers eq 'g' ) {
257                                         $value =~ s/$search/$replace/g;
258                                     }
259                                     else {
260                                         $value =~ s/$search/$replace/;
261                                     }
262
263                                     my @fields_to = $localmarcitem->field($tag);
264                                     foreach my $field_to_update ( @fields_to ) {
265                                         unless ( $old_value eq $value ) {
266                                             $modified++;
267                                             $field_to_update->update( $subfield => $value );
268                                         }
269                                     }
270                                 }
271
272                                 $modified += UpdateMarcWith( $marcitem, $localmarcitem );
273                                 if ($modified) {
274                                     eval {
275                                         if (
276                                             my $item = ModItemFromMarc(
277                                                 $localmarcitem,
278                                                 $itemdata->{biblionumber},
279                                                 $itemnumber,
280                                                 { skip_record_index => 1 },
281                                             )
282                                           )
283                                         {
284                                             LostItem(
285                                                 $itemnumber,
286                                                 'batchmod',
287                                                 undef,
288                                                 { skip_record_index => 1 }
289                                             ) if $item->{itemlost}
290                                               and not $itemdata->{itemlost};
291                                         }
292                                     };
293                                     push @$upd_biblionumbers, $itemdata->{'biblionumber'};
294                                 }
295                             }
296                             $modified_items++ if $modified || $modified_holds_priority;
297                             $modified_fields += $modified + $modified_holds_priority;
298                         }
299                         $i++;
300                     }
301                     if (@not_deleted) {
302                         Koha::Exceptions::Exception->throw(
303                             'Some items have not been deleted, rolling back');
304                     }
305                 }
306             );
307         }
308         catch {
309             if ( $_->isa('Koha::Exceptions::Exception') ) {
310                 $template->param( deletion_failed => 1 );
311             }
312             die "Something terrible has happened!"
313                 if ($_ =~ /Rollback failed/); # Rollback failed
314         };
315         $upd_biblionumbers = [ uniq @$upd_biblionumbers ]; # Only update each bib once
316
317         # Don't send specialUpdate for records we are going to delete
318         my %del_bib_hash = map{ $_ => undef } @$del_biblionumbers;
319         @$upd_biblionumbers = grep( ! exists( $del_bib_hash{$_} ), @$upd_biblionumbers );
320
321         my $indexer = Koha::SearchEngine::Indexer->new({ index => $Koha::SearchEngine::BIBLIOS_INDEX });
322         $indexer->index_records( $upd_biblionumbers, 'specialUpdate', "biblioserver", undef ) if @$upd_biblionumbers;
323         $indexer->index_records( $del_biblionumbers, 'recordDelete', "biblioserver", undef ) if @$del_biblionumbers;
324     }
325
326     # Calling the template
327     $template->param(
328         modified_items => $modified_items,
329         modified_fields => $modified_fields,
330     );
331
332 }
333 #
334 #-------------------------------------------------------------------------------
335 # build screen with existing items. and "new" one
336 #-------------------------------------------------------------------------------
337
338 if ($op eq "show"){
339     my $filefh = $input->upload('uploadfile');
340     my $filecontent = $input->param('filecontent');
341     my ( @notfoundbarcodes, @notfounditemnumbers);
342
343     my $split_chars = C4::Context->preference('BarcodeSeparators');
344     if ($filefh){
345         binmode $filefh, ':encoding(UTF-8)';
346         my @contentlist;
347         while (my $content=<$filefh>){
348             $content =~ s/[\r\n]*$//;
349             push @contentlist, $content if $content;
350         }
351
352         if ($filecontent eq 'barcode_file') {
353             @contentlist = grep /\S/, ( map { split /[$split_chars]/ } @contentlist );
354             @contentlist = uniq @contentlist;
355             # Note: adding lc for case insensitivity
356             my %itemdata = map { lc($_->{barcode}) => $_->{itemnumber} } @{ Koha::Items->search({ barcode => \@contentlist }, { columns => [ 'itemnumber', 'barcode' ] } )->unblessed };
357             @itemnumbers = map { exists $itemdata{lc $_} ? $itemdata{lc $_} : () } @contentlist;
358             @notfoundbarcodes = grep { !exists $itemdata{lc $_} } @contentlist;
359         }
360         elsif ( $filecontent eq 'itemid_file') {
361             @contentlist = uniq @contentlist;
362             my %itemdata = map { $_->{itemnumber} => 1 } @{ Koha::Items->search({ itemnumber => \@contentlist }, { columns => [ 'itemnumber' ] } )->unblessed };
363             @itemnumbers = grep { exists $itemdata{$_} } @contentlist;
364             @notfounditemnumbers = grep { !exists $itemdata{$_} } @contentlist;
365         }
366     } else {
367         if (defined $biblionumber && !@itemnumbers){
368             my @all_items = GetItemsInfo( $biblionumber );
369             foreach my $itm (@all_items) {
370                 push @itemnumbers, $itm->{itemnumber};
371             }
372         }
373         if ( my $list = $input->param('barcodelist') ) {
374             my @barcodelist = grep /\S/, ( split /[$split_chars]/, $list );
375             @barcodelist = uniq @barcodelist;
376             # Note: adding lc for case insensitivity
377             my %itemdata = map { lc($_->{barcode}) => $_->{itemnumber} } @{ Koha::Items->search({ barcode => \@barcodelist }, { columns => [ 'itemnumber', 'barcode' ] } )->unblessed };
378             @itemnumbers = map { exists $itemdata{lc $_} ? $itemdata{lc $_} : () } @barcodelist;
379             @notfoundbarcodes = grep { !exists $itemdata{lc $_} } @barcodelist;
380         }
381     }
382
383     # Flag to tell the template there are valid results, hidden or not
384     if(scalar(@itemnumbers) > 0){ $template->param("itemresults" => 1); }
385     # Only display the items if there are no more than pref MaxItemsToProcessForBatchMod or MaxItemsToDisplayForBatchDel
386     my $max_display_items = $del
387         ? C4::Context->preference("MaxItemsToDisplayForBatchDel")
388         : C4::Context->preference("MaxItemsToDisplayForBatchMod");
389     $template->param("too_many_items_process" => scalar(@itemnumbers)) if !$del && scalar(@itemnumbers) > C4::Context->preference("MaxItemsToProcessForBatchMod");
390     if (scalar(@itemnumbers) <= ( $max_display_items // 1000 ) ) {
391         $items_display_hashref=BuildItemsData(@itemnumbers);
392     } else {
393         $template->param("too_many_items_display" => scalar(@itemnumbers));
394         # Even if we do not display the items, we need the itemnumbers
395         $template->param(itemnumbers_array => \@itemnumbers);
396     }
397 # now, build the item form for entering a new item
398 my @loop_data =();
399 my $i=0;
400 my $branch_limit = C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
401
402 my $libraries = Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed;# build once ahead of time, instead of multiple times later.
403
404 # Adding a default choice, in case the user does not want to modify the branch
405 my $nochange_branch = { branchname => '', value => '', selected => 1 };
406 unshift (@$libraries, $nochange_branch);
407
408 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
409
410 # Getting list of subfields to keep when restricted batchmod edit is enabled
411 my $subfieldsToAllowForBatchmod = C4::Context->preference('SubfieldsToAllowForRestrictedBatchmod');
412 my $allowAllSubfields = (
413     not defined $subfieldsToAllowForBatchmod
414       or $subfieldsToAllowForBatchmod eq q||
415 ) ? 1 : 0;
416 my @subfieldsToAllow = split(/ /, $subfieldsToAllowForBatchmod);
417
418 foreach my $tag (sort keys %{$tagslib}) {
419     # loop through each subfield
420     foreach my $subfield (sort keys %{$tagslib->{$tag}}) {
421         next if IsMarcStructureInternal( $tagslib->{$tag}{$subfield} );
422         next if (not $allowAllSubfields and $restrictededition && !grep { $tag . '$' . $subfield eq $_ } @subfieldsToAllow );
423         next if ($tagslib->{$tag}->{$subfield}->{'tab'} ne "10");
424         # barcode is not meant to be batch-modified
425         next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.barcode';
426         my %subfield_data;
427  
428         my $index_subfield = int(rand(1000000)); 
429         if ($subfield eq '@'){
430             $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
431         } else {
432             $subfield_data{id} = "tag_".$tag."_subfield_".$subfield."_".$index_subfield;
433         }
434         $subfield_data{tag}        = $tag;
435         $subfield_data{subfield}   = $subfield;
436         $subfield_data{marc_lib}   ="<span id=\"error$i\" title=\"".$tagslib->{$tag}->{$subfield}->{lib}."\">".$tagslib->{$tag}->{$subfield}->{lib}."</span>";
437         $subfield_data{mandatory}  = $tagslib->{$tag}->{$subfield}->{mandatory};
438         $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
439     my $value;
440     if ( $use_default_values) {
441             $value = $tagslib->{$tag}->{$subfield}->{defaultvalue};
442             # get today date & replace YYYY, MM, DD if provided in the default value
443             my $today = dt_from_string;
444             my $year  = $today->year;
445             my $month = $today->month;
446             my $day   = $today->day;
447             $value =~ s/YYYY/$year/g;
448             $value =~ s/MM/$month/g;
449             $value =~ s/DD/$day/g;
450         }
451         $subfield_data{visibility} = "display:none;" if (($tagslib->{$tag}->{$subfield}->{hidden} > 4) || ($tagslib->{$tag}->{$subfield}->{hidden} < -4));
452     # testing branch value if IndependentBranches.
453
454         if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
455         my @authorised_values;
456         my %authorised_lib;
457         # builds list, depending on authorised value...
458
459     if ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "branches" ) {
460         foreach my $library (@$libraries) {
461             push @authorised_values, $library->{branchcode};
462             $authorised_lib{$library->{branchcode}} = $library->{branchname};
463         }
464         $value = "";
465     }
466     elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
467         push @authorised_values, "";
468         my $itemtypes = Koha::ItemTypes->search_with_localization;
469         while ( my $itemtype = $itemtypes->next ) {
470             push @authorised_values, $itemtype->itemtype;
471             $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description;
472         }
473         $value = "";
474
475           #---- class_sources
476       }
477       elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
478           push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
479             
480           my $class_sources = GetClassSources();
481           my $default_source = C4::Context->preference("DefaultClassificationSource");
482           
483           foreach my $class_source (sort keys %$class_sources) {
484               next unless $class_sources->{$class_source}->{'used'} or
485                           ($value and $class_source eq $value)      or
486                           ($class_source eq $default_source);
487               push @authorised_values, $class_source;
488               $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
489           }
490                   $value = '';
491
492           #---- "true" authorised value
493       }
494       else {
495           push @authorised_values, ""; # unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
496
497           my @avs = Koha::AuthorisedValues->search({ category => $tagslib->{$tag}->{$subfield}->{authorised_value}, branchcode => $branch_limit },{order_by=>'lib'});
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       my $is_on_loan = C4::Circulation::IsItemIssued( $row->{itemnumber} );
709       $row_data{onloan} = $is_on_loan ? 1 : 0;
710                         push(@item_value_loop,\%row_data);
711                 }
712                 my @header_loop=map { { header_value=> $witness{$_}} } @witnesscodessorted;
713
714         return { item_loop        => \@item_value_loop, item_header_loop => \@header_loop };
715 }
716
717 #BE WARN : it is not the general case 
718 # This function can be OK in the item marc record special case
719 # Where subfield is not repeated
720 # And where we are sure that field should correspond
721 # And $tag>10
722 sub UpdateMarcWith {
723   my ($marcfrom,$marcto)=@_;
724     my (  $itemtag,   $itemtagsubfield) = &GetMarcFromKohaField( "items.itemnumber" );
725     my $fieldfrom=$marcfrom->field($itemtag);
726     my @fields_to=$marcto->field($itemtag);
727     my $modified = 0;
728
729     return $modified unless $fieldfrom;
730
731     foreach my $subfield ( $fieldfrom->subfields() ) {
732         foreach my $field_to_update ( @fields_to ) {
733             if ( $subfield->[1] ) {
734                 unless ( $field_to_update->subfield($subfield->[0]) eq $subfield->[1] ) {
735                     $modified++;
736                     $field_to_update->update( $subfield->[0] => $subfield->[1] );
737                 }
738             }
739             else {
740                 $modified++;
741                 $field_to_update->delete_subfield( code => $subfield->[0] );
742             }
743         }
744     }
745     return $modified;
746 }
747
748 sub find_value {
749     my ($tagfield,$insubfield,$record) = @_;
750     my $result;
751     my $indicator;
752     foreach my $field ($record->field($tagfield)) {
753         my @subfields = $field->subfields();
754         foreach my $subfield (@subfields) {
755             if (@$subfield[0] eq $insubfield) {
756                 $result .= @$subfield[1];
757                 $indicator = $field->indicator(1).$field->indicator(2);
758             }
759         }
760     }
761     return($indicator,$result);
762 }