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