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