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