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