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