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