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