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