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