Merge remote-tracking branch 'origin/new/bug_7458'
[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', 'CHARGE FEE') 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           $value="";
350       }
351       $subfield_data{marc_value} =CGI::scrolling_list(      # FIXME: factor out scrolling_list
352           -name     => "field_value",
353           -values   => \@authorised_values,
354           -default  => $value,
355           -labels   => \%authorised_lib,
356           -override => 1,
357           -size     => 1,
358           -multiple => 0,
359           -tabindex => 1,
360           -id       => "tag_".$tag."_subfield_".$subfield."_".$index_subfield,
361           -class    => "input_marceditor",
362       );
363     # it's a thesaurus / authority field
364     }
365     elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode} ) {
366         $subfield_data{marc_value} = "<input type=\"text\" $attributes />
367             <a href=\"#\" class=\"buttonDot\"
368                 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>
369     ";
370     # it's a plugin field
371     }
372     elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) {
373         # opening plugin
374         my $plugin = C4::Context->intranetdir . "/cataloguing/value_builder/" . $tagslib->{$tag}->{$subfield}->{'value_builder'};
375         if (do $plugin) {
376                         my $temp;
377             my $extended_param = plugin_parameters( $dbh, $temp, $tagslib, $subfield_data{id}, \@loop_data );
378             my ( $function_name, $javascript ) = plugin_javascript( $dbh, $temp, $tagslib, $subfield_data{id}, \@loop_data );
379             $subfield_data{marc_value} = qq[<input $attributes
380                 onfocus="Focus$function_name($subfield_data{random}, '$subfield_data{id}');"
381                  onblur=" Blur$function_name($subfield_data{random}, '$subfield_data{id}');" />
382                 <a href="#" class="buttonDot" onclick="Clic$function_name('$subfield_data{id}'); return false;" title="Tag Editor">...</a>
383                 $javascript];
384         } else {
385             warn "Plugin Failed: $plugin";
386             $subfield_data{marc_value} = "<input $attributes />"; # supply default input form
387         }
388     }
389     elsif ( $tag eq '' ) {       # it's an hidden field
390         $subfield_data{marc_value} = qq(<input type="hidden" $attributes />);
391     }
392     elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) {   # FIXME: shouldn't input type be "hidden" ?
393         $subfield_data{marc_value} = qq(<input type="text" $attributes />);
394     }
395     elsif ( length($value) > 100
396             or (C4::Context->preference("marcflavour") eq "UNIMARC" and
397                   300 <= $tag && $tag < 400 && $subfield eq 'a' )
398             or (C4::Context->preference("marcflavour") eq "MARC21"  and
399                   500 <= $tag && $tag < 600                     )
400           ) {
401         # oversize field (textarea)
402         $subfield_data{marc_value} = "<textarea $attributes_no_value>$value</textarea>\n";
403     } else {
404         # it's a standard field
405          $subfield_data{marc_value} = "<input $attributes />";
406     }
407 #   $subfield_data{marc_value}="<input type=\"text\" name=\"field_value\">";
408     push (@loop_data, \%subfield_data);
409     $i++
410   }
411 } # -- End foreach tag
412
413
414     # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
415     $template->param(item => \@loop_data);
416     if (@notfoundbarcodes) { 
417         my @notfoundbarcodesloop = map{{barcode=>$_}}@notfoundbarcodes;
418         $template->param(notfoundbarcodes => \@notfoundbarcodesloop);
419     }
420     $nextop="action"
421 } # -- End action="show"
422
423 $template->param(%$items_display_hashref) if $items_display_hashref;
424 $template->param(
425     op      => $nextop,
426     $op => 1,
427 );
428
429 if ($op eq "action") {
430
431     #my @not_deleted_loop = map{{itemnumber=>$_}}@not_deleted;
432
433     $template->param(
434         not_deleted_items => $not_deleted_items,
435         deleted_items => $deleted_items,
436         not_deleted_loop => \@not_deleted 
437     );
438 }
439
440 foreach my $error (@errors) {
441     $template->param($error => 1);
442 }
443 output_html_with_http_headers $input, $cookie, $template->output;
444 exit;
445
446
447 # ---------------- Functions
448
449 sub BuildItemsData{
450         my @itemnumbers=@_;
451                 # now, build existiing item list
452                 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
453                 my @big_array;
454                 #---- finds where items.itemnumber is stored
455                 my (  $itemtagfield,   $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
456                 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField("items.homebranch", "");
457                 foreach my $itemnumber (@itemnumbers){
458                         my $itemdata=GetItem($itemnumber);
459                         my $itemmarc=Item2Marc($itemdata);
460                         my %this_row;
461                         foreach my $field (grep {$_->tag() eq $itemtagfield} $itemmarc->fields()) {
462                                 # loop through each subfield
463                                 my $itembranchcode=$field->subfield($branchtagsubfield);
464                                 if ($itembranchcode && C4::Context->preference("IndependantBranches")) {
465                                                 #verifying rights
466                                                 my $userenv = C4::Context->userenv();
467                                                 unless (($userenv->{'flags'} == 1) or (($userenv->{'branch'} eq $itembranchcode))){
468                                                                 $this_row{'nomod'}=1;
469                                                 }
470                                 }
471                                 my $tag=$field->tag();
472                                 foreach my $subfield ($field->subfields) {
473                                         my ($subfcode,$subfvalue)=@$subfield;
474                                         next if ($tagslib->{$tag}->{$subfcode}->{tab} ne 10 
475                                                         && $tag        ne $itemtagfield 
476                                                         && $subfcode   ne $itemtagsubfield);
477
478                                         $witness{$subfcode} = $tagslib->{$tag}->{$subfcode}->{lib} if ($tagslib->{$tag}->{$subfcode}->{tab}  eq 10);
479                                         if ($tagslib->{$tag}->{$subfcode}->{tab}  eq 10) {
480                                                 $this_row{$subfcode}=GetAuthorisedValueDesc( $tag,
481                                                                         $subfcode, $subfvalue, '', $tagslib) 
482                                                                         || $subfvalue;
483                                         }
484
485                                         $this_row{itemnumber} = $subfvalue if ($tag eq $itemtagfield && $subfcode eq $itemtagsubfield);
486                                 }
487                         }
488
489             # grab title, author, and ISBN to identify bib that the item
490             # belongs to in the display
491                          my $biblio=GetBiblioData($$itemdata{biblionumber});
492             $this_row{title} = $biblio->{title};
493             $this_row{author} = $biblio->{author};
494             $this_row{isbn} = $biblio->{isbn};
495             $this_row{biblionumber} = $biblio->{biblionumber};
496
497                         if (%this_row) {
498                                 push(@big_array, \%this_row);
499                         }
500                 }
501                 @big_array = sort {$a->{0} cmp $b->{0}} @big_array;
502
503                 # now, construct template !
504                 # First, the existing items for display
505                 my @item_value_loop;
506                 my @witnesscodessorted=sort keys %witness;
507                 for my $row ( @big_array ) {
508                         my %row_data;
509                         my @item_fields = map +{ field => $_ || '' }, @$row{ @witnesscodessorted };
510                         $row_data{item_value} = [ @item_fields ];
511                         $row_data{itemnumber} = $row->{itemnumber};
512                         #reporting this_row values
513                         $row_data{'nomod'} = $row->{'nomod'};
514       $row_data{bibinfo} = $row->{bibinfo};
515       $row_data{author} = $row->{author};
516       $row_data{title} = $row->{title};
517       $row_data{isbn} = $row->{isbn};
518       $row_data{biblionumber} = $row->{biblionumber};
519                         push(@item_value_loop,\%row_data);
520                 }
521                 my @header_loop=map { { header_value=> $witness{$_}} } @witnesscodessorted;
522
523         return { item_loop        => \@item_value_loop, item_header_loop => \@header_loop };
524 }
525
526 #BE WARN : it is not the general case 
527 # This function can be OK in the item marc record special case
528 # Where subfield is not repeated
529 # And where we are sure that field should correspond
530 # And $tag>10
531 sub UpdateMarcWith {
532   my ($marcfrom,$marcto)=@_;
533   #warn "FROM :",$marcfrom->as_formatted;
534         my (  $itemtag,   $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
535         my $fieldfrom=$marcfrom->field($itemtag);
536         my @fields_to=$marcto->field($itemtag);
537     foreach my $subfield ($fieldfrom->subfields()){
538                 foreach my $field_to_update (@fields_to){
539                     if ($subfield->[1]){
540                         $field_to_update->update($subfield->[0]=>$subfield->[1]);
541                     }
542                     else {
543                         $field_to_update->delete_subfield(code=> $subfield->[0]);
544                     }
545                 }
546     }
547   #warn "TO edited:",$marcto->as_formatted;
548 }
549
550 sub find_value {
551     my ($tagfield,$insubfield,$record) = @_;
552     my $result;
553     my $indicator;
554     foreach my $field ($record->field($tagfield)) {
555         my @subfields = $field->subfields();
556         foreach my $subfield (@subfields) {
557             if (@$subfield[0] eq $insubfield) {
558                 $result .= @$subfield[1];
559                 $indicator = $field->indicator(1).$field->indicator(2);
560             }
561         }
562     }
563     return($indicator,$result);
564 }
565
566 # ----------------------------
567 # Background functions
568
569
570 sub add_results_to_template {
571     my $template = shift;
572     my $results = shift;
573     $template->param(map { $_ => $results->{$_} } keys %{ $results });
574 }
575
576 sub add_saved_job_results_to_template {
577     my $template = shift;
578     my $completedJobID = shift;
579     my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
580     my $results = $job->results();
581     add_results_to_template($template, $results);
582 }
583
584 sub put_in_background {
585     my $job_size = shift;
586
587     my $job = C4::BackgroundJob->new($sessionID, "test", $ENV{'SCRIPT_NAME'}, $job_size);
588     my $jobID = $job->id();
589
590     # fork off
591     if (my $pid = fork) {
592         # parent
593         # return job ID as JSON
594
595         # prevent parent exiting from
596         # destroying the kid's database handle
597         # FIXME: according to DBI doc, this may not work for Oracle
598         $dbh->{InactiveDestroy}  = 1;
599
600         my $reply = CGI->new("");
601         print $reply->header(-type => 'text/html');
602         print '{"jobID":"' . $jobID . '"}';
603         exit 0;
604     } elsif (defined $pid) {
605         # child
606         # close STDOUT to signal to Apache that
607         # we're now running in the background
608         close STDOUT;
609         close STDERR;
610     } else {
611         # fork failed, so exit immediately
612         warn "fork failed while attempting to run $ENV{'SCRIPT_NAME'} as a background job";
613         exit 0;
614     }
615     return $job;
616 }
617
618 sub progress_callback {
619     my $job = shift;
620     my $dbh = shift;
621     return sub {
622         my $progress = shift;
623         $job->progress($progress);
624     }
625 }
626
627