Bug 21395: Fix creation of PO file
[koha.git] / tools / batchMod.pl
blobfe40f84c7ec0ac17416c5933d59b412b98a2e3d0
1 #!/usr/bin/perl
4 # Copyright 2000-2002 Katipo Communications
6 # This file is part of Koha.
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.
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.
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>.
21 use CGI qw ( -utf8 );
22 use Modern::Perl;
23 use Try::Tiny;
25 use C4::Auth;
26 use C4::Output;
27 use C4::Biblio;
28 use C4::Items;
29 use C4::Circulation;
30 use C4::Context;
31 use C4::Koha;
32 use C4::BackgroundJob;
33 use C4::ClassSource;
34 use C4::Debug;
35 use C4::Members;
36 use MARC::File::XML;
37 use List::MoreUtils qw/uniq/;
39 use Koha::Database;
40 use Koha::Exceptions::Exception;
41 use Koha::AuthorisedValues;
42 use Koha::Biblios;
43 use Koha::DateUtils;
44 use Koha::Items;
45 use Koha::ItemTypes;
46 use Koha::Patrons;
48 my $input = new CGI;
49 my $dbh = C4::Context->dbh;
50 my $error = $input->param('error');
51 my @itemnumbers = $input->multi_param('itemnumber');
52 my $biblionumber = $input->param('biblionumber');
53 my $op = $input->param('op');
54 my $del = $input->param('del');
55 my $del_records = $input->param('del_records');
56 my $completedJobID = $input->param('completedJobID');
57 my $runinbackground = $input->param('runinbackground');
58 my $src = $input->param('src');
59 my $use_default_values = $input->param('use_default_values');
61 my $template_name;
62 my $template_flag;
63 if (!defined $op) {
64 $template_name = "tools/batchMod.tt";
65 $template_flag = { tools => '*' };
66 $op = q{};
67 } else {
68 $template_name = ($del) ? "tools/batchMod-del.tt" : "tools/batchMod-edit.tt";
69 $template_flag = ($del) ? { tools => 'items_batchdel' } : { tools => 'items_batchmod' };
73 my ($template, $loggedinuser, $cookie)
74 = get_template_and_user({template_name => $template_name,
75 query => $input,
76 type => "intranet",
77 authnotrequired => 0,
78 flagsrequired => $template_flag,
79 });
81 # Does the user have a restricted item edition permission?
82 my $uid = $loggedinuser ? Koha::Patrons->find( $loggedinuser )->userid : undef;
83 my $restrictededition = $uid ? haspermission($uid, {'tools' => 'items_batchmod_restricted'}) : undef;
84 # In case user is a superlibrarian, edition is not restricted
85 $restrictededition = 0 if ($restrictededition != 0 && C4::Context->IsSuperLibrarian());
87 $template->param(del => $del);
89 my $nextop="";
90 my @errors; # store errors found while checking data BEFORE saving item.
91 my $items_display_hashref;
92 our $tagslib = &GetMarcStructure(1);
94 my $deleted_items = 0; # Number of deleted items
95 my $deleted_records = 0; # Number of deleted records ( with no items attached )
96 my $not_deleted_items = 0; # Number of items that could not be deleted
97 my @not_deleted; # List of the itemnumbers that could not be deleted
98 my $modified_items = 0; # Numbers of modified items
99 my $modified_fields = 0; # Numbers of modified fields
101 my %cookies = parse CGI::Cookie($cookie);
102 my $sessionID = $cookies{'CGISESSID'}->value;
105 #--- ----------------------------------------------------------------------------
106 if ($op eq "action") {
107 #-------------------------------------------------------------------------------
108 my @tags = $input->multi_param('tag');
109 my @subfields = $input->multi_param('subfield');
110 my @values = $input->multi_param('field_value');
111 my @searches = $input->multi_param('regex_search');
112 my @replaces = $input->multi_param('regex_replace');
113 my @modifiers = $input->multi_param('regex_modifiers');
114 my @disabled = $input->multi_param('disable_input');
115 # build indicator hash.
116 my @ind_tag = $input->multi_param('ind_tag');
117 my @indicator = $input->multi_param('indicator');
119 # Is there something to modify ?
120 # TODO : We shall use this var to warn the user in case no modification was done to the items
121 my $values_to_modify = scalar(grep {!/^$/} @values) || scalar(grep {!/^$/} @searches);
122 my $values_to_blank = scalar(@disabled);
124 my $marcitem;
126 # Once the job is done
127 if ($completedJobID) {
128 # If we have a reasonable amount of items, we display them
129 my $max_items = $del ? C4::Context->preference("MaxItemsToDisplayForBatchDel") : C4::Context->preference("MaxItemsToDisplayForBatchMod");
130 if (scalar(@itemnumbers) <= $max_items ){
131 if (scalar(@itemnumbers) <= 1000 ) {
132 $items_display_hashref=BuildItemsData(@itemnumbers);
133 } else {
134 # Else, we only display the barcode
135 my @simple_items_display = map {
136 my $itemnumber = $_;
137 my $item = Koha::Items->find($itemnumber);
139 itemnumber => $itemnumber,
140 barcode => $item ? ( $item->barcode // q{} ) : q{},
141 biblionumber => $item ? $item->biblio->biblionumber : q{},
143 } @itemnumbers;
144 $template->param("simple_items_display" => \@simple_items_display);
146 } else {
147 $template->param( "too_many_items_display" => scalar(@itemnumbers) );
148 $template->param( "job_completed" => 1 );
151 # Setting the job as done
152 my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
154 # Calling the template
155 add_saved_job_results_to_template($template, $completedJobID);
157 } else {
158 # While the job is getting done
160 # Job size is the number of items we have to process
161 my $job_size = scalar(@itemnumbers);
162 my $job = undef;
164 # If we asked for background processing
165 if ($runinbackground) {
166 $job = put_in_background($job_size);
169 #initializing values for updates
170 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField( "items.itemnumber" );
171 if ($values_to_modify){
172 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
173 $marcitem = MARC::Record::new_from_xml($xml, 'UTF-8');
175 if ($values_to_blank){
176 foreach my $disabledsubf (@disabled){
177 if ($marcitem && $marcitem->field($itemtagfield)){
178 $marcitem->field($itemtagfield)->update( $disabledsubf => "" );
180 else {
181 $marcitem = MARC::Record->new();
182 $marcitem->append_fields( MARC::Field->new( $itemtagfield, '', '', $disabledsubf => "" ) );
187 try {
188 my $schema = Koha::Database->new->schema;
189 $schema->txn_do(
190 sub {
191 # For each item
192 my $i = 1;
193 foreach my $itemnumber (@itemnumbers) {
194 $job->progress($i) if $runinbackground;
195 my $item = Koha::Items->find($itemnumber);
196 next
197 unless $item
198 ; # Should have been tested earlier, but just in case...
199 my $itemdata = $item->unblessed;
200 if ($del) {
201 my $return = $item->safe_delete;
202 if ( ref( $return ) ) {
203 $deleted_items++;
205 else {
206 $not_deleted_items++;
207 push @not_deleted,
209 biblionumber => $itemdata->{'biblionumber'},
210 itemnumber => $itemdata->{'itemnumber'},
211 barcode => $itemdata->{'barcode'},
212 title => $itemdata->{'title'},
213 reason => $return,
217 # If there are no items left, delete the biblio
218 if ($del_records) {
219 my $itemscount = Koha::Biblios->find( $itemdata->{'biblionumber'} )->items->count;
220 if ( $itemscount == 0 ) {
221 my $error = DelBiblio( $itemdata->{'biblionumber'} );
222 unless ($error) {
223 $deleted_records++;
224 if ( $src eq 'CATALOGUING' ) {
225 # We are coming catalogue/detail.pl, there were items from a single bib record
226 $template->param( biblio_deleted => 1 );
232 else {
233 if ( $values_to_modify || $values_to_blank ) {
234 my $localmarcitem = Item2Marc($itemdata);
235 my $modified = 0;
237 for ( my $i = 0 ; $i < @tags ; $i++ ) {
238 my $search = $searches[$i];
239 next unless $search;
241 my $tag = $tags[$i];
242 my $subfield = $subfields[$i];
243 my $replace = $replaces[$i];
245 my $value = $localmarcitem->field( $tag )->subfield( $subfield );
246 my $old_value = $value;
248 my @available_modifiers = qw( i g );
249 my $retained_modifiers = q||;
250 for my $modifier ( split //, $modifiers[$i] ) {
251 $retained_modifiers .= $modifier
252 if grep {/$modifier/} @available_modifiers;
254 if ( $retained_modifiers =~ m/^(ig|gi)$/ ) {
255 $value =~ s/$search/$replace/ig;
257 elsif ( $retained_modifiers eq 'i' ) {
258 $value =~ s/$search/$replace/i;
260 elsif ( $retained_modifiers eq 'g' ) {
261 $value =~ s/$search/$replace/g;
263 else {
264 $value =~ s/$search/$replace/;
267 my @fields_to = $localmarcitem->field($tag);
268 foreach my $field_to_update ( @fields_to ) {
269 unless ( $old_value eq $value ) {
270 $modified++;
271 $field_to_update->update( $subfield => $value );
276 $modified += UpdateMarcWith( $marcitem, $localmarcitem );
277 if ($modified) {
278 eval {
279 if (
280 my $item = ModItemFromMarc(
281 $localmarcitem,
282 $itemdata->{biblionumber},
283 $itemnumber
287 LostItem( $itemnumber, 'batchmod' )
288 if $item->{itemlost}
289 and not $itemdata->{itemlost};
293 if ($runinbackground) {
294 $modified_items++ if $modified;
295 $modified_fields += $modified;
296 $job->set(
298 modified_items => $modified_items,
299 modified_fields => $modified_fields,
305 $i++;
307 if (@not_deleted) {
308 Koha::Exceptions::Exception->throw(
309 'Some items have not been deleted, rolling back');
314 catch {
315 if ( $_->isa('Koha::Exceptions::Exception') ) {
316 $template->param( deletion_failed => 1 );
318 die "Something terrible has happened!"
319 if ($_ =~ /Rollback failed/); # Rollback failed
324 #-------------------------------------------------------------------------------
325 # build screen with existing items. and "new" one
326 #-------------------------------------------------------------------------------
328 if ($op eq "show"){
329 my $filefh = $input->upload('uploadfile');
330 my $filecontent = $input->param('filecontent');
331 my ( @notfoundbarcodes, @notfounditemnumbers);
333 my $split_chars = C4::Context->preference('BarcodeSeparators');
334 if ($filefh){
335 binmode $filefh, ':encoding(UTF-8)';
336 my @contentlist;
337 while (my $content=<$filefh>){
338 $content =~ s/[\r\n]*$//;
339 push @contentlist, $content if $content;
342 if ($filecontent eq 'barcode_file') {
343 @contentlist = grep /\S/, ( map { split /[$split_chars]/ } @contentlist );
344 @contentlist = uniq @contentlist;
345 # Note: adding lc for case insensitivity
346 my %itemdata = map { lc($_->{barcode}) => $_->{itemnumber} } @{ Koha::Items->search({ barcode => \@contentlist }, { columns => [ 'itemnumber', 'barcode' ] } )->unblessed };
347 @itemnumbers = map { exists $itemdata{lc $_} ? $itemdata{lc $_} : () } @contentlist;
348 @notfoundbarcodes = grep { !exists $itemdata{lc $_} } @contentlist;
350 elsif ( $filecontent eq 'itemid_file') {
351 @contentlist = uniq @contentlist;
352 my %itemdata = map { $_->{itemnumber} => 1 } @{ Koha::Items->search({ itemnumber => \@contentlist }, { columns => [ 'itemnumber' ] } )->unblessed };
353 @itemnumbers = grep { exists $itemdata{$_} } @contentlist;
354 @notfounditemnumbers = grep { !exists $itemdata{$_} } @contentlist;
356 } else {
357 if (defined $biblionumber && !@itemnumbers){
358 my @all_items = GetItemsInfo( $biblionumber );
359 foreach my $itm (@all_items) {
360 push @itemnumbers, $itm->{itemnumber};
363 if ( my $list = $input->param('barcodelist') ) {
364 my @barcodelist = grep /\S/, ( split /[$split_chars]/, $list );
365 @barcodelist = uniq @barcodelist;
366 # Note: adding lc for case insensitivity
367 my %itemdata = map { lc($_->{barcode}) => $_->{itemnumber} } @{ Koha::Items->search({ barcode => \@barcodelist }, { columns => [ 'itemnumber', 'barcode' ] } )->unblessed };
368 @itemnumbers = map { exists $itemdata{lc $_} ? $itemdata{lc $_} : () } @barcodelist;
369 @notfoundbarcodes = grep { !exists $itemdata{lc $_} } @barcodelist;
373 # Flag to tell the template there are valid results, hidden or not
374 if(scalar(@itemnumbers) > 0){ $template->param("itemresults" => 1); }
375 # Only display the items if there are no more than pref MaxItemsToProcessForBatchMod or MaxItemsToDisplayForBatchDel
376 my $max_display_items = $del
377 ? C4::Context->preference("MaxItemsToDisplayForBatchDel")
378 : C4::Context->preference("MaxItemsToDisplayForBatchMod");
379 $template->param("too_many_items_process" => scalar(@itemnumbers)) if !$del && scalar(@itemnumbers) >= C4::Context->preference("MaxItemsToProcessForBatchMod");
380 if (scalar(@itemnumbers) <= ( $max_display_items // 1000 ) ) {
381 $items_display_hashref=BuildItemsData(@itemnumbers);
382 } else {
383 $template->param("too_many_items_display" => scalar(@itemnumbers));
384 # Even if we do not display the items, we need the itemnumbers
385 $template->param(itemnumbers_array => \@itemnumbers);
387 # now, build the item form for entering a new item
388 my @loop_data =();
389 my $i=0;
390 my $branch_limit = C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
392 my $libraries = Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed;# build once ahead of time, instead of multiple times later.
394 # Adding a default choice, in case the user does not want to modify the branch
395 my $nochange_branch = { branchname => '', value => '', selected => 1 };
396 unshift (@$libraries, $nochange_branch);
398 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
400 # Getting list of subfields to keep when restricted batchmod edit is enabled
401 my $subfieldsToAllowForBatchmod = C4::Context->preference('SubfieldsToAllowForRestrictedBatchmod');
402 my $allowAllSubfields = (
403 not defined $subfieldsToAllowForBatchmod
404 or $subfieldsToAllowForBatchmod eq q||
405 ) ? 1 : 0;
406 my @subfieldsToAllow = split(/ /, $subfieldsToAllowForBatchmod);
408 foreach my $tag (sort keys %{$tagslib}) {
409 # loop through each subfield
410 foreach my $subfield (sort keys %{$tagslib->{$tag}}) {
411 next if IsMarcStructureInternal( $tagslib->{$tag}{$subfield} );
412 next if (not $allowAllSubfields and $restrictededition && !grep { $tag . '$' . $subfield eq $_ } @subfieldsToAllow );
413 next if ($tagslib->{$tag}->{$subfield}->{'tab'} ne "10");
414 # barcode and stocknumber are not meant to be batch-modified
415 next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.barcode';
416 next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.stocknumber';
417 my %subfield_data;
419 my $index_subfield = int(rand(1000000));
420 if ($subfield eq '@'){
421 $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
422 } else {
423 $subfield_data{id} = "tag_".$tag."_subfield_".$subfield."_".$index_subfield;
425 $subfield_data{tag} = $tag;
426 $subfield_data{subfield} = $subfield;
427 $subfield_data{marc_lib} ="<span id=\"error$i\" title=\"".$tagslib->{$tag}->{$subfield}->{lib}."\">".$tagslib->{$tag}->{$subfield}->{lib}."</span>";
428 $subfield_data{mandatory} = $tagslib->{$tag}->{$subfield}->{mandatory};
429 $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
430 my $value;
431 if ( $use_default_values) {
432 $value = $tagslib->{$tag}->{$subfield}->{defaultvalue};
433 # get today date & replace YYYY, MM, DD if provided in the default value
434 my $today = dt_from_string;
435 my $year = $today->year;
436 my $month = $today->month;
437 my $day = $today->day;
438 $value =~ s/YYYY/$year/g;
439 $value =~ s/MM/$month/g;
440 $value =~ s/DD/$day/g;
442 $subfield_data{visibility} = "display:none;" if (($tagslib->{$tag}->{$subfield}->{hidden} > 4) || ($tagslib->{$tag}->{$subfield}->{hidden} < -4));
443 # testing branch value if IndependentBranches.
445 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
446 my @authorised_values;
447 my %authorised_lib;
448 # builds list, depending on authorised value...
450 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "branches" ) {
451 foreach my $library (@$libraries) {
452 push @authorised_values, $library->{branchcode};
453 $authorised_lib{$library->{branchcode}} = $library->{branchname};
455 $value = "";
457 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
458 push @authorised_values, "";
459 my $itemtypes = Koha::ItemTypes->search_with_localization;
460 while ( my $itemtype = $itemtypes->next ) {
461 push @authorised_values, $itemtype->itemtype;
462 $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description;
464 $value = "";
466 #---- class_sources
468 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
469 push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
471 my $class_sources = GetClassSources();
472 my $default_source = C4::Context->preference("DefaultClassificationSource");
474 foreach my $class_source (sort keys %$class_sources) {
475 next unless $class_sources->{$class_source}->{'used'} or
476 ($value and $class_source eq $value) or
477 ($class_source eq $default_source);
478 push @authorised_values, $class_source;
479 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
481 $value = '';
483 #---- "true" authorised value
485 else {
486 push @authorised_values, ""; # unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
488 my @avs = Koha::AuthorisedValues->search({ category => $tagslib->{$tag}->{$subfield}->{authorised_value}, branchcode => $branch_limit },{order_by=>'lib'});
489 for my $av ( @avs ) {
490 push @authorised_values, $av->authorised_value;
491 $authorised_lib{$av->authorised_value} = $av->lib;
493 $value="";
495 $subfield_data{marc_value} = {
496 type => 'select',
497 id => "tag_".$tag."_subfield_".$subfield."_".$index_subfield,
498 name => "field_value",
499 values => \@authorised_values,
500 labels => \%authorised_lib,
501 default => $value,
503 # it's a thesaurus / authority field
505 elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode} ) {
506 $subfield_data{marc_value} = {
507 type => 'text1',
508 id => $subfield_data{id},
509 value => $value,
510 authtypecode => $tagslib->{$tag}->{$subfield}->{authtypecode},
513 elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) { # plugin
514 require Koha::FrameworkPlugin;
515 my $plugin = Koha::FrameworkPlugin->new( {
516 name => $tagslib->{$tag}->{$subfield}->{'value_builder'},
517 item_style => 1,
519 my $temp;
520 my $pars= { dbh => $dbh, record => $temp, tagslib => $tagslib,
521 id => $subfield_data{id}, tabloop => \@loop_data };
522 $plugin->build( $pars );
523 if( !$plugin->errstr ) {
524 $subfield_data{marc_value} = {
525 type => 'text2',
526 id => $subfield_data{id},
527 value => $value,
528 javascript => $plugin->javascript,
529 noclick => $plugin->noclick,
531 } else {
532 warn $plugin->errstr;
533 $subfield_data{marc_value} = { # supply default input form
534 type => 'text',
535 id => $subfield_data{id},
536 value => $value,
540 elsif ( $tag eq '' ) { # it's an hidden field
541 $subfield_data{marc_value} = {
542 type => 'hidden',
543 id => $subfield_data{id},
544 value => $value,
547 elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
548 $subfield_data{marc_value} = {
549 type => 'text',
550 id => $subfield_data{id},
551 value => $value,
554 elsif ( length($value) > 100
555 or (C4::Context->preference("marcflavour") eq "UNIMARC" and
556 300 <= $tag && $tag < 400 && $subfield eq 'a' )
557 or (C4::Context->preference("marcflavour") eq "MARC21" and
558 500 <= $tag && $tag < 600 )
560 # oversize field (textarea)
561 $subfield_data{marc_value} = {
562 type => 'textarea',
563 id => $subfield_data{id},
564 value => $value,
566 } else {
567 # it's a standard field
568 $subfield_data{marc_value} = {
569 type => 'text',
570 id => $subfield_data{id},
571 value => $value,
574 # $subfield_data{marc_value}="<input type=\"text\" name=\"field_value\">";
575 push (@loop_data, \%subfield_data);
576 $i++
578 } # -- End foreach tag
582 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
583 $template->param(
584 item => \@loop_data,
585 notfoundbarcodes => \@notfoundbarcodes,
586 notfounditemnumbers => \@notfounditemnumbers
588 $nextop="action"
589 } # -- End action="show"
591 $template->param(%$items_display_hashref) if $items_display_hashref;
592 $template->param(
593 op => $nextop,
595 $template->param( $op => 1 ) if $op;
597 if ($op eq "action") {
599 #my @not_deleted_loop = map{{itemnumber=>$_}}@not_deleted;
601 $template->param(
602 not_deleted_items => $not_deleted_items,
603 deleted_items => $deleted_items,
604 delete_records => $del_records,
605 deleted_records => $deleted_records,
606 not_deleted_loop => \@not_deleted
610 foreach my $error (@errors) {
611 $template->param($error => 1) if $error;
613 $template->param(src => $src);
614 $template->param(biblionumber => $biblionumber);
615 output_html_with_http_headers $input, $cookie, $template->output;
616 exit;
619 # ---------------- Functions
621 sub BuildItemsData{
622 my @itemnumbers=@_;
623 # now, build existiing item list
624 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
625 my @big_array;
626 #---- finds where items.itemnumber is stored
627 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField( "items.itemnumber" );
628 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField( "items.homebranch" );
629 foreach my $itemnumber (@itemnumbers){
630 my $itemdata = Koha::Items->find($itemnumber);
631 next unless $itemdata; # Should have been tested earlier, but just in case...
632 $itemdata = $itemdata->unblessed;
633 my $itemmarc=Item2Marc($itemdata);
634 my %this_row;
635 foreach my $field (grep {$_->tag() eq $itemtagfield} $itemmarc->fields()) {
636 # loop through each subfield
637 my $itembranchcode=$field->subfield($branchtagsubfield);
638 if ($itembranchcode && C4::Context->preference("IndependentBranches")) {
639 #verifying rights
640 my $userenv = C4::Context->userenv();
641 unless (C4::Context->IsSuperLibrarian() or (($userenv->{'branch'} eq $itembranchcode))){
642 $this_row{'nomod'}=1;
645 my $tag=$field->tag();
646 foreach my $subfield ($field->subfields) {
647 my ($subfcode,$subfvalue)=@$subfield;
648 next if ($tagslib->{$tag}->{$subfcode}->{tab} ne 10
649 && $tag ne $itemtagfield
650 && $subfcode ne $itemtagsubfield);
652 $witness{$subfcode} = $tagslib->{$tag}->{$subfcode}->{lib} if ($tagslib->{$tag}->{$subfcode}->{tab} eq 10);
653 if ($tagslib->{$tag}->{$subfcode}->{tab} eq 10) {
654 $this_row{$subfcode}=GetAuthorisedValueDesc( $tag,
655 $subfcode, $subfvalue, '', $tagslib)
656 || $subfvalue;
659 $this_row{itemnumber} = $subfvalue if ($tag eq $itemtagfield && $subfcode eq $itemtagsubfield);
663 # grab title, author, and ISBN to identify bib that the item
664 # belongs to in the display
665 my $biblio = Koha::Biblios->find( $itemdata->{biblionumber} );
666 $this_row{title} = $biblio->title;
667 $this_row{author} = $biblio->author;
668 $this_row{isbn} = $biblio->biblioitem->isbn;
669 $this_row{biblionumber} = $biblio->biblionumber;
670 $this_row{holds} = $biblio->holds->count;
671 $this_row{item_holds} = Koha::Holds->search( { itemnumber => $itemnumber } )->count;
672 $this_row{item} = Koha::Items->find($itemnumber);
674 if (%this_row) {
675 push(@big_array, \%this_row);
678 @big_array = sort {$a->{0} cmp $b->{0}} @big_array;
680 # now, construct template !
681 # First, the existing items for display
682 my @item_value_loop;
683 my @witnesscodessorted=sort keys %witness;
684 for my $row ( @big_array ) {
685 my %row_data;
686 my @item_fields = map +{ field => $_ || '' }, @$row{ @witnesscodessorted };
687 $row_data{item_value} = [ @item_fields ];
688 $row_data{itemnumber} = $row->{itemnumber};
689 #reporting this_row values
690 $row_data{'nomod'} = $row->{'nomod'};
691 $row_data{bibinfo} = $row->{bibinfo};
692 $row_data{author} = $row->{author};
693 $row_data{title} = $row->{title};
694 $row_data{isbn} = $row->{isbn};
695 $row_data{biblionumber} = $row->{biblionumber};
696 $row_data{holds} = $row->{holds};
697 $row_data{item_holds} = $row->{item_holds};
698 $row_data{item} = $row->{item};
699 my $is_on_loan = C4::Circulation::IsItemIssued( $row->{itemnumber} );
700 $row_data{onloan} = $is_on_loan ? 1 : 0;
701 push(@item_value_loop,\%row_data);
703 my @header_loop=map { { header_value=> $witness{$_}} } @witnesscodessorted;
705 return { item_loop => \@item_value_loop, item_header_loop => \@header_loop };
708 #BE WARN : it is not the general case
709 # This function can be OK in the item marc record special case
710 # Where subfield is not repeated
711 # And where we are sure that field should correspond
712 # And $tag>10
713 sub UpdateMarcWith {
714 my ($marcfrom,$marcto)=@_;
715 my ( $itemtag, $itemtagsubfield) = &GetMarcFromKohaField( "items.itemnumber" );
716 my $fieldfrom=$marcfrom->field($itemtag);
717 my @fields_to=$marcto->field($itemtag);
718 my $modified = 0;
720 return $modified unless $fieldfrom;
722 foreach my $subfield ( $fieldfrom->subfields() ) {
723 foreach my $field_to_update ( @fields_to ) {
724 if ( $subfield->[1] ) {
725 unless ( $field_to_update->subfield($subfield->[0]) eq $subfield->[1] ) {
726 $modified++;
727 $field_to_update->update( $subfield->[0] => $subfield->[1] );
730 else {
731 $modified++;
732 $field_to_update->delete_subfield( code => $subfield->[0] );
736 return $modified;
739 sub find_value {
740 my ($tagfield,$insubfield,$record) = @_;
741 my $result;
742 my $indicator;
743 foreach my $field ($record->field($tagfield)) {
744 my @subfields = $field->subfields();
745 foreach my $subfield (@subfields) {
746 if (@$subfield[0] eq $insubfield) {
747 $result .= @$subfield[1];
748 $indicator = $field->indicator(1).$field->indicator(2);
752 return($indicator,$result);
755 # ----------------------------
756 # Background functions
759 sub add_results_to_template {
760 my $template = shift;
761 my $results = shift;
762 $template->param(map { $_ => $results->{$_} } keys %{ $results });
765 sub add_saved_job_results_to_template {
766 my $template = shift;
767 my $completedJobID = shift;
768 my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
769 my $results = $job->results();
770 add_results_to_template($template, $results);
772 my $fields = $job->get("modified_fields");
773 my $items = $job->get("modified_items");
774 $template->param(
775 modified_items => $items,
776 modified_fields => $fields,
780 sub put_in_background {
781 my $job_size = shift;
783 my $job = C4::BackgroundJob->new($sessionID, "test", '/cgi-bin/koha/tools/batchMod.pl', $job_size);
784 my $jobID = $job->id();
786 # fork off
787 if (my $pid = fork) {
788 # parent
789 # return job ID as JSON
791 # prevent parent exiting from
792 # destroying the kid's database handle
793 # FIXME: according to DBI doc, this may not work for Oracle
794 $dbh->{InactiveDestroy} = 1;
796 my $reply = CGI->new("");
797 print $reply->header(-type => 'text/html');
798 print '{"jobID":"' . $jobID . '"}';
799 exit 0;
800 } elsif (defined $pid) {
801 # child
802 # close STDOUT to signal to Apache that
803 # we're now running in the background
804 close STDOUT;
805 close STDERR;
806 } else {
807 # fork failed, so exit immediately
808 warn "fork failed while attempting to run tools/batchMod.pl as a background job";
809 exit 0;
811 return $job;