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