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_with_library_limits(
498               {
499                   category   => $tagslib->{$tag}->{$subfield}->{authorised_value}
500               },
501               { order_by => 'lib' },
502               $branch_limit
503           );
504           for my $av ( @avs ) {
505               push @authorised_values, $av->authorised_value;
506               $authorised_lib{$av->authorised_value} = $av->lib;
507           }
508           $value="";
509       }
510         $subfield_data{marc_value} = {
511             type    => 'select',
512             id      => "tag_".$tag."_subfield_".$subfield."_".$index_subfield,
513             name    => "field_value",
514             values  => \@authorised_values,
515             labels  => \%authorised_lib,
516             default => $value,
517         };
518     # it's a thesaurus / authority field
519     }
520     elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode} ) {
521         $subfield_data{marc_value} = {
522             type         => 'text1',
523             id           => $subfield_data{id},
524             value        => $value,
525             authtypecode => $tagslib->{$tag}->{$subfield}->{authtypecode},
526         }
527     }
528     elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) { # plugin
529         require Koha::FrameworkPlugin;
530         my $plugin = Koha::FrameworkPlugin->new( {
531             name => $tagslib->{$tag}->{$subfield}->{'value_builder'},
532             item_style => 1,
533         });
534         my $temp;
535         my $pars= { dbh => $dbh, record => $temp, tagslib => $tagslib,
536             id => $subfield_data{id}, tabloop => \@loop_data };
537         $plugin->build( $pars );
538         if( !$plugin->errstr ) {
539             $subfield_data{marc_value} = {
540                 type       => 'text2',
541                 id         => $subfield_data{id},
542                 value      => $value,
543                 javascript => $plugin->javascript,
544                 noclick    => $plugin->noclick,
545             };
546         } else {
547             warn $plugin->errstr;
548             $subfield_data{marc_value} = { # supply default input form
549                 type       => 'text',
550                 id         => $subfield_data{id},
551                 value      => $value,
552             };
553         }
554     }
555     elsif ( $tag eq '' ) {       # it's an hidden field
556             $subfield_data{marc_value} = {
557                 type       => 'hidden',
558                 id         => $subfield_data{id},
559                 value      => $value,
560             };
561     }
562     elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) {   # FIXME: shouldn't input type be "hidden" ?
563         $subfield_data{marc_value} = {
564                 type       => 'text',
565                 id         => $subfield_data{id},
566                 value      => $value,
567         };
568     }
569     elsif ( length($value) > 100
570             or (C4::Context->preference("marcflavour") eq "UNIMARC" and
571                   300 <= $tag && $tag < 400 && $subfield eq 'a' )
572             or (C4::Context->preference("marcflavour") eq "MARC21"  and
573                   500 <= $tag && $tag < 600                     )
574           ) {
575         # oversize field (textarea)
576         $subfield_data{marc_value} = {
577                 type       => 'textarea',
578                 id         => $subfield_data{id},
579                 value      => $value,
580         };
581     } else {
582         # it's a standard field
583         $subfield_data{marc_value} = {
584                 type       => 'text',
585                 id         => $subfield_data{id},
586                 value      => $value,
587         };
588     }
589 #   $subfield_data{marc_value}="<input type=\"text\" name=\"field_value\">";
590     push (@loop_data, \%subfield_data);
591     $i++
592   }
593 } # -- End foreach tag
594
595
596
597     # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
598     $template->param(
599         item                => \@loop_data,
600         notfoundbarcodes    => \@notfoundbarcodes,
601         notfounditemnumbers => \@notfounditemnumbers
602     );
603     $nextop="action"
604 } # -- End action="show"
605
606 $template->param(%$items_display_hashref) if $items_display_hashref;
607 $template->param(
608     op      => $nextop,
609 );
610 $template->param( $op => 1 ) if $op;
611
612 if ($op eq "action") {
613
614     #my @not_deleted_loop = map{{itemnumber=>$_}}@not_deleted;
615
616     $template->param(
617         not_deleted_items => $not_deleted_items,
618         deleted_items => $deleted_items,
619         delete_records => $del_records,
620         deleted_records => $deleted_records,
621         not_deleted_loop => \@not_deleted 
622     );
623 }
624
625 foreach my $error (@errors) {
626     $template->param($error => 1) if $error;
627 }
628 $template->param(src => $src);
629 $template->param(biblionumber => $biblionumber);
630 output_html_with_http_headers $input, $cookie, $template->output;
631 exit;
632
633
634 # ---------------- Functions
635
636 sub BuildItemsData{
637         my @itemnumbers=@_;
638                 # now, build existiing item list
639                 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
640                 my @big_array;
641                 #---- finds where items.itemnumber is stored
642     my (  $itemtagfield,   $itemtagsubfield) = &GetMarcFromKohaField( "items.itemnumber" );
643     my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField( "items.homebranch" );
644                 foreach my $itemnumber (@itemnumbers){
645             my $itemdata = Koha::Items->find($itemnumber);
646             next unless $itemdata; # Should have been tested earlier, but just in case...
647             $itemdata = $itemdata->unblessed;
648                         my $itemmarc=Item2Marc($itemdata);
649                         my %this_row;
650                         foreach my $field (grep {$_->tag() eq $itemtagfield} $itemmarc->fields()) {
651                                 # loop through each subfield
652                                 my $itembranchcode=$field->subfield($branchtagsubfield);
653                 if ($itembranchcode && C4::Context->preference("IndependentBranches")) {
654                                                 #verifying rights
655                                                 my $userenv = C4::Context->userenv();
656                         unless (C4::Context->IsSuperLibrarian() or (($userenv->{'branch'} eq $itembranchcode))){
657                                                                 $this_row{'nomod'}=1;
658                                                 }
659                                 }
660                                 my $tag=$field->tag();
661                                 foreach my $subfield ($field->subfields) {
662                                         my ($subfcode,$subfvalue)=@$subfield;
663                                         next if ($tagslib->{$tag}->{$subfcode}->{tab} ne 10 
664                                                         && $tag        ne $itemtagfield 
665                                                         && $subfcode   ne $itemtagsubfield);
666
667                                         $witness{$subfcode} = $tagslib->{$tag}->{$subfcode}->{lib} if ($tagslib->{$tag}->{$subfcode}->{tab}  eq 10);
668                                         if ($tagslib->{$tag}->{$subfcode}->{tab}  eq 10) {
669                                                 $this_row{$subfcode}=GetAuthorisedValueDesc( $tag,
670                                                                         $subfcode, $subfvalue, '', $tagslib) 
671                                                                         || $subfvalue;
672                                         }
673
674                                         $this_row{itemnumber} = $subfvalue if ($tag eq $itemtagfield && $subfcode eq $itemtagsubfield);
675                                 }
676                         }
677
678             # grab title, author, and ISBN to identify bib that the item
679             # belongs to in the display
680             my $biblio = Koha::Biblios->find( $itemdata->{biblionumber} );
681             $this_row{title}        = $biblio->title;
682             $this_row{author}       = $biblio->author;
683             $this_row{isbn}         = $biblio->biblioitem->isbn;
684             $this_row{biblionumber} = $biblio->biblionumber;
685             $this_row{holds}        = $biblio->holds->count;
686             $this_row{item_holds}   = Koha::Holds->search( { itemnumber => $itemnumber } )->count;
687             $this_row{item}         = Koha::Items->find($itemnumber);
688
689                         if (%this_row) {
690                                 push(@big_array, \%this_row);
691                         }
692                 }
693                 @big_array = sort {$a->{0} cmp $b->{0}} @big_array;
694
695                 # now, construct template !
696                 # First, the existing items for display
697                 my @item_value_loop;
698                 my @witnesscodessorted=sort keys %witness;
699                 for my $row ( @big_array ) {
700                         my %row_data;
701                         my @item_fields = map +{ field => $_ || '' }, @$row{ @witnesscodessorted };
702                         $row_data{item_value} = [ @item_fields ];
703                         $row_data{itemnumber} = $row->{itemnumber};
704                         #reporting this_row values
705                         $row_data{'nomod'} = $row->{'nomod'};
706       $row_data{bibinfo} = $row->{bibinfo};
707       $row_data{author} = $row->{author};
708       $row_data{title} = $row->{title};
709       $row_data{isbn} = $row->{isbn};
710       $row_data{biblionumber} = $row->{biblionumber};
711       $row_data{holds}        = $row->{holds};
712       $row_data{item_holds}   = $row->{item_holds};
713       $row_data{item}         = $row->{item};
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         return { item_loop        => \@item_value_loop, item_header_loop => \@header_loop };
721 }
722
723 #BE WARN : it is not the general case 
724 # This function can be OK in the item marc record special case
725 # Where subfield is not repeated
726 # And where we are sure that field should correspond
727 # And $tag>10
728 sub UpdateMarcWith {
729   my ($marcfrom,$marcto)=@_;
730     my (  $itemtag,   $itemtagsubfield) = &GetMarcFromKohaField( "items.itemnumber" );
731     my $fieldfrom=$marcfrom->field($itemtag);
732     my @fields_to=$marcto->field($itemtag);
733     my $modified = 0;
734
735     return $modified unless $fieldfrom;
736
737     foreach my $subfield ( $fieldfrom->subfields() ) {
738         foreach my $field_to_update ( @fields_to ) {
739             if ( $subfield->[1] ) {
740                 unless ( $field_to_update->subfield($subfield->[0]) eq $subfield->[1] ) {
741                     $modified++;
742                     $field_to_update->update( $subfield->[0] => $subfield->[1] );
743                 }
744             }
745             else {
746                 $modified++;
747                 $field_to_update->delete_subfield( code => $subfield->[0] );
748             }
749         }
750     }
751     return $modified;
752 }
753
754 sub find_value {
755     my ($tagfield,$insubfield,$record) = @_;
756     my $result;
757     my $indicator;
758     foreach my $field ($record->field($tagfield)) {
759         my @subfields = $field->subfields();
760         foreach my $subfield (@subfields) {
761             if (@$subfield[0] eq $insubfield) {
762                 $result .= @$subfield[1];
763                 $indicator = $field->indicator(1).$field->indicator(2);
764             }
765         }
766     }
767     return($indicator,$result);
768 }