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