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