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