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