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