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>.
23 #use warnings; FIXME - Bug 2505
31 use C4::BackgroundJob;
36 use List::MoreUtils qw/uniq/;
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');
60 $template_name = "tools/batchMod.tt";
61 $template_flag = { tools => '*' };
64 $template_name = ($del) ? "tools/batchMod-del.tt" : "tools/batchMod-edit.tt";
65 $template_flag = ($del) ? { tools => 'items_batchdel' } : { tools => 'items_batchmod' };
69 my ($template, $loggedinuser, $cookie)
70 = get_template_and_user({template_name => $template_name,
74 flagsrequired => $template_flag,
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());
83 $template->param(del => $del);
87 my @errors; # store errors found while checking data BEFORE saving item.
88 my $items_display_hashref;
89 our $tagslib = &GetMarcStructure(1);
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
98 my %cookies = parse CGI::Cookie($cookie);
99 my $sessionID = $cookies{'CGISESSID'}->value;
102 #--- ----------------------------------------------------------------------------
103 if ($op eq "action") {
104 #-------------------------------------------------------------------------------
105 my @tags = $input->multi_param('tag');
106 my @subfields = $input->multi_param('subfield');
107 my @values = $input->multi_param('field_value');
108 my @disabled = $input->multi_param('disable_input');
109 # build indicator hash.
110 my @ind_tag = $input->multi_param('ind_tag');
111 my @indicator = $input->multi_param('indicator');
113 # Is there something to modify ?
114 # TODO : We shall use this var to warn the user in case no modification was done to the items
115 my $values_to_modify = scalar(grep {!/^$/} @values);
116 my $values_to_blank = scalar(@disabled);
119 # Once the job is done
120 if ($completedJobID) {
121 # If we have a reasonable amount of items, we display them
122 if (scalar(@itemnumbers) <= ( C4::Context->preference("MaxItemsToDisplayForBatchDel") // 1000 ) ) {
123 $items_display_hashref=BuildItemsData(@itemnumbers);
125 # Else, we only display the barcode
126 my @simple_items_display = map {
128 my $item = Koha::Items->find($itemnumber);
130 itemnumber => $itemnumber,
131 barcode => $item ? ( $item->barcode // q{} ) : q{},
132 biblionumber => $item ? $item->biblio->biblionumber : q{},
135 $template->param("simple_items_display" => \@simple_items_display);
138 # Setting the job as done
139 my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
141 # Calling the template
142 add_saved_job_results_to_template($template, $completedJobID);
145 # While the job is getting done
147 # Job size is the number of items we have to process
148 my $job_size = scalar(@itemnumbers);
151 # If we asked for background processing
152 if ($runinbackground) {
153 $job = put_in_background($job_size);
156 #initializing values for updates
157 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
158 if ($values_to_modify){
159 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
160 $marcitem = MARC::Record::new_from_xml($xml, 'UTF-8');
162 if ($values_to_blank){
163 foreach my $disabledsubf (@disabled){
164 if ($marcitem && $marcitem->field($itemtagfield)){
165 $marcitem->field($itemtagfield)->update( $disabledsubf => "" );
168 $marcitem = MARC::Record->new();
169 $marcitem->append_fields( MARC::Field->new( $itemtagfield, '', '', $disabledsubf => "" ) );
176 foreach my $itemnumber(@itemnumbers){
178 $job->progress($i) if $runinbackground;
179 my $itemdata = GetItem($itemnumber);
181 my $return = DelItemCheck( $itemdata->{'biblionumber'}, $itemdata->{'itemnumber'});
185 $not_deleted_items++;
187 { biblionumber => $itemdata->{'biblionumber'},
188 itemnumber => $itemdata->{'itemnumber'},
189 barcode => $itemdata->{'barcode'},
190 title => $itemdata->{'title'},
195 # If there are no items left, delete the biblio
196 if ( $del_records ) {
197 my $itemscount = Koha::Biblios->find( $itemdata->{'biblionumber'} )->items->count;
198 if ( $itemscount == 0 ) {
199 my $error = DelBiblio($itemdata->{'biblionumber'});
200 $deleted_records++ unless ( $error );
204 if ($values_to_modify || $values_to_blank) {
205 my $localmarcitem = Item2Marc($itemdata);
207 my $modified = UpdateMarcWith( $marcitem, $localmarcitem );
210 if ( my $item = ModItemFromMarc( $localmarcitem, $itemdata->{biblionumber}, $itemnumber ) ) {
211 LostItem($itemnumber) if $item->{itemlost} and not $itemdata->{itemlost};
215 if ( $runinbackground ) {
216 $modified_items++ if $modified;
217 $modified_fields += $modified;
219 modified_items => $modified_items,
220 modified_fields => $modified_fields,
230 #-------------------------------------------------------------------------------
231 # build screen with existing items. and "new" one
232 #-------------------------------------------------------------------------------
235 my $filefh = $input->upload('uploadfile');
236 my $filecontent = $input->param('filecontent');
237 my @notfoundbarcodes;
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 foreach my $barcode (@contentlist) {
250 my $itemnumber = GetItemnumberFromBarcode($barcode);
252 push @itemnumbers,$itemnumber;
254 push @notfoundbarcodes, $barcode;
258 elsif ( $filecontent eq 'itemid_file') {
259 @itemnumbers = @contentlist;
262 if (defined $biblionumber){
263 my @all_items = GetItemsInfo( $biblionumber );
264 foreach my $itm (@all_items) {
265 push @itemnumbers, $itm->{itemnumber};
268 if ( my $list=$input->param('barcodelist')){
269 push my @barcodelist, uniq( split(/\s\n/, $list) );
271 foreach my $barcode (@barcodelist) {
273 my $itemnumber = GetItemnumberFromBarcode($barcode);
275 push @itemnumbers,$itemnumber;
277 push @notfoundbarcodes, $barcode;
284 # Flag to tell the template there are valid results, hidden or not
285 if(scalar(@itemnumbers) > 0){ $template->param("itemresults" => 1); }
286 # Only display the items if there are no more than pref MaxItemsToProcessForBatchMod or MaxItemsToDisplayForBatchDel
288 ? C4::Context->preference("MaxItemsToDisplayForBatchDel")
289 : C4::Context->preference("MaxItemsToProcessForBatchMod");
290 if (scalar(@itemnumbers) <= ( $max_items // 1000 ) ) {
291 $items_display_hashref=BuildItemsData(@itemnumbers);
293 $template->param("too_many_items" => scalar(@itemnumbers));
294 # Even if we do not display the items, we need the itemnumbers
295 $template->param(itemnumbers_array => \@itemnumbers);
297 # now, build the item form for entering a new item
300 my $branch_limit = C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
301 my $query = qq{SELECT authorised_value, lib FROM authorised_values};
302 $query .= qq{ LEFT JOIN authorised_values_branches ON ( id = av_id ) } if $branch_limit;
303 $query .= qq{ WHERE category = ?};
304 $query .= qq{ AND ( branchcode = ? OR branchcode IS NULL ) } if $branch_limit;
305 $query .= qq{ GROUP BY lib ORDER BY lib, lib_opac};
306 my $authorised_values_sth = $dbh->prepare( $query );
308 my $libraries = Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed;# build once ahead of time, instead of multiple times later.
310 # Adding a default choice, in case the user does not want to modify the branch
311 my $nochange_branch = { branchname => '', value => '', selected => 1 };
312 unshift (@$libraries, $nochange_branch);
314 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
316 # Getting list of subfields to keep when restricted batchmod edit is enabled
317 my $subfieldsToAllowForBatchmod = C4::Context->preference('SubfieldsToAllowForRestrictedBatchmod');
318 my $allowAllSubfields = (
319 not defined $subfieldsToAllowForBatchmod
320 or $subfieldsToAllowForBatchmod == q||
322 my @subfieldsToAllow = split(/ /, $subfieldsToAllowForBatchmod);
324 foreach my $tag (sort keys %{$tagslib}) {
325 # loop through each subfield
326 foreach my $subfield (sort keys %{$tagslib->{$tag}}) {
327 next if IsMarcStructureInternal( $tagslib->{$tag}{$subfield} );
328 next if (not $allowAllSubfields and $restrictededition && !grep { $tag . '$' . $subfield eq $_ } @subfieldsToAllow );
329 next if ($tagslib->{$tag}->{$subfield}->{'tab'} ne "10");
330 # barcode and stocknumber are not meant to be batch-modified
331 next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.barcode';
332 next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.stocknumber';
335 my $index_subfield = int(rand(1000000));
336 if ($subfield eq '@'){
337 $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
339 $subfield_data{id} = "tag_".$tag."_subfield_".$subfield."_".$index_subfield;
341 $subfield_data{tag} = $tag;
342 $subfield_data{subfield} = $subfield;
343 $subfield_data{marc_lib} ="<span id=\"error$i\" title=\"".$tagslib->{$tag}->{$subfield}->{lib}."\">".$tagslib->{$tag}->{$subfield}->{lib}."</span>";
344 $subfield_data{mandatory} = $tagslib->{$tag}->{$subfield}->{mandatory};
345 $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
347 $value =~ s/"/"/g;
348 if ( !$value && $use_default_values) {
349 $value = $tagslib->{$tag}->{$subfield}->{defaultvalue};
350 # get today date & replace YYYY, MM, DD if provided in the default value
351 my $today = dt_from_string;
352 my $year = $today->year;
353 my $month = $today->month;
354 my $day = $today->day;
355 $value =~ s/YYYY/$year/g;
356 $value =~ s/MM/$month/g;
357 $value =~ s/DD/$day/g;
359 $subfield_data{visibility} = "display:none;" if (($tagslib->{$tag}->{$subfield}->{hidden} > 4) || ($tagslib->{$tag}->{$subfield}->{hidden} < -4));
360 # testing branch value if IndependentBranches.
362 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
363 my @authorised_values;
365 # builds list, depending on authorised value...
367 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "branches" ) {
368 foreach my $library (@$libraries) {
369 push @authorised_values, $library->{branchcode};
370 $authorised_lib{$library->{branchcode}} = $library->{branchname};
374 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
375 push @authorised_values, "";
376 my $itemtypes = Koha::ItemTypes->search_with_localization;
377 while ( my $itemtype = $itemtypes->next ) {
378 push @authorised_values, $itemtype->itemtype;
379 $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description;
385 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
386 push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
388 my $class_sources = GetClassSources();
389 my $default_source = C4::Context->preference("DefaultClassificationSource");
391 foreach my $class_source (sort keys %$class_sources) {
392 next unless $class_sources->{$class_source}->{'used'} or
393 ($value and $class_source eq $value) or
394 ($class_source eq $default_source);
395 push @authorised_values, $class_source;
396 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
400 #---- "true" authorised value
403 push @authorised_values, ""; # unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
404 $authorised_values_sth->execute( $tagslib->{$tag}->{$subfield}->{authorised_value}, $branch_limit ? $branch_limit : () );
405 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
406 push @authorised_values, $value;
407 $authorised_lib{$value} = $lib;
411 $subfield_data{marc_value} = {
413 id => "tag_".$tag."_subfield_".$subfield."_".$index_subfield,
414 name => "field_value",
415 values => \@authorised_values,
416 labels => \%authorised_lib,
419 # it's a thesaurus / authority field
421 elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode} ) {
422 $subfield_data{marc_value} = {
424 id => $subfield_data{id},
426 authtypecode => $tagslib->{$tag}->{$subfield}->{authtypecode},
429 elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) { # plugin
430 require Koha::FrameworkPlugin;
431 my $plugin = Koha::FrameworkPlugin->new( {
432 name => $tagslib->{$tag}->{$subfield}->{'value_builder'},
436 my $pars= { dbh => $dbh, record => $temp, tagslib => $tagslib,
437 id => $subfield_data{id}, tabloop => \@loop_data };
438 $plugin->build( $pars );
439 if( !$plugin->errstr ) {
440 $subfield_data{marc_value} = {
442 id => $subfield_data{id},
444 javascript => $plugin->javascript,
445 noclick => $plugin->noclick,
448 warn $plugin->errstr;
449 $subfield_data{marc_value} = { # supply default input form
451 id => $subfield_data{id},
456 elsif ( $tag eq '' ) { # it's an hidden field
457 $subfield_data{marc_value} = {
459 id => $subfield_data{id},
463 elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
464 $subfield_data{marc_value} = {
466 id => $subfield_data{id},
470 elsif ( length($value) > 100
471 or (C4::Context->preference("marcflavour") eq "UNIMARC" and
472 300 <= $tag && $tag < 400 && $subfield eq 'a' )
473 or (C4::Context->preference("marcflavour") eq "MARC21" and
474 500 <= $tag && $tag < 600 )
476 # oversize field (textarea)
477 $subfield_data{marc_value} = {
479 id => $subfield_data{id},
483 # it's a standard field
484 $subfield_data{marc_value} = {
486 id => $subfield_data{id},
490 # $subfield_data{marc_value}="<input type=\"text\" name=\"field_value\">";
491 push (@loop_data, \%subfield_data);
494 } # -- End foreach tag
495 $authorised_values_sth->finish;
499 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
500 $template->param(item => \@loop_data);
501 if (@notfoundbarcodes) {
502 my @notfoundbarcodesloop = map{{barcode=>$_}}@notfoundbarcodes;
503 $template->param(notfoundbarcodes => \@notfoundbarcodesloop);
506 } # -- End action="show"
508 $template->param(%$items_display_hashref) if $items_display_hashref;
512 $template->param( $op => 1 ) if $op;
514 if ($op eq "action") {
516 #my @not_deleted_loop = map{{itemnumber=>$_}}@not_deleted;
519 not_deleted_items => $not_deleted_items,
520 deleted_items => $deleted_items,
521 delete_records => $del_records,
522 deleted_records => $deleted_records,
523 not_deleted_loop => \@not_deleted
527 foreach my $error (@errors) {
528 $template->param($error => 1) if $error;
530 $template->param(src => $src);
531 $template->param(biblionumber => $biblionumber);
532 output_html_with_http_headers $input, $cookie, $template->output;
536 # ---------------- Functions
540 # now, build existiing item list
541 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
543 #---- finds where items.itemnumber is stored
544 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
545 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField("items.homebranch", "");
546 foreach my $itemnumber (@itemnumbers){
547 my $itemdata=GetItem($itemnumber);
548 my $itemmarc=Item2Marc($itemdata);
550 foreach my $field (grep {$_->tag() eq $itemtagfield} $itemmarc->fields()) {
551 # loop through each subfield
552 my $itembranchcode=$field->subfield($branchtagsubfield);
553 if ($itembranchcode && C4::Context->preference("IndependentBranches")) {
555 my $userenv = C4::Context->userenv();
556 unless (C4::Context->IsSuperLibrarian() or (($userenv->{'branch'} eq $itembranchcode))){
557 $this_row{'nomod'}=1;
560 my $tag=$field->tag();
561 foreach my $subfield ($field->subfields) {
562 my ($subfcode,$subfvalue)=@$subfield;
563 next if ($tagslib->{$tag}->{$subfcode}->{tab} ne 10
564 && $tag ne $itemtagfield
565 && $subfcode ne $itemtagsubfield);
567 $witness{$subfcode} = $tagslib->{$tag}->{$subfcode}->{lib} if ($tagslib->{$tag}->{$subfcode}->{tab} eq 10);
568 if ($tagslib->{$tag}->{$subfcode}->{tab} eq 10) {
569 $this_row{$subfcode}=GetAuthorisedValueDesc( $tag,
570 $subfcode, $subfvalue, '', $tagslib)
574 $this_row{itemnumber} = $subfvalue if ($tag eq $itemtagfield && $subfcode eq $itemtagsubfield);
578 # grab title, author, and ISBN to identify bib that the item
579 # belongs to in the display
580 my $biblio = Koha::Biblios->find( $itemdata->{biblionumber} );
581 $this_row{title} = $biblio->title;
582 $this_row{author} = $biblio->author;
583 $this_row{isbn} = $biblio->biblioitem->isbn;
584 $this_row{biblionumber} = $biblio->biblionumber;
587 push(@big_array, \%this_row);
590 @big_array = sort {$a->{0} cmp $b->{0}} @big_array;
592 # now, construct template !
593 # First, the existing items for display
595 my @witnesscodessorted=sort keys %witness;
596 for my $row ( @big_array ) {
598 my @item_fields = map +{ field => $_ || '' }, @$row{ @witnesscodessorted };
599 $row_data{item_value} = [ @item_fields ];
600 $row_data{itemnumber} = $row->{itemnumber};
601 #reporting this_row values
602 $row_data{'nomod'} = $row->{'nomod'};
603 $row_data{bibinfo} = $row->{bibinfo};
604 $row_data{author} = $row->{author};
605 $row_data{title} = $row->{title};
606 $row_data{isbn} = $row->{isbn};
607 $row_data{biblionumber} = $row->{biblionumber};
608 my $is_on_loan = C4::Circulation::IsItemIssued( $row->{itemnumber} );
609 $row_data{onloan} = $is_on_loan ? 1 : 0;
610 push(@item_value_loop,\%row_data);
612 my @header_loop=map { { header_value=> $witness{$_}} } @witnesscodessorted;
614 return { item_loop => \@item_value_loop, item_header_loop => \@header_loop };
617 #BE WARN : it is not the general case
618 # This function can be OK in the item marc record special case
619 # Where subfield is not repeated
620 # And where we are sure that field should correspond
623 my ($marcfrom,$marcto)=@_;
624 my ( $itemtag, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
625 my $fieldfrom=$marcfrom->field($itemtag);
626 my @fields_to=$marcto->field($itemtag);
628 foreach my $subfield ( $fieldfrom->subfields() ) {
629 foreach my $field_to_update ( @fields_to ) {
630 if ( $subfield->[1] ) {
631 unless ( $field_to_update->subfield($subfield->[0]) eq $subfield->[1] ) {
633 $field_to_update->update( $subfield->[0] => $subfield->[1] );
638 $field_to_update->delete_subfield( code => $subfield->[0] );
646 my ($tagfield,$insubfield,$record) = @_;
649 foreach my $field ($record->field($tagfield)) {
650 my @subfields = $field->subfields();
651 foreach my $subfield (@subfields) {
652 if (@$subfield[0] eq $insubfield) {
653 $result .= @$subfield[1];
654 $indicator = $field->indicator(1).$field->indicator(2);
658 return($indicator,$result);
661 # ----------------------------
662 # Background functions
665 sub add_results_to_template {
666 my $template = shift;
668 $template->param(map { $_ => $results->{$_} } keys %{ $results });
671 sub add_saved_job_results_to_template {
672 my $template = shift;
673 my $completedJobID = shift;
674 my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
675 my $results = $job->results();
676 add_results_to_template($template, $results);
678 my $fields = $job->get("modified_fields");
679 my $items = $job->get("modified_items");
681 modified_items => $items,
682 modified_fields => $fields,
686 sub put_in_background {
687 my $job_size = shift;
689 my $job = C4::BackgroundJob->new($sessionID, "test", '/cgi-bin/koha/tools/batchMod.pl', $job_size);
690 my $jobID = $job->id();
693 if (my $pid = fork) {
695 # return job ID as JSON
697 # prevent parent exiting from
698 # destroying the kid's database handle
699 # FIXME: according to DBI doc, this may not work for Oracle
700 $dbh->{InactiveDestroy} = 1;
702 my $reply = CGI->new("");
703 print $reply->header(-type => 'text/html');
704 print '{"jobID":"' . $jobID . '"}';
706 } elsif (defined $pid) {
708 # close STDOUT to signal to Apache that
709 # we're now running in the background
713 # fork failed, so exit immediately
714 warn "fork failed while attempting to run tools/batchMod.pl as a background job";