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