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