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