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