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>.
30 use C4::BackgroundJob;
35 use List::MoreUtils qw/uniq/;
44 my $dbh = C4::Context->dbh;
45 my $error = $input->param('error');
46 my @itemnumbers = $input->multi_param('itemnumber');
47 my $biblionumber = $input->param('biblionumber');
48 my $op = $input->param('op');
49 my $del = $input->param('del');
50 my $del_records = $input->param('del_records');
51 my $completedJobID = $input->param('completedJobID');
52 my $runinbackground = $input->param('runinbackground');
53 my $src = $input->param('src');
54 my $use_default_values = $input->param('use_default_values');
59 $template_name = "tools/batchMod.tt";
60 $template_flag = { tools => '*' };
63 $template_name = ($del) ? "tools/batchMod-del.tt" : "tools/batchMod-edit.tt";
64 $template_flag = ($del) ? { tools => 'items_batchdel' } : { tools => 'items_batchmod' };
68 my ($template, $loggedinuser, $cookie)
69 = get_template_and_user({template_name => $template_name,
73 flagsrequired => $template_flag,
76 # Does the user have a restricted item edition permission?
77 my $uid = $loggedinuser ? Koha::Patrons->find( $loggedinuser )->userid : undef;
78 my $restrictededition = $uid ? haspermission($uid, {'tools' => 'items_batchmod_restricted'}) : undef;
79 # In case user is a superlibrarian, edition is not restricted
80 $restrictededition = 0 if ($restrictededition != 0 && C4::Context->IsSuperLibrarian());
82 $template->param(del => $del);
86 my @errors; # store errors found while checking data BEFORE saving item.
87 my $items_display_hashref;
88 our $tagslib = &GetMarcStructure(1);
90 my $deleted_items = 0; # Number of deleted items
91 my $deleted_records = 0; # Number of deleted records ( with no items attached )
92 my $not_deleted_items = 0; # Number of items that could not be deleted
93 my @not_deleted; # List of the itemnumbers that could not be deleted
94 my $modified_items = 0; # Numbers of modified items
95 my $modified_fields = 0; # Numbers of modified fields
97 my %cookies = parse CGI::Cookie($cookie);
98 my $sessionID = $cookies{'CGISESSID'}->value;
101 #--- ----------------------------------------------------------------------------
102 if ($op eq "action") {
103 #-------------------------------------------------------------------------------
104 my @tags = $input->multi_param('tag');
105 my @subfields = $input->multi_param('subfield');
106 my @values = $input->multi_param('field_value');
107 my @disabled = $input->multi_param('disable_input');
108 # build indicator hash.
109 my @ind_tag = $input->multi_param('ind_tag');
110 my @indicator = $input->multi_param('indicator');
112 # Is there something to modify ?
113 # TODO : We shall use this var to warn the user in case no modification was done to the items
114 my $values_to_modify = scalar(grep {!/^$/} @values);
115 my $values_to_blank = scalar(@disabled);
118 # Once the job is done
119 if ($completedJobID) {
120 # If we have a reasonable amount of items, we display them
121 if (scalar(@itemnumbers) <= ( C4::Context->preference("MaxItemsToDisplayForBatchDel") // 1000 ) ) {
122 $items_display_hashref=BuildItemsData(@itemnumbers);
124 # Else, we only display the barcode
125 my @simple_items_display = map {
127 my $item = Koha::Items->find($itemnumber);
129 itemnumber => $itemnumber,
130 barcode => $item ? ( $item->barcode // q{} ) : q{},
131 biblionumber => $item ? $item->biblio->biblionumber : q{},
134 $template->param("simple_items_display" => \@simple_items_display);
137 # Setting the job as done
138 my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
140 # Calling the template
141 add_saved_job_results_to_template($template, $completedJobID);
144 # While the job is getting done
146 # Job size is the number of items we have to process
147 my $job_size = scalar(@itemnumbers);
150 # If we asked for background processing
151 if ($runinbackground) {
152 $job = put_in_background($job_size);
155 #initializing values for updates
156 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
157 if ($values_to_modify){
158 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
159 $marcitem = MARC::Record::new_from_xml($xml, 'UTF-8');
161 if ($values_to_blank){
162 foreach my $disabledsubf (@disabled){
163 if ($marcitem && $marcitem->field($itemtagfield)){
164 $marcitem->field($itemtagfield)->update( $disabledsubf => "" );
167 $marcitem = MARC::Record->new();
168 $marcitem->append_fields( MARC::Field->new( $itemtagfield, '', '', $disabledsubf => "" ) );
175 foreach my $itemnumber(@itemnumbers){
177 $job->progress($i) if $runinbackground;
178 my $itemdata = GetItem($itemnumber);
180 my $return = DelItemCheck( $itemdata->{'biblionumber'}, $itemdata->{'itemnumber'});
184 $not_deleted_items++;
186 { biblionumber => $itemdata->{'biblionumber'},
187 itemnumber => $itemdata->{'itemnumber'},
188 barcode => $itemdata->{'barcode'},
189 title => $itemdata->{'title'},
194 # If there are no items left, delete the biblio
195 if ( $del_records ) {
196 my $itemscount = Koha::Biblios->find( $itemdata->{'biblionumber'} )->items->count;
197 if ( $itemscount == 0 ) {
198 my $error = DelBiblio($itemdata->{'biblionumber'});
199 $deleted_records++ unless ( $error );
203 if ($values_to_modify || $values_to_blank) {
204 my $localmarcitem = Item2Marc($itemdata);
206 my $modified = UpdateMarcWith( $marcitem, $localmarcitem );
209 if ( my $item = ModItemFromMarc( $localmarcitem, $itemdata->{biblionumber}, $itemnumber ) ) {
210 LostItem($itemnumber, 'batchmod') if $item->{itemlost} and not $itemdata->{itemlost};
214 if ( $runinbackground ) {
215 $modified_items++ if $modified;
216 $modified_fields += $modified;
218 modified_items => $modified_items,
219 modified_fields => $modified_fields,
229 #-------------------------------------------------------------------------------
230 # build screen with existing items. and "new" one
231 #-------------------------------------------------------------------------------
234 my $filefh = $input->upload('uploadfile');
235 my $filecontent = $input->param('filecontent');
236 my ( @notfoundbarcodes, @notfounditemnumbers);
240 binmode $filefh, ':encoding(UTF-8)';
241 while (my $content=<$filefh>){
242 $content =~ s/[\r\n]*$//;
243 push @contentlist, $content if $content;
246 @contentlist = uniq @contentlist;
247 if ($filecontent eq 'barcode_file') {
248 my $existing_items = Koha::Items->search({ itemnumber => \@contentlist });
249 @itemnumbers = $existing_items->get_column('itemnumber');
250 my %exists = map {$_=>1} @{$existing_items->get_column('barcode')};
251 @notfoundbarcodes = grep { !$exists{$_} } @contentlist;
253 elsif ( $filecontent eq 'itemid_file') {
254 @itemnumbers = Koha::Items->search({ itemnumber => \@contentlist })->get_column('itemnumber');
255 my %exists = map {$_=>1} @itemnumbers;
256 @notfounditemnumbers = grep { !$exists{$_} } @contentlist;
259 if (defined $biblionumber){
260 my @all_items = GetItemsInfo( $biblionumber );
261 foreach my $itm (@all_items) {
262 push @itemnumbers, $itm->{itemnumber};
265 if ( my $list=$input->param('barcodelist')){
266 push my @barcodelist, uniq( split(/\s\n/, $list) );
268 my $existing_items = Koha::Items->search({ barcode => \@barcodelist });
269 @itemnumbers = $existing_items->get_column('itemnumber');
270 my %exists = map {$_=>1} @{$existing_items->get_column('barcode')};
271 @notfoundbarcodes = grep { !$exists{$_} } @barcodelist;
275 # Flag to tell the template there are valid results, hidden or not
276 if(scalar(@itemnumbers) > 0){ $template->param("itemresults" => 1); }
277 # Only display the items if there are no more than pref MaxItemsToProcessForBatchMod or MaxItemsToDisplayForBatchDel
279 ? C4::Context->preference("MaxItemsToDisplayForBatchDel")
280 : C4::Context->preference("MaxItemsToProcessForBatchMod");
281 if (scalar(@itemnumbers) <= ( $max_items // 1000 ) ) {
282 $items_display_hashref=BuildItemsData(@itemnumbers);
284 $template->param("too_many_items" => scalar(@itemnumbers));
285 # Even if we do not display the items, we need the itemnumbers
286 $template->param(itemnumbers_array => \@itemnumbers);
288 # now, build the item form for entering a new item
291 my $branch_limit = C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
292 my $query = qq{SELECT authorised_value, lib FROM authorised_values};
293 $query .= qq{ LEFT JOIN authorised_values_branches ON ( id = av_id ) } if $branch_limit;
294 $query .= qq{ WHERE category = ?};
295 $query .= qq{ AND ( branchcode = ? OR branchcode IS NULL ) } if $branch_limit;
296 $query .= qq{ GROUP BY lib ORDER BY lib, lib_opac};
297 my $authorised_values_sth = $dbh->prepare( $query );
299 my $libraries = Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed;# build once ahead of time, instead of multiple times later.
301 # Adding a default choice, in case the user does not want to modify the branch
302 my $nochange_branch = { branchname => '', value => '', selected => 1 };
303 unshift (@$libraries, $nochange_branch);
305 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
307 # Getting list of subfields to keep when restricted batchmod edit is enabled
308 my $subfieldsToAllowForBatchmod = C4::Context->preference('SubfieldsToAllowForRestrictedBatchmod');
309 my $allowAllSubfields = (
310 not defined $subfieldsToAllowForBatchmod
311 or $subfieldsToAllowForBatchmod eq q||
313 my @subfieldsToAllow = split(/ /, $subfieldsToAllowForBatchmod);
315 foreach my $tag (sort keys %{$tagslib}) {
316 # loop through each subfield
317 foreach my $subfield (sort keys %{$tagslib->{$tag}}) {
318 next if IsMarcStructureInternal( $tagslib->{$tag}{$subfield} );
319 next if (not $allowAllSubfields and $restrictededition && !grep { $tag . '$' . $subfield eq $_ } @subfieldsToAllow );
320 next if ($tagslib->{$tag}->{$subfield}->{'tab'} ne "10");
321 # barcode and stocknumber are not meant to be batch-modified
322 next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.barcode';
323 next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.stocknumber';
326 my $index_subfield = int(rand(1000000));
327 if ($subfield eq '@'){
328 $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
330 $subfield_data{id} = "tag_".$tag."_subfield_".$subfield."_".$index_subfield;
332 $subfield_data{tag} = $tag;
333 $subfield_data{subfield} = $subfield;
334 $subfield_data{marc_lib} ="<span id=\"error$i\" title=\"".$tagslib->{$tag}->{$subfield}->{lib}."\">".$tagslib->{$tag}->{$subfield}->{lib}."</span>";
335 $subfield_data{mandatory} = $tagslib->{$tag}->{$subfield}->{mandatory};
336 $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
338 $value =~ s/"/"/g;
339 if ( !$value && $use_default_values) {
340 $value = $tagslib->{$tag}->{$subfield}->{defaultvalue};
341 # get today date & replace YYYY, MM, DD if provided in the default value
342 my $today = dt_from_string;
343 my $year = $today->year;
344 my $month = $today->month;
345 my $day = $today->day;
346 $value =~ s/YYYY/$year/g;
347 $value =~ s/MM/$month/g;
348 $value =~ s/DD/$day/g;
350 $subfield_data{visibility} = "display:none;" if (($tagslib->{$tag}->{$subfield}->{hidden} > 4) || ($tagslib->{$tag}->{$subfield}->{hidden} < -4));
351 # testing branch value if IndependentBranches.
353 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
354 my @authorised_values;
356 # builds list, depending on authorised value...
358 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "branches" ) {
359 foreach my $library (@$libraries) {
360 push @authorised_values, $library->{branchcode};
361 $authorised_lib{$library->{branchcode}} = $library->{branchname};
365 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
366 push @authorised_values, "";
367 my $itemtypes = Koha::ItemTypes->search_with_localization;
368 while ( my $itemtype = $itemtypes->next ) {
369 push @authorised_values, $itemtype->itemtype;
370 $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description;
376 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
377 push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
379 my $class_sources = GetClassSources();
380 my $default_source = C4::Context->preference("DefaultClassificationSource");
382 foreach my $class_source (sort keys %$class_sources) {
383 next unless $class_sources->{$class_source}->{'used'} or
384 ($value and $class_source eq $value) or
385 ($class_source eq $default_source);
386 push @authorised_values, $class_source;
387 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
391 #---- "true" authorised value
394 push @authorised_values, ""; # unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
395 $authorised_values_sth->execute( $tagslib->{$tag}->{$subfield}->{authorised_value}, $branch_limit ? $branch_limit : () );
396 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
397 push @authorised_values, $value;
398 $authorised_lib{$value} = $lib;
402 $subfield_data{marc_value} = {
404 id => "tag_".$tag."_subfield_".$subfield."_".$index_subfield,
405 name => "field_value",
406 values => \@authorised_values,
407 labels => \%authorised_lib,
410 # it's a thesaurus / authority field
412 elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode} ) {
413 $subfield_data{marc_value} = {
415 id => $subfield_data{id},
417 authtypecode => $tagslib->{$tag}->{$subfield}->{authtypecode},
420 elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) { # plugin
421 require Koha::FrameworkPlugin;
422 my $plugin = Koha::FrameworkPlugin->new( {
423 name => $tagslib->{$tag}->{$subfield}->{'value_builder'},
427 my $pars= { dbh => $dbh, record => $temp, tagslib => $tagslib,
428 id => $subfield_data{id}, tabloop => \@loop_data };
429 $plugin->build( $pars );
430 if( !$plugin->errstr ) {
431 $subfield_data{marc_value} = {
433 id => $subfield_data{id},
435 javascript => $plugin->javascript,
436 noclick => $plugin->noclick,
439 warn $plugin->errstr;
440 $subfield_data{marc_value} = { # supply default input form
442 id => $subfield_data{id},
447 elsif ( $tag eq '' ) { # it's an hidden field
448 $subfield_data{marc_value} = {
450 id => $subfield_data{id},
454 elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
455 $subfield_data{marc_value} = {
457 id => $subfield_data{id},
461 elsif ( length($value) > 100
462 or (C4::Context->preference("marcflavour") eq "UNIMARC" and
463 300 <= $tag && $tag < 400 && $subfield eq 'a' )
464 or (C4::Context->preference("marcflavour") eq "MARC21" and
465 500 <= $tag && $tag < 600 )
467 # oversize field (textarea)
468 $subfield_data{marc_value} = {
470 id => $subfield_data{id},
474 # it's a standard field
475 $subfield_data{marc_value} = {
477 id => $subfield_data{id},
481 # $subfield_data{marc_value}="<input type=\"text\" name=\"field_value\">";
482 push (@loop_data, \%subfield_data);
485 } # -- End foreach tag
486 $authorised_values_sth->finish;
490 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
493 notfoundbarcodes => \@notfoundbarcodes,
494 notfounditemnumbers => \@notfounditemnumbers
497 } # -- End action="show"
499 $template->param(%$items_display_hashref) if $items_display_hashref;
503 $template->param( $op => 1 ) if $op;
505 if ($op eq "action") {
507 #my @not_deleted_loop = map{{itemnumber=>$_}}@not_deleted;
510 not_deleted_items => $not_deleted_items,
511 deleted_items => $deleted_items,
512 delete_records => $del_records,
513 deleted_records => $deleted_records,
514 not_deleted_loop => \@not_deleted
518 foreach my $error (@errors) {
519 $template->param($error => 1) if $error;
521 $template->param(src => $src);
522 $template->param(biblionumber => $biblionumber);
523 output_html_with_http_headers $input, $cookie, $template->output;
527 # ---------------- Functions
531 # now, build existiing item list
532 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
534 #---- finds where items.itemnumber is stored
535 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
536 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField("items.homebranch", "");
537 foreach my $itemnumber (@itemnumbers){
538 my $itemdata=GetItem($itemnumber);
539 my $itemmarc=Item2Marc($itemdata);
541 foreach my $field (grep {$_->tag() eq $itemtagfield} $itemmarc->fields()) {
542 # loop through each subfield
543 my $itembranchcode=$field->subfield($branchtagsubfield);
544 if ($itembranchcode && C4::Context->preference("IndependentBranches")) {
546 my $userenv = C4::Context->userenv();
547 unless (C4::Context->IsSuperLibrarian() or (($userenv->{'branch'} eq $itembranchcode))){
548 $this_row{'nomod'}=1;
551 my $tag=$field->tag();
552 foreach my $subfield ($field->subfields) {
553 my ($subfcode,$subfvalue)=@$subfield;
554 next if ($tagslib->{$tag}->{$subfcode}->{tab} ne 10
555 && $tag ne $itemtagfield
556 && $subfcode ne $itemtagsubfield);
558 $witness{$subfcode} = $tagslib->{$tag}->{$subfcode}->{lib} if ($tagslib->{$tag}->{$subfcode}->{tab} eq 10);
559 if ($tagslib->{$tag}->{$subfcode}->{tab} eq 10) {
560 $this_row{$subfcode}=GetAuthorisedValueDesc( $tag,
561 $subfcode, $subfvalue, '', $tagslib)
565 $this_row{itemnumber} = $subfvalue if ($tag eq $itemtagfield && $subfcode eq $itemtagsubfield);
569 # grab title, author, and ISBN to identify bib that the item
570 # belongs to in the display
571 my $biblio = Koha::Biblios->find( $itemdata->{biblionumber} );
572 $this_row{title} = $biblio->title;
573 $this_row{author} = $biblio->author;
574 $this_row{isbn} = $biblio->biblioitem->isbn;
575 $this_row{biblionumber} = $biblio->biblionumber;
578 push(@big_array, \%this_row);
581 @big_array = sort {$a->{0} cmp $b->{0}} @big_array;
583 # now, construct template !
584 # First, the existing items for display
586 my @witnesscodessorted=sort keys %witness;
587 for my $row ( @big_array ) {
589 my @item_fields = map +{ field => $_ || '' }, @$row{ @witnesscodessorted };
590 $row_data{item_value} = [ @item_fields ];
591 $row_data{itemnumber} = $row->{itemnumber};
592 #reporting this_row values
593 $row_data{'nomod'} = $row->{'nomod'};
594 $row_data{bibinfo} = $row->{bibinfo};
595 $row_data{author} = $row->{author};
596 $row_data{title} = $row->{title};
597 $row_data{isbn} = $row->{isbn};
598 $row_data{biblionumber} = $row->{biblionumber};
599 my $is_on_loan = C4::Circulation::IsItemIssued( $row->{itemnumber} );
600 $row_data{onloan} = $is_on_loan ? 1 : 0;
601 push(@item_value_loop,\%row_data);
603 my @header_loop=map { { header_value=> $witness{$_}} } @witnesscodessorted;
605 return { item_loop => \@item_value_loop, item_header_loop => \@header_loop };
608 #BE WARN : it is not the general case
609 # This function can be OK in the item marc record special case
610 # Where subfield is not repeated
611 # And where we are sure that field should correspond
614 my ($marcfrom,$marcto)=@_;
615 my ( $itemtag, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
616 my $fieldfrom=$marcfrom->field($itemtag);
617 my @fields_to=$marcto->field($itemtag);
619 foreach my $subfield ( $fieldfrom->subfields() ) {
620 foreach my $field_to_update ( @fields_to ) {
621 if ( $subfield->[1] ) {
622 unless ( $field_to_update->subfield($subfield->[0]) eq $subfield->[1] ) {
624 $field_to_update->update( $subfield->[0] => $subfield->[1] );
629 $field_to_update->delete_subfield( code => $subfield->[0] );
637 my ($tagfield,$insubfield,$record) = @_;
640 foreach my $field ($record->field($tagfield)) {
641 my @subfields = $field->subfields();
642 foreach my $subfield (@subfields) {
643 if (@$subfield[0] eq $insubfield) {
644 $result .= @$subfield[1];
645 $indicator = $field->indicator(1).$field->indicator(2);
649 return($indicator,$result);
652 # ----------------------------
653 # Background functions
656 sub add_results_to_template {
657 my $template = shift;
659 $template->param(map { $_ => $results->{$_} } keys %{ $results });
662 sub add_saved_job_results_to_template {
663 my $template = shift;
664 my $completedJobID = shift;
665 my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
666 my $results = $job->results();
667 add_results_to_template($template, $results);
669 my $fields = $job->get("modified_fields");
670 my $items = $job->get("modified_items");
672 modified_items => $items,
673 modified_fields => $fields,
677 sub put_in_background {
678 my $job_size = shift;
680 my $job = C4::BackgroundJob->new($sessionID, "test", '/cgi-bin/koha/tools/batchMod.pl', $job_size);
681 my $jobID = $job->id();
684 if (my $pid = fork) {
686 # return job ID as JSON
688 # prevent parent exiting from
689 # destroying the kid's database handle
690 # FIXME: according to DBI doc, this may not work for Oracle
691 $dbh->{InactiveDestroy} = 1;
693 my $reply = CGI->new("");
694 print $reply->header(-type => 'text/html');
695 print '{"jobID":"' . $jobID . '"}';
697 } elsif (defined $pid) {
699 # close STDOUT to signal to Apache that
700 # we're now running in the background
704 # fork failed, so exit immediately
705 warn "fork failed while attempting to run tools/batchMod.pl as a background job";