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